在 SystemServiceRegistry 类中,将 netd 注册成系统服务:
registerService(Context.NETD_SERVICE, IBinder.class, new StaticServiceFetcher<IBinder>() {
@Override
public IBinder createService() throws ServiceNotFoundException {
return ServiceManager.getServiceOrThrow(Context.NETD_SERVICE);
}
});
此处注册后,可以通过 Context 的 getSystemService 获取此服务。其中服务名 NETD_SERVICE 的值为 “netd”,createService 函数是向 service manager 获取服务的 binder 代理。
在 system/netd/server/main.cpp 的 main 函数中向 service manager 注册了服务:
int main() {
...
if ((ret = NetdNativeService::start()) != android::OK) {
ALOGE("Unable to start NetdNativeService: %d", ret);
exit(1);
}
...
IPCThreadState::self()->joinThreadPool();
exit(0);
}
看一下 NetdNativeService 的 start 函数:
status_t NetdNativeService::start() {
IPCThreadState::self()->disableBackgroundScheduling(true);
const status_t ret = BinderService<NetdNativeService>::publish();
if (ret != android::OK) {
return ret;
}
sp<ProcessState> ps(ProcessState::self());
ps->startThreadPool();
ps->giveThreadPoolName();
return android::OK;
}
为了简化代码,一般会调用 BinderService 类的 publish 函数进行服务注册:
template<typename SERVICE>
static status_t publish(bool allowIsolated = false,
int dumpFlags = IServiceManager::DUMP_FLAG_PRIORITY_DEFAULT) {
sp<IServiceManager> sm(defaultServiceManager());
return sm->addService(String16(SERVICE::getServiceName()), new SERVICE(), allowIsolated,
dumpFlags);
}
其中服务名由 NetdNativeService 的静态成员函数 getServiceName 指定:
static char const* getServiceName() { return "netd"; }
注意使用 BinderService 类注册服务的方式,服务类一般可以继承 BinderService:
class NetdNativeService : public BinderService<NetdNativeService>, public BnNetd