【Android话题-2.4系统服务】系统服务和bind的应用服务有什么区别

考察内容:

  • 它们在启动方式上有什么区别?
  • 它们在注册方式上有什么区别?
  • 它们在使用方式上有什么区别?

启动方式上有什么区别?

系统服务的启动

系统服务在部分是跑在SystemServer里面

private void run(){
  ......
  startBootstrapServices();
  startCoreServices();
  startOtherServices();
  ......
}

应用服务的启动

ComponentName startServiceCommon(Intent service, ...){
  ......
  ActivityManagerNative.getDefault().startService(...);
}

private void handleCreateService(CreateServiceData data){
  Service service = (Service)cl.loadClass(data.info.name).newInstance();
  ContextImpl context = ContextImpl.createAppContext(this, ...);
  Application app = packageInfo.makeApplication(flase, ...);
  service.onCreate();
}

注册方式上有什么区别?

系统服务的注册

//java层的实现:
public void setSystemProcess(){
  ServiceManager.addService(Context.ACTIVITY_SERVICE, this, true);
  ......
}
//native层的实现
int main(int, char**){
  ......
  sp<IServiceManager> sm(defaultServiceManager());
  sm->addService(String16(SurfaceFlinger::getServiceName()), flinger, flase);
  ......
}

只有系统服务才能注册到ServiceManager

应用服务的注册

在这里插入图片描述

使用上有什么区别?

系统服务的使用

PowerManager pm = context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakLock = pm.newWakLock(flags, TAG);

registerService(Context.POWER_SERVICE, PowerManager.class, new CachedServiceFatcher<PowerManager>(){
  @Overide
  public PowerManager createService(ContextImpl ctx){
    IBinder b = serviceManager.getService(Context.POWER_SERVICE);
    IPowerManager service = IPowerManager.Stub.asInterface(b);
    return new PowerManager(ctx.getOuterContext(), ...);
 }});

应用服务的使用

bindService(serviceIntent, new ServiceConnection(){
  @Override
  public void onServiceConnected(ComponentName name, IBinder service){
    IMyInterface myInterface = IMyInterface.Stub.asInterface(service);
  }

  @Override
  public void onServiceDisconnected(ComponentName name){
 
  }
}, BIND_AUTO_CREATE;

回归:系统服务和bind的应用服务有什么区别?

  • 启动方式上有什么区别?
  • 注册方式上有什么区别?
  • 使用方式上有什么区别?
发布了106 篇原创文章 · 获赞 27 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/menghaocheng/article/details/104320321
今日推荐