Android系统源代码情景分析笔记-Activity组件的启动

2018-03-20  本文已影响0人  一只胖Wa牛

Android系统源代码情景分析笔记

Activity组件的启动过程分析

[toc]

根Activity启动的过程分析

Launcher组件启动MainActivity的流程分析

  1. Launcher组件项ActivityManagerService发送一个启动MainActivity组件的进程间通信请求
  2. ActivityManagerService首先将要启动的MainActivity组件的信息保存下来,然后再向Launcher组件发送一个进入中止状态的进程间通信请求
    3.Launcher组件进入到中止状态之后,就会向ActivityManagerService发送一个已进入中止状态的进程间通信请求,以便ActivityManagerService可以继续执行启动MainActivity组件的操作
    4.ActivityManagerService可以继续执行启动MainActivity组件的操作,但是要先讲MainActiivty的宿主进程给创建出来,创建完成以后才能去进行启动MainActivity组件的操作
    5.ActivityManagerService将启动在第2步保存下来的MainActivity组件的信息发送给第4步创建的应用程序进程,以便它可以将MainActivity组件启动起来
    总结整个流程图大概如下:

    ![

启动流程非常复杂,大概有35个步骤


setp1:Launcher.startActivitySafely

/packages/apps/Launcher3/src/com/android/launcher3/Launcher.java

public class Launcher extends Activity
    implements View.OnClickListener,OnLongClickListener,
    LauncherModel.Callbacks,View.OnTouchListener,
    PageSwitchListener,LauncherProviderChangeListener,
    LauncherStateTransitionAnimation.Callback{
        ...
        boolean startActivitySafely(View v, Intent intent, 
            Object tag) {
            boolean success = false;
            ...
            try {
             //调用startActivity方法去启动应用的根Activity
               success = startActivity(v, intent, tag);
            } catch (ActivityNotFoundException e) {
               ...
            }
            return success;
        }
        ...
}    

首次启动应用时候,会执行Launcher组件的startActivitySafely方法,要启动应用的根Activity信息包含在参数intent重,可以看到这个方法主要调用了Launcher组件的startActivity方法,
/packages/apps/Launcher3/src/com/android/launcher3/Launcher.java

     private boolean startActivity(View v, Intent intent, 
         Object tag) {
         //添加启动新的应用标识
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        try{
            ...
            //
            startActivity(intent, optsBundle);
            ...
            return true;
        }cache(SecurityException e){
            ...
        }
        return false;

由于Launcher是Activity的子类,可以看到Launcher组件的startActivity最终调用了ActivitystartActivity方法

step2:Activity.startActivity

/frameworks/base/core/java/android/app/Activity.java

    public class Activity extends ContextThemeWrapper
        implements LayoutInflater.Factory2,
        Window.Callback, KeyEvent.Callback,
        OnCreateContextMenuListener, ComponentCallbacks2,
        Window.OnWindowDismissedCallback {
        ...
        @Override
        public void startActivity(Intent intent, 
            @Nullable Bundle options) {
            if (options != null) {
                startActivityForResult(intent, -1, options);
            } else {
                //最终也会调用到上面那个分支的函数
                startActivityForResult(intent, -1);
            }
        }
        ...
    }

这里调用了Activity组件的startActivityForResult,跟进如下

step3:Activity.startActivityForResult

public void startActivityForResult(Intent intent, int requestCode, Bundle options) {
    if (mParent == null) {
        Instrumentation.ActivityResult ar =
            mInstrumentation.execStartActivity(this,
                mMainThread.getApplicationThread(), mToken, this,
                intent, requestCode, options);
        ...
    }else{
        ...
    }
}

mInstrumentation

这里看到调用了mInstrumentation.execStartActivity方法,Activity的成员变量mInstrumentation类型是Instrumentation,它是用来监控应用程序和系统之间交互操作。由于启动Activity组件是应用程序与系统之间的一个交互操作,所以mInstrumentation.execStartActivity这个方法其实就是用来代理Activity启动的操作,并且能够监视整个交互的过程。

mMainThread.getApplicationThread()参数

Activity的成员变量mMainThread的类型为ActivityThread,用来描述一个应用程序进程。每当系统启动一个应用程序进程时,都会在它里面加载一个ActivityThread类实例,并且会将这个ActivityThread类实例保存在每一个在该进程中启动的Activity组件的父类Activity的成员变量mMainThread中。ActivityThread类的成员函数getApplicationThread用来获取它内部的一个类型为ApplicationThread的Binder本地对象。mInstrumentation.execStartActivity方法中将ApplicationThread对象作为参数传递,这样就可以把这个Binder对象传递给ActivityManagerService,因此ActivityManagerServcie接下来就可以通知Launcher组件进入Paused状态了。

mToken参数

Activity类的成员变量mToken的类型是IBinder,它是一个Binder代理对象,指向了ActivityManagerService中一个类型为ActivityRecord的Binder本地对象。每一个已经启动的Activity组件在ActivityManagerService中都有一个对应的的ActivityRecord对象,用来维护对应的Activity组件的运行状态。mInstrumentation.execStartActivity方法中将将mToken作为参数传递,这样接下来ActivityManagerService就能够获取到Launcher组件的详细信息了。

setp4:Instrumentation.execStartActivity

/frameworks/base/core/java/android/app/Instrumentation.java

public class Instrumentation {
    ...
    public ActivityResult execStartActivity(Context who, 
        IBinder contextThread, IBinder token, Activity target,
        Intent intent, int requestCode, 
        Bundle options){
            IApplicationThread whoThread = 
                (IApplicationThread) contextThread;
            ...
            try {
                ...
                int result = ActivityManagerNative.getDefault()
                    .startActivity(whoThread, 
                        who.getBasePackageName(),
                        intent,
                        intent.resolveTypeIfNeeded(
                        who.getContentResolver()),
                        token, 
                        target != null ? 
                        target.mEmbeddedID : null,
                        requestCode, 0, null, options);
               ...
            } catch (RemoteException e) {
               ...
            }
            ...
    }
    ...
}

可以看到Instrumentation.execStartActivity主要是调用ActivityManagerNative类的静态成员函数getDefault获取一个ActivityManagerService的代理对象,然后调用ActivityManagerNative的成员函数startActivity去启动一个Activity组件

ActivityManagerNative.getDefault

/frameworks/base/core/java/android/app/ActivityManagerNative.java

public abstract class ActivityManagerNative extends Binder 
    implements IActivityManager{
        ...
        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);
        }
        
        private static final Singleton<IActivityManager> gDefault = 
            new Singleton<IActivityManager>() {
                protected IActivityManager create() {
                    IBinder b = ServiceManager.
                        getService("activity");
                    ...
                    IActivityManager am = asInterface(b);
                    ...
                    return am;
                }
        };
           
        static public IActivityManager getDefault() {
            return gDefault.get();
        }
        ...
}

