Android深入四大元件(三)Service的繫結過程

劉望舒發表於2019-03-02

相關文章
Android深入理解四大元件系列

前言

我們可以通過呼叫Context的startService來啟動Service,也可以通過Context的bindService來繫結Service,建議閱讀此篇文章前請閱讀Android深入四大元件(二)Service的啟動過程這篇文章,知識點重疊的部分,本篇文章將不再贅述。

1.ContextImpl到ActivityManageService的呼叫過程

我們可以用bindService方法來繫結Service,它的實現在ContextWrapper中,程式碼如下所示。
frameworks/base/core/java/android/content/ContextWrapper.java

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

這裡mBase具體指向就是ContextImpl,不明白的請檢視 Android深入四大元件(二)Service的啟動過程這篇文章。接著檢視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());
    }複製程式碼

在bindService方法中,又return了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) {
        sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(), handler, flags);//1
    } else {
        throw new RuntimeException("Not supported in system context");
    }
    validateServiceIntent(service);
    try {
     ...
     /**
     * 2
     */
        int res = ActivityManagerNative.getDefault().bindService(
            mMainThread.getApplicationThread(), getActivityToken(), service,
            service.resolveTypeIfNeeded(getContentResolver()),
            sd, flags, getOpPackageName(), user.getIdentifier());
      ...
    } catch (RemoteException e) {
        throw e.rethrowFromSystemServer();
    }
}複製程式碼

在註釋1處呼叫了LoadedApk型別的物件mPackageInfo的getServiceDispatcher方法,它的主要作用是將ServiceConnection封裝為IServiceConnection型別的物件sd,從IServiceConnection的名字我們就能得知它實現了Binder機制,這樣Service的繫結就支援了跨程式。接著在註釋2處我們又看見了熟悉的程式碼,最終會呼叫AMS的bindService方法。
ContextImpl到ActivityManageService的呼叫過程如下面的時序圖所示。

Android深入四大元件(三)Service的繫結過程

2.Service的繫結過程

AMS的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");
...
        synchronized(this) {
            return mServices.bindServiceLocked(caller, token, service,
                    resolvedType, connection, flags, callingPackage, userId);
        }
    }複製程式碼

bindService方法最後會呼叫ActiveServices型別的物件mServices的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();
                /**
                *  1
                */
                if (bringUpServiceLocked(s, service.getFlags(), callerFg, false,
                        permissionsReviewRequired) != null) {
                    return 0;
                }
            }
          ...
            if (s.app != null && b.intent.received) {//2
                try {
                    c.conn.connected(s.name, b.intent.binder);//3
                } catch (Exception e) {
                ...
                }
                if (b.intent.apps.size() == 1 && b.intent.doRebind) {//4
                    requestServiceBindingLocked(s, b.intent, callerFg, true);//5
                }
            } else if (!b.intent.requested) {//6
                requestServiceBindingLocked(s, b.intent, callerFg, false);//7
            }
            getServiceMap(s.userId).ensureNotStartingBackground(s);
        } finally {
            Binder.restoreCallingIdentity(origId);
        }
        return 1;
}複製程式碼

在註釋1處會bringUpServiceLocked方法,在bringUpServiceLocked方法中又會呼叫realStartServiceLocked方法,最終由ActivityThread來呼叫Service的onCreate方法啟動Service,這一過程在Android深入四大元件(二)Service的啟動過程這篇文章中已經講過,這裡不再贅述。
在註釋2處s.app != null 表示Service已經執行,其中s是ServiceRecord型別物件,app是ProcessRecord型別物件。b.intent.received表示當前應用程式程式的Client端已經接收到繫結Service時返回的Binder,這樣應用程式程式的Client端就可以通過Binder來獲取要繫結的Service的訪問介面。註釋3處呼叫c.conn的connected方法,其中c.conn指的是IServiceConnection,它的具體實現為ServiceDispatcher.InnerConnection,其中ServiceDispatcher是LoadedApk的內部類,InnerConnection的connected方法內部會呼叫H的post方法向主執行緒傳送訊息,從而解決當前應用程式程式和Service跨程式通訊的問題,在後面會詳細介紹這一過程。
在註釋4處如果當前應用程式程式的Client端第一次與Service進行繫結的,並且Service已經呼叫過onUnBind方法,則需要呼叫註釋5的程式碼。
註釋6處如果應用程式程式的Client端沒有傳送過繫結Service的請求,則會呼叫註釋7的程式碼,註釋7和註釋5的程式碼區別就是最後一個引數rebind為false,表示不是重新繫結。
接著我們檢視註釋7的requestServiceBindingLocked方法,程式碼如下所示。
frameworks/base/services/core/java/com/android/server/am/ActiveServices.java

private final boolean requestServiceBindingLocked(ServiceRecord r, IntentBindRecord i,
        boolean execInFg, boolean rebind) throws TransactionTooLargeException {
   ...
    if ((!i.requested || rebind) && i.apps.size() > 0) {//1
        try {
            bumpServiceExecutingLocked(r, execInFg, "bind");
            r.app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
            r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind,
                    r.app.repProcState);//2
           ...
        } 
        ...
    }
    return true;
}複製程式碼

註釋1處i.requested表示是否傳送過繫結Service的請求,從前面的程式碼得知是沒有傳送過,因此,!i.requested為true。從前面的程式碼得知rebind值為false,那麼(!i.requested || rebind)的值為true。如果IntentBindRecord中的應用程式程式記錄大於0,則會呼叫註釋2的程式碼,r.app.thread的型別為IApplicationThread,它的實現我們已經很熟悉了,是ActivityThread的內部類ApplicationThread,scheduleBindService方法如下所示。
frameworks/base/core/java/android/app/ActivityThread.java

  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);
        }複製程式碼

