【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
}
相关推荐
雨白10 小时前
Jetpack系列(二):Lifecycle与LiveData结合,打造响应式UI
android·android jetpack
kk爱闹11 小时前
【挑战14天学完python和pytorch】- day01
android·pytorch·python
每次的天空13 小时前
Android-自定义View的实战学习总结
android·学习·kotlin·音视频
恋猫de小郭13 小时前
Flutter Widget Preview 功能已合并到 master,提前在体验毛坯的预览支持
android·flutter·ios
断剑重铸之日14 小时前
Android自定义相机开发(类似OCR扫描相机)
android
随心最为安14 小时前
Android Library Maven 发布完整流程指南
android
岁月玲珑14 小时前
【使用Android Studio调试手机app时候手机老掉线问题】
android·ide·android studio
还鮟19 小时前
CTF Web的数组巧用
android
小蜜蜂嗡嗡20 小时前
Android Studio flutter项目运行、打包时间太长
android·flutter·android studio
aqi0020 小时前
FFmpeg开发笔记(七十一)使用国产的QPlayer2实现双播放器观看视频
android·ffmpeg·音视频·流媒体