前言
关于服务的启动方式(startService()、stopService()、bindService()、unbindService()),我这里就不多说了,可以参考这篇博文。
示例原理图
本文以一个简单的案例,记录一下怎么使用AIDL结合服务实现进程间的通信:
首先,创建两个项目,一个项目(RemoteService)作为远程服务提供端,另一个(RemoteServiceTest)作为调用远程服务的客户端.然后,当客户端绑定远程服务后,可以通过AIDL接口调用远程服务中的方法,原理过程如图:
远程服务RemoteService 项目
1.创建AIDL文件,选中要提供的服务类所在的包名,右键 -> New -> AIDL -> AIDL File文件,如图
这里将AIDL文件命名为RemoteInterface,创建完成后,会在main下生成一个aidl文件夹,一个包名与刚刚选中的包名相同的包,包下生成了一个RemoteInterface.aidl,如图
2.打开RemoteInterface.aidl文件,定义一个接口方法 remotePrintInterface(); 重新编译一下项目,如果成功编译那么会在如下目录中生成一个RemoteInterface接口文件
注意不要修改这个接口文件,接口中有一个重要的 Stub类,是之后要用的,Stub类继承了Binder,并实现了RemoteInterface接口。
3.创建一个服务类如RemoteService让其继承自Service, 服务中定义一个方法remotePrint(),并定义一个内部类 MyBinder 继承自 Stub, 实现Stub或者说RemoteInterface接口中的remotePrintInterface()的方法,让这个方法去调用服务的remotePrint()方法,代码如下:
package com.yu.remoteservice;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;
/**
* Created by yu on 2016/4/15.
*/
public class RemoteService extends Service {
private static final String TAG = "RemoteService";
@Nullable
@Override
public IBinder onBind(Intent intent) {
Log.d(TAG,"R