往Android系统中添加服务的方法教程
前言
最近因为公司的平台要从Android4.4.4转战Android6.0,带来的问题是之前我们在系统中添加了一些服务,于是要将一些系统级的服务迁移过去,以及一些Framework的自定义包.
碰巧在Gerrit上看到了添加系统服务这一块的patch.正好做个总结.虽然我不是Framework工程师,但是了解Android系统还是很有好处的.
如何获取系统服务
我们获取系统服务都是在context中,getSystemService获取到的.那么我们看一下getSystemService发生了哪些些事情.
getSystemService的实现是ContextImpl,我们去看一下ContextImpl的源码就知道了.
Android4.4.4(KitKat)
这里是Android4.4.4的源码,6.0的源码过会儿看.
//这是我们获取服务的路口
@Override
publicObjectgetSystemService(Stringname){
//可以看到我们是从一个HashMap中拿的服务.
ServiceFetcherfetcher=SYSTEM_SERVICE_MAP.get(name);
returnfetcher==null?null:fetcher.getService(this);
}
privatestaticfinalHashMapSYSTEM_SERVICE_MAP=
newHashMap();
//这是注册服务的方法,请注意是静态方法
privatestaticvoidregisterService(StringserviceName,ServiceFetcherfetcher){
if(!(fetcherinstanceofStaticServiceFetcher)){
fetcher.mContextCacheIndex=sNextPerContextServiceCacheIndex++;
}
SYSTEM_SERVICE_MAP.put(serviceName,fetcher);
}
我们还在ContextImpl中看到很多静态代码块.全是在注册服务,并且全是我们常用的系统服务.
static{
registerService(ACCESSIBILITY_SERVICE,newServiceFetcher(){
publicObjectgetService(ContextImplctx){
returnAccessibilityManager.getInstance(ctx);
}});
registerService(CAPTIONING_SERVICE,newServiceFetcher(){
publicObjectgetService(ContextImplctx){
returnnewCaptioningManager(ctx);
}});
....
}
这么看来,这不就是我们注册服务的地方么?
So.我们找到了注册系统服务的地方,这里我们只需要把我们自己想注册的服务添加进去,完成newServiceFetcher()的抽象方法就行啦.这样我们以后再getSystemService,传入注册时的名称,就可以获取到我们的服务对象了了.当然,这是4.4的方法.
Android6.0(Marshmallow)
我们来看一下ContextImpl的代码
@Override
publicObjectgetSystemService(Stringname){
returnSystemServiceRegistry.getSystemService(this,name);
}
我们发现,与KitKat大大不同,Marshmallow这里是从一个叫做SystemServiceRegistry的类去获取的.
好了,那我们去看它的源码,原来还是和以前一样的套路,不过是单独封装了一个类来管理这些注册的服务.这么设计的确好,代码上的耦合度看上去小多了,且不会使得ContextImpl这个类越来月臃肿.
finalclassSystemServiceRegistry{
privatefinalstaticStringTAG="SystemServiceRegistry";
//Serviceregistryinformation.
//Thisinformationisneverchangedoncestaticinitializationhascompleted.
privatestaticfinalHashMap,String>SYSTEM_SERVICE_NAMES=
newHashMap,String>();
privatestaticfinalHashMap>SYSTEM_SERVICE_FETCHERS=
newHashMap>();
privatestaticintsServiceCacheSize;
//Notinstantiable.
privateSystemServiceRegistry(){}
static{
registerService(Context.ACCESSIBILITY_SERVICE,AccessibilityManager.class,
newCachedServiceFetcher(){
@Override
publicAccessibilityManagercreateService(ContextImplctx){
returnAccessibilityManager.getInstance(ctx);
}});
registerService(Context.CAPTIONING_SERVICE,CaptioningManager.class,
newCachedServiceFetcher(){
@Override
publicCaptioningManagercreateService(ContextImplctx){
returnnewCaptioningManager(ctx);
}});
....
So.我们Marshmallow的系统服务应该在SystemServiceRegistry类中添加.一样的方式.之后我们再getSystemService,传入注册时的名称,就可以获取到我们的服务对象了了.
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对毛票票的支持。