发起绑定

发起方的ServiceConnection对象作为bindService参数

ContextWrapper.java
复制代码
    public boolean bindService(Intent service, ServiceConnection conn,int flags) {return mBase.bindService(service, conn, flags);}
复制代码
ContextImpl.java
复制代码
    public boolean bindService(Intent service, ServiceConnection conn,int flags) {warnIfCallingFromSystemProcess();return bindServiceCommon(service, conn, flags, Process.myUserHandle());}private boolean bindServiceCommon(Intent service, ServiceConnection conn, int flags,UserHandle user) {IServiceConnection sd;if (conn == null) {throw new IllegalArgumentException("connection is null");}if (mPackageInfo != null) {sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(),mMainThread.getHandler(), flags);} else {throw new RuntimeException("Not supported in system context");}validateServiceIntent(service);try {IBinder token = getActivityToken();if (token == null && (flags&BIND_AUTO_CREATE) == 0 && mPackageInfo != null&& mPackageInfo.getApplicationInfo().targetSdkVersion< android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {flags |= BIND_WAIVE_PRIORITY;}service.prepareToLeaveProcess();int res = ActivityManagerNative.getDefault().bindService(mMainThread.getApplicationThread(), getActivityToken(), service,service.resolveTypeIfNeeded(getContentResolver()),sd, flags, getOpPackageName(), user.getIdentifier());if (res < 0) {throw new SecurityException("Not allowed to bind to service " + service);}return res != 0;} catch (RemoteException e) {throw new RuntimeException("Failure from system", e);}}
复制代码
ActivityManagerNative.java
复制代码
    public int bindService(IApplicationThread caller, IBinder token,Intent service, String resolvedType, IServiceConnection connection,int flags,  String callingPackage, int userId) throws RemoteException {Parcel data = Parcel.obtain();Parcel reply = Parcel.obtain();data.writeInterfaceToken(IActivityManager.descriptor);data.writeStrongBinder(caller != null ? caller.asBinder() : null);data.writeStrongBinder(token);service.writeToParcel(data, 0);data.writeString(resolvedType);data.writeStrongBinder(connection.asBinder());data.writeInt(flags);data.writeString(callingPackage);data.writeInt(userId);mRemote.transact(BIND_SERVICE_TRANSACTION, data, reply, 0);reply.readException();int res = reply.readInt();data.recycle();reply.recycle();return res;}
复制代码

mRemote为IActivityManager类型。

ActivityManagerService.java
复制代码
    public int bindService(IApplicationThread caller, IBinder token, Intent service,String resolvedType, IServiceConnection connection, int flags, String callingPackage,int userId) throws TransactionTooLargeException {enforceNotIsolatedCaller("bindService");synchronized(this) {return mServices.bindServiceLocked(caller, token, service,resolvedType, connection, flags, callingPackage, userId);}}
