如何使用Binder实现分析
发布网友
发布时间:2022-04-22 07:20
我来回答
共1个回答
热心网友
时间:2022-06-17 14:07
(1)获得ServiceManager的对象引用
(2)向ServiceManager注册新的Service
(3)在Client中通过ServiceManager获得Service对象引用
(3)在Client中发送请求,由Service返回结果。
下面看具体的代码如何实现。
3.1 libmyservice代码实现
(1)新建目录frameworks/base/myservice/libservice,进入该目录
view plain
$ cd frameworks/base
$ mkdir myservice
$ cd myservice
$ mkdir libmyservice
$ cd libmyservice
(2)编写libmyservice/myservic.h文件
view plain
#include <utils/threads.h>
#include <utils/RefBase.h>
#include <binder/IInterface.h>
#include <binder/BpBinder.h>
#include <binder/Parcel.h>
namespace android {
class MyService : public BBinder
{
mutable Mutex mLock;
int32_t mNextConnId;
public:
static int instantiate();
MyService();
virtual ~MyService();
virtual status_t onTransact(uint32_t, const Parcel&, Parcel*, uint32_t);
};
}; //namespace
(2)编写libservice/myservice.cpp文件
view plain
#include "myservice.h"
#include <binder/IServiceManager.h>
#include <binder/IPCThreadState.h>
namespace android {
static struct sigaction oldact;
static pthread_key_t sigbuskey;
int MyService::instantiate()
{
LOGE("MyService instantiate");
// defaultServiceManager ()获得ServiceManager的对象引用,addService()可向ServiceManager注册新的服务
int r = defaultServiceManager()->addService(String16("android.myservice"), new MyService());
LOGE("MyService r = %d/n", r);
return r;
}
MyService::MyService()
{
LOGV("MyService created");
mNextConnId = 1;
pthread_key_create(&sigbuskey, NULL);
}
MyService::~MyService()
{
pthread_key_delete(sigbuskey);
LOGV("MyService destroyed");
}
// 每个系统服务都继承自BBinder类,都应重写BBinder的onTransact虚函数。当用户发送请求到达Service时,系统框架会调用Service的onTransact函数,该函数分析接收到的数据包,调用相应的接口函数处理请求
status_t MyService::onTransact(uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
{
switch(code)
{
case 0: {
pid_t pid = data.readInt32();
int num = data.readInt32();
num = num + 100;
reply->writeInt32(num);
return NO_ERROR;
}
break;
default:
return BBinder::onTransact(code, data, reply, flags);
}
}
}; //namespace
(3)编写libservice/Android.mk文件
view plain
# File: Android.mk
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_SRC_FILES := myservice.cpp
LOCAL_C_INCLUDES := $(JNI_H_INCLUDE)
LOCAL_SHARED_LIBRARIES := libutils libbinder
LOCAL_MODULE_TAGS := optional
LOCAL_PRELINK_MODULE := false
LOCAL_MODULE := libmyservice
include $(BUILD_SHARED_LIBRARY)
(4)编译libmyservice.so动态库
在android源码主目录下
view plain
$ source build/envsetup.sh
including device/htc/passion/vendorsetup.sh
including device/samsung/crespo4g/vendorsetup.sh
including device/samsung/crespo/vendorsetup.sh
$ mmm frameworks/base/myservice/libmyservice/
编译成功后生成文件:out/target/proct/generic/system/lib/libmyservice.so