在Android 中,一個進(jìn)程通常無法訪問另一個進(jìn)程的內(nèi)存。因此為了進(jìn)程間通信,Android提供了AIDL機(jī)制,AIDL是Android中IPC(Inter-Process Communication)方式中的一種,AIDL是Android Interface definition language的縮寫,AIDL的作用是可以在自己的App里綁定一個其他App的Service,這樣App可以通過AIDL與其他App進(jìn)行交互。
App之間操作Service
這是BasicService應(yīng)用中 AndroidManifest.xml定義的Service組件
<service
android:name=".MyService"
android:enabled="true"
android:exported="true" >
<intent-filter>
<action android:name="cn.tim.basic_service.myservice"/>
</intent-filter>
</service>
MyService.java實(shí)現(xiàn)如下:
public class MyService extends Service {
private static final String TAG = "MyService";
private DownloadBinder mBinder = new DownloadBinder();
static class DownloadBinder extends Binder {
public void startDownload() {
// 模擬下載
Log.i(TAG, "startDownload executed");
}
public int getProgress() {
// 模擬返回下載進(jìn)度
Log.i(TAG, "getProgress executed");
return 0;
}
}
public MyService() {
}
// 創(chuàng)建
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "onCreate: ");
}
// 啟動
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "onStartCommand: ");
return super.onStartCommand(intent, flags, startId);
}
// 綁定
@Override
public IBinder onBind(Intent intent) {
Log.i(TAG, "onBind: ");
return mBinder;
}
// 解綁
@Override
public void unbindService(ServiceConnection conn) {
super.unbindService(conn);
Log.i(TAG, "unbindService: ");
}
// 銷毀
@Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy: ");
}
}
如何在另一個應(yīng)用中遠(yuǎn)程對BasicService這個App中的應(yīng)用進(jìn)行操作呢?在AIDLDemo這個App中:
MainActivity.java如下:
public class MainActivity extends AppCompatActivity {
ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void aboutService(View view) {
int id = view.getId();
// Android5.0后不支持隱式啟動了,最好都寫成顯示啟動
Intent intent = new Intent();
intent.setAction("cn.tim.basic_service.myservice");
intent.setPackage("cn.tim.basic_service");
switch (id){
case R.id.start_btn:
startService(intent);
break;
case R.id.stop_btn:
stopService(intent);
break;
case R.id.bind_btn:
bindService(intent, connection, BIND_AUTO_CREATE);
break;
case R.id.unbind_btn:
unbindService(connection);
break;
}
}
}
App之間Service通信
上面雖然完成了App之間的Service基本控制,比如啟動、停止、綁定解綁等操作,但是即使綁定了Service,但是Activity還是并不知道服務(wù)到底去做了什么事情,以及完成得如何。這個時候就需要用到AIDL進(jìn)行通信了。
首先需要明白的是要創(chuàng)建一套被調(diào)用的接口肯定要從被調(diào)用者出發(fā),所以先在BasicService這個App中:
step1、創(chuàng)建AIDL文件,本例中命名為IMyAidlInterface.aidl:
step2、編輯AIDL文件,在這個AIDL文件里編寫需要在服務(wù)綁定后通信的方法:
// IMyAidlInterface.aidl
package cn.tim.basic_service;
// Declare any non-default types here with import statements
interface IMyAidlInterface {
// 定義自己需要的方法:獲取當(dāng)前服務(wù)的進(jìn)度
int getProgress();
}
step3、rebuild project自動生成對應(yīng)的接口,接下來只要Rebuild一下工程就會在build > generated > aidl_source_output_dir > debug 下出現(xiàn)一個包,包下就是IMyAidlInterface.java:
其實(shí)Stub還會定義幾個輔助方法,其中最值得注意的是 asInterface(),該方法會接收 IBinder(通常是傳遞給客戶端 onServiceConnected() 回調(diào)方法的參數(shù)),并返回 Stub 接口的實(shí)例,其實(shí)就是通過代理的方式去完成IPC通信。
在MyService中綁定的回調(diào)函數(shù)onBind()中返回的那就是IMyAidlInterface.Stub代理對象了:
public class MyService extends Service {
...
@Override
public IBinder onBind(Intent intent) {
Log.i(TAG, "onBind: ");
//return mBinder;
return new IMyAidlInterface.Stub() {
@Override
public int getProgress() {
Log.i(TAG, "getProgress: IMyAidlInterface");
return 0;
}
};
}
}
這樣即使是在BasicService這個App中也可以使用IMyAidlInterface中的代理對象:
ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// MyService.DownloadBinder binder = (MyService.DownloadBinder) service;
// binder.startDownload();
// binder.getProgress();
IMyAidlInterface asInterface = IMyAidlInterface.Stub.asInterface(service);
try {
asInterface.getProgress();
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
step4、復(fù)制同樣的AIDL文件到AIDLDemo這個工程中,AIDL作為調(diào)用者。需要注意的是必須放到相同的包下,因此需要手動建包,再把文件復(fù)制過來:
同樣的方式,工程進(jìn)行一次rebuild,同樣會生成IMyAidlInterface.java,這樣大家都具有了IMyAidlInterface這個接口,使用起來也就還是一樣了,MainActivity.java:
step5、在AIDLDemo這個工程中使用IMyAidlInterface:
public class MainActivity extends AppCompatActivity {
private static final String TAG = "AIDLMainActivity";
ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
IMyAidlInterface asInterface = IMyAidlInterface.Stub.asInterface(service);
try {
int progress = asInterface.getProgress();
Log.i(TAG, "onServiceConnected: progress = " + progress);
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void aboutService(View view) {
int id = view.getId();
Intent intent = new Intent();
intent.setAction("cn.tim.basic_service.myservice");
intent.setPackage("cn.tim.basic_service");
switch (id){
case R.id.start_btn:
startService(intent);
break;
case R.id.stop_btn:
stopService(intent);
break;
case R.id.bind_btn:
bindService(intent, connection, BIND_AUTO_CREATE);
break;
case R.id.unbind_btn:
unbindService(connection);
break;
}
}
}
可以看到,AIDLDemo這個App的MainActivity已經(jīng)和BasicService這個App的MyService服務(wù)已經(jīng)綁定了,并且可以正常的調(diào)用MyService中的方法。至此,通過AIDL實(shí)現(xiàn)的遠(yuǎn)程綁定服務(wù)通信已經(jīng)完成了:
tips:上面logcat同時打印兩個TAG的日志的方法就是在配置過濾器LogTag:MyService | AIDLMainActivity即可。
使用AIDL的注意事項(xiàng)
1、只有在需要不同應(yīng)用的客戶端通過 IPC 方式訪問服務(wù),并且希望在服務(wù)中進(jìn)行多線程處理時,才有必要使用 AIDL。如果無需跨不同應(yīng)用執(zhí)行并發(fā) IPC,則應(yīng)通過實(shí)現(xiàn) Binder 來創(chuàng)建接口;或者如果想執(zhí)行 IPC,但不需要處理多線程,推薦使用 Messenger 來實(shí)現(xiàn)接口。
2、如果需要在首次發(fā)布 AIDL 接口后對其進(jìn)行更改,則每次更改必須保持向后兼容性,以免中斷其他應(yīng)用使用對應(yīng)的服務(wù)。換言之,由于只有在將 .aidl 文件復(fù)制到其他應(yīng)用后,才能使其訪問服務(wù)接口,因而必須保留對原始接口的支持。