复制代码
ActiveServices.java
复制代码
int bindServiceLocked(IApplicationThread caller, IBinder token, Intent service,String resolvedType, IServiceConnection connection, int flags,String callingPackage, int userId) throws TransactionTooLargeException {if ((flags&Context.BIND_AUTO_CREATE) != 0) {s.lastActivity = SystemClock.uptimeMillis();if (bringUpServiceLocked(s, service.getFlags(), callerFg, false) != null) {return 0;}}
}private final String bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg,boolean whileRestarting) throws TransactionTooLargeException {// Not running -- get it started, and enqueue this service record// to be executed when the app comes up.if (app != null && app.thread != null) {try {app.addPackage(r.appInfo.packageName, r.appInfo.versionCode, mAm.mProcessStats);realStartServiceLocked(r, app, execInFg);return null;} catch (TransactionTooLargeException e) {...if (app == null) {if ((app=mAm.startProcessLocked(procName, r.appInfo, true, intentFlags,"service", r.name, false, isolated, false)) == null) {String msg = "Unable to launch app "+ r.appInfo.packageName + "/"+ r.appInfo.uid + " for service "+ r.intent.getIntent() + ": process is bad";Slog.w(TAG, msg);bringDownServiceLocked(r);return msg;}if (isolated) {r.isolatedProc = app;}}
}private final void realStartServiceLocked(ServiceRecord r,ProcessRecord app, boolean execInFg) throws RemoteException {app.thread.scheduleCreateService(r, r.serviceInfo,mAm.compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo),app.repProcState);}//进入service的onCreate...requestServiceBindingsLocked(r, execInFg);//绑定
复制代码
ApplicationThreadNative.java
复制代码
    public final void scheduleCreateService(IBinder token, ServiceInfo info,CompatibilityInfo compatInfo, int processState) throws RemoteException {Parcel data = Parcel.obtain();data.writeInterfaceToken(IApplicationThread.descriptor);data.writeStrongBinder(token);info.writeToParcel(data, 0);compatInfo.writeToParcel(data, 0);data.writeInt(processState);try {mRemote.transact(SCHEDULE_CREATE_SERVICE_TRANSACTION, data, null,IBinder.FLAG_ONEWAY);} catch (TransactionTooLargeException e) {Log.e("CREATE_SERVICE", "Binder failure starting service; service=" + info);throw e;}data.recycle();}
复制代码

创建Application对象并进入service的onCreate方法

