Acticity启动流程
1、根启动的流程:从桌面点击图标,到启动Activity的页面
- Activity启动之前
- init进程->Zygote进程->SystemService进程和Launcher进程
- Launcher的定义:Android系统启动后,加载的第一个程序,是其他应用程序的入口。可以看成是整个桌面UI
- Launcher的源码??????
注:需要写一个Launcher的源码,来进行源码分析
2、普通Activity的启动流程
注:Android源码读取不到:1)编译版本不对 2)厂商修改了源码
- 启动模式和Intent.Flag的区别
- 栈中Activity 的变化
- handleLaunchActivity,handleStartActivity和handleResumeActivity 调用的区别
2.1 涉及到的概念
- 进程:Android系统为每个APP分配至少一个进程
- 系统服务进程(SystemService进程):Android中最核心的服务,主要负责系统中
四大组件的启动、切换、调度 及应用进程的管理和调度 等工作,其职责与操作系统中的进程管理和调度模块相类似,Android 10之后,该服务由AMTS代替。 - IPC:跨进程通信,Android中采用Binder机制,在Activity启动流程中,都是采用AIDL的方式进行跨进程通信。
2.2 涉及到的类
-
Activity:启动的开端 -
Instrumentation:负责调用Activity和Application生命周期 -
ActivityTaskManager: -
IActivityTaskMansger:AIDL 接口,实现类是ATMS -
ActivityTaskMansgerService:分担AMS的功能,负责统一调度各个应用程序之间的activity -
ActivityStart:启动Activity的类 -
RootWindowContainer:RootWindowContainer是窗口容器(WindowContainer)的根容器,管理了所有窗口容器,设备上所有的窗口(Window)、显示(Display)都是由它来管理的 -
ActivityStack:Activity在AMS的栈管理,一个ActivityStack包含了若干个TaskRecord,每个TaskRecord又包含了若干个ActivityRecord,每个ActivityRecord对应了一个Activity。在这里,TaskRecord相当于在启动模式中的“任务栈”,根据启动模式的不同,在启动Activity的时候,会对TaskRecord进行不同的操作。 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-HhKcgTNd-1628666141156)(Acticity启动流程.assets/webp.png)] Android系统中的每一个Activity都位于一个Task中。一个Task可以包含多个Activity,同一个Activity也可 能有多个实例。 在AndroidManifest.xml中,我们可以通过 android:launchMode 来控制Activity在Task中的实例。 另外,在startActivity的时候,我们也可以通过 setFlag 来控制启动的Activity在Task中的实例。 Task管理的意义还在于近期任务列表以及Back栈。 当你通过多任务键(有些设备上是长按Home键,有些设备上是专门提供的多任务键)调出多任务时,其实就是从ActivityManagerService获取了最近启动的Task列表。 -
ActivityRecord:记录Activity的所有信息。 -
ActivityStackSupervisor:主要作用是进行对ActivityStack的管理。 -
ClientLifecycleManager: -
ClientTransaction: -
IApplicationThread:AIDL接口,实现类是ApplicationThread -
ApplicationThread:ActivityThread的内部类,一个应用的主线程(虽然它不是一个线程) -
ActivityThread: -
ClientTransactionHandler:ActivityThread的父类 -
TransactionExecutor:处理事务的类 -
LaunchActivityItem:启动Activity选项
2.3 总体启动流程
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Sa10P6Ty-1628666141158)(Acticity启动流程.assets/image-20210809164948670.png)]
通过进程的变换将其总体分为以下三个过程:App进程中 ——[通过Binder]——> 系统进程中 ——[通过Binder]——> 回到App进程中
-
App进程请求AMS的过程 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-06d27poq-1628666141158)(Acticity启动流程.assets/image-20210810122133436.png)]
-
Activity 一般通过Activity.startActivity(Intent)来启动Activity。
public void startActivity(Intent intent, @Nullable Bundle options) {
...
if (options != null) {
startActivityForResult(intent, -1, options);
} else {
startActivityForResult(intent, -1);
}
}
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
@Nullable Bundle options) {
if (mParent == null) {
options = transferSpringboardActivityOptions(options);
Instrumentation.ActivityResult ar =
mInstrumentation.execStartActivity(
this, mMainThread.getApplicationThread(), mToken, this,
intent, requestCode, options);
...
} else {
if (options != null) {
mParent.startActivityFromChild(this, intent, requestCode, options);
} else {
mParent.startActivityFromChild(this, intent, requestCode);
}
}
}
-
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 = ActivityTaskManager.getService().startActivity(whoThread,
who.getBasePackageName(), who.getAttributionTag(), intent,
intent.resolveTypeIfNeeded(who.getContentResolver()), token,
target != null ? target.mEmbeddedID : null, requestCode, 0, null, options);
...
} catch (RemoteException e) {
throw new RuntimeException("Failure from system", e);
}
return null;
}
通过ActivityTaskManager.getService() 获取到一个IActivityTaskManager 对象。通过其获取方式: -
ActivityTaskManager
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);
return IActivityTaskManager.Stub.asInterface(b);
}
};
public abstract class Singleton<T> {
private T mInstance;
protected abstract T create();
public final T get() {
synchronized (this) {
if (mInstance == null) {
mInstance = create();
}
return mInstance;
}
}
}
-
IActivityTaskManager IActivityTaskManager作为ATMS的代理对象,是通过AIDL实现的 -
ActivityTaskManagerService(ATMS) -
AMS处理请求 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-FgdujTKa-1628666141159)(Acticity启动流程.assets/image-20210810122103122.png)]
-
ActivityTaskManagerService 在ATMS中依次调用startActivity(args) -> startActivityAsUser(args)->startActivityAsUser(args) Args如下:
- IApplicationThread caller:Activity1所在的Application
- String callingPackage: Activity1所在的Application 的包名
- intent
- String resolvedType: intent.resolveTypeIfNeeded(who.getContentResolver())
- IBinder resultTo: attachToApplication时的mTolen
- String resultWho: target != null ? target.mEmbeddedID : null
- int requestCode: -1
- int startFlags: 0
- ProfilerInfo profilerInfo: null
- Bundle bOptions: null(默认)
- int userId: UserHandle.getCallingUserId()
- boolean validateIncomingUser: true
private int startActivityAsUser(IApplicationThread caller, String callingPackage,
@Nullable String callingFeatureId, Intent intent, String resolvedType,
IBinder resultTo, String resultWho, int requestCode, int startFlags,
ProfilerInfo profilerInfo, Bundle bOptions, int userId, boolean validateIncomingUser) {
assertPackageMatchesCallingUid(callingPackage);
enforceNotIsolatedCaller("startActivityAsUser");
userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
.setCaller(caller)
.setCallingPackage(callingPackage)
.setCallingFeatureId(callingFeatureId)
.setResolvedType(resolvedType)
.setResultTo(resultTo)
.setResultWho(resultWho)
.setRequestCode(requestCode)
.setStartFlags(startFlags)
.setProfilerInfo(profilerInfo)
.setActivityOptions(bOptions)
.setUserId(userId)
.execute();
}
-
ActivityStarter 顾名思义,ActivityStarter类就是为了启动Activity的。 在execute 方法中,会调用executeRequest 方法,这里会处理启动Activity的请求,并开始一个Activity启动的旅程(代码注释原话)。 executeRequest 方法会进行初步的检查并且确认权限,并且在这里组装对应Activity的ActivityRecord ,其包含了对应Activity的所有信息,并储存在任务栈帧TaskRecord 中。在Activity的启动过程中,Activity都是通过ActivityRecord来表示的。然后,会调用startActivityUnchecked 方法,接着startActivityUnchecked方法会调用startActivityInner 方法。 在startActivityInner 中,主要的一件事就是就是处理了Activity的启动模式,并且在ActivityStack 中处理对应Activity在任务栈中的相关事宜,包括但不仅限于将对应的ActivityRecord添加到TaskRecord中、将对应的ActivityRecord提到栈中最顶部。 最后,会调用RootWindowContainer的resumeFocusedStacksTopActivities 方法。
int execute() {
try {
...
int res;
synchronized (mService.mGlobalLock) {
...
res = resolveToHeavyWeightSwitcherIfNeeded();
if (res != START_SUCCESS) {
return res;
}
res = executeRequest(mRequest);
...
if (globalConfigWillChange) {
}
...
}
} finally {
onExecutionComplete();
}
}
private int executeRequest(Request request) {
...
int err = ActivityManager.START_SUCCESS;
final Bundle verificationBundle =
options != null ? options.popAppVerificationBundle() : null;
WindowProcessController callerApp = null;
if (caller != null) {
callerApp = mService.getProcessController(caller);
if (callerApp != null) {
callingPid = callerApp.getPid();
callingUid = callerApp.mInfo.uid;
} else {
Slog.w(TAG, "Unable to find app for caller " + caller + " (pid=" + callingPid
+ ") when starting: " + intent.toString());
err = ActivityManager.START_PERMISSION_DENIED;
}
}
final int userId = aInfo != null && aInfo.applicationInfo != null
? UserHandle.getUserId(aInfo.applicationInfo.uid) : 0;
if (err == ActivityManager.START_SUCCESS) {
Slog.i(TAG, "START u" + userId + " {" + intent.toShortString(true, true, true, false)
+ "} from uid " + callingUid);
}
ActivityRecord sourceRecord = null;
ActivityRecord resultRecord = null;
if (resultTo != null) {
sourceRecord = mRootWindowContainer.isInAnyStack(resultTo);
if (DEBUG_RESULTS) {
Slog.v(TAG_RESULTS, "Will send result to " + resultTo + " " + sourceRecord);
}
if (sourceRecord != null) {
if (requestCode >= 0 && !sourceRecord.finishing) {
resultRecord = sourceRecord;
}
}
}
final int launchFlags = intent.getFlags();
if ((launchFlags & Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0 && sourceRecord != null) {
if (requestCode >= 0) {
SafeActivityOptions.abort(options);
return ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT;
}
resultRecord = sourceRecord.resultTo;
if (resultRecord != null && !resultRecord.isInStackLocked()) {
resultRecord = null;
}
resultWho = sourceRecord.resultWho;
requestCode = sourceRecord.requestCode;
sourceRecord.resultTo = null;
if (resultRecord != null) {
resultRecord.removeResultsLocked(sourceRecord, resultWho, requestCode);
}
if (sourceRecord.launchedFromUid == callingUid) {
callingPackage = sourceRecord.launchedFromPackage;
callingFeatureId = sourceRecord.launchedFromFeatureId;
}
}
final ActivityRecord r = new ActivityRecord(mService, callerApp, callingPid, callingUid,
callingPackage, callingFeatureId, intent, resolvedType, aInfo,
mService.getGlobalConfiguration(), resultRecord, resultWho, requestCode,
request.componentSpecified, voiceSession != null, mSupervisor, checkedOptions,
sourceRecord);
mLastStartActivityRecord = r;
...
final ActivityStack stack = mRootWindowContainer.getTopDisplayFocusedStack();
...
mLastStartActivityResult = startActivityUnchecked(r, sourceRecord, voiceSession,
request.voiceInteractor, startFlags, true , checkedOptions, inTask,
restrictedBgActivity, intentGrants);
if (request.outActivity != null) {
request.outActivity[0] = mLastStartActivityRecord;
}
return mLastStartActivityResult;
}
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, Task inTask,
boolean restrictedBgActivity, NeededUriGrants intentGrants) {
int result = START_CANCELED;
final ActivityStack startedActivityStack;
try {
mService.deferWindowLayout();
Trace.traceBegin(Trace.TRACE_TAG_WINDOW_MANAGER, "startActivityInner");
result = startActivityInner(r, sourceRecord, voiceSession, voiceInteractor,
startFlags, doResume, options, inTask, restrictedBgActivity, intentGrants);
} finally {
Trace.traceEnd(Trace.TRACE_TAG_WINDOW_MANAGER);
startedActivityStack = handleStartResult(r, result);
mService.continueWindowLayout();
}
postStartActivityProcessing(r, result, startedActivityStack);
return result;
}
int startActivityInner(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, Task inTask,
boolean restrictedBgActivity, NeededUriGrants intentGrants) {
setInitialState(r, options, inTask, doResume, startFlags, sourceRecord, voiceSession,
voiceInteractor, restrictedBgActivity);
computeLaunchingTaskFlags();
computeSourceStack();
mIntent.setFlags(mLaunchFlags);
...
if (mDoResume) {
final ActivityRecord topTaskActivity =
mStartActivity.getTask().topRunningActivityLocked();
if (!mTargetStack.isTopActivityFocusable()
|| (topTaskActivity != null && topTaskActivity.isTaskOverlay()
&& mStartActivity != topTaskActivity)) {
mTargetStack.ensureActivitiesVisible(null ,
0 , !PRESERVE_WINDOWS);
mTargetStack.getDisplay().mDisplayContent.executeAppTransition();
} else {
if (mTargetStack.isTopActivityFocusable()
&& !mRootWindowContainer.isTopDisplayFocusedStack(mTargetStack)) {
mTargetStack.moveToFront("startActivityInner");
}
mRootWindowContainer.resumeFocusedStacksTopActivities(
mTargetStack, mStartActivity, mOptions);
}
}
mRootWindowContainer.updateUserStack(mStartActivity.mUserId, mTargetStack);
mSupervisor.mRecentTasks.add(mStartActivity.getTask());
mSupervisor.handleNonResizableTaskIfNeeded(mStartActivity.getTask(),
mPreferredWindowingMode, mPreferredTaskDisplayArea, mTargetStack);
return START_SUCCESS;
}
-
RootWindowContainer boolean resumeFocusedStacksTopActivities(
ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
...
boolean result = false;
if (targetStack != null && (targetStack.isTopStackInDisplayArea()
|| getTopDisplayFocusedStack() == targetStack)) {
result = targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
}
...
return result;
}
-
ActivityStack 一个ActivityStack包含了若干个TaskRecord,每个TaskRecord又包含了若干个ActivityRecord,每个ActivityRecord对应了一个Activity。在这里,TaskRecord相当于在启动模式中的“任务栈”,根据启动模式的不同,在启动Activity的时候,会对TaskRecord进行不同的操作。在之前的操作中,已经将要可见的Activity放在了栈顶,只需要显示即可。 boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
if (mInResumeTopActivity) {
return false;
}
boolean result = false;
try {
mInResumeTopActivity = true;
result = resumeTopActivityInnerLocked(prev, options);
...
} finally {
mInResumeTopActivity = false;
}
return result;
}
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
if (!mAtmService.isBooting() && !mAtmService.isBooted()) {
return false;
}
if (next.attachedToProcess()) {
...
} else {
...
mStackSupervisor.startSpecificActivity(next, true, true);
}
return true;
}
-
ActivityStackSupervisor ? 在ActivityStackSupervisor的startSpecificActivity 方法中,对于已经启动进程的Activity,会调用realStartActivityLocked 方法,看名字就知道这是真正的启动Activity了(若对应Activity的进程尚未启动,则会通过ATMS的startProcessAsync 方法启动进程,这就是另一个流程了)。 void startSpecificActivity(ActivityRecord r, boolean andResume, boolean checkConfig) {
final WindowProcessController wpc =
mService.getProcessController(r.processName, r.info.applicationInfo.uid);
boolean knownToBeDead = false;
if (wpc != null && wpc.hasThread()) {
try {
realStartActivityLocked(r, wpc, andResume, checkConfig);
return;
} catch (RemoteException e) {
Slog.w(TAG, "Exception when starting activity "
+ r.intent.getComponent().flattenToShortString(), e);
}
knownToBeDead = true;
}
r.notifyUnknownVisibilityLaunchedForKeyguardTransition();
final boolean isTop = andResume && r.isTopRunningActivity();
mService.startProcessAsync(r, knownToBeDead, isTop, isTop ? "top-activity" : "activity");
}
boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
boolean andResume, boolean checkConfig) throws RemoteException {
final ClientTransaction clientTransaction = ClientTransaction.obtain(proc.getThread(), r.appToken);
clientTransaction.addCallback(LaunchActivityItem.obtain(...));
clientTransaction.setLifecycleStateRequest(ResumeActivityItem.obtain(...));
mService.getLifecycleManager().scheduleTransaction(clientTransaction);
}
mService 对应的就是ActivityTaskManagerService,即ATMS;而getLifecycleManager 对应的类是ClientLifecycleManager ,通过其scheduleTransaction 方法将对应事务发送到App进程。 在这里,obtain 方法传入的proc.getThread() ,即是联系待启动Activity进程的Binder对象,之后会于系统服务进程和App进程的跨进程通信。
- ClientLifecycleManager. ClientTransaction
mClient对应的类是IApplicationThread这个AIDL接口,具体实现类是ActivityThread.ApplicationThread。 系统服务进程ATMS将事务转发给了App进程。
-
IApplicationThread ApplicationThread ActivityThread public void scheduleTransaction(ClientTransaction transaction) throws RemoteException { ActivityThread.this.scheduleTransaction(transaction); }
ApplicationThread是ActivityThread的内部类,其实现的是IApplicationThread中的方法 -
App进程启动Activity的过程 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Fakh7iAf-1628666141160)(Acticity启动流程.assets/image-20210810121535503.png)]
-
ActivityThread、ClientTransactionHandler ActivityThread中没有该方法scheduleTransaction(),在其父类ClientTransactionHandler中实现 void scheduleTransaction(ClientTransaction transaction) { transaction.preExecute(this); sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction); }
sendMessage()方法的实现在ActivityThread,由实现可知:mH发送消息EXECUTE_TRANSACTION,mH的handleMessage()处理这个消息。mH的类H是一个ActivityThread内部类,它是一个Handler。 public void handleMessage(Message msg) { switch (msg.what) { ... case EXECUTE_TRANSACTION: final ClientTransaction transaction = (ClientTransaction) msg.obj;
-
TransactionExecutor 管理事务执行顺序 首先,所有回调顺序按照他门出现在列表中的顺序执行,其次,如果可以支持,客户端可以循环到最终的生命周期 public void execute(ClientTransaction transaction) { ...
-
LaunchActivityItem public void execute(ClientTransactionHandler client, IBinder token, PendingTransactionActions pendingActions) { Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityStart"); ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo, mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState, mPendingResults, mPendingNewIntents, mIsForward, mProfilerInfo, client, mAssistToken, mFixedRotationAdjustments);
client是ClientTransactionHandler的对象,在上面我们知道ActivityThread实现了ClientTransactionHandler类 -
ActivityThread
-
Instrumentation 就会调用Activity的performCreate()方法。 public void callActivityOnCreate(Activity activity, Bundle icicle) {
prePerformCreate(activity);
activity.performCreate(icicle);
postPerformCreate(activity);
}
-
Activity @UnsupportedAppUsage
final void performCreate(Bundle icicle, PersistableBundle persistentState) {
...
if (persistentState != null) {
onCreate(icicle, persistentState);
} else {
onCreate(icicle);
}
...
}
最后调用Activity2 重写的onCreate()方法。至此启动完成。 -
注:TransactionExecutor
-
cycleToPath() 执行到请求状态之前的状态; -
通过合适的参数执行到最后的状态 lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
2.4 对Activity启动流程的总结
- App进程和系统服务进程是通过IBinder进行进程间通信
3、Activity的启动模式
- standard:标准模式
- 会创建新的Activity实例,并将该实例添加到当前Task内。
- singleTop:Task栈顶复用模式
- 若要启动的Activity实例,已经位于栈顶,将不会创建
- 若要启动的Activity实例,没有位于栈顶,将会创建新的实例,并把它加载到栈顶
- singleTask:Task内单例模式。目的:在Task中只存在一个实例
- 若要启动的Activity不存在,则会创建新的Activity实例,并将它放入栈顶
- 若要启动的Activity存在且在栈顶,则不会创建
- 若要启动的Activity存在且不在栈顶,则会将已存在的Activity之上的所有Activity出栈,使Activity位于栈顶
- singleInstance:全局单例模式
- 若要启动的Activity不存在,则会在新的Task创建新的Activity实例,并将它放入栈顶,该Task只会存在该Activity
- 若要启动的Activity存在,则会把Activity转到栈顶,且该Task只会有这个Activity。
3.1 启动模式的原理
- ActivityStarter#startActivityInner() 启动模式的入口
int startActivityInner(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, Task inTask,
boolean restrictedBgActivity, NeededUriGrants intentGrants) {
setInitialState(r, options, inTask, doResume, startFlags, sourceRecord, voiceSession,
voiceInteractor, restrictedBgActivity);
computeLaunchingTaskFlags();
computeSourceStack();
mIntent.setFlags(mLaunchFlags);
final Task reusedTask = getReusableTask();
if (mOptions != null && mOptions.freezeRecentTasksReordering()
&& mSupervisor.mRecentTasks.isCallerRecents(r.launchedFromUid)
&& !mSupervisor.mRecentTasks.isFreezeTaskListReorderingSet()) {
mFrozeTaskList = true;
mSupervisor.mRecentTasks.setFreezeTaskListReordering();
}
final Task targetTask = reusedTask != null ? reusedTask : computeTargetTask();
final boolean newTask = targetTask == null;
mTargetTask = targetTask;
computeLaunchParams(r, sourceRecord, targetTask);
int startResult = isAllowedToStart(r, newTask, targetTask);
if (startResult != START_SUCCESS) {
return startResult;
}
final ActivityRecord targetTaskTop = newTask
? null : targetTask.getTopNonFinishingActivity();
if (targetTaskTop != null) {
startResult = recycleTask(targetTask, targetTaskTop, reusedTask, intentGrants);
if (startResult != START_SUCCESS) {
return startResult;
}
} else {
mAddingToTask = true;
}
final ActivityStack topStack = mRootWindowContainer.getTopDisplayFocusedStack();
if (topStack != null) {
startResult = deliverToCurrentTopIfNeeded(topStack, intentGrants);
if (startResult != START_SUCCESS) {
return startResult;
}
}
if (mTargetStack == null) {
mTargetStack = getLaunchStack(mStartActivity, mLaunchFlags, targetTask, mOptions);
}
if (newTask) {
final Task taskToAffiliate = (mLaunchTaskBehind && mSourceRecord != null)
? mSourceRecord.getTask() : null;
setNewTask(taskToAffiliate);
if (mService.getLockTaskController().isLockTaskModeViolation(
mStartActivity.getTask())) {
Slog.e(TAG, "Attempted Lock Task Mode violation mStartActivity=" + mStartActivity);
return START_RETURN_LOCK_TASK_MODE_VIOLATION;
}
} else if (mAddingToTask) {
addOrReparentStartingActivity(targetTask, "adding to task");
}
if (!mAvoidMoveToFront && mDoResume) {
mTargetStack.getStack().moveToFront("reuseOrNewTask", targetTask);
if (mOptions != null) {
if (mOptions.getTaskAlwaysOnTop()) {
mTargetStack.setAlwaysOnTop(true);
}
}
if (!mTargetStack.isTopStackInDisplayArea() && mService.mInternal.isDreaming()) {
mLaunchTaskBehind = true;
r.mLaunchTaskBehind = true;
}
}
mService.mUgmInternal.grantUriPermissionUncheckedFromIntent(intentGrants,
mStartActivity.getUriPermissionsLocked());
if (mStartActivity.resultTo != null && mStartActivity.resultTo.info != null) {
final PackageManagerInternal pmInternal =
mService.getPackageManagerInternalLocked();
final int resultToUid = pmInternal.getPackageUidInternal(
mStartActivity.resultTo.info.packageName, 0, mStartActivity.mUserId);
pmInternal.grantImplicitAccess(mStartActivity.mUserId, mIntent,
UserHandle.getAppId(mStartActivity.info.applicationInfo.uid) ,
resultToUid , true );
}
if (newTask) {
EventLogTags.writeWmCreateTask(mStartActivity.mUserId,
mStartActivity.getTask().mTaskId);
}
mStartActivity.logStartActivity(
EventLogTags.WM_CREATE_ACTIVITY, mStartActivity.getTask());
mTargetStack.mLastPausedActivity = null;
mRootWindowContainer.sendPowerHintForLaunchStartIfNeeded(
false , mStartActivity);
mTargetStack.startActivityLocked(mStartActivity, topStack.getTopNonFinishingActivity(),
newTask, mKeepCurTransition, mOptions);
if (mDoResume) {
final ActivityRecord topTaskActivity =
mStartActivity.getTask().topRunningActivityLocked();
if (!mTargetStack.isTopActivityFocusable()
|| (topTaskActivity != null && topTaskActivity.isTaskOverlay()
&& mStartActivity != topTaskActivity)) {
mTargetStack.ensureActivitiesVisible(null ,
0 , !PRESERVE_WINDOWS);
mTargetStack.getDisplay().mDisplayContent.executeAppTransition();
} else {
if (mTargetStack.isTopActivityFocusable()
&& !mRootWindowContainer.isTopDisplayFocusedStack(mTargetStack)) {
mTargetStack.moveToFront("startActivityInner");
}
mRootWindowContainer.resumeFocusedStacksTopActivities(
mTargetStack, mStartActivity, mOptions);
}
}
mRootWindowContainer.updateUserStack(mStartActivity.mUserId, mTargetStack);
mSupervisor.mRecentTasks.add(mStartActivity.getTask());
mSupervisor.handleNonResizableTaskIfNeeded(mStartActivity.getTask(),
mPreferredWindowingMode, mPreferredTaskDisplayArea, mTargetStack);
return START_SUCCESS;
}
private Task getReusableTask() {
if (mOptions != null && mOptions.getLaunchTaskId() != INVALID_TASK_ID) {
Task launchTask = mRootWindowContainer.anyTaskForId(mOptions.getLaunchTaskId());
if (launchTask != null) {
return launchTask;
}
return null;
}
boolean putIntoExistingTask = ((mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) != 0 &&
(mLaunchFlags & FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
|| isLaunchModeOneOf(LAUNCH_SINGLE_INSTANCE, LAUNCH_SINGLE_TASK);
putIntoExistingTask &= mInTask == null && mStartActivity.resultTo == null;
ActivityRecord intentActivity = null;
if (putIntoExistingTask) {
if (LAUNCH_SINGLE_INSTANCE == mLaunchMode) {
intentActivity = mRootWindowContainer.findActivity(mIntent, mStartActivity.info,
mStartActivity.isActivityTypeHome());
} else if ((mLaunchFlags & FLAG_ACTIVITY_LAUNCH_ADJACENT) != 0) {
intentActivity = mRootWindowContainer.findActivity(mIntent, mStartActivity.info,
!(LAUNCH_SINGLE_TASK == mLaunchMode));
} else {
intentActivity =
mRootWindowContainer.findTask(mStartActivity, mPreferredTaskDisplayArea);
}
}
if (intentActivity != null
&& (mStartActivity.isActivityTypeHome() || intentActivity.isActivityTypeHome())
&& intentActivity.getDisplayArea() != mPreferredTaskDisplayArea) {
intentActivity = null;
}
return intentActivity != null ? intentActivity.getTask() : null;
}
private int deliverToCurrentTopIfNeeded(ActivityStack topStack, NeededUriGrants intentGrants) {
final ActivityRecord top = topStack.topRunningNonDelayedActivityLocked(mNotTop);
final boolean dontStart = top != null && mStartActivity.resultTo == null
&& top.mActivityComponent.equals(mStartActivity.mActivityComponent)
&& top.mUserId == mStartActivity.mUserId
&& top.attachedToProcess()
&& ((mLaunchFlags & FLAG_ACTIVITY_SINGLE_TOP) != 0
|| isLaunchModeOneOf(LAUNCH_SINGLE_TOP, LAUNCH_SINGLE_TASK))
&& (!top.isActivityTypeHome() || top.getDisplayArea() == mPreferredTaskDisplayArea);
if (!dontStart) {
return START_SUCCESS;
}
topStack.mLastPausedActivity = null;
if (mDoResume) {
mRootWindowContainer.resumeFocusedStacksTopActivities();
}
ActivityOptions.abort(mOptions);
if ((mStartFlags & START_FLAG_ONLY_IF_NEEDED) != 0) {
return START_RETURN_INTENT_TO_CALLER;
}
deliverNewIntent(top, intentGrants);
mSupervisor.handleNonResizableTaskIfNeeded(top.getTask(),
mLaunchParams.mWindowingMode, mPreferredTaskDisplayArea, topStack);
return START_DELIVERED_TO_TOP;
}
* - 将目标任务定位在首选显示的有效堆栈上。
* - 遵守指定的活动启动标志
* - 确定是否需要在顶部添加新活动或只是将任务放在前面。
int recycleTask(Task targetTask, ActivityRecord targetTaskTop, Task reusedTask,
NeededUriGrants intentGrants) {
if (targetTask.mUserId != mStartActivity.mUserId) {
mTargetStack = targetTask.getStack();
mAddingToTask = true;
return START_SUCCESS;
}
boolean clearTaskForReuse = false;
if (reusedTask != null) {
if (mStartActivity.getTask() == null) {
mStartActivity.setTaskForReuse(reusedTask);
clearTaskForReuse = true;
}
if (targetTask.intent == null) {
targetTask.setIntent(mStartActivity);
} else {
final boolean taskOnHome =
(mStartActivity.intent.getFlags() & FLAG_ACTIVITY_TASK_ON_HOME) != 0;
if (taskOnHome) {
targetTask.intent.addFlags(FLAG_ACTIVITY_TASK_ON_HOME);
} else {
targetTask.intent.removeFlags(FLAG_ACTIVITY_TASK_ON_HOME);
}
}
}
mRootWindowContainer.sendPowerHintForLaunchStartIfNeeded(false ,
targetTaskTop);
setTargetStackIfNeeded(targetTaskTop);
if (mLastStartActivityRecord != null
&& (mLastStartActivityRecord.finishing || mLastStartActivityRecord.noDisplay)) {
mLastStartActivityRecord = targetTaskTop;
}
if ((mStartFlags & START_FLAG_ONLY_IF_NEEDED) != 0) {
if (!mMovedToFront && mDoResume) {
if (DEBUG_TASKS) {
Slog.d(TAG_TASKS, "Bring to front target: " + mTargetStack
+ " from " + targetTaskTop);
}
mTargetStack.moveToFront("intentActivityFound");
}
resumeTargetStackIfNeeded();
return START_RETURN_INTENT_TO_CALLER;
}
complyActivityFlags(targetTask,
reusedTask != null ? reusedTask.getTopNonFinishingActivity() : null, intentGrants);
if (clearTaskForReuse) {
mStartActivity.setTaskForReuse(null);
}
if (mAddingToTask) {
return START_SUCCESS;
}
if (targetTaskTop.canTurnScreenOn() && mService.mInternal.isDreaming()) {
targetTaskTop.mStackSupervisor.wakeUp("recycleTask#turnScreenOnFlag");
}
if (mMovedToFront) {
targetTaskTop.showStartingWindow(null , false ,
true );
} else if (mDoResume) {
mTargetStack.moveToFront("intentActivityFound");
}
resumeTargetStackIfNeeded();
mLastStartActivityRecord =
targetTaskTop.finishing ? targetTask.getTopNonFinishingActivity() : targetTaskTop;
return mMovedToFront ? START_TASK_TO_FRONT : START_DELIVERED_TO_TOP;
}
private void complyActivityFlags(Task targetTask, ActivityRecord reusedActivity,
NeededUriGrants intentGrants) {
ActivityRecord targetTaskTop = targetTask.getTopNonFinishingActivity();
final boolean resetTask =
reusedActivity != null && (mLaunchFlags & FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0;
if (resetTask) {
targetTaskTop = mTargetStack.resetTaskIfNeeded(targetTaskTop, mStartActivity);
}
if ((mLaunchFlags & (FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK))
== (FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK)) {
targetTask.performClearTaskLocked();
targetTask.setIntent(mStartActivity);
mAddingToTask = true;
} else if ((mLaunchFlags & FLAG_ACTIVITY_CLEAR_TOP) != 0
|| isDocumentLaunchesIntoExisting(mLaunchFlags)
|| isLaunchModeOneOf(LAUNCH_SINGLE_INSTANCE, LAUNCH_SINGLE_TASK)) {
final ActivityRecord top = targetTask.performClearTaskForReuseLocked(mStartActivity,
mLaunchFlags);
if (targetTaskTop.getTask() == null) {
targetTask.addChild(targetTaskTop);
}
if (top != null) {
if (top.isRootOfTask()) {
top.getTask().setIntent(mStartActivity);
}
deliverNewIntent(top, intentGrants);
} else {
mAddingToTask = true;
if (targetTask.getStack() == null) {
mTargetStack =
getLaunchStack(mStartActivity, mLaunchFlags, null , mOptions);
mTargetStack.addChild(targetTask, !mLaunchTaskBehind ,
(mStartActivity.info.flags & FLAG_SHOW_FOR_ALL_USERS) != 0);
}
}
} else if ((mLaunchFlags & FLAG_ACTIVITY_CLEAR_TOP) == 0 && !mAddingToTask
&& (mLaunchFlags & FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) {
final ActivityRecord act =
targetTask.findActivityInHistory(mStartActivity.mActivityComponent);
if (act != null) {
final Task task = act.getTask();
task.moveActivityToFrontLocked(act);
act.updateOptionsLocked(mOptions);
deliverNewIntent(act, intentGrants);
mTargetStack.mLastPausedActivity = null;
} else {
mAddingToTask = true;
}
} else if (mStartActivity.mActivityComponent.equals(targetTask.realActivity)) {
if (targetTask == mInTask) {
} else if (((mLaunchFlags & FLAG_ACTIVITY_SINGLE_TOP) != 0
|| LAUNCH_SINGLE_TOP == mLaunchMode)
&& targetTaskTop.mActivityComponent.equals(mStartActivity.mActivityComponent)
&& mStartActivity.resultTo == null) {
if (targetTaskTop.isRootOfTask()) {
targetTaskTop.getTask().setIntent(mStartActivity);
}
deliverNewIntent(targetTaskTop, intentGrants);
} else if (!targetTask.isSameIntentFilter(mStartActivity)) {
mAddingToTask = true;
} else if (reusedActivity == null) {
mAddingToTask = true;
}
} else if (!resetTask) {
mAddingToTask = true;
} else if (!targetTask.rootWasReset) {
targetTask.setIntent(mStartActivity);
}
}
|