ActivityManagerService框架粗略分析

前言

AMS是系統的引導服務,應用進程的啓動、切換和調度、四大組件的啓動和管理都需要AMS的支持。Android應用各個組件都是通過AMS調度,Android進程也是AMS創建,Android應用程序啓動之前先啓動進程,然後啓動對應的Activity

AMS框架

從Launcher開始

應用啓動可以通過adb啓動,可以通過其他應用啓動(包括Launcher),也可以通過監聽廣播啓動。一般啓動一個Android應用都是從Launcher開始,通過點擊桌面圖標啓動一個應用程序。

在這裏插入圖片描述

  1. 點擊Launcher啓動圖標,執行Activity的startActivityForResults

Activity.java

   public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
            @Nullable Bundle options) {    
    ...
    Instrumentation.ActivityResult ar =
                mInstrumentation.execStartActivity(
                    this, mMainThread.getApplicationThread(), mToken, this,
                    intent, requestCode, options);...
    ...
    }
  1. startActivityForResults中Instrumentation對象執行execStartActivity,其中注意mMainThread.getApplicationThread()這個參數,這個是所啓動這個Activity應用裏面的ApplicationThread,繼承IApplicationThread.Stub,顯然這是一個用於跨進程通訊的類.其中ApplicationThread是服務端,它傳輸到AMS,那麼AMS對於ApplicationThread就是客戶端.因爲Binder是客戶服務模式,只能從客戶端主動請求,傳入對於binder到AMS客戶讓AMS能夠主動與應用交互,
  2. execStartActivity中通過ActivityManger與ActivityManagerService跨進程通訊

Instrumentation.java

    public ActivityResult execStartActivity(
            Context who, IBinder contextThread, IBinder token, String resultWho,
            Intent intent, int requestCode, Bundle options, UserHandle user) {
        IApplicationThread whoThread = (IApplicationThread) contextThread; //1
       ...
        try {
            intent.migrateExtraStreamToClipData();
            intent.prepareToLeaveProcess(who);
            int result = ActivityManager.getService() //2
                .startActivityAsUser(whoThread, who.getBasePackageName(), intent,
                        intent.resolveTypeIfNeeded(who.getContentResolver()),
                        token, resultWho,
                        requestCode, 0, null, options, user.getIdentifier());
            checkStartActivityResult(result, intent);
        } catch (RemoteException e) {
            throw new RuntimeException("Failure from system", e);
        }
        return null;
    }

Instrumentation:

  • 在ActivityThread中實例化
  • 用於監控系統與應用程序交互
  • 用於單元測試

ActivityManager:

  • ActivityManager是一個和AMS相關聯的類,它主要對運行中的Activity進行管理,這些管理工作並不是由ActivityManager來處理的,而是交由AMS來處理
  • AMS作爲系統核心服務,很多API是不會暴露給ActivityManager的
  • Activity通過binder與AMS交互
  • binder的service_server可以向service_client提供service服務,但反過來不行。所以binder service其實是單向的,上面1傳入的當前應用的IApplicationThread,如果該IApplicationThread就是此時啓動的Activity,那麼AMS會使用該IApplicationThread與這個應用的ActivityThread交互。
    上面注2,int result = ActivityManager.getService() //2 這裏對應代碼
    ActivityManager.java
    /**
     * @hide
     */
    public static IActivityManager getService() {
        return IActivityManagerSingleton.get();
    }

    private static final Singleton<IActivityManager> IActivityManagerSingleton =
            new Singleton<IActivityManager>() {
                @Override
                protected IActivityManager create() {
                    final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
                    final IActivityManager am = IActivityManager.Stub.asInterface(b);
                    return am;
                }
            };

IActivityManager.Stub.asInterface(b);如果此時調用與實際實現不在一個進程會生成一個可供跨進程通訊的接口,應用裏面寫AIDL也有同樣的操作.

然後調用IActivityManager的startActivity方法,把數據傳遞到AMS中

@Override public int startActivity(android.app.IApplicationThread caller, java.lang.String callingPackage, android.content.Intent intent, java.lang.String resolvedType, android.os.IBinder resultTo, java.lang.String resultWho, int requestCode, int flags, android.app.ProfilerInfo profilerInfo, android.os.Bundle options) throws android.os.RemoteException
{
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
int _result;
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeStrongBinder((((caller!=null))?(caller.asBinder()):(null)));
_data.writeString(callingPackage);
if ((intent!=null)) {
_data.writeInt(1);
intent.writeToParcel(_data, 0);
}
else {
_data.writeInt(0);
}
_data.writeString(resolvedType);
_data.writeStrongBinder(resultTo);
_data.writeString(resultWho);
_data.writeInt(requestCode);
_data.writeInt(flags);
if ((profilerInfo!=null)) {
_data.writeInt(1);
profilerInfo.writeToParcel(_data, 0);
}
else {
_data.writeInt(0);
}
if ((options!=null)) {
_data.writeInt(1);
options.writeToParcel(_data, 0);
}
else {
_data.writeInt(0);
}
mRemote.transact(Stub.TRANSACTION_startActivity, _data, _reply, 0);
_reply.readException();
_result = _reply.readInt();
}
finally {
_reply.recycle();
_data.recycle();
}
return _result;
}

