Android - Binder机制 - 普通service注册

来源:互联网 发布:warframe淘宝买白金 编辑:程序博客网 时间:2024/06/10 05:09

以下几篇文章是较深入分析binder机制。

目录

1. Android - Binder机制 - ServiceManager

2. Android - Binder机制 - 普通service注册

3. Android - Binder机制 - 获得普通service

4. Android - Binder机制 - client和普通service交互

5. Android - Binder机制 - Binder框架总结

6. Android - Binder机制 - ProcessState和IPCThreadState

7. Android - Binder机制 - 驱动


Android - Binder机制 - 普通service注册

UML及说明


这个要比ServiceManager复杂多了,首先对每个类进行简单角色说明:

1. Main_mediaserver是一个进程,它是多媒体方面的总进程,这个进程共开启了MediaPlayerService等四个服务,我们这篇讲的就是如何注册一个服务;

2. Service_manager.c就是第一篇将的ServiceManager,它是另外一个进程,它要通过binder接收该进程的AddService请求,并进行相应处理(第一篇已经讲);

3. IInterface和IServiceManager定义了Main_mediaserver和ServiceManager之间的功能接口,它是一个抽象类;

4. BpServiceManager和BpInterface继承于IServiceManager,当然就是对功能接口的具体实现;

5. CameraService是照相机的服务,它继承于BinderService,它主要是调用BpServiceManager的addService()接口注册服务;

6. IBinder是定义Binder数据传输层的功能接口,它有一个接口transact,做过android的应该都有印象,它也是一个抽象类;

7. BpBinder是对IBinder的具体实现,它是用来进行数据传输的,BpRefBase中的mRemote就是指向的BpBinder,BpRefBase起了一个代理作用,但是BpBinder没有直接和binder打交道,而是通过调用下面的IPCThreadState实现的;

8. IPCThreadState才是和binder进行打交道的类,它才是真正的数据传输者;

9. ProcessState它主要打开binder设备供IPCThreadState使用和获得ServiceManager用来注册服务;

10. 在分析的时候还是先有一个整体把握,这个会在后面详解,BpRefBase以上是业务逻辑(要实现什么功能),BpRefBase以下是数据传输(通过binder如何将功能实现);

11. 以后只要是见到Bpxxx的是在client进程,Bnxxx的是在service进程;


Main_mediaserver初始化

int main(int argc, char** argv){    sp<ProcessState> proc(ProcessState::self());    sp<IServiceManager> sm = defaultServiceManager();    AudioFlinger::instantiate();    MediaPlayerService::instantiate();    CameraService::instantiate();    AudioPolicyService::instantiate();    ProcessState::self()->startThreadPool();    IPCThreadState::self()->joinThreadPool();}

主要进行以下几步:

1. 创建ProcessState,每个进程就一个ProcessState;

2. 获得ServiceManager,defaultServiceManager()返回的其实是BpServiceManager,在new BpServiceManager时,传入的参数其实就是BpBinder,逐步保存在了BpRefBase中的mRemote中,而这个BpBinder的mHandle是0,这个0就是ServiceManager的索引值;

3. 注册各个服务,在后面详细说明;

4. ProcessState::self()->startThreadPool()和IPCThreadState::self()->joinThreadPool(),这俩是开启两个线程,这两个线程其实完成同样的工作,就是检测是否有发往binder的数据和binder有没有数据发来,这在以后篇章详细讲解,本篇在关系到这两类时会简单说明;

这个进程就开始工作了,它提供了四个服务,下面详细说明如何注册一个服务。


CameraService注册服务

1. BinderService通过defaultServiceManager()->addService(String16(SERVICE::getServiceName()), new SERVICE());

2. defaultServiceManager其实是BpServiceManager,addService则执行remote()->transact(ADD_SERVICE_TRANSACTION, data, &reply);

3. remote()其实是BpBinder,transact执行IPCThreadState::self()->transact(mHandle, code, data, reply, flags),注意mHandle是0,代表ServiceManager;

4. IPCThreadState::self()->transact执行writeTransactionData(BC_TRANSACTION, flags, handle, code, data, NULL)和waitForResponse(reply),很明显就是发送数据,然后等待响应;

5. writeTransactionData其实并不直接将数据发送到binder驱动,而是将数据写到了mOut缓冲区,mOut是Parcel,该类是封装和驱动交互数据的数据格式(如果精通binder,要清楚这个格式);

6. waitForResponse调用talkWithDriver()获得binder的答复;

至此,基本经过六步,注册服务就完成了,这里只是介绍了简单的工作流程。

原创粉丝点击