Android之bindService過程源碼解析

一 前言

前一篇介紹了startService啟動(dòng)過程,本篇接著介紹Service中另一種啟動(dòng)方式:bindService過程。bindService過程前一部分在startService中都會得到體現(xiàn),所以本文只介紹在同一個(gè)進(jìn)程中bindService的流程。即在上一篇的基礎(chǔ)上在AndroidManifest.xml中注冊MyService時(shí)不注冊為遠(yuǎn)程進(jìn)程:

 <service android:name=".MyService">
 </service>

然后可以MainActivity.java中通過如下方式即可以bindService:

public class MainActivity extends Activity implements OnClickListener { 
    ...
    MyService.MyBinder serverService;
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            serverService = ((MyService.MyBinder) service);
            serverService. startTask();  
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            serverService = null;
        }
    };
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
        Intent intent = new Intent(MainActivity.this, MyService.class);
        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
    }  
  ...
}

接著先給出bindService主流程的時(shí)序圖:


bindService過程分析.png

二 啟動(dòng)流程分析

在MainActivity的里onCreate方法中調(diào)用bindService(Intent service)方法時(shí),它實(shí)際上是調(diào)用ContextWrapper.bindService(Intent service),然后就從此展示分析。

步驟1.ContextWrapper.bindService
源碼位置:/frameworks/base/core/java/android/content/ContextWrapper.java

 @Override
    public boolean bindService(Intent service, ServiceConnection conn,
            int flags) {
        return mBase.bindService(service, conn, flags);
    }

這個(gè)過程與startService類似,mBase的對象類型是Context,它實(shí)際上指向了Context的實(shí)現(xiàn)類ContextImpl,所以該方法進(jìn)一步調(diào)用ContextImpl.bindService。
步驟2.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());
    }

ContextImpl的bindService方法內(nèi)部又調(diào)用了自己的startServiceCommon方法
步驟3.ContextImpl.bindServiceCommon
源碼位置:/frameworks/base/core/java/android/app/ContextImpl.java

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轉(zhuǎn)成Binder對象,也就是ServiceDispatcher.InnerConnection對象
            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.prepareToLeaveProcess(this);
            //接著通過AWS來完成Service的綁定過程
            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 e.rethrowFromSystemServer();
        }
    }

bindServiceCommon方法主要完成如下兩件事情:
1.把ServiceConnection轉(zhuǎn)成Binder對象,也就是ServiceDispatcher.InnerConnection對象,這個(gè)過程主要是因?yàn)榻壎ǚ?wù)的過程有可能是跨進(jìn)程的,因此需要借助Binder才能讓遠(yuǎn)程進(jìn)程回調(diào)onServiceConnected方法,而ServiceDispatcher.InnerConnection就充當(dāng)Binder這個(gè)角色。這個(gè)過程由LoadApk的getServiceDispatcher方法中完成的,看下源碼:

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();
        }
    }

這個(gè)方法中會首先查找ArrayMap的mServices中是否存在與當(dāng)前ServiceConnection相同的對象,如果不存在就創(chuàng)建一個(gè)ServiceDispatcher對象并放入mServices中以便復(fù)用。
2.接著通過AWS來完成Service的綁定過程
這個(gè)過程調(diào)用ActivityManagerNative.getDefault().bindService方法實(shí)現(xiàn),ActivityManagerNative.getDefault()前面兩篇文章已經(jīng)出現(xiàn)多次,會返回一個(gè)ActivityManagerService的遠(yuǎn)程接口,即ActivityManagerProxy接口,然后接著看ActivityManagerProxy.bindService()方法調(diào)用的源碼。
步驟4.ActivityManagerProxy.bindService
源碼位置:/frameworks/base/core/java/android/app/ActivityManagerNative.java的內(nèi)部類

 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;
    }

ActivityManagerProxy內(nèi)部通過Binder對象mRemote調(diào)用transact方法向ActivityManagerService發(fā)送一個(gè)BIND_SERVICE_TRANSACTION進(jìn)程間通信請求。這樣就把綁定Service的操作交給system_server進(jìn)程的ActivityManagerService處理
步驟5. 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);
        }
    }