ActivityManagerService

在這裏插入圖片描述

  1. ActivityManagerService調用startActivityAsUser
    public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
            Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
            int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
            boolean validateIncomingUser) {
        enforceNotIsolatedCaller("startActivity");

        userId = mActivityStartController.checkTargetUser(userId, validateIncomingUser,
                Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");

        // TODO: Switch to user app stacks here.
        return mActivityStartController.obtainStarter(intent, "startActivityAsUser")//3
                .setCaller(caller)
                .setCallingPackage(callingPackage)
                .setResolvedType(resolvedType)
                .setResultTo(resultTo)
                .setResultWho(resultWho)
                .setRequestCode(requestCode)
                .setStartFlags(startFlags)
                .setProfilerInfo(profilerInfo)
                .setActivityOptions(bOptions)
                .setMayWait(userId)
                .execute();

    }

上面3處的mActivityStartController.obtainStarter返回的是ActivityStarter

ActivityStartController

    ActivityStarter obtainStarter(Intent intent, String reason) {
        return mFactory.obtain().setIntent(intent).setReason(reason);
    }
  1. ActivityStarter管理Activity的launchmode,ActivityStarter下一步通過ActivityStackSupervisor完成與ActivityThread(應用端)交互。ActivityStackSupervisor由AMS創建,如下:

ActivityManagerService.java

    protected ActivityStackSupervisor createStackSupervisor() {
        final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mHandler.getLooper());
        supervisor.initialize();
        return supervisor;
    }

ActivityStarter通過ActivityStackSupervisor,判斷應用進程是否存在

ActivityStackSupervisor.java

    void startSpecificActivityLocked(ActivityRecord r,
            boolean andResume, boolean checkConfig) {
        // Is this activity's application already running?
        ProcessRecord app = mService.getProcessRecordLocked(r.processName,//4
                r.info.applicationInfo.uid, true);

        getLaunchTimeTracker().setLaunchTime(r);

        if (app != null && app.thread != null) {//5
            try {
                if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0
                        || !"android".equals(r.info.packageName)) {
                    // Don't add this if it is a platform component that is marked
                    // to run in multiple processes, because this is actually
                    // part of the framework so doesn't make sense to track as a
                    // separate apk in the process.
                    app.addPackage(r.info.packageName, r.info.applicationInfo.longVersionCode,
                            mService.mProcessStats);
                }
                realStartActivityLocked(r, app, andResume, checkConfig);
                return;
            } catch (RemoteException e) {
                Slog.w(TAG, "Exception when starting activity "
                        + r.intent.getComponent().flattenToShortString(), e);
            }

            // If a dead object exception was thrown -- fall through to
            // restart the application.
        }

        mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,//5
                "activity", r.intent.getComponent(), false, false, true);
    }

在4處,查詢應用進程是否存在,如果不存在,在5處會開始新的進程,這是一個十分重要的步驟,否則在4處執行完成後直接return。

ActivityManagerService

  • ActivityManagerService負責四大組件的調用和應用進程的創建

ActivityStarter

  • ActivityStarter管理Activity的啓動模式:singleTask,SIngtop等等,還有flag也是在其中處理的

ActivityStackSupervisor

  • ActivityStack從名稱來看是跟棧相關的類,其實它是一個管理類,用來管理系統所有Activity的各種狀態。它由ActivityStackSupervisor來進行管理的,而ActivityStackSupervisor在AMS中的構造方法中被創建。
  • ActivityStackSupervisor管理了當前應用的Activitytaskh和HomeActivityTask
  • ActivityStack是應用的activity的task
  • ActivityStack保存的TaskRecord,Task裏面保存着ActivityRecord

AMS創建進程與應用啓動

在上面提到如果啓動的Activity進程不存在,AMS就會創建進程。AMS創建進程是AMS通過Zygoted socket通訊。Zygoted通過傳過來的信息fork新的進程,啓動應用ActivityThread的main方法,把IApplication保存在AMS中。

在這裏插入圖片描述

Zygote:

  • zygote在系統啓動時啓動的,他在孵化出SystemService後循環等待AMS的socket通訊
  • zygote啓動的時候創建的虛擬機,但是沒有創建binder,因爲zygote只需要與AMS進行socket通訊
  • RuntimeInit創建的binder線程池,他在zygote孵化新的進程後運行。通過反射啓動ActivityThread

ActivityThread

  • 啓動消息循環,通過消息循環控制Activity主線程與其他線程交互
  • 創建Applcaition,通過ApplcaitionThread的binder與AMS交互,AMS通過IApplaction管理Activit的生命週期

…看不下去了…

總結

  1. 瞭解Instumentation,ActivityManager,AMS,ActivityStacSuperVisor,ActivityTask,ActivityThread,ApplcaitionThread,zygote,ActivityStarter作用和功能
  2. 瞭解相關流程
  3. 知道binder是單向通訊,所以AMS與Activity交互除了用AMS的binder,還得用ApplicationThread的binder
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章