Framework 源碼解析知識梳理(1) 應用程序與 AMS 的通訊實現

1、前言

咱們在許多和Framework解析相關的文章中,都會看到ActivityManagerService這個類,可是在上層的應用開發中,卻不多直接會使用到他。bash

那麼咱們爲何要學習它的呢,一個最直接的好處就是它是咱們理解應用程序啓動過程的基礎,只有把和ActivityManagerService以及和它相關的類的關係都理解透了,咱們才能理清應用程序啓動的過程。app

今天這篇文章,咱們就來對ActivityManagerService與應用進程之間的通訊方式作一個簡單的總結,這裏咱們根據進程之間的通訊方向,分爲兩個部分來討論:框架

  • 從應用程序進程到管理者進程ide

    (a) IActivityManager (b) ActivityManagerNative (c) ActivityManagerProxy (d) ActivityManagerService函數

  • 從管理者進程到應用程序進程學習

    (a) IApplicationThread (b) ApplicationThreadNative (c) ApplicationThreadProxy (d) ApplicationThreadui

2、從應用程序進程到管理者進程

在這一方向上的通訊,應用程序進程做爲客戶端,而管理者進程則做爲服務端。舉一個最簡單的例子,當咱們啓動一個Activity,就須要通知全局的管理者,讓它去負責啓動,這個全局的管理者就運行在另一個進程,這裏就涉及到了從應用程序進程到管理者進程的通訊。this

這一個方向上通訊過程所涉及到的類包括: spa

2.1 應用程序進程向管理者進程發送消息

當咱們想要啓動一個Activity,會首先調用到Activity的:代理

@Override
    public void startActivityForResult(
            String who, Intent intent, int requestCode, @Nullable Bundle options) {
        //...
        Instrumentation.ActivityResult ar =
            mInstrumentation.execStartActivity(
                this, mMainThread.getApplicationThread(), mToken, who,
                intent, requestCode, options);
        //...
    }
複製代碼

以後調用到Instrumentation的:

public ActivityResult execStartActivity(
            Context who, IBinder contextThread, IBinder token, Activity target,
            Intent intent, int requestCode, Bundle options) {
            //....
            int result = ActivityManagerNative.getDefault()
                .startActivity(whoThread, who.getBasePackageName(), intent,
                        intent.resolveTypeIfNeeded(who.getContentResolver()),
                        token, target != null ? target.mEmbeddedID : null,
                        requestCode, 0, null, options);
            //...
    }
複製代碼

這裏咱們看到了上面UML圖中ActivityManagerNative,它的getDefault()方法返回的是一個IActivityManager的實現類:

private static final Singleton<IActivityManager> gDefault = new Singleton<IActivityManager>() {
        protected IActivityManager create() {
            //1.獲得一個代理對象
            IBinder b = ServiceManager.getService("activity");
            //2.將這個代理對象再通過一層封裝
            IActivityManager am = asInterface(b);
            return am;
        }
    };

    static public IActivityManager getDefault() {
        return gDefault.get();
    }
複製代碼

這裏,對於gDefault變量有兩點說明:

  • 這是一個static類型的變量,所以在程序中的任何地方調用getDefault()方法訪問的是內存中的同一個對象
  • 這裏採用了Singleton模式,也就是懶漢模式的單例,只有第一次調用get()方法時,纔會經過create()方法來建立一個對象

create()作了兩件事:

  • 經過ServieManager獲得IBinder,這個IBinder是管理進程在應用程序進程的代理對象,經過IBindertransact方法,咱們就能夠向管理進程發送消息:
public boolean transact(int code, Parcel data, Parcel reply, int flags)
複製代碼
  • IBinder傳入asInterface(IBinder b)構建一個IActivityManager的實現類,能夠看到,這裏返回的是一個ActivityManagerProxy對象:
static public IActivityManager asInterface(IBinder obj) {
        if (obj == null) {
            return null;
        }
        //這一步先忽略....
        IActivityManager in = (IActivityManager)obj.queryLocalInterface(descriptor);
        if (in != null) {
            return in;
        }
        return new ActivityManagerProxy(obj);
    }
複製代碼

下面,咱們在來看一下這個ActivityManagerProxy,它實現了IActivityManager接口,咱們能夠看到它所實現的IActivityManager接口方法都是經過構造這個對象時所傳入的IBinder.transact(xxxx)來調用的,這些方法之間的區別就在於消息的類型以及參數。