mServices的類型是ActiveServices,ActiveServices是一個(gè)AMS的輔助類,管理Service類的啟動(dòng)、綁定和銷毀等,因此進(jìn)一步調(diào)用ActiveServices.bindServiceLocked()方法。
步驟6.ActiveServices.bindServiceLocked
源碼位置:
/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 {
      ...
      if ((flags&Context.BIND_AUTO_CREATE) != 0) {
                s.lastActivity = SystemClock.uptimeMillis();
                if (bringUpServiceLocked(s, service.getFlags(), callerFg, false,
                        permissionsReviewRequired) != null) {
                    return 0;
                }
            }

      ...
}

該方法中調(diào)用bringUpServiceLocked方法
步驟7.ActiveServices.bringUpServiceLocked
源碼位置:
/frameworks/base/services/core/java/com/android/server/am/ActiveServices.java

private String bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg,
            boolean whileRestarting, boolean permissionsReviewRequired)
            throws TransactionTooLargeException {
        //Slog.i(TAG, "Bring up service:");
        //r.dump("  ");

        if (r.app != null && r.app.thread != null) {
            sendServiceArgsLocked(r, execInFg, false);
            return null;
        }

        if (!whileRestarting && r.restartDelay > 0) {
            // If waiting for a restart, then do nothing.
            return null;
        }

        if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bringing up " + r + " " + r.intent);

        // We are now bringing the service up, so no longer in the
        // restarting state.
        if (mRestartingServices.remove(r)) {
            r.resetRestartCounter();
            clearRestartingIfNeededLocked(r);
        }

        // Make sure this service is no longer considered delayed, we are starting it now.
        if (r.delayed) {
            if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (bring up): " + r);
            getServiceMap(r.userId).mDelayedStartList.remove(r);
            r.delayed = false;
        }

        // Make sure that the user who owns this service is started.  If not,
        // we don't want to allow it to run.
        if (!mAm.mUserController.hasStartedUserState(r.userId)) {
            String msg = "Unable to launch app "
                    + r.appInfo.packageName + "/"
                    + r.appInfo.uid + " for service "
                    + r.intent.getIntent() + ": user " + r.userId + " is stopped";
            Slog.w(TAG, msg);
            bringDownServiceLocked(r);
            return msg;
        }

        // Service is now being launched, its package can't be stopped.
        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 {
            // If this service runs in an isolated process, then each time
            // we call startProcessLocked() we will get a new isolated
            // process, starting another process if we are currently waiting
            // for a previous process to come up.  To deal with this, we store
            // in the service any current isolated process it is running in or
            // waiting to have come up.
            app = r.isolatedProc;
        }

        // Not running -- get it started, and enqueue this service record
        // to be executed when the app comes up.
        if (app == null && !permissionsReviewRequired) {
            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;
            }
        }

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

        if (r.delayedStop) {
            // Oh and hey we've already been asked to stop!
            r.delayedStop = false;
            if (r.startRequested) {
                if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
                        "Applying delayed stop (in bring up): " + r);
                stopServiceLocked(r);
            }
        }

        return null;
    }

前言中舉的例子假設(shè)MySerivce是一個(gè)與MainActivity所在app屬于同一個(gè)進(jìn)程,因此,此時(shí)MySerivce所在進(jìn)程已啟動(dòng),會直接走realStartServiceLocked方法,
如果Service所在進(jìn)程未啟動(dòng),則會調(diào)用mAm.startProcessLocked方法,而這個(gè)過程在上一篇文章已經(jīng)跟蹤過代碼,對應(yīng)上一篇文章的步驟8-16,本篇就不重復(fù)分析這個(gè)過程。
步驟8.ActiveServices.realStartServiceLocked
源碼位置:
/frameworks/base/services/core/java/com/android/server/am/ActiveServices.java

