Activity启动流程1

本文详细剖析了从Launcher启动Activity的整个流程,包括startActivitySafely、execStartActivity、ActivityManagerService的角色以及Activity的创建和启动过程,涵盖从应用进程到系统服务的交互和Activity生命周期的关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

从Launcher启动页启动Activity

1、startActivitySafely

packages\apps\Launcher2\src\com\android\launcher2\Launcher.java

    void startActivitySafely(Intent intent, Object tag) {
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//启动标志位设置为NEW_TASK以便activity可以在一个新的任务中启动
        try {
        try {
            startActivity(intent);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
            Log.e(TAG, "Unable to launch. tag=" + tag + " intent=" + intent, e);
        } catch (SecurityException e) {
            Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
            Log.e(TAG, "Launcher does not have the permission to launch " + intent +
                    ". Make sure to create a MAIN intent-filter for the corresponding activity " +
                    "or use the exported attribute for this activity. "
                    + "tag="+ tag + " intent=" + intent, e);
        }
    }

在Launcher页面点击启动图标时调用startActivitySafely来启动这个应用程序的根Activity,根Activity的信息包含在intent中。

2、startActivity

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

    @Override
    public void startActivity(Intent intent) {
        startActivityForResult(intent, -1);//-1表示不需要知道即将启动的Activity组件的执行结果
    }

3、startActivityForResult
    public void startActivityForResult(Intent intent, int requestCode) {
        if (mParent == null) {
			//Instrumentation用来监控应用程序与系统之间的交互
            Instrumentation.ActivityResult ar =
            //mMainThread.getApplicationThread()得到类型为AppliactionThread的Binder本地对象,将它传递给ActivityManagerService用于进程间通信
            //mToken类型是IBinder,它是一个Binder代理对象,指向ActivityManagerService中类型为ActivityRecord的Binder本地对象,用来维护对应的Activity组件的运行状态以及信息
                mInstrumentation.execStartActivity(
                    this, mMainThread.getApplicationThread(), mToken, this,
                    intent, requestCode);
            if (ar != null) {
				//成员变量mMainThread为ActivityThread,用来描述一个应用进程
                mMainThread.sendActivityResult(
                    mToken, mEmbeddedID, requestCode, ar.getResultCode(),
                    ar.getResultData());
            }
            if (requestCode >= 0) {
                mStartedActivity = true;
            }
        } else {
        }
    }
4、execStartActivity
    public ActivityResult execStartActivity(
        Context who, IBinder contextThread, IBinder token, Activity target,
        Intent intent, int requestCode) {
        IApplicationThread whoThread = (IApplicationThread) contextThread;
 
        try {
            int result = ActivityManagerNative.getDefault()//获得ActivityManagerService的代理对象
                .startActivity(whoThread, intent,
                        intent.resolveTypeIfNeeded(who.getContentResolver()),
                        null, 0, token, target != null ? target.mEmbeddedID : null,
                        requestCode, false, false);
            checkStartActivityResult(result, intent);
        } catch (RemoteException e) {
        }
        return null;
    }
    static public IActivityManager getDefault()
    {
        if (gDefault != null) {
            return gDefault;
        }
        IBinder b = ServiceManager.getService("activity");
        return gDefault;
    }
5、startActivity

frameworks\base\core\java\android\app\ActivityManagerNative.ActivityManagerProxy.java

    //(whoThread, intent,intent.resolveTypeIfNeeded(who.getContentResolver()),null, 
    //0, token, target != null ? target.mEmbeddedID : null,requestCode, false, false)
    //caller为应用进程的ApplicationThread对象,intent包含要启动的Activity组件信息,
    //resultTo指向ActivityManagerService内的一个ActivityRecord对象
    public int startActivity(IApplicationThread caller, Intent intent,
            String resolvedType, Uri[] grantedUriPermissions, int grantedMode,
            IBinder resultTo, String resultWho,
            int requestCode, boolean onlyIfNeeded,
            boolean debug) throws RemoteException {
        Parcel data = Parcel.obtain();
        Parcel reply = Parcel.obtain();
        data.writeInterfaceToken(IActivityManager.descriptor);
        data.writeStrongBinder(caller != null ? caller.asBinder() : null);
        intent.writeToParcel(data, 0);
        data.writeString(resolvedType);
        data.writeTypedArray(grantedUriPermissions, 0);
        data.writeInt(grantedMode);
        data.writeStrongBinder(resultTo);
        data.writeString(resultWho);
        data.writeInt(requestCode);
        data.writeInt(onlyIfNeeded ? 1 : 0);
        data.writeInt(debug ? 1 : 0);
        mRemote.transact(START_ACTIVITY_TRANSACTION, data, reply, 0);
        reply.readException();
        int result = reply.readInt();
        reply.recycle();
        data.recycle();
        return result;
    }

向ActivityManagerService发送START_ACTIVITY_TRANSACTION进程间通信请求。

以上5步都是在Launcher应用进程中执行的。

6、onTransact

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

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);
            Intent intent = Intent.CREATOR.createFromParcel(data);
            String resolvedType = data.readString();
            Uri[] grantedUriPermissions = data.createTypedArray(Uri.CREATOR);
            int grantedMode = data.readInt();
            IBinder resultTo = data.readStrongBinder();
            String resultWho = data.readString();    
            int requestCode = data.readInt();
            boolean onlyIfNeeded = data.readInt() != 0;
            boolean debug = data.readInt() != 0;
            int result = startActivity(app, intent, resolvedType,
                    grantedUriPermissions, grantedMode, resultTo, resultWho,
                    requestCode, onlyIfNeeded, debug);
            reply.writeNoException();
            reply.writeInt(result);
            return true;
        }
      }
}
    public final int startActivity(IApplicationThread caller,
            Intent intent, String resolvedType, Uri[] grantedUriPermissions,
            int grantedMode, IBinder resultTo,
            String resultWho, int requestCode, boolean onlyIfNeeded,
            boolean debug) {
            //mMainStack描述一个Activity组件堆栈
        return mMainStack.startActivityMayWait(caller, intent, resolvedType,
                grantedUriPermissions, grantedMode, resultTo, resultWho,
                requestCode, onlyIfNeeded, debug, null, null);
    }
