【Android】【Binder】cpp 如何监听service死亡状态

前言

最近有个需求,需要在cpp bin中监听phone 进程异常死亡的状态。

代码

test.cpp

bash 复制代码
#define LOG_TAG "BINDER_DEATH"

#include <binder/IServiceManager.h>
#include <binder/Binder.h>
#include <binder/Parcel.h>
#include <android-base/stringprintf.h>
#include <utils/String16.h>
#include <string>
#include <cstdlib>
#include <pthread.h>
#include <binder/ProcessState.h>
#include <binder/IPCThreadState.h>
#include <utils/Errors.h>



namespace android{
int binderPhone();

namespace {
    Mutex                     gLock;
    class DeathNotifier : public IBinder::DeathRecipient
    {
    public:
        DeathNotifier() {}

        virtual void binderDied(const wp<IBinder>& /*who*/) {
            ALOGV("binderDied");
            Mutex::Autolock _l(gLock);
            ALOGW("phone service died!");
            sleep(2);
            binderPhone();
        }
    };
    sp<DeathNotifier>         gDeathNotifier;
};

int binderPhone(){
    sp<IServiceManager> sm = defaultServiceManager();
    sp<IBinder> binder = sm->checkService(String16("phone"));
    if (binder == nullptr) {
        ALOGE("step1: phone binder is null ! ");
        return -1;
    }
    binder = sm->getService(String16("phone"));
    if(binder == NULL){
        ALOGE("step2: phone binder is null ");
        return -1;
    }

    if (gDeathNotifier == NULL) {
        gDeathNotifier = new DeathNotifier();
    }

    status_t status = binder->linkToDeath(gDeathNotifier);

    if(status != NO_ERROR){
        ALOGE("linkToDeath fail");
    } else {
        ALOGD("linkToDeath sucessful");
    }
    return 0;
}
}

int main(){
    android::ProcessState::self()->startThreadPool();
    android::binderPhone();
    android::IPCThreadState::self()->joinThreadPool();
    return 0;
}

Android.mk

bash 复制代码
LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE := binderDeathTest
LOCAL_SRC_FILES := test.cpp
LOCAL_CFLAGS := -Wno-unused-parameter
LOCAL_C_INCLUDES :=  $(LOCAL_PATH)/../../../inc/
LOCAL_SHARED_LIBRARIES := libcutils libutils liblog libbinder libbase

LOCAL_MODULE_TAGS := optional

include $(BUILD_EXECUTABLE)

测试

bash 复制代码
while(true){
kill -9 `pidof  com.android.phone`
sleep 1
}
相关推荐
二流小码农37 分钟前
鸿蒙开发:个人开发者如何使用华为账号登录
android·ios·harmonyos
StarShip1 小时前
Android View框架概览
android·计算机图形学
愤怒的代码1 小时前
解析Android内存分析的指标
android·app
summerkissyou19871 小时前
android-hardware/interfaces/automotive和hardware/libhardware/include/hardware区别
android
Evan芙1 小时前
mysql二进制部署以及多实例部署
android·数据库·mysql
走在路上的菜鸟2 小时前
Android学Dart学习笔记第二十三节 类-扩展类型
android·笔记·学习·flutter
百***78752 小时前
【技术教程】3步极速接入GPT-5.1:零门槛体验多模态AI能力
android·java·人工智能·gpt·opencv
走在路上的菜鸟3 小时前
Android学Dart学习笔记第二十一节 类-点的简写
android·笔记·学习·flutter
QQ12958455043 小时前
ThingsBoard-修改Android APP应用程序名和描述
android·物联网·iot
代码代码快快显灵4 小时前
Android项目架构深度解析
android