Service流程源碼分析(二) bindService

前面startService流程源碼分析介紹了startService的啓動流程,我們這一節來說說Service的綁定流程(基於Android10源碼)。

  • Service主要處理一些不與用戶交互的耗時任務,比如I/O操作。Service分爲兩種,一種是通過startService來啓動,另外一種是通過bindService的形式來啓動一個Service。本篇主要介紹bindService啓動流程源碼分析
  • bindServicestartService的結構很相似,兩者可以比較着研究。

bindService的啓動流程源碼分析

  • 一般我們綁定Service都是在一個Activity中開始的,我們就從這裏開始分析。但是我們在Activity中並沒有發現bindService方法,而是在它的父類ContextWrapper中找到了這個方法,源碼如下:
    @Override
    public boolean bindService(Intent service, ServiceConnection conn,
            int flags) {
        return mBase.bindService(service, conn, flags);
    }
    
  • 這裏的mBaseAndroid深入理解Context一文中已經詳細介紹了它的來歷,這裏其實是一種橋接模式,mBase其實就是真正實現了Context的ContextImpl,這裏就不詳細敘述了。那麼我們就直接看ContextImpl中的bindService
    @Override
    public boolean bindService(Intent service, ServiceConnection conn, int flags) {
        warnIfCallingFromSystemProcess();
        //-----1-----
        return bindServiceCommon(service, conn, flags, null, mMainThread.getHandler(), null,
                getUser());
    }
    
    private boolean bindServiceCommon(Intent service, ServiceConnection conn, int flags,
            String instanceName, Handler handler, Executor executor, UserHandle user) {
        // Keep this in sync with DevicePolicyManager.bindDeviceAdminServiceAsUser.
        IServiceConnection sd;
        if (conn == null) {
            throw new IllegalArgumentException("connection is null");
        }
        if (handler != null && executor != null) {
            throw new IllegalArgumentException("Handler and Executor both supplied");
        }
        if (mPackageInfo != null) {
            if (executor != null) {
                sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(), executor, flags);
            } else {
            	//-----2-----
                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);
            //-----3-----
            int res = ActivityManager.getService().bindIsolatedServicebins(
                mMainThread.getApplicationThread(), getActivityToken(), service,
                service.resolveTypeIfNeeded(getContentResolver()),
                sd, flags, instanceName, 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();
        }
    }
    
  • 在註釋1處我們發現調用了bindServiceCommon
  • 在註釋2處將客戶端傳進去的ServiceConnection轉換爲了IServiceConnection, 它是一個Binder, 之所以這麼做是因爲服務綁定是跨進程的,這個ServiceConnection不能進行進程間的通信,得找到一個能進行進程間通信的Binder對象來回調ServiceConnection中的方法,而ServiceDispatcher.InnerConnection就是這樣的一個角色,它繼承了IServiceConnection.stubServiceDispatcher內部持有InnerConnectionServiceConnection, 這樣的話在需要的時候就會通過InnerConnection調取ServiceConnection中的方法達到目的。
  • 獲取ServiceDispatcher的源碼如下:
    private final ArrayMap<Context, ArrayMap<ServiceConnection, LoadedApk.ServiceDispatcher>> mServices = new ArrayMap<>();	
        
    @UnsupportedAppUsage
    public final IServiceConnection getServiceDispatcher(ServiceConnection c,
            Context context, Handler handler, int flags) {
        return getServiceDispatcherCommon(c, context, handler, null, flags);
    }
    
    private IServiceConnection getServiceDispatcherCommon(ServiceConnection c,
            Context context, Handler handler, Executor executor, int flags) {
        synchronized (mServices) {
            LoadedApk.ServiceDispatcher sd = null;
            ArrayMap<ServiceConnection, LoadedApk.ServiceDispatcher> map = mServices.get(context);
            if (map != null) {
                if (DEBUG) Slog.d(TAG, "Returning existing dispatcher " + sd + " for conn " + c);
                sd = map.get(c);
            }
            if (sd == null) {
                if (executor != null) {
                    sd = new ServiceDispatcher(c, context, executor, flags);
                } else {
                    sd = new ServiceDispatcher(c, context, handler, flags);
                }
                if (DEBUG) Slog.d(TAG, "Creating new dispatcher " + sd + " for conn " + c);
                if (map == null) {
                    map = new ArrayMap<>();
                    mServices.put(context, map);
                }
                map.put(c, sd);
            } else {
                sd.validate(context, handler, executor);
            }
            return sd.getIServiceConnection();
        }
    }
    
  • 在獲取ServiceDispatcher過程中,有一個mServices成員變量,這個變量是一個ArrayMap類型的,它存儲了ServiceConnectionLoadedApk.ServiceDispatcher之間的映射關係。首先判斷是否有這個映射關係,如果有的話就直接返回,如果沒有的話就創建ServiceDispatcher, 並且將其存儲到mServices中。
  • 接着進入到註釋3ActivityManager.getService(), 在Activity啓動流程源碼分析一文中我們說到了這裏其實是得到了一個ActivityManagerService(下文簡稱AMS),接着我們進入AMS的bindIsolatedService中看看。
    public int bindIsolatedService(IApplicationThread caller, IBinder token, Intent service,
            String resolvedType, IServiceConnection connection, int flags, String instanceName,
            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");
        }
    
        // Ensure that instanceName, which is caller provided, does not contain
        // unusual characters.
        if (instanceName != null) {
            for (int i = 0; i < instanceName.length(); ++i) {
                char c = instanceName.charAt(i);
                if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
                            || (c >= '0' && c <= '9') || c == '_' || c == '.')) {
                    throw new IllegalArgumentException("Illegal instanceName");
                }
            }
        }
    
        synchronized(this) {
            return mServices.bindServiceLocked(caller, token, service,
                    resolvedType, connection, flags, instanceName, callingPackage, userId);
        }
    }
    
  • 我們看到在最後調用了mServices.bindServiceLocked,這裏mServices是ActivteServices類型的,我們上一篇Service流程源碼分析(一) startService中有所介紹。下面接着看這個bindServiceLocked
    int bindServiceLocked(IApplicationThread caller, IBinder token, Intent service,
            String resolvedType, final IServiceConnection connection, int flags,
            String instanceName, String callingPackage, final int userId)
            throws TransactionTooLargeException {
        
       		...
       		//-----1-----
            if ((flags&Context.BIND_AUTO_CREATE) != 0) {
                s.lastActivity = SystemClock.uptimeMillis();
                if (bringUpServiceLocked(s, service.getFlags(), callerFg, false,
                        permissionsReviewRequired) != null) {
                    return 0;
                }
            }	
          	//-----2-----
            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) {
                    Slog.w(TAG, "Failure sending service " + s.shortInstanceName
                            + " to connection " + c.conn.asBinder()
                            + " (in " + c.binding.client.processName + ")", 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) {
            		//-----3-----
                    requestServiceBindingLocked(s, b.intent, callerFg, true);
                }
            } else if (!b.intent.requested) {
            	//-----4-----
                requestServiceBindingLocked(s, b.intent, callerFg, false);
            }
    
            getServiceMapLocked(s.userId).ensureNotStartingBackgroundLocked(s);
    
        } finally {
            Binder.restoreCallingIdentity(origId);
        }
    
        return 1;
    }
    
  • 在註釋1處,我們根據Context.BIND_AUTO_CREATE進行判斷,這個標記是在我們調用bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE)傳入的最後一個參數,所以這裏會進入bringUpServiceLocked, 這裏怎麼看着這麼熟悉呢,沒錯,這個方法我們在Service流程源碼分析(一) startService中是重點分析的對象,也就是這個方法最終執行的service.onCreate(), 這裏bindService自然也是要執行onCreate的,這裏就不詳細介紹了,不懂的可以看那篇文章熟悉一下 bringUpServiceLocked的流程。
  • 註釋2的地方根據s.app != null && b.intent.received進行判斷,但是最終都會執行3或者4處的requestServiceBindingLocked方法。在講解requestServiceBindingLocked之前,我們提一下這兩個判斷條件。
  • s.appProcessRecord類型,它在bringUpServiceLocked -> realStartServiceLocked中的開始被賦值,源碼如下注釋1處,所以是在requestServiceBindingLocked之前就被賦值了,這裏s.app!=nulltrue
    private final void realStartServiceLocked(ServiceRecord r,
            ProcessRecord app, boolean execInFg) throws RemoteException {
        if (app.thread == null) {
            throw new RemoteException();
        }
        ...
        //-----1-----
        r.setProcess(app);
        ...
    
  • b.intent.received是一個boolean類型的,默認爲false,它是在什麼時候被賦值爲true的呢 ?它是在當收到請求binder的時候被賦值爲true, 這裏很明顯還是false, 所以實際上走的是上面註釋4處的requestServiceBindingLocked, 因爲b.intent.requested默認爲false。其實這兩個值都是在ActivityThread.handleBindService -> ActivityManager.getService().publishService -> mServices.publishServiceLocked中賦值的,這裏很明顯沒有進入到這裏,所以都還是false, 感興趣的可以看看這部分源碼。
  • 好了,我們接着看requestServiceBindingLocked部分的源碼。
    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 (DEBUG_SERVICE) Slog.d(TAG_SERVICE, "requestBind " + i + ": requested=" + i.requested
                + " rebind=" + rebind);
        if ((!i.requested || rebind) && i.apps.size() > 0) {
            try {
                bumpServiceExecutingLocked(r, execInFg, "bind");
                r.app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
                //-----1-----
                r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind,
                        r.app.getReportedProcState());
                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;
    }
    
    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);
        }
    
    case BIND_SERVICE:
             Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceBind");
            handleBindService((BindServiceData)msg.obj);
            Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
            break;
    
  • H是前面文章介紹過了,它是一個Handler, 通過Handler機制來處理消息,我們看到接着會調用handleBindService來進行處理,我們進入這個方法看看。
    private void handleBindService(BindServiceData data) {
    	//-----1-----
        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) {
                   		 //-----2-----
                        IBinder binder = s.onBind(data.intent);
                        //-----3-----
                        ActivityManager.getService().publishService(
                                data.token, data.intent, binder);
                    } else {
                        s.onRebind(data.intent);
                        ActivityManager.getService().serviceDoneExecuting(
                                data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
                    }
                } 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);
                }
            }
        }
    }
    
  • 註釋1處獲取之前在handleCreateService中存入的service。
  • 在註釋2s.onBind(data.intent)我們已經很熟悉了, 它返回一個我們自己創建的Binder對象給客戶端。這個時候客戶端和服務端其實已經綁定上了,但是onBind是在服務端調用的,客戶端並不知道已經綁定成功了,需要執行我們自己創建的ServiceConnection.onServiceConnected告知客戶端,這些邏輯就在註釋3中。
  • 我們查看註釋3ActivityManager.getService().publishService源碼。
    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");
            }
            //-----1-----
            mServices.publishServiceLocked((ServiceRecord)token, intent, service);
        }
    }
    
    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;
                    ArrayMap<IBinder, ArrayList<ConnectionRecord>> connections = r.getConnections();
                    for (int conni = connections.size() - 1; conni >= 0; conni--) {
                        ArrayList<ConnectionRecord> clist = 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 {
                            	//-----2-----
                                c.conn.connected(r.name, service, false);
                            } catch (Exception e) {
                                Slog.w(TAG, "Failure sending service " + r.shortInstanceName
                                      + " to connection " + c.conn.asBinder()
                                      + " (in " + c.binding.client.processName + ")", e);
                            }
                        }
                    }
                }
    
                serviceDoneExecutingLocked(r, mDestroyingServices.contains(r), false);
            }
        } finally {
            Binder.restoreCallingIdentity(origId);
        }
    }
    
  • 代碼進入到了註釋1處的publishServiceLocked,交給了ActiveServices進行處理。
  • 接着進入到了註釋2處的c.conn.connected(r.name, service, false);。這一行可以說是重點。c.connServiceDispatcher.InnerConnection類型,這裏又傳入了onBind返回的service對象。下面看一下這個InnerConnection.connected源碼。
    private static class InnerConnection extends IServiceConnection.Stub {
            @UnsupportedAppUsage
            final WeakReference<LoadedApk.ServiceDispatcher> mDispatcher;
    
            InnerConnection(LoadedApk.ServiceDispatcher sd) {
                mDispatcher = new WeakReference<LoadedApk.ServiceDispatcher>(sd);
            }
    
            public void connected(ComponentName name, IBinder service, boolean dead)
                    throws RemoteException {
                LoadedApk.ServiceDispatcher sd = mDispatcher.get();
                if (sd != null) {
                    sd.connected(name, service, dead);
                }
            }
    }
    
  • 我們看到又調用了sd.connected(name, service, dead), 源碼如下。
    public void connected(ComponentName name, IBinder service, boolean dead) {
            if (mActivityExecutor != null) {
                mActivityExecutor.execute(new RunConnection(name, service, 0, dead));
            } else if (mActivityThread != null) {
                mActivityThread.post(new RunConnection(name, service, 0, dead));
            } else {
                doConnected(name, service, dead);
            }
    }
    
  • 這裏mActivityExecutormActivityThread在一開始我們調用bindService的時候,調用了ContextImpl.bindServicemActivityExecutor是null, mActivityThread是一個Handler, 其實就是ActivityThread中的H,所以不爲null, 所以這裏進入了第二個mActivityThread != null中,執行了RunConnection中的run方法。源碼如下。
    private final class RunConnection implements Runnable {
            RunConnection(ComponentName name, IBinder service, int command, boolean dead) {
                mName = name;
                mService = service;
                mCommand = command;
                mDead = dead;
            }
    
            public void run() {
                if (mCommand == 0) {
                	//-----1-----
                    doConnected(mName, mService, mDead);
                } else if (mCommand == 1) {
                    doDeath(mName, mService);
                }
            }
    
            final ComponentName mName;
            final IBinder mService;
            final int mCommand;
            final boolean mDead;
    }
    
  • 這裏很清楚調用了doConnected(mName, mService, mDead)方法,源碼如下:
    public void doConnected(ComponentName name, IBinder service, boolean dead) {
            ServiceDispatcher.ConnectionInfo old;
            ServiceDispatcher.ConnectionInfo info;
    		...
            // If there is a new viable service, it is now connected.
            if (service != null) {
                mConnection.onServiceConnected(name, service);
            } else {
                // The binding machinery worked, but the remote returned null from onBind().
                mConnection.onNullBinding(name);
            }
        }
    
  • 上面的源碼中doConnectedServiceDispatcher的方法,前面講到,它存儲了ServiceConnection, 所以很容易就調用到了onServiceConnected方,這是在客戶端調用的,到這裏bindService也就分析完了,unbindService比較簡單,就不分析了。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章