/
/
class MyBinderService : public BnInterface<IMyBinderService>
{
public:
// ...(保留原有代码)
// 注册客户端死亡通知回调
void RegisterClientDeathRecipient(const sp<IBinder::DeathRecipient>& recipient);
private:
sp<IBinder::DeathRecipient> m_clientDeathRecipient;
};
void MyBinderService::RegisterClientDeathRecipient(const sp<IBinder::DeathRecipient>& recipient)
{
if (recipient != nullptr) {
m_clientDeathRecipient = recipient;
// 从客户端获取Binder对象并注册死亡通知
sp<IBinder> clientBinder = data.readStrongBinder();
clientBinder->linkToDeath(m_clientDeathRecipient);
}
}
status_t MyBinderService::OnTransact(uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
{
switch (code) {
// ...(保留原有代码)
case REGISTER_CLIENT_DEATH_RECIPIENT: {
// 解析Parcel中的死亡通知接收者引用
sp<IBinder::DeathRecipient> recipient = data.readStrongBinder().asBinder()->queryLocalInterface(DEATH_RECIPIENT_INTERFACE_DESCRIPTOR).cast<IBinder::DeathRecipient>();
if (recipient != nullptr) {
RegisterClientDeathRecipient(recipient);
reply->writeInt32(RESULT_OK);
} else {
reply->writeInt32(RESULT_ERROR);
}
return NO_ERROR;
}
// ...
}
return SuperType::OnTransact(code, data, reply, flags);
}
/
/
class MyClientDeathRecipient : public IBinder::DeathRecipient
{
public:
explicit MyClientDeathRecipient(std::function<void()> onClientDiedCallback) : m_onClientDied(onClientDiedCallback) {}
void binderDied(const wp<IBinder>& who) override
{
ALOGE("Binder client with object %p has died.", who.unsafe_get());
if (m_onClientDied) {
m_onClientDied();
}
}
private:
std::function<void()> m_onClientDied;
};
sp<MyClientDeathRecipient> clientDeathRecipient = new MyClientDeathRecipient([] {
// 在这里执行客户端死亡后的清理逻辑
});
// 获取服务端Binder对象
sp<IBinder> binder = getService("com.example.MyBinderService");
// 将客户端死亡接收者封装成Binder对象
sp<IBinder> clientDeathRecipientBinder = new BBinder();
clientDeathRecipientBinder->setInterface(static_cast<IInterface*>(clientDeathRecipient.get()));
// 向服务端发送注册请求
Parcel data, reply;
data.writeInterfaceToken(IMyBinderService::getInterfaceDescriptor());
data.writeStrongBinder(clientDeathRecipientBinder);
status_t status = binder->transact(REGISTER_CLIENT_DEATH_RECIPIENT, data, &reply, FLAG_ONEWAY);
if (status == NO_ERROR && reply.readInt32() == RESULT_OK) {
ALOGI("Client death recipient registered successfully.");
} else {
ALOGE("Failed to register client death recipient.");
}