step5:ActivityManagerProxy.startActivity

public abstract class ActivityManagerNative extends Binder 
    implements IActivityManager{
    ...
    class ActivityManagerProxy implements IActivityManager{
            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.writeInterfaceToken(IActivityManager.descriptor);
                    //对应Activity中的mMainThread.getApplicationThread()
                    data.writeStrongBinder(caller != null ? 
                        caller.asBinder() : null);
                    //包名
                    data.writeString(callingPackage);
                    intent.writeToParcel(data, 0);
                    data.writeString(resolvedType);
                    //对应ActivityManagerService中的ActivityRecord
                    data.writeStrongBinder(resultTo);
                    data.writeString(resultWho);
                    data.writeInt(requestCode);
                    data.writeInt(startFlags);
                    if (profilerInfo != null) {
                        data.writeInt(1);
                        profilerInfo.writeToParcel(
                            data, Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
                    } else {
                        data.writeInt(0);
                    }
                    if (options != null) {
                        data.writeInt(1);
                        options.writeToParcel(data, 0);
                    } else {
                        data.writeInt(0);
                    }
                    mRemote.transact(START_ACTIVITY_TRANSACTION, data, reply, 0);
                    reply.readException();
                    int result = reply.readInt();
                    reply.recycle();
                    data.recycle();
                    return result;
        }
    }
    ...
}

可以看到这个方法中,将前面传递过来的参数写入到Parcel对象data中,然后再通过ActivityManagerNativeProxy类内部的一个Binder代理对象mRemote向ActivityManagerService发送一个类型为START_ACTIVITY_TRANSACTION的进程间通信请求。
这里面参数虽然非常多,但是需要注意的点参数只有三个,分别是callerintentresultTocaller指向的是Launcher组件所运行在的应用程序进程的Appication对象;intent包含了即将启动的Activity组件信息;resultTo指向了ActivityManagerService内部的一个ActivityRecord对象,保存了Launcher组件的详细信息。

ActivityManagerService处理进程通信指令

以上的5个步骤都是在Launcher进程中执行,接下来的6-12部是在ActivityManagerService中进行的,主要用来处理Launcher组件发出的START_ACTIVITY_TRANSACTION的进程间通信请求。如下图所示:

image.png

step6:ActivityManagerService.startActivity

/frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

public final class ActivityManagerService extends ActivityManagerNative
        implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
        ...
        @Override
        public final int startActivity(IApplicationThread caller, 
            String callingPackage,Intent intent, String resolvedType, 
            IBinder resultTo, String resultWho, int requestCode,int startFlags, 
            ProfilerInfo profilerInfo, Bundle options) {
                //caller是Launcher应用中对应的ApplicationThread代理对象
                //callingPackage包名
                //intent携带要启动的Activity组件信息
                //resultTo指向ActivityRecord
                return startActivityAsUser(caller, callingPackage, intent, 
                    resolvedType, resultTo,resultWho, requestCode, startFlags, 
                    profilerInfo, options,UserHandle.getCallingUserId());
        }

        @Override
        public final int startActivityAsUser(IApplicationThread caller, 
            String callingPackage,Intent intent, String resolvedType, 
            IBinder resultTo, String resultWho, int requestCode,
            int startFlags, ProfilerInfo profilerInfo, Bundle options, int userId){
            ...
            userId = handleIncomingUser(Binder.getCallingPid(), 
                Binder.getCallingUid(),userId,false, ALLOW_FULL_ONLY, 
                "startActivity", null);
            // TODO: Switch to user app stacks here.
            return mStackSupervisor.startActivityMayWait(caller, -1, 
                callingPackage,intent,resolvedType, null, null, resultTo, 
                resultWho, requestCode, startFlags,profilerInfo, null, null, 
                options, false, userId, null, null);
        }
    ...
}

ActivityManagerService类的成员函数startActivity用来处理类型为START_ACTIVITY_TRANSACTION的进程间通信请求。
ActivityManagerService类有一个类型为ActivityStackSupervisor的成员变量mStackSupervisor,用来管理Activity组件的堆栈,上面ActivityManagerService.startActivityAsUser中最终调用的是ActivityStackSupervisor的startActivityMayWait,来进一步处理类型为START_ACTIVITY_TRANSACTION的进程间通信请求,即执行一个启动Activity组件的操作。

setp7:ActivityStackSupervisor.startActivityMayWait

/frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java

