睁开说说:Android服务之bindService解析

打印 上一主题 下一主题

主题 944|帖子 944|积分 2832

前面两篇文章我们分别总结了Android四种Service的根本使用以及源码层面总结一下startService的执行过程,本篇继续从源码层面总结bindService的执行过程。

本文依然按着是什么?有什么?怎么用?啥原理?的步骤来分析。

bindService使用方法和调用流程都与startService时有很多相似之处,方便的话请先阅读上一篇《睁开说说:Android服务之startService解析》。


  • 是什么
调用bindService()来创建,调用方可以通过一个IBinder接口和service举行通信,需要通过ServiceConnection建立毗连。多用于有交互的场景。

只能调用方通过unbindService()方法来断开毗连。调用方可以和Service通讯,并且一个service可以同时和多个调用方存在绑定关系,解除绑定也需要全部调用全部解除绑定之后系统才会烧毁service。


2、有什么

Service和Activity一样也有自己的生命周期,也需要在AndroidManifest.xml中注册。另外bindService的使用比startService要复杂一些:第一需要中创建一个Binder子类并定义方法来给使用者调用在onBind方法中返回它的实例;第二使用者需要创建ServiceConnection对象,并在onServiceConnected回调方法调用Binder子类中定义方法。

2.1 在AndroidManifest.xml中注册

和startService注册流程一样:
 <service android:name="com.example.testdemo.service.ServiceJia" />

2.2 bindService时Service的生命周期

与startService时执行的生命周期有些不同。
onCreate   

它只在Service刚被创建的时候被调用,Service在运行中,这个方法将不会被调用。也就是只有经历过onDestroy生命周期以后再次。

onBind

当另一个组件调用 bindService()想要与Service绑定(例如执行 RPC)时执行,在此方法的实现中,必须通过返回 IBinder 提供一个接口,供客户端用来与服务通信。您必须始终实现此方法;但是,如果您不想答应绑定,则应返回 null。这个方法默认时返回null。
onUnbind

调用方调用 unbindService() 来解除Service绑定时执行。
onDestroy

全部绑定到Service的调用方都解绑以后,则系统会烧毁该服务。

onRebind

当Service中的onUnbind方法返回true,并且Service调用unbindService之后并没有烧毁,此时重新绑定时将会触发onRebind。Service执行过onBind又onUnbind返回true并且还没执行onDestroy,等再次bindService就会执行它。

日志打印

bindService
2024-12-01 11:19:14.434 30802-30802/com.example.testdemo3 E/com.example.testdemo3.service.ServiceJia: onCreate:


2023-12-01 11:19:14.436 30802-30802/com.example.testdemo3 E/com.example.testdemo3.activity.ServiceActivity: onServiceConnected:


2023-12-01 11:19:14.436 30802-30802/com.example.testdemo3 E/com.example.testdemo3.service.ServiceJia: JiaBinder  --doSomething: start conncetion    //这里不是生命周期,是binder对象调用binder内方法的打印证明完成交互


unbindService
2023-12-01 11:21:10.705 12765-12765/com.example.testdemo3 E/com.example.testdemo3.service.ServiceJia: onUnbind:


2023-12-01 11:21:10.705 12765-12765/com.example.testdemo3 E/com.example.testdemo3.service.ServiceJia: onDestroy:


  • 怎么用
因为是有交互的嘛,因此肯定比那些启动以后就成了甩手掌柜的startService使用稍微负责一些,第一需要中创建一个Binder子类并定义方法来给使用者调用在onBind方法中返回它的实例;第二使用者需要创建ServiceConnection对象,并在onServiceConnected回调方法调用Binder子类中定义方法。


详细可以参考前面的《睁开说说:Android四大组件之Service使用》已经总结了使用方法,这里不在赘述。


  • 啥原理,SDK版本API 30
bindService调用流程都与startService时有很多相似之处,方便的话请先阅读上一篇《睁开说说:Android服务之startService解析》。

bindService的启动方法是调用

  1. Intent serviceIntent = new Intent(ServiceActivity.this, ServiceJia.class);
  2. bindService(serviceIntent,serviceConnection, Context.BIND_AUTO_CREATE)
复制代码
然后我们顺着bindService方法开始解析源码,Go :

