什么是AIDL:
1懂诗、AIDL(Android Interface Definition Language安卓接口定義語言):讓其它應(yīng)用可以調(diào)用當(dāng)前應(yīng)用Service中的方法
2、Android系統(tǒng)中的進(jìn)程之間不能共享內(nèi)存墨叛,因此,需要提供一些機(jī)制在不同進(jìn)程之間進(jìn)行數(shù)據(jù)通信
3并村、RPC(Remote Procedure Call遠(yuǎn)程過程調(diào)用):AIDL解決的就是RPC的問題
4巍实、IPC(Inter Process Communication)進(jìn)程間通信
5、每一個(gè)Android應(yīng)用都運(yùn)行在獨(dú)立的進(jìn)程中哩牍,所以應(yīng)用之間的通信就是進(jìn)程間通信
6棚潦、Activity通過Intent可調(diào)起其它應(yīng)用,也可傳遞數(shù)據(jù)
7膝昆、BroadcastReceiver通過onReceive方法丸边,可以處理其它應(yīng)用發(fā)來的廣播,都是通過Intent攜帶數(shù)據(jù)
-AIDL的實(shí)現(xiàn)過程:
1荚孵、提供遠(yuǎn)程服務(wù)方法的應(yīng)用
1.創(chuàng)建一個(gè)Service妹窖,重寫onBind方法,在onBind中返回一個(gè)Binder對象收叶,需要遠(yuǎn)程調(diào)用的方法放到這個(gè)Binder對象中
2.在清單文件中聲明對應(yīng)的Service骄呼,需要添加一個(gè)intent-filter,可以通過隱式意圖調(diào)用Service
3.創(chuàng)建一個(gè)接口判没,需要暴露給其它應(yīng)用調(diào)用的方法都聲明在這個(gè)接口中
4.把接口文件的擴(kuò)展名修改為.aidl蜓萄,需要注意的是,.aidl文件不支持public關(guān)鍵字澄峰,如果aidl創(chuàng)建得沒有問題嫉沽,就會在gen目錄下生成一個(gè)IService.java
5.修改Service的代碼,讓MyBinder繼承Stub
2俏竞、遠(yuǎn)程調(diào)用服務(wù)的應(yīng)用
1.通過隱式意圖以及bindService的方式開啟遠(yuǎn)程服務(wù)
2.創(chuàng)建ServiceConnection的實(shí)現(xiàn)類
3.在當(dāng)前應(yīng)用中創(chuàng)建一個(gè)目錄绸硕,目錄結(jié)構(gòu)要跟提供遠(yuǎn)程服務(wù)的應(yīng)用的aidl文件所在目錄結(jié)構(gòu)保持一致,把a(bǔ)idl文件拷貝過來魂毁,如果沒有問題玻佩,會在gen目錄下生成一個(gè)IService.java文件,包名跟aidl文件的包名一致
4.在onServiceConnected方法中席楚,通過Stub.asInterface(service)把當(dāng)前的IBinder對象轉(zhuǎn)化成遠(yuǎn)程服務(wù)中的接口類型夺蛇,最終通過這個(gè)對象實(shí)現(xiàn)調(diào)用遠(yuǎn)程方法
創(chuàng)建一個(gè)類繼承Service
···
public class RemoteService extends Service{
@Override
public IBinder onBind(Intent intent) {
return new MyBinder();
}
public void remotoMethod(){
Log.e("TAG", "遠(yuǎn)程方法被調(diào)用");
}
public class MyBinder extends Stub{//自己包名下的Stub
public void callRemotoMethod(){
remotoMethod();
}
}
}
···
定義一個(gè)接口
:
里面實(shí)現(xiàn)方法
如:
void remotoMethod();
注意:不能用public 修飾
在創(chuàng)建一個(gè)項(xiàng)目;
xml*******
···
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="調(diào)用遠(yuǎn)程方法"
android:onClick="callRemote"
/>
···
MainAction中------------
···
public class MainActivity extends Activity {
private MyConntention conn;
private IService iservice;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent service = new Intent();
conn=new MyConntention();
//隱式意圖開啟其他應(yīng)用
service.setAction("com.krr.remotoservice");
bindService(service, conn, BIND_AUTO_CREATE);
}
public void callRemote(View v){
try {
iservice.callRemotoMethod();//遠(yuǎn)程調(diào)用
} catch (RemoteException e) {
e.printStackTrace();
}
}
public class MyConntention implements ServiceConnection{
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
iservice =Stub.asInterface(service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
}
}
···