public final class ActivityStackSupervisor implements DisplayListener {
    final int startActivityMayWait(IApplicationThread caller, int callingUid,
        String callingPackage, Intent intent, String resolvedType,
        IVoiceInteractionSession voiceSession, 
        IVoiceInteractor voiceInteractor,
        IBinder resultTo, String resultWho, int requestCode, int startFlags,
        ProfilerInfo profilerInfo, WaitResult outResult, Configuration config,
        Bundle options, boolean ignoreTargetSecurity, int userId,
        IActivityContainer iContainer, TaskRecord inTask) {
           //解析Intent内容,获取更多即将启动的Activity的信息
           ...
           boolean componentSpecified = intent.getComponent() != null;

           // Don't modify the client's object!
           intent = new Intent(intent);
            
            // Collect information about the target of the Intent.
            ActivityInfo aInfo =
                    resolveActivity(intent, resolvedType, startFlags, 
                    profilerInfo, userId);
            ...
            synchronized (mService) {
                ...
                try {
                      ResolveInfo rInfo =
                          AppGlobals.getPackageManager().resolveIntent(
                                  intent, null,
                                  PackageManager.MATCH_DEFAULT_ONLY
                                  | ActivityManagerService.STOCK_PM_FLAGS, userId);
                      //将解析到的信息保存到类型为ActivityInfo的aInfo对象中
                      aInfo = rInfo != null ? rInfo.activityInfo : null;
                      aInfo = mService.getActivityInfoForUser(aInfo, userId);
                } catch (RemoteException e) {
                    ...
                }
                ...
            }
            
            //继续执行启动Activity组件的工作
            int res = startActivityLocked(caller, intent, resolvedType, aInfo,
                    voiceSession, voiceInteractor, resultTo, resultWho,
                    requestCode, callingPid, callingUid, callingPackage,
                    realCallingPid, realCallingUid, startFlags, 
                    options, ignoreTargetSecurity,
                    componentSpecified, null, container, inTask);
            ...
            return res;
        }
    }
    
    //解析Intent内容,并保存到aInfo中
    ActivityInfo resolveActivity(Intent intent, String resolvedType, int startFlags,
            ProfilerInfo profilerInfo, int userId) {
        ActivityInfo aInfo;
        try {
            ResolveInfo rInfo =
                AppGlobals.getPackageManager().resolveIntent(
                        intent, resolvedType,
                        PackageManager.MATCH_DEFAULT_ONLY
                                    | ActivityManagerService.STOCK_PM_FLAGS, userId);
            aInfo = rInfo != null ? rInfo.activityInfo : null;
        } catch (RemoteException e) {
            ...
        }
        ...
        return aInfo;
    }
}    

上面这层的调用分为两个部分:

step8:ActivityStackSupervisor.startActivityLocked

final int startActivityLocked(IApplicationThread caller,
    Intent intent, String resolvedType, ActivityInfo aInfo,
    IVoiceInteractionSession voiceSession, 
    IVoiceInteractor voiceInteractor,
    IBinder resultTo, String resultWho, int requestCode,
    int callingPid, int callingUid, String callingPackage,
    int realCallingPid, int realCallingUid, int startFlags, Bundle options,
    boolean ignoreTargetSecurity, boolean componentSpecified, 
    ActivityRecord[] outActivity,
    ActivityContainer container, TaskRecord inTask) {
        int err = ActivityManager.START_SUCCESS;
        //获取描述Launcher组件的ProcessRecord
        ProcessRecord callerApp = null;
        if (caller != null) {
            callerApp = mService.getRecordForAppLocked(caller);
            if (callerApp != null) {
                callingPid = callerApp.pid;
                callingUid = callerApp.info.uid;
            } else {
                ...
            }
        }
        ...
        //查找Launcher组件对应的ActivityRecord
        ActivityRecord sourceRecord = null;
        ...
        if (resultTo != null) {
            sourceRecord = isInAnyStackLocked(resultTo);
            ...
        }
        ...
        //创建描述即将启动的Activity组件的ActivityRecord
        ActivityRecord r = new ActivityRecord(mService, callerApp, 
            callingUid, callingPackage, intent, resolvedType, aInfo, 
            mService.mConfiguration, resultRecord, resultWho, requestCode, 
            componentSpecified, voiceSession != null, this, container, options);
        ...
        err = startActivityUncheckedLocked(r, sourceRecord, voiceSession, 
            voiceInteractor,startFlags, true, options, inTask);
        return err;
}

6.0下ActivityManagerService针对Activity堆栈存储分类

/** Mapping from displayId to display current state */
private final SparseArray<ActivityDisplay> mActivityDisplays = new SparseArray<>();

 
// Exactly one of these classes per Display in the system. 
// Capable of holding zero or more
// attached {@link ActivityStack}s 
class ActivityDisplay {
    /** Actual Display this object tracks. */
    //对应的ID
    int mDisplayId;
    /** All of the stacks on this display. Order matters, topmost stack is in front of all other stacks, bottommost behind. Accessed directly by ActivityManager package classes */
    //Activity栈
    final ArrayList<ActivityStack> mStacks = new ArrayList<ActivityStack>();
}

ActivityRecord isInAnyStackLocked(IBinder token) {
        int numDisplays = mActivityDisplays.size();
        for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
            ArrayList<ActivityStack> stacks = mActivityDisplays.
                valueAt(displayNdx).mStacks;
            for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
                final ActivityRecord r = stacks.get(stackNdx).
                        isInStackLocked(token);
                if (r != null) {
                    return r;
                }
            }
        }
        return null;
}       

setp9:ActivityStackSupervisor.startActivityUncheckedLocked