4.1 从ContexWrapper的bindService开始,同startService:

  1. @Override
  2. public boolean bindService(Intent service, ServiceConnection conn,
  3.         int flags) {
  4.     return mBase.bindService(service, conn, flags);
  5. }
复制代码
4.2 ContextImpl类bindService

mBase的类型是Context,但现实代码逻辑是在它的实现类ContextImpl类。

  1. @Override
  2.     public boolean bindService(Intent service, ServiceConnection conn, int flags) {
  3.         warnIfCallingFromSystemProcess();
  4.         return bindServiceCommon(service, conn, flags, null, mMainThread.getHandler(), null,
  5.                 getUser());
  6. }
  7.     private boolean bindServiceCommon(Intent service, ServiceConnection conn, int flags,
  8.             String instanceName, Handler handler, Executor executor, UserHandle user) {
  9.         // Keep this in sync with DevicePolicyManager.bindDeviceAdminServiceAsUser.
  10.         IServiceConnection sd;
  11.         if (conn == null) {
  12.             throw new IllegalArgumentException("connection is null");
  13.         }
  14.         if (handler != null && executor != null) {
  15.             throw new IllegalArgumentException("Handler and Executor both supplied");
  16.         }
  17.         if (mPackageInfo != null) {
  18.             if (executor != null) {
  19.                 sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(), executor, flags);
  20.             } else {
  21.                 sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(), handler, flags);
  22.             }
  23.         } else {
  24.             throw new RuntimeException("Not supported in system context");
  25.         }
  26.         validateServiceIntent(service);
  27.         try {
  28.             IBinder token = getActivityToken();
  29.             if (token == null && (flags&BIND_AUTO_CREATE) == 0 && mPackageInfo != null
  30.                     && mPackageInfo.getApplicationInfo().targetSdkVersion
  31.                     < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
  32.                 flags |= BIND_WAIVE_PRIORITY;
  33.             }
  34.             service.prepareToLeaveProcess(this);
  35.             int res = ActivityManager.getService().bindIsolatedService(
  36.                 mMainThread.getApplicationThread(), getActivityToken(), service,
  37.                 service.resolveTypeIfNeeded(getContentResolver()),
  38.                 sd, flags, instanceName, getOpPackageName(), user.getIdentifier());
  39.             if (res < 0) {
  40.                 throw new SecurityException(
  41.                         "Not allowed to bind to service " + service);
  42.             }
  43.             return res != 0;
  44.         } catch (RemoteException e) {
  45.             throw e.rethrowFromSystemServer();
  46.         }
  47.     }
复制代码
bindService调用bindServiceCommon方法。将ServiceConnection 转为Binder的实现类IServiceConnection方便跨历程的长途服务的回调自己定义的方法。

4.3 来到LoadedApk

 final @NonNull LoadedApk mPackageInfo;

因此来到LoadedApk 检察getServiceDispatcher方法:

  1. @UnsupportedAppUsage
  2. public final IServiceConnection getServiceDispatcher(ServiceConnection c,
  3.         Context context, Handler handler, int flags) {
  4.     return getServiceDispatcherCommon(c, context, handler, null, flags);
  5. }
  6. private IServiceConnection getServiceDispatcherCommon(ServiceConnection c,
  7.         Context context, Handler handler, Executor executor, int flags) {
  8.     synchronized (mServices) {
  9.         LoadedApk.ServiceDispatcher sd = null;
  10.         ArrayMap<ServiceConnection, LoadedApk.ServiceDispatcher> map = mServices.get(context);
  11.         if (map != null) {
  12.             if (DEBUG) Slog.d(TAG, "Returning existing dispatcher " + sd + " for conn " + c);
  13.             sd = map.get(c);
  14.         }
  15.         if (sd == null) {
  16.             if (executor != null) {
  17.                 sd = new ServiceDispatcher(c, context, executor, flags);
  18.             } else {
  19.                 sd = new ServiceDispatcher(c, context, handler, flags);
  20.             }
  21.             if (DEBUG) Slog.d(TAG, "Creating new dispatcher " + sd + " for conn " + c);
  22.             if (map == null) {
  23.                 map = new ArrayMap<>();
  24.                 mServices.put(context, map);
  25.             }
  26.             map.put(c, sd);
  27.         } else {
  28.             sd.validate(context, handler, executor);
  29.         }
  30.         return sd.getIServiceConnection();
  31.     }
  32. }
