【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
}
相关推荐
jiet_h28 分钟前
Android锁
android
teacher伟大光荣且正确9 小时前
Qt Creator 配置 Android 编译环境
android·开发语言·qt
飞猿_SIR11 小时前
Android Exoplayer 实现多个音视频文件混合播放以及音轨切换
android·音视频
HumoChen9912 小时前
GZip+Base64压缩字符串在ios上解压报错问题解决(安卓、PC模拟器正常)
android·小程序·uniapp·base64·gzip
沙振宇16 小时前
【HarmonyOS】ArkTS开发应用的横竖屏切换
android·华为·harmonyos
橙子1991101617 小时前
Kotlin 中的作用域函数
android·开发语言·kotlin
zimoyin17 小时前
Kotlin 懒初始化值
android·开发语言·kotlin
枣伊吕波18 小时前
第六节第二部分:抽象类的应用-模板方法设计模式
android·java·设计模式
萧然CS18 小时前
使用ADB命令操作Android的apk/aab包
android·adb
_extraordinary_1 天前
MySQL 事务(二)
android·数据库·mysql