libbinder -- BinderService

模板类,通过继承该类,能够轻松其publish方法就能将创建服务并注册到sm。通过publishAndJoinThreadPool会在pusblish的基础上,同时让当前线程进入到binder数据处理的循环中。

template<typename SERVICE>
class BinderService
{
public:
    static status_t publish(bool allowIsolated = false) {
        sp<IServiceManager> sm(defaultServiceManager());
        return sm->addService(
                String16(SERVICE::getServiceName()),
                new SERVICE(), allowIsolated);
    }

    static void publishAndJoinThreadPool(bool allowIsolated = false) {
        publish(allowIsolated);
        joinThreadPool();
    }

    static void instantiate() { publish(); }

    static status_t shutdown() { return NO_ERROR; }
private:
    static void joinThreadPool() {
        sp<ProcessState> ps(ProcessState::self());
        ps->startThreadPool();
        ps->giveThreadPoolName();
        IPCThreadState::self()->joinThreadPool();
    }
};

从上面的代码可以看到,我们的子类还要定义并实现一个静态方法getServiceName。这里为什么不弄一个纯虚函数呢??

参考AudioFlingerBinderService用法如下:

class AudioFlinger :
    public BinderService<AudioFlinger>,
    public BnAudioFlinger
{
    friend class BinderService<AudioFlinger>;   // for AudioFlinger()

public:
    static const char* getServiceName() ANDROID_API { return "media.audio_flinger"; }
	...
};

// main_mediaserver.cpp
int main() {
    ...  
    AudioFlinger::instantiate();
    AudioPolicyService::instantiate();
    ...
}

用法就是酱紫。。。

原文地址:https://www.cnblogs.com/liutimo/p/14615310.html