final int startActivityUncheckedLocked(final ActivityRecord r, 
    ActivityRecord sourceRecord,IVoiceInteractionSession voiceSession, 
    IVoiceInteractor voiceInteractor, int startFlags,boolean doResume, 
    Bundle options, TaskRecord inTask) {
        final Intent intent = r.intent;
        final int callingUid = r.launchedFromUid;
        ...
        //获取目标Activity组件的启动标识
        int launchFlags = intent.getFlags();
        ...
        // We'll invoke onUserLeaving before onPause only if the launching
        // activity did not explicitly state that this is an automated launch.
        //检查是否由用户手动启动
        mUserLeaving = (launchFlags & Intent.FLAG_ACTIVITY_NO_USER_ACTION) == 0;
        ...
        boolean addingToTask = false;
        ...
        ActivityStack sourceStack;
        ...
        boolean newTask = false;
        ...
         // Should this be considered a new task?
        if (r.resultTo == null && inTask == null && !addingToTask
                && (launchFlags & Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
                newTask = true;
                //创建或者计算将要启动的Actiivty组件的专属的TaskStack
                targetStack = computeStackFocus(r, newTask);
                targetStack.moveToFront("startingNewTask");
                ...
        }
        
        targetStack.startActivityLocked(r, newTask, doResume, keepCurTransition, options);
        return ActivityManager.START_SUCCESS;
}

ActivityStack.startActivityLocked

/frameworks/base/services/core/java/com/android/server/am/ActivityStack.java

1 final class ActivityStack {
2   ...
3   final void startActivityLocked(ActivityRecord r, boolean newTask,
4            boolean doResume, boolean keepCurTransition, Bundle options) {
        //获取目标Activity的专属任务描述TaskRecord
5       TaskRecord rTask = r.task;
6       final int taskId = rTask.taskId;
7        // mLaunchTaskBehind tasks get placed at the back of the task stack.
8        if (!r.mLaunchTaskBehind && (taskForIdLocked(taskId) == null || newTask)){
9             // Last activity in task had been removed or ActivityManagerService 
10            //is reusing task.
11            // Insert or replace.
12            // Might not even be in.
13            insertTaskAtTop(rTask, r);
14            mWindowManager.moveTaskToTop(taskId);
15         }
16     }
17     ...
18     if (doResume) {
19           mStackSupervisor.resumeTopActivitiesLocked(this, r, options);
20       }
21   ...
22 }

step10:ActivityStackSupervisor.resumeTopActivityLocked

/frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java

 boolean resumeTopActivitiesLocked(ActivityStack targetStack, 
    ActivityRecord target,Bundle targetOptions) {
    //上一步传入的targetStack不会是null,所以这不会执行
    if (targetStack == null) {
       targetStack = mFocusedStack;
    }
    // Do targetStack first.
    boolean result = false;
    //由于目标Activity组件的堆栈已经在上一步置顶,所以会执行这里
    if (isFrontStack(targetStack)) {
        result = targetStack.resumeTopActivityLocked(target, targetOptions);
    }
    //后续先不分析
    ...
    return result;
 }          

ActivityStack.resumeTopActivityLocked

final boolean resumeTopActivityLocked(ActivityRecord prev, Bundle options) {
    ...
    try{
        ...
        result = resumeTopActivityInnerLocked(prev, options);
    }finally{
    }
    ...
}

继续跟进ActivityStack的成员函数resumeTopActivityInnerLocked

1 private boolean resumeTopActivityInnerLocked(ActivityRecord prev,Bundle options){
      //获取待启动的Activity组件
2     ...
3     // Find the first activity that is not finishing.
4     final ActivityRecord next = topRunningActivityLocked(null);
5    
6     // Remember how we'll process this pause/resume situation, 
7     // and ensure that the state is reset however we wind up proceeding.
8     final boolean userLeaving = mStackSupervisor.mUserLeaving;
9     mStackSupervisor.mUserLeaving = false;
10    ...
11    // If the top activity is the resumed one, nothing to do.
12    if (mResumedActivity == next && next.state == ActivityState.RESUMED &&
13          mStackSupervisor.allResumedActivitiesComplete()) {
14       ...
15       return false;   
16   }
17    ...
18    // If we are sleeping, and there is no resumed activity, and the top
19    // activity is paused, well that is the state we want.
20    if (mService.isSleepingOrShuttingDown()
21            && mLastPausedActivity == next
22            && mStackSupervisor.allPausedActivitiesComplete()) {
23      // Make sure we have executed any pending transitions, since there
24      // should be nothing left to do at this point.
25      mWindowManager.executeAppTransition();
26      mNoAnimActivities.clear();
27      ActivityOptions.abort(options);
28      return false;
29    }
30    ...
31    // If we are currently pausing an activity, then don't do anything
32    // until that is done.
33    if (!mStackSupervisor.allPausedActivitiesComplete()) {
34        return false;
35    }
36    ...
37    // We need to start pausing the current activity so the top one
38    // can be resumed...
39    ...
40    boolean pausing = mStackSupervisor.pauseBackStacks(userLeaving, true,
41          dontWaitForPause);
42    if (mResumedActivity != null) {
43      ...
44      pausing |= startPausingLocked(userLeaving, false, true, dontWaitForPause);
45    }
46    if (pausing) {
47      return true;
48    }
49    ...
50 }

step11:ActiviyStack.startPausingLocked

final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping, 
    boolean resuming,boolean dontWait) {
    ...
    //mResumedActivity当前指向的是Launcher组件
    ActivityRecord prev = mResumedActivity;
    ...
    mResumedActivity = null;
    mPausingActivity = prev;
    mLastPausedActivity = prev;
    ...
    prev.state = ActivityState.PAUSING;
    ...
    if (prev.app != null && prev.app.thread != null) {
        try {
            ...
            prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing,
                userLeaving, prev.configChangeFlags, dontWait);
        } catch (Exception e) {
            ...
        }
    }else{
        ...
    }
    ...
    if (mPausingActivity != null) {
       ...
       if(dontWait){
            ...
       } else{
            // Have the window manager pause its key dispatching until the new
            // activity has started.  If we're pausing the activity just because
            // the screen is being turned off and the UI is sleeping, don't interrupt
            // key dispatch; the same activity will pick it up again on wakeup.
            Message msg = mHandler.obtainMessage(PAUSE_TIMEOUT_MSG);
            msg.obj = prev;
            prev.pauseTime = SystemClock.uptimeMillis();
            mHandler.sendMessageDelayed(msg, PAUSE_TIMEOUT);
            return true;
       }
   }else{
       ...
   }        
}

step12:ApplicationThreadProxy.schedulePauseActivity

/frameworks/base/core/java/android/app/ApplicationThreadNative.java

public abstract class ApplicationThreadNative extends Binder
        implements IApplicationThread {
        ...
        class ApplicationThreadProxy implements IApplicationThread {
                ...
                public final void schedulePauseActivity(IBinder token, 
                    boolean finished, boolean userLeaving, int configChanges, 
                    boolean dontReport) throws RemoteException {
                        Parcel data = Parcel.obtain();
                        data.writeInterfaceToken(IApplicationThread.descriptor);
                        data.writeStrongBinder(token);
                        data.writeInt(finished ? 1 : 0);
                        data.writeInt(userLeaving ? 1 :0);
                        data.writeInt(configChanges);
                        data.writeInt(dontReport ? 1 : 0);
                        mRemote.transact(SCHEDULE_PAUSE_ACTIVITY_TRANSACTION, data, 
                            null,IBinder.FLAG_ONEWAY);
                        data.recycle();
                }
                ...
        }
        ...
}

小总结

step13: ActivityThread.schedulePauseActivity