private final void realStartServiceLocked(ServiceRecord r,
            ProcessRecord app, boolean execInFg) throws RemoteException {
        ...
        boolean created = false;
        try {
            if (LOG_SERVICE_START_STOP) {
                String nameTerm;
                int lastPeriod = r.shortName.lastIndexOf('.');
                nameTerm = lastPeriod >= 0 ? r.shortName.substring(lastPeriod) : r.shortName;
                EventLogTags.writeAmCreateService(
                        r.userId, System.identityHashCode(r), nameTerm, r.app.uid, r.app.pid);
            }
            synchronized (r.stats.getBatteryStats()) {
                r.stats.startLaunchedLocked();
            }
            mAm.notifyPackageUse(r.serviceInfo.packageName,
                                 PackageManager.NOTIFY_PACKAGE_USE_SERVICE);
            app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
           //1.創(chuàng)建Service
            app.thread.scheduleCreateService(r, r.serviceInfo,
                    mAm.compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo),
                    app.repProcState);
            r.postNotification();
            created = true;
        } catch (DeadObjectException e) {
            Slog.w(TAG, "Application dead when creating service " + r);
            mAm.appDiedLocked(app);
            throw e;
        } finally {
            if (!created) {
                // Keep the executeNesting count accurate.
                final boolean inDestroying = mDestroyingServices.contains(r);
                serviceDoneExecutingLocked(r, inDestroying, inDestroying);

                // Cleanup.
                if (newService) {
                    app.services.remove(r);
                    r.app = null;
                }

                // Retry.
                if (!inDestroying) {
                    scheduleServiceRestartLocked(r, false);
                }
            }
        }

        if (r.whitelistManager) {
            app.whitelistManager = true;
        }
        //2.請求綁定Service
        requestServiceBindingsLocked(r, execInFg);

        updateServiceClientActivitiesLocked(app, null, true);
      ...
}

該方法內(nèi)部要完成如下兩件事情:
1.創(chuàng)建Service,這個(gè)過程與上一篇文章startService的步驟17-21對應(yīng),本文也就不再分析。
2.請求綁定Service,本文接著重點(diǎn)分析Service創(chuàng)建成功后的綁定的流程。

步驟9-步驟14與上一篇startService文章的步驟17-21類似,可自行查看其過程,接著看requestServiceBindingsLocked請求綁定Service過程
步驟15.ActiveServices.requestServiceBindingsLocked
源碼位置:
/frameworks/base/services/core/java/com/android/server/am/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 {
        if (r.app == null || r.app.thread == null) {
            // If service is not currently running, can't yet bind.
            return false;
        }
        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 (TransactionTooLargeException e) {
                // Keep the executeNesting count accurate.
                if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while binding " + r, e);
                final boolean inDestroying = mDestroyingServices.contains(r);
                serviceDoneExecutingLocked(r, inDestroying, inDestroying);
                throw e;
            } catch (RemoteException e) {
                if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while binding " + r);
                // Keep the executeNesting count accurate.
                final boolean inDestroying = mDestroyingServices.contains(r);
                serviceDoneExecutingLocked(r, inDestroying, inDestroying);
                return false;
            }
        }
        return true;
    }

可知,requestServiceBindingLocked內(nèi)部又通過r.app.thread調(diào)用scheduleBindService方法,而app.thread這個(gè)對象在前兩篇文章也出現(xiàn)多次,其在ApplicationThreadNative實(shí)現(xiàn)初始化后返回ApplicationThreadProxy對象。接著看ApplicationThreadProxy.scheduleBindService源碼:
步驟16. ApplicationThreadProxy.scheduleBindService
源碼位置:frameworks/base/core/java/android/app/ApplicationThreadNative.java的內(nèi)部類

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();
    }

ApplicationThreadProxy內(nèi)部通過Binder對象mRemote調(diào)用transact方法向ApplicationThread發(fā)送一個(gè)SCHEDULE_BIND_SERVICE_TRANSACTION進(jìn)程間通信請求。這樣就把綁定Service的操作交給system_server進(jìn)程的ApplicationThread處理
步驟17.ActivityThread$ApplicationThread.scheduleBindService
源碼位置:/frameworks/base/core/java/android/app/ActivityThread.java的內(nèi)部類

        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);
        }

步驟18.ActivityThread.sendMessage
源碼位置:
/frameworks/base/core/java/android/app/ActivityThread.java

private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
        if (DEBUG_MESSAGES) Slog.v(
            TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
            + ": " + arg1 + " / " + obj);
        Message msg = Message.obtain();
        msg.what = what;
        msg.obj = obj;
        msg.arg1 = arg1;
        msg.arg2 = arg2;
        if (async) {
            msg.setAsynchronous(true);
        }
        mH.sendMessage(msg);
    }

