RemoteCallbackList 是 Android 中的一个类,用于管理跨进程的回调接口。它提供了一种安全和高效的方式来管理多个回调对象,并避免因为进程间通信 (IPC) 导致的内存泄漏问题。RemoteCallbackList 的主要作用是在客户端和服务端之间传递回调对象,所以一般传递对象代码:
val listenerMap = mutableMapOf<Class<*>, RemoteCallbackList<IInterface>>()
fun sendState(state: Int) {
synchronized(lock){
var remoteCallbackList = listenerMap.get(OnStateAidl::class.java)
remoteCallbackList?.let {
var num = remoteCallbackList.beginBroadcast();
for (i in 0 until num) {
var listener = remoteCallbackList.getBroadcastItem(i) as OnStateAidl
if (listener!=null){
listener.onState(state)
}
}
remoteCallbackList.finishBroadcast();
}
}
}
代码还挺多,如果存在多个回调方法代码量会非常大,下面将重复的逻辑提取为一个通用的函数,然后在需要调用不同回调函数的地方进行调用
fun sendData(listenerClass: Class<*>, callback: (Any) -> Unit) {
synchronized(lock) {
val remoteCallbackList = listenerMap.get(listenerClass)
remoteCallbackList?.let {
val num = remoteCallbackList.beginBroadcast()
try {
for (i in 0 until num) {
val listener = remoteCallbackList.getBroadcastItem(i)
listener?.let {
callback.invoke(listener)
}
}
} finally {
remoteCallbackList.finishBroadcast()
}
}
}
}
重新修改传递数据代码:
fun sendState(state: Int) {
sendData(OnStateAidl::class.java){listener->
(listener as OnStateAidl).onState(data)
}
}