Aidl简单使用例子
AIDL是Android中IPC(Inter-Process Communication)方式中的一种,AIDL是Android Interface definition language的缩写,对于小白来说,AIDL的作用是让你可以在自己的APP里绑定一个其他APP的service,这样你的APP可以和其他APP交互。
打开AndroidStudio创建两个module,例如 aidlClient aidlServer
1.aidl接口文件
// IBook.aidl
package com.example.androidbinddemo;
// Declare any non-default types here with import statements
interface IBook {
/**
* Demonstrates some basic types that you can use as parameters
* and return values in AIDL.
*/
void borrowBook(String number, int count);
}
2.创建一个服务例如 BookService
class BookService : Service() {
private var handler = Handler(Looper.getMainLooper())
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
println("xxxx onStartCommand")
Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK
return super.onStartCommand(intent, flags, startId)
}
override fun onBind(p0: Intent?): IBinder {
return object : IBook.Stub() {
override fun borrowBook(number: String?, count: Int) {
println("xxxx borrow number = $number count = $count")
handler.post {
Toast.makeText(
this@BookService,
"borrowBook $number $count",
Toast.LENGTH_SHORT
).show()
}
}
}
}
}
3.aidlClient 如何连接BookService操作呢?
private var serviceConnection: ServiceConnection? = null
serviceConnection = object : ServiceConnection {
override fun onServiceConnected(p0: ComponentName?, p1: IBinder?) {
println("xxxx onServiceConnected p0 = [${p0}], p1 = [${p1}]")
val iBook = IBook.Stub.asInterface(p1)
iBook?.borrowBook("you are best!",202288)
}
override fun onServiceDisconnected(p0: ComponentName?) {
println("xxxx onServiceDisconnected p0 = [${p0}]")
}
}
val ret = bindService(
Intent("com.example.androidbinddemo.BookService").apply {
setPackage("com.example.androidbinddemo")
},
serviceConnection as ServiceConnection,
Service.BIND_AUTO_CREATE
)
println("xxxx bindService ret = $ret")
4.实例
viewBinding.test.setOnClickListener {
if (iBookInterface == null) {
Toast.makeText(it.context, "未获取到binder对象", Toast.LENGTH_SHORT).show()
} else {
iBookInterface?.borrowBook("you are best!", 202288)
}
}
注意事项
- 最好使用隐式itennt启动service,并且设置service所在的包名,否则可能无法启动。
- 启动service在高版本中是红notificationChannel启动前台service.
- 在api32无法启动service,我找不到解决方法,惭愧。