Android 8.1 中 bindService 是如何一步步拿到 Binder 的

1 阅读1分钟

1. 引言

在 Android 开发中,bindService 是获取系统服务(如 ActivityManagerService、PackageManagerService)或跨进程服务能力的核心入口。很多同学会背「bindService 最终会拿到一个 IBinder 代理对象」,但具体是怎么一步步拿到的,往往说不清楚。

本文以 Android 8.1(API 27,Oreo) 源码为基准,沿着 bindService 的调用链,从应用进程一路追到 system_server,把「Binder 对象是怎么被创建、怎么被传回、怎么被包装成代理」这条链路完整走一遍。

说明:不同 Android 版本在细节上有差异(例如 8.0 之后 ActivityManager 的 AIDL 接口、LoadedApk 的缓存策略等),本文只针对 8.1 的代码路径。

2. 整体链路概览

先给出一张全局图,后面再逐段展开。

flowchart TD
  A["ContextImpl.bindService()"] --> B["LoadedApk.getServiceDispatcher()"]
  B --> C["ServiceDispatcher 缓存/新建"]
  C --> D["ActivityManagerService.bindService()"]
  D --> E["ActiveServices.bindServiceLocked()"]
  E --> F["retrieveServiceLocked() 解析 ServiceRecord"]
  F --> G["bringUpServiceLocked() 启动目标进程"]
  G --> H["realStartServiceLocked() -> scheduleCreateService()"]
  H --> I["目标进程 ActivityThread.handleCreateService()"]
  I --> J["Service.onBind() 返回 IBinder"]
  J --> K["publishService() 回传 Binder"]
  K --> L["AMS.publishService() -> IServiceConnection.connected()"]
  L --> M["LoadedApk.ServiceDispatcher.InnerConnection.connected()"]
  M --> N["runOnServiceConnected() -> ServiceConnection.onServiceConnected()"]

关键点在于:bindService 本身并不直接返回 Binder,而是通过一次「启动服务 → 服务端 onBind 返回 Binder → 通过 Binder 驱动回传 → 客户端回调 onServiceConnected」的异步过程拿到 IBinder。

3. 客户端入口:ContextImpl.bindService

应用里调用 bindService,实际执行的是 ContextImpl.bindService:

// frameworks/base/core/java/android/app/ContextImpl.java
@Override
public boolean bindService(Intent service, ServiceConnection conn, int flags) {
    warnIfCallingFromSystemProcess();
    return bindServiceCommon(service, conn, flags, mMainThread.getHandler(),
            Process.myUserHandle());
}

bindServiceCommon 做了三件关键的事:

  1. 通过 LoadedApk 把 ServiceConnection 包装成 IServiceConnection;
  2. 把 Intent 解析成 ComponentName;
  3. 调用 ActivityManager.getService().bindService(...),即跨进程调用 AMS。
private boolean bindServiceCommon(Intent service, ServiceConnection conn, int flags,
        Handler handler, UserHandle user) {
    IServiceConnection sd;
    if (conn == null) {
        throw new IllegalArgumentException("connection is null");
    }
    if (mPackageInfo != null) {
        // 关键:把 ServiceConnection 包装成 Binder 通信对象
        sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(), handler, 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.setComponent(service.resolveActivity(mPackageManager));
        int res = ActivityManager.getService().bindService(
            mMainThread.getApplicationThread(), getActivityToken(), service,
            service.resolveTypeIfNeeded(getContentResolver()),
            sd, flags, getOpPackageName(), user.getIdentifier());
        return res != 0;
    } catch (RemoteException e) {
        throw e.rethrowFromSystemServer();
    }
}

注意 ActivityManager.getService() 返回的是 IActivityManager 的 Binder 代理,这一步本身就是一次 Binder 调用,但此时我们还没有拿到目标服务的 Binder,只是把「我要绑定谁」告诉 AMS。

4. ServiceConnection 的包装:LoadedApk.getServiceDispatcher

getServiceDispatcher 是客户端侧非常关键的一步,它把普通的 ServiceConnection 接口包装成一个 IServiceConnection(Binder 对象),这样服务端才能回调客户端。

// frameworks/base/core/java/android/app/LoadedApk.java
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<>();
                mServices.put(context, map);
            }
            map.put(c, sd);
        } else {
            sd.validate(context, handler);
        }
        return sd.getIServiceConnection();
    }
}

ServiceDispatcher 内部持有一个 InnerConnection,它继承自 IServiceConnection.Stub,也就是一个真正的 Binder 服务端对象:

