Tim's Note

试问Coding应不好,却道:此心安处是吾乡

0%

远程服务使用 AIDL 通信

在 Android 中,一个进程通常无法访问另一个进程的内存。因此为了进程间通信,Android 提供了 AIDL 机制,AIDL 是 Android 中 IPC(Inter-Process Communication)方式中的一种,AIDL 是 Android Interface definition language 的缩写,AIDL 的作用是可以在自己的 App 里绑定一个其他 App 的 Service,这样 App 可以通过 AIDL 与其他 App 进行交互。

App 之间操作 Service

这是 BasicService 应用中 AndroidManifest.xml 定义的 Service 组件

1
2
3
4
5
6
7
8
<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 实现如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
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() {
// 模拟返回下载进度
Log.i (TAG, "getProgress executed");
return 0;
}
}

public MyService() {

}

// 创建
@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: ");
}
}

如何在另一个应用中远程对 BasicService 这个 App 中的应用进行操作呢?在 AIDLDemo 这个 App 中:

MainActivity.java 如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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 还是并不知道服务到底去做了什么事情,以及完成得如何。这个时候就需要用到 AIDL 进行通信了。

首先需要明白的是要创建一套被调用的接口肯定要从被调用者出发,所以先在 BasicService 这个 App 中:

step1、创建 AIDL 文件 ,本例中命名为 IMyAidlInterface.aidl:

step2、编辑 AIDL 文件 ,在这个 AIDL 文件里编写需要在服务绑定后通信的方法:

1
2
3
4
5
6
7
8
9
10
// IMyAidlInterface.aidl
package cn.tim.basic_service;

// Declare any non-default types here with import statements

interface IMyAidlInterface {

// 定义自己需要的方法:获取当前服务的进度
int getProgress();
}

step3、rebuild project 自动生成对应的接口 ,接下来只要 Rebuild 一下工程就会在 build > generated > aidl_source_output_dir > debug 下出现一个包,包下就是 IMyAidlInterface.java:

其实 Stub 还会定义几个辅助方法,其中最值得注意的是 asInterface (),该方法会接收 IBinder(通常是传递给客户端 onServiceConnected () 回调方法的参数),并返回 Stub 接口的实例,其实就是通过代理的方式去完成 IPC 通信。

在 MyService 中绑定的回调函数 onBind () 中返回的那就是 IMyAidlInterface.Stub 代理对象了:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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 中的代理对象:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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、复制同样的 AIDL 文件到 AIDLDemo 这个工程中 ,AIDL 作为调用者。需要注意的是必须放到相同的包下,因此需要手动建包,再把文件复制过来:

同样的方式,工程进行一次 rebuild,同样会生成 IMyAidlInterface.java,这样大家都具有了 IMyAidlInterface 这个接口,使用起来也就还是一样了,MainActivity.java:

step5、在 AIDLDemo 这个工程中使用 IMyAidlInterface

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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 已经和 BasicService 这个 App 的 MyService 服务已经绑定了,并且可以正常的调用 MyService 中的方法。至此,通过 AIDL 实现的远程绑定服务通信已经完成了:

tips:上面 logcat 同时打印两个 TAG 的日志的方法就是在配置过滤器 LogTag:MyService | AIDLMainActivity 即可。

使用 AIDL 的注意事项

1、只有在需要不同应用的客户端通过 IPC 方式访问服务,并且希望在服务中进行多线程处理时,才有必要使用 AIDL。如果无需跨不同应用执行并发 IPC,则应通过实现 Binder 来创建接口;或者如果想执行 IPC,但不需要处理多线程,推荐使用 Messenger 来实现接口。

2、如果需要在首次发布 AIDL 接口后对其进行更改,则每次更改必须保持向后兼容性,以免中断其他应用使用对应的服务。换言之,由于只有在将 .aidl 文件复制到其他应用后,才能使其访问服务接口,因而必须保留对原始接口的支持。

原文地址:《远程服务使用 AIDL 通信》

欢迎关注我的其它发布渠道