【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
}
相关推荐
szhangbiao1 小时前
“开发板”类APP如果做屏幕适配
android
高林雨露2 小时前
RecyclerView中跳转到最后一条item并确保它在可视区域内显示
android
移动开发者1号4 小时前
ReLinker优化So库加载指南
android·kotlin
山野万里__4 小时前
C++与Java内存共享技术:跨平台与跨语言实现指南
android·java·c++·笔记
Huckings4 小时前
Android 性能问题
android
移动开发者1号5 小时前
剖析 Systrace:定位 UI 线程阻塞的终极指南
android·kotlin
移动开发者1号5 小时前
深入解析内存抖动:定位与修复实战(Kotlin版)
android·kotlin
whysqwhw5 小时前
OkHttp深度架构缺陷分析与革命性演进方案
android
Digitally7 小时前
如何将文件从 iPhone 传输到 Android(新指南)
android·ios·iphone
whysqwhw8 小时前
OkHttp深度架构缺陷分析与演进规划
android