7、startActivityMayWait

frameworks\base\services\java\com\android\server\am\ActivityStack.java

    final int startActivityMayWait(IApplicationThread caller,
            Intent intent, String resolvedType, Uri[] grantedUriPermissions,
            int grantedMode, IBinder resultTo,
            String resultWho, int requestCode, boolean onlyIfNeeded,
            boolean debug, WaitResult outResult, Configuration config) {
        // Refuse possible leaked file descriptors
        if (intent != null && intent.hasFileDescriptors()) {
            throw new IllegalArgumentException("File descriptors passed in Intent");
        }

        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;
        try {
            ResolveInfo rInfo =
                AppGlobals.getPackageManager().resolveIntent(
                        intent, resolvedType,
                        PackageManager.MATCH_DEFAULT_ONLY
                        | ActivityManagerService.STOCK_PM_FLAGS);//到Package管理服务中去解析intent的内容,以便获得更多即将启动的Activity信息
            aInfo = rInfo != null ? rInfo.activityInfo : null;
        } catch (RemoteException e) {
            aInfo = null;
        }

        if (aInfo != null) {
            // Store the found target back into the intent, because now that
            // we have it we never want to do this again.  For example, if the
            // user navigates back to this point in the history, we should
            // always restart the exact same activity.
            intent.setComponent(new ComponentName(
                    aInfo.applicationInfo.packageName, aInfo.name));
        }

        synchronized (mService) {
            
            int res = startActivityLocked(caller, intent, resolvedType,
                    grantedUriPermissions, grantedMode, aInfo,
                    resultTo, resultWho, requestCode, callingPid, callingUid,
                    onlyIfNeeded, componentSpecified);
            
            return res;
        }
    }
8、startActivityLocked
    final int startActivityLocked(IApplicationThread caller,
            Intent intent, String resolvedType,
            Uri[] grantedUriPermissions,
            int grantedMode, ActivityInfo aInfo, IBinder resultTo,
            String resultWho, int requestCode,
            int callingPid, int callingUid, boolean onlyIfNeeded,
            boolean componentSpecified) {

        int err = START_SUCCESS;

        ProcessRecord callerApp = null;//每一个应用程序进程都是用一个ProcessRecord来描述,并保存在ActivityManagerService内部
        if (caller != null) {
            callerApp = mService.getRecordForAppLocked(caller);
            if (callerApp != null) {
                callingPid = callerApp.pid;//进程的pid
                callingUid = callerApp.info.uid;//进程的uid
            } else {
            }
        }

        ActivityRecord sourceRecord = null;
        ActivityRecord resultRecord = null;
        if (resultTo != null) {
            int index = indexOfTokenLocked(resultTo);
            if (DEBUG_RESULTS) Slog.v(
                TAG, "Sending result to " + resultTo + " (index " + index + ")");
            if (index >= 0) {
                sourceRecord = (ActivityRecord)mHistory.get(index);//mHistory描述系统的Activity组件堆栈,在这个堆栈中每一个已启动的Activity都使用一个ActivityRecord来描述
                if (requestCode >= 0 && !sourceRecord.finishing) {
                    resultRecord = sourceRecord;
                }
            }
        }
        
        ActivityRecord r = new ActivityRecord(mService, this, callerApp, callingUid,
                intent, resolvedType, aInfo, mService.mConfiguration,
                resultRecord, resultWho, requestCode, componentSpecified);//描述即将要启动的Activity

        return startActivityUncheckedLocked(r, sourceRecord,
                grantedUriPermissions, grantedMode, onlyIfNeeded, true);
    }

