【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
}
相关推荐
冬奇Lab9 小时前
Android触摸事件分发、手势识别与输入优化实战
android·源码阅读
城东米粉儿12 小时前
Android MediaPlayer 笔记
android
Jony_12 小时前
Android 启动优化方案
android
阿巴斯甜12 小时前
Android studio 报错:Cause: error=86, Bad CPU type in executable
android
张小潇12 小时前
AOSP15 Input专题InputReader源码分析
android
_小马快跑_17 小时前
Kotlin | 协程调度器选择:何时用CoroutineScope配置,何时用launch指定?
android
_小马快跑_17 小时前
Kotlin | 从SparseArray、ArrayMap的set操作符看类型检查的不同
android
_小马快跑_17 小时前
Android | 为什么有了ArrayMap还要再设计SparseArray?
android
_小马快跑_17 小时前
Android TextView图标对齐优化:使用LayerList精准控制drawable位置
android
_小马快跑_17 小时前
Kotlin协程并发控制:多线程环境下的顺序执行
android