前面的博文分析了 Android Service 中 startService 启动方法。我们知道还可以通过 bindService 的方式,一个需要进行 Binder 通信的 Client 一般通过 bindService() 来启动 Service。
相比于用 startService 启动的 Service,bindService 启动的服务具有如下特点:
1.bindService 启动的服务在调用者和服务之间是典型的 client-server 的接口,即调用者是客户端,service 是服务端,service 就一个,但是连接绑定到 service 上面的客户端 client 可以是一个或多个。这里特别要说明的是,这里所提到的 client 指的是组件,比如某个 Activity。
2.客户端 client(即调用 bindService 的一方,比如某个 Activity)可以通过 IBinder 接口获取 Service 的实例,从而可以实现在 client 端直接调用 Service 中的方法以实现灵活的交互,并且可借助 IBinder 实现跨进程的 client-server 的交互,这在纯 startService 启动的 Service 中是无法实现的。
3.不同于 startService 启动的服务默认无限期执行(可以通过 Context 的 stopService 或 Service 的 stopSelf 方法停止运行),bindService 启动的服务的生命周期与其绑定的 client 息息相关。当 client 销毁的时候,client 会自动与 Service 解除绑定,当然 client 也可以通过明确调用 Context 的 unbindService 方法与 Service 解除绑定。当没有任何 client 与 Service 绑定的时候,Service 会自行销毁(通过 startService 启动的除外)。
4.startService 和 bindService 二者执行的回调方法不同:startService 启动的服务会涉及 Service 的 onStartCommand 回调方法,而通过 bindService 启动的服务会涉及 Service 的 onBind、onUnbind等回调方法。
下面是使用绑定 Service 的代码,我们在主 Activity 中 bindService。然后在 onServiceConnected 方法中拿到服务对象,并调用其 exec 方法。这可以理解为我们的 Activity 把任务委托给了 Service 执行。
class MainActivity : AppCompatActivity() {
companion object {
const val TAG = "MainActivity"
......
}
......
private var mDemoBindService: DemoBindService? = null
private val mDemoBindServiceConnection = object : ServiceConnection {
override fun onServiceDisconnected(name: ComponentName) {
mDemoBindService = null
}
override fun onServiceConnected(name: ComponentName, service: IBinder) {
Log.d(TAG, "--onServiceConnected--")
mDemoBindService = (service as DemoBindService.DemoBinder).getService()
val result = mDemoBindService?.exec()
Log.d(TAG, "result=$result")
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
......
val btn1 = findViewById<Button>(R.id.button1)
btn1.setOnClickListener {
val intent = Intent(this, DemoBindService::class.java)
bindService(intent, mDemoBindServiceConnection, Context.BIND_AUTO_CREATE)
}
val btn2 = findViewById<Button>(R.id.button2)
btn2.setOnClickListener {
unbindService(mDemoBindServiceConnection)
}
......
}
......
}
对应的 Service 如下:
class DemoBindService : Service() {
companion object {
const val TAG = "DemoBindService"
}
private val mBinder = DemoBinder(this@DemoBindService)
override fun onBind(intent: Intent?): IBinder? {
Log.d(TAG, "onBind")
return mBinder
}
class DemoBinder(private val demoBindService: DemoBindService) : Binder() {
fun getService(): DemoBindService {
return demoBindService
}
}
fun exec(): Int {
Log.d(TAG, "exec() from DemoBindService")
return 1
}
override fun onDestroy() {
super.onDestroy()
}
override fun onUnbind(intent: Intent): Boolean {
Log.d(TAG, "onUnbind")
return super.onUnbind(intent)
}
}
如果点击按钮绑定了 DemoBindService,但不点击取消绑定按钮,就会看到下面的报错 Log,这个 Log 其实已经给我们指明了方向。
07-18 06:39:51.595 4401-4401/com.demo.framework E/ActivityThread: Activity com.demo.framework.MainActivity has leaked ServiceConnection com.demo.framework.MainActivity$mDemoBindServiceConnection$1@e8f48f4 that was originally bound here
android.app.ServiceConnectionLeaked: Activity com.demo.framework.MainActivity has leaked ServiceConnection com.demo.framework.MainActivity$mDemoBindServiceConnection$1@e8f48f4 that was originally bound here
at android.app.LoadedApk$ServiceDispatcher.<init>(LoadedApk.java:1097)
at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:991)
at android.app.ContextImpl.bindServiceCommon(ContextImpl.java:1310)
at android.app.ContextImpl.bindService(ContextImpl.java:1293)
at android.content.ContextWrapper.bindService(ContextWrapper.java:606)
at com.demo.framework.MainActivity$onCreate$2.onClick(MainActivity.kt:67)
at android.view.View.performClick(View.java:5204)
at android.view.View$PerformClick.run(View.java:21153)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5436)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
马上转到 ContextWrapper bindService。
frameworks/base/core/java/android/content/ContextWrapper.java
public class ContextWrapper extends Context {
Context mBase;
......
@Override
public boolean bindService(Intent service, ServiceConnection conn,
int flags) {
return mBase.bindService(service, conn, flags);
}
......
}
和之前的分析流程一样,mBase 实际上是 ContextImpl 对象。下一步调用 ContextImpl.bindService。这个方法内部先调用 warnIfCallingFromSystemProcess() 方法,它会检查当前的进程用户 ID 是否是系统ID,如果是就打印一条警告级别的 Log。接着继续调用 bindServiceCommon 方法。
UserHandle ---- 表示设备上的用户。
如果传入的 ServiceConnection 为 null,则抛出 IllegalArgumentException。接着获取 IServiceConnection 对象,这是通过调用 getServiceDispatcher 方法实现的。
validateServiceIntent 方法实现校验 Intent 是否有效。
最后会调用 ActivityManagerProxy bindService 方法和远程 ActivityManagerService 通信。
frameworks/base/core/java/android/app/ContextImpl.java
class ContextImpl extends Context {
......
@Override
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);
}
}
......
private void warnIfCallingFromSystemProcess() {
if (Process.myUid() == Process.SYSTEM_UID) {
Slog.w(TAG, "Calling a method in the system process without a qualified user: "
+ Debug.getCallers(5));
}
}
......
}
现在具体看 getServiceDispatcher 的实现,mPackageInfo 是一个 LoadedApk 对象。此方法的 Context 形参,实际上就是 Demo 中的 MainActivity。首先使用 Context 作为 key 在对应的 ArrayMap 中查找,这个 Map 记录了组件中关联有多少 ServiceConnection-LoadedApk.ServiceDispatcher 对。每个 ServiceConnection 都对应一个 LoadedApk.ServiceDispatcher 对象。我们第一次调用 sd 对象一定为 null,因此就会新创建一个 ServiceDispatcher 对象,并将其添加到 map 中。最后调用 ServiceDispatcher 的 getIServiceConnection() 方法返回实现 IServiceConnection 接口的对象。
frameworks/base/core/java/android/app/LoadedApk.java
public final class LoadedApk {
......
private final ArrayMap<Context, ArrayMap<ServiceConnection, LoadedApk.ServiceDispatcher>> mServices
= new ArrayMap<Context, ArrayMap<ServiceConnection, LoadedApk.ServiceDispatcher>>();
......
public final IServiceConnection getServiceDispatcher(ServiceConnection c,
Context context, Handler handler, int flags) {
synchronized (mServices) {
LoadedApk.ServiceDispatcher sd = null;
ArrayMap<ServiceConnection, LoadedApk.ServiceDispatcher> map = mServices.get(context);
if (map != null) {
sd = map.get(c);
}
if (sd == null) {
sd = new ServiceDispatcher(c, context, handler, flags);
if (map == null) {
map = new ArrayMap<ServiceConnection, LoadedApk.ServiceDispatcher>();
mServices.put(context, map);
}
map.put(c, sd);
} else {
sd.validate(context, handler);
}
return sd.getIServiceConnection();
}
}
......
}
马上来看新建一个 ServiceDispatcher 对象都做了什么?需要注意一下返回的实现 IServiceConnection 接口对象实际上是 InnerConnection 类型的。validate 函数则验证传入的 context 和 handler 是否和构建 ServiceDispatcher 对象时相同,如果不相同则抛出异常。
frameworks/base/core/java/android/app/LoadedApk.java
public final class LoadedApk {
......
static final class ServiceDispatcher {
private final ServiceDispatcher.InnerConnection mIServiceConnection;
private final ServiceConnection mConnection;
private final Context mContext;
private final Handler mActivityThread;
private final ServiceConnectionLeaked mLocation;
private final int mFlags;
private RuntimeException mUnbindLocation;
private boolean mDied;
private boolean mForgotten;
......
private static class InnerConnection extends IServiceConnection.Stub {
......
}
......
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;
}
void validate(Context context, Handler activityThread) {
if (mContext != context) {
throw new RuntimeException(
"ServiceConnection " + mConnection +
" registered with differing Context (was " +
mContext + " now " + context + ")");
}
if (mActivityThread != activityThread) {
throw new RuntimeException(
"ServiceConnection " + mConnection +
" registered with differing handler (was " +
mActivityThread + " now " + activityThread + ")");
}
}
......
IServiceConnection getIServiceConnection() {
return mIServiceConnection;
}
......
}
......
}
下一步是调用 ActivityManagerProxy bindService 方法。ActivityManagerProxy 的 bindService 方法最终是调用其内部的一个 Binder 代理对象 mRemote 向 ActivityManagerService 发送一个类型为 BIND_SERVICE_TRANSACTION 的进程间通信请求。
frameworks/base/core/java/android/app/ActivityManagerNative.java
class ActivityManagerProxy implements IActivityManager
{
......
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;
}
......
}
ActivityManagerService 中的 bindService 方法,最后会调用 ActiveServices 对象的 bindServiceLocked 方法。
frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
public final class ActivityManagerService extends ActivityManagerNative
implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
......
public int bindService(IApplicationThread caller, IBinder token, Intent service,
String resolvedType, IServiceConnection connection, int flags, String callingPackage,
int userId) throws TransactionTooLargeException {
enforceNotIsolatedCaller("bindService");
// 拒绝可能泄露的文件描述符
if (service != null && service.hasFileDescriptors() == true) {
throw new IllegalArgumentException("File descriptors passed in Intent");
}
if (callingPackage == null) {
throw new IllegalArgumentException("callingPackage cannot be null");
}
synchronized(this) {
return mServices.bindServiceLocked(caller, token, service,
resolvedType, connection, flags, callingPackage, userId);
}
}
......
}
bindServiceLocked 非常冗长,首先它会调用 bringUpServiceLocked ,然后调用发布连接,这是我们重点关注的两步。
frameworks/base/services/core/java/com/android/server/am/ActiveServices.java
public final class ActiveServices {
......
int bindServiceLocked(IApplicationThread caller, IBinder token, Intent service,
String resolvedType, IServiceConnection connection, int flags,
String callingPackage, int userId) throws TransactionTooLargeException {
// 调用 ActivityManagerService getRecordForAppLocked 获取 ProcessRecord 对象
final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
if (callerApp == null) {
throw new SecurityException(
"Unable to find app for caller " + caller
+ " (pid=" + Binder.getCallingPid()
+ ") when binding service " + service);
}
ActivityRecord activity = null;
if (token != null) {
activity = ActivityRecord.isInStackLocked(token);
if (activity == null) {
Slog.w(TAG, "Binding with unknown activity: " + token);
return 0;
}
}
......
// 进程组优先级级别是否等于 THREAD_GROUP_BG_NONINTERACTIVE
final boolean callerFg = callerApp.setSchedGroup != Process.THREAD_GROUP_BG_NONINTERACTIVE;
// 检索 ServiceLookupResult 对象,ServiceLookupResult 是一个包装了 ServiceRecord 和 permission 的实体类
ServiceLookupResult res =
retrieveServiceLocked(service, resolvedType, callingPackage,
Binder.getCallingPid(), Binder.getCallingUid(), userId, true, callerFg);
if (res == null) {
return 0;
}
if (res.record == null) {
return -1;
}
ServiceRecord s = res.record;
final long origId = Binder.clearCallingIdentity();
try {
.......
if ((flags&Context.BIND_AUTO_CREATE) != 0) {
s.lastActivity = SystemClock.uptimeMillis();
if (!s.hasAutoCreateConnections()) {
// 这是第一次绑定,让跟踪器知道。
ProcessStats.ServiceState stracker = s.getTracker();
if (stracker != null) {
stracker.setBound(true, mAm.mProcessStats.getMemFactorLocked(),
s.lastActivity);
}
}
}
mAm.startAssociationLocked(callerApp.uid, callerApp.processName,
s.appInfo.uid, s.name, s.processName);
AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
ConnectionRecord c = new ConnectionRecord(b, activity,
connection, flags, clientLabel, clientIntent);
IBinder binder = connection.asBinder();
// 可能有多个客户端关联同一个 Service
ArrayList<ConnectionRecord> clist = s.connections.get(binder);
// 如果还没有则添加对应的 ConnectionRecord
if (clist == null) {
clist = new ArrayList<ConnectionRecord>();
s.connections.put(binder, clist);
}
clist.add(c);
b.connections.add(c);
// Activity 中关联的所有 ConnectionRecord 对象,所以也需要将其加入对应列表
if (activity != null) {
if (activity.connections == null) {
activity.connections = new HashSet<ConnectionRecord>();
}
activity.connections.add(c);
}
b.client.connections.add(c);
// 设置 BIND_ABOVE_CLIENT 标志,会提升优先级,其会超过 Activity
if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
b.client.hasAboveClient = true;
}
if (s.app != null) {
updateServiceClientActivitiesLocked(s.app, c, true);
}
clist = mServiceConnections.get(binder);
if (clist == null) {
clist = new ArrayList<ConnectionRecord>();
mServiceConnections.put(binder, clist);
}
clist.add(c);
// 进入此分支
if ((flags&Context.BIND_AUTO_CREATE) != 0) {
s.lastActivity = SystemClock.uptimeMillis();
// 调用 bringUpServiceLocked
if (bringUpServiceLocked(s, service.getFlags(), callerFg, false) != null) {
return 0;
}
}
......
if (s.app != null && b.intent.received) {
// Service 已经在运行,因此我们可以立即发布连接。
try {
c.conn.connected(s.name, b.intent.binder);
} catch (Exception e) {
Slog.w(TAG, "Failure sending service " + s.shortName
+ " to connection " + c.conn.asBinder()
+ " (in " + c.binding.client.processName + ")", e);
}
......
} else if (!b.intent.requested) {
requestServiceBindingLocked(s, b.intent, callerFg, false);
}
getServiceMap(s.userId).ensureNotStartingBackground(s);
} finally {
Binder.restoreCallingIdentity(origId);
}
return 1;
}
......
}
接下来先看 bringUpServiceLocked 方法。
frameworks/base/services/core/java/com/android/server/am/ActiveServices.java
public final class ActiveServices {
......
private final String bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg,
boolean whileRestarting) throws TransactionTooLargeException {
......
// 服务现在正在启动,它的包不能停止。
try {
AppGlobals.getPackageManager().setPackageStoppedState(
r.packageName, false, r.userId);
} catch (RemoteException e) {
} catch (IllegalArgumentException e) {
Slog.w(TAG, "Failed trying to unstop package "
+ r.packageName + ": " + e);
}
// 如果设置了,服务将在自己的独立进程中运行。
final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
final String procName = r.processName;
ProcessRecord app;
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.versionCode, mAm.mProcessStats);
// 下一步调用
realStartServiceLocked(r, app, execInFg);
return null;
} catch (TransactionTooLargeException e) {
throw e;
} catch (RemoteException e) {
Slog.w(TAG, "Exception when starting service " + r.shortName, e);
}
// If a dead object exception was thrown -- fall through to
// restart the application.
}
} else {
......
}
......
return null;
}
......
}
真正启动 Service 的方法是 realStartServiceLocked,接下来转入它。scheduleCreateService 方法调用参见《startService启动流程分析》一节,最后会调用 Service 的 onCreate 方法。
frameworks/base/services/core/java/com/android/server/am/ActiveServices.java
public final class ActiveServices {
......
private final void realStartServiceLocked(ServiceRecord r,
ProcessRecord app, boolean execInFg) throws RemoteException {
......
try {
......
// 最终会调用 Service 的 onCreate 方法
app.thread.scheduleCreateService(r, r.serviceInfo,
mAm.compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo),
app.repProcState);
......
} catch (DeadObjectException e) {
......
} finally {
......
}
// 接下来走到这里
requestServiceBindingsLocked(r, execInFg);
......
}
......
}
函数继续串行执行代码,就会走到 requestServiceBindingsLocked 方法。这个带有两个入参的函数,其实又调用了四个入参的 requestServiceBindingLocked (Binding没有带s)函数。
frameworks/base/services/core/java/com/android/server/am/ActiveServices.java
public final class ActiveServices {
......
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 {
if (r.app == null || r.app.thread == null) {
// 如果服务当前没有运行,还不能绑定。
return false;
}
if ((!i.requested || rebind) && i.apps.size() > 0) {
try {
bumpServiceExecutingLocked(r, execInFg, "bind");
r.app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
// 接下来安排绑定 Service
r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind,
r.app.repProcState);
if (!rebind) {
i.requested = true;
}
i.hasBound = true;
i.doRebind = false;
} catch (TransactionTooLargeException e) {
......
} catch (RemoteException e) {
......
}
}
return true;
}
......
}
下一步调用 scheduleBindService,首先获取一个 ApplicationThreadProxy 代理类对象,然后通过 Binder 机制远程调用 ApplicationThread scheduleBindService 方法。
frameworks/base/core/java/android/app/ApplicationThreadNative.java
class ApplicationThreadProxy implements IApplicationThread {
......
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();
}
......
}
在 ApplicationThread scheduleBindService 方法中调用了 sendMessage ,最终由 ActivityThread 中的 Looper 轮询 BIND_SERVICE 消息并调用 H 对象的 handleMessage 进行处理。
frameworks/base/core/java/android/app/ActivityThread.java
private class ApplicationThread extends ApplicationThreadNative {
......
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);
}
......
}
handleMessage 中根据 Message what 字段找到 BIND_SERVICE 消息,然后调用 ActivityThread handleBindService 进行处理。
frameworks/base/core/java/android/app/ActivityThread.java
private class H extends Handler {
......
public static final int BIND_SERVICE = 121;
......
public void handleMessage(Message msg) {
if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
switch (msg.what) {
......
case BIND_SERVICE:
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceBind");
handleBindService((BindServiceData)msg.obj);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
break;
......
}
}
......
}
在 handleBindService 方法中,ActivityManagerNative.getDefault() 实际上获取的是一个 ActivityManagerProxy 对象,然后通过 Binder 机制远程调用 ActivityManagerService publishService 方法。
frameworks/base/core/java/android/app/ActivityThread.java
public final class ActivityThread {
......
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);
// ②
ActivityManagerNative.getDefault().publishService(
data.token, data.intent, binder);
} else {
s.onRebind(data.intent);
ActivityManagerNative.getDefault().serviceDoneExecuting(
data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
}
ensureJitEnabled();
} catch (RemoteException ex) {
}
} catch (Exception e) {
if (!mInstrumentation.onException(s, e)) {
throw new RuntimeException(
"Unable to bind to service " + s
+ " with " + data.intent + ": " + e.toString(), e);
}
}
}
}
......
}
先看 ①,调用了 Service 的 onBind 方法。
再看在 ②,ActivityManagerNative 抽象类中 gDefault 是一个全局变量,并且它是单例的,它返回一个实现 IActivityManager 的 ActivityManagerProxy 对象。
frameworks/base/core/java/android/app/ActivityManagerNative.java
public abstract class ActivityManagerNative extends Binder implements IActivityManager
{ ......
/**
* 检索系统的默认/全局活动管理器。
*/
static public IActivityManager getDefault() {
return gDefault.get();
}
......
private static final Singleton<IActivityManager> gDefault = new Singleton<IActivityManager>() {
protected IActivityManager create() {
IBinder b = ServiceManager.getService("activity");
if (false) {
Log.v("ActivityManager", "default service binder = " + b);
}
IActivityManager am = asInterface(b);
if (false) {
Log.v("ActivityManager", "default service = " + am);
}
return am;
}
};
......
}
接着转向 ActivityManagerProxy 的 publishService 方法。ActivityManagerProxy 的 publishService 方法最终是调用其内部的一个 Binder 代理对象 mRemote 向 ActivityManagerService 发送一个类型为 PUBLISH_SERVICE_TRANSACTION 的进程间通信请求。
frameworks/base/core/java/android/app/ActivityManagerNative.java
class ActivityManagerProxy implements IActivityManager
{
......
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();
}
......
}
在 ActivityManagerService publishService 方法中,首先判断 intent 是否为空,并且其是否持有文件描述符。最后调用 ActiveServices publishServiceLocked 方法。
frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
public final class ActivityManagerService extends ActivityManagerNative
implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
......
public void publishService(IBinder token, Intent intent, IBinder service) {
// 拒绝可能泄露的文件描述符
if (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 publishServiceLocked 方法中,会调用 ConnectionRecord 的 conn 属性 connected 方法。conn 是一个实现了 IServiceConnection 接口的对象。在前面的分析中不难知道这个对象实际上是 InnerConnection 类型。
frameworks/base/services/core/java/com/android/server/am/ActiveServices.java
public final class ActiveServices {
......
void publishServiceLocked(ServiceRecord r, Intent intent, IBinder service) {
final long origId = Binder.clearCallingIdentity();
try {
if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "PUBLISHING " + r
+ " " + intent + ": " + service);
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 (!filter.equals(c.binding.intent.intent)) {
if (DEBUG_SERVICE) Slog.v(
TAG_SERVICE, "Not publishing to: " + c);
if (DEBUG_SERVICE) Slog.v(
TAG_SERVICE, "Bound intent: " + c.binding.intent.intent);
if (DEBUG_SERVICE) Slog.v(
TAG_SERVICE, "Published intent: " + intent);
continue;
}
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);
}
}
......
}
在 InnerConnection 对象中调用 connected 方法,实际上调用了外部类 ServiceDispatcher 的 connected 方法。在 ServiceDispatcher 的 connected 方法中接着又使用了 Handler 向其中 post 一个 Runnable 对象,我们知道这最终会调用 Runnable 对象的 run 方法,即执行 RunConnection 的 run 方法,我们传入的 mCommand 等于 0,因此会调用外部类的 doConnected 方法,在 ServiceDispatcher 的 doConnected 方法中最终会调用 onServiceConnected 方法。mConnection 是 ServiceConnection 类型对象,这是我们之前传入的,所以最后就会调用其 onServiceConnected 方法。
frameworks/base/core/java/android/app/LoadedApk.java
static final class ServiceDispatcher {
......
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);
}
}
}
......
public void connected(ComponentName name, IBinder service) {
if (mActivityThread != null) {
mActivityThread.post(new RunConnection(name, service, 0));
} else {
doConnected(name, service);
}
}
......
public void doConnected(ComponentName name, IBinder service) {
ServiceDispatcher.ConnectionInfo old;
ServiceDispatcher.ConnectionInfo info;
synchronized (this) {
if (mForgotten) {
// 我们在接收连接之前解除绑定;忽略接收到的任何连接。
return;
}
old = mActiveConnections.get(name);
if (old != null && old.binder == service) {
// 已经有这个了。
return;
}
if (service != null) {
// 一个新的服务正在连接…一切都准备好了。
mDied = false;
info = new ConnectionInfo();
info.binder = service;
info.deathMonitor = new DeathMonitor(name, service);
try {
service.linkToDeath(info.deathMonitor, 0);
mActiveConnections.put(name, info);
} catch (RemoteException e) {
// 这个服务在我们得到它之前就死了…什么都不要做。
mActiveConnections.remove(name);
return;
}
} else {
// 已命名的服务正在断开连接…清理。
mActiveConnections.remove(name);
}
if (old != null) {
old.binder.unlinkToDeath(old.deathMonitor, 0);
}
}
// 如果有一个旧的服务,它不是断开连接的。
if (old != null) {
mConnection.onServiceDisconnected(name);
}
// 如果有一个新服务,它现在是连接的。
if (service != null) {
mConnection.onServiceConnected(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;
}
......
}
老规矩,画一张时序图作为总结。