/frameworks/base/core/java/android/app/ActivityThread.java

public final class ActivityThread {
    ...
    private class ApplicationThread extends ApplicationThreadNative {
        ...
        public final void schedulePauseActivity(IBinder token, boolean finished,
                boolean userLeaving, int configChanges, boolean dontReport) {
            sendMessage(
                    finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,
                    token,
                    (userLeaving ? 1 : 0) | (dontReport ? 2 : 0),
                    configChanges);
        }
        ...
    }
    ...
}   

step13:ActivityThread.sendMessage

/frameworks/base/core/java/android/app/ActivityThread.java

public final class ActivityThread {
    ...
    final H mH = new H();
    ...
    private void sendMessage(int what, Object obj, int arg1, int arg2) {
        sendMessage(what, obj, arg1, arg2, false);
    }

    private void sendMessage(int what, Object obj, int arg1, int arg2, 
        boolean async) {
        ...
        Message msg = Message.obtain();
        msg.what = what;
        msg.obj = obj;
        msg.arg1 = arg1;
        msg.arg2 = arg2;
        if (async) {
            msg.setAsynchronous(true);
        }
        mH.sendMessage(msg);
    }
}   

step15:H.handleMessage

/frameworks/base/core/java/android/app/ActivityThread.java

...
private class H extends Handler {

    ...
    public void handleMessage(Message msg) {
        ...
        switch (msg.what) {
            ...
            case PAUSE_ACTIVITY:
                ...
                handlePauseActivity((IBinder)msg.obj, false, 
                    (msg.arg1&1) != 0, msg.arg2,(msg.arg1&2) != 0);
                ...
                break;
            ...
        }   
        ...
    }
    ...
}
...

step16:ActivityThead.handlePauseActivity

public final class ActivityThread {
    ...
    final ArrayMap<IBinder, ActivityClientRecord> mActivities = 
            new ArrayMap<>();
    ...
    private void handlePauseActivity(IBinder token, boolean finished,
           boolean userLeaving, int configChanges, boolean dontReport) {
        ActivityClientRecord r = mActivities.get(token);
        if (r != null) {
            //Slog.v(TAG, "userLeaving=" + userLeaving + " handling pause of " + r);
            if (userLeaving) {
                performUserLeavingActivity(r);
            }

            r.activity.mConfigChangeFlags |= configChanges;
            performPauseActivity(token, finished, r.isPreHoneycomb());

            // Make sure any pending writes are now committed.
            if (r.isPreHoneycomb()) {
                QueuedWork.waitToFinish();
            }

            // Tell the activity manager we have paused.
            if (!dontReport) {
                try {
                    ActivityManagerNative.getDefault().activityPaused(token);
                } catch (RemoteException ex) {
                }
            }
            mSomeActivitiesChanged = true;
        }
    }
    ...
}

setp17:ActivityManagerProxy.activityPaused

ActivityManagerNative.getDefault()最终获取得到的对象是一个类型为ActivityManagerProxy的对象
/frameworks/base/core/java/android/app/ActivityManagerNative.java

class ActivityManagerProxy implements IActivityManager{
    ...
    public void activityPaused(IBinder token) throws RemoteException{
       Parcel data = Parcel.obtain();
       Parcel reply = Parcel.obtain();
       data.writeInterfaceToken(IActivityManager.descriptor);
       data.writeStrongBinder(token);
       mRemote.transact(ACTIVITY_PAUSED_TRANSACTION, data, reply, 0);
       reply.readException();
       data.recycle();
       reply.recycle();
    }
    ...
}

step18:ActivityManagerService.activityPaused

/frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

public final class ActivityManagerService extends ActivityManagerNative
        implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
    ...
    @Override
    public final void activityPaused(IBinder token) {
        ...
        synchronized(this) {
            //根据传入的token找到Launcher组件对应的ActivityStack
            ActivityStack stack = ActivityRecord.getStackLocked(token);
            if (stack != null) {
                stack.activityPausedLocked(token, false);
            }
        }
        ...
    }
    ...
}

setp19:ActivityStack.activityPausedLocked

/frameworks/base/services/core/java/com/android/server/am/ActivityStack.java

final class ActivityStack {
    ...
    final void activityPausedLocked(IBinder token, boolean timeout) {
        ...
        final ActivityRecord r = isInStackLocked(token);
        if (r != null) {
            mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
            if (mPausingActivity == r) {
                ...
                completePauseLocked(true);
            }else{
                ...
            }
        }
    }
    ...
}

step20:ActivityStack.completePauseLocked

/frameworks/base/services/core/java/com/android/server/am/ActivityStack.java

final class ActivityStack {
    ...
    private void completePauseLocked(boolean resumeNext) {
        //获取Launcher组件对应的ActivityRecord
        ActivityRecord prev = mPausingActivity;
        if (prev != null) {
            prev.state = ActivityState.PAUSED;
            ...
            mPausingActivity = null;
        }
        //前面传入的resumeNext == true
        if (resumeNext) {
            final ActivityStack topStack = mStackSupervisor.getFocusedStack();
            if (!mService.isSleepingOrShuttingDown()) {
                mStackSupervisor.resumeTopActivitiesLocked(topStack, 
                    prev, null);
            }else{
                ...
            }
        }
    }
    ...
}

ActivityStackSupervisor.resumeTopActivitiesLocked

/frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java

public final class ActivityStackSupervisor implements DisplayListener {
    ...
    boolean resumeTopActivitiesLocked(ActivityStack targetStack, 
        ActivityRecord target,Bundle targetOptions) {
        ...
        //targetStack上一步传入也就是即将要启动的应用的Activity组件堆栈
        // Do targetStack first.
        boolean result = false;
        if (isFrontStack(targetStack)) {
            result = targetStack.resumeTopActivityLocked(target, targetOptions);
        }
        for (int displayNdx = mActivityDisplays.size() - 1; 
            displayNdx >= 0;--displayNdx) {
            final ArrayList<ActivityStack> stacks = 
                mActivityDisplays.valueAt(displayNdx).mStacks;
            for (int stackNdx = stacks.size() - 1; stackNdx >= 0; 
                --stackNdx) {
                final ActivityStack stack = stacks.get(stackNdx);
                if (stack == targetStack) {
                    // Already started above.
                    continue;
                }
                if (isFrontStack(stack)) {
                    stack.resumeTopActivityLocked(null);
                }
            }
        }
        return result;
    }   
    ...
}

