侧边栏壁纸
博主头像
慢行的骑兵博主等级

贪多嚼不烂,欲速则不达

  • 累计撰写 29 篇文章
  • 累计创建 27 个标签
  • 累计收到 1 条评论

目 录CONTENT

文章目录

Activity的启动流程源码分析

慢行的骑兵
2021-09-26 / 0 评论 / 0 点赞 / 142 阅读 / 1,737 字
  • 基于Android10.0(Sdk版本为29)分析,跟8.0(也有做过笔记)差别非常大;
  • 建议先看《APP的启动流程》那篇笔记,再来看该篇笔记;
  • 看源码的目的:了解主线流程(核心步骤),在开发中遇到了一些问题,可能就有思路并能快速的锁定问题范围;

一.源码分析

  • 分析入口:startActivity方法

1.startActivity

public void startActivity(Intent intent) {
    this.startActivity(intent, null);
}

public void startActivity(Intent intent, @Nullable Bundle options) {
    if (options != null) {
        startActivityForResult(intent, -1, options);
    } else {
        // Note we want to go through this call for compatibility with
        // applications that may have overridden the method.
        startActivityForResult(intent, -1);
    }
}

public void startActivityForResult(@RequiresPermission Intent intent, int requestCode) {
    startActivityForResult(intent, requestCode, null);
}

public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
        @Nullable Bundle options) {
	//mParent是根Activity	
    if (mParent == null) {
        options = transferSpringboardActivityOptions(options);
        Instrumentation.ActivityResult ar =
            mInstrumentation.execStartActivity(
                this, mMainThread.getApplicationThread(), mToken, this,
                intent, requestCode, options);
        if (ar != null) {
            mMainThread.sendActivityResult(
                mToken, mEmbeddedID, requestCode, ar.getResultCode(),
                ar.getResultData());
        }
        if (requestCode >= 0) {
            // If this start is requesting a result, we can avoid making
            // the activity visible until the result is received.  Setting
            // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
            // activity hidden during this time, to avoid flickering.
            // This can only be done when a result is requested because
            // that guarantees we will get information back when the
            // activity is finished, no matter what happens to it.
            mStartedActivity = true;
        }

        cancelInputsAndStartExitTransition(options);
        // TODO Consider clearing/flushing other event sources and events for child windows.
    } else {
		//最终也是执行mInstrumentation.execStartActivity方法
        if (options != null) {
            mParent.startActivityFromChild(this, intent, requestCode, options);
        } else {
            // Note we want to go through this method for compatibility with
            // existing applications that may have overridden it.
            mParent.startActivityFromChild(this, intent, requestCode);
        }
    }
}

2.Instrumentation类execStartActivity

//Instrumentation类
public ActivityResult execStartActivity(
        Context who, IBinder contextThread, IBinder token, Activity target,
        Intent intent, int requestCode, Bundle options) {
	//...	
    //ActivityManager.getService()是IActivityManager(其实现类是ActivityManagerService)
    //这里的代码非常重要
    int result = ActivityTaskManager.getService()
                .startActivity(whoThread, who.getBasePackageName(), intent,
                        intent.resolveTypeIfNeeded(who.getContentResolver()),
                        token, target != null ? target.mEmbeddedID : null,
                        requestCode, 0, null, options);
	//...				
    return null;
}

3.ActivityManager.getService

public static IActivityTaskManager getService() {
        return IActivityTaskManagerSingleton.get();
}
    
@UnsupportedAppUsage(trackingBug = 129726065)
private static final Singleton<IActivityTaskManager> IActivityTaskManagerSingleton =
        new Singleton<IActivityTaskManager>() {
            @Override
            protected IActivityTaskManager create() {
                final IBinder b = ServiceManager.getService(Context.ACTIVITY_TASK_SERVICE);
                //9.0的实现跟10.0的不同
                return IActivityTaskManager.Stub.asInterface(b);
            }
        };