得到请求ActivityManagerService执行启动Activity组件操作的源Activity组件和目标Activity组件信息,分别保存在ActivityRecord对象sourceRecord和r中。

9、startActivityUncheckedLocked
    final int startActivityUncheckedLocked(ActivityRecord r,
            ActivityRecord sourceRecord, Uri[] grantedUriPermissions,
            int grantedMode, boolean onlyIfNeeded, boolean doResume) {
        final Intent intent = r.intent;
        final int callingUid = r.launchedFromUid;
        
        int launchFlags = intent.getFlags();//得到目标Activity的启动标志位
        
        // 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;//判断目标组件是否由用户手动启动,1不是,0是其源Activity会获得一个用户离开事件通知
        if (DEBUG_USER_LEAVING) Slog.v(TAG,
                "startActivity() => mUserLeaving=" + mUserLeaving);
        
        // If the caller has asked not to resume at this point, we make note
        // of this in the record so that we can skip it when trying to find
        // the top running activity.
        if (!doResume) {
            r.delayedResume = true;
        }
        if (sourceRecord == null) {
            // This activity is not being started from another...  in this
            // case we -always- start a new task.
            if ((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {//是否需要创建新任务
                Slog.w(TAG, "startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: "
                      + intent);
                launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
            }
        } else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
            // The original activity who is starting us is running as a single
            // instance...  this new activity it is starting must go on its
            // own task.
            launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
        } else if (r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE
                || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
            // The activity being started is a single instance...  it always
            // gets launched into its own task.
            launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
        }

        boolean addingToTask = false;//标记是否要为目标Activity创建专属任务

        boolean newTask = false;

        // Should this be considered a new task?
        if (r.resultTo == null && !addingToTask
                && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
            // todo: should do better management of integers.
            mService.mCurTask++;
            if (mService.mCurTask <= 0) {
                mService.mCurTask = 1;
            }
            r.task = new TaskRecord(mService.mCurTask, r.info, intent,
                    (r.info.flags&ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0);//为目标Activity创建专属任务
            newTask = true;
            if (mMainStack) {
                mService.addRecentTaskLocked(r.task);//将新创建的任务交给ActivityManagerService管理
            }
            
        } else if (sourceRecord != null) {
        } else {
        }

        startActivityLocked(r, newTask, doResume);
        return START_SUCCESS;
    }
10、startActivityLocked
    private final void startActivityLocked(ActivityRecord r, boolean newTask,
            boolean doResume) {
        final int NH = mHistory.size();

        int addPos = -1;
        
        // Place a new activity at top of stack, so it is next to interact
        // with the user.
        if (addPos < 0) {
            addPos = NH;//将要添加ActivityRecord,发在Activity组件堆栈的最上面
        }
        // Slot the activity into the history stack and proceed
        mHistory.add(addPos, r);
        r.inHistory = true;
        r.frontOfTask = newTask;
        r.task.numActivities++;

        if (doResume) {
            resumeTopActivityLocked(null);
        }
    }
11、resumeTopActivityLocked
    final boolean resumeTopActivityLocked(ActivityRecord prev) {
        // Find the first activity that is not finishing.
        ActivityRecord next = topRunningActivityLocked(null);//得到Activity组件堆栈中最上面的不是处于结束状态的Activity组件

        // Remember how we'll process this pause/resume situation, and ensure
        // that the state is reset however we wind up proceeding.
        final boolean userLeaving = mUserLeaving;//判断是否要向源Activity发送用户离开事件通知
        mUserLeaving = false;

        if (next == null) {
            // There are no more activities!  Let's just start up the
            // Launcher...
            if (mMainStack) {
                return mService.startHomeActivityLocked();
            }
        }

        next.delayedResume = false;
        
        // If the top activity is the resumed one, nothing to do.
        if (mResumedActivity == next && next.state == ActivityState.RESUMED) {//判断要启动的Activity是否为当前被激活的Activity
            // Make sure we have executed any pending transitions, since there
            // should be nothing left to do at this point.
            mService.mWindowManager.executeAppTransition();
            mNoAnimActivities.clear();
            return false;//直接返回
        }

        // If we are sleeping, and there is no resumed activity, and the top
        // activity is paused, well that is the state we want.
        if ((mService.mSleeping || mService.mShuttingDown)//系统正要进入睡眠或关机状态
                && mLastPausedActivity == next && next.state == ActivityState.PAUSED) {//判断要启动的Activity是否为上次被终止的Activity
            // Make sure we have executed any pending transitions, since there
            // should be nothing left to do at this point.
            mService.mWindowManager.executeAppTransition();
            mNoAnimActivities.clear();
            return false;//直接返回,再启动Activity已经没有意义
        }
        
        // The activity may be waiting for stop, but that is no longer
        // appropriate for it.
        mStoppingActivities.remove(next);
        mWaitingVisibleActivities.remove(next);

        // If we are currently pausing an activity, then don't do anything
        // until that is done.
        if (mPausingActivity != null) {//检查系统当前是否正在暂停一个Activity,如果是,要等到它暂停完成后在启动Activity组件next
            if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: pausing=" + mPausingActivity);
            return false;
        }
        if (false) {
            } else {
                next.startTime = SystemClock.uptimeMillis();
                mLastStartedActivity = next;
            }
        }
        
        // We need to start pausing the current activity so the top one
        // can be resumed...
        if (mResumedActivity != null) {//当前系统激活的Activity不为null
            if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: need to start pausing");
            startPausingLocked(userLeaving, false);//通知它进入Paused状态,以便即将要启动的Activity获得焦点
            return true;
        }
12、startPausingLocked
    private final void startPausingLocked(boolean userLeaving, boolean uiSleeping) {

        ActivityRecord prev = mResumedActivity;//修改即将要进入Pausing状态的Activity组件状态

        mResumedActivity = null;
        mPausingActivity = prev;
        mLastPausedActivity = prev;
        prev.state = ActivityState.PAUSING;
        prev.task.touchActiveTime();

        mService.updateCpuStats();
        
        if (prev.app != null && prev.app.thread != null) {
            try {
				//向正在运行的Launcher组件发送一个暂停通知,以便正在运行的组件能够做一些数据保存操作,
				//Launcher组件处理完该状暂停通知后,必须向ActivityManagerService发送一个启动
				//启动MainActivity组件的通知,将位于Activity组件堆栈的MainActivity组件启动起来。但
				//ActivityManagerService不能无限制的等待
                prev.app.thread.schedulePauseActivity(prev, prev.finishing, userLeaving,
                        prev.configChangeFlags);
                if (mMainStack) {
                    mService.updateUsageStats(prev, false);
                }
            } catch (Exception e) {
            }
        } else {
            mPausingActivity = null;
            mLastPausedActivity = null;
        }

        if (mPausingActivity != null) {
            Message msg = mHandler.obtainMessage(PAUSE_TIMEOUT_MSG);
            msg.obj = prev;
			//如果Launcher组件没有再PAUSE_TIMEOUT时间内发送一个启动MainActivity组件的通知,
			//该消息将被处理,ActivityManagerService会认为Launcher组件没响应
            mHandler.sendMessageDelayed(msg, PAUSE_TIMEOUT);
            if (DEBUG_PAUSE) Slog.v(TAG, "Waiting for pause to complete...");
        } else {
            // This activity failed to schedule the
            // pause, so just treat it as being paused now.
            if (DEBUG_PAUSE) Slog.v(TAG, "Activity not running, resuming next.");
            resumeTopActivityLocked(null);
        }
    }

以上7步都是在ActivityManagerService中进行的。

13、schedulePauseActivity

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

    private final class ApplicationThread extends ApplicationThreadNative {
        private static final String HEAP_COLUMN = "%17s %8s %8s %8s %8s";
        private static final String ONE_COUNT_COLUMN = "%17s %8d";
        private static final String TWO_COUNT_COLUMNS = "%17s %8d %17s %8d";
        private static final String TWO_COUNT_COLUMNS_DB = "%20s %8d %20s %8d";
        private static final String DB_INFO_FORMAT = "  %8d %8d %14d  %s";

        // Formatting for checkin service - update version if row format changes
        private static final int ACTIVITY_THREAD_CHECKIN_VERSION = 1;

		//token为ActivityRecord, userLeaving表示用户是否正在离开当前Activity
		处理类型为SCHEDULE_PAUSE_ACTIVITY_TRANSACTION的进程间通信请求
        public final void schedulePauseActivity(IBinder token, boolean finished,
                boolean userLeaving, int configChanges) {
            queueOrSendMessage(
                    finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,
                    token,
                    (userLeaving ? 1 : 0),
                    configChanges);
        }
14、queueOrSendMessage
    final H mH = new H();
	private final void queueOrSendMessage(int what, Object obj, int arg1, int arg2) {
        synchronized (this) {
            Message msg = Message.obtain();
            msg.what = what;
            msg.obj = obj;
            msg.arg1 = arg1;
            msg.arg2 = arg2;
            mH.sendMessage(msg);//向应用程序的主线程发送消息
        }
    }

15、handleMessage
        public void handleMessage(Message msg) {
            if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + msg.what);
            switch (msg.what) {
                case PAUSE_ACTIVITY:
                    //将msg.obj强制转换成一个IBinder接口,因为它指向一个Binder代理对象
                    handlePauseActivity((IBinder)msg.obj, false, msg.arg1 != 0, msg.arg2);
                    maybeSnapshot();
                    break;
16、handlePauseActivity
    private final void handlePauseActivity(IBinder token, boolean finished,
            boolean userLeaving, int configChanges) {
        //应用进程中启动的每一个Activity都使用一个ActivityClientRecord对象来描述,
        //与AMS中的ActivityRecord对应
        //找到用来描述Launcher组件的ActivityClientRecord对象
        ActivityClientRecord r = mActivities.get(token);
        if (r != null) {
            //Slog.v(TAG, "userLeaving=" + userLeaving + " handling pause of " + r);
            if (userLeaving) {
                performUserLeavingActivity(r);//发送用户离开事件通知,即调用Activity的成员函数onUserLeaveHint
            }

            r.activity.mConfigChangeFlags |= configChanges;
            Bundle state = performPauseActivity(token, finished, true);//发送一个Pause事件通知,即调用Activity成员函数onPause

            // Make sure any pending writes are now committed.
            QueuedWork.waitToFinish();//等待完成前面的一些数据写入操作,因为不保证数据写入操作完成,等到Launcher重新进入Resumed状态时,就无法恢复之前保存的一些状态数据
            
            // Tell the activity manager we have paused.
            try {
                ActivityManagerNative.getDefault().activityPaused(token, state);//告诉ActivityManagerService Launcher组件已经进入Paused状态了,它可以把MainActivity启动起来了
            } catch (RemoteException ex) {
            }
        }
    }
17、activityPaused
    public void activityPaused(IBinder token, Bundle state) throws RemoteException
    {
        Parcel data = Parcel.obtain();
        Parcel reply = Parcel.obtain();
        data.writeInterfaceToken(IActivityManager.descriptor);
        data.writeStrongBinder(token);
        data.writeBundle(state);
        mRemote.transact(ACTIVITY_PAUSED_TRANSACTION, data, reply, 0);
        reply.readException();
        data.recycle();
        reply.recycle();
    }
18、activityPaused
    public final void activityPaused(IBinder token, Bundle icicle) {
        // Refuse possible leaked file descriptors
        if (icicle != null && icicle.hasFileDescriptors()) {
            throw new IllegalArgumentException("File descriptors passed in Bundle");
        }

        final long origId = Binder.clearCallingIdentity();
        mMainStack.activityPaused(token, icicle, false);
        Binder.restoreCallingIdentity(origId);
    }
19、activityPaused
    final void activityPaused(IBinder token, Bundle icicle, boolean timeout) {

        ActivityRecord r = null;

        synchronized (mService) {
            int index = indexOfTokenLocked(token);//根据ActivityRecord的代理对象token找到对应的ActivityRecord对象
            if (index >= 0) {
                r = (ActivityRecord)mHistory.get(index);
                if (!timeout) {
                    r.icicle = icicle;
                    r.haveState = true;
                }
                mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);//删除PAUSE_TIMEOUT_MSG消息,Launcher已在规定时间内完成中止通知了
                if (mPausingActivity == r) {//MPauseActivity指向Launcher组件对应的ActivityRecord,true
                    r.state = ActivityState.PAUSED;//Launcher组件已进入Paused状态了
                    completePauseLocked();//启动MainActivity组件
                } else {
                }
            }
        }
    }
20、completePauseLocked
    private final void completePauseLocked() {
        ActivityRecord prev = mPausingActivity;//Launcher
        
        if (prev != null) {
            mPausingActivity = null;//Launcher已进入Paused状态
        }

        if (!mService.mSleeping && !mService.mShuttingDown) {//系统是否睡眠或关闭状态
            resumeTopActivityLocked(prev);//再次调用resumeTopActivityLocked,启动处于Activity堆栈顶端的Activity组件
        } else {
        }
    }
21、resumeTopActivityLocked
    final boolean resumeTopActivityLocked(ActivityRecord prev) {
        // Find the first activity that is not finishing.
        ActivityRecord next = topRunningActivityLocked(null);//得到Activity组件堆栈中最上面的不是处于结束状态的Activity组件

        // Remember how we'll process this pause/resume situation, and ensure
        // that the state is reset however we wind up proceeding.
        final boolean userLeaving = mUserLeaving;//判断是否要向源Activity发送用户离开事件通知
        mUserLeaving = false;

        if (next == null) {
            // There are no more activities!  Let's just start up the
            // Launcher...
            if (mMainStack) {
                return mService.startHomeActivityLocked();
            }
        }

        next.delayedResume = false;
        
        // If the top activity is the resumed one, nothing to do.
        if (mResumedActivity == next && next.state == ActivityState.RESUMED) {//判断要启动的Activity是否为当前被激活的Activity
            // Make sure we have executed any pending transitions, since there
            // should be nothing left to do at this point.
            mService.mWindowManager.executeAppTransition();
            mNoAnimActivities.clear();
            return false;//直接返回
        }

        // If we are sleeping, and there is no resumed activity, and the top
        // activity is paused, well that is the state we want.
        if ((mService.mSleeping || mService.mShuttingDown)//系统正要进入睡眠或关机状态
                && mLastPausedActivity == next && next.state == ActivityState.PAUSED) {//判断要启动的Activity是否为上次被终止的Activity
            // Make sure we have executed any pending transitions, since there
            // should be nothing left to do at this point.
            mService.mWindowManager.executeAppTransition();
            mNoAnimActivities.clear();
            return false;//直接返回,再启动Activity已经没有意义
        }
        
        // The activity may be waiting for stop, but that is no longer
        // appropriate for it.
        mStoppingActivities.remove(next);
        mWaitingVisibleActivities.remove(next);

        if (DEBUG_SWITCH) Slog.v(TAG, "Resuming " + next);

        // If we are currently pausing an activity, then don't do anything
        // until that is done.
        if (mPausingActivity != null) {//检查系统当前是否正在暂停一个Activity,如果是,要等到它暂停完成后在启动Activity组件next
            if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: pausing=" + mPausingActivity);
            return false;
        }

        if (mResumedActivity != null) {//当前系统激活的Activity不为null,Launcher Paused返回后,会被置为null
            startPausingLocked(userLeaving, false);//通知它进入Paused状态,以便即将要启动的Activity获得焦点
            return true;
        }

        if (next.app != null && next.app.thread != null) {//MainActivity尚未启动起来,因此它的app就会等于null

        } else {
            startSpecificActivityLocked(next, true, true);//将应用进程启动起来
        }

        return true;
    }
22、startSpecificActivityLocked
    private final void startSpecificActivityLocked(ActivityRecord r,
            boolean andResume, boolean checkConfig) {
        // Is this activity's application already running?
        //每一个Activity都有一个进程名称和一个用户ID;其中用户id是安装该Activity是由PMS分配的,
        //而进程名称是由Activity组件的android:process属性决定的。
        ProcessRecord app = mService.getProcessRecordLocked(r.processName,
                r.info.applicationInfo.uid);//检查是否存在对应进程
        
        if (app != null && app.thread != null) {//存在,通知该应用进程将Activity启动起来
            try {
                realStartActivityLocked(r, app, andResume, checkConfig);//启动Activity
                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,
                "activity", r.intent.getComponent(), false);//创建一个应用进程,再启动Activity
    }
23、startProcessLocked
    final ProcessRecord startProcessLocked(String processName,
            ApplicationInfo info, boolean knownToBeDead, int intentFlags,
            String hostingType, ComponentName hostingName, boolean allowWhileBooting) {
        ProcessRecord app = getProcessRecordLocked(processName, info.uid);//检查要创建的应用进程是否已经存在

        String hostingNameStr = hostingName != null
                ? hostingName.flattenToShortString() : null;
        
        if (app == null) {//不存在
            app = newProcessRecordLocked(null, info, processName);//根据指定的名称用户id创建ProcessRecord对象
            mProcessNames.put(processName, info.uid, app);
        } else {
            // If this is a new package in the process, add the package to the list
            app.addPackage(info.packageName);
        }
        startProcessLocked(app, hostingType, hostingNameStr);//创建一个应用程序进程
        return (app.pid != 0) ? app : null;
    }
24、startProcessLocked
    private final void startProcessLocked(ProcessRecord app,
            String hostingType, String hostingNameStr) {
        
        try {
            int uid = app.info.uid;//用户uid
            int[] gids = null;
            try {
                gids = mContext.getPackageManager().getPackageGids(
                        app.info.packageName);//用户组id
            } catch (PackageManager.NameNotFoundException e) {
                Slog.w(TAG, "Unable to retrieve gids", e);
            }
 
            int pid = Process.start("android.app.ActivityThread",
                    mSimpleProcessManagement ? app.processName : null, uid, uid,
                    gids, debugFlags, null);//启动新的应用程序进程,指定入口函数为android.app.ActivityThread类的静态成员函数main
            BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
            synchronized (bs) {
               
            if (pid == 0 || pid == MY_PID) {//新创建的应用进程
                // Processes are being emulated with threads.
                app.pid = MY_PID;
                app.removed = false;
                mStartingProcesses.add(app);
            } else if (pid > 0) {//父进程,得到pid,设置app,并存入mPidsSelfLocked
                app.pid = pid;
                app.removed = false;
                synchronized (mPidsSelfLocked) {
                    this.mPidsSelfLocked.put(pid, app);
                    Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
                    msg.obj = app;
					//向AMS运行的线程中发送PROC_START_TIMEOUT_MSG消息,延迟PROC_START_TIMEOUT发送,
					//所以新的应用进程必须在PROC_START_TIMEOUT时间内完成
                    mHandler.sendMessageDelayed(msg, PROC_START_TIMEOUT);
                }
            } else {
        
            }
        } catch (RuntimeException e) {

        }
    }
25、main

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

    public static final void main(String[] args) {

        Looper.prepareMainLooper();//创建一个消息循环
        if (sMainThreadHandler == null) {
            sMainThreadHandler = new Handler();
        }

        ActivityThread thread = new ActivityThread();//创建ActivityThread对象,同时在它内部会创建一个ApplicationThread对象,这是一个Binder本地对象
        thread.attach(false);//向AMS发送一个启动完成通知后,阻塞等待AMS返回

        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }

        Looper.loop();//启动消息循环

    }

   private final void attach(boolean system) {
        sThreadLocal.set(this);
        mSystemThread = system;
        if (!system) {
            IActivityManager mgr = ActivityManagerNative.getDefault();//得到AMS的代理对象
            try {
                mgr.attachApplication(mAppThread);//向AMS发送一个进程间通信请求
            } catch (RemoteException ex) {
            }
        }
26、attachApplication
    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();
    }
27、attachApplication

frameworks\base\services\java\com\android\server\am\ActivityManagerService.java

    public final void attachApplication(IApplicationThread thread) {
        synchronized (this) {
            int callingPid = Binder.getCallingPid();
            final long origId = Binder.clearCallingIdentity();
            attachApplicationLocked(thread, callingPid);
            Binder.restoreCallingIdentity(origId);
        }
    }
28、attachApplicationLocked
    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);//取回先前保存的ProcessRecord对象app
            }
        } else if (mStartingProcesses.size() > 0) {
            app = mStartingProcesses.remove(0);
            app.setPid(pid);
        } else {
            app = null;
        }

        //对ProcessRecord对象app进行初始化
        app.thread = thread;//通过ApplicationThread代理对象与新建的应用程序进程通信
        app.curAdj = app.setAdj = -100;
        app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
        app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
        app.forcingToForeground = null;
        app.foregroundServices = false;
        app.debugging = false;

        mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);//删除PROC_START_TIMEOUT_MSG消息,新的应用进程已经在规定的时间内启动起来了


        // See if the top visible activity is waiting to run in this process...
        ActivityRecord hr = mMainStack.topRunningActivityLocked(null);//得到位于Activity堆栈顶端的Activity,也就是MainActivity
        if (hr != null && normalMode) {
            if (hr.app == null && app.info.uid == hr.info.applicationInfo.uid
                    && processName.equals(hr.processName)) {//判断MainActivity的用户名id和进程名是否与新进程的相等
                try {
                    if (mMainStack.realStartActivityLocked(hr, app, true, true)) {//ActivityRecord对象hr所描述的Activity应该在ProcessRecord对象app描述的进程中启动
                        didSomething = true;
                    }
                } catch (Exception e) {
                    badApp = true;
                }
            } else {
            }
        }

        return true;
    }