mH是一個(gè)H對象,類H是ActivityThread的內(nèi)部類,并繼承了Handler。接著在handleMessage方法中看BIND_SERVICE類型消息的處理
步驟19.ActivityThread$H.handleMessage
源碼位置:
/frameworks/base/core/java/android/app/ActivityThread.java內(nèi)部類H

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;
      ...
}

綁定過程又調(diào)用ActivityThread.handleBindService方法來實(shí)現(xiàn)
步驟20.ActivityThread.handleBindService
源碼位置:
/frameworks/base/core/java/android/app/ActivityThread.java

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) {
                    throw ex.rethrowFromSystemServer();
                }
            } catch (Exception e) {
                if (!mInstrumentation.onException(s, e)) {
                    throw new RuntimeException(
                            "Unable to bind to service " + s
                            + " with " + data.intent + ": " + e.toString(), e);
                }
            }
        }
    }

首先方法會先判斷Service是否重復(fù)綁定,如果不是rebind,Service會執(zhí)行Service.onBind方法即步驟21,然后再告訴AMS.publishService即步驟22
步驟21.Service.onBind
即回調(diào)執(zhí)行MyService中的onBind方法

public class MyService extends Service {
    private Binder mBinder = new MyBinder();
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    class MyBinder extends Binder {
        public void startTask() {
            // 執(zhí)行具體的任務(wù)
        }
    }
}

步驟22. ActivityManagerProxy.publishService
源碼位置:
/frameworks/base/core/java/android/app/ActivityManagerNative.java的內(nèi)部類

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();
    }

ActivityManagerProxy內(nèi)部通過Binder對象mRemote調(diào)用transact方法向ActivityManagerService發(fā)送一個(gè)PUBLISH_SERVICE_TRANSACTION進(jìn)程間通信請求。這樣就把綁定Service的操作交給system_server進(jìn)程的ActivityManagerService處理
步驟23. ActivityManagerService.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);
        }
    }

mServices的類型是ActiveServices,因此進(jìn)一步調(diào)用ActiveServices.publishServiceLocked()方法。
步驟24. ActiveServices.publishServiceLocked
源碼位置:
/frameworks/base/services/core/java/com/android/server/am/ActiveServices.java

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);
        }
    }

代碼比較長,其內(nèi)部核心調(diào)用其實(shí)是 c.conn.connected(r.name, service);c的類型是ConnectionRecord,c.conn的類型就是步驟3中討論的ServiceDispatcher.InnerConnection,接著就看看InnerConnection內(nèi)部的調(diào)用情況。
步驟25. LoadedApk$ServiceDispatcher$InnerConnection.connected
源碼位置:
/frameworks/base/core/java/android/app/LoadedApk.java

LoadedApk.ServiceDispatcher sd = mDispatcher.get();
                if (sd != null) {
                    sd.connected(name, service);
                }

方法內(nèi)部又調(diào)用了ServiceDispatcher.connected
步驟26. LoadedApk$ServiceDispatcher.connected
源碼位置:
/frameworks/base/core/java/android/app/LoadedApk.java

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

mActivityThread是ActivityThread中的H,所以之后會通過H這個(gè)handler post一個(gè)Connection Runnable:

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;
        }

其內(nèi)部調(diào)用了ServiceDispatcher.doConnected方法。
步驟27. LoadedApk$ServiceDispatcher.doConnected
源碼位置:
/frameworks/base/core/java/android/app/LoadedApk.java

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

            synchronized (this) {
                if (mForgotten) {
                    // We unbound before receiving the connection; ignore
                    // any connection received.
                    return;
                }
                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) {
                        // This service was dead before we got it...  just
                        // don't do anything with it.
                        mActiveConnections.remove(name);
                        return;
                    }

                } else {
                    // The named service is being disconnected... clean up.
                    mActiveConnections.remove(name);
                }

                if (old != null) {
                    old.binder.unlinkToDeath(old.deathMonitor, 0);
                }
            }

            // If there was an old service, it is now disconnected.
            if (old != null) {
                mConnection.onServiceDisconnected(name);
            }
            // If there is a new service, it is now connected.
            if (service != null) {
                mConnection.onServiceConnected(name, service);
            }
        }

ServiceDispatcher在步驟3時(shí)保存了客戶端的ServiceConnection對象,因此,最終在doConnected方法真正執(zhí)行了ServiceConnection中的onServiceConnected方法,完成最終綁定的過程,整個(gè)bindService過程就完成了。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容