ActivityThread.java
复制代码
        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;sendMessage(H.CREATE_SERVICE, s);}private void handleCreateService(CreateServiceData data) {try {if (localLOGV) Slog.v(TAG, "Creating service " + data.info.name);ContextImpl context = ContextImpl.createAppContext(this, packageInfo);context.setOuterContext(service);Application app = packageInfo.makeApplication(false, mInstrumentation);service.attach(context, this, data.info.name, data.token, app,ActivityManagerNative.getDefault());service.onCreate();//进入远程服务mServices.put(data.token, service);try {ActivityManagerNative.getDefault().serviceDoneExecuting(data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);} catch (RemoteException e) {// nothing to do.}} }
复制代码

服务进程创建完成后,调用requestServiceBindingsLocked(r, execInFg);绑定。

ActiveServices.java
复制代码
    private final void requestServiceBindingsLocked(ServiceRecord r, boolean execInFg)throws TransactionTooLargeException {for (int i=r.bindings.size()-1; i>=0; i--) {IntentBindRecord ibr = r.bindings.valueAt(i);if (!requestServiceBindingLocked(r, ibr, execInFg, false)) {break;}}}private final boolean requestServiceBindingLocked(ServiceRecord r, IntentBindRecord i,boolean execInFg, boolean rebind) throws TransactionTooLargeException {bumpServiceExecutingLocked(r, execInFg, "bind");r.app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind,r.app.repProcState);}
复制代码
ApplicationThreadNative.java
复制代码
    public final void scheduleBindService(IBinder token, Intent intent, boolean rebind,int processState) throws RemoteException {Parcel data = Parcel.obtain();data.writeInterfaceToken(IApplicationThread.descriptor);data.writeStrongBinder(token);intent.writeToParcel(data, 0);data.writeInt(rebind ? 1 : 0);data.writeInt(processState);mRemote.transact(SCHEDULE_BIND_SERVICE_TRANSACTION, data, null,IBinder.FLAG_ONEWAY);data.recycle();}
复制代码

进入Service的onBind

ActivityThread.java
复制代码
        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);}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) {IBinder binder = s.onBind(data.intent);//进入Service的onBindActivityManagerNative.getDefault().publishService(data.token, data.intent, binder);//通过onServiceConnected回调将binder对象返回给Service} else {s.onRebind(data.intent);ActivityManagerNative.getDefault().serviceDoneExecuting(data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);}}}
复制代码

回调ServiceConnection的onServiceConnected

ActivityManagerNative.java
复制代码
    public void publishService(IBinder token,Intent intent, IBinder service) throws RemoteException {Parcel data = Parcel.obtain();Parcel reply = Parcel.obtain();data.writeInterfaceToken(IActivityManager.descriptor);data.writeStrongBinder(token);intent.writeToParcel(data, 0);data.writeStrongBinder(service);mRemote.transact(PUBLISH_SERVICE_TRANSACTION, data, reply, 0);reply.readException();data.recycle();reply.recycle();}
复制代码

mRemote为IActivityManager类型

ActivityManagerService.java
复制代码
    public 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.java
复制代码
    void publishServiceLocked(ServiceRecord r, Intent intent, IBinder service) {final long origId = Binder.clearCallingIdentity();try {if (r != null) {Intent.FilterComparison filter= new Intent.FilterComparison(intent);IntentBindRecord b = r.bindings.get(filter);if (b != null && !b.received) {b.binder = service;b.requested = true;b.received = true;for (int conni=r.connections.size()-1; conni>=0; conni--) {ArrayList<ConnectionRecord> clist = r.connections.valueAt(conni);for (int i=0; i<clist.size(); i++) {ConnectionRecord c = clist.get(i);if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Publishing to: " + c);try {c.conn.connected(r.name, service);} catch (Exception e) {Slog.w(TAG, "Failure sending service " + r.name +" to connection " + c.conn.asBinder() +" (in " + c.binding.client.processName + ")", e);}}}}serviceDoneExecutingLocked(r, mDestroyingServices.contains(r), false);}} finally {Binder.restoreCallingIdentity(origId);}}
复制代码
LoadedApk.java
复制代码
        private static class InnerConnection extends IServiceConnection.Stub {final WeakReference<LoadedApk.ServiceDispatcher> mDispatcher;InnerConnection(LoadedApk.ServiceDispatcher sd) {mDispatcher = new WeakReference<LoadedApk.ServiceDispatcher>(sd);}public void connected(ComponentName name, IBinder service) throws RemoteException {LoadedApk.ServiceDispatcher sd = mDispatcher.get();if (sd != null) {sd.connected(name, service);}}}static final class ServiceDispatcher {ServiceDispatcher(ServiceConnection conn,Context context, Handler activityThread, int flags) {mIServiceConnection = new InnerConnection(this);mConnection = conn;mContext = context;mActivityThread = activityThread;mLocation = new ServiceConnectionLeaked(null);mLocation.fillInStackTrace();mFlags = flags;}public void connected(ComponentName name, IBinder service) {if (mActivityThread != null) {mActivityThread.post(new RunConnection(name, service, 0));//新建RunConnection任务,在该任务中回调onServiceConnected} else {doConnected(name, service);}}}private final class RunConnection implements Runnable {RunConnection(ComponentName name, IBinder service, int command) {mName = name;mService = service;mCommand = command;}public void run() {if (mCommand == 0) {doConnected(mName, mService);} else if (mCommand == 1) {doDeath(mName, mService);}}final ComponentName mName;final IBinder mService;final int mCommand;}public void doConnected(ComponentName name, IBinder service) {// If there was an old service, it is not disconnected.if (old != null) {mConnection.onServiceDisconnected(name);}// If there is a new service, it is now connected.if (service != null) {mConnection.onServiceConnected(name, service);//回调ServiceConnection的onServiceConnected}}
复制代码

至此。onBind方法返回Ibinder对象就通过发起方的ServiceConnection的onServiceConnected返回了。

转载于:https://juejin.im/post/5c998aabe51d452a12197f09

bindService过程相关推荐

  1. bindService()流程源码分析

    ServiceManager管理着系统中的所有服务,服务在启动的时候会注册到ServiceManager,其他进程要使用相应服务时需要先去ServiceManager中寻找,然后使用. Service ...

  2. 深入理解Binder机制4-bindService过程分析

    一.概述 1.1 Binder架构 Android内核基于Linux系统,而Linux系统进程间通信方式有很多,如管道,共g享内存,信号,信号量,消息队列,套接字.而Android为什么要用binde ...

  3. [转]Android中程序与Service交互的方式——交互方式

    本文转自:http://blog.csdn.net/yihongyuelan/article/details/7216188 上一篇文章:Android中程序与Service交互的方式--综述 简述了 ...

  4. android面试service,Android面试,与Service交互方式(4)

    自定义接口交互 4何谓自定义接口呢,其实就是我们自己通过接口的实现来达到Activity与Service交互的目的,我们通过在Activity和Service之间架设一座桥樑,从而达到数据交互的目的, ...

  5. Android 系统(248)---解读Android进程优先级ADJ算法

    本文基于原生Android P源码来解读进程优先级原理,基于篇幅考虑会精炼部分代码 一.概述 1.1 进程 Android框架对进程创建与管理进行了封装,对于APP开发者只需知道Android四大组件 ...

  6. Android面试,与Service交互方式

    五种交互方式,分别是:通过广播交互.通过共享文件交互.通过Messenger(信使)交互.通过自定义接口交互.通过AIDL交互.(可能更多) Service与Thread的区别 Thread:Thre ...

  7. Andromeda:适用于多进程架构的组件通信框架

    引言 其实Android的组件化由来已久,而且已经有了一些不错的方案,特别是在页面跳转这方面,比如阿里的ARouter, 天猫的统跳协议, Airbnb的DeepLinkDispatch, 借助注解来 ...

  8. Android应用程序绑定服务(bindService)的过程源代码分析

    Android应用程序组件Service与Activity一样,既可以在新的进程中启动,也可以在应用程序进程内部启动:前面我们已经分析了在新的进程中启动Service的过程,本文将要介绍在应用程序内部 ...

  9. 深入理解Android的startservice和bindservice

    一.首先,让我们确认下什么是service?          service就是android系统中的服务,它有这么几个特点:它无法与用户直接进行交互.它必须由用户或者其他程序显式的启动.它的优先级 ...

最新文章

  1. 深度学习与工业互联网安全
  2. memcached在windows下的基本使用方法
  3. 独家揭秘!史上最强中文NLP预训练模型 | 直播报名中
  4. nginx反代理服务器
  5. Java百度网盘创建链接,java获取百度网盘真实下载链接的方法
  6. 纪中C组模拟赛总结(2019.7.5)
  7. 汽车上有哪些很难发现却非常实用的配置?
  8. java中访问权限的设置
  9. IT6613,是一款BT1120 TO HDMI 单转芯片
  10. matlab有限元分析教程,Matlab做有限元分析
  11. VS下使用多字符集编码和Unicode字符集编码的总结
  12. Google账号登录后直接跳转百度首页,登陆不上
  13. illegal multibyte sequence
  14. arduino超声波测距接线图详细_Arduino Uno + HY-SRF05 超声波测距模块详细讲解演示实验...
  15. 新人报道,请多多关照。
  16. Android 第三方SDK的检测与提取
  17. LimeSDR srsLTE实验
  18. 硬件开发:嵌入式系统知识和接口技术(值得收藏)
  19. 1KB (Kilobyte 千字节)=1024B=8192b【大B代表Byte字节,小b代表bit位】
  20. 计算机视觉中low-level feature和high level feature的理解

热门文章

  1. 编译并使用boost库(win7+boost1.60+vs2013)
  2. 在Qt Creator以外编写Qt程序
  3. 双系统windows10扩容ubuntu16.04
  4. php中的Register Globals
  5. [Turn]C# 强制关闭当前程序进程(完全Kill掉不留痕迹)
  6. 设置笔记笔触摸区(Vista)
  7. 获取 Windows 窗体 DataGridView 控件中选定的单元格、行和列
  8. 我的程序员偶像在哪里?
  9. 什么是Apache Spark?这篇文章带你从零基础学起
  10. 从AI到IA,你愿意买一个机器人伴侣同居吗?