首先將Service的資訊封裝成BindServiceData物件,需要注意的BindServiceData的成員變數rebind的值為false,後面會用到它。接著將BindServiceData傳入到sendMessage方法中。sendMessage向H傳送訊息,我們接著檢視H的handleMessage方法。
frameworks/base/core/java/android/app/ActivityThread.java

public void handleMessage(Message msg) {
          if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
          switch (msg.what) {
          ...
              case BIND_SERVICE:
                    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceBind");
                    handleBindService((BindServiceData)msg.obj);
                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                    break;
          ...
           }
        ...
        }
     ...   
}複製程式碼

H在接收到BIND_SERVICE型別訊息時,會在handleMessage方法中會呼叫handleBindService方法:
frameworks/base/core/java/android/app/ActivityThread.java

 private void handleBindService(BindServiceData data) {
        Service s = mServices.get(data.token);//1
        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
                        ActivityManagerNative.getDefault().publishService(
                                data.token, data.intent, binder);//4
                    } else {
                        s.onRebind(data.intent);//5
                        ActivityManagerNative.getDefault().serviceDoneExecuting(
                                data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
                    }
                    ensureJitEnabled();
                } 
                ...
            } 
            ...
        }
    }複製程式碼

註釋1處獲取要繫結的Service 。註釋2處的BindServiceData的成員變數rebind的值為false,這樣會呼叫註釋3處的程式碼來呼叫Service的onBind方法,這樣Service處於繫結狀態了。如果rebind的值為true就會呼叫註釋5處的Service的onRebind方法,結合前文的bindServiceLocked方法的註釋4處,我們得知如果當前應用程式程式的Client端第一次與Service進行繫結,並且Service已經呼叫過onUnBind方法,則會呼叫Service的onRebind方法。
接著檢視註釋4的程式碼,實際上是呼叫AMS的publishService方法。
講到這,先給出這一部分的程式碼時序圖(不包括Service啟動過程)

Android深入四大元件(三)Service的繫結過程

我們接著來檢視AMS的publishService方法,程式碼如下所示。
frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

public void publishService(IBinder token, Intent intent, IBinder service) {
  ...
    synchronized(this) {
        if (!(token instanceof ServiceRecord)) {
            throw new IllegalArgumentException("Invalid service token");
        }
        mServices.publishServiceLocked((ServiceRecord)token, intent, service);
    }
}複製程式碼

publishService方法中,呼叫了ActiveServices型別的mServices物件的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 {
           ...
                    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++) {
                         ...
                            try {
                                c.conn.connected(r.name, service);//1
                            } catch (Exception e) {
                             ...
                            }
                        }
                    }
                }
                serviceDoneExecutingLocked(r, mDestroyingServices.contains(r), false);
            }
        } finally {
            Binder.restoreCallingIdentity(origId);
        }
    }複製程式碼

註釋1處的程式碼,我在前面介紹過,c.conn指的是IServiceConnection,它的具體實現為ServiceDispatcher.InnerConnection,其中ServiceDispatcher是LoadedApk的內部類,ServiceDispatcher.InnerConnectiond的connected方法的程式碼如下所示。
frameworks/base/core/java/android/app/LoadedApk.java

static final class ServiceDispatcher {
     ...
        private static class InnerConnection extends IServiceConnection.Stub {
            final WeakReference<LoadedApk.ServiceDispatcher> mDispatcher;
            InnerConnection(LoadedApk.ServiceDispatcher sd) {
                mDispatcher = new WeakReference<LoadedApk.ServiceDispatcher>(sd);
            }
            public void connected(ComponentName name, IBinder service) throws RemoteException {
                LoadedApk.ServiceDispatcher sd = mDispatcher.get();
                if (sd != null) {
                    sd.connected(name, service);//1
                }
            }
        }
 ...
 }複製程式碼

在註釋1處呼叫了ServiceDispatcher 型別的sd物件的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));//1
            } else {
                doConnected(name, service);
            }
        }複製程式碼

註釋1處呼叫Handler型別的物件mActivityThread的post方法,mActivityThread實際上指向的是H。因此,通過呼叫H的post方法將RunConnection物件的內容執行在主執行緒中。RunConnection的定義如下所示。
frameworks/base/core/java/android/app/LoadedApk.java

  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;
    }複製程式碼

在RunConnection的run方法中呼叫了doConnected方法:
frameworks/base/core/java/android/app/LoadedApk.java

public void doConnected(ComponentName name, IBinder service) {
  ...
    // If there was an old service, it is not disconnected.
    if (old != null) {
        mConnection.onServiceDisconnected(name);
    }
    // If there is a new service, it is now connected.
    if (service != null) {
        mConnection.onServiceConnected(name, service);//1
    }
}複製程式碼

在註釋1處呼叫了ServiceConnection型別的物件mConnection的onServiceConnected方法,這樣在客戶端中實現了ServiceConnection介面的類的onServiceConnected方法就會被執行。至此,Service的繫結過程就分析到這。
最後給出剩餘部分的程式碼時序圖。

Android深入四大元件(三)Service的繫結過程


歡迎關注我的微信公眾號,第一時間獲得部落格更新提醒,以及更多成體系的Android相關原創技術乾貨。
掃一掃下方二維碼或者長按識別二維碼,即可關注。

Android深入四大元件(三)Service的繫結過程

相關文章