复制代码
private final ArrayMap<Context, ArrayMap<ServiceConnection, LoadedApk.ServiceDispatcher>> mServices
    = new ArrayMap<>();

mServices记载了应用当前运动的ServiceConnection和ServiceDispatcher的映射关系,不知是否记得ActivityThread中也有一个final ArrayMap<IBinder, Service> mServices = new ArrayMap<>(); 记载了IBinder,和Service的映射关系。

继续说LoadedApk中的service哈,上面代码会判定是否存在相同的ServiceConnection,如果不存在就创建新ServiceDispatcher实例并将其存储在mService中,key时ServiceConnection,value为ServiceDispatcher,ServiceDispatcher内部存储了ServiceConnection和InnerConnection对象。在调用bindService以后Service和调用方成功建立毗连时系统会通过InnerConnection调用ServiceConnection中的onServiceConnected方法,此时我们就可以使用传过来的IBinder调用Service中的方法完成交互了。这个过程支持跨历程IPC通信,好比两个历程使用AIDL通信。


4.4 ContextImpl类bindService的bindIsolatedService

返回头看上面4.2中的bindService方法,继续向下看会调用ActivityManagerService的bindIsolatedService方法:

  1. synchronized(this) {
  2.             return mServices.bindServiceLocked(caller, token, service,
  3.                     resolvedType, connection, flags, instanceName, callingPackage, userId);
  4.         }
复制代码
4.5 来到ActiveService类的bindServiceLocked

继续调用本类的bringUpServiceLocked:

bringUpServiceLocked(serviceRecord,
        serviceIntent.getFlags(),
        callerFg, false, false);


在调用本类realStartServiceLocked:

realStartServiceLocked(r, app, execInFg);



一样平常来说源码中当一个方法多次穿梭调用之后突然带上了real,那一定是离真相不远了。
app.thread.scheduleCreateService(r, r.serviceInfo,
        mAm.compatibilityInfoForPackage(r.serviceInfo.applicationInfo),
        app.getReportedProcState());
这一行就很熟悉了,和上一篇startService一样,调用的ApplicationThread来创建Service实例并调用它的onCreate生命周期。
上一篇分析这个方法之下是调用onStartCommand生命周期
,没错这里也不例外下面requestServiceBindingsLocked(r, execInFg)也会去调用ApplicationThread的scheduleBindService:

r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind,
        r.app.getReportedProcState());
4.6来到ApplicationThread

使用它封装的handler发送BIND_SERVICE消息:

  1. public final void scheduleBindService(IBinder token, Intent intent,
  2.                 boolean rebind, int processState) {
  3.             updateProcessState(processState, false);
  4.             BindServiceData s = new BindServiceData();
  5.             s.token = token;
  6.             s.intent = intent;
  7.             s.rebind = rebind;
  8.             if (DEBUG_SERVICE)
  9.                 Slog.v(TAG, "scheduleBindService token=" + token + " intent=" + intent + " uid="
  10.                         + Binder.getCallingUid() + " pid=" + Binder.getCallingPid());
  11.             sendMessage(H.BIND_SERVICE, s);
  12.         }
复制代码
接收消息:

  1. case BIND_SERVICE:
  2.                     Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceBind");
  3.                     handleBindService((BindServiceData)msg.obj);
  4.                     Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
  5.                     break;
