App 绑定service

    fun bindService() {val i = Intent("com.example.iffyservice.Iffyservice")i.setPackage("com.example.iffyservice")if (bindService(i, this, Service.BIND_AUTO_CREATE)) {println("绑定成功")} else {println("绑定失败")}}
ContextImpl
    @Overridepublic boolean bindService(Intent service, ServiceConnection conn, int flags) {warnIfCallingFromSystemProcess();return bindServiceCommon(service, conn, flags, null, mMainThread.getHandler(), null,getUser());}private boolean bindServiceCommon(Intent service, ServiceConnection conn, int flags,String instanceName, Handler handler, Executor executor, UserHandle user) {//调用AMS的bindIsolatedServiceint res = ActivityManager.getService().bindIsolatedService(mMainThread.getApplicationThread(), getActivityToken(), service,service.resolveTypeIfNeeded(getContentResolver()),sd, flags, instanceName, getOpPackageName(), user.getIdentifier());}

ActivityManagerService bindIsolatedService

    public int bindIsolatedService(IApplicationThread caller, IBinder token, Intent service,String resolvedType, IServiceConnection connection, int flags, String instanceName,String callingPackage, int userId) throws TransactionTooLargeException {enforceNotIsolatedCaller("bindService");//调用ActiveServices的bindServiceLockedsynchronized(this) {return mServices.bindServiceLocked(caller, token, service,resolvedType, connection, flags, instanceName, callingPackage, userId);}}

ActiveServices 启动service

    int bindServiceLocked(IApplicationThread caller, IBinder token, Intent service,String resolvedType, final IServiceConnection connection, int flags,String instanceName, String callingPackage, final int userId)throws TransactionTooLargeException {//BIND_AUTO_CREATE时候 创建serviceif ((flags&Context.BIND_AUTO_CREATE) != 0) {s.lastActivity = SystemClock.uptimeMillis();if (bringUpServiceLocked(s, service.getFlags(), callerFg, false,permissionsReviewRequired) != null) {return 0;}}}private String bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg,boolean whileRestarting, boolean permissionsReviewRequired)throws TransactionTooLargeException {if (!isolated) {app = mAm.getProcessRecordLocked(procName, r.appInfo.uid, false);if (DEBUG_MU) Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid+ " app=" + app);if (app != null && app.thread != null) {try {app.addPackage(r.appInfo.packageName, r.appInfo.longVersionCode, mAm.mProcessStats);//启动ServicerealStartServiceLocked(r, app, execInFg);return null;} catch (TransactionTooLargeException e) {throw e;} catch (RemoteException e) {Slog.w(TAG, "Exception when starting service " + r.shortInstanceName, e);}// If a dead object exception was thrown -- fall through to// restart the application.}} }private final void realStartServiceLocked(ServiceRecord r,ProcessRecord app, boolean execInFg) throws RemoteException {//ActivityThread startServiceapp.thread.scheduleCreateService(r, r.serviceInfo,mAm.compatibilityInfoForPackage(r.serviceInfo.applicationInfo),app.getReportedProcState());}

ActivityThread

        public final void scheduleCreateService(IBinder token,ServiceInfo info, CompatibilityInfo compatInfo, int processState) {updateProcessState(processState, false);CreateServiceData s = new CreateServiceData();s.token = token;s.info = info;s.compatInfo = compatInfo;//Handler create ServicesendMessage(H.CREATE_SERVICE, s);}case CREATE_SERVICE:Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, ("serviceCreate: " + String.valueOf(msg.obj)));handleCreateService((CreateServiceData)msg.obj);Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);break;private void handleCreateService(CreateServiceData data) {//工厂用于创建下面这些东西
//public class AppComponentFactory* @see #instantiateApplication* @see #instantiateActivity* @see #instantiateClassLoader* @see #instantiateService* @see #instantiateReceiver* @see #instantiateProvider*/service = packageInfo.getAppFactory().instantiateService(cl, data.info.name, data.intent);
}

ActiveServices

int bindServiceLocked(IApplicationThread caller, IBinder token, Intent service,String resolvedType, final IServiceConnection connection, int flags,String instanceName, String callingPackage, final int userId)throws TransactionTooLargeException {//service已经存在就直接回调app的onServiceConnectedif (s.app != null && b.intent.received) {// Service is already running, so we can immediately// publish the connection.try {c.conn.connected(s.name, b.intent.binder, false);} catch (Exception e) {Slog.w(TAG, "Failure sending service " + s.shortInstanceName+ " to connection " + c.conn.asBinder()+ " (in " + c.binding.client.processName + ")", e);}// If this is the first app connected back to this binding,// and the service had previously asked to be told when// rebound, then do so.if (b.intent.apps.size() == 1 && b.intent.doRebind) {requestServiceBindingLocked(s, b.intent, callerFg, true);}} else if (!b.intent.requested) {//Service没有bind的话就去bindrequestServiceBindingLocked(s, b.intent, callerFg, false);}}private final boolean requestServiceBindingLocked(ServiceRecord r, IntentBindRecord i,boolean execInFg, boolean rebind) throws TransactionTooLargeException {//thread 是 IApplicationThread zygote fork出来的r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind,r.app.getReportedProcState());
}
ActivityThread.ApplicationThread
        public final void scheduleBindService(IBinder token, Intent intent,boolean rebind, int processState) {updateProcessState(processState, false);BindServiceData s = new BindServiceData();s.token = token;s.intent = intent;s.rebind = rebind;if (DEBUG_SERVICE)Slog.v(TAG, "scheduleBindService token=" + token + " intent=" + intent + " uid="+ Binder.getCallingUid() + " pid=" + Binder.getCallingPid());sendMessage(H.BIND_SERVICE, s);}public void handleMessage(Message msg) {case BIND_SERVICE:Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceBind");handleBindService((BindServiceData)msg.obj);Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);break;}private void handleBindService(BindServiceData data) {Service s = mServices.get(data.token);if (DEBUG_SERVICE)Slog.v(TAG, "handleBindService s=" + s + " rebind=" + data.rebind);if (s != null) {try {data.intent.setExtrasClassLoader(s.getClassLoader());data.intent.prepareToEnterProcess();try {if (!data.rebind) {IBinder binder = s.onBind(data.intent);//调用AMS publishServiceActivityManager.getService().publishService(data.token, data.intent, binder);}} catch (RemoteException ex) {throw ex.rethrowFromSystemServer();}} }}

ActivityManagerService 发布Service

    ActivityManagerService 发布Servicepublic void publishService(IBinder token, Intent intent, IBinder service) {// Refuse possible leaked file descriptorsif (intent != null && intent.hasFileDescriptors() == true) {throw new IllegalArgumentException("File descriptors passed in Intent");}synchronized(this) {if (!(token instanceof ServiceRecord)) {throw new IllegalArgumentException("Invalid service token");}mServices.publishServiceLocked((ServiceRecord)token, intent, service);}}
ActiveServices 
ActiveServices
void publishServiceLocked(ServiceRecord r, Intent intent, IBinder service) {for (int conni = connections.size() - 1; conni >= 0; conni--) {ArrayList<ConnectionRecord> clist = connections.valueAt(conni);for (int i=0; i<clist.size(); i++) {ConnectionRecord c = clist.get(i);c.conn.connected(r.name, service, false);}}
}

会调用client app的OnServiceconnected

override fun onServiceConnected(name: ComponentName?, service: IBinder?) {mIMyAidlInterface =IMyAidlInterface.Stub.asInterface(service)
}

BindeService相关推荐

  1. Android service启动流程分析.

    文章仅仅用于个人的学习记录,基本上内容都是网上各个大神的杰作,此处摘录过来以自己的理解学习方式记录一下. 参考链接: https://my.oschina.net/youranhongcha/blog ...

最新文章

  1. Struts编程心得
  2. MySQL 5.5.19 GA 发布 修复多个Bug
  3. 港湾命令行 配管理IP
  4. 学了C语言,如何利用CURL写一个下载程序?—用nmake编译CURL并安装
  5. linux下安装php的swoole扩展模块(安装后php加载不出来?)
  6. 模型学习 - RNN及一系列发展
  7. 转载:VMware Workstation 无法连接到虚拟机。
  8. NVIDIA显示下载Java_大佬们!我的NVIDIA Geforce Experience 一直下载更新怎么办?
  9. 使用RNN解决NLP中序列标注问题的通用优化思路
  10. python注册登陆程序未响应_SpringBoot实现登录注册常见问题解决方案
  11. mysql 42
  12. Eigen教程(2)之Matrix,Vectors, Dynamic介绍
  13. jquery自定义动画animate方法
  14. 【VS开发】【图像处理】RGB Bayer Color分析
  15. iOS线程之——NSCondition
  16. 使用Python和Asyncio编写在线多人游戏(三)
  17. 华为 IP源防攻击和MAC认证
  18. Redis系列-生产应用篇-分布式锁(5)-单进程Redis分布式锁的Java实现(Redisson使用与底层实现)-原子锁类
  19. [前端案例]百行代码实现炫酷时钟
  20. redirect_uri 参数错误 公众号H5授权登录原理

热门文章

  1. 为什么我建议每个开发人员都需要学Python?不看会后悔!
  2. 经典面试题(47):以下代码将输出的结果是什么?
  3. 如何保证文章中同一组样品在不同子图颜色一致?
  4. xming+putty在windows下远程linux主机图形界面程序及putty乱码解决
  5. Mac插件分享——AE插件、PS插件、FCPX插件【持续更新中】
  6. Snagit好用吗?Snagit 2022最全快捷键指南
  7. monterey系统怎么降级?macOS Monterey系统降回Big Sur的详细教程
  8. 1.7 编程基础之字符串 27 单词翻转 4分 python
  9. NOI题库 python题解-2022.01.07整理(1.1-1.3)
  10. 08产品经理要明白的人性思维-团队管理篇