29、realStartActivityLocked
    final boolean realStartActivityLocked(ActivityRecord r,
            ProcessRecord app, boolean andResume, boolean checkConfig)
            throws RemoteException {

        r.app = app;//将app赋给ActivityRecod所描述的r对象的成员变量,表示Activity是在app所描述的应用程序中启动的

        int idx = app.activities.indexOf(r);
        if (idx < 0) {
            app.activities.add(r);//将Activity添加到应用进程的Activity组件列表中
        }

        try {
          
            app.thread.scheduleLaunchActivity(new Intent(r.intent), r,
                    System.identityHashCode(r),
                    r.info, r.icicle, results, newIntents, !andResume,
                    mService.isNextTransitionForward());//通知应用进程启动由参数r描述的Activity组件,thread是ApplicationThreadProxy类型的Binder代理对象
            
30、scheduleLaunchActivity

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

    public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
            ActivityInfo info, Bundle state, List<ResultInfo> pendingResults,
    		List<Intent> pendingNewIntents, boolean notResumed, boolean isForward)
    		throws RemoteException {
        Parcel data = Parcel.obtain();
        data.writeInterfaceToken(IApplicationThread.descriptor);
        intent.writeToParcel(data, 0);
        data.writeStrongBinder(token);
        data.writeInt(ident);
        info.writeToParcel(data, 0);
        data.writeBundle(state);
        data.writeTypedList(pendingResults);
        data.writeTypedList(pendingNewIntents);
        data.writeInt(notResumed ? 1 : 0);
        data.writeInt(isForward ? 1 : 0);
        mRemote.transact(SCHEDULE_LAUNCH_ACTIVITY_TRANSACTION, data, null,
                IBinder.FLAG_ONEWAY);
        data.recycle();
    }

以上4步都是在ActivityManagerService中执行的。、

31、scheduleLaunchActivity

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

        public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
                ActivityInfo info, Bundle state, List<ResultInfo> pendingResults,
                List<Intent> pendingNewIntents, boolean notResumed, boolean isForward) {
            ActivityClientRecord r = new ActivityClientRecord();//将要启动的Activity的信息封装成一个ActivityClientRecord对象

            r.token = token;
            r.ident = ident;
            r.intent = intent;
            r.activityInfo = info;
            r.state = state;

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

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

            queueOrSendMessage(H.LAUNCH_ACTIVITY, r);//向应用进程主线程发送一个LAUNCH_ACTIVITY的消息
        }