复制代码
关键来咯:

  1. private void handleBindService(BindServiceData data) {
  2.         Service s = mServices.get(data.token);
  3.         if (DEBUG_SERVICE)
  4.             Slog.v(TAG, "handleBindService s=" + s + " rebind=" + data.rebind);
  5.         if (s != null) {
  6.             try {
  7.                 data.intent.setExtrasClassLoader(s.getClassLoader());
  8.                 data.intent.prepareToEnterProcess();
  9.                 try {
  10.                     if (!data.rebind) {
  11.                         IBinder binder = s.onBind(data.intent);
  12.                         ActivityManager.getService().publishService(
  13.                                 data.token, data.intent, binder);
  14.                     } else {
  15.                         s.onRebind(data.intent);
  16.                         ActivityManager.getService().serviceDoneExecuting(
  17.                                 data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
  18.                     }
  19.                 } catch (RemoteException ex) {
  20.                     throw ex.rethrowFromSystemServer();
  21.                 }
  22.             } catch (Exception e) {
  23.                 if (!mInstrumentation.onException(s, e)) {
  24.                     throw new RuntimeException(
  25.                             "Unable to bind to service " + s
  26.                             + " with " + data.intent + ": " + e.toString(), e);
  27.                 }
  28.             }
  29.         }
  30. }
复制代码
上面代码显示根据token获取Service对象,然后判定首次绑定就调用onBind生命周期,已经绑定过就调用onReBind生命周期,返回的IBinder对象就可以用来调用Service中的方法了。但是为了让调用方拿到这个IBinder就同过onServiceConnected方法回调回去,这个工作就有ActivityManagerService的publishService方法来完成。


4.6 来到ActivityManagerService

  1. public void publishService(IBinder token, Intent intent, IBinder service) {
  2.         // Refuse possible leaked file descriptors
  3.         if (intent != null && intent.hasFileDescriptors() == true) {
  4.             throw new IllegalArgumentException("File descriptors passed in Intent");
  5.         }
  6.         synchronized(this) {
  7.             if (!(token instanceof ServiceRecord)) {
  8.                 throw new IllegalArgumentException("Invalid service token");
  9.             }
  10.             mServices.publishServiceLocked((ServiceRecord)token, intent, service);
  11.         }
  12.     }
复制代码
然后它有调用了ActiveService的publishServiceLocked方法来处置惩罚:

  1. void publishServiceLocked(ServiceRecord r, Intent intent, IBinder service) {
  2.     final long origId = Binder.clearCallingIdentity();
  3.     try {
  4.         if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "PUBLISHING " + r
  5.                 + " " + intent + ": " + service);
  6.         if (r != null) {
  7.             Intent.FilterComparison filter
  8.                     = new Intent.FilterComparison(intent);
  9.             IntentBindRecord b = r.bindings.get(filter);
  10.             if (b != null && !b.received) {
  11.                 b.binder = service;
  12.                 b.requested = true;
  13.                 b.received = true;
  14.                 ArrayMap<IBinder, ArrayList<ConnectionRecord>> connections = r.getConnections();
  15.                 for (int conni = connections.size() - 1; conni >= 0; conni--) {
  16.                     ArrayList<ConnectionRecord> clist = connections.valueAt(conni);
  17.                     for (int i=0; i<clist.size(); i++) {
  18.                         ConnectionRecord c = clist.get(i);
  19.                         if (!filter.equals(c.binding.intent.intent)) {
  20.                             if (DEBUG_SERVICE) Slog.v(
  21.                                     TAG_SERVICE, "Not publishing to: " + c);
  22.                             if (DEBUG_SERVICE) Slog.v(
  23.                                     TAG_SERVICE, "Bound intent: " + c.binding.intent.intent);
  24.                             if (DEBUG_SERVICE) Slog.v(
  25.                                     TAG_SERVICE, "Published intent: " + intent);
  26.                             continue;
  27.                         }
  28.                         if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Publishing to: " + c);
  29.                         try {
  30.                             c.conn.connected(r.name, service, false);
  31.                         } catch (Exception e) {
  32.                             Slog.w(TAG, "Failure sending service " + r.shortInstanceName
  33.                                   + " to connection " + c.conn.asBinder()
  34.                                   + " (in " + c.binding.client.processName + ")", e);
  35.                         }
  36.                     }
  37.                 }
  38.             }
  39.             serviceDoneExecutingLocked(r, mDestroyingServices.contains(r), false);
  40.         }
  41.     } finally {
  42.         Binder.restoreCallingIdentity(origId);
  43.     }
  44. }
复制代码

它在for循环里调用一行代码:

c.conn.connected(r.name, service, false);

顺着代码看:

Conn的类型是是在ConnectionRecord类定义的IServiceConnection:

final IServiceConnection conn;  // The client connection.

Service就是建立毗连的Ibinder实例。

