同一个进程之间的通信:iBinder ,例如Activity和Service之间的通信过程
AIDL:Android Interface definition language
作用:进程间的通信接口
AIDL的使用
-
创建aidl文件
-
定义自己的方法
// IMyAidlInterface.aidl
package com.example.servicedemo;
// Declare any non-default types here with import statements
interface IMyAidlInterface {
void showProgress();
}
-
自动生成的java文件(rebuild project)
-
使用aidl
MyService
//绑定
//IBinder:在Android中用于远程操作对象的一个基本接口
override fun onBind(intent: Intent): IBinder? {
Log.e("TAG", "绑定")
return object : IMyAidlInterface.Stub() {
@Throws(RemoteException::class)
override fun showProgress() {
Log.e("TAG", "Current: $process")
}
}
}
MainActivity
//ServiceConnection 用于绑定客户端和Service
private val conn: ServiceConnection = object : ServiceConnection {
//当客户端正常连接服务时,执行服务的绑定操作会被调用
override fun onServiceConnected(name: ComponentName, service: IBinder) {
Log.e("TAG", "ServiceConnection")
val imai = IMyAidlInterface.Stub.asInterface(service)
try {
imai.showProgress()
} catch (e: RemoteException) {
e.printStackTrace()
}
}
//当客户端和服务的连接丢失了
override fun onServiceDisconnected(name: ComponentName) {}
}
- 在远程通信的module中复制aidl
位置、包名和文件名应该温泉相同
- 重写ServiceConnection
var conn: ServiceConnection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName, service: IBinder) {
val imai = IMyAidlInterface.Stub.asInterface(service)
try {
imai.showProgress()
} catch (e: RemoteException) {
e.printStackTrace()
}
}
override fun onServiceDisconnected(name: ComponentName) {}
}
- 远程调用其他module服务的写法
fun operate(view: View) {
when (view.id) {
R.id.start -> {
//Android5.0之后必须显示调用Intent
//5.0前写法 val it = Intent("com.imooc.myservice")
val it = Intent()
it.action = "com.imooc.myservice"
it.setPackage("com.example.servicedemo")
startService(it)
}
R.id.stop -> {
val it2 = Intent()
it2.action = "com.imooc.myservice"
it2.setPackage("com.example.servicedemo")
stopService(it2)
}
R.id.bind -> {
val it3 = Intent()
it3.action = "com.imooc.myservice"
it3.setPackage("com.example.servicedemo")
bindService(it3, conn, BIND_AUTO_CREATE)
}
R.id.unbind -> unbindService(conn)
}
}
注意:
需要在myservice的AndroidManifest文件中添加intent-filter,定义android:name
<service
android:name=".MyService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.imooc.myservice"/>
</intent-filter>
</service>