ActivityStack.resumeTopActivityLocked

final boolean resumeTopActivityLocked(ActivityRecord prev) {
    return resumeTopActivityLocked(prev, null);
}

final boolean resumeTopActivityLocked(ActivityRecord prev, Bundle options) {
    ...
    boolean result = false;
    try{
        ...
        result = resumeTopActivityInnerLocked(prev, options);
    }finally{
        ...
    }
    return result;
    ...
}

private boolean resumeTopActivityInnerLocked(ActivityRecord prev, 
    Bundle options) {
    ...
    // Find the first activity that is not finishing.
    final ActivityRecord next = topRunningActivityLocked(null);
    ...
    
    // We need to start pausing the current activity so the top one
    // can be resumed...
    boolean dontWaitForPause = (next.info.flags&
        ActivityInfo.FLAG_RESUME_WHILE_PAUSING) != 0;
    boolean pausing = mStackSupervisor.
        pauseBackStacks(userLeaving, true, dontWaitForPause);
    if (mResumedActivity != null) {
        ...
        pausing |= startPausingLocked(userLeaving, false, 
            true, dontWaitForPause);
    }
    if (pausing) {
        ...
        return true;
    }
    ...
    if (next.app != null && next.app.thread != null) {
        ...
    }else{
        ...
        mStackSupervisor.startSpecificActivityLocked(next, true, true);
    }
    return true;
}    

setp22:ActivityStackSupervisor.startSpecific

/frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java

public final class ActivityStackSupervisor implements DisplayListener {
    ... 
    void startSpecificActivityLocked(ActivityRecord r,
            boolean andResume, boolean checkConfig){
        // Is this activity's application already running?
        ProcessRecord app = mService.getProcessRecordLocked(r.processName,
                r.info.applicationInfo.uid, true);
        ...
        if (app != null && app.thread != null) {
            ...
            try{
                ...
                realStartActivityLocked(r, app, andResume, checkConfig);
                return;
            }catch(RemoteException e){
                ...
            }
        }
        mService.startProcessLocked(r.processName, 
            r.info.applicationInfo, 
            true, 0,"activity", r.intent.getComponent(),
            false, false, true);
    } 
    ...          
}

ActivityManagerService.startProcessLocked

/frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

public final class ActivityManagerService extends ActivityManagerNative
    implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
    ...
    final ProcessRecord startProcessLocked(String processName,
    ApplicationInfo info, boolean knownToBeDead, int intentFlags,
    String hostingType, ComponentName hostingName, 
    boolean allowWhileBooting,
    boolean isolated, boolean keepIfLarge) {
        return startProcessLocked(processName, info, knownToBeDead, 
                intentFlags, hostingType,hostingName, 
                allowWhileBooting, isolated, 0 /* isolatedUid */, 
                keepIfLarge,
                null /* ABI override */, 
                null /* entryPoint */, 
                null /* entryPointArgs */,
                null /* crashHandler */);
    }
    
    final ProcessRecord startProcessLocked(String processName, 
        ApplicationInfo info,boolean knownToBeDead, int intentFlags, 
        String hostingType, ComponentName hostingName,
        boolean allowWhileBooting, boolean isolated, 
        int isolatedUid, boolean keepIfLarge, String abiOverride, 
        String entryPoint, String[] entryPointArgs, 
        Runnable crashHandler){
        ...
        ProcessRecord app;
        //前面传入的islated = false
        if (!isolated) {
            //检查请求的进程是否已经存在
            app = getProcessRecordLocked(processName, info.uid, keepIfLarge);
            ...
        else{
            ...
        }
        String hostingNameStr = hostingName != null
            ? hostingName.flattenToShortString() : null;
        if (app == null) {
            ...
            app = newProcessRecordLocked(info, processName, 
                isolated, isolatedUid);
            ...
        }else{
            ...
        }
        ...
        startProcessLocked(app, hostingType, hostingNameStr, 
            abiOverride, entryPoint, entryPointArgs);
        return (app.pid != 0) ? app : null;    
    }
    ...
}
/**
* All of the processes we currently have running organized by pid.
* The keys are the pid running the application.
*
* <p>NOTE: This object is protected by its own lock, NOT the global
* activity manager lock!
*/
final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();

private final void startProcessLocked(ProcessRecord app, 
    String hostingType,String hostingNameStr, String abiOverride, 
    String entryPoint, String[] entryPointArgs) {
    ...
    try{
        ...
        //获取应用的uid
        int uid = app.uid;
        //获取应用的用户组id
        int[] gids = null;
        if (!app.isolated) {
                  int[] permGids = null;
                  try {
                      final IPackageManager pm = AppGlobals.
                      getPackageManager();
                      permGids = pm.
                       getPackageGids(app.info.packageName, app.userId);
                      MountServiceInternal mountServiceInternal = 
                       LocalServices.
                       getService(MountServiceInternal.class);
                      mountExternal = mountServiceInternal.
                       getExternalStorageMountMode(uid,
                              app.info.packageName);
                  } catch (RemoteException e) {
                      ...
                  }
            
                  // Add shared application and profile GIDs  
                  // so applications can share some
                  // resources like shared libraries and access 
                  // user-wide resources
                  if (ArrayUtils.isEmpty(permGids)) {
                      gids = new int[2];
                  } else {
                      gids = new int[permGids.length + 2];
                      System.arraycopy(permGids, 0, gids, 2, 
                       permGids.length);
                  }
                  gids[0] = UserHandle.
                   getSharedAppGid(UserHandle.getAppId(uid));
                  gids[1] = UserHandle.
                   getUserGid(UserHandle.getUserId(uid));
              }
            ...
    int debugFlags = 0;
    ...
    app.gids = gids;
    app.requiredAbi = requiredAbi;
    app.instructionSet = instructionSet;
    // Start the process.  It will either succeed and return a 
    // result containing
    // the PID of the new process, or else throw a RuntimeException.
    //前面传入的entry==null = true
    boolean isActivityProcess = (entryPoint == null);
    //指定Process进程的入口
    if (entryPoint == null) entryPoint = "android.app.ActivityThread";
    ...
    Process.ProcessStartResult startResult = Process.
        start(entryPoint,app.processName, uid, uid, gids, 
        debugFlags, mountExternal,
        app.info.targetSdkVersion, app.info.seinfo, 
        requiredAbi, instructionSet,app.info.dataDir, entryPointArgs);
    ...
    app.setPid(startResult.pid);
    app.usingWrapper = startResult.usingWrapper;
    app.removed = false;
    app.killed = false;
    app.killedByAm = false;
    ...
    synchronized (mPidsSelfLocked) {
        this.mPidsSelfLocked.put(startResult.pid, app);
        if (isActivityProcess) {
             Message msg = mHandler.
                 obtainMessage(PROC_START_TIMEOUT_MSG);
                   msg.obj = app;
             mHandler.sendMessageDelayed(msg, 
                 startResult.usingWrapper
                 ? PROC_START_TIMEOUT_WITH_WRAPPER : 
                 PROC_START_TIMEOUT);
        }
    }
    ...
    }catch(RemoteException e){
        ...
    }
}

