blob: bcdd6e39e85cc6ec0a5b79e1aae789ed254ee2e5 [file] [log] [blame]
Kenny Guyb1b30262016-02-09 16:02:35 +00001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Wale Ogunwale59507092018-10-29 09:00:30 -070017package com.android.server.wm;
Filip Gruszczynski07a0e492015-12-17 14:16:38 -080018
Michal Karpinski7b97a022018-12-14 15:17:29 +000019import static android.Manifest.permission.START_ACTIVITIES_FROM_BACKGROUND;
Wale Ogunwale01d66562015-12-29 08:19:19 -080020import static android.app.Activity.RESULT_CANCELED;
Bryce Leef9d49542017-06-26 16:27:32 -070021import static android.app.ActivityManager.START_ABORTED;
Bryce Leeaa5e8c32017-03-01 16:01:06 -080022import static android.app.ActivityManager.START_CANCELED;
Wale Ogunwale01d66562015-12-29 08:19:19 -080023import static android.app.ActivityManager.START_CLASS_NOT_FOUND;
24import static android.app.ActivityManager.START_DELIVERED_TO_TOP;
25import static android.app.ActivityManager.START_FLAG_ONLY_IF_NEEDED;
26import static android.app.ActivityManager.START_RETURN_INTENT_TO_CALLER;
27import static android.app.ActivityManager.START_RETURN_LOCK_TASK_MODE_VIOLATION;
28import static android.app.ActivityManager.START_SUCCESS;
29import static android.app.ActivityManager.START_TASK_TO_FRONT;
Winson Chung8a168902020-03-12 22:39:22 -070030import static android.app.ActivityTaskManager.INVALID_TASK_ID;
Louis Chang0513a942019-03-06 12:38:13 +080031import static android.app.WaitResult.LAUNCH_STATE_COLD;
32import static android.app.WaitResult.LAUNCH_STATE_HOT;
Wale Ogunwale04a05ac2017-09-17 21:35:02 -070033import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
34import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale0568aed2017-09-08 13:29:37 -070035import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Filip Gruszczynski07a0e492015-12-17 14:16:38 -080036import static android.content.Intent.FLAG_ACTIVITY_CLEAR_TASK;
37import static android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP;
Wale Ogunwale2a25a622016-01-30 11:27:21 -080038import static android.content.Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT;
Filip Gruszczynski07a0e492015-12-17 14:16:38 -080039import static android.content.Intent.FLAG_ACTIVITY_MULTIPLE_TASK;
Wale Ogunwale01d66562015-12-29 08:19:19 -080040import static android.content.Intent.FLAG_ACTIVITY_NEW_DOCUMENT;
Filip Gruszczynski07a0e492015-12-17 14:16:38 -080041import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale01d66562015-12-29 08:19:19 -080042import static android.content.Intent.FLAG_ACTIVITY_NO_ANIMATION;
43import static android.content.Intent.FLAG_ACTIVITY_NO_USER_ACTION;
Wale Ogunwale01d66562015-12-29 08:19:19 -080044import static android.content.Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP;
45import static android.content.Intent.FLAG_ACTIVITY_REORDER_TO_FRONT;
46import static android.content.Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED;
47import static android.content.Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS;
48import static android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP;
Louis Changb45ee7e2019-01-17 10:36:56 +080049import static android.content.Intent.FLAG_ACTIVITY_TASK_ON_HOME;
Wale Ogunwale01d66562015-12-29 08:19:19 -080050import static android.content.pm.ActivityInfo.DOCUMENT_LAUNCH_ALWAYS;
Wale Ogunwale2322bed2019-10-10 17:24:19 +020051import static android.content.pm.ActivityInfo.FLAG_SHOW_FOR_ALL_USERS;
Wale Ogunwale01d66562015-12-29 08:19:19 -080052import static android.content.pm.ActivityInfo.LAUNCH_SINGLE_INSTANCE;
53import static android.content.pm.ActivityInfo.LAUNCH_SINGLE_TASK;
54import static android.content.pm.ActivityInfo.LAUNCH_SINGLE_TOP;
Michal Karpinski7b97a022018-12-14 15:17:29 +000055import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Andrii Kulian79d67982019-08-19 11:56:16 -070056import static android.os.Process.INVALID_UID;
David Stevensc6b91c62017-02-08 14:23:58 -080057import static android.view.Display.DEFAULT_DISPLAY;
Riddle Hsub70b36d2018-09-11 21:20:02 +080058
Wale Ogunwale59507092018-10-29 09:00:30 -070059import static com.android.server.wm.ActivityStack.ActivityState.RESUMED;
60import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
61import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
62import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
63import static com.android.server.wm.ActivityStackSupervisor.TAG_TASKS;
Bernardo Rufino1e088f12020-04-28 16:40:25 +010064import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ACTIVITY_STARTS;
Wale Ogunwale59507092018-10-29 09:00:30 -070065import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
Wale Ogunwale59507092018-10-29 09:00:30 -070066import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_PERMISSIONS_REVIEW;
67import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_RESULTS;
Wale Ogunwale59507092018-10-29 09:00:30 -070068import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
69import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_USER_LEAVING;
70import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
71import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
72import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_RESULTS;
73import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_USER_LEAVING;
74import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
75import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
76import static com.android.server.wm.ActivityTaskManagerService.ANIMATE;
Louis Chang6fb1e842018-12-03 16:07:50 +080077import static com.android.server.wm.LaunchParamsController.LaunchParamsModifier.PHASE_BOUNDS;
78import static com.android.server.wm.LaunchParamsController.LaunchParamsModifier.PHASE_DISPLAY;
Louis Changcdec0802019-11-11 11:45:07 +080079import static com.android.server.wm.Task.REPARENT_MOVE_STACK_TO_FRONT;
Louis Changa009c762020-02-26 11:21:31 +080080import static com.android.server.wm.WindowContainer.POSITION_TOP;
Winson Chung74666102017-02-22 17:49:24 -080081
Todd Kennedye9910222017-02-21 16:00:11 -080082import android.annotation.NonNull;
Jorim Jaggi4d8d32c2018-01-19 15:57:41 +010083import android.annotation.Nullable;
Filip Gruszczynski07a0e492015-12-17 14:16:38 -080084import android.app.ActivityManager;
85import android.app.ActivityOptions;
Filip Gruszczynski07a0e492015-12-17 14:16:38 -080086import android.app.IApplicationThread;
Filip Gruszczynski07a0e492015-12-17 14:16:38 -080087import android.app.PendingIntent;
88import android.app.ProfilerInfo;
Sudheer Shankafc46e9b2016-10-21 17:55:27 -070089import android.app.WaitResult;
Filip Gruszczynski07a0e492015-12-17 14:16:38 -080090import android.content.IIntentSender;
91import android.content.Intent;
92import android.content.IntentSender;
93import android.content.pm.ActivityInfo;
94import android.content.pm.ApplicationInfo;
Todd Kennedye9910222017-02-21 16:00:11 -080095import android.content.pm.AuxiliaryResolveInfo;
Kenny Guyb1b30262016-02-09 16:02:35 +000096import android.content.pm.PackageManager;
Winson81fef842019-08-28 12:19:08 -070097import android.content.pm.PackageManagerInternal;
Filip Gruszczynski07a0e492015-12-17 14:16:38 -080098import android.content.pm.ResolveInfo;
Kenny Guyb1b30262016-02-09 16:02:35 +000099import android.content.pm.UserInfo;
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800100import android.content.res.Configuration;
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800101import android.os.Binder;
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800102import android.os.Bundle;
103import android.os.IBinder;
Michal Karpinski8596ded2018-11-14 14:43:48 +0000104import android.os.Process;
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800105import android.os.RemoteException;
Michal Karpinski201bc0c2018-07-20 15:32:00 +0100106import android.os.Trace;
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800107import android.os.UserHandle;
Kenny Guyb1b30262016-02-09 16:02:35 +0000108import android.os.UserManager;
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800109import android.service.voice.IVoiceInteractionSession;
Wale Ogunwale692dcd62017-06-20 13:38:14 -0700110import android.text.TextUtils;
Michal Karpinskib7daac22019-03-25 10:12:41 +0000111import android.util.ArraySet;
Bernardo Rufino1e088f12020-04-28 16:40:25 +0100112import android.util.DebugUtils;
Bryce Leedaa91e42017-12-06 14:13:01 -0800113import android.util.Pools.SynchronizedPool;
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800114import android.util.Slog;
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800115
Bryce Leed3624e12017-11-30 08:51:45 -0800116import com.android.internal.annotations.VisibleForTesting;
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800117import com.android.internal.app.HeavyWeightSwitcherActivity;
118import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale59507092018-10-29 09:00:30 -0700119import com.android.server.am.PendingIntentRecord;
Louis Changdd3592a2018-11-05 11:04:14 +0800120import com.android.server.pm.InstantAppResolver;
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800121import com.android.server.wm.ActivityMetricsLogger.LaunchingState;
Wale Ogunwale59507092018-10-29 09:00:30 -0700122import com.android.server.wm.ActivityStackSupervisor.PendingActivityLaunch;
123import com.android.server.wm.LaunchParamsController.LaunchParams;
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800124
Wale Ogunwale692dcd62017-06-20 13:38:14 -0700125import java.io.PrintWriter;
126import java.text.DateFormat;
Wale Ogunwale692dcd62017-06-20 13:38:14 -0700127import java.util.Date;
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800128
129/**
Bryce Leed3624e12017-11-30 08:51:45 -0800130 * Controller for interpreting how and then launching an activity.
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800131 *
132 * This class collects all the logic for determining how an intent and flags should be turned into
133 * an activity and associated task and stack.
134 */
Wale Ogunwale01d66562015-12-29 08:19:19 -0800135class ActivityStarter {
Wale Ogunwale98875612018-10-12 07:53:02 -0700136 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityStarter" : TAG_ATM;
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800137 private static final String TAG_RESULTS = TAG + POSTFIX_RESULTS;
138 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
139 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
140 private static final String TAG_USER_LEAVING = TAG + POSTFIX_USER_LEAVING;
Bryce Lee7daee392017-10-12 13:46:18 -0700141 private static final int INVALID_LAUNCH_MODE = -1;
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800142
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700143 private final ActivityTaskManagerService mService;
Louis Chang149d5c82019-12-30 09:47:39 +0800144 private final RootWindowContainer mRootWindowContainer;
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800145 private final ActivityStackSupervisor mSupervisor;
Benjamin Franz563707b2017-06-29 15:06:13 +0100146 private final ActivityStartInterceptor mInterceptor;
Bryce Leed3624e12017-11-30 08:51:45 -0800147 private final ActivityStartController mController;
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800148
Wale Ogunwale01d66562015-12-29 08:19:19 -0800149 // Share state variable among methods when starting an activity.
Louis Chang07b13002019-11-27 22:08:37 +0800150 @VisibleForTesting
151 ActivityRecord mStartActivity;
Wale Ogunwale01d66562015-12-29 08:19:19 -0800152 private Intent mIntent;
153 private int mCallingUid;
154 private ActivityOptions mOptions;
155
Ricky Waib147fa12019-04-25 16:08:30 +0100156 // If it is true, background activity can only be started in an existing task that contains
Alan Stokes07389b62019-05-20 15:22:54 +0100157 // an activity with same uid, or if activity starts are enabled in developer options.
Ricky Waib147fa12019-04-25 16:08:30 +0100158 private boolean mRestrictedBgActivity;
159
Bryce Lee7daee392017-10-12 13:46:18 -0700160 private int mLaunchMode;
Wale Ogunwale01d66562015-12-29 08:19:19 -0800161 private boolean mLaunchTaskBehind;
162 private int mLaunchFlags;
163
Bryce Leeec55eb02017-12-05 20:51:27 -0800164 private LaunchParams mLaunchParams = new LaunchParams();
Wale Ogunwale01d66562015-12-29 08:19:19 -0800165
166 private ActivityRecord mNotTop;
167 private boolean mDoResume;
168 private int mStartFlags;
169 private ActivityRecord mSourceRecord;
Bryce Lee7daee392017-10-12 13:46:18 -0700170
Andrii Kulian1cfcae82020-04-10 12:44:38 -0700171 // The task display area to launch the activity onto, barring any strong reason to do otherwise.
172 private TaskDisplayArea mPreferredTaskDisplayArea;
Winson Chung8a168902020-03-12 22:39:22 -0700173 private int mPreferredWindowingMode;
Wale Ogunwale01d66562015-12-29 08:19:19 -0800174
Louis Changcdec0802019-11-11 11:45:07 +0800175 private Task mInTask;
Louis Chang07b13002019-11-27 22:08:37 +0800176 @VisibleForTesting
177 boolean mAddingToTask;
Louis Changcdec0802019-11-11 11:45:07 +0800178 private Task mReuseTask;
Wale Ogunwale01d66562015-12-29 08:19:19 -0800179
180 private ActivityInfo mNewTaskInfo;
181 private Intent mNewTaskIntent;
182 private ActivityStack mSourceStack;
183 private ActivityStack mTargetStack;
Winson Chunge789ff62020-02-24 14:40:23 -0800184 // The task that the last activity was started into. We currently reset the actual start
185 // activity's task and as a result may not have a reference to the task in all cases
186 private Task mTargetTask;
Wale Ogunwale01d66562015-12-29 08:19:19 -0800187 private boolean mMovedToFront;
188 private boolean mNoAnimation;
189 private boolean mKeepCurTransition;
Jorim Jaggic875ae72016-04-26 22:41:06 -0700190 private boolean mAvoidMoveToFront;
Winson Chunge219ae12019-07-18 13:43:23 -0700191 private boolean mFrozeTaskList;
Wale Ogunwale01d66562015-12-29 08:19:19 -0800192
Bryce Lee325e09682017-10-05 17:20:25 -0700193 // We must track when we deliver the new intent since multiple code paths invoke
194 // {@link #deliverNewIntent}. This is due to early returns in the code path. This flag is used
195 // inside {@link #deliverNewIntent} to suppress duplicate requests and ensure the intent is
196 // delivered at most once.
197 private boolean mIntentDelivered;
198
Wale Ogunwale01d66562015-12-29 08:19:19 -0800199 private IVoiceInteractionSession mVoiceSession;
200 private IVoiceInteractor mVoiceInteractor;
201
Wale Ogunwale692dcd62017-06-20 13:38:14 -0700202 // Last activity record we attempted to start
Louis Chang54fbb052019-10-16 17:10:17 +0800203 private ActivityRecord mLastStartActivityRecord;
Wale Ogunwale692dcd62017-06-20 13:38:14 -0700204 // The result of the last activity we attempted to start.
205 private int mLastStartActivityResult;
206 // Time in milli seconds we attempted to start the last activity.
207 private long mLastStartActivityTimeMs;
208 // The reason we were trying to start the last activity
209 private String mLastStartReason;
Wale Ogunwale59bcba62017-06-16 12:42:51 -0700210
Bryce Lee4c9a5972017-12-01 22:14:24 -0800211 /*
212 * Request details provided through setter methods. Should be reset after {@link #execute()}
213 * to avoid unnecessarily retaining parameters. Note that the request is ignored when
214 * {@link #startResolvedActivity} is invoked directly.
215 */
Louis Chang54fbb052019-10-16 17:10:17 +0800216 @VisibleForTesting
217 Request mRequest = new Request();
Bryce Lee4c9a5972017-12-01 22:14:24 -0800218
Bryce Leed3624e12017-11-30 08:51:45 -0800219 /**
220 * An interface that to provide {@link ActivityStarter} instances to the controller. This is
221 * used by tests to inject their own starter implementations for verification purposes.
222 */
223 @VisibleForTesting
224 interface Factory {
225 /**
Bryce Lee4c9a5972017-12-01 22:14:24 -0800226 * Sets the {@link ActivityStartController} to be passed to {@link ActivityStarter}.
227 */
228 void setController(ActivityStartController controller);
229
230 /**
Bryce Leed3624e12017-11-30 08:51:45 -0800231 * Generates an {@link ActivityStarter} that is ready to handle a new start request.
232 * @param controller The {@link ActivityStartController} which the starter who will own
233 * this instance.
234 * @return an {@link ActivityStarter}
235 */
Bryce Leedaa91e42017-12-06 14:13:01 -0800236 ActivityStarter obtain();
237
238 /**
239 * Recycles a starter for reuse.
240 */
241 void recycle(ActivityStarter starter);
Wale Ogunwale01d66562015-12-29 08:19:19 -0800242 }
243
Bryce Leed3624e12017-11-30 08:51:45 -0800244 /**
245 * Default implementation of {@link StarterFactory}.
246 */
247 static class DefaultFactory implements Factory {
Bryce Leedaa91e42017-12-06 14:13:01 -0800248 /**
249 * The maximum count of starters that should be active at one time:
250 * 1. last ran starter (for logging and post activity processing)
251 * 2. current running starter
252 * 3. starter from re-entry in (2)
253 */
254 private final int MAX_STARTER_COUNT = 3;
255
Bryce Lee4c9a5972017-12-01 22:14:24 -0800256 private ActivityStartController mController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700257 private ActivityTaskManagerService mService;
Bryce Lee4c9a5972017-12-01 22:14:24 -0800258 private ActivityStackSupervisor mSupervisor;
259 private ActivityStartInterceptor mInterceptor;
260
Bryce Leedaa91e42017-12-06 14:13:01 -0800261 private SynchronizedPool<ActivityStarter> mStarterPool =
262 new SynchronizedPool<>(MAX_STARTER_COUNT);
263
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700264 DefaultFactory(ActivityTaskManagerService service,
Bryce Lee4c9a5972017-12-01 22:14:24 -0800265 ActivityStackSupervisor supervisor, ActivityStartInterceptor interceptor) {
266 mService = service;
267 mSupervisor = supervisor;
268 mInterceptor = interceptor;
Bryce Leed3624e12017-11-30 08:51:45 -0800269 }
Bryce Lee4c9a5972017-12-01 22:14:24 -0800270
271 @Override
272 public void setController(ActivityStartController controller) {
273 mController = controller;
274 }
275
276 @Override
Bryce Leedaa91e42017-12-06 14:13:01 -0800277 public ActivityStarter obtain() {
278 ActivityStarter starter = mStarterPool.acquire();
279
280 if (starter == null) {
281 starter = new ActivityStarter(mController, mService, mSupervisor, mInterceptor);
282 }
283
284 return starter;
285 }
286
287 @Override
288 public void recycle(ActivityStarter starter) {
289 starter.reset(true /* clearRequest*/);
290 mStarterPool.release(starter);
Bryce Lee4c9a5972017-12-01 22:14:24 -0800291 }
292 }
293
294 /**
295 * Container for capturing initial start request details. This information is NOT reset until
296 * the {@link ActivityStarter} is recycled, allowing for multiple invocations with the same
297 * parameters.
298 *
299 * TODO(b/64750076): Investigate consolidating member variables of {@link ActivityStarter} with
300 * the request object. Note that some member variables are referenced in
301 * {@link #dump(PrintWriter, String)} and therefore cannot be cleared immediately after
302 * execution.
303 */
Louis Chang54fbb052019-10-16 17:10:17 +0800304 @VisibleForTesting
305 static class Request {
Bryce Lee4c9a5972017-12-01 22:14:24 -0800306 private static final int DEFAULT_CALLING_UID = -1;
307 private static final int DEFAULT_CALLING_PID = 0;
Michal Karpinski84d9ebd2019-01-17 18:28:59 +0000308 static final int DEFAULT_REAL_CALLING_UID = -1;
309 static final int DEFAULT_REAL_CALLING_PID = 0;
Bryce Lee4c9a5972017-12-01 22:14:24 -0800310
311 IApplicationThread caller;
312 Intent intent;
Louis Chang54fbb052019-10-16 17:10:17 +0800313 // A copy of the original requested intent, in case for ephemeral app launch.
Bryce Lee4c9a5972017-12-01 22:14:24 -0800314 Intent ephemeralIntent;
315 String resolvedType;
316 ActivityInfo activityInfo;
317 ResolveInfo resolveInfo;
318 IVoiceInteractionSession voiceSession;
319 IVoiceInteractor voiceInteractor;
320 IBinder resultTo;
321 String resultWho;
322 int requestCode;
Michal Karpinski84d9ebd2019-01-17 18:28:59 +0000323 int callingPid = DEFAULT_CALLING_PID;
324 int callingUid = DEFAULT_CALLING_UID;
Bryce Lee4c9a5972017-12-01 22:14:24 -0800325 String callingPackage;
Philip P. Moltmannee295092020-02-10 08:46:26 -0800326 @Nullable String callingFeatureId;
Michal Karpinski84d9ebd2019-01-17 18:28:59 +0000327 int realCallingPid = DEFAULT_REAL_CALLING_PID;
328 int realCallingUid = DEFAULT_REAL_CALLING_UID;
Bryce Lee4c9a5972017-12-01 22:14:24 -0800329 int startFlags;
Jorim Jaggi4d8d32c2018-01-19 15:57:41 +0100330 SafeActivityOptions activityOptions;
Bryce Lee4c9a5972017-12-01 22:14:24 -0800331 boolean ignoreTargetSecurity;
332 boolean componentSpecified;
Winson Chunge2d72172018-01-25 17:46:20 +0000333 boolean avoidMoveToFront;
Bryce Lee4c9a5972017-12-01 22:14:24 -0800334 ActivityRecord[] outActivity;
Louis Changcdec0802019-11-11 11:45:07 +0800335 Task inTask;
Bryce Lee4c9a5972017-12-01 22:14:24 -0800336 String reason;
337 ProfilerInfo profilerInfo;
338 Configuration globalConfig;
Bryce Lee4c9a5972017-12-01 22:14:24 -0800339 int userId;
340 WaitResult waitResult;
Patrick Baumann31426b22018-05-21 13:46:40 -0700341 int filterCallingUid;
Michal Karpinski201bc0c2018-07-20 15:32:00 +0100342 PendingIntentRecord originatingPendingIntent;
Michal Karpinskiac116df2018-12-10 17:51:42 +0000343 boolean allowBackgroundActivityStart;
Bryce Lee4c9a5972017-12-01 22:14:24 -0800344
345 /**
Jorim Jaggi6fa41c32018-04-23 18:35:00 +0200346 * If set to {@code true}, allows this activity start to look into
347 * {@link PendingRemoteAnimationRegistry}
348 */
349 boolean allowPendingRemoteAnimationRegistryLookup;
350
351 /**
Bryce Leea3cd8e02018-01-09 15:44:24 -0800352 * Ensure constructed request matches reset instance.
353 */
354 Request() {
355 reset();
356 }
357
358 /**
Bryce Leedaa91e42017-12-06 14:13:01 -0800359 * Sets values back to the initial state, clearing any held references.
360 */
361 void reset() {
362 caller = null;
363 intent = null;
364 ephemeralIntent = null;
365 resolvedType = null;
366 activityInfo = null;
367 resolveInfo = null;
368 voiceSession = null;
369 voiceInteractor = null;
370 resultTo = null;
371 resultWho = null;
372 requestCode = 0;
Bryce Leea3cd8e02018-01-09 15:44:24 -0800373 callingPid = DEFAULT_CALLING_PID;
374 callingUid = DEFAULT_CALLING_UID;
Bryce Leedaa91e42017-12-06 14:13:01 -0800375 callingPackage = null;
Philip P. Moltmannee295092020-02-10 08:46:26 -0800376 callingFeatureId = null;
Michal Karpinski84d9ebd2019-01-17 18:28:59 +0000377 realCallingPid = DEFAULT_REAL_CALLING_PID;
378 realCallingUid = DEFAULT_REAL_CALLING_UID;
Bryce Leedaa91e42017-12-06 14:13:01 -0800379 startFlags = 0;
380 activityOptions = null;
381 ignoreTargetSecurity = false;
382 componentSpecified = false;
383 outActivity = null;
384 inTask = null;
385 reason = null;
386 profilerInfo = null;
387 globalConfig = null;
Bryce Leedaa91e42017-12-06 14:13:01 -0800388 userId = 0;
389 waitResult = null;
Winson Chunge2d72172018-01-25 17:46:20 +0000390 avoidMoveToFront = false;
Jorim Jaggi6fa41c32018-04-23 18:35:00 +0200391 allowPendingRemoteAnimationRegistryLookup = true;
Patrick Baumann31426b22018-05-21 13:46:40 -0700392 filterCallingUid = UserHandle.USER_NULL;
Michal Karpinski201bc0c2018-07-20 15:32:00 +0100393 originatingPendingIntent = null;
Michal Karpinskiac116df2018-12-10 17:51:42 +0000394 allowBackgroundActivityStart = false;
Bryce Leedaa91e42017-12-06 14:13:01 -0800395 }
396
397 /**
398 * Adopts all values from passed in request.
399 */
400 void set(Request request) {
401 caller = request.caller;
402 intent = request.intent;
403 ephemeralIntent = request.ephemeralIntent;
404 resolvedType = request.resolvedType;
405 activityInfo = request.activityInfo;
406 resolveInfo = request.resolveInfo;
407 voiceSession = request.voiceSession;
408 voiceInteractor = request.voiceInteractor;
409 resultTo = request.resultTo;
410 resultWho = request.resultWho;
411 requestCode = request.requestCode;
412 callingPid = request.callingPid;
413 callingUid = request.callingUid;
414 callingPackage = request.callingPackage;
Philip P. Moltmannee295092020-02-10 08:46:26 -0800415 callingFeatureId = request.callingFeatureId;
Bryce Leedaa91e42017-12-06 14:13:01 -0800416 realCallingPid = request.realCallingPid;
417 realCallingUid = request.realCallingUid;
418 startFlags = request.startFlags;
419 activityOptions = request.activityOptions;
420 ignoreTargetSecurity = request.ignoreTargetSecurity;
421 componentSpecified = request.componentSpecified;
422 outActivity = request.outActivity;
423 inTask = request.inTask;
424 reason = request.reason;
425 profilerInfo = request.profilerInfo;
426 globalConfig = request.globalConfig;
Bryce Leedaa91e42017-12-06 14:13:01 -0800427 userId = request.userId;
428 waitResult = request.waitResult;
Winson Chunge2d72172018-01-25 17:46:20 +0000429 avoidMoveToFront = request.avoidMoveToFront;
Jorim Jaggi6fa41c32018-04-23 18:35:00 +0200430 allowPendingRemoteAnimationRegistryLookup
431 = request.allowPendingRemoteAnimationRegistryLookup;
Patrick Baumann31426b22018-05-21 13:46:40 -0700432 filterCallingUid = request.filterCallingUid;
Michal Karpinski201bc0c2018-07-20 15:32:00 +0100433 originatingPendingIntent = request.originatingPendingIntent;
Michal Karpinskiac116df2018-12-10 17:51:42 +0000434 allowBackgroundActivityStart = request.allowBackgroundActivityStart;
Bryce Leedaa91e42017-12-06 14:13:01 -0800435 }
Louis Chang54fbb052019-10-16 17:10:17 +0800436
437 /**
438 * Resolve activity from the given intent for this launch.
439 */
440 void resolveActivity(ActivityStackSupervisor supervisor) {
441 if (realCallingPid == Request.DEFAULT_REAL_CALLING_PID) {
442 realCallingPid = Binder.getCallingPid();
443 }
444 if (realCallingUid == Request.DEFAULT_REAL_CALLING_UID) {
445 realCallingUid = Binder.getCallingUid();
446 }
447
448 if (callingUid >= 0) {
449 callingPid = -1;
450 } else if (caller == null) {
451 callingPid = realCallingPid;
452 callingUid = realCallingUid;
453 } else {
454 callingPid = callingUid = -1;
455 }
456
457 // Save a copy in case ephemeral needs it
458 ephemeralIntent = new Intent(intent);
459 // Don't modify the client's object!
460 intent = new Intent(intent);
461 if (intent.getComponent() != null
462 && !(Intent.ACTION_VIEW.equals(intent.getAction()) && intent.getData() == null)
463 && !Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE.equals(intent.getAction())
464 && !Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE.equals(intent.getAction())
465 && supervisor.mService.getPackageManagerInternalLocked()
466 .isInstantAppInstallerComponent(intent.getComponent())) {
467 // Intercept intents targeted directly to the ephemeral installer the ephemeral
468 // installer should never be started with a raw Intent; instead adjust the intent
469 // so it looks like a "normal" instant app launch.
470 intent.setComponent(null /* component */);
471 }
472
473 resolveInfo = supervisor.resolveIntent(intent, resolvedType, userId,
474 0 /* matchFlags */,
475 computeResolveFilterUid(callingUid, realCallingUid, filterCallingUid));
476 if (resolveInfo == null) {
477 final UserInfo userInfo = supervisor.getUserInfo(userId);
478 if (userInfo != null && userInfo.isManagedProfile()) {
479 // Special case for managed profiles, if attempting to launch non-cryto aware
480 // app in a locked managed profile from an unlocked parent allow it to resolve
481 // as user will be sent via confirm credentials to unlock the profile.
482 final UserManager userManager = UserManager.get(supervisor.mService.mContext);
483 boolean profileLockedAndParentUnlockingOrUnlocked = false;
484 final long token = Binder.clearCallingIdentity();
485 try {
486 final UserInfo parent = userManager.getProfileParent(userId);
487 profileLockedAndParentUnlockingOrUnlocked = (parent != null)
488 && userManager.isUserUnlockingOrUnlocked(parent.id)
489 && !userManager.isUserUnlockingOrUnlocked(userId);
490 } finally {
491 Binder.restoreCallingIdentity(token);
492 }
493 if (profileLockedAndParentUnlockingOrUnlocked) {
494 resolveInfo = supervisor.resolveIntent(intent, resolvedType, userId,
495 PackageManager.MATCH_DIRECT_BOOT_AWARE
496 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
497 computeResolveFilterUid(callingUid, realCallingUid,
498 filterCallingUid));
499 }
500 }
501 }
502
503 // Collect information about the target of the Intent.
504 activityInfo = supervisor.resolveActivity(intent, resolveInfo, startFlags,
505 profilerInfo);
506 }
Bryce Leed3624e12017-11-30 08:51:45 -0800507 }
508
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700509 ActivityStarter(ActivityStartController controller, ActivityTaskManagerService service,
Bryce Leed3624e12017-11-30 08:51:45 -0800510 ActivityStackSupervisor supervisor, ActivityStartInterceptor interceptor) {
511 mController = controller;
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800512 mService = service;
Louis Chang149d5c82019-12-30 09:47:39 +0800513 mRootWindowContainer = service.mRootWindowContainer;
Bryce Leed3624e12017-11-30 08:51:45 -0800514 mSupervisor = supervisor;
515 mInterceptor = interceptor;
Bryce Leedaa91e42017-12-06 14:13:01 -0800516 reset(true);
517 }
518
519 /**
520 * Effectively duplicates the starter passed in. All state and request values will be
521 * mirrored.
522 * @param starter
523 */
524 void set(ActivityStarter starter) {
525 mStartActivity = starter.mStartActivity;
526 mIntent = starter.mIntent;
527 mCallingUid = starter.mCallingUid;
528 mOptions = starter.mOptions;
Ricky Waib147fa12019-04-25 16:08:30 +0100529 mRestrictedBgActivity = starter.mRestrictedBgActivity;
Bryce Leedaa91e42017-12-06 14:13:01 -0800530
531 mLaunchTaskBehind = starter.mLaunchTaskBehind;
532 mLaunchFlags = starter.mLaunchFlags;
533 mLaunchMode = starter.mLaunchMode;
534
Bryce Leeec55eb02017-12-05 20:51:27 -0800535 mLaunchParams.set(starter.mLaunchParams);
Bryce Leedaa91e42017-12-06 14:13:01 -0800536
537 mNotTop = starter.mNotTop;
538 mDoResume = starter.mDoResume;
539 mStartFlags = starter.mStartFlags;
540 mSourceRecord = starter.mSourceRecord;
Andrii Kulian1cfcae82020-04-10 12:44:38 -0700541 mPreferredTaskDisplayArea = starter.mPreferredTaskDisplayArea;
Winson Chung8a168902020-03-12 22:39:22 -0700542 mPreferredWindowingMode = starter.mPreferredWindowingMode;
Bryce Leedaa91e42017-12-06 14:13:01 -0800543
544 mInTask = starter.mInTask;
545 mAddingToTask = starter.mAddingToTask;
546 mReuseTask = starter.mReuseTask;
547
548 mNewTaskInfo = starter.mNewTaskInfo;
549 mNewTaskIntent = starter.mNewTaskIntent;
550 mSourceStack = starter.mSourceStack;
551
Winson Chunge789ff62020-02-24 14:40:23 -0800552 mTargetTask = starter.mTargetTask;
Bryce Leedaa91e42017-12-06 14:13:01 -0800553 mTargetStack = starter.mTargetStack;
554 mMovedToFront = starter.mMovedToFront;
555 mNoAnimation = starter.mNoAnimation;
556 mKeepCurTransition = starter.mKeepCurTransition;
557 mAvoidMoveToFront = starter.mAvoidMoveToFront;
Winson Chunge219ae12019-07-18 13:43:23 -0700558 mFrozeTaskList = starter.mFrozeTaskList;
Bryce Leedaa91e42017-12-06 14:13:01 -0800559
560 mVoiceSession = starter.mVoiceSession;
561 mVoiceInteractor = starter.mVoiceInteractor;
562
563 mIntentDelivered = starter.mIntentDelivered;
564
565 mRequest.set(starter.mRequest);
Bryce Leed3624e12017-11-30 08:51:45 -0800566 }
567
Bryce Lee4c9a5972017-12-01 22:14:24 -0800568 boolean relatedToPackage(String packageName) {
Louis Chang54fbb052019-10-16 17:10:17 +0800569 return (mLastStartActivityRecord != null
570 && packageName.equals(mLastStartActivityRecord.packageName))
Bryce Lee4c9a5972017-12-01 22:14:24 -0800571 || (mStartActivity != null && packageName.equals(mStartActivity.packageName));
572 }
573
574 /**
Louis Chang54fbb052019-10-16 17:10:17 +0800575 * Starts an activity based on the provided {@link ActivityRecord} and environment parameters.
576 * Note that this method is called internally as well as part of {@link #executeRequest}.
577 */
578 void startResolvedActivity(final ActivityRecord r, ActivityRecord sourceRecord,
579 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
Louis Changcdec0802019-11-11 11:45:07 +0800580 int startFlags, boolean doResume, ActivityOptions options, Task inTask) {
Louis Chang54fbb052019-10-16 17:10:17 +0800581 try {
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800582 final LaunchingState launchingState = mSupervisor.getActivityMetricsLogger()
583 .notifyActivityLaunching(r.intent, r.resultTo);
Louis Chang54fbb052019-10-16 17:10:17 +0800584 mLastStartReason = "startResolvedActivity";
585 mLastStartActivityTimeMs = System.currentTimeMillis();
586 mLastStartActivityRecord = r;
587 mLastStartActivityResult = startActivityUnchecked(r, sourceRecord, voiceSession,
588 voiceInteractor, startFlags, doResume, options, inTask,
589 false /* restrictedBgActivity */);
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800590 mSupervisor.getActivityMetricsLogger().notifyActivityLaunched(launchingState,
591 mLastStartActivityResult, mLastStartActivityRecord);
Louis Chang54fbb052019-10-16 17:10:17 +0800592 } finally {
593 onExecutionComplete();
594 }
595 }
596
597 /**
598 * Resolve necessary information according the request parameters provided earlier, and execute
599 * the request which begin the journey of starting an activity.
Bryce Lee4c9a5972017-12-01 22:14:24 -0800600 * @return The starter result.
601 */
602 int execute() {
Bryce Leedaa91e42017-12-06 14:13:01 -0800603 try {
Louis Chang54fbb052019-10-16 17:10:17 +0800604 // Refuse possible leaked file descriptors
605 if (mRequest.intent != null && mRequest.intent.hasFileDescriptors()) {
606 throw new IllegalArgumentException("File descriptors passed in Intent");
607 }
608
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800609 final LaunchingState launchingState;
610 synchronized (mService.mGlobalLock) {
611 final ActivityRecord caller = ActivityRecord.forTokenLocked(mRequest.resultTo);
612 launchingState = mSupervisor.getActivityMetricsLogger().notifyActivityLaunching(
613 mRequest.intent, caller);
614 }
Louis Chang54fbb052019-10-16 17:10:17 +0800615
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800616 // Do not lock the resolving to avoid potential deadlock.
Louis Chang54fbb052019-10-16 17:10:17 +0800617 if (mRequest.activityInfo == null) {
618 mRequest.resolveActivity(mSupervisor);
619 }
620
621 int res;
622 synchronized (mService.mGlobalLock) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -0800623 final boolean globalConfigWillChange = mRequest.globalConfig != null
Louis Chang54fbb052019-10-16 17:10:17 +0800624 && mService.getGlobalConfiguration().diff(mRequest.globalConfig) != 0;
Darryl L Johnson1e3885c2020-02-27 17:38:13 -0800625 final ActivityStack stack = mRootWindowContainer.getTopDisplayFocusedStack();
626 if (stack != null) {
627 stack.mConfigWillChange = globalConfigWillChange;
628 }
Louis Chang54fbb052019-10-16 17:10:17 +0800629 if (DEBUG_CONFIGURATION) {
630 Slog.v(TAG_CONFIGURATION, "Starting activity when config will change = "
Darryl L Johnson1e3885c2020-02-27 17:38:13 -0800631 + globalConfigWillChange);
Louis Chang54fbb052019-10-16 17:10:17 +0800632 }
633
634 final long origId = Binder.clearCallingIdentity();
635
636 res = resolveToHeavyWeightSwitcherIfNeeded();
637 if (res != START_SUCCESS) {
638 return res;
639 }
640 res = executeRequest(mRequest);
641
642 Binder.restoreCallingIdentity(origId);
643
Darryl L Johnson1e3885c2020-02-27 17:38:13 -0800644 if (globalConfigWillChange) {
Louis Chang54fbb052019-10-16 17:10:17 +0800645 // If the caller also wants to switch to a new configuration, do so now.
646 // This allows a clean switch, as we are waiting for the current activity
647 // to pause (so we will not destroy it), and have not yet started the
648 // next activity.
649 mService.mAmInternal.enforceCallingPermission(
650 android.Manifest.permission.CHANGE_CONFIGURATION,
651 "updateConfiguration()");
Darryl L Johnson1e3885c2020-02-27 17:38:13 -0800652 if (stack != null) {
653 stack.mConfigWillChange = false;
654 }
Louis Chang54fbb052019-10-16 17:10:17 +0800655 if (DEBUG_CONFIGURATION) {
656 Slog.v(TAG_CONFIGURATION,
657 "Updating to new configuration after starting activity.");
658 }
659 mService.updateConfigurationLocked(mRequest.globalConfig, null, false);
660 }
661
662 // Notify ActivityMetricsLogger that the activity has launched.
663 // ActivityMetricsLogger will then wait for the windows to be drawn and populate
664 // WaitResult.
Riddle Hsufd66d4d2019-11-14 10:35:55 +0800665 mSupervisor.getActivityMetricsLogger().notifyActivityLaunched(launchingState, res,
Louis Chang54fbb052019-10-16 17:10:17 +0800666 mLastStartActivityRecord);
667 return getExternalResult(mRequest.waitResult == null ? res
668 : waitForResult(res, mLastStartActivityRecord));
Bryce Leedaa91e42017-12-06 14:13:01 -0800669 }
670 } finally {
671 onExecutionComplete();
672 }
673 }
674
675 /**
Louis Chang54fbb052019-10-16 17:10:17 +0800676 * Updates the request to heavy-weight switch if this is a heavy-weight process while there
677 * already have another, different heavy-weight process running.
Bryce Leedaa91e42017-12-06 14:13:01 -0800678 */
Louis Chang54fbb052019-10-16 17:10:17 +0800679 private int resolveToHeavyWeightSwitcherIfNeeded() {
680 if (mRequest.activityInfo == null || !mService.mHasHeavyWeightFeature
681 || (mRequest.activityInfo.applicationInfo.privateFlags
682 & ApplicationInfo.PRIVATE_FLAG_CANT_SAVE_STATE) == 0) {
683 return START_SUCCESS;
Wale Ogunwale692dcd62017-06-20 13:38:14 -0700684 }
Bryce Leef9d49542017-06-26 16:27:32 -0700685
Louis Chang54fbb052019-10-16 17:10:17 +0800686 if (!mRequest.activityInfo.processName.equals(
687 mRequest.activityInfo.applicationInfo.packageName)) {
688 return START_SUCCESS;
689 }
Bryce Lee93e7f792017-10-25 15:54:55 -0700690
Louis Chang54fbb052019-10-16 17:10:17 +0800691 final WindowProcessController heavy = mService.mHeavyWeightProcess;
692 if (heavy == null || (heavy.mInfo.uid == mRequest.activityInfo.applicationInfo.uid
693 && heavy.mName.equals(mRequest.activityInfo.processName))) {
694 return START_SUCCESS;
695 }
696
697 int appCallingUid = mRequest.callingUid;
698 if (mRequest.caller != null) {
699 WindowProcessController callerApp = mService.getProcessController(mRequest.caller);
700 if (callerApp != null) {
701 appCallingUid = callerApp.mInfo.uid;
702 } else {
703 Slog.w(TAG, "Unable to find app for caller " + mRequest.caller + " (pid="
704 + mRequest.callingPid + ") when starting: " + mRequest.intent.toString());
705 SafeActivityOptions.abort(mRequest.activityOptions);
706 return ActivityManager.START_PERMISSION_DENIED;
707 }
708 }
709
710 final IIntentSender target = mService.getIntentSenderLocked(
Philip P. Moltmannee295092020-02-10 08:46:26 -0800711 ActivityManager.INTENT_SENDER_ACTIVITY, "android" /* packageName */,
712 null /* featureId */, appCallingUid, mRequest.userId, null /* token */,
713 null /* resultWho*/, 0 /* requestCode*/, new Intent[]{mRequest.intent},
714 new String[]{mRequest.resolvedType},
Louis Chang54fbb052019-10-16 17:10:17 +0800715 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT,
716 null /* bOptions */);
717
718 final Intent newIntent = new Intent();
719 if (mRequest.requestCode >= 0) {
720 // Caller is requesting a result.
721 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_HAS_RESULT, true);
722 }
723 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_INTENT, new IntentSender(target));
724 heavy.updateIntentForHeavyWeightActivity(newIntent);
725 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_NEW_APP,
726 mRequest.activityInfo.packageName);
727 newIntent.setFlags(mRequest.intent.getFlags());
728 newIntent.setClassName("android" /* packageName */,
729 HeavyWeightSwitcherActivity.class.getName());
730 mRequest.intent = newIntent;
731 mRequest.resolvedType = null;
732 mRequest.caller = null;
733 mRequest.callingUid = Binder.getCallingUid();
734 mRequest.callingPid = Binder.getCallingPid();
735 mRequest.componentSpecified = true;
736 mRequest.resolveInfo = mSupervisor.resolveIntent(mRequest.intent, null /* resolvedType */,
737 mRequest.userId, 0 /* matchFlags */,
738 computeResolveFilterUid(mRequest.callingUid, mRequest.realCallingUid,
739 mRequest.filterCallingUid));
740 mRequest.activityInfo =
741 mRequest.resolveInfo != null ? mRequest.resolveInfo.activityInfo : null;
742 if (mRequest.activityInfo != null) {
743 mRequest.activityInfo = mService.mAmInternal.getActivityInfoForUser(
744 mRequest.activityInfo, mRequest.userId);
745 }
746
747 return START_SUCCESS;
Wale Ogunwale692dcd62017-06-20 13:38:14 -0700748 }
749
Bryce Leedaa91e42017-12-06 14:13:01 -0800750 /**
Louis Chang54fbb052019-10-16 17:10:17 +0800751 * Wait for activity launch completes.
Bryce Leedaa91e42017-12-06 14:13:01 -0800752 */
Louis Chang54fbb052019-10-16 17:10:17 +0800753 private int waitForResult(int res, ActivityRecord r) {
754 mRequest.waitResult.result = res;
755 switch(res) {
756 case START_SUCCESS: {
757 mSupervisor.mWaitingActivityLaunched.add(mRequest.waitResult);
758 do {
759 try {
760 mService.mGlobalLock.wait();
761 } catch (InterruptedException e) {
762 }
763 } while (mRequest.waitResult.result != START_TASK_TO_FRONT
764 && !mRequest.waitResult.timeout && mRequest.waitResult.who == null);
765 if (mRequest.waitResult.result == START_TASK_TO_FRONT) {
766 res = START_TASK_TO_FRONT;
767 }
768 break;
769 }
770 case START_DELIVERED_TO_TOP: {
771 mRequest.waitResult.timeout = false;
772 mRequest.waitResult.who = r.mActivityComponent;
773 mRequest.waitResult.totalTime = 0;
774 break;
775 }
776 case START_TASK_TO_FRONT: {
777 mRequest.waitResult.launchState =
778 r.attachedToProcess() ? LAUNCH_STATE_HOT : LAUNCH_STATE_COLD;
779 // ActivityRecord may represent a different activity, but it should not be
780 // in the resumed state.
781 if (r.nowVisible && r.isState(RESUMED)) {
782 mRequest.waitResult.timeout = false;
783 mRequest.waitResult.who = r.mActivityComponent;
784 mRequest.waitResult.totalTime = 0;
785 } else {
Riddle Hsuc48c8912019-10-31 13:34:27 +0800786 mSupervisor.waitActivityVisible(r.mActivityComponent, mRequest.waitResult);
Louis Chang54fbb052019-10-16 17:10:17 +0800787 // Note: the timeout variable is not currently not ever set.
788 do {
789 try {
790 mService.mGlobalLock.wait();
791 } catch (InterruptedException e) {
792 }
793 } while (!mRequest.waitResult.timeout && mRequest.waitResult.who == null);
794 }
795 break;
796 }
797 }
798 return res;
Bryce Leedaa91e42017-12-06 14:13:01 -0800799 }
800
Louis Chang54fbb052019-10-16 17:10:17 +0800801 /**
802 * Executing activity start request and starts the journey of starting an activity. Here
803 * begins with performing several preliminary checks. The normally activity launch flow will
804 * go through {@link #startActivityUnchecked} to {@link #startActivityInner}.
805 */
806 private int executeRequest(Request request) {
807 if (TextUtils.isEmpty(request.reason)) {
808 throw new IllegalArgumentException("Need to specify a reason.");
809 }
810 mLastStartReason = request.reason;
811 mLastStartActivityTimeMs = System.currentTimeMillis();
812 mLastStartActivityRecord = null;
813
814 final IApplicationThread caller = request.caller;
815 Intent intent = request.intent;
816 String resolvedType = request.resolvedType;
817 ActivityInfo aInfo = request.activityInfo;
818 ResolveInfo rInfo = request.resolveInfo;
819 final IVoiceInteractionSession voiceSession = request.voiceSession;
820 final IBinder resultTo = request.resultTo;
821 String resultWho = request.resultWho;
822 int requestCode = request.requestCode;
823 int callingPid = request.callingPid;
824 int callingUid = request.callingUid;
825 String callingPackage = request.callingPackage;
Philip P. Moltmannee295092020-02-10 08:46:26 -0800826 String callingFeatureId = request.callingFeatureId;
Louis Chang54fbb052019-10-16 17:10:17 +0800827 final int realCallingPid = request.realCallingPid;
828 final int realCallingUid = request.realCallingUid;
829 final int startFlags = request.startFlags;
830 final SafeActivityOptions options = request.activityOptions;
Louis Changcdec0802019-11-11 11:45:07 +0800831 Task inTask = request.inTask;
Louis Chang54fbb052019-10-16 17:10:17 +0800832
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800833 int err = ActivityManager.START_SUCCESS;
Chad Brubaker06068612017-04-06 09:43:47 -0700834 // Pull the optional Ephemeral Installer-only bundle out of the options early.
Louis Chang54fbb052019-10-16 17:10:17 +0800835 final Bundle verificationBundle =
836 options != null ? options.popAppVerificationBundle() : null;
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800837
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700838 WindowProcessController callerApp = null;
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800839 if (caller != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700840 callerApp = mService.getProcessController(caller);
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800841 if (callerApp != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700842 callingPid = callerApp.getPid();
843 callingUid = callerApp.mInfo.uid;
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800844 } else {
Louis Chang54fbb052019-10-16 17:10:17 +0800845 Slog.w(TAG, "Unable to find app for caller " + caller + " (pid=" + callingPid
846 + ") when starting: " + intent.toString());
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800847 err = ActivityManager.START_PERMISSION_DENIED;
848 }
849 }
850
Bryce Lee93e7f792017-10-25 15:54:55 -0700851 final int userId = aInfo != null && aInfo.applicationInfo != null
852 ? UserHandle.getUserId(aInfo.applicationInfo.uid) : 0;
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800853 if (err == ActivityManager.START_SUCCESS) {
854 Slog.i(TAG, "START u" + userId + " {" + intent.toShortString(true, true, true, false)
Andrii Kulian03c403d2016-11-11 11:14:12 -0800855 + "} from uid " + callingUid);
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800856 }
857
858 ActivityRecord sourceRecord = null;
859 ActivityRecord resultRecord = null;
860 if (resultTo != null) {
Louis Chang149d5c82019-12-30 09:47:39 +0800861 sourceRecord = mRootWindowContainer.isInAnyStack(resultTo);
Louis Chang54fbb052019-10-16 17:10:17 +0800862 if (DEBUG_RESULTS) {
863 Slog.v(TAG_RESULTS, "Will send result to " + resultTo + " " + sourceRecord);
864 }
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800865 if (sourceRecord != null) {
866 if (requestCode >= 0 && !sourceRecord.finishing) {
867 resultRecord = sourceRecord;
868 }
869 }
870 }
871
872 final int launchFlags = intent.getFlags();
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800873 if ((launchFlags & Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0 && sourceRecord != null) {
Louis Chang54fbb052019-10-16 17:10:17 +0800874 // Transfer the result target from the source activity to the new one being started,
875 // including any failures.
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800876 if (requestCode >= 0) {
Jorim Jaggi4d8d32c2018-01-19 15:57:41 +0100877 SafeActivityOptions.abort(options);
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800878 return ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT;
879 }
880 resultRecord = sourceRecord.resultTo;
881 if (resultRecord != null && !resultRecord.isInStackLocked()) {
882 resultRecord = null;
883 }
884 resultWho = sourceRecord.resultWho;
885 requestCode = sourceRecord.requestCode;
886 sourceRecord.resultTo = null;
887 if (resultRecord != null) {
888 resultRecord.removeResultsLocked(sourceRecord, resultWho, requestCode);
889 }
890 if (sourceRecord.launchedFromUid == callingUid) {
Louis Chang54fbb052019-10-16 17:10:17 +0800891 // The new activity is being launched from the same uid as the previous activity
892 // in the flow, and asking to forward its result back to the previous. In this
893 // case the activity is serving as a trampoline between the two, so we also want
894 // to update its launchedFromPackage to be the same as the previous activity.
895 // Note that this is safe, since we know these two packages come from the same
896 // uid; the caller could just as well have supplied that same package name itself
897 // . This specifially deals with the case of an intent picker/chooser being
898 // launched in the app flow to redirect to an activity picked by the user, where
899 // we want the final activity to consider it to have been launched by the
900 // previous app activity.
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800901 callingPackage = sourceRecord.launchedFromPackage;
Philip P. Moltmannee295092020-02-10 08:46:26 -0800902 callingFeatureId = sourceRecord.launchedFromFeatureId;
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800903 }
904 }
905
906 if (err == ActivityManager.START_SUCCESS && intent.getComponent() == null) {
907 // We couldn't find a class that can handle the given Intent.
908 // That's the end of that!
909 err = ActivityManager.START_INTENT_NOT_RESOLVED;
910 }
911
912 if (err == ActivityManager.START_SUCCESS && aInfo == null) {
913 // We couldn't find the specific class specified in the Intent.
914 // Also the end of the line.
915 err = ActivityManager.START_CLASS_NOT_FOUND;
916 }
917
918 if (err == ActivityManager.START_SUCCESS && sourceRecord != null
Louis Changcdec0802019-11-11 11:45:07 +0800919 && sourceRecord.getTask().voiceSession != null) {
Louis Chang54fbb052019-10-16 17:10:17 +0800920 // If this activity is being launched as part of a voice session, we need to ensure
921 // that it is safe to do so. If the upcoming activity will also be part of the voice
922 // session, we can only launch it if it has explicitly said it supports the VOICE
923 // category, or it is a part of the calling app.
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800924 if ((launchFlags & FLAG_ACTIVITY_NEW_TASK) == 0
925 && sourceRecord.info.applicationInfo.uid != aInfo.applicationInfo.uid) {
926 try {
927 intent.addCategory(Intent.CATEGORY_VOICE);
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700928 if (!mService.getPackageManager().activitySupportsIntent(
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800929 intent.getComponent(), intent, resolvedType)) {
Louis Chang54fbb052019-10-16 17:10:17 +0800930 Slog.w(TAG, "Activity being started in current voice task does not support "
931 + "voice: " + intent);
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800932 err = ActivityManager.START_NOT_VOICE_COMPATIBLE;
933 }
934 } catch (RemoteException e) {
935 Slog.w(TAG, "Failure checking voice capabilities", e);
936 err = ActivityManager.START_NOT_VOICE_COMPATIBLE;
937 }
938 }
939 }
940
941 if (err == ActivityManager.START_SUCCESS && voiceSession != null) {
942 // If the caller is starting a new voice session, just make sure the target
943 // is actually allowing it to run this way.
944 try {
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700945 if (!mService.getPackageManager().activitySupportsIntent(intent.getComponent(),
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800946 intent, resolvedType)) {
947 Slog.w(TAG,
Louis Chang54fbb052019-10-16 17:10:17 +0800948 "Activity being started in new voice task does not support: " + intent);
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800949 err = ActivityManager.START_NOT_VOICE_COMPATIBLE;
950 }
951 } catch (RemoteException e) {
952 Slog.w(TAG, "Failure checking voice capabilities", e);
953 err = ActivityManager.START_NOT_VOICE_COMPATIBLE;
954 }
955 }
956
Wale Ogunwale8b19de92018-11-29 19:58:26 -0800957 final ActivityStack resultStack = resultRecord == null
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -0800958 ? null : resultRecord.getRootTask();
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800959
Wale Ogunwale01d66562015-12-29 08:19:19 -0800960 if (err != START_SUCCESS) {
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800961 if (resultRecord != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -0700962 resultRecord.sendResult(INVALID_UID, resultWho, requestCode, RESULT_CANCELED,
963 null /* data */);
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800964 }
Jorim Jaggi4d8d32c2018-01-19 15:57:41 +0100965 SafeActivityOptions.abort(options);
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800966 return err;
967 }
968
969 boolean abort = !mSupervisor.checkStartAnyActivityPermission(intent, aInfo, resultWho,
Philip P. Moltmannee295092020-02-10 08:46:26 -0800970 requestCode, callingPid, callingUid, callingPackage, callingFeatureId,
971 request.ignoreTargetSecurity, inTask != null, callerApp, resultRecord, resultStack);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700972 abort |= !mService.mIntentFirewall.checkStartActivity(intent, callingUid,
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800973 callingPid, resolvedType, aInfo.applicationInfo);
Hai Zhangf4da9be2019-05-01 13:46:06 +0800974 abort |= !mService.getPermissionPolicyInternal().checkStartActivity(intent, callingUid,
975 callingPackage);
Filip Gruszczynski07a0e492015-12-17 14:16:38 -0800976
Ricky Waib147fa12019-04-25 16:08:30 +0100977 boolean restrictedBgActivity = false;
Michal Karpinski8596ded2018-11-14 14:43:48 +0000978 if (!abort) {
Michal Karpinski4fd5b842019-01-28 15:13:32 +0000979 try {
Riddle Hsu2ca561b2019-10-08 21:58:58 +0800980 Trace.traceBegin(Trace.TRACE_TAG_WINDOW_MANAGER,
Michal Karpinski4fd5b842019-01-28 15:13:32 +0000981 "shouldAbortBackgroundActivityStart");
Ricky Waib147fa12019-04-25 16:08:30 +0100982 restrictedBgActivity = shouldAbortBackgroundActivityStart(callingUid,
Ricky Waiaca8a772019-04-04 16:01:06 +0100983 callingPid, callingPackage, realCallingUid, realCallingPid, callerApp,
Louis Chang54fbb052019-10-16 17:10:17 +0800984 request.originatingPendingIntent, request.allowBackgroundActivityStart,
Galia Peychevaed401cc2020-03-19 20:28:09 +0100985 intent);
Michal Karpinski4fd5b842019-01-28 15:13:32 +0000986 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +0800987 Trace.traceEnd(Trace.TRACE_TAG_WINDOW_MANAGER);
Michal Karpinski4fd5b842019-01-28 15:13:32 +0000988 }
Michal Karpinski8596ded2018-11-14 14:43:48 +0000989 }
990
Jorim Jaggi4d8d32c2018-01-19 15:57:41 +0100991 // Merge the two options bundles, while realCallerOptions takes precedence.
992 ActivityOptions checkedOptions = options != null
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700993 ? options.getOptions(intent, aInfo, callerApp, mSupervisor) : null;
Louis Chang54fbb052019-10-16 17:10:17 +0800994 if (request.allowPendingRemoteAnimationRegistryLookup) {
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700995 checkedOptions = mService.getActivityStartController()
Jorim Jaggi6fa41c32018-04-23 18:35:00 +0200996 .getPendingRemoteAnimationRegistry()
997 .overrideOptionsIfNeeded(callingPackage, checkedOptions);
998 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700999 if (mService.mController != null) {
Filip Gruszczynski07a0e492015-12-17 14:16:38 -08001000 try {
Louis Chang54fbb052019-10-16 17:10:17 +08001001 // The Intent we give to the watcher has the extra data stripped off, since it
1002 // can contain private information.
Filip Gruszczynski07a0e492015-12-17 14:16:38 -08001003 Intent watchIntent = intent.cloneFilter();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001004 abort |= !mService.mController.activityStarting(watchIntent,
Filip Gruszczynski07a0e492015-12-17 14:16:38 -08001005 aInfo.applicationInfo.packageName);
1006 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001007 mService.mController = null;
Filip Gruszczynski07a0e492015-12-17 14:16:38 -08001008 }
1009 }
1010
Philip P. Moltmannee295092020-02-10 08:46:26 -08001011 mInterceptor.setStates(userId, realCallingPid, realCallingUid, startFlags, callingPackage,
1012 callingFeatureId);
Benjamin Franz563707b2017-06-29 15:06:13 +01001013 if (mInterceptor.intercept(intent, rInfo, aInfo, resolvedType, inTask, callingPid,
Jorim Jaggi4d8d32c2018-01-19 15:57:41 +01001014 callingUid, checkedOptions)) {
Benjamin Franz563707b2017-06-29 15:06:13 +01001015 // activity start was intercepted, e.g. because the target user is currently in quiet
1016 // mode (turn off work) or the target application is suspended
1017 intent = mInterceptor.mIntent;
1018 rInfo = mInterceptor.mRInfo;
1019 aInfo = mInterceptor.mAInfo;
1020 resolvedType = mInterceptor.mResolvedType;
1021 inTask = mInterceptor.mInTask;
1022 callingPid = mInterceptor.mCallingPid;
1023 callingUid = mInterceptor.mCallingUid;
Jorim Jaggi4d8d32c2018-01-19 15:57:41 +01001024 checkedOptions = mInterceptor.mActivityOptions;
Benjamin Franz563707b2017-06-29 15:06:13 +01001025 }
1026
Filip Gruszczynski07a0e492015-12-17 14:16:38 -08001027 if (abort) {
1028 if (resultRecord != null) {
Andrii Kulian79d67982019-08-19 11:56:16 -07001029 resultRecord.sendResult(INVALID_UID, resultWho, requestCode, RESULT_CANCELED,
1030 null /* data */);
Filip Gruszczynski07a0e492015-12-17 14:16:38 -08001031 }
Louis Chang54fbb052019-10-16 17:10:17 +08001032 // We pretend to the caller that it was really started, but they will just get a
1033 // cancel result.
Jorim Jaggi4d8d32c2018-01-19 15:57:41 +01001034 ActivityOptions.abort(checkedOptions);
Bryce Leef9d49542017-06-26 16:27:32 -07001035 return START_ABORTED;
Filip Gruszczynski07a0e492015-12-17 14:16:38 -08001036 }
1037
1038 // If permissions need a review before any of the app components can run, we
1039 // launch the review activity and pass a pending intent to start the activity
1040 // we are to launching now after the review is completed.
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001041 if (aInfo != null) {
Wale Ogunwale906f9c62018-07-23 11:23:44 -07001042 if (mService.getPackageManagerInternalLocked().isPermissionsReviewRequired(
Filip Gruszczynski07a0e492015-12-17 14:16:38 -08001043 aInfo.packageName, userId)) {
Louis Chang54fbb052019-10-16 17:10:17 +08001044 final IIntentSender target = mService.getIntentSenderLocked(
Philip P. Moltmannee295092020-02-10 08:46:26 -08001045 ActivityManager.INTENT_SENDER_ACTIVITY, callingPackage, callingFeatureId,
Filip Gruszczynski07a0e492015-12-17 14:16:38 -08001046 callingUid, userId, null, null, 0, new Intent[]{intent},
1047 new String[]{resolvedType}, PendingIntent.FLAG_CANCEL_CURRENT
1048 | PendingIntent.FLAG_ONE_SHOT, null);
1049
Filip Gruszczynski07a0e492015-12-17 14:16:38 -08001050 Intent newIntent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
Philip P. Moltmannc3e66d02019-01-31 15:56:18 -08001051
1052 int flags = intent.getFlags();
1053 flags |= Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
1054
1055 /*
1056 * Prevent reuse of review activity: Each app needs their own review activity. By
1057 * default activities launched with NEW_TASK or NEW_DOCUMENT try to reuse activities
1058 * with the same launch parameters (extras are ignored). Hence to avoid possible
1059 * reuse force a new activity via the MULTIPLE_TASK flag.
1060 *
1061 * Activities that are not launched with NEW_TASK or NEW_DOCUMENT are not re-used,
1062 * hence no need to add the flag in this case.
1063 */
1064 if ((flags & (FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_NEW_DOCUMENT)) != 0) {
1065 flags |= Intent.FLAG_ACTIVITY_MULTIPLE_TASK;
1066 }
1067 newIntent.setFlags(flags);
1068
Filip Gruszczynski07a0e492015-12-17 14:16:38 -08001069 newIntent.putExtra(Intent.EXTRA_PACKAGE_NAME, aInfo.packageName);
1070 newIntent.putExtra(Intent.EXTRA_INTENT, new IntentSender(target));
1071 if (resultRecord != null) {
1072 newIntent.putExtra(Intent.EXTRA_RESULT_NEEDED, true);
1073 }
1074 intent = newIntent;
1075
1076 resolvedType = null;
1077 callingUid = realCallingUid;
1078 callingPid = realCallingPid;
1079
Svet Ganovcbcbf662018-05-10 17:25:29 -07001080 rInfo = mSupervisor.resolveIntent(intent, resolvedType, userId, 0,
Patrick Baumann31426b22018-05-21 13:46:40 -07001081 computeResolveFilterUid(
Louis Chang54fbb052019-10-16 17:10:17 +08001082 callingUid, realCallingUid, request.filterCallingUid));
Filip Gruszczynski07a0e492015-12-17 14:16:38 -08001083 aInfo = mSupervisor.resolveActivity(intent, rInfo, startFlags,
1084 null /*profilerInfo*/);
1085
1086 if (DEBUG_PERMISSIONS_REVIEW) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001087 final ActivityStack focusedStack =
Louis Chang149d5c82019-12-30 09:47:39 +08001088 mRootWindowContainer.getTopDisplayFocusedStack();
Filip Gruszczynski07a0e492015-12-17 14:16:38 -08001089 Slog.i(TAG, "START u" + userId + " {" + intent.toShortString(true, true,
1090 true, false) + "} from uid " + callingUid + " on display "
Wale Ogunwale0b3d2922019-12-30 08:55:07 -08001091 + (focusedStack == null ? DEFAULT_DISPLAY
1092 : focusedStack.getDisplayId()));
Filip Gruszczynski07a0e492015-12-17 14:16:38 -08001093 }
1094 }
1095 }
1096
1097 // If we have an ephemeral app, abort the process of launching the resolved intent.
1098 // Instead, launch the ephemeral installer. Once the installer is finished, it
1099 // starts either the intent we resolved here [on install error] or the ephemeral
1100 // app [on install success].
Patrick Baumanna89a1722018-02-07 15:26:52 -08001101 if (rInfo != null && rInfo.auxiliaryInfo != null) {
Louis Chang54fbb052019-10-16 17:10:17 +08001102 intent = createLaunchIntent(rInfo.auxiliaryInfo, request.ephemeralIntent,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001103 callingPackage, callingFeatureId, verificationBundle, resolvedType, userId);
Filip Gruszczynski07a0e492015-12-17 14:16:38 -08001104 resolvedType = null;
1105 callingUid = realCallingUid;
1106 callingPid = realCallingPid;
1107
Filip Gruszczynski07a0e492015-12-17 14:16:38 -08001108 aInfo = mSupervisor.resolveActivity(intent, rInfo, startFlags, null /*profilerInfo*/);
1109 }
1110
Louis Chang54fbb052019-10-16 17:10:17 +08001111 final ActivityRecord r = new ActivityRecord(mService, callerApp, callingPid, callingUid,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001112 callingPackage, callingFeatureId, intent, resolvedType, aInfo,
1113 mService.getGlobalConfiguration(), resultRecord, resultWho, requestCode,
1114 request.componentSpecified, voiceSession != null, mSupervisor, checkedOptions,
1115 sourceRecord);
Louis Chang54fbb052019-10-16 17:10:17 +08001116 mLastStartActivityRecord = r;
Filip Gruszczynski07a0e492015-12-17 14:16:38 -08001117
1118 if (r.appTimeTracker == null && sourceRecord != null) {
1119 // If the caller didn't specify an explicit time tracker, we want to continue
1120 // tracking under any it has.
1121 r.appTimeTracker = sourceRecord.appTimeTracker;
1122 }
1123
Louis Chang149d5c82019-12-30 09:47:39 +08001124 final ActivityStack stack = mRootWindowContainer.getTopDisplayFocusedStack();
Jorim Jaggi4d8d32c2018-01-19 15:57:41 +01001125
1126 // If we are starting an activity that is not from the same uid as the currently resumed
1127 // one, check whether app switches are allowed.
Jeff Chang51de04a2020-04-29 16:14:31 +08001128 if (voiceSession == null && stack != null && (stack.getResumedActivity() == null
Bryce Leec4ab62a2018-03-05 14:19:26 -08001129 || stack.getResumedActivity().info.applicationInfo.uid != realCallingUid)) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001130 if (!mService.checkAppSwitchAllowedLocked(callingPid, callingUid,
Filip Gruszczynski07a0e492015-12-17 14:16:38 -08001131 realCallingPid, realCallingUid, "Activity start")) {
Alan Stokes07389b62019-05-20 15:22:54 +01001132 if (!(restrictedBgActivity && handleBackgroundActivityAbort(r))) {
Ricky Waib147fa12019-04-25 16:08:30 +01001133 mController.addPendingActivityLaunch(new PendingActivityLaunch(r,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00001134 sourceRecord, startFlags, stack, callerApp));
Ricky Waib147fa12019-04-25 16:08:30 +01001135 }
Jorim Jaggi4d8d32c2018-01-19 15:57:41 +01001136 ActivityOptions.abort(checkedOptions);
Filip Gruszczynski07a0e492015-12-17 14:16:38 -08001137 return ActivityManager.START_SWITCHES_CANCELED;
1138 }
1139 }
1140
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001141 mService.onStartActivitySetDidAppSwitch();
Bryce Leed3624e12017-11-30 08:51:45 -08001142 mController.doPendingActivityLaunches(false);
Filip Gruszczynski07a0e492015-12-17 14:16:38 -08001143
Louis Chang54fbb052019-10-16 17:10:17 +08001144 mLastStartActivityResult = startActivityUnchecked(r, sourceRecord, voiceSession,
1145 request.voiceInteractor, startFlags, true /* doResume */, checkedOptions, inTask,
1146 restrictedBgActivity);
1147
1148 if (request.outActivity != null) {
1149 request.outActivity[0] = mLastStartActivityRecord;
1150 }
1151
Riddle Hsu7f8643a2019-12-05 14:37:30 +08001152 return mLastStartActivityResult;
Louis Chang54fbb052019-10-16 17:10:17 +08001153 }
1154
1155 /**
1156 * Return true if background activity is really aborted.
1157 *
1158 * TODO(b/131748165): Refactor the logic so we don't need to call this method everywhere.
1159 */
1160 private boolean handleBackgroundActivityAbort(ActivityRecord r) {
1161 // TODO(b/131747138): Remove toast and refactor related code in R release.
1162 final boolean abort = !mService.isBackgroundActivityStartsEnabled();
1163 if (!abort) {
1164 return false;
1165 }
1166 final ActivityRecord resultRecord = r.resultTo;
1167 final String resultWho = r.resultWho;
1168 int requestCode = r.requestCode;
1169 if (resultRecord != null) {
1170 resultRecord.sendResult(INVALID_UID, resultWho, requestCode, RESULT_CANCELED,
1171 null /* data */);
1172 }
1173 // We pretend to the caller that it was really started to make it backward compatible, but
1174 // they will just get a cancel result.
1175 ActivityOptions.abort(r.pendingOptions);
1176 return true;
1177 }
1178
1179 static int getExternalResult(int result) {
1180 // Aborted results are treated as successes externally, but we must track them internally.
1181 return result != START_ABORTED ? result : START_SUCCESS;
1182 }
1183
1184 /**
1185 * Called when execution is complete. Sets state indicating completion and proceeds with
1186 * recycling if appropriate.
1187 */
1188 private void onExecutionComplete() {
1189 mController.onExecutionComplete(this);
Wale Ogunwalecc25a8a2016-01-23 14:31:37 -08001190 }
Filip Gruszczynski07a0e492015-12-17 14:16:38 -08001191
Ricky Waiaca8a772019-04-04 16:01:06 +01001192 boolean shouldAbortBackgroundActivityStart(int callingUid, int callingPid,
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00001193 final String callingPackage, int realCallingUid, int realCallingPid,
1194 WindowProcessController callerApp, PendingIntentRecord originatingPendingIntent,
Galia Peychevaed401cc2020-03-19 20:28:09 +01001195 boolean allowBackgroundActivityStart, Intent intent) {
Michal Karpinski8596ded2018-11-14 14:43:48 +00001196 // don't abort for the most important UIDs
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001197 final int callingAppId = UserHandle.getAppId(callingUid);
1198 if (callingUid == Process.ROOT_UID || callingAppId == Process.SYSTEM_UID
1199 || callingAppId == Process.NFC_UID) {
Bernardo Rufino1e088f12020-04-28 16:40:25 +01001200 if (DEBUG_ACTIVITY_STARTS) {
1201 Slog.d(TAG, "Activity start allowed for important callingUid (" + callingUid + ")");
1202 }
Michal Karpinski8596ded2018-11-14 14:43:48 +00001203 return false;
1204 }
Galia Peycheva6861e912019-08-21 10:20:23 +02001205
Alan Stokeseea8d3e2019-04-10 17:37:25 +01001206 // don't abort if the callingUid has a visible window or is a persistent system process
Riddle Hsua0536432019-02-16 00:38:59 +08001207 final int callingUidProcState = mService.getUidState(callingUid);
Michal Karpinski4fd5b842019-01-28 15:13:32 +00001208 final boolean callingUidHasAnyVisibleWindow =
1209 mService.mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(callingUid);
1210 final boolean isCallingUidForeground = callingUidHasAnyVisibleWindow
Amith Yamasanif235d0b2019-03-20 22:49:43 -07001211 || callingUidProcState == ActivityManager.PROCESS_STATE_TOP
1212 || callingUidProcState == ActivityManager.PROCESS_STATE_BOUND_TOP;
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001213 final boolean isCallingUidPersistentSystemProcess =
1214 callingUidProcState <= ActivityManager.PROCESS_STATE_PERSISTENT_UI;
Alan Stokeseea8d3e2019-04-10 17:37:25 +01001215 if (callingUidHasAnyVisibleWindow || isCallingUidPersistentSystemProcess) {
Bernardo Rufino1e088f12020-04-28 16:40:25 +01001216 if (DEBUG_ACTIVITY_STARTS) {
1217 Slog.d(TAG, "Activity start allowed: callingUidHasAnyVisibleWindow = " + callingUid
1218 + ", isCallingUidPersistentSystemProcess = "
1219 + isCallingUidPersistentSystemProcess);
1220 }
Michal Karpinski8596ded2018-11-14 14:43:48 +00001221 return false;
1222 }
Michal Karpinskiac116df2018-12-10 17:51:42 +00001223 // take realCallingUid into consideration
Michal Karpinski4fd5b842019-01-28 15:13:32 +00001224 final int realCallingUidProcState = (callingUid == realCallingUid)
1225 ? callingUidProcState
Riddle Hsua0536432019-02-16 00:38:59 +08001226 : mService.getUidState(realCallingUid);
Michal Karpinski4fd5b842019-01-28 15:13:32 +00001227 final boolean realCallingUidHasAnyVisibleWindow = (callingUid == realCallingUid)
1228 ? callingUidHasAnyVisibleWindow
1229 : mService.mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(realCallingUid);
1230 final boolean isRealCallingUidForeground = (callingUid == realCallingUid)
1231 ? isCallingUidForeground
1232 : realCallingUidHasAnyVisibleWindow
1233 || realCallingUidProcState == ActivityManager.PROCESS_STATE_TOP;
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001234 final int realCallingAppId = UserHandle.getAppId(realCallingUid);
Michal Karpinski4fd5b842019-01-28 15:13:32 +00001235 final boolean isRealCallingUidPersistentSystemProcess = (callingUid == realCallingUid)
1236 ? isCallingUidPersistentSystemProcess
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001237 : (realCallingAppId == Process.SYSTEM_UID)
Michal Karpinski4fd5b842019-01-28 15:13:32 +00001238 || realCallingUidProcState <= ActivityManager.PROCESS_STATE_PERSISTENT_UI;
Michal Karpinskiac116df2018-12-10 17:51:42 +00001239 if (realCallingUid != callingUid) {
Alan Stokes6ac9efd2019-05-09 12:50:37 +00001240 // don't abort if the realCallingUid has a visible window
1241 if (realCallingUidHasAnyVisibleWindow) {
Bernardo Rufino1e088f12020-04-28 16:40:25 +01001242 if (DEBUG_ACTIVITY_STARTS) {
1243 Slog.d(TAG, "Activity start allowed: realCallingUid (" + realCallingUid
1244 + ") has visible (non-toast) window");
1245 }
Michal Karpinskiac116df2018-12-10 17:51:42 +00001246 return false;
1247 }
1248 // if the realCallingUid is a persistent system process, abort if the IntentSender
1249 // wasn't whitelisted to start an activity
Michal Karpinskid0162852019-01-15 16:05:25 +00001250 if (isRealCallingUidPersistentSystemProcess && allowBackgroundActivityStart) {
Bernardo Rufino1e088f12020-04-28 16:40:25 +01001251 if (DEBUG_ACTIVITY_STARTS) {
1252 Slog.d(TAG, "Activity start allowed: realCallingUid (" + realCallingUid
1253 + ") is persistent system process AND intent sender whitelisted "
1254 + "(allowBackgroundActivityStart = true)");
1255 }
Michal Karpinskiac116df2018-12-10 17:51:42 +00001256 return false;
1257 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01001258 // don't abort if the realCallingUid is an associated companion app
1259 if (mService.isAssociatedCompanionApp(UserHandle.getUserId(realCallingUid),
1260 realCallingUid)) {
Bernardo Rufino1e088f12020-04-28 16:40:25 +01001261 if (DEBUG_ACTIVITY_STARTS) {
1262 Slog.d(TAG, "Activity start allowed: realCallingUid (" + realCallingUid
1263 + ") is companion app");
1264 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01001265 return false;
1266 }
Michal Karpinskiac116df2018-12-10 17:51:42 +00001267 }
Michal Karpinski7b97a022018-12-14 15:17:29 +00001268 // don't abort if the callingUid has START_ACTIVITIES_FROM_BACKGROUND permission
1269 if (mService.checkPermission(START_ACTIVITIES_FROM_BACKGROUND, callingPid, callingUid)
1270 == PERMISSION_GRANTED) {
Bernardo Rufino1e088f12020-04-28 16:40:25 +01001271 if (DEBUG_ACTIVITY_STARTS) {
1272 Slog.d(TAG,
1273 "Background activity start allowed: START_ACTIVITIES_FROM_BACKGROUND "
1274 + "permission granted for uid "
1275 + callingUid);
1276 }
Michal Karpinski7b97a022018-12-14 15:17:29 +00001277 return false;
1278 }
Michal Karpinski82bb5902018-11-28 15:52:52 +00001279 // don't abort if the caller has the same uid as the recents component
1280 if (mSupervisor.mRecentTasks.isCallerRecents(callingUid)) {
Bernardo Rufino1e088f12020-04-28 16:40:25 +01001281 if (DEBUG_ACTIVITY_STARTS) {
1282 Slog.d(TAG, "Background activity start allowed: callingUid (" + callingUid
1283 + ") is recents");
1284 }
Michal Karpinski82bb5902018-11-28 15:52:52 +00001285 return false;
1286 }
Ricky Wai96f5c352019-04-10 18:40:17 +01001287 // don't abort if the callingUid is the device owner
1288 if (mService.isDeviceOwner(callingUid)) {
Bernardo Rufino1e088f12020-04-28 16:40:25 +01001289 if (DEBUG_ACTIVITY_STARTS) {
1290 Slog.d(TAG, "Background activity start allowed: callingUid (" + callingUid
1291 + ") is device owner");
1292 }
Michal Karpinski302dcec2019-02-01 11:48:25 +00001293 return false;
1294 }
Ricky Wai96f5c352019-04-10 18:40:17 +01001295 // don't abort if the callingUid has companion device
Ricky Wai2452e2d2019-03-18 19:19:08 +00001296 final int callingUserId = UserHandle.getUserId(callingUid);
Michal Karpinskida34cd42019-04-02 19:46:52 +01001297 if (mService.isAssociatedCompanionApp(callingUserId, callingUid)) {
Bernardo Rufino1e088f12020-04-28 16:40:25 +01001298 if (DEBUG_ACTIVITY_STARTS) {
1299 Slog.d(TAG, "Background activity start allowed: callingUid (" + callingUid
1300 + ") is companion app");
1301 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00001302 return false;
1303 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01001304 // If we don't have callerApp at this point, no caller was provided to startActivity().
1305 // That's the case for PendingIntent-based starts, since the creator's process might not be
1306 // up and alive. If that's the case, we retrieve the WindowProcessController for the send()
1307 // caller, so that we can make the decision based on its foreground/whitelisted state.
1308 int callerAppUid = callingUid;
1309 if (callerApp == null) {
1310 callerApp = mService.getProcessController(realCallingPid, realCallingUid);
1311 callerAppUid = realCallingUid;
1312 }
1313 // don't abort if the callerApp or other processes of that uid are whitelisted in any way
1314 if (callerApp != null) {
1315 // first check the original calling process
1316 if (callerApp.areBackgroundActivityStartsAllowed()) {
Bernardo Rufino1e088f12020-04-28 16:40:25 +01001317 if (DEBUG_ACTIVITY_STARTS) {
1318 Slog.d(TAG, "Background activity start allowed: callerApp process (pid = "
1319 + callerApp.getPid() + ", uid = " + callerAppUid + ") is whitelisted");
1320 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01001321 return false;
1322 }
1323 // only if that one wasn't whitelisted, check the other ones
1324 final ArraySet<WindowProcessController> uidProcesses =
1325 mService.mProcessMap.getProcesses(callerAppUid);
1326 if (uidProcesses != null) {
1327 for (int i = uidProcesses.size() - 1; i >= 0; i--) {
1328 final WindowProcessController proc = uidProcesses.valueAt(i);
1329 if (proc != callerApp && proc.areBackgroundActivityStartsAllowed()) {
Bernardo Rufino1e088f12020-04-28 16:40:25 +01001330 if (DEBUG_ACTIVITY_STARTS) {
1331 Slog.d(TAG,
1332 "Background activity start allowed: process " + proc.getPid()
1333 + " from uid " + callerAppUid + " is whitelisted");
1334 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01001335 return false;
1336 }
1337 }
1338 }
1339 }
Michal Karpinski15486842019-04-25 17:33:42 +01001340 // don't abort if the callingUid has SYSTEM_ALERT_WINDOW permission
1341 if (mService.hasSystemAlertWindowPermission(callingUid, callingPid, callingPackage)) {
1342 Slog.w(TAG, "Background activity start for " + callingPackage
1343 + " allowed because SYSTEM_ALERT_WINDOW permission is granted.");
1344 return false;
1345 }
Michal Karpinskic02364c2019-01-22 13:00:04 +00001346 // anything that has fallen through would currently be aborted
1347 Slog.w(TAG, "Background activity start [callingPackage: " + callingPackage
Michal Karpinskid0162852019-01-15 16:05:25 +00001348 + "; callingUid: " + callingUid
1349 + "; isCallingUidForeground: " + isCallingUidForeground
Bernardo Rufino1e088f12020-04-28 16:40:25 +01001350 + "; callingUidHasAnyVisibleWindow: " + callingUidHasAnyVisibleWindow
1351 + "; callingUidProcState: " + DebugUtils.valueToString(ActivityManager.class,
1352 "PROCESS_STATE_", callingUidProcState)
Michal Karpinskid0162852019-01-15 16:05:25 +00001353 + "; isCallingUidPersistentSystemProcess: " + isCallingUidPersistentSystemProcess
1354 + "; realCallingUid: " + realCallingUid
1355 + "; isRealCallingUidForeground: " + isRealCallingUidForeground
Bernardo Rufino1e088f12020-04-28 16:40:25 +01001356 + "; realCallingUidHasAnyVisibleWindow: " + realCallingUidHasAnyVisibleWindow
1357 + "; realCallingUidProcState: " + DebugUtils.valueToString(ActivityManager.class,
1358 "PROCESS_STATE_", realCallingUidProcState)
Michal Karpinskid0162852019-01-15 16:05:25 +00001359 + "; isRealCallingUidPersistentSystemProcess: "
Ricky Waiaca8a772019-04-04 16:01:06 +01001360 + isRealCallingUidPersistentSystemProcess
Michal Karpinskid0162852019-01-15 16:05:25 +00001361 + "; originatingPendingIntent: " + originatingPendingIntent
1362 + "; isBgStartWhitelisted: " + allowBackgroundActivityStart
1363 + "; intent: " + intent
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00001364 + "; callerApp: " + callerApp
Michal Karpinskid0162852019-01-15 16:05:25 +00001365 + "]");
Michal Karpinski4fd5b842019-01-28 15:13:32 +00001366 // log aborted activity start to TRON
1367 if (mService.isActivityStartsLoggingEnabled()) {
1368 mSupervisor.getActivityMetricsLogger().logAbortedBgActivityStart(intent, callerApp,
1369 callingUid, callingPackage, callingUidProcState, callingUidHasAnyVisibleWindow,
1370 realCallingUid, realCallingUidProcState, realCallingUidHasAnyVisibleWindow,
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001371 (originatingPendingIntent != null));
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001372 }
Michal Karpinski4fd5b842019-01-28 15:13:32 +00001373 return true;
Michal Karpinski201bc0c2018-07-20 15:32:00 +01001374 }
Jorim Jaggi4d8d32c2018-01-19 15:57:41 +01001375
Bryce Leeaa5e8c32017-03-01 16:01:06 -08001376 /**
1377 * Creates a launch intent for the given auxiliary resolution data.
1378 */
Patrick Baumann577d4022018-01-31 16:55:10 +00001379 private @NonNull Intent createLaunchIntent(@Nullable AuxiliaryResolveInfo auxiliaryResponse,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001380 Intent originalIntent, String callingPackage, @Nullable String callingFeatureId,
1381 Bundle verificationBundle, String resolvedType, int userId) {
Patrick Baumann577d4022018-01-31 16:55:10 +00001382 if (auxiliaryResponse != null && auxiliaryResponse.needsPhaseTwo) {
Todd Kennedye9910222017-02-21 16:00:11 -08001383 // request phase two resolution
Winson81fef842019-08-28 12:19:08 -07001384 PackageManagerInternal packageManager = mService.getPackageManagerInternalLocked();
1385 boolean isRequesterInstantApp = packageManager.isInstantApp(callingPackage, userId);
1386 packageManager.requestInstantAppResolutionPhaseTwo(
Chad Brubaker06068612017-04-06 09:43:47 -07001387 auxiliaryResponse, originalIntent, resolvedType, callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001388 callingFeatureId, isRequesterInstantApp, verificationBundle, userId);
Todd Kennedye9910222017-02-21 16:00:11 -08001389 }
Todd Kennedydfc27c62017-05-17 15:32:10 -07001390 return InstantAppResolver.buildEphemeralInstallerIntent(
Patrick Baumann577d4022018-01-31 16:55:10 +00001391 originalIntent,
1392 InstantAppResolver.sanitizeIntent(originalIntent),
1393 auxiliaryResponse == null ? null : auxiliaryResponse.failureIntent,
1394 callingPackage,
Philip P. Moltmannee295092020-02-10 08:46:26 -08001395 callingFeatureId,
Patrick Baumann577d4022018-01-31 16:55:10 +00001396 verificationBundle,
1397 resolvedType,
1398 userId,
1399 auxiliaryResponse == null ? null : auxiliaryResponse.installFailureActivity,
1400 auxiliaryResponse == null ? null : auxiliaryResponse.token,
1401 auxiliaryResponse != null && auxiliaryResponse.needsPhaseTwo,
1402 auxiliaryResponse == null ? null : auxiliaryResponse.filters);
Todd Kennedye9910222017-02-21 16:00:11 -08001403 }
1404
Riddle Hsu16567132018-08-16 21:37:47 +08001405 void postStartActivityProcessing(ActivityRecord r, int result,
1406 ActivityStack startedActivityStack) {
Winson Chunge219ae12019-07-18 13:43:23 -07001407 if (!ActivityManager.isStartResultSuccessful(result)) {
1408 if (mFrozeTaskList) {
1409 // If we specifically froze the task list as part of starting an activity, then
1410 // reset the frozen list state if it failed to start. This is normally otherwise
1411 // called when the freeze-timeout has elapsed.
1412 mSupervisor.mRecentTasks.resetFreezeTaskListReorderingOnTimeout();
1413 }
1414 }
Bryce Lee7f936862017-05-09 15:33:18 -07001415 if (ActivityManager.isStartResultFatalError(result)) {
Wale Ogunwalecc25a8a2016-01-23 14:31:37 -08001416 return;
Filip Gruszczynski07a0e492015-12-17 14:16:38 -08001417 }
Filip Gruszczynski303210b2016-01-08 16:28:08 -08001418
Chong Zhang5022da32016-06-21 16:31:37 -07001419 // We're waiting for an activity launch to finish, but that activity simply
Bryce Lee5f0e28f2018-01-30 16:00:03 -08001420 // brought another activity to front. We must also handle the case where the task is already
1421 // in the front as a result of the trampoline activity being in the same task (it will be
Louis Chang54fbb052019-10-16 17:10:17 +08001422 // considered focused as the trampoline will be finished). Let them know about this, so
1423 // it waits for the new activity to become visible instead, {@link #waitResultIfNeeded}.
Bryce Lee5f0e28f2018-01-30 16:00:03 -08001424 mSupervisor.reportWaitingActivityLaunchedIfNeeded(r, result);
Chong Zhang5022da32016-06-21 16:31:37 -07001425
Winson Chunge789ff62020-02-24 14:40:23 -08001426 final Task targetTask = r.getTask() != null
1427 ? r.getTask()
1428 : mTargetTask;
1429 if (startedActivityStack == null || targetTask == null) {
Wale Ogunwale44f036f2017-09-29 05:09:09 -07001430 return;
1431 }
1432
Wale Ogunwaleac36e4d2017-11-29 13:30:26 -08001433 final int clearTaskFlags = FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK;
1434 boolean clearedTask = (mLaunchFlags & clearTaskFlags) == clearTaskFlags
1435 && mReuseTask != null;
Wale Ogunwale7d7973a2018-04-05 10:25:59 -07001436 if (result == START_TASK_TO_FRONT || result == START_DELIVERED_TO_TOP || clearedTask) {
1437 // The activity was already running so it wasn't started, but either brought to the
1438 // front or the new intent was delivered to it since it was already in front. Notify
1439 // anyone interested in this piece of information.
Andrii Kulian86d676c2020-03-27 19:34:54 -07001440 final ActivityStack homeStack = targetTask.getDisplayArea().getRootHomeTask();
Winson Chunge789ff62020-02-24 14:40:23 -08001441 final boolean homeTaskVisible = homeStack != null && homeStack.shouldBeVisible(null);
1442 mService.getTaskChangeNotificationController().notifyActivityRestartAttempt(
Evan Rosky8d1c24e2020-04-23 09:21:16 -07001443 targetTask.getTaskInfo(), homeTaskVisible, clearedTask,
1444 targetTask.getTopNonFinishingActivity().isVisible());
Wale Ogunwalecc25a8a2016-01-23 14:31:37 -08001445 }
Filip Gruszczynski07a0e492015-12-17 14:16:38 -08001446 }
1447
Svet Ganovcbcbf662018-05-10 17:25:29 -07001448 /**
1449 * Compute the logical UID based on which the package manager would filter
1450 * app components i.e. based on which the instant app policy would be applied
1451 * because it is the logical calling UID.
1452 *
1453 * @param customCallingUid The UID on whose behalf to make the call.
1454 * @param actualCallingUid The UID actually making the call.
Patrick Baumann31426b22018-05-21 13:46:40 -07001455 * @param filterCallingUid The UID to be used to filter for instant apps.
Svet Ganovcbcbf662018-05-10 17:25:29 -07001456 * @return The logical UID making the call.
1457 */
Patrick Baumann31426b22018-05-21 13:46:40 -07001458 static int computeResolveFilterUid(int customCallingUid, int actualCallingUid,
1459 int filterCallingUid) {
1460 return filterCallingUid != UserHandle.USER_NULL
1461 ? filterCallingUid
1462 : (customCallingUid >= 0 ? customCallingUid : actualCallingUid);
Svet Ganovcbcbf662018-05-10 17:25:29 -07001463 }
1464
Louis Chang54fbb052019-10-16 17:10:17 +08001465 /**
1466 * Start an activity while most of preliminary checks has been done and caller has been
1467 * confirmed that holds necessary permissions to do so.
1468 * Here also ensures that the starting activity is removed if the start wasn't successful.
1469 */
1470 private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
Bryce Leedaa91e42017-12-06 14:13:01 -08001471 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
Louis Changcdec0802019-11-11 11:45:07 +08001472 int startFlags, boolean doResume, ActivityOptions options, Task inTask,
Louis Chang54fbb052019-10-16 17:10:17 +08001473 boolean restrictedBgActivity) {
Bryce Leeaa5e8c32017-03-01 16:01:06 -08001474 int result = START_CANCELED;
Riddle Hsu16567132018-08-16 21:37:47 +08001475 final ActivityStack startedActivityStack;
Bryce Leeaa5e8c32017-03-01 16:01:06 -08001476 try {
Riddle Hsua0022cd2019-09-09 21:12:41 +08001477 mService.deferWindowLayout();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001478 Trace.traceBegin(Trace.TRACE_TAG_WINDOW_MANAGER, "startActivityInner");
1479 result = startActivityInner(r, sourceRecord, voiceSession, voiceInteractor,
Louis Chang54fbb052019-10-16 17:10:17 +08001480 startFlags, doResume, options, inTask, restrictedBgActivity);
Bryce Leeaa5e8c32017-03-01 16:01:06 -08001481 } finally {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001482 Trace.traceEnd(Trace.TRACE_TAG_WINDOW_MANAGER);
1483 startedActivityStack = handleStartResult(r, result);
Riddle Hsua0022cd2019-09-09 21:12:41 +08001484 mService.continueWindowLayout();
Bryce Leeaa5e8c32017-03-01 16:01:06 -08001485 }
1486
Riddle Hsu16567132018-08-16 21:37:47 +08001487 postStartActivityProcessing(r, result, startedActivityStack);
Bryce Leeaa5e8c32017-03-01 16:01:06 -08001488
1489 return result;
1490 }
1491
Ricky Waib147fa12019-04-25 16:08:30 +01001492 /**
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001493 * If the start result is success, ensure that the configuration of the started activity matches
1494 * the current display. Otherwise clean up unassociated containers to avoid leakage.
1495 *
1496 * @return the stack where the successful started activity resides.
1497 */
1498 private @Nullable ActivityStack handleStartResult(@NonNull ActivityRecord started, int result) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08001499 final ActivityStack currentStack = started.getRootTask();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001500 ActivityStack startedActivityStack = currentStack != null ? currentStack : mTargetStack;
1501
1502 if (ActivityManager.isStartResultSuccessful(result)) {
1503 if (startedActivityStack != null) {
1504 // If there is no state change (e.g. a resumed activity is reparented to top of
1505 // another display) to trigger a visibility/configuration checking, we have to
1506 // update the configuration for changing to different display.
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09001507 final ActivityRecord currentTop = startedActivityStack.topRunningActivity();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001508 if (currentTop != null && currentTop.shouldUpdateConfigForDisplayChanged()) {
Louis Chang149d5c82019-12-30 09:47:39 +08001509 mRootWindowContainer.ensureVisibilityAndConfig(
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001510 currentTop, currentTop.getDisplayId(),
1511 true /* markFrozenIfConfigChanged */, false /* deferResume */);
1512 }
1513 }
1514 return startedActivityStack;
1515 }
1516
1517 // If we are not able to proceed, disassociate the activity from the task. Leaving an
1518 // activity in an incomplete state can lead to issues, such as performing operations
1519 // without a window container.
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08001520 final ActivityStack stack = mStartActivity.getRootTask();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001521 if (stack != null) {
1522 mStartActivity.finishIfPossible("startActivity", true /* oomAdj */);
1523 }
1524
1525 // Stack should also be detached from display and be removed if it's empty.
1526 if (startedActivityStack != null && startedActivityStack.isAttached()
Wale Ogunwalea38654f2019-11-17 20:37:15 -08001527 && !startedActivityStack.hasActivity()
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001528 && !startedActivityStack.isActivityTypeHome()) {
Wale Ogunwalebebd8cd2019-10-28 15:53:31 -07001529 startedActivityStack.removeIfPossible();
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001530 startedActivityStack = null;
1531 }
1532 return startedActivityStack;
1533 }
1534
1535 /**
Louis Chang54fbb052019-10-16 17:10:17 +08001536 * Start an activity and determine if the activity should be adding to the top of an existing
1537 * task or delivered new intent to an existing activity. Also manipulating the activity task
1538 * onto requested or valid stack/display.
Ricky Waib147fa12019-04-25 16:08:30 +01001539 *
Louis Chang54fbb052019-10-16 17:10:17 +08001540 * Note: This method should only be called from {@link #startActivityUnchecked}.
Ricky Waib147fa12019-04-25 16:08:30 +01001541 */
Diego Vela671c0072020-03-25 09:39:26 -07001542
1543 // TODO(b/152429287): Make it easier to exercise code paths through startActivityInner
1544 @VisibleForTesting
1545 int startActivityInner(final ActivityRecord r, ActivityRecord sourceRecord,
Wale Ogunwale01d66562015-12-29 08:19:19 -08001546 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
Louis Changcdec0802019-11-11 11:45:07 +08001547 int startFlags, boolean doResume, ActivityOptions options, Task inTask,
Louis Chang54fbb052019-10-16 17:10:17 +08001548 boolean restrictedBgActivity) {
Wale Ogunwale01d66562015-12-29 08:19:19 -08001549 setInitialState(r, options, inTask, doResume, startFlags, sourceRecord, voiceSession,
Ricky Waib147fa12019-04-25 16:08:30 +01001550 voiceInteractor, restrictedBgActivity);
1551
Louis Chang6fb1e842018-12-03 16:07:50 +08001552 computeLaunchingTaskFlags();
1553
1554 computeSourceStack();
1555
1556 mIntent.setFlags(mLaunchFlags);
1557
Louis Changcdec0802019-11-11 11:45:07 +08001558 final Task reusedTask = getReusableTask();
Louis Chang6fb1e842018-12-03 16:07:50 +08001559
Winson Chunge219ae12019-07-18 13:43:23 -07001560 // If requested, freeze the task list
1561 if (mOptions != null && mOptions.freezeRecentTasksReordering()
1562 && mSupervisor.mRecentTasks.isCallerRecents(r.launchedFromUid)
1563 && !mSupervisor.mRecentTasks.isFreezeTaskListReorderingSet()) {
1564 mFrozeTaskList = true;
1565 mSupervisor.mRecentTasks.setFreezeTaskListReordering();
1566 }
1567
Louis Changbde91e92019-08-16 17:19:47 +08001568 // Compute if there is an existing task that should be used for.
Louis Changcdec0802019-11-11 11:45:07 +08001569 final Task targetTask = reusedTask != null ? reusedTask : computeTargetTask();
Louis Changbde91e92019-08-16 17:19:47 +08001570 final boolean newTask = targetTask == null;
Winson Chunge789ff62020-02-24 14:40:23 -08001571 mTargetTask = targetTask;
Louis Changbde91e92019-08-16 17:19:47 +08001572
Louis Chang38430df2020-01-02 17:14:59 +08001573 computeLaunchParams(r, sourceRecord, targetTask);
1574
Louis Changbde91e92019-08-16 17:19:47 +08001575 // Check if starting activity on given task or on a new task is allowed.
1576 int startResult = isAllowedToStart(r, newTask, targetTask);
1577 if (startResult != START_SUCCESS) {
1578 return startResult;
Louis Changbd48dca2018-08-29 17:44:34 +08001579 }
1580
Wale Ogunwale21e06482019-11-18 05:14:15 -08001581 final ActivityRecord targetTaskTop = newTask
1582 ? null : targetTask.getTopNonFinishingActivity();
Louis Changbde91e92019-08-16 17:19:47 +08001583 if (targetTaskTop != null) {
1584 // Recycle the target task for this launch.
Louis Changf7dd7f22019-11-05 11:59:56 +08001585 startResult = recycleTask(targetTask, targetTaskTop, reusedTask);
Louis Changbde91e92019-08-16 17:19:47 +08001586 if (startResult != START_SUCCESS) {
1587 return startResult;
Wale Ogunwale01d66562015-12-29 08:19:19 -08001588 }
Louis Changf7dd7f22019-11-05 11:59:56 +08001589 } else {
1590 mAddingToTask = true;
Wale Ogunwale01d66562015-12-29 08:19:19 -08001591 }
1592
1593 // If the activity being launched is the same as the one currently at the top, then
1594 // we need to check if it should only be launched once.
Louis Chang149d5c82019-12-30 09:47:39 +08001595 final ActivityStack topStack = mRootWindowContainer.getTopDisplayFocusedStack();
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08001596 if (topStack != null) {
1597 startResult = deliverToCurrentTopIfNeeded(topStack);
1598 if (startResult != START_SUCCESS) {
1599 return startResult;
1600 }
Wale Ogunwale01d66562015-12-29 08:19:19 -08001601 }
1602
Louis Changbde91e92019-08-16 17:19:47 +08001603 if (mTargetStack == null) {
Louis Chang38430df2020-01-02 17:14:59 +08001604 mTargetStack = getLaunchStack(mStartActivity, mLaunchFlags, targetTask, mOptions);
Wale Ogunwale01d66562015-12-29 08:19:19 -08001605 }
Louis Changbde91e92019-08-16 17:19:47 +08001606 if (newTask) {
Louis Changcdec0802019-11-11 11:45:07 +08001607 final Task taskToAffiliate = (mLaunchTaskBehind && mSourceRecord != null)
1608 ? mSourceRecord.getTask() : null;
Louis Changbde91e92019-08-16 17:19:47 +08001609 setNewTask(taskToAffiliate);
Louis Changa3e6b892019-09-16 10:39:00 +08001610 if (mService.getLockTaskController().isLockTaskModeViolation(
Louis Changcdec0802019-11-11 11:45:07 +08001611 mStartActivity.getTask())) {
Louis Changa3e6b892019-09-16 10:39:00 +08001612 Slog.e(TAG, "Attempted Lock Task Mode violation mStartActivity=" + mStartActivity);
1613 return START_RETURN_LOCK_TASK_MODE_VIOLATION;
1614 }
Louis Changbde91e92019-08-16 17:19:47 +08001615 } else if (mAddingToTask) {
1616 addOrReparentStartingActivity(targetTask, "adding to task");
1617 }
1618
1619 if (!mAvoidMoveToFront && mDoResume) {
Louis Changa009c762020-02-26 11:21:31 +08001620 mTargetStack.getStack().moveToFront("reuseOrNewTask", targetTask);
Winson Chung8a168902020-03-12 22:39:22 -07001621 if (mOptions != null) {
Winson Chung8a168902020-03-12 22:39:22 -07001622 if (mOptions.getTaskAlwaysOnTop()) {
1623 mTargetStack.setAlwaysOnTop(true);
1624 }
1625 }
Chong Zhang6cda19c2016-06-14 19:07:56 -07001626 }
Wale Ogunwale01d66562015-12-29 08:19:19 -08001627
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00001628 mService.mUgmInternal.grantUriPermissionFromIntent(mCallingUid, mStartActivity.packageName,
1629 mIntent, mStartActivity.getUriPermissionsLocked(), mStartActivity.mUserId);
Patrick Baumann58bcea62020-02-25 17:30:36 -08001630 if (mStartActivity.resultTo != null && mStartActivity.resultTo.info != null) {
1631 // we need to resolve resultTo to a uid as grantImplicitAccess deals explicitly in UIDs
1632 final PackageManagerInternal pmInternal =
1633 mService.getPackageManagerInternalLocked();
1634 final int resultToUid = pmInternal.getPackageUidInternal(
1635 mStartActivity.resultTo.info.packageName, 0, mStartActivity.mUserId);
1636 pmInternal.grantImplicitAccess(mStartActivity.mUserId, mIntent,
1637 UserHandle.getAppId(mStartActivity.info.applicationInfo.uid) /*recipient*/,
1638 resultToUid /*visible*/, true /*direct*/);
1639 }
Wale Ogunwale01d66562015-12-29 08:19:19 -08001640 if (newTask) {
Jeff Changd136e772019-11-05 20:33:52 +08001641 EventLogTags.writeWmCreateTask(mStartActivity.mUserId,
Louis Changcdec0802019-11-11 11:45:07 +08001642 mStartActivity.getTask().mTaskId);
Wale Ogunwale01d66562015-12-29 08:19:19 -08001643 }
Andrii Kulian79d67982019-08-19 11:56:16 -07001644 mStartActivity.logStartActivity(
Jeff Changd136e772019-11-05 20:33:52 +08001645 EventLogTags.WM_CREATE_ACTIVITY, mStartActivity.getTask());
1646
Wale Ogunwale01d66562015-12-29 08:19:19 -08001647 mTargetStack.mLastPausedActivity = null;
Wei Wang98f03f92016-05-18 11:32:52 -07001648
Louis Chang149d5c82019-12-30 09:47:39 +08001649 mRootWindowContainer.sendPowerHintForLaunchStartIfNeeded(
Wale Ogunwaled32da472018-11-16 07:19:28 -08001650 false /* forceSend */, mStartActivity);
Wei Wang98f03f92016-05-18 11:32:52 -07001651
Wale Ogunwale21e06482019-11-18 05:14:15 -08001652 mTargetStack.startActivityLocked(mStartActivity, topStack.getTopNonFinishingActivity(),
1653 newTask, mKeepCurTransition, mOptions);
Wale Ogunwale01d66562015-12-29 08:19:19 -08001654 if (mDoResume) {
Bryce Leeaf691c02017-03-20 14:20:22 -07001655 final ActivityRecord topTaskActivity =
Louis Changcdec0802019-11-11 11:45:07 +08001656 mStartActivity.getTask().topRunningActivityLocked();
Evan Rosky226de132020-01-03 18:00:29 -08001657 if (!mTargetStack.isTopActivityFocusable()
Wale Ogunwale0b3d2922019-12-30 08:55:07 -08001658 || (topTaskActivity != null && topTaskActivity.isTaskOverlay()
Wale Ogunwale68741142016-05-17 09:40:02 -07001659 && mStartActivity != topTaskActivity)) {
Filip Gruszczynski3d7fdc12016-01-31 17:33:29 -08001660 // If the activity is not focusable, we can't resume it, but still would like to
1661 // make sure it becomes visible as it starts (this will also trigger entry
1662 // animation). An example of this are PIP activities.
Wale Ogunwale3b232392016-05-13 15:37:13 -07001663 // Also, we don't want to resume activities in a task that currently has an overlay
1664 // as the starting activity just needs to be in the visible paused state until the
1665 // over is removed.
Diego Vela671c0072020-03-25 09:39:26 -07001666 // Passing {@code null} as the start parameter ensures all activities are made
1667 // visible.
1668 mTargetStack.ensureActivitiesVisible(null /* starting */,
1669 0 /* configChanges */, !PRESERVE_WINDOWS);
Wale Ogunwaleae846f42016-02-22 14:00:56 -08001670 // Go ahead and tell window manager to execute app transition for this activity
1671 // since the app transition will not be triggered through the resume channel.
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001672 mTargetStack.getDisplay().mDisplayContent.executeAppTransition();
Wale Ogunwale3b232392016-05-13 15:37:13 -07001673 } else {
Winson Chung32066032016-11-04 11:55:21 -07001674 // If the target stack was not previously focusable (previous top running activity
1675 // on that stack was not visible) then any prior calls to move the stack to the
1676 // will not update the focused stack. If starting the new activity now allows the
1677 // task stack to be focusable, then ensure that we now update the focused stack
1678 // accordingly.
Evan Rosky226de132020-01-03 18:00:29 -08001679 if (mTargetStack.isTopActivityFocusable()
Louis Chang149d5c82019-12-30 09:47:39 +08001680 && !mRootWindowContainer.isTopDisplayFocusedStack(mTargetStack)) {
Riddle Hsu2ca561b2019-10-08 21:58:58 +08001681 mTargetStack.moveToFront("startActivityInner");
Winson Chung32066032016-11-04 11:55:21 -07001682 }
Louis Chang149d5c82019-12-30 09:47:39 +08001683 mRootWindowContainer.resumeFocusedStacksTopActivities(
Wale Ogunwaled32da472018-11-16 07:19:28 -08001684 mTargetStack, mStartActivity, mOptions);
Filip Gruszczynski3d7fdc12016-01-31 17:33:29 -08001685 }
Wale Ogunwale01d66562015-12-29 08:19:19 -08001686 }
Louis Chang149d5c82019-12-30 09:47:39 +08001687 mRootWindowContainer.updateUserStack(mStartActivity.mUserId, mTargetStack);
Wale Ogunwale01d66562015-12-29 08:19:19 -08001688
Winson Chungf45dd9f2019-10-11 15:07:47 -07001689 // Update the recent tasks list immediately when the activity starts
1690 mSupervisor.mRecentTasks.add(mStartActivity.getTask());
Louis Changcdec0802019-11-11 11:45:07 +08001691 mSupervisor.handleNonResizableTaskIfNeeded(mStartActivity.getTask(),
Andrii Kulian1cfcae82020-04-10 12:44:38 -07001692 mPreferredWindowingMode, mPreferredTaskDisplayArea, mTargetStack);
Wale Ogunwale01d66562015-12-29 08:19:19 -08001693
1694 return START_SUCCESS;
1695 }
1696
Louis Changcdec0802019-11-11 11:45:07 +08001697 private Task computeTargetTask() {
Louis Changf7dd7f22019-11-05 11:59:56 +08001698 if (mStartActivity.resultTo == null && mInTask == null && !mAddingToTask
Louis Changbde91e92019-08-16 17:19:47 +08001699 && (mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) != 0) {
1700 // A new task should be created instead of using existing one.
1701 return null;
1702 } else if (mSourceRecord != null) {
Louis Changcdec0802019-11-11 11:45:07 +08001703 return mSourceRecord.getTask();
Louis Changbde91e92019-08-16 17:19:47 +08001704 } else if (mInTask != null) {
1705 return mInTask;
1706 } else {
Louis Chang38430df2020-01-02 17:14:59 +08001707 final ActivityStack stack = getLaunchStack(mStartActivity, mLaunchFlags,
1708 null /* task */, mOptions);
1709 final ActivityRecord top = stack.getTopNonFinishingActivity();
Louis Changbde91e92019-08-16 17:19:47 +08001710 if (top != null) {
Louis Changcdec0802019-11-11 11:45:07 +08001711 return top.getTask();
Louis Chang38430df2020-01-02 17:14:59 +08001712 } else {
1713 // Remove the stack if no activity in the stack.
1714 stack.removeIfPossible();
Louis Changbde91e92019-08-16 17:19:47 +08001715 }
1716 }
1717 return null;
1718 }
1719
Louis Chang38430df2020-01-02 17:14:59 +08001720 private void computeLaunchParams(ActivityRecord r, ActivityRecord sourceRecord,
1721 Task targetTask) {
1722 final ActivityStack sourceStack = mSourceStack != null ? mSourceStack
1723 : mRootWindowContainer.getTopDisplayFocusedStack();
1724 if (sourceStack != null && sourceStack.inSplitScreenWindowingMode()
1725 && (mOptions == null
1726 || mOptions.getLaunchWindowingMode() == WINDOWING_MODE_UNDEFINED)) {
1727 int windowingMode =
1728 targetTask != null ? targetTask.getWindowingMode() : WINDOWING_MODE_UNDEFINED;
1729 if ((mLaunchFlags & FLAG_ACTIVITY_LAUNCH_ADJACENT) != 0) {
1730 if (sourceStack.inSplitScreenPrimaryWindowingMode()) {
1731 windowingMode = WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
1732 } else if (sourceStack.inSplitScreenSecondaryWindowingMode()) {
1733 windowingMode = WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
1734 }
1735 }
1736
1737 if (mOptions == null) {
1738 mOptions = ActivityOptions.makeBasic();
1739 }
1740 mOptions.setLaunchWindowingMode(windowingMode);
1741 }
1742
1743 mSupervisor.getLaunchParamsController().calculate(targetTask, r.info.windowLayout, r,
1744 sourceRecord, mOptions, PHASE_BOUNDS, mLaunchParams);
Andrii Kulian1cfcae82020-04-10 12:44:38 -07001745 mPreferredTaskDisplayArea = mLaunchParams.hasPreferredTaskDisplayArea()
1746 ? mLaunchParams.mPreferredTaskDisplayArea
1747 : mRootWindowContainer.getDefaultTaskDisplayArea();
Winson Chung8a168902020-03-12 22:39:22 -07001748 mPreferredWindowingMode = mLaunchParams.mWindowingMode;
Louis Chang38430df2020-01-02 17:14:59 +08001749 }
1750
Louis Changcdec0802019-11-11 11:45:07 +08001751 private int isAllowedToStart(ActivityRecord r, boolean newTask, Task targetTask) {
Louis Changbde91e92019-08-16 17:19:47 +08001752 if (mStartActivity.packageName == null) {
1753 if (mStartActivity.resultTo != null) {
1754 mStartActivity.resultTo.sendResult(INVALID_UID, mStartActivity.resultWho,
1755 mStartActivity.requestCode, RESULT_CANCELED, null /* data */);
1756 }
1757 ActivityOptions.abort(mOptions);
1758 return START_CLASS_NOT_FOUND;
1759 }
1760
1761 // Do not start home activity if it cannot be launched on preferred display. We are not
1762 // doing this in ActivityStackSupervisor#canPlaceEntityOnDisplay because it might
1763 // fallback to launch on other displays.
Andrii Kulian1cfcae82020-04-10 12:44:38 -07001764 if (r.isActivityTypeHome()) {
1765 if (!mRootWindowContainer.canStartHomeOnDisplayArea(r.info, mPreferredTaskDisplayArea,
1766 true /* allowInstrumenting */)) {
1767 Slog.w(TAG, "Cannot launch home on display area " + mPreferredTaskDisplayArea);
1768 return START_CANCELED;
1769 }
Louis Changbde91e92019-08-16 17:19:47 +08001770 }
1771
Wale Ogunwalea38654f2019-11-17 20:37:15 -08001772 if (mRestrictedBgActivity && (newTask || !targetTask.isUidPresent(mCallingUid))
Louis Changbde91e92019-08-16 17:19:47 +08001773 && handleBackgroundActivityAbort(mStartActivity)) {
1774 Slog.e(TAG, "Abort background activity starts from " + mCallingUid);
1775 return START_ABORTED;
1776 }
1777
1778 // When the flags NEW_TASK and CLEAR_TASK are set, then the task gets reused but still
1779 // needs to be a lock task mode violation since the task gets cleared out and the device
1780 // would otherwise leave the locked task.
1781 final boolean isNewClearTask =
1782 (mLaunchFlags & (FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK))
1783 == (FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK);
Louis Changa3e6b892019-09-16 10:39:00 +08001784 if (!newTask && mService.getLockTaskController().isLockTaskModeViolation(targetTask,
1785 isNewClearTask)) {
Louis Changbde91e92019-08-16 17:19:47 +08001786 Slog.e(TAG, "Attempted Lock Task Mode violation mStartActivity=" + mStartActivity);
1787 return START_RETURN_LOCK_TASK_MODE_VIOLATION;
1788 }
1789
1790 return START_SUCCESS;
1791 }
1792
1793 /**
1794 * Prepare the target task to be reused for this launch, which including:
1795 * - Position the target task on valid stack on preferred display.
1796 * - Comply to the specified activity launch flags
1797 * - Determine whether need to add a new activity on top or just brought the task to front.
1798 */
Louis Chang07b13002019-11-27 22:08:37 +08001799 @VisibleForTesting
1800 int recycleTask(Task targetTask, ActivityRecord targetTaskTop, Task reusedTask) {
1801 // Should not recycle task which is from a different user, just adding the starting
1802 // activity to the task.
1803 if (targetTask.mUserId != mStartActivity.mUserId) {
1804 mTargetStack = targetTask.getStack();
1805 mAddingToTask = true;
1806 return START_SUCCESS;
1807 }
1808
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08001809 boolean clearTaskForReuse = false;
Louis Changf7dd7f22019-11-05 11:59:56 +08001810 if (reusedTask != null) {
Louis Chang2787a9a2019-12-17 15:15:11 +08001811 if (mStartActivity.getTask() == null) {
Louis Changf7dd7f22019-11-05 11:59:56 +08001812 mStartActivity.setTaskForReuse(reusedTask);
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08001813 clearTaskForReuse = true;
1814 }
1815
Louis Changbde91e92019-08-16 17:19:47 +08001816 if (targetTask.intent == null) {
1817 // This task was started because of movement of the activity based on
1818 // affinity...
1819 // Now that we are actually launching it, we can assign the base intent.
1820 targetTask.setIntent(mStartActivity);
1821 } else {
1822 final boolean taskOnHome =
1823 (mStartActivity.intent.getFlags() & FLAG_ACTIVITY_TASK_ON_HOME) != 0;
1824 if (taskOnHome) {
1825 targetTask.intent.addFlags(FLAG_ACTIVITY_TASK_ON_HOME);
1826 } else {
1827 targetTask.intent.removeFlags(FLAG_ACTIVITY_TASK_ON_HOME);
1828 }
1829 }
1830 }
1831
Louis Chang149d5c82019-12-30 09:47:39 +08001832 mRootWindowContainer.sendPowerHintForLaunchStartIfNeeded(false /* forceSend */,
Louis Changbde91e92019-08-16 17:19:47 +08001833 targetTaskTop);
1834
1835 setTargetStackIfNeeded(targetTaskTop);
1836
Louis Changbde91e92019-08-16 17:19:47 +08001837 // When there is a reused activity and the current result is a trampoline activity,
1838 // set the reused activity as the result.
Louis Chang54fbb052019-10-16 17:10:17 +08001839 if (mLastStartActivityRecord != null
1840 && (mLastStartActivityRecord.finishing || mLastStartActivityRecord.noDisplay)) {
1841 mLastStartActivityRecord = targetTaskTop;
Louis Changbde91e92019-08-16 17:19:47 +08001842 }
1843
1844 if ((mStartFlags & START_FLAG_ONLY_IF_NEEDED) != 0) {
1845 // We don't need to start a new activity, and the client said not to do anything
1846 // if that is the case, so this is it! And for paranoia, make sure we have
1847 // correctly resumed the top activity.
1848 if (!mMovedToFront && mDoResume) {
1849 if (DEBUG_TASKS) {
1850 Slog.d(TAG_TASKS, "Bring to front target: " + mTargetStack
1851 + " from " + targetTaskTop);
1852 }
1853 mTargetStack.moveToFront("intentActivityFound");
1854 }
1855 resumeTargetStackIfNeeded();
1856 return START_RETURN_INTENT_TO_CALLER;
1857 }
1858
Wale Ogunwale21e06482019-11-18 05:14:15 -08001859 complyActivityFlags(targetTask,
1860 reusedTask != null ? reusedTask.getTopNonFinishingActivity() : null);
Louis Changbde91e92019-08-16 17:19:47 +08001861
Wale Ogunwaleda8b8272018-11-29 19:37:37 -08001862 if (clearTaskForReuse) {
1863 // Clear task for re-use so later code to methods
1864 // {@link #setTaskFromReuseOrCreateNewTask}, {@link #setTaskFromSourceRecord}, or
1865 // {@link #setTaskFromInTask} can parent it to the task.
1866 mStartActivity.setTaskForReuse(null);
1867 }
1868
Louis Changbde91e92019-08-16 17:19:47 +08001869 if (mAddingToTask) {
1870 return START_SUCCESS;
1871 }
1872
Louis Chang3ee5fc02019-09-23 11:32:10 +08001873 if (mMovedToFront) {
1874 // We moved the task to front, use starting window to hide initial drawn delay.
1875 targetTaskTop.showStartingWindow(null /* prev */, false /* newTask */,
1876 true /* taskSwitch */);
1877 } else if (mDoResume) {
1878 // Make sure the stack and its belonging display are moved to topmost.
Louis Changbde91e92019-08-16 17:19:47 +08001879 mTargetStack.moveToFront("intentActivityFound");
1880 }
1881 // We didn't do anything... but it was needed (a.k.a., client don't use that intent!)
1882 // And for paranoia, make sure we have correctly resumed the top activity.
1883 resumeTargetStackIfNeeded();
Louis Chang54fbb052019-10-16 17:10:17 +08001884 // The reusedActivity could be finishing, for example of starting an activity with
1885 // FLAG_ACTIVITY_CLEAR_TOP flag. In that case, return the top running activity in the
1886 // task instead.
1887 mLastStartActivityRecord =
Wale Ogunwale21e06482019-11-18 05:14:15 -08001888 targetTaskTop.finishing ? targetTask.getTopNonFinishingActivity() : targetTaskTop;
Louis Changbde91e92019-08-16 17:19:47 +08001889 return mMovedToFront ? START_TASK_TO_FRONT : START_DELIVERED_TO_TOP;
1890 }
1891
1892 /**
1893 * Check if the activity being launched is the same as the one currently at the top and it
1894 * should only be launched once.
1895 */
1896 private int deliverToCurrentTopIfNeeded(ActivityStack topStack) {
1897 final ActivityRecord top = topStack.topRunningNonDelayedActivityLocked(mNotTop);
Daniel Chapinde8fade2020-02-22 00:12:50 +00001898 final boolean dontStart = top != null && mStartActivity.resultTo == null
Louis Changbde91e92019-08-16 17:19:47 +08001899 && top.mActivityComponent.equals(mStartActivity.mActivityComponent)
1900 && top.mUserId == mStartActivity.mUserId
1901 && top.attachedToProcess()
1902 && ((mLaunchFlags & FLAG_ACTIVITY_SINGLE_TOP) != 0
Daniel Chapinde8fade2020-02-22 00:12:50 +00001903 || isLaunchModeOneOf(LAUNCH_SINGLE_TOP, LAUNCH_SINGLE_TASK))
Andrii Kulian1cfcae82020-04-10 12:44:38 -07001904 // This allows home activity to automatically launch on secondary task display area
1905 // when it was added, if home was the top activity on default task display area,
1906 // instead of sending new intent to the home activity on default display area.
1907 && (!top.isActivityTypeHome() || top.getDisplayArea() == mPreferredTaskDisplayArea);
Louis Changbde91e92019-08-16 17:19:47 +08001908 if (!dontStart) {
1909 return START_SUCCESS;
1910 }
1911
1912 // For paranoia, make sure we have correctly resumed the top activity.
1913 topStack.mLastPausedActivity = null;
1914 if (mDoResume) {
Louis Chang149d5c82019-12-30 09:47:39 +08001915 mRootWindowContainer.resumeFocusedStacksTopActivities();
Louis Changbde91e92019-08-16 17:19:47 +08001916 }
1917 ActivityOptions.abort(mOptions);
1918 if ((mStartFlags & START_FLAG_ONLY_IF_NEEDED) != 0) {
1919 // We don't need to start a new activity, and the client said not to do anything if
1920 // that is the case, so this is it!
1921 return START_RETURN_INTENT_TO_CALLER;
1922 }
1923
1924 deliverNewIntent(top);
1925
1926 // Don't use mStartActivity.task to show the toast. We're not starting a new activity but
1927 // reusing 'top'. Fields in mStartActivity may not be fully initialized.
Louis Changcdec0802019-11-11 11:45:07 +08001928 mSupervisor.handleNonResizableTaskIfNeeded(top.getTask(),
Andrii Kulian1cfcae82020-04-10 12:44:38 -07001929 mLaunchParams.mWindowingMode, mPreferredTaskDisplayArea, topStack);
Louis Changbde91e92019-08-16 17:19:47 +08001930
1931 return START_DELIVERED_TO_TOP;
1932 }
1933
1934 /**
1935 * Applying the launching flags to the task, which might clear few or all the activities in the
1936 * task.
1937 */
Louis Changcdec0802019-11-11 11:45:07 +08001938 private void complyActivityFlags(Task targetTask, ActivityRecord reusedActivity) {
Wale Ogunwale21e06482019-11-18 05:14:15 -08001939 ActivityRecord targetTaskTop = targetTask.getTopNonFinishingActivity();
Louis Chang2dcb1272019-09-27 15:01:19 +08001940 final boolean resetTask =
1941 reusedActivity != null && (mLaunchFlags & FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0;
1942 if (resetTask) {
Wale Ogunwaledfbeed72019-11-20 08:57:39 -08001943 targetTaskTop = mTargetStack.resetTaskIfNeeded(targetTaskTop, mStartActivity);
Louis Changbde91e92019-08-16 17:19:47 +08001944 }
1945
1946 if ((mLaunchFlags & (FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK))
1947 == (FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK)) {
1948 // The caller has requested to completely replace any existing task with its new
1949 // activity. Well that should not be too hard...
Louis Changcdec0802019-11-11 11:45:07 +08001950 // Note: we must persist the {@link Task} first as intentActivity could be
Louis Changbde91e92019-08-16 17:19:47 +08001951 // removed from calling performClearTaskLocked (For example, if it is being brought out
1952 // of history or if it is finished immediately), thus disassociating the task. Also note
Louis Changcdec0802019-11-11 11:45:07 +08001953 // that mReuseTask is reset as a result of {@link Task#performClearTaskLocked}
Louis Changbde91e92019-08-16 17:19:47 +08001954 // launching another activity.
1955 // TODO(b/36119896): We shouldn't trigger activity launches in this path since we are
1956 // already launching one.
1957 targetTask.performClearTaskLocked();
1958 targetTask.setIntent(mStartActivity);
1959 mAddingToTask = true;
1960 } else if ((mLaunchFlags & FLAG_ACTIVITY_CLEAR_TOP) != 0
1961 || isDocumentLaunchesIntoExisting(mLaunchFlags)
1962 || isLaunchModeOneOf(LAUNCH_SINGLE_INSTANCE, LAUNCH_SINGLE_TASK)) {
1963 // In this situation we want to remove all activities from the task up to the one
1964 // being started. In most cases this means we are resetting the task to its initial
1965 // state.
1966 final ActivityRecord top = targetTask.performClearTaskForReuseLocked(mStartActivity,
1967 mLaunchFlags);
1968
1969 // The above code can remove {@code reusedActivity} from the task, leading to the
Louis Changcdec0802019-11-11 11:45:07 +08001970 // {@code ActivityRecord} removing its reference to the {@code Task}. The task
Wale Ogunwalec17418e2019-10-13 23:00:40 +02001971 // reference is needed in the call below to {@link setTargetStackAndMoveToFrontIfNeeded}
Louis Changcdec0802019-11-11 11:45:07 +08001972 if (targetTaskTop.getTask() == null) {
Wale Ogunwale2322bed2019-10-10 17:24:19 +02001973 targetTask.addChild(targetTaskTop);
Louis Changbde91e92019-08-16 17:19:47 +08001974 }
1975
1976 if (top != null) {
1977 if (top.isRootOfTask()) {
1978 // Activity aliases may mean we use different intents for the top activity,
1979 // so make sure the task now has the identity of the new intent.
Louis Changcdec0802019-11-11 11:45:07 +08001980 top.getTask().setIntent(mStartActivity);
Louis Changbde91e92019-08-16 17:19:47 +08001981 }
1982 deliverNewIntent(top);
1983 } else {
1984 // A special case: we need to start the activity because it is not currently
1985 // running, and the caller has asked to clear the current task to have this
1986 // activity at the top.
1987 mAddingToTask = true;
1988 if (targetTask.getStack() == null) {
1989 // Target stack got cleared when we all activities were removed above.
1990 // Go ahead and reset it.
Louis Chang38430df2020-01-02 17:14:59 +08001991 mTargetStack =
1992 getLaunchStack(mStartActivity, mLaunchFlags, null /* task */, mOptions);
Wale Ogunwale2322bed2019-10-10 17:24:19 +02001993 mTargetStack.addChild(targetTask, !mLaunchTaskBehind /* toTop */,
1994 (mStartActivity.info.flags & FLAG_SHOW_FOR_ALL_USERS) != 0);
Louis Changbde91e92019-08-16 17:19:47 +08001995 }
1996 }
1997 } else if ((mLaunchFlags & FLAG_ACTIVITY_CLEAR_TOP) == 0 && !mAddingToTask
1998 && (mLaunchFlags & FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) {
1999 // In this case, we are launching an activity in our own task that may
2000 // already be running somewhere in the history, and we want to shuffle it to
2001 // the front of the stack if so.
Wale Ogunwalea38654f2019-11-17 20:37:15 -08002002 final ActivityRecord act =
2003 targetTask.findActivityInHistory(mStartActivity.mActivityComponent);
Louis Changbde91e92019-08-16 17:19:47 +08002004 if (act != null) {
Louis Changcdec0802019-11-11 11:45:07 +08002005 final Task task = act.getTask();
Louis Changbde91e92019-08-16 17:19:47 +08002006 task.moveActivityToFrontLocked(act);
2007 act.updateOptionsLocked(mOptions);
2008 deliverNewIntent(act);
2009 mTargetStack.mLastPausedActivity = null;
2010 } else {
2011 mAddingToTask = true;
2012 }
2013 } else if (mStartActivity.mActivityComponent.equals(targetTask.realActivity)) {
Louis Chang382419b2019-10-03 21:43:38 +08002014 if (targetTask == mInTask) {
2015 // In this case we are bringing up an existing activity from a recent task. We
2016 // don't need to add a new activity instance on top.
2017 } else if (((mLaunchFlags & FLAG_ACTIVITY_SINGLE_TOP) != 0
2018 || LAUNCH_SINGLE_TOP == mLaunchMode)
2019 && targetTaskTop.mActivityComponent.equals(mStartActivity.mActivityComponent)
2020 && mStartActivity.resultTo == null) {
2021 // In this case the top activity on the task is the same as the one being launched,
2022 // so we take that as a request to bring the task to the foreground. If the top
2023 // activity in the task is the root activity, deliver this new intent to it if it
2024 // desires.
Louis Changbde91e92019-08-16 17:19:47 +08002025 if (targetTaskTop.isRootOfTask()) {
Louis Changcdec0802019-11-11 11:45:07 +08002026 targetTaskTop.getTask().setIntent(mStartActivity);
Louis Changbde91e92019-08-16 17:19:47 +08002027 }
2028 deliverNewIntent(targetTaskTop);
2029 } else if (!targetTask.isSameIntentFilter(mStartActivity)) {
2030 // In this case we are launching the root activity of the task, but with a
2031 // different intent. We should start a new instance on top.
2032 mAddingToTask = true;
2033 } else if (reusedActivity == null) {
2034 mAddingToTask = true;
2035 }
Louis Chang2dcb1272019-09-27 15:01:19 +08002036 } else if (!resetTask) {
Louis Changbde91e92019-08-16 17:19:47 +08002037 // In this case an activity is being launched in to an existing task, without
2038 // resetting that task. This is typically the situation of launching an activity
2039 // from a notification or shortcut. We want to place the new activity on top of the
2040 // current task.
2041 mAddingToTask = true;
2042 } else if (!targetTask.rootWasReset) {
2043 // In this case we are launching into an existing task that has not yet been started
2044 // from its front door. The current task has been brought to the front. Ideally,
2045 // we'd probably like to place this new task at the bottom of its stack, but that's
2046 // a little hard to do with the current organization of the code so for now we'll
2047 // just drop it.
2048 targetTask.setIntent(mStartActivity);
2049 }
2050 }
2051
Bryce Leedaa91e42017-12-06 14:13:01 -08002052 /**
2053 * Resets the {@link ActivityStarter} state.
2054 * @param clearRequest whether the request should be reset to default values.
2055 */
2056 void reset(boolean clearRequest) {
2057 mStartActivity = null;
2058 mIntent = null;
2059 mCallingUid = -1;
2060 mOptions = null;
Ricky Waib147fa12019-04-25 16:08:30 +01002061 mRestrictedBgActivity = false;
Bryce Leedaa91e42017-12-06 14:13:01 -08002062
2063 mLaunchTaskBehind = false;
2064 mLaunchFlags = 0;
2065 mLaunchMode = INVALID_LAUNCH_MODE;
2066
Bryce Leeec55eb02017-12-05 20:51:27 -08002067 mLaunchParams.reset();
Bryce Leedaa91e42017-12-06 14:13:01 -08002068
2069 mNotTop = null;
2070 mDoResume = false;
2071 mStartFlags = 0;
2072 mSourceRecord = null;
Andrii Kulian1cfcae82020-04-10 12:44:38 -07002073 mPreferredTaskDisplayArea = null;
Winson Chung8a168902020-03-12 22:39:22 -07002074 mPreferredWindowingMode = WINDOWING_MODE_UNDEFINED;
Bryce Leedaa91e42017-12-06 14:13:01 -08002075
2076 mInTask = null;
2077 mAddingToTask = false;
2078 mReuseTask = null;
2079
2080 mNewTaskInfo = null;
2081 mNewTaskIntent = null;
2082 mSourceStack = null;
2083
2084 mTargetStack = null;
Winson Chunge789ff62020-02-24 14:40:23 -08002085 mTargetTask = null;
Bryce Leedaa91e42017-12-06 14:13:01 -08002086 mMovedToFront = false;
2087 mNoAnimation = false;
2088 mKeepCurTransition = false;
2089 mAvoidMoveToFront = false;
Winson Chunge219ae12019-07-18 13:43:23 -07002090 mFrozeTaskList = false;
Bryce Leedaa91e42017-12-06 14:13:01 -08002091
2092 mVoiceSession = null;
2093 mVoiceInteractor = null;
2094
2095 mIntentDelivered = false;
2096
2097 if (clearRequest) {
2098 mRequest.reset();
2099 }
2100 }
2101
Louis Changcdec0802019-11-11 11:45:07 +08002102 private void setInitialState(ActivityRecord r, ActivityOptions options, Task inTask,
Wale Ogunwale01d66562015-12-29 08:19:19 -08002103 boolean doResume, int startFlags, ActivityRecord sourceRecord,
Ricky Waib147fa12019-04-25 16:08:30 +01002104 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
2105 boolean restrictedBgActivity) {
Bryce Leedaa91e42017-12-06 14:13:01 -08002106 reset(false /* clearRequest */);
2107
Wale Ogunwale01d66562015-12-29 08:19:19 -08002108 mStartActivity = r;
2109 mIntent = r.intent;
2110 mOptions = options;
2111 mCallingUid = r.launchedFromUid;
2112 mSourceRecord = sourceRecord;
2113 mVoiceSession = voiceSession;
2114 mVoiceInteractor = voiceInteractor;
Ricky Waib147fa12019-04-25 16:08:30 +01002115 mRestrictedBgActivity = restrictedBgActivity;
Wale Ogunwale01d66562015-12-29 08:19:19 -08002116
Bryce Leeec55eb02017-12-05 20:51:27 -08002117 mLaunchParams.reset();
Bryce Leedacefc42017-10-10 12:56:02 -07002118
Louis Chang6fb1e842018-12-03 16:07:50 +08002119 // Preferred display id is the only state we need for now and it could be updated again
2120 // after we located a reusable task (which might be resided in another display).
Garfield Tan706dbcb2018-10-15 11:33:02 -07002121 mSupervisor.getLaunchParamsController().calculate(inTask, r.info.windowLayout, r,
Louis Chang6fb1e842018-12-03 16:07:50 +08002122 sourceRecord, options, PHASE_DISPLAY, mLaunchParams);
Andrii Kulian1cfcae82020-04-10 12:44:38 -07002123 mPreferredTaskDisplayArea = mLaunchParams.hasPreferredTaskDisplayArea()
2124 ? mLaunchParams.mPreferredTaskDisplayArea
2125 : mRootWindowContainer.getDefaultTaskDisplayArea();
Winson Chung8a168902020-03-12 22:39:22 -07002126 mPreferredWindowingMode = mLaunchParams.mWindowingMode;
Garfield Tanb5cc09f2018-09-28 10:06:52 -07002127
Bryce Lee7daee392017-10-12 13:46:18 -07002128 mLaunchMode = r.launchMode;
2129
Wale Ogunwale01d66562015-12-29 08:19:19 -08002130 mLaunchFlags = adjustLaunchFlagsToDocumentMode(
Bryce Lee7daee392017-10-12 13:46:18 -07002131 r, LAUNCH_SINGLE_INSTANCE == mLaunchMode,
2132 LAUNCH_SINGLE_TASK == mLaunchMode, mIntent.getFlags());
Wale Ogunwale01d66562015-12-29 08:19:19 -08002133 mLaunchTaskBehind = r.mLaunchTaskBehind
Bryce Lee7daee392017-10-12 13:46:18 -07002134 && !isLaunchModeOneOf(LAUNCH_SINGLE_TASK, LAUNCH_SINGLE_INSTANCE)
Wale Ogunwale01d66562015-12-29 08:19:19 -08002135 && (mLaunchFlags & FLAG_ACTIVITY_NEW_DOCUMENT) != 0;
2136
Daniel Chapinde8fade2020-02-22 00:12:50 +00002137 sendNewTaskResultRequestIfNeeded();
2138
Wale Ogunwale01d66562015-12-29 08:19:19 -08002139 if ((mLaunchFlags & FLAG_ACTIVITY_NEW_DOCUMENT) != 0 && r.resultTo == null) {
2140 mLaunchFlags |= FLAG_ACTIVITY_NEW_TASK;
2141 }
2142
2143 // If we are actually going to launch in to a new task, there are some cases where
2144 // we further want to do multiple task.
2145 if ((mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) != 0) {
2146 if (mLaunchTaskBehind
2147 || r.info.documentLaunchMode == DOCUMENT_LAUNCH_ALWAYS) {
2148 mLaunchFlags |= FLAG_ACTIVITY_MULTIPLE_TASK;
2149 }
2150 }
2151
2152 // We'll invoke onUserLeaving before onPause only if the launching
2153 // activity did not explicitly state that this is an automated launch.
2154 mSupervisor.mUserLeaving = (mLaunchFlags & FLAG_ACTIVITY_NO_USER_ACTION) == 0;
2155 if (DEBUG_USER_LEAVING) Slog.v(TAG_USER_LEAVING,
2156 "startActivity() => mUserLeaving=" + mSupervisor.mUserLeaving);
2157
2158 // If the caller has asked not to resume at this point, we make note
2159 // of this in the record so that we can skip it when trying to find
2160 // the top running activity.
2161 mDoResume = doResume;
Louis Chang37317152019-05-09 09:53:58 +08002162 if (!doResume || !r.okToShowLocked() || mLaunchTaskBehind) {
Wale Ogunwale01d66562015-12-29 08:19:19 -08002163 r.delayedResume = true;
2164 mDoResume = false;
2165 }
2166
Winson Chunge2d72172018-01-25 17:46:20 +00002167 if (mOptions != null) {
Winson Chung8a168902020-03-12 22:39:22 -07002168 if (mOptions.getLaunchTaskId() != INVALID_TASK_ID && mOptions.getTaskOverlay()) {
Wale Ogunwale0b3d2922019-12-30 08:55:07 -08002169 r.setTaskOverlay(true);
Winson Chunge2d72172018-01-25 17:46:20 +00002170 if (!mOptions.canTaskOverlayResume()) {
Louis Chang149d5c82019-12-30 09:47:39 +08002171 final Task task = mRootWindowContainer.anyTaskForId(
Winson Chunge2d72172018-01-25 17:46:20 +00002172 mOptions.getLaunchTaskId());
Wale Ogunwale21e06482019-11-18 05:14:15 -08002173 final ActivityRecord top = task != null
2174 ? task.getTopNonFinishingActivity() : null;
Bryce Lee7ace3952018-02-16 14:34:32 -08002175 if (top != null && !top.isState(RESUMED)) {
Jorim Jaggic875ae72016-04-26 22:41:06 -07002176
Winson Chunge2d72172018-01-25 17:46:20 +00002177 // The caller specifies that we'd like to be avoided to be moved to the
2178 // front, so be it!
2179 mDoResume = false;
2180 mAvoidMoveToFront = true;
2181 }
Winson Chungcbcadc92017-01-12 15:54:12 -08002182 }
Winson Chunge2d72172018-01-25 17:46:20 +00002183 } else if (mOptions.getAvoidMoveToFront()) {
Winson Chungba40d3a2018-05-16 09:40:16 -07002184 mDoResume = false;
Winson Chunge2d72172018-01-25 17:46:20 +00002185 mAvoidMoveToFront = true;
Jorim Jaggic875ae72016-04-26 22:41:06 -07002186 }
2187 }
2188
Louis Chang2f4e9b462019-03-05 16:43:15 +08002189 mNotTop = (mLaunchFlags & FLAG_ACTIVITY_PREVIOUS_IS_TOP) != 0 ? sourceRecord : null;
Wale Ogunwale01d66562015-12-29 08:19:19 -08002190
2191 mInTask = inTask;
2192 // In some flows in to this function, we retrieve the task record and hold on to it
2193 // without a lock before calling back in to here... so the task at this point may
2194 // not actually be in recents. Check for that, and if it isn't in recents just
2195 // consider it invalid.
2196 if (inTask != null && !inTask.inRecents) {
2197 Slog.w(TAG, "Starting activity in task not in recents: " + inTask);
2198 mInTask = null;
2199 }
2200
2201 mStartFlags = startFlags;
2202 // If the onlyIfNeeded flag is set, then we can do this if the activity being launched
2203 // is the same as the one making the call... or, as a special case, if we do not know
2204 // the caller then we count the current top activity as the caller.
2205 if ((startFlags & START_FLAG_ONLY_IF_NEEDED) != 0) {
2206 ActivityRecord checkedCaller = sourceRecord;
2207 if (checkedCaller == null) {
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08002208 ActivityStack topFocusedStack = mRootWindowContainer.getTopDisplayFocusedStack();
2209 if (topFocusedStack != null) {
2210 checkedCaller = topFocusedStack.topRunningNonDelayedActivityLocked(mNotTop);
2211 }
Wale Ogunwale01d66562015-12-29 08:19:19 -08002212 }
Darryl L Johnson1e3885c2020-02-27 17:38:13 -08002213 if (checkedCaller == null
2214 || !checkedCaller.mActivityComponent.equals(r.mActivityComponent)) {
Wale Ogunwale01d66562015-12-29 08:19:19 -08002215 // Caller is not the same as launcher, so always needed.
2216 mStartFlags &= ~START_FLAG_ONLY_IF_NEEDED;
2217 }
2218 }
2219
2220 mNoAnimation = (mLaunchFlags & FLAG_ACTIVITY_NO_ANIMATION) != 0;
Ricky Waib147fa12019-04-25 16:08:30 +01002221
Alan Stokes07389b62019-05-20 15:22:54 +01002222 if (mRestrictedBgActivity && !mService.isBackgroundActivityStartsEnabled()) {
Ricky Waib147fa12019-04-25 16:08:30 +01002223 mAvoidMoveToFront = true;
2224 mDoResume = false;
2225 }
Wale Ogunwale01d66562015-12-29 08:19:19 -08002226 }
2227
2228 private void sendNewTaskResultRequestIfNeeded() {
Andrii Kulian79d67982019-08-19 11:56:16 -07002229 if (mStartActivity.resultTo != null && (mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) != 0) {
Wale Ogunwale01d66562015-12-29 08:19:19 -08002230 // For whatever reason this activity is being launched into a new task...
2231 // yet the caller has requested a result back. Well, that is pretty messed up,
2232 // so instead immediately send back a cancel and let the new task continue launched
2233 // as normal without a dependency on its originator.
2234 Slog.w(TAG, "Activity is launching as a new task, so cancelling activity result.");
Andrii Kulian79d67982019-08-19 11:56:16 -07002235 mStartActivity.resultTo.sendResult(INVALID_UID, mStartActivity.resultWho,
2236 mStartActivity.requestCode, RESULT_CANCELED, null /* data */);
Wale Ogunwale01d66562015-12-29 08:19:19 -08002237 mStartActivity.resultTo = null;
2238 }
2239 }
2240
2241 private void computeLaunchingTaskFlags() {
2242 // If the caller is not coming from another activity, but has given us an explicit task into
2243 // which they would like us to launch the new activity, then let's see about doing that.
Andrii Kulian02b7a832016-10-06 23:11:56 -07002244 if (mSourceRecord == null && mInTask != null && mInTask.getStack() != null) {
Wale Ogunwale01d66562015-12-29 08:19:19 -08002245 final Intent baseIntent = mInTask.getBaseIntent();
2246 final ActivityRecord root = mInTask.getRootActivity();
2247 if (baseIntent == null) {
2248 ActivityOptions.abort(mOptions);
2249 throw new IllegalArgumentException("Launching into task without base intent: "
2250 + mInTask);
2251 }
2252
2253 // If this task is empty, then we are adding the first activity -- it
2254 // determines the root, and must be launching as a NEW_TASK.
Bryce Lee7daee392017-10-12 13:46:18 -07002255 if (isLaunchModeOneOf(LAUNCH_SINGLE_INSTANCE, LAUNCH_SINGLE_TASK)) {
Wale Ogunwale01d66562015-12-29 08:19:19 -08002256 if (!baseIntent.getComponent().equals(mStartActivity.intent.getComponent())) {
2257 ActivityOptions.abort(mOptions);
2258 throw new IllegalArgumentException("Trying to launch singleInstance/Task "
2259 + mStartActivity + " into different task " + mInTask);
2260 }
2261 if (root != null) {
2262 ActivityOptions.abort(mOptions);
2263 throw new IllegalArgumentException("Caller with mInTask " + mInTask
2264 + " has root " + root + " but target is singleInstance/Task");
2265 }
2266 }
2267
2268 // If task is empty, then adopt the interesting intent launch flags in to the
2269 // activity being started.
2270 if (root == null) {
2271 final int flagsOfInterest = FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_MULTIPLE_TASK
2272 | FLAG_ACTIVITY_NEW_DOCUMENT | FLAG_ACTIVITY_RETAIN_IN_RECENTS;
2273 mLaunchFlags = (mLaunchFlags & ~flagsOfInterest)
2274 | (baseIntent.getFlags() & flagsOfInterest);
2275 mIntent.setFlags(mLaunchFlags);
2276 mInTask.setIntent(mStartActivity);
2277 mAddingToTask = true;
2278
2279 // If the task is not empty and the caller is asking to start it as the root of
2280 // a new task, then we don't actually want to start this on the task. We will
2281 // bring the task to the front, and possibly give it a new intent.
2282 } else if ((mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) != 0) {
2283 mAddingToTask = false;
2284
2285 } else {
2286 mAddingToTask = true;
2287 }
2288
2289 mReuseTask = mInTask;
2290 } else {
2291 mInTask = null;
2292 // Launch ResolverActivity in the source task, so that it stays in the task bounds
2293 // when in freeform workspace.
2294 // Also put noDisplay activities in the source task. These by itself can be placed
2295 // in any task/stack, however it could launch other activities like ResolverActivity,
2296 // and we want those to stay in the original task.
Louis Chang6a9be162019-07-15 10:41:32 +08002297 if ((mStartActivity.isResolverOrDelegateActivity() || mStartActivity.noDisplay)
2298 && mSourceRecord != null && mSourceRecord.inFreeformWindowingMode()) {
Wale Ogunwale01d66562015-12-29 08:19:19 -08002299 mAddingToTask = true;
2300 }
2301 }
2302
2303 if (mInTask == null) {
2304 if (mSourceRecord == null) {
2305 // This activity is not being started from another... in this
2306 // case we -always- start a new task.
2307 if ((mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) == 0 && mInTask == null) {
2308 Slog.w(TAG, "startActivity called from non-Activity context; forcing " +
2309 "Intent.FLAG_ACTIVITY_NEW_TASK for: " + mIntent);
2310 mLaunchFlags |= FLAG_ACTIVITY_NEW_TASK;
2311 }
2312 } else if (mSourceRecord.launchMode == LAUNCH_SINGLE_INSTANCE) {
2313 // The original activity who is starting us is running as a single
2314 // instance... this new activity it is starting must go on its
2315 // own task.
2316 mLaunchFlags |= FLAG_ACTIVITY_NEW_TASK;
Bryce Lee7daee392017-10-12 13:46:18 -07002317 } else if (isLaunchModeOneOf(LAUNCH_SINGLE_INSTANCE, LAUNCH_SINGLE_TASK)) {
Wale Ogunwale01d66562015-12-29 08:19:19 -08002318 // The activity being started is a single instance... it always
2319 // gets launched into its own task.
2320 mLaunchFlags |= FLAG_ACTIVITY_NEW_TASK;
2321 }
2322 }
2323 }
2324
2325 private void computeSourceStack() {
2326 if (mSourceRecord == null) {
2327 mSourceStack = null;
2328 return;
2329 }
2330 if (!mSourceRecord.finishing) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002331 mSourceStack = mSourceRecord.getRootTask();
Wale Ogunwale01d66562015-12-29 08:19:19 -08002332 return;
2333 }
2334
2335 // If the source is finishing, we can't further count it as our source. This is because the
2336 // task it is associated with may now be empty and on its way out, so we don't want to
2337 // blindly throw it in to that task. Instead we will take the NEW_TASK flow and try to find
2338 // a task for it. But save the task information so it can be used when creating the new task.
2339 if ((mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) == 0) {
2340 Slog.w(TAG, "startActivity called from finishing " + mSourceRecord
2341 + "; forcing " + "Intent.FLAG_ACTIVITY_NEW_TASK for: " + mIntent);
2342 mLaunchFlags |= FLAG_ACTIVITY_NEW_TASK;
2343 mNewTaskInfo = mSourceRecord.info;
Bryce Leed9ed45d2017-05-22 15:57:24 -07002344
2345 // It is not guaranteed that the source record will have a task associated with it. For,
2346 // example, if this method is being called for processing a pending activity launch, it
2347 // is possible that the activity has been removed from the task after the launch was
2348 // enqueued.
Louis Changcdec0802019-11-11 11:45:07 +08002349 final Task sourceTask = mSourceRecord.getTask();
Bryce Leed9ed45d2017-05-22 15:57:24 -07002350 mNewTaskIntent = sourceTask != null ? sourceTask.intent : null;
Wale Ogunwale01d66562015-12-29 08:19:19 -08002351 }
2352 mSourceRecord = null;
2353 mSourceStack = null;
2354 }
2355
2356 /**
2357 * Decide whether the new activity should be inserted into an existing task. Returns null
2358 * if not or an ActivityRecord with the task into which the new activity should be added.
2359 */
Louis Changcdec0802019-11-11 11:45:07 +08002360 private Task getReusableTask() {
Winson Chung8a168902020-03-12 22:39:22 -07002361 // If a target task is specified, try to reuse that one
2362 if (mOptions != null && mOptions.getLaunchTaskId() != INVALID_TASK_ID) {
2363 Task launchTask = mRootWindowContainer.anyTaskForId(mOptions.getLaunchTaskId());
2364 if (launchTask != null) {
2365 return launchTask;
2366 }
2367 return null;
2368 }
2369
Wale Ogunwale01d66562015-12-29 08:19:19 -08002370 // We may want to try to place the new activity in to an existing task. We always
2371 // do this if the target activity is singleTask or singleInstance; we will also do
2372 // this if NEW_TASK has been requested, and there is not an additional qualifier telling
2373 // us to still place it in a new task: multi task, always doc mode, or being asked to
2374 // launch this as a new task behind the current one.
2375 boolean putIntoExistingTask = ((mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) != 0 &&
2376 (mLaunchFlags & FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
Bryce Lee7daee392017-10-12 13:46:18 -07002377 || isLaunchModeOneOf(LAUNCH_SINGLE_INSTANCE, LAUNCH_SINGLE_TASK);
Wale Ogunwale01d66562015-12-29 08:19:19 -08002378 // If bring to front is requested, and no result is requested and we have not been given
2379 // an explicit task to launch in to, and we can find a task that was started with this
2380 // same component, then instead of launching bring that one to the front.
2381 putIntoExistingTask &= mInTask == null && mStartActivity.resultTo == null;
2382 ActivityRecord intentActivity = null;
Winson Chung8a168902020-03-12 22:39:22 -07002383 if (putIntoExistingTask) {
Bryce Lee7daee392017-10-12 13:46:18 -07002384 if (LAUNCH_SINGLE_INSTANCE == mLaunchMode) {
Wale Ogunwale13dbfff2016-05-20 08:50:15 -07002385 // There can be one and only one instance of single instance activity in the
2386 // history, and it is always in its own unique task, so we do a special search.
Louis Chang149d5c82019-12-30 09:47:39 +08002387 intentActivity = mRootWindowContainer.findActivity(mIntent, mStartActivity.info,
Wale Ogunwale6fbde9f2017-08-24 07:24:12 -07002388 mStartActivity.isActivityTypeHome());
Wale Ogunwale13dbfff2016-05-20 08:50:15 -07002389 } else if ((mLaunchFlags & FLAG_ACTIVITY_LAUNCH_ADJACENT) != 0) {
2390 // For the launch adjacent case we only want to put the activity in an existing
2391 // task if the activity already exists in the history.
Louis Chang149d5c82019-12-30 09:47:39 +08002392 intentActivity = mRootWindowContainer.findActivity(mIntent, mStartActivity.info,
Bryce Lee7daee392017-10-12 13:46:18 -07002393 !(LAUNCH_SINGLE_TASK == mLaunchMode));
Wale Ogunwale13dbfff2016-05-20 08:50:15 -07002394 } else {
2395 // Otherwise find the best task to put the activity in.
Wale Ogunwaled32da472018-11-16 07:19:28 -08002396 intentActivity =
Andrii Kulian1cfcae82020-04-10 12:44:38 -07002397 mRootWindowContainer.findTask(mStartActivity, mPreferredTaskDisplayArea);
Wale Ogunwale13dbfff2016-05-20 08:50:15 -07002398 }
Wale Ogunwale01d66562015-12-29 08:19:19 -08002399 }
Louis Changbd48dca2018-08-29 17:44:34 +08002400
Louis Chang54506cb2018-11-23 11:03:41 +08002401 if (intentActivity != null
2402 && (mStartActivity.isActivityTypeHome() || intentActivity.isActivityTypeHome())
Andrii Kulian1cfcae82020-04-10 12:44:38 -07002403 && intentActivity.getDisplayArea() != mPreferredTaskDisplayArea) {
2404 // Do not reuse home activity on other display areas.
Louis Changbd48dca2018-08-29 17:44:34 +08002405 intentActivity = null;
2406 }
2407
Louis Changcdec0802019-11-11 11:45:07 +08002408 return intentActivity != null ? intentActivity.getTask() : null;
Wale Ogunwale01d66562015-12-29 08:19:19 -08002409 }
2410
Andrii Kulianfab9cd82017-03-21 19:37:09 -07002411 /**
2412 * Figure out which task and activity to bring to front when we have found an existing matching
2413 * activity record in history. May also clear the task if needed.
2414 * @param intentActivity Existing matching activity.
2415 * @return {@link ActivityRecord} brought to front.
2416 */
Louis Changbde91e92019-08-16 17:19:47 +08002417 private void setTargetStackIfNeeded(ActivityRecord intentActivity) {
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002418 mTargetStack = intentActivity.getRootTask();
Wale Ogunwale01d66562015-12-29 08:19:19 -08002419 mTargetStack.mLastPausedActivity = null;
Louis Changa009c762020-02-26 11:21:31 +08002420 Task intentTask = intentActivity.getTask();
Wale Ogunwale01d66562015-12-29 08:19:19 -08002421 // If the target task is not in the front, then we need to bring it to the front...
2422 // except... well, with SINGLE_TASK_LAUNCH it's not entirely clear. We'd like to have
2423 // the same behavior as if a new instance was being started, which means not bringing it
2424 // to the front if the caller is not itself in the front.
Riddle Hsub70b36d2018-09-11 21:20:02 +08002425 final boolean differentTopTask;
Andrii Kulian1cfcae82020-04-10 12:44:38 -07002426 if (mTargetStack.getDisplayArea() == mPreferredTaskDisplayArea) {
Riddle Hsub70b36d2018-09-11 21:20:02 +08002427 final ActivityStack focusStack = mTargetStack.getDisplay().getFocusedStack();
2428 final ActivityRecord curTop = (focusStack == null)
2429 ? null : focusStack.topRunningNonDelayedActivityLocked(mNotTop);
Louis Changcdec0802019-11-11 11:45:07 +08002430 final Task topTask = curTop != null ? curTop.getTask() : null;
Louis Changa009c762020-02-26 11:21:31 +08002431 differentTopTask = topTask != intentTask
Wale Ogunwale85fb19a2019-12-05 10:41:05 +09002432 || (focusStack != null && topTask != focusStack.getTopMostTask());
Riddle Hsub70b36d2018-09-11 21:20:02 +08002433 } else {
2434 // The existing task should always be different from those in other displays.
2435 differentTopTask = true;
2436 }
Wale Ogunwale01d66562015-12-29 08:19:19 -08002437
Riddle Hsub70b36d2018-09-11 21:20:02 +08002438 if (differentTopTask && !mAvoidMoveToFront) {
Wale Ogunwale01d66562015-12-29 08:19:19 -08002439 mStartActivity.intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
Wale Ogunwale21e06482019-11-18 05:14:15 -08002440 if (mSourceRecord == null || (mSourceStack.getTopNonFinishingActivity() != null &&
2441 mSourceStack.getTopNonFinishingActivity().getTask()
Louis Changcdec0802019-11-11 11:45:07 +08002442 == mSourceRecord.getTask())) {
Wale Ogunwale01d66562015-12-29 08:19:19 -08002443 // We really do want to push this one into the user's face, right now.
2444 if (mLaunchTaskBehind && mSourceRecord != null) {
Louis Changcdec0802019-11-11 11:45:07 +08002445 intentActivity.setTaskToAffiliateWith(mSourceRecord.getTask());
Wale Ogunwale01d66562015-12-29 08:19:19 -08002446 }
Chong Zhangdea4bd92016-03-15 12:50:03 -07002447
Louis Changf3070c52019-10-09 15:57:30 +08002448 final ActivityStack launchStack =
2449 getLaunchStack(mStartActivity, mLaunchFlags, intentTask, mOptions);
Louis Changbde91e92019-08-16 17:19:47 +08002450 if (launchStack == null || launchStack == mTargetStack) {
Louis Chang38430df2020-01-02 17:14:59 +08002451 // Do not set mMovedToFront to true below for split-screen-top stack, or
2452 // START_TASK_TO_FRONT will be returned and trigger unexpected animations when a
2453 // new intent has delivered.
2454 final boolean isSplitScreenTopStack = mTargetStack.isTopSplitScreenStack();
2455
Louis Changa009c762020-02-26 11:21:31 +08002456 // TODO(b/151572268): Figure out a better way to move tasks in above 2-levels
2457 // tasks hierarchies.
2458 if (mTargetStack != intentTask
2459 && mTargetStack != intentTask.getParent().asTask()) {
2460 intentTask.getParent().positionChildAt(POSITION_TOP, intentTask,
2461 false /* includingParents */);
2462 intentTask = intentTask.getParent().asTask();
2463 }
Louis Changbde91e92019-08-16 17:19:47 +08002464 // We only want to move to the front, if we aren't going to launch on a
2465 // different stack. If we launch on a different stack, we will put the
2466 // task on top there.
Louis Chang38430df2020-01-02 17:14:59 +08002467 // Defer resuming the top activity while moving task to top, since the
2468 // current task-top activity may not be the activity that should be resumed.
Wale Ogunwale0d465192020-01-23 19:14:44 -08002469 mTargetStack.moveTaskToFront(intentTask, mNoAnimation, mOptions,
Louis Chang38430df2020-01-02 17:14:59 +08002470 mStartActivity.appTimeTracker, DEFER_RESUME,
2471 "bringingFoundTaskToFront");
2472 mMovedToFront = !isSplitScreenTopStack;
2473 } else {
2474 intentTask.reparent(launchStack, ON_TOP, REPARENT_MOVE_STACK_TO_FRONT, ANIMATE,
2475 DEFER_RESUME, "reparentToTargetStack");
Louis Changbde91e92019-08-16 17:19:47 +08002476 mMovedToFront = true;
Louis Changf3070c52019-10-09 15:57:30 +08002477 }
Louis Changbde91e92019-08-16 17:19:47 +08002478 mOptions = null;
Wale Ogunwale01d66562015-12-29 08:19:19 -08002479 }
2480 }
Andrii Kulianb850ea52017-12-12 23:49:10 -08002481 // Need to update mTargetStack because if task was moved out of it, the original stack may
2482 // be destroyed.
Wale Ogunwale1ebcd8e2020-01-21 11:27:03 -08002483 mTargetStack = intentActivity.getRootTask();
Louis Changa009c762020-02-26 11:21:31 +08002484 mSupervisor.handleNonResizableTaskIfNeeded(intentTask, WINDOWING_MODE_UNDEFINED,
Andrii Kulian1cb59dd2020-04-10 12:17:17 -07002485 mRootWindowContainer.getDefaultTaskDisplayArea(), mTargetStack);
Wale Ogunwale01d66562015-12-29 08:19:19 -08002486 }
2487
2488 private void resumeTargetStackIfNeeded() {
2489 if (mDoResume) {
Louis Chang149d5c82019-12-30 09:47:39 +08002490 mRootWindowContainer.resumeFocusedStacksTopActivities(mTargetStack, null, mOptions);
Wale Ogunwale01d66562015-12-29 08:19:19 -08002491 } else {
2492 ActivityOptions.abort(mOptions);
2493 }
Louis Chang149d5c82019-12-30 09:47:39 +08002494 mRootWindowContainer.updateUserStack(mStartActivity.mUserId, mTargetStack);
Wale Ogunwale01d66562015-12-29 08:19:19 -08002495 }
2496
Louis Changcdec0802019-11-11 11:45:07 +08002497 private void setNewTask(Task taskToAffiliate) {
Louis Changbde91e92019-08-16 17:19:47 +08002498 final boolean toTop = !mLaunchTaskBehind && !mAvoidMoveToFront;
Wale Ogunwale0d465192020-01-23 19:14:44 -08002499 final Task task = mTargetStack.reuseOrCreateTask(
Louis Changbde91e92019-08-16 17:19:47 +08002500 mNewTaskInfo != null ? mNewTaskInfo : mStartActivity.info,
2501 mNewTaskIntent != null ? mNewTaskIntent : mIntent, mVoiceSession,
2502 mVoiceInteractor, toTop, mStartActivity, mSourceRecord, mOptions);
2503 addOrReparentStartingActivity(task, "setTaskFromReuseOrCreateNewTask - mReuseTask");
Louis Change8902452019-06-10 10:49:28 +08002504
Louis Changbde91e92019-08-16 17:19:47 +08002505 if (DEBUG_TASKS) {
2506 Slog.v(TAG_TASKS, "Starting new activity " + mStartActivity
Louis Changcdec0802019-11-11 11:45:07 +08002507 + " in new task " + mStartActivity.getTask());
Wale Ogunwalea0cd15e2017-02-01 15:33:08 -08002508 }
2509
2510 if (taskToAffiliate != null) {
2511 mStartActivity.setTaskToAffiliateWith(taskToAffiliate);
Wale Ogunwale01d66562015-12-29 08:19:19 -08002512 }
2513 }
2514
Bryce Lee325e09682017-10-05 17:20:25 -07002515 private void deliverNewIntent(ActivityRecord activity) {
2516 if (mIntentDelivered) {
2517 return;
2518 }
2519
Jeff Changd136e772019-11-05 20:33:52 +08002520 activity.logStartActivity(EventLogTags.WM_NEW_INTENT, activity.getTask());
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002521 activity.deliverNewIntentLocked(mCallingUid, mStartActivity.intent,
Bryce Lee325e09682017-10-05 17:20:25 -07002522 mStartActivity.launchedFromPackage);
2523 mIntentDelivered = true;
2524 }
2525
Louis Changcdec0802019-11-11 11:45:07 +08002526 private void addOrReparentStartingActivity(Task parent, String reason) {
2527 if (mStartActivity.getTask() == null || mStartActivity.getTask() == parent) {
Wale Ogunwalec17418e2019-10-13 23:00:40 +02002528 parent.addChild(mStartActivity);
Wale Ogunwalea0cd15e2017-02-01 15:33:08 -08002529 } else {
Wale Ogunwale1a06f152019-10-11 11:26:30 +02002530 mStartActivity.reparent(parent, parent.getChildCount() /* top */, reason);
Wale Ogunwalea0cd15e2017-02-01 15:33:08 -08002531 }
Wale Ogunwale01d66562015-12-29 08:19:19 -08002532 }
2533
2534 private int adjustLaunchFlagsToDocumentMode(ActivityRecord r, boolean launchSingleInstance,
2535 boolean launchSingleTask, int launchFlags) {
2536 if ((launchFlags & Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0 &&
2537 (launchSingleInstance || launchSingleTask)) {
2538 // We have a conflict between the Intent and the Activity manifest, manifest wins.
2539 Slog.i(TAG, "Ignoring FLAG_ACTIVITY_NEW_DOCUMENT, launchMode is " +
2540 "\"singleInstance\" or \"singleTask\"");
2541 launchFlags &=
2542 ~(Intent.FLAG_ACTIVITY_NEW_DOCUMENT | FLAG_ACTIVITY_MULTIPLE_TASK);
2543 } else {
2544 switch (r.info.documentLaunchMode) {
2545 case ActivityInfo.DOCUMENT_LAUNCH_NONE:
2546 break;
2547 case ActivityInfo.DOCUMENT_LAUNCH_INTO_EXISTING:
2548 launchFlags |= Intent.FLAG_ACTIVITY_NEW_DOCUMENT;
2549 break;
2550 case ActivityInfo.DOCUMENT_LAUNCH_ALWAYS:
2551 launchFlags |= Intent.FLAG_ACTIVITY_NEW_DOCUMENT;
2552 break;
2553 case ActivityInfo.DOCUMENT_LAUNCH_NEVER:
2554 launchFlags &= ~FLAG_ACTIVITY_MULTIPLE_TASK;
2555 break;
2556 }
2557 }
2558 return launchFlags;
Filip Gruszczynski07a0e492015-12-17 14:16:38 -08002559 }
2560
Louis Changcdec0802019-11-11 11:45:07 +08002561 private ActivityStack getLaunchStack(ActivityRecord r, int launchFlags, Task task,
Jorim Jaggi4ad98562016-04-19 20:30:47 -07002562 ActivityOptions aOptions) {
Bryce Leea19b5ad2017-06-07 16:54:11 -07002563 // We are reusing a task, keep the stack!
2564 if (mReuseTask != null) {
2565 return mReuseTask.getStack();
2566 }
Jorim Jaggib8c58762016-04-20 17:58:29 -07002567
Louis Chang38430df2020-01-02 17:14:59 +08002568 final boolean onTop =
2569 (aOptions == null || !aOptions.getAvoidMoveToFront()) && !mLaunchTaskBehind;
2570 return mRootWindowContainer.getLaunchStack(r, aOptions, task, onTop, mLaunchParams,
2571 mRequest.realCallingPid, mRequest.realCallingUid);
Filip Gruszczynski07a0e492015-12-17 14:16:38 -08002572 }
2573
Bryce Lee7daee392017-10-12 13:46:18 -07002574 private boolean isLaunchModeOneOf(int mode1, int mode2) {
2575 return mode1 == mLaunchMode || mode2 == mLaunchMode;
Filip Gruszczynski07a0e492015-12-17 14:16:38 -08002576 }
2577
Daichi Hirono15a02992016-04-27 18:47:01 +09002578 static boolean isDocumentLaunchesIntoExisting(int flags) {
2579 return (flags & Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0 &&
2580 (flags & Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0;
2581 }
liulvpingcfa825f2016-09-26 20:00:15 +08002582
Bryce Lee4c9a5972017-12-01 22:14:24 -08002583 ActivityStarter setIntent(Intent intent) {
2584 mRequest.intent = intent;
2585 return this;
2586 }
2587
Bryce Lee32e09ef2018-03-19 15:29:49 -07002588 Intent getIntent() {
2589 return mRequest.intent;
2590 }
2591
Bryce Lee4c9a5972017-12-01 22:14:24 -08002592 ActivityStarter setReason(String reason) {
2593 mRequest.reason = reason;
2594 return this;
2595 }
2596
2597 ActivityStarter setCaller(IApplicationThread caller) {
2598 mRequest.caller = caller;
2599 return this;
2600 }
2601
Bryce Lee4c9a5972017-12-01 22:14:24 -08002602 ActivityStarter setResolvedType(String type) {
2603 mRequest.resolvedType = type;
2604 return this;
2605 }
2606
2607 ActivityStarter setActivityInfo(ActivityInfo info) {
2608 mRequest.activityInfo = info;
2609 return this;
2610 }
2611
2612 ActivityStarter setResolveInfo(ResolveInfo info) {
2613 mRequest.resolveInfo = info;
2614 return this;
2615 }
2616
2617 ActivityStarter setVoiceSession(IVoiceInteractionSession voiceSession) {
2618 mRequest.voiceSession = voiceSession;
2619 return this;
2620 }
2621
2622 ActivityStarter setVoiceInteractor(IVoiceInteractor voiceInteractor) {
2623 mRequest.voiceInteractor = voiceInteractor;
2624 return this;
2625 }
2626
2627 ActivityStarter setResultTo(IBinder resultTo) {
2628 mRequest.resultTo = resultTo;
2629 return this;
2630 }
2631
2632 ActivityStarter setResultWho(String resultWho) {
2633 mRequest.resultWho = resultWho;
2634 return this;
2635 }
2636
2637 ActivityStarter setRequestCode(int requestCode) {
2638 mRequest.requestCode = requestCode;
2639 return this;
2640 }
2641
lumarkf65e02d2019-09-14 19:25:21 +08002642 /**
2643 * Sets the pid of the caller who originally started the activity.
2644 *
2645 * Normally, the pid/uid would be the calling pid from the binder call.
2646 * However, in case of a {@link PendingIntent}, the pid/uid pair of the caller is considered
2647 * the original entity that created the pending intent, in contrast to setRealCallingPid/Uid,
2648 * which represents the entity who invoked pending intent via {@link PendingIntent#send}.
2649 */
Bryce Lee4c9a5972017-12-01 22:14:24 -08002650 ActivityStarter setCallingPid(int pid) {
2651 mRequest.callingPid = pid;
2652 return this;
2653 }
2654
lumarkf65e02d2019-09-14 19:25:21 +08002655 /**
2656 * Sets the uid of the caller who originally started the activity.
2657 *
2658 * @see #setCallingPid
2659 */
Bryce Lee4c9a5972017-12-01 22:14:24 -08002660 ActivityStarter setCallingUid(int uid) {
2661 mRequest.callingUid = uid;
2662 return this;
2663 }
2664
2665 ActivityStarter setCallingPackage(String callingPackage) {
2666 mRequest.callingPackage = callingPackage;
2667 return this;
2668 }
2669
Philip P. Moltmannee295092020-02-10 08:46:26 -08002670 ActivityStarter setCallingFeatureId(String callingFeatureId) {
2671 mRequest.callingFeatureId = callingFeatureId;
2672 return this;
2673 }
2674
lumarkf65e02d2019-09-14 19:25:21 +08002675 /**
2676 * Sets the pid of the caller who requested to launch the activity.
2677 *
2678 * The pid/uid represents the caller who launches the activity in this request.
2679 * It will almost same as setCallingPid/Uid except when processing {@link PendingIntent}:
2680 * the pid/uid will be the caller who called {@link PendingIntent#send()}.
2681 *
2682 * @see #setCallingPid
2683 */
Bryce Lee4c9a5972017-12-01 22:14:24 -08002684 ActivityStarter setRealCallingPid(int pid) {
2685 mRequest.realCallingPid = pid;
2686 return this;
2687 }
2688
lumarkf65e02d2019-09-14 19:25:21 +08002689 /**
2690 * Sets the uid of the caller who requested to launch the activity.
2691 *
2692 * @see #setRealCallingPid
2693 */
Bryce Lee4c9a5972017-12-01 22:14:24 -08002694 ActivityStarter setRealCallingUid(int uid) {
2695 mRequest.realCallingUid = uid;
2696 return this;
2697 }
2698
2699 ActivityStarter setStartFlags(int startFlags) {
2700 mRequest.startFlags = startFlags;
2701 return this;
2702 }
2703
Jorim Jaggi4d8d32c2018-01-19 15:57:41 +01002704 ActivityStarter setActivityOptions(SafeActivityOptions options) {
Bryce Lee4c9a5972017-12-01 22:14:24 -08002705 mRequest.activityOptions = options;
2706 return this;
2707 }
2708
Jorim Jaggi4d8d32c2018-01-19 15:57:41 +01002709 ActivityStarter setActivityOptions(Bundle bOptions) {
2710 return setActivityOptions(SafeActivityOptions.fromBundle(bOptions));
2711 }
2712
Bryce Lee4c9a5972017-12-01 22:14:24 -08002713 ActivityStarter setIgnoreTargetSecurity(boolean ignoreTargetSecurity) {
2714 mRequest.ignoreTargetSecurity = ignoreTargetSecurity;
2715 return this;
2716 }
2717
Patrick Baumann31426b22018-05-21 13:46:40 -07002718 ActivityStarter setFilterCallingUid(int filterCallingUid) {
2719 mRequest.filterCallingUid = filterCallingUid;
2720 return this;
2721 }
2722
Bryce Lee4c9a5972017-12-01 22:14:24 -08002723 ActivityStarter setComponentSpecified(boolean componentSpecified) {
2724 mRequest.componentSpecified = componentSpecified;
2725 return this;
2726 }
2727
2728 ActivityStarter setOutActivity(ActivityRecord[] outActivity) {
2729 mRequest.outActivity = outActivity;
2730 return this;
2731 }
2732
Louis Changcdec0802019-11-11 11:45:07 +08002733 ActivityStarter setInTask(Task inTask) {
Bryce Lee4c9a5972017-12-01 22:14:24 -08002734 mRequest.inTask = inTask;
2735 return this;
2736 }
2737
2738 ActivityStarter setWaitResult(WaitResult result) {
2739 mRequest.waitResult = result;
2740 return this;
2741 }
2742
2743 ActivityStarter setProfilerInfo(ProfilerInfo info) {
2744 mRequest.profilerInfo = info;
2745 return this;
2746 }
2747
2748 ActivityStarter setGlobalConfiguration(Configuration config) {
2749 mRequest.globalConfig = config;
2750 return this;
2751 }
2752
Bryce Lee4c9a5972017-12-01 22:14:24 -08002753 ActivityStarter setUserId(int userId) {
2754 mRequest.userId = userId;
2755 return this;
2756 }
2757
Jorim Jaggi6fa41c32018-04-23 18:35:00 +02002758 ActivityStarter setAllowPendingRemoteAnimationRegistryLookup(boolean allowLookup) {
2759 mRequest.allowPendingRemoteAnimationRegistryLookup = allowLookup;
2760 return this;
2761 }
2762
Michal Karpinski201bc0c2018-07-20 15:32:00 +01002763 ActivityStarter setOriginatingPendingIntent(PendingIntentRecord originatingPendingIntent) {
2764 mRequest.originatingPendingIntent = originatingPendingIntent;
2765 return this;
2766 }
2767
Michal Karpinskiac116df2018-12-10 17:51:42 +00002768 ActivityStarter setAllowBackgroundActivityStart(boolean allowBackgroundActivityStart) {
2769 mRequest.allowBackgroundActivityStart = allowBackgroundActivityStart;
2770 return this;
2771 }
2772
Bryce Leed3624e12017-11-30 08:51:45 -08002773 void dump(PrintWriter pw, String prefix) {
Wale Ogunwale692dcd62017-06-20 13:38:14 -07002774 prefix = prefix + " ";
Dianne Hackborne676ec72017-07-25 10:55:08 -07002775 pw.print(prefix);
2776 pw.print("mCurrentUser=");
Louis Chang149d5c82019-12-30 09:47:39 +08002777 pw.println(mRootWindowContainer.mCurrentUser);
Dianne Hackborne676ec72017-07-25 10:55:08 -07002778 pw.print(prefix);
2779 pw.print("mLastStartReason=");
2780 pw.println(mLastStartReason);
2781 pw.print(prefix);
2782 pw.print("mLastStartActivityTimeMs=");
2783 pw.println(DateFormat.getDateTimeInstance().format(new Date(mLastStartActivityTimeMs)));
2784 pw.print(prefix);
2785 pw.print("mLastStartActivityResult=");
2786 pw.println(mLastStartActivityResult);
Louis Chang54fbb052019-10-16 17:10:17 +08002787 if (mLastStartActivityRecord != null) {
Dianne Hackborne676ec72017-07-25 10:55:08 -07002788 pw.print(prefix);
2789 pw.println("mLastStartActivityRecord:");
Louis Chang54fbb052019-10-16 17:10:17 +08002790 mLastStartActivityRecord.dump(pw, prefix + " ", true /* dumpAll */);
Wale Ogunwale692dcd62017-06-20 13:38:14 -07002791 }
Wale Ogunwale692dcd62017-06-20 13:38:14 -07002792 if (mStartActivity != null) {
Dianne Hackborne676ec72017-07-25 10:55:08 -07002793 pw.print(prefix);
2794 pw.println("mStartActivity:");
Garfield Tane8d84ab2019-10-11 09:49:40 -07002795 mStartActivity.dump(pw, prefix + " ", true /* dumpAll */);
Wale Ogunwale692dcd62017-06-20 13:38:14 -07002796 }
2797 if (mIntent != null) {
Dianne Hackborne676ec72017-07-25 10:55:08 -07002798 pw.print(prefix);
2799 pw.print("mIntent=");
2800 pw.println(mIntent);
Wale Ogunwale692dcd62017-06-20 13:38:14 -07002801 }
2802 if (mOptions != null) {
Dianne Hackborne676ec72017-07-25 10:55:08 -07002803 pw.print(prefix);
2804 pw.print("mOptions=");
2805 pw.println(mOptions);
Wale Ogunwale692dcd62017-06-20 13:38:14 -07002806 }
Dianne Hackborne676ec72017-07-25 10:55:08 -07002807 pw.print(prefix);
2808 pw.print("mLaunchSingleTop=");
Bryce Lee7daee392017-10-12 13:46:18 -07002809 pw.print(LAUNCH_SINGLE_TOP == mLaunchMode);
Dianne Hackborne676ec72017-07-25 10:55:08 -07002810 pw.print(" mLaunchSingleInstance=");
Bryce Lee7daee392017-10-12 13:46:18 -07002811 pw.print(LAUNCH_SINGLE_INSTANCE == mLaunchMode);
Dianne Hackborne676ec72017-07-25 10:55:08 -07002812 pw.print(" mLaunchSingleTask=");
Bryce Lee7daee392017-10-12 13:46:18 -07002813 pw.println(LAUNCH_SINGLE_TASK == mLaunchMode);
Dianne Hackborne676ec72017-07-25 10:55:08 -07002814 pw.print(prefix);
2815 pw.print("mLaunchFlags=0x");
2816 pw.print(Integer.toHexString(mLaunchFlags));
2817 pw.print(" mDoResume=");
2818 pw.print(mDoResume);
2819 pw.print(" mAddingToTask=");
2820 pw.println(mAddingToTask);
Wale Ogunwale692dcd62017-06-20 13:38:14 -07002821 }
Filip Gruszczynski07a0e492015-12-17 14:16:38 -08002822}