32、queueOrSendMessage
    private final void queueOrSendMessage(int what, Object obj) {
        queueOrSendMessage(what, obj, 0, 0);
    }

...

    private final void queueOrSendMessage(int what, Object obj, int arg1, int arg2) {
        synchronized (this) {
            if (DEBUG_MESSAGES) Slog.v(
                TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
                + ": " + arg1 + " / " + obj);
            Message msg = Message.obtain();
            msg.what = what;
            msg.obj = obj;
            msg.arg1 = arg1;
            msg.arg2 = arg2;
			//向应用程序的主线程发送消息,
			//binder线程需要尽快返回binder线程池去处理其他进程间通信请求,
			//另一方面pause请求可能涉及一些界面操作,这儿就返回了AMS,AMS继续向下执行
            mH.sendMessage(msg);
        }
    }
33、handleMessage
        public void handleMessage(Message msg) {
            if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + msg.what);
            switch (msg.what) {
                case LAUNCH_ACTIVITY: {
                    ActivityClientRecord r = (ActivityClientRecord)msg.obj;

                    r.packageInfo = getPackageInfoNoCheck(
                            r.activityInfo.applicationInfo);//获得一个LoadedApk对象,描述已加载的apk文件
                    handleLaunchActivity(r, null);//启动由ActivityClientRecord描述的Activity
                } break;
34、handleLaunchActivity
private final void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {

    Activity a = performLaunchActivity(r, customIntent);//将Activity启动起来

        if (a != null) {
            r.createdConfig = new Configuration(mConfiguration);
            Bundle oldState = r.state;
            handleResumeActivity(r.token, false, r.isForward);//将Activity的状态置为Resumed
35、performLaunchActivity
    private final Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");

        ActivityInfo aInfo = r.activityInfo;
        if (r.packageInfo == null) {
            r.packageInfo = getPackageInfo(aInfo.applicationInfo,
                    Context.CONTEXT_INCLUDE_CODE);
        }

        ComponentName component = r.intent.getComponent();//获得要启动Activity的包名和类名
        if (component == null) {
            component = r.intent.resolveActivity(
                mInitialApplication.getPackageManager());
            r.intent.setComponent(component);
        }

        if (r.activityInfo.targetActivity != null) {
            component = new ComponentName(r.activityInfo.packageName,
                    r.activityInfo.targetActivity);
        }

        Activity activity = null;
        try {
            java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
            activity = mInstrumentation.newActivity(
                    cl, component.getClassName(), r.intent);//将要启动Activity的类文件加载到内存中,并创建一个实例
            r.intent.setExtrasClassLoader(cl);
            if (r.state != null) {
                r.state.setClassLoader(cl);
            }
        } catch (Exception e) {
        }

        try {
            Application app = r.packageInfo.makeApplication(false, mInstrumentation);

            if (activity != null) {
				//初始化一个ContextImpl对象appContext,用来作为activity的上下文环境
				//通过它可以访问特定的应用程序资源,以及启动其他应用程序组件
                ContextImpl appContext = new ContextImpl();
                appContext.init(r.packageInfo, r.token, this);
                appContext.setOuterContext(activity);
                CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
                Configuration config = new Configuration(mConfiguration);

                activity.attach(appContext, this, getInstrumentation(), r.token,
                        r.ident, app, r.intent, r.activityInfo, title, r.parent,
                        r.embeddedID, r.lastNonConfigurationInstance,
                        r.lastNonConfigurationChildInstances, config);//初始化activity

                if (customIntent != null) {
                    activity.mIntent = customIntent;
                }
                r.lastNonConfigurationInstance = null;
                r.lastNonConfigurationChildInstances = null;
                activity.mStartedActivity = false;
                int theme = r.activityInfo.getThemeResource();
                if (theme != 0) {
                    activity.setTheme(theme);
                }

                activity.mCalled = false;
                mInstrumentation.callActivityOnCreate(activity, r.state);//启动activity,会调用activity的onCreate成员函数
            }
            r.paused = true;

            mActivities.put(r.token, r);//以r.token,ActivityRecord的代理对象作为关键字,保存ActivityClientRecord对象r

        } catch (SuperNotCalledException e) {
            throw e;

        } catch (Exception e) {
        }

        return activity;
    }

36、onCreate
    public void callActivityOnCreate(Activity activity, Bundle icicle) {
        activity.onCreate(icicle);
    }
    protected void onCreate(Bundle savedInstanceState) {
        mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
                com.android.internal.R.styleable.Window_windowNoDisplay, false);
        mCalled = true;
    }
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btn1 = findViewById(R.id.btn_sub);
        Button btn2 = findViewById(R.id.btn_sub2);
        btn1.setOnClickListener(this);
        btn2.setOnClickListener(this);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值