在Android的应用开发过程中,遇到与Service进行通信时,会使用Aidl。那到底Aidl是什么?Aidl的优势是什么?实现的原理是怎么样的?
习惯从例子入手,从实际应用加深对知识点的了解。我们来通过一个简单的例子,来了解具体实现。
现在我们想通过App1来绑定App2的Service,然后通过App1的线程获取Service的模拟下载进度,如下图所示:
1.创建App2提供服务
1.1 新建HelloWorld工程
1.2 新建aidl文件,内容很简单,创建一个接口类
// DownloadAidlInterface.aidl
package com.example.myapplication2;
// Declare any non-default types here with import statements
interface DownloadAidlInterface {
int getProgress();
}
1.3 实现App2中的服务:
/**
* Created by jiay on 2018/8/11.
*/
public class DownloadService extends Service {
private int progress = 0;//模拟下载进度
public class MyBinder extends DownloadAidlInterface.Stub{
@Override
public int getProgress() throws RemoteException {
return progress;
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
System.out.println("onbind");
return new MyBinder();
}
@Override
public void onCreate() {
System.out.println("onCreate");
super.onCreate();
new Threa