Android Interface definition language
接口定义语言
作用:进程间的通信
原因:因为进程之间不能共享内存,所以需要进程进程间通信
案例:
在上节service基础上修改
在A demo中创建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传输数据,它只限同进程之间(在demo B中拿不到自定义的MyBinder类)
因此只能使用AIDL
步骤1
步骤2
结果生成文件
IMyAidlInterface
Stub 继承 android.os.Binder 实现接口 com.zhang.servicedemo.IMyAidlInterface
之后就是调用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", "远程连接 count " + i);
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
网友评论