4.IActivityTaskManager.Stub实现类

  • 分析ActivityTaskManagerService的startActivity方法

  • 最终调用的代码


int startActivityAsUser(IApplicationThread caller, String callingPackage,
        Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
        int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
        boolean validateIncomingUser) {
    enforceNotIsolatedCaller("startActivityAsUser");

    //userId,了解即可     处理安全方面相关的
    userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
            Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");

    // 分析ActivityStartController
    return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
            .setCaller(caller)
            .setCallingPackage(callingPackage)
            .setResolvedType(resolvedType)
            .setResultTo(resultTo)
            .setResultWho(resultWho)
            .setRequestCode(requestCode)
            .setStartFlags(startFlags)
            .setProfilerInfo(profilerInfo)
            .setActivityOptions(bOptions)
            .setMayWait(userId)	//关注
            .execute();		//需要关注该方法

}

5.ActivityStartController

ActivityStarter obtainStarter(Intent intent, String reason) {
    //根据import com.android.server.wm.ActivityStarter.Factory;得知mFactory是ActivityStarter类中的
    //分析ActivityStarter的Factory类
    return mFactory.obtain().setIntent(intent).setReason(reason);
}

6.ActivityStarter的Factory类的obtain方法

  • 最终调用的是DefaultFactory的obtain方法
private SynchronizedPool<ActivityStarter> mStarterPool = new SynchronizedPool<>(MAX_STARTER_COUNT);

public ActivityStarter obtain() {
    ActivityStarter starter = mStarterPool.acquire();

    if (starter == null) {
        starter = new ActivityStarter(mController, mService, mSupervisor, mInterceptor);
    }

    return starter;
}
  • 到此,我们只需要知道getActivityStartController().obtainStarter得到的是ActivityStarter对象。返回步骤4的注释进行查看;

7.分析ActivityStarter的execute方法

int execute() {
    try {
        //根据4中的setMayWait可以知道,mRequest.mayWait = true
        if (mRequest.mayWait) {
            //分析startActivityMayWait
            return startActivityMayWait(mRequest.caller, mRequest.callingUid,
                    mRequest.callingPackage, mRequest.realCallingPid, mRequest.realCallingUid,
                    mRequest.intent, mRequest.resolvedType,
                    mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,
                    mRequest.resultWho, mRequest.requestCode, mRequest.startFlags,
                    mRequest.profilerInfo, mRequest.waitResult, mRequest.globalConfig,
                    mRequest.activityOptions, mRequest.ignoreTargetSecurity, mRequest.userId,
                    mRequest.inTask, mRequest.reason,
                    mRequest.allowPendingRemoteAnimationRegistryLookup,
                    mRequest.originatingPendingIntent, mRequest.allowBackgroundActivityStart);
        } else {
            //...
        }
    } finally {
        onExecutionComplete();
    }
}

8.startActivityMayWait

private int startActivityMayWait(IApplicationThread caller, int callingUid,
        String callingPackage, int requestRealCallingPid, int requestRealCallingUid,
        Intent intent, String resolvedType, IVoiceInteractionSession voiceSession,
        IVoiceInteractor voiceInteractor, IBinder resultTo, String resultWho, int requestCode,
        int startFlags, ProfilerInfo profilerInfo, WaitResult outResult,
        Configuration globalConfig, SafeActivityOptions options, boolean ignoreTargetSecurity,
        int userId, TaskRecord inTask, String reason,
        boolean allowPendingRemoteAnimationRegistryLookup,
        PendingIntentRecord originatingPendingIntent, boolean allowBackgroundActivityStart) {
    
	//...
    int res = startActivity(caller, intent, ephemeralIntent, resolvedType, aInfo, rInfo,
            voiceSession, voiceInteractor, resultTo, resultWho, requestCode, callingPid,
            callingUid, callingPackage, realCallingPid, realCallingUid, startFlags, options,
            ignoreTargetSecurity, componentSpecified, outRecord, inTask, reason,
            allowPendingRemoteAnimationRegistryLookup, originatingPendingIntent,
            allowBackgroundActivityStart);

    //...

    return res;
    }
}

