Android之bindService過程源碼解析

一 前言

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

 <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主流程的時序圖:


bindService過程分析.png

二 啟動流程分析

在MainActivity的里onCreate方法中調(diào)用bindService(Intent service)方法時饭冬,它實際上是調(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);
    }

這個過程與startService類似昌抠,mBase的對象類型是Context,它實際上指向了Context的實現(xiàn)類ContextImpl鲁僚,所以該方法進一步調(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對象侨艾,這個過程主要是因為綁定服務的過程有可能是跨進程的,因此需要借助Binder才能讓遠程進程回調(diào)onServiceConnected方法倦淀,而ServiceDispatcher.InnerConnection就充當Binder這個角色蒋畜。這個過程由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();
        }
    }

這個方法中會首先查找ArrayMap的mServices中是否存在與當前ServiceConnection相同的對象撞叽,如果不存在就創(chuàng)建一個ServiceDispatcher對象并放入mServices中以便復用。
2.接著通過AWS來完成Service的綁定過程
這個過程調(diào)用ActivityManagerNative.getDefault().bindService方法實現(xiàn)插龄,ActivityManagerNative.getDefault()前面兩篇文章已經(jīng)出現(xiàn)多次愿棋,會返回一個ActivityManagerService的遠程接口,即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ā)送一個BIND_SERVICE_TRANSACTION進程間通信請求。這樣就把綁定Service的操作交給system_server進程的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是一個AMS的輔助類甘邀,管理Service類的啟動琅攘、綁定和銷毀等,因此進一步調(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;
    }

前言中舉的例子假設MySerivce是一個與MainActivity所在app屬于同一個進程坞琴,因此,此時MySerivce所在進程已啟動逗抑,會直接走realStartServiceLocked方法剧辐,
如果Service所在進程未啟動,則會調(diào)用mAm.startProcessLocked方法邮府,而這個過程在上一篇文章已經(jīng)跟蹤過代碼荧关,對應上一篇文章的步驟8-16,本篇就不重復分析這個過程褂傀。
步驟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忍啤,這個過程與上一篇文章startService的步驟17-21對應,本文也就不再分析仙辟。
2.請求綁定Service檀轨,本文接著重點分析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這個對象在前兩篇文章也出現(xiàn)多次讹挎,其在ApplicationThreadNative實現(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ā)送一個SCHEDULE_BIND_SERVICE_TRANSACTION進程間通信請求吆玖。這樣就把綁定Service的操作交給system_server進程的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是一個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方法來實現(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是否重復綁定怜奖,如果不是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í)行具體的任務
        }
    }
}

步驟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ā)送一個PUBLISH_SERVICE_TRANSACTION進程間通信請求歪玲。這樣就把綁定Service的操作交給system_server進程的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,因此進一步調(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)用其實是 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這個handler post一個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時保存了客戶端的ServiceConnection對象短条,因此导匣,最終在doConnected方法真正執(zhí)行了ServiceConnection中的onServiceConnected方法,完成最終綁定的過程茸时,整個bindService過程就完成了贡定。

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市屹蚊,隨后出現(xiàn)的幾起案子厕氨,更是在濱河造成了極大的恐慌,老刑警劉巖汹粤,帶你破解...
    沈念sama閱讀 221,820評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件命斧,死亡現(xiàn)場離奇詭異,居然都是意外死亡嘱兼,警方通過查閱死者的電腦和手機国葬,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,648評論 3 399
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來芹壕,“玉大人汇四,你說我怎么就攤上這事√哂浚” “怎么了通孽?”我有些...
    開封第一講書人閱讀 168,324評論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長睁壁。 經(jīng)常有香客問我背苦,道長,這世上最難降的妖魔是什么潘明? 我笑而不...
    開封第一講書人閱讀 59,714評論 1 297
  • 正文 為了忘掉前任行剂,我火速辦了婚禮,結果婚禮上钳降,老公的妹妹穿的比我還像新娘厚宰。我一直安慰自己,他們只是感情好遂填,可當我...
    茶點故事閱讀 68,724評論 6 397
  • 文/花漫 我一把揭開白布铲觉。 她就那樣靜靜地躺著,像睡著了一般城菊。 火紅的嫁衣襯著肌膚如雪备燃。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,328評論 1 310
  • 那天凌唬,我揣著相機與錄音,去河邊找鬼。 笑死客税,一個胖子當著我的面吹牛况褪,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播更耻,決...
    沈念sama閱讀 40,897評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼测垛,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了秧均?” 一聲冷哼從身側響起食侮,我...
    開封第一講書人閱讀 39,804評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎目胡,沒想到半個月后锯七,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,345評論 1 318
  • 正文 獨居荒郊野嶺守林人離奇死亡誉己,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,431評論 3 340
  • 正文 我和宋清朗相戀三年眉尸,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片巨双。...
    茶點故事閱讀 40,561評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡噪猾,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出筑累,到底是詐尸還是另有隱情袱蜡,我是刑警寧澤,帶...
    沈念sama閱讀 36,238評論 5 350
  • 正文 年R本政府宣布慢宗,位于F島的核電站坪蚁,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏婆廊。R本人自食惡果不足惜迅细,卻給世界環(huán)境...
    茶點故事閱讀 41,928評論 3 334
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望淘邻。 院中可真熱鬧茵典,春花似錦、人聲如沸宾舅。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,417評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽筹我。三九已至扶平,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間蔬蕊,已是汗流浹背结澄。 一陣腳步聲響...
    開封第一講書人閱讀 33,528評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人麻献。 一個月前我還...
    沈念sama閱讀 48,983評論 3 376
  • 正文 我出身青樓们妥,卻偏偏與公主長得像,于是被迫代替她去往敵國和親勉吻。 傳聞我的和親對象是個殘疾皇子监婶,可洞房花燭夜當晚...
    茶點故事閱讀 45,573評論 2 359

推薦閱讀更多精彩內(nèi)容