这可以通过Binder.linkToDeath()
机制来完成 - 您必须要求每个客户发送new Binder()
他们发起的对象,然后链接到他们(您的客户)的死亡。我将解释如何使用AIDL文件执行此操作。
(您可以选择任何 android IPC 机制,只要您可以将 Binder 对象从客户端传递到您的服务)
代码示例 -
在您的 .AIDL
文件中- 创建一个将IBinder
对象从客户端传递到服务的方法
void registerProcessDeath(in IBinder clientDeathListener, String packageName);
在客户端- 初始化一个新对象并通过 AIDL 接口将其传递给您的服务。
public void onServiceConnected(ComponentName className, IBinder service) {
mIMyAidlInterface = IMyAidlInterface.Stub.asInterface(service);
//Call the registerProcessDeath method from the AIDL file and pass
//the new Binder object and the client's package name
mIMyAidlInterface.registerProcessDeath(new Binder(),getPackageName());
}
在服务方面——
1. 获取客户Binder
并注册到他的linkToDeath()
.
2.使用helper类通过android的IBinder.DeathRecipient类处理所有客户端
public class MyService extends Service {
//Helper class to handle all client's deaths.
private volatile ClientsDeathWatcher mClientsList;
@Override
public IBinder onBind(Intent intent) {
mClientsList = new ClientsDeathWatcher();
return mStub;
}
private final IMyAidlInterface.Stub mStub = new IMyAidlInterface.Stub() {
@Override
public void registerProcessDeath(IBinder cb, String packageName){
boolean isRegistered = mClientsList.register(cb , packageName);
}
};
}
//This is thread-safe helper class to handle all
//the client death related tasks.
//All you care abut is the clientDeath() method.
public class ClientsDeathWatcher {
private ArrayMap<String, DeathCallBack> mCallbacks = new ArrayMap<>();
private final class DeathCallBack implements IBinder.DeathRecipient {
private String pn;
private IBinder mBinder;
DeathCallBack(String packageName,IBinder binder) {
pn = packageName;
mBinder = binder;
}
public void binderDied() {
synchronized (mCallbacks) {
mBinder.unlinkToDeath(this,0);
clientDeath(pn);
}
}
}
//To be called only from thread-safe functions
private void clientDeath(String packageName) {
mCallbacks.remove(packageName);
//Do your stuff here.
//$$$$$$$$$
}
public boolean register(IBinder token, String packageName) {
synchronized (mCallbacks) {
try {
if (!mCallbacks.containsKey(packageName)) {
DeathCallBack mDeathCallBack = new DeathCallBack(packageName,token);
mCallbacks.put(packageName, mDeathCallBack);
//This is where the magic happens
token.linkToDeath(mDeathCallBack, 0);
}
return true;
} catch (RemoteException e) {
e.printStackTrace();
return false;
}
}
}
}