step24:ActivityThread.main

/frameworks/base/core/java/android/app/ActivityThread.java

public final class ActivityThread {
    ...
    public static void main(String[] args) {
        ...
        //创建 消息循环
        Looper.prepareMainLooper();
        
        //创建ActivityThread并向ActivityManagerService发送一个启动完成的通知
        ActivityThread thread = new ActivityThread();
        thread.attach(false);
        
        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }
        ...
        //通知完成以后当前进程进入消息循环的过程
        Looper.loop();
    }

    final ApplicationThread mAppThread = new ApplicationThread();

    private void attach(boolean system) {
        ...
        mSysytemThread = system;
        if(!system){
            ...
            final IActivityManager mgr = ActivityManagerNative.getDefault();
            tyr{
                mgr.attachApplication(mAppThread);
            }catch(RemoteException ex){
                ...
            }
            ...
        }
        ...
    }   
    ...
}

step25:ActivityManagerProxy.attachApplication

/frameworks/base/core/java/android/app/ActivityManagerNative.java

public abstract class ActivityManagerNative extends Binder implements IActivityManager{
    ...
    class ActivityManagerProxy implements IActivityManager{
        ...
        public void attachApplication(IApplicationThread app) 
            throws RemoteException{
            Parcel data = Parcel.obtain();
            Parcel reply = Parcel.obtain();
            data.writeInterfaceToken(IActivityManager.descriptor);
            data.writeStrongBinder(app.asBinder());
            mRemote.transact(ATTACH_APPLICATION_TRANSACTION, data, reply, 0);
            reply.readException();
            data.recycle();
            reply.recycle();
        }
        ...
        
    }
    ...

}

step26:ActivityManagerService.attachApplication

/frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

public final class ActivityManagerService extends ActivityManagerNative
    implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
    ...
    @Override
    public final void attachApplication(IApplicationThread thread) {
        synchronized (this) {
            int callingPid = Binder.getCallingPid();
            final long origId = Binder.clearCallingIdentity();
            attachApplicationLocked(thread, callingPid);
            Binder.restoreCallingIdentity(origId);
        }
    }
    ...   
}

step27:ActivityManagerService.attachApplicationLocked

/frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

public final class ActivityManagerService extends ActivityManagerNative
    implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
    ...
    private final boolean attachApplicationLocked(IApplicationThread thread,
        int pid) {
        
        // Find the application record that is being attached...  either via
        // the pid if we are running in multiple processes, or just pull the
        // next app record if we are emulating process with anonymous threads.
        ProcessRecord app;
        if (pid != MY_PID && pid >= 0) {
            synchronized (mPidsSelfLocked) {
                app = mPidsSelfLocked.get(pid);
            }
        }else{
            ...
        }
        ...
        final String processName = app.processName;
        ...
        //收集信息
        app.makeActive(thread, mProcessStats);
        app.curAdj = app.setAdj = -100;
        app.curSchedGroup = app.setSchedGroup = Process.THREAD_GROUP_DEFAULT;
        app.forcingToForeground = null;
        updateProcessForegroundLocked(app, false, false);
        app.hasShownUi = false;
        app.debugging = false;
        app.cached = false;
        app.killedByAm = false;
        //移除进程启动的消息
        mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
        boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
        ...
        // See if the top visible activity is waiting to run in this process...
        if (normalMode) {
            try {
                if (mStackSupervisor.attachApplicationLocked(app)) {
                    didSomething = true;
                }
            } catch (Exception e) {
                ...
            }
        }
    }   
    ...   
}

ActivityStackSupervisor.attacApplication

/frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java

public final class ActivityStackSupervisor implements DisplayListener {
    ...
    boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {
        final String processName = app.processName;
        boolean didSomething = false;
        for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; 
            --displayNdx) {
            ArrayList<ActivityStack> stacks = 
                mActivityDisplays.valueAt(displayNdx).mStacks;
            for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
                final ActivityStack stack = stacks.get(stackNdx);
                if (!isFrontStack(stack)) {
                    continue;
                }
                //找到即将要启动的Activity组件
                ActivityRecord hr = stack.topRunningActivityLocked(null);
                if (hr != null) {
                    if (hr.app == null && app.uid == hr.info.applicationInfo.uid
                            && processName.equals(hr.processName)) {
                        try {
                            if (realStartActivityLocked(hr, app, true, true)) {
                                didSomething = true;
                            }
                        } catch (RemoteException e) {
                            ...
                        }
                    }
                }
            }
        }
        ...
        return didSomething;
    }
    ...
}   

step 28:ActivityStackSupervisor.realStartActivityLocked

/frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java

