【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的应用服务有什么区别?

  • 启动方式上有什么区别?
    a)系统服务:大部分是在SystemServer里启动的,也是跑在SystemServer里面,另一些不在SystemServer里的系统服务是在Native实现的,有自己的main入口函数、需要自己去启动binder机制、去管理binder通信;
    b)应用服务:由应用通过bindService或startService向AMS发起的,AMS再通知Service启动。[service启动大致流程?]
  • 注册方式上有什么区别?
    a)系统服务注册到ServiceManager,应用服务注册到AMS;
    b)系统服务是主动注册,应用服务是被动注册
  • 使用方式上有什么区别?
    a) 使用系统服务是通过ServiceManager获取指定名称的服务IBinder实体对象,然后进行Binder通信;
    b)使用应用服务是先向AMS发起绑定请求,AMS通过onServiceConnected回调把服务的binder对象返给应用端,应用端再把binder对象封装成业务接口对象。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值