Android Interface definition language
接口定義語言
作用:進程間的通信
原因:因為進程之間不能共享內(nèi)存,所以需要進程進程間通信
案例:
在上節(jié)service基礎(chǔ)上修改
在A demo中創(chuàng)建MyService,唯一要注意的是,在AndroidManifest中,service加一個filter
exported=true
<service
android:name=".MyService"
android:enabled="true"
android:exported="true"
>
<intent-filter>
<action android:name="com.zhang.myservice"/>
</intent-filter>
</service>
在B demo中MainActivity
private ServiceConnection mConnection=new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
@butterknife.OnClick({R.id.start, R.id.stop, R.id.bind, R.id.unbind})
public void onViewClicked(View view) {
Intent intent =new Intent();
intent.setAction("com.zhang.myservice");
intent.setPackage("com.zhang.servicedemo");
switch (view.getId()) {
case R.id.start:
startService(intent);
break;
case R.id.stop:
stopService(intent);
break;
case R.id.bind:
bindService(intent,mConnection,BIND_AUTO_CREATE);
break;
case R.id.unbind:
unbindService(mConnection);
break;
}
}
AIDL
不能使用Binder傳輸數(shù)據(jù),它只限同進程之間(在demo B中拿不到自定義的MyBinder類)
因此只能使用AIDL
步驟1

步驟2

結(jié)果生成文件

IMyAidlInterface
Stub 繼承 android.os.Binder 實現(xiàn)接口 com.zhang.servicedemo.IMyAidlInterface
之后就是調(diào)用stub
package com.zhang.servicedemo;
// Declare any non-default types here with import statements
public interface IMyAidlInterface extends android.os.IInterface
{
/** Local-side IPC implementation stub class. */
public static abstract class Stub extends android.os.Binder implements com.zhang.servicedemo.IMyAidlInterface
{
private static final java.lang.String DESCRIPTOR = "com.zhang.servicedemo.IMyAidlInterface";
/** Construct the stub at attach it to the interface. */
public Stub()
{
this.attachInterface(this, DESCRIPTOR);
}
MyService
@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 {
}
@Override
public int getProgress() throws RemoteException {
return count;
}
};
}
步驟3
拷貝一份到demo B中,同時build

步驟4
demo B中 MainActivity ServiceConnection
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
IMyAidlInterface iMyAidlInterface = IMyAidlInterface.Stub.asInterface(service);
try {
int i = iMyAidlInterface.getProgress();
Log.i("zhang", "遠(yuǎn)程連接 count " + i);
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