public final class ActivityStackSupervisor implements DisplayListener {
    ...
    final boolean realStartActivityLocked(ActivityRecord r,
        ProcessRecord app, boolean andResume, boolean checkConfig)
        throws RemoteException {
        ...
        r.app = app;
        ...
        //将r所描述的Activity组件添加到参数app所描述的应用程序进程的Activity组件列表中
        int idx = app.activities.indexOf(r);
        if (idx < 0) {
            app.activities.add(r);
        }
        ...
        try {
            ...
            List<ResultInfo> results = null;
            List<ReferrerIntent> newIntents = null;
            //上一步传入的andResume == true
            if (andResume) {
                results = r.results;
                newIntents = r.newIntents;
            }
            ...
            app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
                System.identityHashCode(r), r.info, 
                new Configuration(mService.mConfiguration),
                new Configuration(stack.mOverrideConfig), 
                r.compat, r.launchedFromPackage,task.voiceInteractor, 
                app.repProcState, r.icicle, r.persistentState, results,
                newIntents, !andResume, mService.isNextTransitionForward(), 
                profilerInfo);
            ...
        } catch (RemoteException e) {
        }
        ...
        return true;
    }
    ... 
}

step29:ApplicationThreadProxy.scheduleLaunchActivity

/frameworks/base/core/java/android/app/ActivityThread.java

final class ActivityThead{
    ...
    class ApplicationThreadProxy extends ApplicaionThreadNative{
        ...
         // we use token to identify this activity without having to send the
        // activity itself back to the activity manager. (matters more with ipc)
        @Override
        public final void scheduleLaunchActivity(Intent intent, IBinder token, 
            int ident,ActivityInfo info, Configuration curConfig, 
            Configuration overrideConfig,
            CompatibilityInfo compatInfo, String referrer, 
            IVoiceInteractor voiceInteractor,
            int procState, Bundle state, PersistableBundle persistentState,
            List<ResultInfo> pendingResults, 
            List<ReferrerIntent> pendingNewIntents,
            boolean notResumed, boolean isForward, ProfilerInfo profilerInfo) {
            ...
            ActivityClientRecord r = new ActivityClientRecord();

            r.token = token;
            r.ident = ident;
            r.intent = intent;
            r.referrer = referrer;
            r.voiceInteractor = voiceInteractor;
            r.activityInfo = info;
            r.compatInfo = compatInfo;
            r.state = state;
            r.persistentState = persistentState;

            r.pendingResults = pendingResults;
            r.pendingIntents = pendingNewIntents;

            r.startsNotResumed = notResumed;
            r.isForward = isForward;

            r.profilerInfo = profilerInfo;

            r.overrideConfig = overrideConfig;
            updatePendingConfiguration(curConfig);

            sendMessage(H.LAUNCH_ACTIVITY, r);
        }
        ...
    }
    ...
}

step 30:ActivityThread&&H.handleMessage

/frameworks/base/core/java/android/app/ActivityThread.java

final class ActivityThead{
    ...
    private class H extends Handler {
        ...
        public void handleMessage(Message msg) {
            ...
            switch (msg.what) {
                case LAUNCH_ACTIVITY:{
                    final ActivityClientRecord r = (ActivityClientRecord) msg.obj;
                    //解析包名
                    r.packageInfo = getPackageInfoNoCheck(
                            r.activityInfo.applicationInfo, r.compatInfo);
                    handleLaunchActivity(r, null);
                }break;
        }
    }
    ...
    
    public final LoadedApk peekPackageInfo(String packageName, boolean includeCode) {
        synchronized (mResourcesManager) {
            WeakReference<LoadedApk> ref;
            if (includeCode) {
                ref = mPackages.get(packageName);
            } else {
                ref = mResourcePackages.get(packageName);
            }
            return ref != null ? ref.get() : null;
        }
    }
}

step 31:ActivityThread.handlLaunchActivity

/frameworks/base/core/java/android/app/ActivityThread.java

final class ActivityThead{
    ...
    private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        ...
        Activity a = performLaunchActivity(r, customIntent);
        if (a != null) {
            r.createdConfig = new Configuration(mConfiguration);
            Bundle oldState = r.state;
            //后续会引起一些列的onResume相关的生命周期相关的操作
            handleResumeActivity(r.token, false, r.isForward,
                    !r.activity.mFinished && !r.startsNotResumed);
            ..
        }else{
            // If there was an error, for any reason, tell the activity
            // manager to stop us.
            try {
                ActivityManagerNative.getDefault()
                    .finishActivity(r.token, Activity.RESULT_CANCELED, null, false);
            } catch (RemoteException ex) {
                // Ignore
            }
        }        
        ...
    }
    ...
}

step 32:ActivityThread.performLaunchActivity

/frameworks/base/core/java/android/app/ActivityThread.java

final class ActivityThead{
    ...
    private Activity performLaunchActivity(ActivityClientRecord r, 
        Intent customIntent){
        
        ...
        //获取要启动的MainActivity信息
        ComponentName component = r.intent.getComponent();
        ...
        //加载要启动的MainActivity组件的类文件
        try {
            java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
            activity = mInstrumentation.newActivity(
                cl, component.getClassName(), r.intent);
            ...
        catch(Exception e){
            ...
        }     
    
        try {
            Application app = r.packageInfo.makeApplication(false, mInstrumentation);
            ...
            if (activity != null) {
                //创建上下文运行环境
                Context appContext = createBaseContextForActivity(r, activity);
                CharSequence title = 
                    r.activityInfo.loadLabel(appContext.getPackageManager());
                Configuration config = new Configuration(mCompatConfiguration);
                ...
                //基础信息的保存
                activity.attach(appContext, this, getInstrumentation(), r.token,
                        r.ident, app, r.intent, r.activityInfo, title, r.parent,
                        r.embeddedID, r.lastNonConfigurationInstances, config,
                        r.referrer, r.voiceInteractor);
                ...
                if (r.isPersistable()) {
                    mInstrumentation.callActivityOnCreate(activity, 
                        r.state, r.persistentState);
                } else {
                    mInstrumentation.callActivityOnCreate(activity, r.state);
                }
                ...
            }
            ...
            mActivities.put(r.token, r);
        }catch(SuperNotCalledException e){
            ...
        }catch(Exception e){
            ...
        }
    }
    return activity;
}
上一篇 下一篇

猜你喜欢

热点阅读