4.7再次来到LoadedApk类

看一下IServiceConnection类connected方法:

  1. private static class InnerConnection extends IServiceConnection.Stub {
  2.     @UnsupportedAppUsage
  3.     final WeakReference<LoadedApk.ServiceDispatcher> mDispatcher;
  4.     InnerConnection(LoadedApk.ServiceDispatcher sd) {
  5.         mDispatcher = new WeakReference<LoadedApk.ServiceDispatcher>(sd);
  6.     }
  7.     public void connected(ComponentName name, IBinder service, boolean dead)
  8.             throws RemoteException {
  9.         LoadedApk.ServiceDispatcher sd = mDispatcher.get();
  10.         if (sd != null) {
  11.             sd.connected(name, service, dead);
  12.         }
  13.     }
  14. }
复制代码
而它又调用了ActivityThread类,mActivityThread就是此中Handler子类 H ,这一步就是为了使用Handler在主线程回调给调用方的onServiceConnected:

  1. public void connected(ComponentName name, IBinder service, boolean dead) {
  2.     if (mActivityExecutor != null) {
  3.         mActivityExecutor.execute(new RunConnection(name, service, 0, dead));
  4.     } else if (mActivityThread != null) {
  5.         mActivityThread.post(new RunConnection(name, service, 0, dead));
  6.     } else {
  7.         doConnected(name, service, dead);
  8.     }
  9. }
复制代码
RunConnection 的实现:

  1. private final class RunConnection implements Runnable {
  2.     RunConnection(ComponentName name, IBinder service, int command, boolean dead) {
  3.         mName = name;
  4.         mService = service;
  5.         mCommand = command;
  6.         mDead = dead;
  7.     }
  8.     public void run() {
  9.         if (mCommand == 0) {
  10.             doConnected(mName, mService, mDead);
  11.         } else if (mCommand == 1) {
  12.             doDeath(mName, mService);
  13.         }
  14.     }
  15.     final ComponentName mName;
  16.     final IBinder mService;
  17.     final int mCommand;
  18.     final boolean mDead;
  19. }
复制代码

回调onServiceConnected彻底呼应上了

  1. public void doConnected(ComponentName name, IBinder service, boolean dead) {
  2.     ServiceDispatcher.ConnectionInfo old;
  3.     ServiceDispatcher.ConnectionInfo info;
  4.     synchronized (this) {
  5.         if (mForgotten) {
  6.             // We unbound before receiving the connection; ignore
  7.             // any connection received.
  8.             return;
  9.         }
  10.         old = mActiveConnections.get(name);
  11.         if (old != null && old.binder == service) {
  12.             // Huh, already have this one.  Oh well!
  13.             return;
  14.         }
  15.         if (service != null) {
  16.             // A new service is being connected... set it all up.
  17.             info = new ConnectionInfo();
  18.             info.binder = service;
  19.             info.deathMonitor = new DeathMonitor(name, service);
  20.             try {
  21.                 service.linkToDeath(info.deathMonitor, 0);
  22.                 mActiveConnections.put(name, info);
  23.             } catch (RemoteException e) {
  24.                 // This service was dead before we got it...  just
  25.                 // don't do anything with it.
  26.                 mActiveConnections.remove(name);
  27.                 return;
  28.             }
  29.         } else {
  30.             // The named service is being disconnected... clean up.
  31.             mActiveConnections.remove(name);
  32.         }
  33.         if (old != null) {
  34.             old.binder.unlinkToDeath(old.deathMonitor, 0);
  35.         }
  36.     }
  37.     // If there was an old service, it is now disconnected.
  38.     if (old != null) {
  39.         mConnection.onServiceDisconnected(name);
  40.     }
  41.     if (dead) {
  42.         mConnection.onBindingDied(name);
  43.     }
  44.     // If there is a new viable service, it is now connected.
  45.     if (service != null) {
  46.         mConnection.onServiceConnected(name, service);
  47.     } else {
  48.         // The binding machinery worked, but the remote returned null from onBind().
  49.         mConnection.onNullBinding(name);
  50.     }
  51. }
复制代码

至此bindService的绑定流程分析完毕!

才疏学浅,如有错误,欢迎指正,多谢。


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

大连密封材料

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表