直接右键项目新建一个AIDL,在service的onBind(Intent intent)
里面返回new IMyAidlInterface.Stub()
@Override
public IBinder onBind(Intent intent) {
return new IMyAidlInterface.Stub() {
@Override
public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {
}
};
}
仍然用之前的
serviceIntent = new Intent();
serviceIntent.setComponent(new ComponentName("com.jackie.startanotherapp",
"com.jackie.startanotherapp.AppService"));
//绑定服务的代码
bindService(serviceIntent, this, Context.BIND_AUTO_CREATE);
//解绑服务的代码
unbindService(this);
而在绑定服务的时候,获取一下IBinder对象:
10-21 10:42:53.371 30813-30813/com.jackie.anotherapp V/jackie: Service binded
10-21 10:42:53.371 30813-30813/com.jackie.anotherapp V/jacke: Ibinder is android.os.BinderProxy@42a63810
绑定服务的目的就在于与服务进行通信,只绑定不实现通信是毫无意义的。
之前学过的通信的时候,是自己定义一个MyBinder,然后在里面进行数据的修改,这里既然有了AIDL,就在它里面添加抽象方法即可。
如果要实现远程通信,那么在anotherapp里面要新建一个aidl folder,里面新建包,包名要和service所在包一样,而且将aidl拷贝进去
这样一来,anotherapp也可以找到IMyAidlInterface的定义了,在它的MainActivity里面定义
private IMyAidlInterface binder;
...
//修改data
case R.id.sync:
try {
binder.setData(editText.getText().toString());
} catch (RemoteException e) {
e.printStackTrace();
}
如果运行出现NullPointerException,那么很可能是忘记在onServiceConnected(ComponentName name, IBinder service)
里面给binder初始化一下:
binder = (IMyAidlInterface) service;
然而po主修改以后发现虽然绑定以后线程运行了但是anotherapp报错了,
java.lang.ClassCastException: android.os.BinderProxy cannot be cast to com.jackie.startanotherapp.IMyAidlInterface
因为两个aidl的内存是不一样的
//binder = (IMyAidlInterface) service;
binder = IMyAidlInterface.Stub.asInterface(service);
要这样写才行
然后观察logcat
10-21 11:20:32.681 25488-25530/com.jackie.startanotherapp V/jackie: data is default
10-21 11:20:34.681 25488-25530/com.jackie.startanotherapp V/jackie: data is default
10-21 11:20:36.681 25488-25530/com.jackie.startanotherapp V/jackie: data is default
10-21 11:20:38.681 25488-25530/com.jackie.startanotherapp V/jackie: data is 修改后
10-21 11:20:40.681 25488-25530/com.jackie.startanotherapp V/jackie: data is 修改后
10-21 11:20:42.681 25488-25530/com.jackie.startanotherapp V/jackie: data is 修改后
这样就实现了跨应用远程service通信了。