AIDL 介紹:
AIDL 是 Android Interface definition language的縮寫(xiě),它是一種android內(nèi)部進(jìn)程通信接口的描述語(yǔ)言,通過(guò)它我們可以定義進(jìn)程間的通信接口。
新建兩個(gè)小demo
server.png
client.png
這里新建兩個(gè)工程,一個(gè)服務(wù)端,一個(gè)客戶(hù)端,用于實(shí)踐。
AIDL文件
在server端新建一個(gè)aidl文件,操作如下:
新建aidl文件.png
新建之后的目錄結(jié)構(gòu)如下:
新建后的目錄結(jié)構(gòu).png
打開(kāi)剛才新建的aidl文件:
aidl文件.png
如果需要定義一些非基本類(lèi)型的類(lèi),也需要放在和AIDL文件同目錄下。
將整個(gè)AIDL文件拷貝到客戶(hù)端同樣的目錄下面:
拷貝到客戶(hù)端.png
兩端都編譯一下,系統(tǒng)會(huì)生成對(duì)應(yīng)的接口類(lèi):
生成的接口類(lèi).png
Server端開(kāi)發(fā)
在Server端,創(chuàng)建一個(gè)Service:
新建的Service.png
在配置文件中注冊(cè)一下:
注冊(cè)Service.png
Client端開(kāi)發(fā)
在Clinet端簡(jiǎn)單的隱式啟動(dòng)剛才的Service,然后取得那個(gè)IBinder對(duì)象,轉(zhuǎn)換為IMyAidlInterface對(duì)象,再調(diào)接口:
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private Button clickButton;
private TextView showTextView;
private String action = "net.wyf.myaidlserver.service.MyService";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
clickButton = findViewById(R.id.clickId);
showTextView = findViewById(R.id.answerId);
bind();
clickButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (aidlInterface != null) {
try {
double add = aidlInterface.add(1.3, 2.4);
Log.d(TAG, "onClick: "+ add);
showTextView.setText(add + "");
} catch (RemoteException e) {
e.printStackTrace();
showTextView.setText("fail");
}
} else {
Log.e(TAG, "fail");
showTextView.setText("fail");
}
}
});
}
IMyAidlInterface aidlInterface;
private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
aidlInterface = IMyAidlInterface.Stub.asInterface(iBinder);
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
Log.e(TAG, "onServiceDisconnected: ");
}
};
@Override
protected void onDestroy() {
super.onDestroy();
unbindService(serviceConnection);
}
private void bind() {
Intent intent = new Intent(action);
intent.setPackage("net.wyf.myaidlserver");
bindService(intent, serviceConnection, BIND_AUTO_CREATE);
}
}
注意:隱式啟動(dòng)Service的時(shí)候千萬(wàn)不要忘記加包名。
運(yùn)行結(jié)果
客戶(hù)端打印.png
服務(wù)端打印.png
一個(gè)簡(jiǎn)單的例子實(shí)現(xiàn)了。
MyAIDLClient:https://gitee.com/xiaobindegushi/MyAIDLClient
MyAIDLServer:https://gitee.com/xiaobindegushi/MyAIDLServer