class ActivityManagerProxy implements IActivityManager {

    public ActivityManagerProxy(IBinder remote) {
        mRemote = remote;
    }

    public IBinder asBinder() {
        return mRemote;
    }

    public int startActivity(IApplicationThread caller, String callingPackage, Intent intent,
            String resolvedType, IBinder resultTo, String resultWho, int requestCode,
            int startFlags, ProfilerInfo profilerInfo, Bundle options) throws RemoteException {
        Parcel data = Parcel.obtain();
        Parcel reply = Parcel.obtain();
        //這個也很重要,咱們以後分析..
        data.writeStrongBinder(caller != null ? caller.asBinder() : null);
        //發送消息到管理者進程...
        mRemote.transact(START_ACTIVITY_TRANSACTION, data, reply, 0);
        reply.readException();
        int result = reply.readInt();
        reply.recycle();
        data.recycle();
        return result;
    }
 }
複製代碼

通過上面的分析,咱們用一句話總結:

應用程序進程經過ActivityManagerProxy內部的IBinder.transact(...)向管理者進程發送消息,這個IBinder是管理者進程在應用程序進程的一個代理對象,它是經過ServieManager得到的。

2.2 管理者進程處理消息

下面,咱們看一下管理者進程對於消息的處理,在管理者進程中,最終是經過ActivityManagerService對各個應用程序進行管理的。

它繼承了ActivityManagerNative類,並重寫了Binder類的onTransact(...)方法,咱們前面經過ActivityManagerProxyIBinder對象發送的消息最終會調用到管理者進程中的這個函數當中,ActivityManagerNative對該方法進行了重寫:

@Override
  public boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException {
    switch (code) {
        case START_ACTIVITY_TRANSACTION:
            data.enforceInterface(IActivityManager.descriptor);
            IBinder b = data.readStrongBinder();
            IApplicationThread app = ApplicationThreadNative.asInterface(b);
            String callingPackage = data.readString();
            Intent intent = Intent.CREATOR.createFromParcel(data);
            String resolvedType = data.readString();
            IBinder resultTo = data.readStrongBinder();
            String resultWho = data.readString();
            int requestCode = data.readInt();
            int startFlags = data.readInt();
            ProfilerInfo profilerInfo = data.readInt() != 0
                    ? ProfilerInfo.CREATOR.createFromParcel(data) : null;
            Bundle options = data.readInt() != 0
                    ? Bundle.CREATOR.createFromParcel(data) : null;
            //這裏在管理者進程進行處理操做....
            int result = startActivity(app, callingPackage, intent, resolvedType,
                    resultTo, resultWho, requestCode, startFlags, profilerInfo, options);
            reply.writeNoException();
            reply.writeInt(result);
            return true;
      //...
  }
複製代碼

onTransact(xxx)方法中,會根據收到的消息類型,調用IActivityManager接口中所定義的不一樣接口,而ActivityManagerNative是沒有實現這些接口的,真正的處理在ActivityManagerService中,ActivityManagerService開始進行一系列複雜的操做,這裏以後咱們介紹應用程序啓動過程的時候再詳細分析。

@Override
    public final int startActivity(IApplicationThread caller, String callingPackage,
            Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
            int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
        return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
                resultWho, requestCode, startFlags, profilerInfo, bOptions,
                UserHandle.getCallingUserId());
    }
複製代碼

一樣的,咱們也用一句話總結:

管理者進程經過onTransact(xxxx)處理應用程序發送過來的消息

3、從管理者進程到應用程序進程

接着,咱們考慮另外一個方向上的通訊方式,從管理者進程到應用程序進程,這一方向上的通訊過程涉及到下面的類:

能夠看到, ApplicationThread的整個框架和上面很相似,只不過在這一個方向上,管理者進程做爲客戶端,而應用程序進行則做爲服務端。

3.1 管理者進程嚮應用程序進程發送消息

前面咱們分析的時候,應用程序進程向管理者進程發送消息的時候,是經過IBinder這個管理者進程在應用程序進程中的代理對象來實現的,而這個IBinder則是經過ServiceManager獲取的:

IBinder b = ServiceManager.getService("activity");
複製代碼

同理,若是管理者進程但願嚮應用程序進程發送消息,那麼它也必須設法獲得一個應用程序進程在它這邊的代理對象。

