在實際的項目中,如果進程A和進程B進行AIDL綁定通信,通常B進程中的Service不止一個。
這時候採用將A進程和B進程的一個MainService綁定,再通過MainService獲得B進程中其他service的接口。這樣一來,綁定了一個MainService就可以與所有service交互。 代碼的架構將清晰明瞭。
進程主Service的AIDL文件IMainInterface.aidl:
interface IMainInterface{
/**
* Demonstrates some basic types that you can use as parameters
* and return values in AIDL.
*/
IBinder getFirstService();
IBinder getSecodService();
}
進程的其他Service的AIDL文件IFirstInterface.aidl和ISecondInterface.aidl
interface IFirstInterface {
/**
* Demonstrates some basic types that you can use as parameters
* and return values in AIDL.
*/
String getString(String s);
}
interface ISecondInterface {
/**
* Demonstrates some basic types that you can use as parameters
* and return values in AIDL.
*/
int add(int a, int b);
}
新建每個aidl的Stub文件 MyMainStub.java MyFirstStub.java MySecondStub.java
public class MyMainStub extends IMainInterface.Stub{
@Override
public IBinder getFirstService() throws RemoteException {
return new MyFirstStub();
}
@Override
public IBinder getSecodService() throws RemoteException {
return new MySecondStub();
}
}
public class MyFirstStub extends IFirstInterface.Stub{
@Override
public String getString(String s) throws RemoteException {
return s.toUpperCase();
}
}
public class MySecondStub extends ISecondInterface.Stub {
@Override
public int add(int a, int b) throws RemoteException {
return a+b;
}
}
新建每個Service文件 MainService.java FirstService.java SecondService.java
public class MainService extends Service {
MyMainStub myMainStub = new MyMainStub();
@Override
public IBinder onBind(Intent intent) {
return myMainStub;
}
}
public class FirstService extends Service{
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
public class SecondService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
在進程的非主service當中onbind返回null即可。
在MainActivity當中使用:
serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mService = IMainInterface.Stub.asInterface(service);
/*try {
IBinder iBinder = mService.getFirstService();
fService = IFirstInterface.Stub.asInterface(iBinder);
mTextView.setText(fService.getString("helloword"));
} catch (RemoteException e) {
e.printStackTrace();
}*/
try {
IBinder iBinder = mService.getSecodService();
sService = ISecondInterface.Stub.asInterface(iBinder);
mTextView.setText(sService.add(5, 5) + "");
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};