static final class ServiceDispatcher {
    private final ServiceDispatcher.InnerConnection mIServiceConnection;
    private final ServiceConnection mConnection;
    private final Handler mActivityThread;
    // ...

    ServiceDispatcher(ServiceConnection conn, Context context, Handler activityThread, int flags) {
        mIServiceConnection = new InnerConnection(this);
        mConnection = conn;
        mActivityThread = activityThread;
        // ...
    }

    IServiceConnection getIServiceConnection() {
        return mIServiceConnection;
    }

    private static class InnerConnection extends IServiceConnection.Stub {
        final WeakReference<LoadedApk.ServiceDispatcher> mDispatcher;

        InnerConnection(LoadedApk.ServiceDispatcher sd) {
            mDispatcher = new WeakReference<LoadedApk.ServiceDispatcher>(sd);
        }

        @Override
        public void connected(ComponentName name, IBinder service, boolean dead)
                throws RemoteException {
            LoadedApk.ServiceDispatcher sd = mDispatcher.get();
            if (sd != null) {
                sd.connected(name, service, dead);
            }
        }
    }
}

到这里,客户端已经准备好了一个「接收 Binder 的回调通道」。这个 InnerConnection 会被作为参数传给 AMS,AMS 在服务绑定成功后通过它把目标服务的 IBinder 回传回来。

5. 进入 system_server:AMS.bindService

ActivityManager.getService().bindService(...) 通过 Binder 驱动进入 system_server 进程,最终落到 ActivityManagerService.bindService:

// frameworks/base/services/core/java/com/android/server/am/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");


    // Refuse possible leaked file descriptors
    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);
    }
}

真正的逻辑在 ActiveServices.bindServiceLocked。

6. ActiveServices.bindServiceLocked:解析与启动

bindServiceLocked 是绑定流程的核心,主要做这几件事:

  1. 通过 retrieveServiceLocked 解析出 ServiceRecord(服务在 AMS 中的内部表示);
  2. 检查服务是否已启动,未启动则 bringUpServiceLocked 拉起进程;
  3. 把 IServiceConnection 记录到 ServiceRecord 的 bindings 列表中;
  4. 如果服务已经绑定过(app != null && app.thread != null),直接调用 requestServiceBindingLocked 触发 onBind。

简化后的关键代码:

// frameworks/base/services/core/java/com/android/server/am/ActiveServices.java
int bindServiceLocked(IApplicationThread caller, IBinder token, Intent service,
        String resolvedType, final IServiceConnection connection, int flags,
        String callingPackage, final int userId) throws TransactionTooLargeException {
    final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
    // ...

    ActivityRecord activity = null;
    if (token != null) {
        activity = ActivityRecord.isInStackLocked(token);
        // ...
    }
    // ...

    ServiceLookupResult res =
        retrieveServiceLocked(service, resolvedType, callingPackage,
                Binder.getCallingPid(), Binder.getCallingUid(), userId, true, callerFg, false);
    if (res == null) {
        return 0;
    }
    if (res.record == null) {
        return -1;
    }
    ServiceRecord s = res.record;
    
    // ...

    try {
        if (unscheduleServiceRestartLocked(s, callerApp, false, false)) {
            // ...
        }

        // ...

        if (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) {
                // ...
            }
           
            // 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) {
            requestServiceBindingLocked(s, b.intent, callerFg, false);
        }
    } finally {
        Binder.restoreCallingIdentity(origId);
    }
    return 1;
}

这里有两个分支值得注意:

  • 服务已绑定过:b.intent.received == true,说明 onBind 已经返回过 Binder,直接调用 c.conn.connected(s.name, b.intent.binder, false) 把缓存的 Binder 回传,无需再走一次 onBind。
  • 首次绑定:调用 requestServiceBindingLocked,它会通过 IApplicationThread.scheduleBindService 通知目标进程执行 onBind。

7. 拉起服务进程:bringUpServiceLocked

如果目标服务所在进程还没启动,bringUpServiceLocked 会负责拉起进程:

private String bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg,
        boolean whileRestarting, boolean permissionsReviewRequired)
        throws TransactionTooLargeException {
    // ...
    final String procName = r.processName;
    ProcessRecord app;

    if (!isolated) {
        app = mAm.getProcessRecordLocked(procName, r.appInfo.uid, false);
        if (app != null && app.thread != null) {
            try {
                app.addPackage(r.appInfo.packageName, r.appInfo.versionCode, mAm.mProcessStats);
                realStartServiceLocked(r, app, execInFg);
                return null;
            } catch (RemoteException e) {
                // ...
            }
        }
    }

    // 进程不存在,先启动进程
    if (app == null && !permissionsReviewRequired) {
        if ((app = mAm.startProcessLocked(procName, r.appInfo, true, intentFlags,
                "service", r.name, false, isolated, false)) == null) {
            // ...
        }
    }

    if (!mPendingServices.contains(r)) {
        mPendingServices.add(r);
    }
    return null;
}