private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,
        String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,
        IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
        IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,
        String callingPackage, int realCallingPid, int realCallingUid, int startFlags,
        SafeActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified,
        ActivityRecord[] outActivity, TaskRecord inTask, String reason,
        boolean allowPendingRemoteAnimationRegistryLookup,
        PendingIntentRecord originatingPendingIntent, boolean allowBackgroundActivityStart) {

	//...
    mLastStartActivityResult = startActivity(caller, intent, ephemeralIntent, resolvedType,
            aInfo, rInfo, voiceSession, voiceInteractor, resultTo, resultWho, requestCode,
            callingPid, callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
            options, ignoreTargetSecurity, componentSpecified, mLastStartActivityRecord,
            inTask, allowPendingRemoteAnimationRegistryLookup, originatingPendingIntent,
            allowBackgroundActivityStart);

    //...

    return getExternalResult(mLastStartActivityResult);
}

private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,
            String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,
            String callingPackage, int realCallingPid, int realCallingUid, int startFlags,
            SafeActivityOptions options,
            boolean ignoreTargetSecurity, boolean componentSpecified, ActivityRecord[] outActivity,
            TaskRecord inTask, boolean allowPendingRemoteAnimationRegistryLookup,
            PendingIntentRecord originatingPendingIntent, boolean allowBackgroundActivityStart) {
			//...
		final int res = startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags,
                true /* doResume */, checkedOptions, inTask, outActivity, restrictedBgActivity);
        mSupervisor.getActivityMetricsLogger().notifyActivityLaunched(res, outActivity[0]);
        return res;
}

private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
            ActivityRecord[] outActivity, boolean restrictedBgActivity) {
    //...
    try {
        mService.mWindowManager.deferSurfaceLayout();
        result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
                startFlags, doResume, options, inTask, outActivity, restrictedBgActivity);
    }
	//...

    return result;
}


private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
        IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
        int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
        ActivityRecord[] outActivity, boolean restrictedBgActivity) {
	//...
    if (dontStart) {
        // For paranoia, make sure we have correctly resumed the top activity.
        topStack.mLastPausedActivity = null;
        if (mDoResume) {
            mRootActivityContainer.resumeFocusedStacksTopActivities();
        }
        //...
    }

    //...

    return START_SUCCESS;
}

//RootActivityContainer类的resumeFocusedStacksTopActivities

9.RootActivityContainer类的resumeFocusedStacksTopActivities

boolean resumeFocusedStacksTopActivities() {
    return resumeFocusedStacksTopActivities(null, null, null);
}

boolean resumeFocusedStacksTopActivities(
        ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {

    //...
    if (targetStack != null && (targetStack.isTopStackOnDisplay()
            || getTopDisplayFocusedStack() == targetStack)) {
        //分析resumeTopActivityUncheckedLocked
        result = targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
    }

    //...
    return result;
}

10.ActivityStack类resumeTopActivityUncheckedLocked

boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
    if (mInResumeTopActivity) {
        // Don't even start recursing.
        return false;
    }

    boolean result = false;
    try {
        // Protect against recursion.
        mInResumeTopActivity = true;
        result = resumeTopActivityInnerLocked(prev, options);

        final ActivityRecord next = topRunningActivityLocked(true /* focusableOnly */);
        if (next == null || !next.canTurnScreenOn()) {
            checkReadyForSleep();
        }
    } finally {
        mInResumeTopActivity = false;
    }

    return result;
}

private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
    
	//...
	
    mStackSupervisor.startSpecificActivityLocked(next, true, true);
    

    return true;
}

11.ActivityStackSupervisor类startSpecificActivityLocked

//ActivityStackSupervisor类
void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) {
    //...
    realStartActivityLocked(r, wpc, andResume, checkConfig);
    //...
}

boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
        boolean andResume, boolean checkConfig) throws RemoteException {

    //...
    mService.getLifecycleManager().scheduleTransaction(clientTransaction);
    //...

    return true;
}

12.ClientLifecycleManager类scheduleTransaction

void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
    final IApplicationThread client = transaction.getClient();
    //分析
	transaction.schedule();
    //...
}

//ClientTransaction类
public void schedule() throws RemoteException {
    //mClient是IApplicationThread,但是通过as不能搜索出IApplicationThread
    //通过查找IApplicationThread的说明,确定IApplicationThread的实现类在ActivityThread中
    mClient.scheduleTransaction(this);
}

13.ActivityThread类的内部类ApplicationThread

  • 分析IApplicationThread的实现类的scheduleTransaction方法,即分析ApplicationThread
public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
    //调用了ActivityThread父类的scheduleTransaction方法
    ActivityThread.this.scheduleTransaction(transaction);
}

//ClientTransactionHandler类
void scheduleTransaction(ClientTransaction transaction) {
    transaction.preExecute(this);
    //执行了子类的内部类的sendMessage方法
    sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}

//执行了
public final class ActivityThread extends ClientTransactionHandler {
    private final TransactionExecutor mTransactionExecutor = new TransactionExecutor(this);
    
	//...
	class H extends Handler {
		case EXECUTE_TRANSACTION:
			//...
			mTransactionExecutor.execute(transaction);
			//...
		}
	}
	//...	
}

14.TransactionExecutor的execute方法

public void execute(ClientTransaction transaction) {

	//...
    executeCallbacks(transaction);
    //...
}

public void executeCallbacks(ClientTransaction transaction) {
    //...
    final ClientTransactionItem item = callbacks.get(i);
    //...
    item.execute(mTransactionHandler, token, mPendingActions);
    //...
}

15.分析ClientTransactionItem的execute

  • 最终是调用其实现类LaunchActivityItem的方法
public void execute(ClientTransactionHandler client, IBinder token,
        PendingTransactionActions pendingActions) {
    //...
    //最终实现是在ClientTransactionHandler实现类中,即ActivityThread
    client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
    //...
}

16.即ActivityThread的handleLaunchActivity

public Activity handleLaunchActivity(ActivityClientRecord r,
        PendingTransactionActions pendingActions, Intent customIntent) {
    //...

    final Activity a = performLaunchActivity(r, customIntent);

    //...

    return a;
}

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
    
	//创建activity
    activity = mInstrumentation.newActivity(
            cl, component.getClassName(), r.intent);
    //...
    if (r.isPersistable()) {
        mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
    } else {
        mInstrumentation.callActivityOnCreate(activity, r.state);
    }
    
	//...
	
	r.activity = activity;
	
    //...

    return activity;
}

17.Instrumentation类callActivityOnCreate

public void callActivityOnCreate(Activity activity, Bundle icicle,
        PersistableBundle persistentState) {
    prePerformCreate(activity);
    //分析
    activity.performCreate(icicle, persistentState);
    postPerformCreate(activity);
}

final void performCreate(Bundle icicle) {
    performCreate(icicle, null);
}

@UnsupportedAppUsage
final void performCreate(Bundle icicle, PersistableBundle persistentState) {
    //...
    if (persistentState != null) {
        onCreate(icicle, persistentState);
    } else {
        onCreate(icicle);
    }
    //...
}

二.时序图

01.Android10.0Activity启动流程分析

三.问题总结

  • 1.如果从本应用的Aactivity跳转到Bactivity,请问是属于同一个进程还是跨进程的调用?

    • 在Instrumentation类的execStartActivity方法可以找到答案,ActivityManager.getService()就涉及到了跨进程通信了。
  • 2.activity的启动变化有哪些?

    • 之前是可以通过在后台启动activity,现在需要通过notifycation来启动;
0

评论区