服务端:
1
// IAlipayInterface.aidl
package com.example.alipay;
// Declare any non-default types here with import statements
interface IAlipayInterface {
/**
* Demonstrates some basic types that you can use as parameters
* and return values in AIDL.
*/
int call_safepay();
}
2
public class Alipay extends Service {
private class MyBinder extends IAlipayInterface.Stub{
@Override
public int call_safepay() throws RemoteException {
return safepay();
}
}
public Alipay() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
//throw new UnsupportedOperationException("Not yet implemented");
return new MyBinder();
}
public int safepay(){
return 5;
}
}
3
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Alipay">
<service
android:name=".Alipay"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.example.alipay"/>
</intent-filter>
</service>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
客户端
1.将服务端的aidl整个目录拷贝过来,特别注意,目录要和服务端一模一样
2、
private IAlipayInterface mIService;
private MyConn mConn = null;
private class MyConn implements ServiceConnection {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
System.out.println("成功绑定到远程alipay服务上");
mIService = IAlipayInterface.Stub.asInterface(service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent();
intent.setAction("com.example.alipay");
// 远程调用服务在安卓8.0系统及以上,也需要指定组件名,也就是显式调用
intent.setComponent(new ComponentName("com.example.alipay", "com.example.alipay.Alipay"));
mConn = new MyConn();
bindService(intent, mConn, BIND_AUTO_CREATE);
}
3、调用方法
public void click(View view) {
try {
int i = mIService.call_safepay();
Toast.makeText(MainActivity.this,i+"",Toast.LENGTH_SHORT).show();
} catch (RemoteException e) {
e.printStackTrace();
}
}