咱們回憶一下,在第二節的分析中,應用者進程向管理者進程發送消息的同時,經過writeStringBinder,放入了下面這個對象:

public int startActivity(IApplicationThread caller, ...) {
    //...
    data.writeStrongBinder(caller != null ? caller.asBinder() : null);
    //...
    mRemote.transact(START_ACTIVITY_TRANSACTION, data, reply, 0);
}
複製代碼

這個caller是在最開始調用startActivityForResult時傳入的:

ActivityThread mMainThread;

    @Override
    public void startActivityForResult(
            String who, Intent intent, int requestCode, @Nullable Bundle options) {
        //...
        Instrumentation.ActivityResult ar =
            mInstrumentation.execStartActivity(
                this, mMainThread.getApplicationThread(), mToken, who,
                intent, requestCode, options);
        //...
    }
複製代碼

經過查看ActivityThread的代碼,咱們能夠看到它實際上是一個定義在ApplicationThread中的ApplicationThread對象,它的asBinder實現是在ApplicationThreadNative當中:

public IBinder asBinder() {
       return this;
   }
複製代碼

在管理者進程接收消息的時候,就能夠經過readStrongBinder得到這個ApplicationThread對象在管理者進程的代理對象IBinder

@Override
  public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
            throws RemoteException {
      switch (code) {
        case START_ACTIVITY_TRANSACTION:
            //取出傳入的ApplicationThread對象,以後調用asInterface方法..
            IBinder b = data.readStrongBinder();
            IApplicationThread app = ApplicationThreadNative.asInterface(b);
            //...
            int result = startActivity(app, callingPackage, intent, resolvedType,
                    resultTo, resultWho, requestCode, startFlags, profilerInfo, options);
            return true;
     }
  }
複製代碼

接着,它再經過asInterface(IBinder xx)方法把傳入的代理對象經過ApplicationThreadProxy進行了一層封裝:

static public IApplicationThread asInterface(IBinder obj) {
        if (obj == null) {
            return null;
        }
        IApplicationThread in = (IApplicationThread) obj.queryLocalInterface(descriptor);
        if (in != null) {
            return in;
        }
        return new ApplicationThreadProxy(obj);
    }
複製代碼

以後,管理者進程就能夠經過這個代理對象的transact(xxxx)方法嚮應用程序進程發送消息了:

class ApplicationThreadProxy implements IApplicationThread {

    private final IBinder mRemote;

    public ApplicationThreadProxy(IBinder remote) {
        mRemote = remote;
    }

    public final IBinder asBinder() {
        return mRemote;
    }

    public final void schedulePauseActivity(IBinder token, boolean finished,
            boolean userLeaving, int configChanges, boolean dontReport) throws RemoteException {
        //....
        mRemote.transact(SCHEDULE_PAUSE_ACTIVITY_TRANSACTION, data, null, IBinder.FLAG_ONEWAY);
        //...
    }
複製代碼

這一個過程能夠總結爲:

管理者進程經過ApplicationThreadProxy內部的IBinder嚮應用程序進程發送消息,這個IBinder是應用程序進程在管理者進程的代理對象,它是在管理者進程接收應用程序進程發送過來的消息中得到的。

3.2 用戶進程接收消息

在用戶程序進程中,ApplicationThreadonTransact(....)就能夠收到管理者進程發送的消息,以後再調用ApplicationThread所實現的IApplicationThread的接口方法進行消息的處理:

@Override
  public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
            throws RemoteException {
        switch (code) {
        case SCHEDULE_PAUSE_ACTIVITY_TRANSACTION: 
            data.enforceInterface(IApplicationThread.descriptor);
            IBinder b = data.readStrongBinder();
            boolean finished = data.readInt() != 0;
            boolean userLeaving = data.readInt() != 0;
            int configChanges = data.readInt();
            boolean dontReport = data.readInt() != 0;
            schedulePauseActivity(b, finished, userLeaving, configChanges, dontReport);
            return true;
  }
複製代碼

3、小結

以上就是應用程序進程和管理者進程之間的通訊方式,究其根本,都是經過獲取對方進程的代理對象的transact(xxxx)方法發送消息,而對方進程則在onTransact(xxxx)方法中進行消息的處理,從而實現了進程之間的通訊。


更多文章,歡迎訪問個人 Android 知識梳理系列:

相關文章
相關標籤/搜索