系统服务大部分跑在system server里,也是在它里面启动的, 在system server启动时顺便把服务都启动了如AMS ,WMS,PMS都在system server里面html
private void run(){
...
startBootstrapService();
startCoreService();
startOtherServices();
...
}
复制代码
启动服务不必定是要启动工做线程,其实大部分服务都是跑在binder线程的,少部分才有本身的工做线程。 因此启动服务是什么意思?主要是作服务的init工做,如准备服务的binder实体对象, 当client有请求,就会在binder线程池里把请求分发给对应的binder实体对象处理,再回复给clientjava
还有一些服务不在system server里面,它本身开了一个进程, 这种服务通常是native实现的,有本身的main入口函数,须要本身启用binder机制,管理binder通讯,复杂一些, 可是同样的,它也要有binder实体对象,binder线程,binder线程等待client请求,再分发给binder实体对象。面试
不管是start service,仍是bind service,都是从应用端发起的 请求会调到AMS里面。bash
ComponentName startServiceCommon(...){
....
//拿到AMS的binder对象,startSetvice是IPC调用,它里面会建立ServiceRecord,
//ServiceRecord只是service的记录,AMS只是负责service的管理和调度,service的启动和加载仍是要在应用端作的
ActivityManagerNative.getDefault().startService(...);
}
复制代码
应用端怎么启动和加载serviceapp
private void handleCreateService(CreateServiceData data) {
//经过loadClass加载service的类,newInstance给service建立对象
Service service = (Service)cl.loadClass(data.info.name).newInstance();
//给service建立上下文
ContextImpl context = ContextImpl.createAppContext(this, ..);
//create application
Application app = packageInfo.makeApplication(false, ...);
//attach service
service.attach(context, this, ...);
//执行声明周期回调
service.onCreate();
}
复制代码
//跑在system server进程,java层实现
pubic void setSystemProcess(){
ServiceManager.addService(Context.ACTIVITY_SERVICE, this, true);
...
}
//跑在单独进程,native层实现
int main(int, char**){
sp<IServiceManager> sm(defaultServiceManager());
sm->addService(String16(SurfaceFlinger::getServiceName(), flinger, false));
}
复制代码
不管是在sysemserver进程,仍是单独进程,都要在service manager注册服务。ide
应用端的binder实体对象注册到service manager,确定提示权限错误,由于只有系统服务能够注册到service mananger。函数
//经过context的getSystemService(),传入名字,查到服务的管理对象
PowerManager pm = context.getSystemService(Context.POWER_SERVICE);
//调用对象的接口函数使用系统服务
PowerManagfer.WakeLock = pm.newWakelock(Flags. TAG);
复制代码
SystemServiceRegistry.javaui
获取系统服务
registerService(Context.POWER_SERVICE, PowerManager.class,
//先找到Service对应的serviceFetcher,再经过Fecher拿到服务的管理对象
new CachedServiceFetcher<PowerManager>(){
@Override
public PowerManager createService(ContextImpl ctx){
//先经过service manager的getService函数获取系统服务的binder对象
IBinder b = ServiceManager.getService(Context.POWER_SERVICE);
//用对象封装了一层服务的管理对象再传给AP层,方便应用层调用
IPowerManager service = IPowerManager.Stub.asInterface(b);
return new PowerManager(ctx.getOuterContext(),..);
}
});
复制代码
bindService(serviceIntent, new ServiceConection(){
@Override
//AMS经过onServiceConnected回调,把服务的IBinder对象返回给AP端,
public void onServiceConnected(ComponentName name, IBinder service){
//把binder对象service封装一层业务接口对象,就能够持有对象向AP服务发起调用了
IMyInterface myInterface = IMyInterface.Stub.asInterface(service);
}
})
复制代码