进程启动后,ActivityThread 会回调 AMS.attachApplication,AMS 在 attachApplicationLocked 中遍历 mPendingServices,对每个待启动服务调用 realStartServiceLocked。

8. 触发 onBind:realStartServiceLocked

realStartServiceLocked 通过 IApplicationThread.scheduleCreateService 通知目标进程创建 Service 实例:

private final void realStartServiceLocked(ServiceRecord r,
        ProcessRecord app, boolean execInFg) throws RemoteException {
    // ...
    try {
        // ...
        app.thread.scheduleCreateService(r, r.serviceInfo,
                mAm.compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo),
                app.repProcState);
        r.postNotification();
        created = true;
    } catch (DeadObjectException e) {
        // ...
    } finally {
        // ...
    }

    // 关键:创建完成后请求绑定
    requestServiceBindingsLocked(r, execInFg);
    // ...
}

requestServiceBindingsLocked 会遍历该服务的所有 bindings,对每个尚未请求绑定的连接调用 requestServiceBindingLocked:

private final boolean requestServiceBindingLocked(ServiceRecord r, IntentBindRecord i,
        boolean execInFg, boolean rebind) throws TransactionTooLargeException {
    if ((!i.requested || rebind) && i.apps.size() > 0) {
        try {
            bumpServiceExecutingLocked(r, execInFg, "bind");
            r.app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_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 (RemoteException e) {
            // ...
        }
    }
    return true;
}

9. 服务端执行 onBind:ActivityThread.handleBindService

目标进程收到 scheduleBindService 后,在 ActivityThread 的 handleBindService 中执行:

// frameworks/base/core/java/android/app/ActivityThread.java
private void handleBindService(BindServiceData data) {
    Service s = mServices.get(data.token);
    if (s != null) {
        try {
            data.intent.setExtrasClassLoader(s.getClassLoader());
            data.intent.prepareToEnterProcess();
            try {
                if (!data.rebind) {
                    IBinder binder = s.onBind(data.intent);
                    ActivityManager.getService().publishService(
                            data.token, data.intent, binder);
                } else {
                    s.onRebind(data.intent);
                    ActivityManager.getService().publishService(
                            data.token, data.intent, null);
                }
            } catch (RemoteException ex) {
                throw ex.rethrowFromSystemServer();
            }
        } finally {
            // ...
        }
    }
}

这里是 Binder 真正诞生的地方:s.onBind(data.intent) 返回的 IBinder 就是服务端暴露给客户端的 Binder 对象(通常是 AIDL 生成的 Stub 实例,或者 Messenger 内部的 Binder)。

随后通过 ActivityManager.getService().publishService(...) 把这个 IBinder 回传给 AMS。

10. 回传 Binder:AMS.publishService

// frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
public void publishService(IBinder token, Intent intent, IBinder service) {
    // Refuse possible leaked file descriptors
    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 会把 IBinder 保存到 IntentBindRecord.binder,并遍历所有等待该服务的连接,逐个回调 connected:

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 (!filter.equals(c.binding.intent.intent)) {
                            continue;
                        }
                        try {
                            c.conn.connected(r.name, service, false);
                        } catch (Exception e) {
                            // ...
                        }
                    }
                }
            }
        }
    } finally {
        Binder.restoreCallingIdentity(origId);
    }
}

注意 c.conn 就是客户端传过来的 IServiceConnection(即 InnerConnection 的 Binder 代理),connected(r.name, service, false) 是一次跨进程调用,service 这个 IBinder 会作为 Binder 参数被驱动传递回客户端进程。

11. 客户端回调:ServiceDispatcher.connected

回到客户端进程,InnerConnection.connected 被调用:

@Override
public void connected(ComponentName name, IBinder service, boolean dead)
        throws RemoteException {
    LoadedApk.ServiceDispatcher sd = mDispatcher.get();
    if (sd != null) {
        sd.connected(name, service, dead);
    }
}

ServiceDispatcher.connected 会切换到主线程(或指定的 Handler)执行 doConnected:

public void connected(ComponentName name, IBinder service, boolean dead) {
    if (mActivityThread != null) {
        mActivityThread.post(new RunConnection(name, service, 0, dead));
    } else {
        doConnected(name, service, dead);
    }
}

private void doConnected(ComponentName name, IBinder service, boolean dead) {
    ServiceDispatcher.ConnectionInfo old;
    ServiceDispatcher.ConnectionInfo info;

    synchronized (this) {
        // ...
        old = mActiveConnections.get(name);
        if (old != null && old.binder == service) {
            // Huh, already have this one.  Oh well!
            return;
        }

        if (service != null) {
            // A new service is being connected... set it all up.
            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) {
                // ...
            }
        } else {
            mActiveConnections.remove(name);
        }
    }

    if (service != null) {
        mConnection.onServiceConnected(name, service);
    } else {
        mConnection.onServiceDisconnected(name);
    }
}

最终,应用里实现的 ServiceConnection.onServiceConnected(ComponentName name, IBinder service) 被调用,这个 service 参数就是目标服务返回的 Binder 代理对象。

12. 完整时序图

把上面的流程串起来:

sequenceDiagram
    participant App as &#34;客户端进程&#34;
    participant AMS as &#34;system_server (AMS)&#34;
    participant Svc as &#34;服务端进程&#34;

    App->>App: ContextImpl.bindService()
    App->>App: LoadedApk.getServiceDispatcher() 创建 InnerConnection
    App->>AMS: IActivityManager.bindService(sd, intent)
    AMS->>AMS: ActiveServices.bindServiceLocked()
    AMS->>AMS: retrieveServiceLocked() 得到 ServiceRecord
    alt 服务进程未启动
        AMS->>Svc: startProcessLocked() 拉起进程
        Svc->>AMS: attachApplication()
        AMS->>Svc: scheduleCreateService()
        Svc->>Svc: handleCreateService() 创建 Service 实例
    end
    AMS->>Svc: scheduleBindService()
    Svc->>Svc: handleBindService() ->> Service.onBind()
    Svc->>AMS: publishService(token, intent, binder)
    AMS->>AMS: publishServiceLocked() 保存 binder
    AMS->>App: IServiceConnection.connected(name, binder)
    App->>App: ServiceDispatcher.doConnected()
    App->>App: ServiceConnection.onServiceConnected(name, binder)

13. 几个容易踩坑的细节

13.1 Binder 是「代理」还是「实体」

onServiceConnected 拿到的 IBinder 在客户端进程里是 BinderProxy(Java 层),它持有内核 Binder 驱动的 handle,通过 transact 与内核通信。只有在服务端进程里,它才是 Binder(BBinder)实体。所以客户端拿到的永远是代理,不能直接强转成服务端的 Stub 实现类。

13.2 为什么 onBind 只调用一次

IntentBindRecord 会缓存 binder 和 received 标志。同一个 Intent(FilterComparison 相等)再次绑定时,只要 b.received == true,AMS 直接复用缓存的 binder 回调 connected,不会再次触发 onBind。这也是为什么多个客户端绑定同一个服务时,服务端 onBind 通常只执行一次。

13.3 绑定与启动的区别

  • startService 走 startServiceLocked,只保证服务被创建并执行 onStartCommand,不关心 onBind。
  • bindService 走 bindServiceLocked,核心是拿到 onBind 返回的 IBinder。
  • 两者可以共存,BIND_AUTO_CREATE 表示绑定同时自动创建服务。

13.4 死亡通知

doConnected 中调用了 service.linkToDeath(info.deathMonitor, 0),当服务端进程死亡时,客户端会收到 binderDied 回调,进而触发 onServiceDisconnected。这是 Binder 机制提供的进程存活感知能力。

14. 总结

把 Android 8.1 中 bindService 拿到 Binder 的过程浓缩成一句话:

客户端把 ServiceConnection 包装成 IServiceConnection(Binder 对象)传给 AMS;AMS 解析 ServiceRecord、必要时拉起服务进程并调度 onBind;服务端 onBind 返回 IBinder 后通过 publishService 回传 AMS;AMS 再通过 IServiceConnection.connected 把该 IBinder 跨进程回传给客户端,最终在 onServiceConnected 中交付给应用。

整条链路涉及 两次跨进程回调(客户端 → AMS,AMS → 服务端,服务端 → AMS,AMS → 客户端,严格说是四次 Binder 调用),理解这条链路,对排查「绑定超时」「onServiceConnected 不回调」「Binder 代理失效」等问题非常有帮助。