1 /* 2 * Copyright (C) 2013 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 17 package com.android.server.wm; 18 19 import static android.Manifest.permission.ACTIVITY_EMBEDDING; 20 import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW; 21 import static android.Manifest.permission.START_ANY_ACTIVITY; 22 import static android.app.ActivityManager.LOCK_TASK_MODE_LOCKED; 23 import static android.app.ActivityManager.START_DELIVERED_TO_TOP; 24 import static android.app.ActivityManager.START_FLAG_DEBUG; 25 import static android.app.ActivityManager.START_FLAG_NATIVE_DEBUGGING; 26 import static android.app.ActivityManager.START_FLAG_TRACK_ALLOCATION; 27 import static android.app.ActivityManager.START_TASK_TO_FRONT; 28 import static android.app.ITaskStackListener.FORCED_RESIZEABLE_REASON_SECONDARY_DISPLAY; 29 import static android.app.ITaskStackListener.FORCED_RESIZEABLE_REASON_SPLIT_SCREEN; 30 import static android.app.WaitResult.INVALID_DELAY; 31 import static android.app.WindowConfiguration.ACTIVITY_TYPE_HOME; 32 import static android.app.WindowConfiguration.ACTIVITY_TYPE_RECENTS; 33 import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED; 34 import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM; 35 import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN; 36 import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED; 37 import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY; 38 import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY; 39 import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED; 40 import static android.content.pm.PackageManager.NOTIFY_PACKAGE_USE_ACTIVITY; 41 import static android.content.pm.PackageManager.PERMISSION_DENIED; 42 import static android.content.pm.PackageManager.PERMISSION_GRANTED; 43 import static android.graphics.Rect.copyOrNull; 44 import static android.os.PowerManager.PARTIAL_WAKE_LOCK; 45 import static android.os.Process.SYSTEM_UID; 46 import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER; 47 import static android.view.Display.DEFAULT_DISPLAY; 48 import static android.view.Display.INVALID_DISPLAY; 49 import static android.view.Display.TYPE_VIRTUAL; 50 import static android.view.WindowManager.TRANSIT_DOCK_TASK_FROM_RECENTS; 51 52 import static com.android.server.wm.ActivityStack.ActivityState.PAUSED; 53 import static com.android.server.wm.ActivityStack.ActivityState.PAUSING; 54 import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_MOVING; 55 import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL; 56 import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IDLE; 57 import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_PAUSE; 58 import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_RECENTS; 59 import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK; 60 import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STATES; 61 import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH; 62 import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS; 63 import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IDLE; 64 import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_PAUSE; 65 import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_RECENTS; 66 import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK; 67 import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH; 68 import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_TASKS; 69 import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM; 70 import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME; 71 import static com.android.server.wm.ActivityTaskManagerService.ANIMATE; 72 import static com.android.server.wm.ActivityTaskManagerService.H.FIRST_SUPERVISOR_STACK_MSG; 73 import static com.android.server.wm.ActivityTaskManagerService.RELAUNCH_REASON_NONE; 74 import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_ONLY; 75 import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS; 76 import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE; 77 import static com.android.server.wm.RootActivityContainer.TAG_STATES; 78 import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_LAUNCHABLE; 79 import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_LAUNCHABLE_PRIV; 80 import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_WHITELISTED; 81 import static com.android.server.wm.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT; 82 import static com.android.server.wm.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE; 83 import static com.android.server.wm.TaskRecord.REPARENT_MOVE_STACK_TO_FRONT; 84 85 import android.Manifest; 86 import android.app.Activity; 87 import android.app.ActivityManager; 88 import android.app.ActivityManagerInternal; 89 import android.app.ActivityOptions; 90 import android.app.AppOpsManager; 91 import android.app.ProfilerInfo; 92 import android.app.ResultInfo; 93 import android.app.WaitResult; 94 import android.app.servertransaction.ActivityLifecycleItem; 95 import android.app.servertransaction.ClientTransaction; 96 import android.app.servertransaction.LaunchActivityItem; 97 import android.app.servertransaction.PauseActivityItem; 98 import android.app.servertransaction.ResumeActivityItem; 99 import android.content.ComponentName; 100 import android.content.Intent; 101 import android.content.pm.ActivityInfo; 102 import android.content.pm.ApplicationInfo; 103 import android.content.pm.PackageInfo; 104 import android.content.pm.PackageManager; 105 import android.content.pm.ResolveInfo; 106 import android.content.pm.UserInfo; 107 import android.content.res.Configuration; 108 import android.graphics.Rect; 109 import android.os.Binder; 110 import android.os.Bundle; 111 import android.os.Debug; 112 import android.os.Handler; 113 import android.os.IBinder; 114 import android.os.Looper; 115 import android.os.Message; 116 import android.os.PowerManager; 117 import android.os.Process; 118 import android.os.RemoteException; 119 import android.os.SystemClock; 120 import android.os.Trace; 121 import android.os.UserHandle; 122 import android.os.UserManager; 123 import android.os.WorkSource; 124 import android.provider.MediaStore; 125 import android.util.ArrayMap; 126 import android.util.ArraySet; 127 import android.util.EventLog; 128 import android.util.MergedConfiguration; 129 import android.util.Slog; 130 import android.util.SparseArray; 131 import android.util.SparseIntArray; 132 133 import com.android.internal.annotations.GuardedBy; 134 import com.android.internal.annotations.VisibleForTesting; 135 import com.android.internal.content.ReferrerIntent; 136 import com.android.internal.os.TransferPipe; 137 import com.android.internal.os.logging.MetricsLoggerWrapper; 138 import com.android.internal.util.ArrayUtils; 139 import com.android.internal.util.function.pooled.PooledLambda; 140 import com.android.server.am.ActivityManagerService; 141 import com.android.server.am.EventLogTags; 142 import com.android.server.am.UserState; 143 144 import java.io.FileDescriptor; 145 import java.io.IOException; 146 import java.io.PrintWriter; 147 import java.util.ArrayList; 148 import java.util.List; 149 150 // TODO: This class has become a dumping ground. Let's 151 // - Move things relating to the hierarchy to RootWindowContainer 152 // - Move things relating to activity life cycles to maybe a new class called ActivityLifeCycler 153 // - Move interface things to ActivityTaskManagerService. 154 // - All other little things to other files. 155 public class ActivityStackSupervisor implements RecentTasks.Callbacks { 156 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityStackSupervisor" : TAG_ATM; 157 private static final String TAG_IDLE = TAG + POSTFIX_IDLE; 158 private static final String TAG_PAUSE = TAG + POSTFIX_PAUSE; 159 private static final String TAG_RECENTS = TAG + POSTFIX_RECENTS; 160 private static final String TAG_STACK = TAG + POSTFIX_STACK; 161 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH; 162 static final String TAG_TASKS = TAG + POSTFIX_TASKS; 163 164 /** How long we wait until giving up on the last activity telling us it is idle. */ 165 static final int IDLE_TIMEOUT = 10 * 1000; 166 167 /** How long we can hold the sleep wake lock before giving up. */ 168 static final int SLEEP_TIMEOUT = 5 * 1000; 169 170 // How long we can hold the launch wake lock before giving up. 171 static final int LAUNCH_TIMEOUT = 10 * 1000; 172 173 /** How long we wait until giving up on the activity telling us it released the top state. */ 174 static final int TOP_RESUMED_STATE_LOSS_TIMEOUT = 500; 175 176 static final int IDLE_TIMEOUT_MSG = FIRST_SUPERVISOR_STACK_MSG; 177 static final int IDLE_NOW_MSG = FIRST_SUPERVISOR_STACK_MSG + 1; 178 static final int RESUME_TOP_ACTIVITY_MSG = FIRST_SUPERVISOR_STACK_MSG + 2; 179 static final int SLEEP_TIMEOUT_MSG = FIRST_SUPERVISOR_STACK_MSG + 3; 180 static final int LAUNCH_TIMEOUT_MSG = FIRST_SUPERVISOR_STACK_MSG + 4; 181 static final int LAUNCH_TASK_BEHIND_COMPLETE = FIRST_SUPERVISOR_STACK_MSG + 12; 182 static final int RESTART_ACTIVITY_PROCESS_TIMEOUT_MSG = FIRST_SUPERVISOR_STACK_MSG + 13; 183 static final int REPORT_MULTI_WINDOW_MODE_CHANGED_MSG = FIRST_SUPERVISOR_STACK_MSG + 14; 184 static final int REPORT_PIP_MODE_CHANGED_MSG = FIRST_SUPERVISOR_STACK_MSG + 15; 185 static final int REPORT_HOME_CHANGED_MSG = FIRST_SUPERVISOR_STACK_MSG + 16; 186 static final int TOP_RESUMED_STATE_LOSS_TIMEOUT_MSG = FIRST_SUPERVISOR_STACK_MSG + 17; 187 188 // Used to indicate that windows of activities should be preserved during the resize. 189 static final boolean PRESERVE_WINDOWS = true; 190 191 // Used to indicate if an object (e.g. task) should be moved/created 192 // at the top of its container (e.g. stack). 193 static final boolean ON_TOP = true; 194 195 // Don't execute any calls to resume. 196 static final boolean DEFER_RESUME = true; 197 198 // Used to indicate that a task is removed it should also be removed from recents. 199 static final boolean REMOVE_FROM_RECENTS = true; 200 201 // Used to indicate that pausing an activity should occur immediately without waiting for 202 // the activity callback indicating that it has completed pausing 203 static final boolean PAUSE_IMMEDIATELY = true; 204 205 /** True if the docked stack is currently being resized. */ 206 private boolean mDockedStackResizing; 207 208 /** 209 * True if there are pending docked bounds that need to be applied after 210 * {@link #mDockedStackResizing} is reset to false. 211 */ 212 private boolean mHasPendingDockedBounds; 213 private Rect mPendingDockedBounds; 214 private Rect mPendingTempDockedTaskBounds; 215 private Rect mPendingTempDockedTaskInsetBounds; 216 private Rect mPendingTempOtherTaskBounds; 217 private Rect mPendingTempOtherTaskInsetBounds; 218 219 // Activity actions an app cannot start if it uses a permission which is not granted. 220 private static final ArrayMap<String, String> ACTION_TO_RUNTIME_PERMISSION = 221 new ArrayMap<>(); 222 223 static { ACTION_TO_RUNTIME_PERMISSION.put(MediaStore.ACTION_IMAGE_CAPTURE, Manifest.permission.CAMERA)224 ACTION_TO_RUNTIME_PERMISSION.put(MediaStore.ACTION_IMAGE_CAPTURE, 225 Manifest.permission.CAMERA); ACTION_TO_RUNTIME_PERMISSION.put(MediaStore.ACTION_VIDEO_CAPTURE, Manifest.permission.CAMERA)226 ACTION_TO_RUNTIME_PERMISSION.put(MediaStore.ACTION_VIDEO_CAPTURE, 227 Manifest.permission.CAMERA); ACTION_TO_RUNTIME_PERMISSION.put(Intent.ACTION_CALL, Manifest.permission.CALL_PHONE)228 ACTION_TO_RUNTIME_PERMISSION.put(Intent.ACTION_CALL, 229 Manifest.permission.CALL_PHONE); 230 } 231 232 /** Action restriction: launching the activity is not restricted. */ 233 private static final int ACTIVITY_RESTRICTION_NONE = 0; 234 /** Action restriction: launching the activity is restricted by a permission. */ 235 private static final int ACTIVITY_RESTRICTION_PERMISSION = 1; 236 /** Action restriction: launching the activity is restricted by an app op. */ 237 private static final int ACTIVITY_RESTRICTION_APPOP = 2; 238 239 // For debugging to make sure the caller when acquiring/releasing our 240 // wake lock is the system process. 241 static final boolean VALIDATE_WAKE_LOCK_CALLER = false; 242 /** The number of distinct task ids that can be assigned to the tasks of a single user */ 243 private static final int MAX_TASK_IDS_PER_USER = UserHandle.PER_USER_RANGE; 244 245 final ActivityTaskManagerService mService; 246 RootActivityContainer mRootActivityContainer; 247 248 /** The historial list of recent tasks including inactive tasks */ 249 RecentTasks mRecentTasks; 250 251 /** Helper class to abstract out logic for fetching the set of currently running tasks */ 252 RunningTasks mRunningTasks; 253 254 final ActivityStackSupervisorHandler mHandler; 255 final Looper mLooper; 256 257 /** Short cut */ 258 WindowManagerService mWindowManager; 259 260 /** Common synchronization logic used to save things to disks. */ 261 PersisterQueue mPersisterQueue; 262 LaunchParamsPersister mLaunchParamsPersister; 263 private LaunchParamsController mLaunchParamsController; 264 265 /** 266 * Maps the task identifier that activities are currently being started in to the userId of the 267 * task. Each time a new task is created, the entry for the userId of the task is incremented 268 */ 269 private final SparseIntArray mCurTaskIdForUser = new SparseIntArray(20); 270 271 /** List of processes waiting to find out when a specific activity becomes visible. */ 272 private final ArrayList<WaitInfo> mWaitingForActivityVisible = new ArrayList<>(); 273 274 /** List of processes waiting to find out about the next launched activity. */ 275 final ArrayList<WaitResult> mWaitingActivityLaunched = new ArrayList<>(); 276 277 /** List of activities that are ready to be stopped, but waiting for the next activity to 278 * settle down before doing so. */ 279 final ArrayList<ActivityRecord> mStoppingActivities = new ArrayList<>(); 280 281 /** List of activities that are ready to be finished, but waiting for the previous activity to 282 * settle down before doing so. It contains ActivityRecord objects. */ 283 final ArrayList<ActivityRecord> mFinishingActivities = new ArrayList<>(); 284 285 /** List of activities that are in the process of going to sleep. */ 286 final ArrayList<ActivityRecord> mGoingToSleepActivities = new ArrayList<>(); 287 288 /** List of activities whose multi-window mode changed that we need to report to the 289 * application */ 290 final ArrayList<ActivityRecord> mMultiWindowModeChangedActivities = new ArrayList<>(); 291 292 /** List of activities whose picture-in-picture mode changed that we need to report to the 293 * application */ 294 final ArrayList<ActivityRecord> mPipModeChangedActivities = new ArrayList<>(); 295 296 /** 297 * Animations that for the current transition have requested not to 298 * be considered for the transition animation. 299 */ 300 final ArrayList<ActivityRecord> mNoAnimActivities = new ArrayList<>(); 301 302 /** 303 * Cached value of the topmost resumed activity in the system. Updated when new activity is 304 * resumed. 305 */ 306 private ActivityRecord mTopResumedActivity; 307 308 /** 309 * Flag indicating whether we're currently waiting for the previous top activity to handle the 310 * loss of the state and report back before making new activity top resumed. 311 */ 312 private boolean mTopResumedActivityWaitingForPrev; 313 314 /** The target stack bounds for the picture-in-picture mode changed that we need to report to 315 * the application */ 316 Rect mPipModeChangedTargetStackBounds; 317 318 /** Used on user changes */ 319 final ArrayList<UserState> mStartingUsers = new ArrayList<>(); 320 321 /** Set to indicate whether to issue an onUserLeaving callback when a newly launched activity 322 * is being brought in front of us. */ 323 boolean mUserLeaving = false; 324 325 /** 326 * We don't want to allow the device to go to sleep while in the process 327 * of launching an activity. This is primarily to allow alarm intent 328 * receivers to launch an activity and get that to run before the device 329 * goes back to sleep. 330 */ 331 PowerManager.WakeLock mLaunchingActivityWakeLock; 332 333 /** 334 * Set when the system is going to sleep, until we have 335 * successfully paused the current activity and released our wake lock. 336 * At that point the system is allowed to actually sleep. 337 */ 338 PowerManager.WakeLock mGoingToSleepWakeLock; 339 340 /** 341 * Temporary rect used during docked stack resize calculation so we don't need to create a new 342 * object each time. 343 */ 344 private final Rect tempRect = new Rect(); 345 private final ActivityOptions mTmpOptions = ActivityOptions.makeBasic(); 346 347 private ActivityMetricsLogger mActivityMetricsLogger; 348 349 /** Check if placing task or activity on specified display is allowed. */ canPlaceEntityOnDisplay(int displayId, int callingPid, int callingUid, ActivityInfo activityInfo)350 boolean canPlaceEntityOnDisplay(int displayId, int callingPid, int callingUid, 351 ActivityInfo activityInfo) { 352 if (displayId == DEFAULT_DISPLAY) { 353 // No restrictions for the default display. 354 return true; 355 } 356 if (!mService.mSupportsMultiDisplay) { 357 // Can't launch on secondary displays if feature is not supported. 358 return false; 359 } 360 if (!isCallerAllowedToLaunchOnDisplay(callingPid, callingUid, displayId, activityInfo)) { 361 // Can't place activities to a display that has restricted launch rules. 362 // In this case the request should be made by explicitly adding target display id and 363 // by caller with corresponding permissions. See #isCallerAllowedToLaunchOnDisplay(). 364 return false; 365 } 366 return true; 367 } 368 369 /** 370 * Used to keep track whether app visibilities got changed since the last pause. Useful to 371 * determine whether to invoke the task stack change listener after pausing. 372 */ 373 boolean mAppVisibilitiesChangedSinceLastPause; 374 375 /** 376 * Set of tasks that are in resizing mode during an app transition to fill the "void". 377 */ 378 private final ArraySet<Integer> mResizingTasksDuringAnimation = new ArraySet<>(); 379 380 381 /** 382 * If set to {@code false} all calls to resize the docked stack {@link #resizeDockedStackLocked} 383 * will be ignored. Useful for the case where the caller is handling resizing of other stack and 384 * moving tasks around and doesn't want dock stack to be resized due to an automatic trigger 385 * like the docked stack going empty. 386 */ 387 private boolean mAllowDockedStackResize = true; 388 389 private KeyguardController mKeyguardController; 390 391 private PowerManager mPowerManager; 392 private int mDeferResumeCount; 393 394 private boolean mInitialized; 395 396 /** 397 * Description of a request to start a new activity, which has been held 398 * due to app switches being disabled. 399 */ 400 static class PendingActivityLaunch { 401 final ActivityRecord r; 402 final ActivityRecord sourceRecord; 403 final int startFlags; 404 final ActivityStack stack; 405 final WindowProcessController callerApp; 406 PendingActivityLaunch(ActivityRecord _r, ActivityRecord _sourceRecord, int _startFlags, ActivityStack _stack, WindowProcessController app)407 PendingActivityLaunch(ActivityRecord _r, ActivityRecord _sourceRecord, 408 int _startFlags, ActivityStack _stack, WindowProcessController app) { 409 r = _r; 410 sourceRecord = _sourceRecord; 411 startFlags = _startFlags; 412 stack = _stack; 413 callerApp = app; 414 } 415 sendErrorResult(String message)416 void sendErrorResult(String message) { 417 try { 418 if (callerApp != null && callerApp.hasThread()) { 419 callerApp.getThread().scheduleCrash(message); 420 } 421 } catch (RemoteException e) { 422 Slog.e(TAG, "Exception scheduling crash of failed " 423 + "activity launcher sourceRecord=" + sourceRecord, e); 424 } 425 } 426 } 427 ActivityStackSupervisor(ActivityTaskManagerService service, Looper looper)428 public ActivityStackSupervisor(ActivityTaskManagerService service, Looper looper) { 429 mService = service; 430 mLooper = looper; 431 mHandler = new ActivityStackSupervisorHandler(looper); 432 } 433 initialize()434 public void initialize() { 435 if (mInitialized) { 436 return; 437 } 438 439 mInitialized = true; 440 mRunningTasks = createRunningTasks(); 441 442 mActivityMetricsLogger = new ActivityMetricsLogger(this, mService.mContext, 443 mHandler.getLooper()); 444 mKeyguardController = new KeyguardController(mService, this); 445 446 mPersisterQueue = new PersisterQueue(); 447 mLaunchParamsPersister = new LaunchParamsPersister(mPersisterQueue, this); 448 mLaunchParamsController = new LaunchParamsController(mService, mLaunchParamsPersister); 449 mLaunchParamsController.registerDefaultModifiers(this); 450 } 451 onSystemReady()452 void onSystemReady() { 453 mLaunchParamsPersister.onSystemReady(); 454 } 455 onUserUnlocked(int userId)456 void onUserUnlocked(int userId) { 457 // Only start persisting when the first user is unlocked. The method call is 458 // idempotent so there is no side effect to call it again when the second user is 459 // unlocked. 460 mPersisterQueue.startPersisting(); 461 mLaunchParamsPersister.onUnlockUser(userId); 462 } 463 getActivityMetricsLogger()464 public ActivityMetricsLogger getActivityMetricsLogger() { 465 return mActivityMetricsLogger; 466 } 467 getKeyguardController()468 public KeyguardController getKeyguardController() { 469 return mKeyguardController; 470 } 471 setRecentTasks(RecentTasks recentTasks)472 void setRecentTasks(RecentTasks recentTasks) { 473 mRecentTasks = recentTasks; 474 mRecentTasks.registerCallback(this); 475 } 476 477 @VisibleForTesting createRunningTasks()478 RunningTasks createRunningTasks() { 479 return new RunningTasks(); 480 } 481 482 /** 483 * At the time when the constructor runs, the power manager has not yet been 484 * initialized. So we initialize our wakelocks afterwards. 485 */ initPowerManagement()486 void initPowerManagement() { 487 mPowerManager = mService.mContext.getSystemService(PowerManager.class); 488 mGoingToSleepWakeLock = mPowerManager 489 .newWakeLock(PARTIAL_WAKE_LOCK, "ActivityManager-Sleep"); 490 mLaunchingActivityWakeLock = mPowerManager.newWakeLock(PARTIAL_WAKE_LOCK, "*launch*"); 491 mLaunchingActivityWakeLock.setReferenceCounted(false); 492 } 493 setWindowManager(WindowManagerService wm)494 void setWindowManager(WindowManagerService wm) { 495 mWindowManager = wm; 496 getKeyguardController().setWindowManager(wm); 497 } 498 moveRecentsStackToFront(String reason)499 void moveRecentsStackToFront(String reason) { 500 final ActivityStack recentsStack = mRootActivityContainer.getDefaultDisplay().getStack( 501 WINDOWING_MODE_UNDEFINED, ACTIVITY_TYPE_RECENTS); 502 if (recentsStack != null) { 503 recentsStack.moveToFront(reason); 504 } 505 } 506 setNextTaskIdForUserLocked(int taskId, int userId)507 void setNextTaskIdForUserLocked(int taskId, int userId) { 508 final int currentTaskId = mCurTaskIdForUser.get(userId, -1); 509 if (taskId > currentTaskId) { 510 mCurTaskIdForUser.put(userId, taskId); 511 } 512 } 513 nextTaskIdForUser(int taskId, int userId)514 static int nextTaskIdForUser(int taskId, int userId) { 515 int nextTaskId = taskId + 1; 516 if (nextTaskId == (userId + 1) * MAX_TASK_IDS_PER_USER) { 517 // Wrap around as there will be smaller task ids that are available now. 518 nextTaskId -= MAX_TASK_IDS_PER_USER; 519 } 520 return nextTaskId; 521 } 522 getNextTaskIdForUserLocked(int userId)523 int getNextTaskIdForUserLocked(int userId) { 524 final int currentTaskId = mCurTaskIdForUser.get(userId, userId * MAX_TASK_IDS_PER_USER); 525 // for a userId u, a taskId can only be in the range 526 // [u*MAX_TASK_IDS_PER_USER, (u+1)*MAX_TASK_IDS_PER_USER-1], so if MAX_TASK_IDS_PER_USER 527 // was 10, user 0 could only have taskIds 0 to 9, user 1: 10 to 19, user 2: 20 to 29, so on. 528 int candidateTaskId = nextTaskIdForUser(currentTaskId, userId); 529 while (mRecentTasks.containsTaskId(candidateTaskId, userId) 530 || mRootActivityContainer.anyTaskForId( 531 candidateTaskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS) != null) { 532 candidateTaskId = nextTaskIdForUser(candidateTaskId, userId); 533 if (candidateTaskId == currentTaskId) { 534 // Something wrong! 535 // All MAX_TASK_IDS_PER_USER task ids are taken up by running tasks for this user 536 throw new IllegalStateException("Cannot get an available task id." 537 + " Reached limit of " + MAX_TASK_IDS_PER_USER 538 + " running tasks per user."); 539 } 540 } 541 mCurTaskIdForUser.put(userId, candidateTaskId); 542 return candidateTaskId; 543 } 544 waitActivityVisible(ComponentName name, WaitResult result, long startTimeMs)545 void waitActivityVisible(ComponentName name, WaitResult result, long startTimeMs) { 546 final WaitInfo waitInfo = new WaitInfo(name, result, startTimeMs); 547 mWaitingForActivityVisible.add(waitInfo); 548 } 549 cleanupActivity(ActivityRecord r)550 void cleanupActivity(ActivityRecord r) { 551 // Make sure this record is no longer in the pending finishes list. 552 // This could happen, for example, if we are trimming activities 553 // down to the max limit while they are still waiting to finish. 554 mFinishingActivities.remove(r); 555 556 stopWaitingForActivityVisible(r); 557 } 558 stopWaitingForActivityVisible(ActivityRecord r)559 void stopWaitingForActivityVisible(ActivityRecord r) { 560 boolean changed = false; 561 for (int i = mWaitingForActivityVisible.size() - 1; i >= 0; --i) { 562 final WaitInfo w = mWaitingForActivityVisible.get(i); 563 if (w.matches(r.mActivityComponent)) { 564 final WaitResult result = w.getResult(); 565 changed = true; 566 result.timeout = false; 567 result.who = w.getComponent(); 568 result.totalTime = SystemClock.uptimeMillis() - w.getStartTime(); 569 mWaitingForActivityVisible.remove(w); 570 } 571 } 572 if (changed) { 573 mService.mGlobalLock.notifyAll(); 574 } 575 } 576 reportWaitingActivityLaunchedIfNeeded(ActivityRecord r, int result)577 void reportWaitingActivityLaunchedIfNeeded(ActivityRecord r, int result) { 578 if (mWaitingActivityLaunched.isEmpty()) { 579 return; 580 } 581 582 if (result != START_DELIVERED_TO_TOP && result != START_TASK_TO_FRONT) { 583 return; 584 } 585 586 boolean changed = false; 587 588 for (int i = mWaitingActivityLaunched.size() - 1; i >= 0; i--) { 589 WaitResult w = mWaitingActivityLaunched.remove(i); 590 if (w.who == null) { 591 changed = true; 592 w.result = result; 593 594 // Unlike START_TASK_TO_FRONT, When an intent is delivered to top, there 595 // will be no followup launch signals. Assign the result and launched component. 596 if (result == START_DELIVERED_TO_TOP) { 597 w.who = r.mActivityComponent; 598 } 599 } 600 } 601 602 if (changed) { 603 mService.mGlobalLock.notifyAll(); 604 } 605 } 606 reportActivityLaunchedLocked(boolean timeout, ActivityRecord r, long totalTime, @WaitResult.LaunchState int launchState)607 void reportActivityLaunchedLocked(boolean timeout, ActivityRecord r, long totalTime, 608 @WaitResult.LaunchState int launchState) { 609 boolean changed = false; 610 for (int i = mWaitingActivityLaunched.size() - 1; i >= 0; i--) { 611 WaitResult w = mWaitingActivityLaunched.remove(i); 612 if (w.who == null) { 613 changed = true; 614 w.timeout = timeout; 615 if (r != null) { 616 w.who = new ComponentName(r.info.packageName, r.info.name); 617 } 618 w.totalTime = totalTime; 619 w.launchState = launchState; 620 // Do not modify w.result. 621 } 622 } 623 if (changed) { 624 mService.mGlobalLock.notifyAll(); 625 } 626 } 627 resolveActivity(Intent intent, ResolveInfo rInfo, int startFlags, ProfilerInfo profilerInfo)628 ActivityInfo resolveActivity(Intent intent, ResolveInfo rInfo, int startFlags, 629 ProfilerInfo profilerInfo) { 630 final ActivityInfo aInfo = rInfo != null ? rInfo.activityInfo : null; 631 if (aInfo != null) { 632 // Store the found target back into the intent, because now that 633 // we have it we never want to do this again. For example, if the 634 // user navigates back to this point in the history, we should 635 // always restart the exact same activity. 636 intent.setComponent(new ComponentName( 637 aInfo.applicationInfo.packageName, aInfo.name)); 638 639 // Don't debug things in the system process 640 if (!aInfo.processName.equals("system")) { 641 if ((startFlags & (START_FLAG_DEBUG | START_FLAG_NATIVE_DEBUGGING 642 | START_FLAG_TRACK_ALLOCATION)) != 0 || profilerInfo != null) { 643 644 // Mimic an AMS synchronous call by passing a message to AMS and wait for AMS 645 // to notify us that the task has completed. 646 // TODO(b/80414790) look into further untangling for the situation where the 647 // caller is on the same thread as the handler we are posting to. 648 synchronized (mService.mGlobalLock) { 649 // Post message to AMS. 650 final Message msg = PooledLambda.obtainMessage( 651 ActivityManagerInternal::setDebugFlagsForStartingActivity, 652 mService.mAmInternal, aInfo, startFlags, profilerInfo, 653 mService.mGlobalLock); 654 mService.mH.sendMessage(msg); 655 try { 656 mService.mGlobalLock.wait(); 657 } catch (InterruptedException ignore) { 658 659 } 660 } 661 } 662 } 663 final String intentLaunchToken = intent.getLaunchToken(); 664 if (aInfo.launchToken == null && intentLaunchToken != null) { 665 aInfo.launchToken = intentLaunchToken; 666 } 667 } 668 return aInfo; 669 } 670 resolveIntent(Intent intent, String resolvedType, int userId, int flags, int filterCallingUid)671 ResolveInfo resolveIntent(Intent intent, String resolvedType, int userId, int flags, 672 int filterCallingUid) { 673 try { 674 Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "resolveIntent"); 675 int modifiedFlags = flags 676 | PackageManager.MATCH_DEFAULT_ONLY | ActivityManagerService.STOCK_PM_FLAGS; 677 if (intent.isWebIntent() 678 || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) != 0) { 679 modifiedFlags |= PackageManager.MATCH_INSTANT; 680 } 681 682 // In order to allow cross-profile lookup, we clear the calling identity here. 683 // Note the binder identity won't affect the result, but filterCallingUid will. 684 685 // Cross-user/profile call check are done at the entry points 686 // (e.g. AMS.startActivityAsUser). 687 final long token = Binder.clearCallingIdentity(); 688 try { 689 return mService.getPackageManagerInternalLocked().resolveIntent( 690 intent, resolvedType, modifiedFlags, userId, true, filterCallingUid); 691 } finally { 692 Binder.restoreCallingIdentity(token); 693 } 694 } finally { 695 Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER); 696 } 697 } 698 resolveActivity(Intent intent, String resolvedType, int startFlags, ProfilerInfo profilerInfo, int userId, int filterCallingUid)699 ActivityInfo resolveActivity(Intent intent, String resolvedType, int startFlags, 700 ProfilerInfo profilerInfo, int userId, int filterCallingUid) { 701 final ResolveInfo rInfo = resolveIntent(intent, resolvedType, userId, 0, filterCallingUid); 702 return resolveActivity(intent, rInfo, startFlags, profilerInfo); 703 } 704 realStartActivityLocked(ActivityRecord r, WindowProcessController proc, boolean andResume, boolean checkConfig)705 boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc, 706 boolean andResume, boolean checkConfig) throws RemoteException { 707 708 if (!mRootActivityContainer.allPausedActivitiesComplete()) { 709 // While there are activities pausing we skipping starting any new activities until 710 // pauses are complete. NOTE: that we also do this for activities that are starting in 711 // the paused state because they will first be resumed then paused on the client side. 712 if (DEBUG_SWITCH || DEBUG_PAUSE || DEBUG_STATES) Slog.v(TAG_PAUSE, 713 "realStartActivityLocked: Skipping start of r=" + r 714 + " some activities pausing..."); 715 return false; 716 } 717 718 final TaskRecord task = r.getTaskRecord(); 719 final ActivityStack stack = task.getStack(); 720 721 beginDeferResume(); 722 723 try { 724 r.startFreezingScreenLocked(proc, 0); 725 726 // schedule launch ticks to collect information about slow apps. 727 r.startLaunchTickingLocked(); 728 729 r.setProcess(proc); 730 731 // Ensure activity is allowed to be resumed after process has set. 732 if (andResume && !r.canResumeByCompat()) { 733 andResume = false; 734 } 735 736 if (getKeyguardController().isKeyguardLocked()) { 737 r.notifyUnknownVisibilityLaunched(); 738 } 739 740 // Have the window manager re-evaluate the orientation of the screen based on the new 741 // activity order. Note that as a result of this, it can call back into the activity 742 // manager with a new orientation. We don't care about that, because the activity is 743 // not currently running so we are just restarting it anyway. 744 if (checkConfig) { 745 // Deferring resume here because we're going to launch new activity shortly. 746 // We don't want to perform a redundant launch of the same record while ensuring 747 // configurations and trying to resume top activity of focused stack. 748 mRootActivityContainer.ensureVisibilityAndConfig(r, r.getDisplayId(), 749 false /* markFrozenIfConfigChanged */, true /* deferResume */); 750 } 751 752 if (r.getActivityStack().checkKeyguardVisibility(r, true /* shouldBeVisible */, 753 true /* isTop */)) { 754 // We only set the visibility to true if the activity is allowed to be visible 755 // based on 756 // keyguard state. This avoids setting this into motion in window manager that is 757 // later cancelled due to later calls to ensure visible activities that set 758 // visibility back to false. 759 r.setVisibility(true); 760 } 761 762 final int applicationInfoUid = 763 (r.info.applicationInfo != null) ? r.info.applicationInfo.uid : -1; 764 if ((r.mUserId != proc.mUserId) || (r.appInfo.uid != applicationInfoUid)) { 765 Slog.wtf(TAG, 766 "User ID for activity changing for " + r 767 + " appInfo.uid=" + r.appInfo.uid 768 + " info.ai.uid=" + applicationInfoUid 769 + " old=" + r.app + " new=" + proc); 770 } 771 772 r.launchCount++; 773 r.lastLaunchTime = SystemClock.uptimeMillis(); 774 775 if (DEBUG_ALL) Slog.v(TAG, "Launching: " + r); 776 777 proc.addActivityIfNeeded(r); 778 779 final LockTaskController lockTaskController = mService.getLockTaskController(); 780 if (task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE 781 || task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE_PRIV 782 || (task.mLockTaskAuth == LOCK_TASK_AUTH_WHITELISTED 783 && lockTaskController.getLockTaskModeState() 784 == LOCK_TASK_MODE_LOCKED)) { 785 lockTaskController.startLockTaskMode(task, false, 0 /* blank UID */); 786 } 787 788 try { 789 if (!proc.hasThread()) { 790 throw new RemoteException(); 791 } 792 List<ResultInfo> results = null; 793 List<ReferrerIntent> newIntents = null; 794 if (andResume) { 795 // We don't need to deliver new intents and/or set results if activity is going 796 // to pause immediately after launch. 797 results = r.results; 798 newIntents = r.newIntents; 799 } 800 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, 801 "Launching: " + r + " icicle=" + r.icicle + " with results=" + results 802 + " newIntents=" + newIntents + " andResume=" + andResume); 803 EventLog.writeEvent(EventLogTags.AM_RESTART_ACTIVITY, r.mUserId, 804 System.identityHashCode(r), task.taskId, r.shortComponentName); 805 if (r.isActivityTypeHome()) { 806 // Home process is the root process of the task. 807 updateHomeProcess(task.mActivities.get(0).app); 808 } 809 mService.getPackageManagerInternalLocked().notifyPackageUse( 810 r.intent.getComponent().getPackageName(), NOTIFY_PACKAGE_USE_ACTIVITY); 811 r.sleeping = false; 812 r.forceNewConfig = false; 813 mService.getAppWarningsLocked().onStartActivity(r); 814 r.compat = mService.compatibilityInfoForPackageLocked(r.info.applicationInfo); 815 816 // Because we could be starting an Activity in the system process this may not go 817 // across a Binder interface which would create a new Configuration. Consequently 818 // we have to always create a new Configuration here. 819 820 final MergedConfiguration mergedConfiguration = new MergedConfiguration( 821 proc.getConfiguration(), r.getMergedOverrideConfiguration()); 822 r.setLastReportedConfiguration(mergedConfiguration); 823 824 logIfTransactionTooLarge(r.intent, r.icicle); 825 826 827 // Create activity launch transaction. 828 final ClientTransaction clientTransaction = ClientTransaction.obtain( 829 proc.getThread(), r.appToken); 830 831 final DisplayContent dc = r.getDisplay().mDisplayContent; 832 clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent), 833 System.identityHashCode(r), r.info, 834 // TODO: Have this take the merged configuration instead of separate global 835 // and override configs. 836 mergedConfiguration.getGlobalConfiguration(), 837 mergedConfiguration.getOverrideConfiguration(), r.compat, 838 r.launchedFromPackage, task.voiceInteractor, proc.getReportedProcState(), 839 r.icicle, r.persistentState, results, newIntents, 840 dc.isNextTransitionForward(), proc.createProfilerInfoIfNeeded(), 841 r.assistToken)); 842 843 // Set desired final state. 844 final ActivityLifecycleItem lifecycleItem; 845 if (andResume) { 846 lifecycleItem = ResumeActivityItem.obtain(dc.isNextTransitionForward()); 847 } else { 848 lifecycleItem = PauseActivityItem.obtain(); 849 } 850 clientTransaction.setLifecycleStateRequest(lifecycleItem); 851 852 // Schedule transaction. 853 mService.getLifecycleManager().scheduleTransaction(clientTransaction); 854 855 if ((proc.mInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_CANT_SAVE_STATE) != 0 856 && mService.mHasHeavyWeightFeature) { 857 // This may be a heavy-weight process! Note that the package manager will ensure 858 // that only activity can run in the main process of the .apk, which is the only 859 // thing that will be considered heavy-weight. 860 if (proc.mName.equals(proc.mInfo.packageName)) { 861 if (mService.mHeavyWeightProcess != null 862 && mService.mHeavyWeightProcess != proc) { 863 Slog.w(TAG, "Starting new heavy weight process " + proc 864 + " when already running " 865 + mService.mHeavyWeightProcess); 866 } 867 mService.setHeavyWeightProcess(r); 868 } 869 } 870 871 } catch (RemoteException e) { 872 if (r.launchFailed) { 873 // This is the second time we failed -- finish activity and give up. 874 Slog.e(TAG, "Second failure launching " 875 + r.intent.getComponent().flattenToShortString() + ", giving up", e); 876 proc.appDied(); 877 stack.requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null, 878 "2nd-crash", false); 879 return false; 880 } 881 882 // This is the first time we failed -- restart process and 883 // retry. 884 r.launchFailed = true; 885 proc.removeActivity(r); 886 throw e; 887 } 888 } finally { 889 endDeferResume(); 890 } 891 892 r.launchFailed = false; 893 if (stack.updateLRUListLocked(r)) { 894 Slog.w(TAG, "Activity " + r + " being launched, but already in LRU list"); 895 } 896 897 // TODO(lifecycler): Resume or pause requests are done as part of launch transaction, 898 // so updating the state should be done accordingly. 899 if (andResume && readyToResume()) { 900 // As part of the process of launching, ActivityThread also performs 901 // a resume. 902 stack.minimalResumeActivityLocked(r); 903 } else { 904 // This activity is not starting in the resumed state... which should look like we asked 905 // it to pause+stop (but remain visible), and it has done so and reported back the 906 // current icicle and other state. 907 if (DEBUG_STATES) Slog.v(TAG_STATES, 908 "Moving to PAUSED: " + r + " (starting in paused state)"); 909 r.setState(PAUSED, "realStartActivityLocked"); 910 } 911 // Perform OOM scoring after the activity state is set, so the process can be updated with 912 // the latest state. 913 proc.onStartActivity(mService.mTopProcessState, r.info); 914 915 // Launch the new version setup screen if needed. We do this -after- 916 // launching the initial activity (that is, home), so that it can have 917 // a chance to initialize itself while in the background, making the 918 // switch back to it faster and look better. 919 if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) { 920 mService.getActivityStartController().startSetupActivity(); 921 } 922 923 // Update any services we are bound to that might care about whether 924 // their client may have activities. 925 if (r.app != null) { 926 r.app.updateServiceConnectionActivities(); 927 } 928 929 return true; 930 } 931 updateHomeProcess(WindowProcessController app)932 void updateHomeProcess(WindowProcessController app) { 933 if (app != null && mService.mHomeProcess != app) { 934 if (!mHandler.hasMessages(REPORT_HOME_CHANGED_MSG)) { 935 mHandler.sendEmptyMessage(REPORT_HOME_CHANGED_MSG); 936 } 937 mService.mHomeProcess = app; 938 } 939 } 940 logIfTransactionTooLarge(Intent intent, Bundle icicle)941 private void logIfTransactionTooLarge(Intent intent, Bundle icicle) { 942 int extrasSize = 0; 943 if (intent != null) { 944 final Bundle extras = intent.getExtras(); 945 if (extras != null) { 946 extrasSize = extras.getSize(); 947 } 948 } 949 int icicleSize = (icicle == null ? 0 : icicle.getSize()); 950 if (extrasSize + icicleSize > 200000) { 951 Slog.e(TAG, "Transaction too large, intent: " + intent + ", extras size: " + extrasSize 952 + ", icicle size: " + icicleSize); 953 } 954 } 955 startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig)956 void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) { 957 // Is this activity's application already running? 958 final WindowProcessController wpc = 959 mService.getProcessController(r.processName, r.info.applicationInfo.uid); 960 961 boolean knownToBeDead = false; 962 if (wpc != null && wpc.hasThread()) { 963 try { 964 realStartActivityLocked(r, wpc, andResume, checkConfig); 965 return; 966 } catch (RemoteException e) { 967 Slog.w(TAG, "Exception when starting activity " 968 + r.intent.getComponent().flattenToShortString(), e); 969 } 970 971 // If a dead object exception was thrown -- fall through to 972 // restart the application. 973 knownToBeDead = true; 974 } 975 976 // Suppress transition until the new activity becomes ready, otherwise the keyguard can 977 // appear for a short amount of time before the new process with the new activity had the 978 // ability to set its showWhenLocked flags. 979 if (getKeyguardController().isKeyguardLocked()) { 980 r.notifyUnknownVisibilityLaunched(); 981 } 982 983 try { 984 if (Trace.isTagEnabled(TRACE_TAG_ACTIVITY_MANAGER)) { 985 Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "dispatchingStartProcess:" 986 + r.processName); 987 } 988 // Post message to start process to avoid possible deadlock of calling into AMS with the 989 // ATMS lock held. 990 final Message msg = PooledLambda.obtainMessage( 991 ActivityManagerInternal::startProcess, mService.mAmInternal, r.processName, 992 r.info.applicationInfo, knownToBeDead, "activity", r.intent.getComponent()); 993 mService.mH.sendMessage(msg); 994 } finally { 995 Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER); 996 } 997 } 998 checkStartAnyActivityPermission(Intent intent, ActivityInfo aInfo, String resultWho, int requestCode, int callingPid, int callingUid, String callingPackage, boolean ignoreTargetSecurity, boolean launchingInTask, WindowProcessController callerApp, ActivityRecord resultRecord, ActivityStack resultStack)999 boolean checkStartAnyActivityPermission(Intent intent, ActivityInfo aInfo, String resultWho, 1000 int requestCode, int callingPid, int callingUid, String callingPackage, 1001 boolean ignoreTargetSecurity, boolean launchingInTask, 1002 WindowProcessController callerApp, ActivityRecord resultRecord, 1003 ActivityStack resultStack) { 1004 final boolean isCallerRecents = mService.getRecentTasks() != null 1005 && mService.getRecentTasks().isCallerRecents(callingUid); 1006 final int startAnyPerm = mService.checkPermission(START_ANY_ACTIVITY, callingPid, 1007 callingUid); 1008 if (startAnyPerm == PERMISSION_GRANTED || (isCallerRecents && launchingInTask)) { 1009 // If the caller has START_ANY_ACTIVITY, ignore all checks below. In addition, if the 1010 // caller is the recents component and we are specifically starting an activity in an 1011 // existing task, then also allow the activity to be fully relaunched. 1012 return true; 1013 } 1014 final int componentRestriction = getComponentRestrictionForCallingPackage( 1015 aInfo, callingPackage, callingPid, callingUid, ignoreTargetSecurity); 1016 final int actionRestriction = getActionRestrictionForCallingPackage( 1017 intent.getAction(), callingPackage, callingPid, callingUid); 1018 if (componentRestriction == ACTIVITY_RESTRICTION_PERMISSION 1019 || actionRestriction == ACTIVITY_RESTRICTION_PERMISSION) { 1020 if (resultRecord != null) { 1021 resultStack.sendActivityResultLocked(-1, 1022 resultRecord, resultWho, requestCode, 1023 Activity.RESULT_CANCELED, null); 1024 } 1025 final String msg; 1026 if (actionRestriction == ACTIVITY_RESTRICTION_PERMISSION) { 1027 msg = "Permission Denial: starting " + intent.toString() 1028 + " from " + callerApp + " (pid=" + callingPid 1029 + ", uid=" + callingUid + ")" + " with revoked permission " 1030 + ACTION_TO_RUNTIME_PERMISSION.get(intent.getAction()); 1031 } else if (!aInfo.exported) { 1032 msg = "Permission Denial: starting " + intent.toString() 1033 + " from " + callerApp + " (pid=" + callingPid 1034 + ", uid=" + callingUid + ")" 1035 + " not exported from uid " + aInfo.applicationInfo.uid; 1036 } else { 1037 msg = "Permission Denial: starting " + intent.toString() 1038 + " from " + callerApp + " (pid=" + callingPid 1039 + ", uid=" + callingUid + ")" 1040 + " requires " + aInfo.permission; 1041 } 1042 Slog.w(TAG, msg); 1043 throw new SecurityException(msg); 1044 } 1045 1046 if (actionRestriction == ACTIVITY_RESTRICTION_APPOP) { 1047 final String message = "Appop Denial: starting " + intent.toString() 1048 + " from " + callerApp + " (pid=" + callingPid 1049 + ", uid=" + callingUid + ")" 1050 + " requires " + AppOpsManager.permissionToOp( 1051 ACTION_TO_RUNTIME_PERMISSION.get(intent.getAction())); 1052 Slog.w(TAG, message); 1053 return false; 1054 } else if (componentRestriction == ACTIVITY_RESTRICTION_APPOP) { 1055 final String message = "Appop Denial: starting " + intent.toString() 1056 + " from " + callerApp + " (pid=" + callingPid 1057 + ", uid=" + callingUid + ")" 1058 + " requires appop " + AppOpsManager.permissionToOp(aInfo.permission); 1059 Slog.w(TAG, message); 1060 return false; 1061 } 1062 1063 return true; 1064 } 1065 1066 /** Check if caller is allowed to launch activities on specified display. */ isCallerAllowedToLaunchOnDisplay(int callingPid, int callingUid, int launchDisplayId, ActivityInfo aInfo)1067 boolean isCallerAllowedToLaunchOnDisplay(int callingPid, int callingUid, int launchDisplayId, 1068 ActivityInfo aInfo) { 1069 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check: displayId=" + launchDisplayId 1070 + " callingPid=" + callingPid + " callingUid=" + callingUid); 1071 1072 if (callingPid == -1 && callingUid == -1) { 1073 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check: no caller info, skip check"); 1074 return true; 1075 } 1076 1077 final ActivityDisplay activityDisplay = 1078 mRootActivityContainer.getActivityDisplayOrCreate(launchDisplayId); 1079 if (activityDisplay == null || activityDisplay.isRemoved()) { 1080 Slog.w(TAG, "Launch on display check: display not found"); 1081 return false; 1082 } 1083 1084 // Check if the caller has enough privileges to embed activities and launch to private 1085 // displays. 1086 final int startAnyPerm = mService.checkPermission(INTERNAL_SYSTEM_WINDOW, callingPid, 1087 callingUid); 1088 if (startAnyPerm == PERMISSION_GRANTED) { 1089 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:" 1090 + " allow launch any on display"); 1091 return true; 1092 } 1093 1094 // Check if caller is already present on display 1095 final boolean uidPresentOnDisplay = activityDisplay.isUidPresent(callingUid); 1096 1097 final int displayOwnerUid = activityDisplay.mDisplay.getOwnerUid(); 1098 if (activityDisplay.mDisplay.getType() == TYPE_VIRTUAL && displayOwnerUid != SYSTEM_UID 1099 && displayOwnerUid != aInfo.applicationInfo.uid) { 1100 // Limit launching on virtual displays, because their contents can be read from Surface 1101 // by apps that created them. 1102 if ((aInfo.flags & ActivityInfo.FLAG_ALLOW_EMBEDDED) == 0) { 1103 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:" 1104 + " disallow launch on virtual display for not-embedded activity."); 1105 return false; 1106 } 1107 // Check if the caller is allowed to embed activities from other apps. 1108 if (mService.checkPermission(ACTIVITY_EMBEDDING, callingPid, callingUid) 1109 == PERMISSION_DENIED && !uidPresentOnDisplay) { 1110 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:" 1111 + " disallow activity embedding without permission."); 1112 return false; 1113 } 1114 } 1115 1116 if (!activityDisplay.isPrivate()) { 1117 // Anyone can launch on a public display. 1118 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:" 1119 + " allow launch on public display"); 1120 return true; 1121 } 1122 1123 // Check if the caller is the owner of the display. 1124 if (displayOwnerUid == callingUid) { 1125 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:" 1126 + " allow launch for owner of the display"); 1127 return true; 1128 } 1129 1130 if (uidPresentOnDisplay) { 1131 if (DEBUG_TASKS) Slog.d(TAG, "Launch on display check:" 1132 + " allow launch for caller present on the display"); 1133 return true; 1134 } 1135 1136 Slog.w(TAG, "Launch on display check: denied"); 1137 return false; 1138 } 1139 getUserInfo(int userId)1140 UserInfo getUserInfo(int userId) { 1141 final long identity = Binder.clearCallingIdentity(); 1142 try { 1143 return UserManager.get(mService.mContext).getUserInfo(userId); 1144 } finally { 1145 Binder.restoreCallingIdentity(identity); 1146 } 1147 } 1148 getComponentRestrictionForCallingPackage(ActivityInfo activityInfo, String callingPackage, int callingPid, int callingUid, boolean ignoreTargetSecurity)1149 private int getComponentRestrictionForCallingPackage(ActivityInfo activityInfo, 1150 String callingPackage, int callingPid, int callingUid, boolean ignoreTargetSecurity) { 1151 if (!ignoreTargetSecurity && mService.checkComponentPermission(activityInfo.permission, 1152 callingPid, callingUid, activityInfo.applicationInfo.uid, activityInfo.exported) 1153 == PERMISSION_DENIED) { 1154 return ACTIVITY_RESTRICTION_PERMISSION; 1155 } 1156 1157 if (activityInfo.permission == null) { 1158 return ACTIVITY_RESTRICTION_NONE; 1159 } 1160 1161 final int opCode = AppOpsManager.permissionToOpCode(activityInfo.permission); 1162 if (opCode == AppOpsManager.OP_NONE) { 1163 return ACTIVITY_RESTRICTION_NONE; 1164 } 1165 1166 if (mService.getAppOpsService().noteOperation(opCode, callingUid, callingPackage) 1167 != AppOpsManager.MODE_ALLOWED) { 1168 if (!ignoreTargetSecurity) { 1169 return ACTIVITY_RESTRICTION_APPOP; 1170 } 1171 } 1172 1173 return ACTIVITY_RESTRICTION_NONE; 1174 } 1175 getActionRestrictionForCallingPackage(String action, String callingPackage, int callingPid, int callingUid)1176 private int getActionRestrictionForCallingPackage(String action, 1177 String callingPackage, int callingPid, int callingUid) { 1178 if (action == null) { 1179 return ACTIVITY_RESTRICTION_NONE; 1180 } 1181 1182 String permission = ACTION_TO_RUNTIME_PERMISSION.get(action); 1183 if (permission == null) { 1184 return ACTIVITY_RESTRICTION_NONE; 1185 } 1186 1187 final PackageInfo packageInfo; 1188 try { 1189 packageInfo = mService.mContext.getPackageManager() 1190 .getPackageInfo(callingPackage, PackageManager.GET_PERMISSIONS); 1191 } catch (PackageManager.NameNotFoundException e) { 1192 Slog.i(TAG, "Cannot find package info for " + callingPackage); 1193 return ACTIVITY_RESTRICTION_NONE; 1194 } 1195 1196 if (!ArrayUtils.contains(packageInfo.requestedPermissions, permission)) { 1197 return ACTIVITY_RESTRICTION_NONE; 1198 } 1199 1200 if (mService.checkPermission(permission, callingPid, callingUid) == PERMISSION_DENIED) { 1201 return ACTIVITY_RESTRICTION_PERMISSION; 1202 } 1203 1204 final int opCode = AppOpsManager.permissionToOpCode(permission); 1205 if (opCode == AppOpsManager.OP_NONE) { 1206 return ACTIVITY_RESTRICTION_NONE; 1207 } 1208 1209 if (mService.getAppOpsService().noteOperation(opCode, callingUid, callingPackage) 1210 != AppOpsManager.MODE_ALLOWED) { 1211 return ACTIVITY_RESTRICTION_APPOP; 1212 } 1213 1214 return ACTIVITY_RESTRICTION_NONE; 1215 } 1216 setLaunchSource(int uid)1217 void setLaunchSource(int uid) { 1218 mLaunchingActivityWakeLock.setWorkSource(new WorkSource(uid)); 1219 } 1220 acquireLaunchWakelock()1221 void acquireLaunchWakelock() { 1222 if (VALIDATE_WAKE_LOCK_CALLER && Binder.getCallingUid() != Process.myUid()) { 1223 throw new IllegalStateException("Calling must be system uid"); 1224 } 1225 mLaunchingActivityWakeLock.acquire(); 1226 if (!mHandler.hasMessages(LAUNCH_TIMEOUT_MSG)) { 1227 // To be safe, don't allow the wake lock to be held for too long. 1228 mHandler.sendEmptyMessageDelayed(LAUNCH_TIMEOUT_MSG, LAUNCH_TIMEOUT); 1229 } 1230 } 1231 1232 /** 1233 * Called when all resumed tasks/stacks are idle. 1234 * @return the state of mService.mAm.mBooting before this was called. 1235 */ 1236 @GuardedBy("mService") checkFinishBootingLocked()1237 private boolean checkFinishBootingLocked() { 1238 final boolean booting = mService.isBooting(); 1239 boolean enableScreen = false; 1240 mService.setBooting(false); 1241 if (!mService.isBooted()) { 1242 mService.setBooted(true); 1243 enableScreen = true; 1244 } 1245 if (booting || enableScreen) { 1246 mService.postFinishBooting(booting, enableScreen); 1247 } 1248 return booting; 1249 } 1250 1251 // Checked. 1252 @GuardedBy("mService") activityIdleInternalLocked(final IBinder token, boolean fromTimeout, boolean processPausingActivities, Configuration config)1253 final ActivityRecord activityIdleInternalLocked(final IBinder token, boolean fromTimeout, 1254 boolean processPausingActivities, Configuration config) { 1255 if (DEBUG_ALL) Slog.v(TAG, "Activity idle: " + token); 1256 1257 ArrayList<ActivityRecord> finishes = null; 1258 ArrayList<UserState> startingUsers = null; 1259 int NS = 0; 1260 int NF = 0; 1261 boolean booting = false; 1262 boolean activityRemoved = false; 1263 1264 ActivityRecord r = ActivityRecord.forTokenLocked(token); 1265 if (r != null) { 1266 if (DEBUG_IDLE) Slog.d(TAG_IDLE, "activityIdleInternalLocked: Callers=" 1267 + Debug.getCallers(4)); 1268 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r); 1269 r.finishLaunchTickingLocked(); 1270 if (fromTimeout) { 1271 reportActivityLaunchedLocked(fromTimeout, r, INVALID_DELAY, 1272 -1 /* launchState */); 1273 } 1274 1275 // This is a hack to semi-deal with a race condition 1276 // in the client where it can be constructed with a 1277 // newer configuration from when we asked it to launch. 1278 // We'll update with whatever configuration it now says 1279 // it used to launch. 1280 if (config != null) { 1281 r.setLastReportedGlobalConfiguration(config); 1282 } 1283 1284 // We are now idle. If someone is waiting for a thumbnail from 1285 // us, we can now deliver. 1286 r.idle = true; 1287 1288 //Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout); 1289 1290 // Check if able to finish booting when device is booting and all resumed activities 1291 // are idle. 1292 if ((mService.isBooting() && mRootActivityContainer.allResumedActivitiesIdle()) 1293 || fromTimeout) { 1294 booting = checkFinishBootingLocked(); 1295 } 1296 1297 // When activity is idle, we consider the relaunch must be successful, so let's clear 1298 // the flag. 1299 r.mRelaunchReason = RELAUNCH_REASON_NONE; 1300 } 1301 1302 if (mRootActivityContainer.allResumedActivitiesIdle()) { 1303 if (r != null) { 1304 mService.scheduleAppGcsLocked(); 1305 } 1306 1307 if (mLaunchingActivityWakeLock.isHeld()) { 1308 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG); 1309 if (VALIDATE_WAKE_LOCK_CALLER && 1310 Binder.getCallingUid() != Process.myUid()) { 1311 throw new IllegalStateException("Calling must be system uid"); 1312 } 1313 mLaunchingActivityWakeLock.release(); 1314 } 1315 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS); 1316 } 1317 1318 // Atomically retrieve all of the other things to do. 1319 final ArrayList<ActivityRecord> stops = processStoppingActivitiesLocked(r, 1320 true /* remove */, processPausingActivities); 1321 NS = stops != null ? stops.size() : 0; 1322 if ((NF = mFinishingActivities.size()) > 0) { 1323 finishes = new ArrayList<>(mFinishingActivities); 1324 mFinishingActivities.clear(); 1325 } 1326 1327 if (mStartingUsers.size() > 0) { 1328 startingUsers = new ArrayList<>(mStartingUsers); 1329 mStartingUsers.clear(); 1330 } 1331 1332 // Stop any activities that are scheduled to do so but have been 1333 // waiting for the next one to start. 1334 for (int i = 0; i < NS; i++) { 1335 r = stops.get(i); 1336 final ActivityStack stack = r.getActivityStack(); 1337 if (stack != null) { 1338 if (r.finishing) { 1339 stack.finishCurrentActivityLocked(r, ActivityStack.FINISH_IMMEDIATELY, false, 1340 "activityIdleInternalLocked"); 1341 } else { 1342 stack.stopActivityLocked(r); 1343 } 1344 } 1345 } 1346 1347 // Finish any activities that are scheduled to do so but have been 1348 // waiting for the next one to start. 1349 for (int i = 0; i < NF; i++) { 1350 r = finishes.get(i); 1351 final ActivityStack stack = r.getActivityStack(); 1352 if (stack != null) { 1353 activityRemoved |= stack.destroyActivityLocked(r, true, "finish-idle"); 1354 } 1355 } 1356 1357 if (!booting) { 1358 // Complete user switch 1359 if (startingUsers != null) { 1360 for (int i = 0; i < startingUsers.size(); i++) { 1361 mService.mAmInternal.finishUserSwitch(startingUsers.get(i)); 1362 } 1363 } 1364 } 1365 1366 mService.mH.post(() -> mService.mAmInternal.trimApplications()); 1367 //dump(); 1368 //mWindowManager.dump(); 1369 1370 if (activityRemoved) { 1371 mRootActivityContainer.resumeFocusedStacksTopActivities(); 1372 } 1373 1374 return r; 1375 } 1376 1377 /** This doesn't just find a task, it also moves the task to front. */ findTaskToMoveToFront(TaskRecord task, int flags, ActivityOptions options, String reason, boolean forceNonResizeable)1378 void findTaskToMoveToFront(TaskRecord task, int flags, ActivityOptions options, String reason, 1379 boolean forceNonResizeable) { 1380 ActivityStack currentStack = task.getStack(); 1381 if (currentStack == null) { 1382 Slog.e(TAG, "findTaskToMoveToFront: can't move task=" 1383 + task + " to front. Stack is null"); 1384 return; 1385 } 1386 1387 if ((flags & ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) { 1388 mUserLeaving = true; 1389 } 1390 1391 reason = reason + " findTaskToMoveToFront"; 1392 boolean reparented = false; 1393 if (task.isResizeable() && canUseActivityOptionsLaunchBounds(options)) { 1394 final Rect bounds = options.getLaunchBounds(); 1395 task.updateOverrideConfiguration(bounds); 1396 1397 ActivityStack stack = 1398 mRootActivityContainer.getLaunchStack(null, options, task, ON_TOP); 1399 1400 if (stack != currentStack) { 1401 moveHomeStackToFrontIfNeeded(flags, stack.getDisplay(), reason); 1402 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, !ANIMATE, DEFER_RESUME, 1403 reason); 1404 currentStack = stack; 1405 reparented = true; 1406 // task.reparent() should already placed the task on top, 1407 // still need moveTaskToFrontLocked() below for any transition settings. 1408 } 1409 if (stack.resizeStackWithLaunchBounds()) { 1410 mRootActivityContainer.resizeStack(stack, bounds, null /* tempTaskBounds */, 1411 null /* tempTaskInsetBounds */, !PRESERVE_WINDOWS, 1412 true /* allowResizeInDockedMode */, !DEFER_RESUME); 1413 } else { 1414 // WM resizeTask must be done after the task is moved to the correct stack, 1415 // because Task's setBounds() also updates dim layer's bounds, but that has 1416 // dependency on the stack. 1417 task.resizeWindowContainer(); 1418 } 1419 } 1420 1421 if (!reparented) { 1422 moveHomeStackToFrontIfNeeded(flags, currentStack.getDisplay(), reason); 1423 } 1424 1425 final ActivityRecord r = task.getTopActivity(); 1426 currentStack.moveTaskToFrontLocked(task, false /* noAnimation */, options, 1427 r == null ? null : r.appTimeTracker, reason); 1428 1429 if (DEBUG_STACK) Slog.d(TAG_STACK, 1430 "findTaskToMoveToFront: moved to front of stack=" + currentStack); 1431 1432 handleNonResizableTaskIfNeeded(task, WINDOWING_MODE_UNDEFINED, DEFAULT_DISPLAY, 1433 currentStack, forceNonResizeable); 1434 } 1435 moveHomeStackToFrontIfNeeded(int flags, ActivityDisplay display, String reason)1436 private void moveHomeStackToFrontIfNeeded(int flags, ActivityDisplay display, String reason) { 1437 final ActivityStack focusedStack = display.getFocusedStack(); 1438 1439 if ((display.getWindowingMode() == WINDOWING_MODE_FULLSCREEN 1440 && (flags & ActivityManager.MOVE_TASK_WITH_HOME) != 0) 1441 || (focusedStack != null && focusedStack.isActivityTypeRecents())) { 1442 // We move home stack to front when we are on a fullscreen display and caller has 1443 // requested the home activity to move with it. Or the previous stack is recents. 1444 display.moveHomeStackToFront(reason); 1445 } 1446 } 1447 canUseActivityOptionsLaunchBounds(ActivityOptions options)1448 boolean canUseActivityOptionsLaunchBounds(ActivityOptions options) { 1449 // We use the launch bounds in the activity options is the device supports freeform 1450 // window management or is launching into the pinned stack. 1451 if (options == null || options.getLaunchBounds() == null) { 1452 return false; 1453 } 1454 return (mService.mSupportsPictureInPicture 1455 && options.getLaunchWindowingMode() == WINDOWING_MODE_PINNED) 1456 || mService.mSupportsFreeformWindowManagement; 1457 } 1458 getLaunchParamsController()1459 LaunchParamsController getLaunchParamsController() { 1460 return mLaunchParamsController; 1461 } 1462 deferUpdateRecentsHomeStackBounds()1463 private void deferUpdateRecentsHomeStackBounds() { 1464 mRootActivityContainer.deferUpdateBounds(ACTIVITY_TYPE_RECENTS); 1465 mRootActivityContainer.deferUpdateBounds(ACTIVITY_TYPE_HOME); 1466 } 1467 continueUpdateRecentsHomeStackBounds()1468 private void continueUpdateRecentsHomeStackBounds() { 1469 mRootActivityContainer.continueUpdateBounds(ACTIVITY_TYPE_RECENTS); 1470 mRootActivityContainer.continueUpdateBounds(ACTIVITY_TYPE_HOME); 1471 } 1472 notifyAppTransitionDone()1473 void notifyAppTransitionDone() { 1474 continueUpdateRecentsHomeStackBounds(); 1475 for (int i = mResizingTasksDuringAnimation.size() - 1; i >= 0; i--) { 1476 final int taskId = mResizingTasksDuringAnimation.valueAt(i); 1477 final TaskRecord task = 1478 mRootActivityContainer.anyTaskForId(taskId, MATCH_TASK_IN_STACKS_ONLY); 1479 if (task != null) { 1480 task.setTaskDockedResizing(false); 1481 } 1482 } 1483 mResizingTasksDuringAnimation.clear(); 1484 } 1485 1486 /** 1487 * TODO: This should just change the windowing mode and resize vs. actually moving task around. 1488 * Can do that once we are no longer using static stack ids. 1489 */ moveTasksToFullscreenStackInSurfaceTransaction(ActivityStack fromStack, int toDisplayId, boolean onTop)1490 private void moveTasksToFullscreenStackInSurfaceTransaction(ActivityStack fromStack, 1491 int toDisplayId, boolean onTop) { 1492 1493 mWindowManager.deferSurfaceLayout(); 1494 try { 1495 final int windowingMode = fromStack.getWindowingMode(); 1496 final boolean inPinnedWindowingMode = windowingMode == WINDOWING_MODE_PINNED; 1497 final ActivityDisplay toDisplay = 1498 mRootActivityContainer.getActivityDisplay(toDisplayId); 1499 1500 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) { 1501 // Tell the display we are exiting split-screen mode. 1502 toDisplay.onExitingSplitScreenMode(); 1503 // We are moving all tasks from the docked stack to the fullscreen stack, 1504 // which is dismissing the docked stack, so resize all other stacks to 1505 // fullscreen here already so we don't end up with resize trashing. 1506 for (int i = toDisplay.getChildCount() - 1; i >= 0; --i) { 1507 final ActivityStack otherStack = toDisplay.getChildAt(i); 1508 if (!otherStack.inSplitScreenSecondaryWindowingMode()) { 1509 continue; 1510 } 1511 otherStack.setWindowingMode(WINDOWING_MODE_UNDEFINED); 1512 } 1513 1514 // Also disable docked stack resizing since we have manually adjusted the 1515 // size of other stacks above and we don't want to trigger a docked stack 1516 // resize when we remove task from it below and it is detached from the 1517 // display because it no longer contains any tasks. 1518 mAllowDockedStackResize = false; 1519 } 1520 1521 // If we are moving from the pinned stack, then the animation takes care of updating 1522 // the picture-in-picture mode. 1523 final boolean schedulePictureInPictureModeChange = inPinnedWindowingMode; 1524 final ArrayList<TaskRecord> tasks = fromStack.getAllTasks(); 1525 1526 if (!tasks.isEmpty()) { 1527 mTmpOptions.setLaunchWindowingMode(WINDOWING_MODE_FULLSCREEN); 1528 final int size = tasks.size(); 1529 for (int i = 0; i < size; ++i) { 1530 final TaskRecord task = tasks.get(i); 1531 final ActivityStack toStack = toDisplay.getOrCreateStack( 1532 null, mTmpOptions, task, task.getActivityType(), onTop); 1533 1534 if (onTop) { 1535 final boolean isTopTask = i == (size - 1); 1536 // Defer resume until all the tasks have been moved to the fullscreen stack 1537 task.reparent(toStack, ON_TOP, REPARENT_MOVE_STACK_TO_FRONT, 1538 isTopTask /* animate */, DEFER_RESUME, 1539 schedulePictureInPictureModeChange, 1540 "moveTasksToFullscreenStack - onTop"); 1541 MetricsLoggerWrapper.logPictureInPictureFullScreen(mService.mContext, 1542 task.effectiveUid, task.realActivity.flattenToString()); 1543 } else { 1544 // Position the tasks in the fullscreen stack in order at the bottom of the 1545 // stack. Also defer resume until all the tasks have been moved to the 1546 // fullscreen stack. 1547 task.reparent(toStack, ON_TOP, 1548 REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE, DEFER_RESUME, 1549 schedulePictureInPictureModeChange, 1550 "moveTasksToFullscreenStack - NOT_onTop"); 1551 } 1552 } 1553 } 1554 1555 mRootActivityContainer.ensureActivitiesVisible(null, 0, PRESERVE_WINDOWS); 1556 mRootActivityContainer.resumeFocusedStacksTopActivities(); 1557 } finally { 1558 mAllowDockedStackResize = true; 1559 mWindowManager.continueSurfaceLayout(); 1560 } 1561 } 1562 moveTasksToFullscreenStackLocked(ActivityStack fromStack, boolean onTop)1563 void moveTasksToFullscreenStackLocked(ActivityStack fromStack, boolean onTop) { 1564 moveTasksToFullscreenStackLocked(fromStack, DEFAULT_DISPLAY, onTop); 1565 } 1566 moveTasksToFullscreenStackLocked(ActivityStack fromStack, int toDisplayId, boolean onTop)1567 void moveTasksToFullscreenStackLocked(ActivityStack fromStack, int toDisplayId, boolean onTop) { 1568 mWindowManager.inSurfaceTransaction(() -> 1569 moveTasksToFullscreenStackInSurfaceTransaction(fromStack, toDisplayId, onTop)); 1570 } 1571 setSplitScreenResizing(boolean resizing)1572 void setSplitScreenResizing(boolean resizing) { 1573 if (resizing == mDockedStackResizing) { 1574 return; 1575 } 1576 1577 mDockedStackResizing = resizing; 1578 mWindowManager.setDockedStackResizing(resizing); 1579 1580 if (!resizing && mHasPendingDockedBounds) { 1581 resizeDockedStackLocked(mPendingDockedBounds, mPendingTempDockedTaskBounds, 1582 mPendingTempDockedTaskInsetBounds, mPendingTempOtherTaskBounds, 1583 mPendingTempOtherTaskInsetBounds, PRESERVE_WINDOWS); 1584 1585 mHasPendingDockedBounds = false; 1586 mPendingDockedBounds = null; 1587 mPendingTempDockedTaskBounds = null; 1588 mPendingTempDockedTaskInsetBounds = null; 1589 mPendingTempOtherTaskBounds = null; 1590 mPendingTempOtherTaskInsetBounds = null; 1591 } 1592 } 1593 resizeDockedStackLocked(Rect dockedBounds, Rect tempDockedTaskBounds, Rect tempDockedTaskInsetBounds, Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds, boolean preserveWindows)1594 void resizeDockedStackLocked(Rect dockedBounds, Rect tempDockedTaskBounds, 1595 Rect tempDockedTaskInsetBounds, Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds, 1596 boolean preserveWindows) { 1597 resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds, tempDockedTaskInsetBounds, 1598 tempOtherTaskBounds, tempOtherTaskInsetBounds, preserveWindows, 1599 false /* deferResume */); 1600 } 1601 resizeDockedStackLocked(Rect dockedBounds, Rect tempDockedTaskBounds, Rect tempDockedTaskInsetBounds, Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds, boolean preserveWindows, boolean deferResume)1602 void resizeDockedStackLocked(Rect dockedBounds, Rect tempDockedTaskBounds, 1603 Rect tempDockedTaskInsetBounds, Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds, 1604 boolean preserveWindows, boolean deferResume) { 1605 1606 if (!mAllowDockedStackResize) { 1607 // Docked stack resize currently disabled. 1608 return; 1609 } 1610 1611 final ActivityStack stack = 1612 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack(); 1613 if (stack == null) { 1614 Slog.w(TAG, "resizeDockedStackLocked: docked stack not found"); 1615 return; 1616 } 1617 1618 if (mDockedStackResizing) { 1619 mHasPendingDockedBounds = true; 1620 mPendingDockedBounds = copyOrNull(dockedBounds); 1621 mPendingTempDockedTaskBounds = copyOrNull(tempDockedTaskBounds); 1622 mPendingTempDockedTaskInsetBounds = copyOrNull(tempDockedTaskInsetBounds); 1623 mPendingTempOtherTaskBounds = copyOrNull(tempOtherTaskBounds); 1624 mPendingTempOtherTaskInsetBounds = copyOrNull(tempOtherTaskInsetBounds); 1625 } 1626 1627 Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "am.resizeDockedStack"); 1628 mWindowManager.deferSurfaceLayout(); 1629 try { 1630 // Don't allow re-entry while resizing. E.g. due to docked stack detaching. 1631 mAllowDockedStackResize = false; 1632 ActivityRecord r = stack.topRunningActivityLocked(); 1633 stack.resize(dockedBounds, tempDockedTaskBounds, tempDockedTaskInsetBounds); 1634 1635 // TODO: Checking for isAttached might not be needed as if the user passes in null 1636 // dockedBounds then they want the docked stack to be dismissed. 1637 if (stack.getWindowingMode() == WINDOWING_MODE_FULLSCREEN 1638 || (dockedBounds == null && !stack.isAttached())) { 1639 // The dock stack either was dismissed or went fullscreen, which is kinda the same. 1640 // In this case we make all other static stacks fullscreen and move all 1641 // docked stack tasks to the fullscreen stack. 1642 moveTasksToFullscreenStackLocked(stack, ON_TOP); 1643 1644 // stack shouldn't contain anymore activities, so nothing to resume. 1645 r = null; 1646 } else { 1647 // Docked stacks occupy a dedicated region on screen so the size of all other 1648 // static stacks need to be adjusted so they don't overlap with the docked stack. 1649 // We get the bounds to use from window manager which has been adjusted for any 1650 // screen controls and is also the same for all stacks. 1651 final ActivityDisplay display = mRootActivityContainer.getDefaultDisplay(); 1652 final Rect otherTaskRect = new Rect(); 1653 for (int i = display.getChildCount() - 1; i >= 0; --i) { 1654 final ActivityStack current = display.getChildAt(i); 1655 if (!current.inSplitScreenSecondaryWindowingMode()) { 1656 continue; 1657 } 1658 if (!current.affectedBySplitScreenResize()) { 1659 continue; 1660 } 1661 if (mDockedStackResizing && !current.isTopActivityVisible()) { 1662 // Non-visible stacks get resized once we're done with the resize 1663 // interaction. 1664 continue; 1665 } 1666 current.getStackDockedModeBounds(dockedBounds, 1667 tempOtherTaskBounds /* currentTempTaskBounds */, 1668 tempRect /* outStackBounds */, 1669 otherTaskRect /* outTempTaskBounds */); 1670 1671 mRootActivityContainer.resizeStack(current, 1672 !tempRect.isEmpty() ? tempRect : null, 1673 !otherTaskRect.isEmpty() ? otherTaskRect : tempOtherTaskBounds, 1674 tempOtherTaskInsetBounds, preserveWindows, 1675 true /* allowResizeInDockedMode */, deferResume); 1676 } 1677 } 1678 if (!deferResume) { 1679 stack.ensureVisibleActivitiesConfigurationLocked(r, preserveWindows); 1680 } 1681 } finally { 1682 mAllowDockedStackResize = true; 1683 mWindowManager.continueSurfaceLayout(); 1684 Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER); 1685 } 1686 } 1687 resizePinnedStackLocked(Rect pinnedBounds, Rect tempPinnedTaskBounds)1688 void resizePinnedStackLocked(Rect pinnedBounds, Rect tempPinnedTaskBounds) { 1689 // TODO(multi-display): The display containing the stack should be passed in. 1690 final ActivityStack stack = 1691 mRootActivityContainer.getDefaultDisplay().getPinnedStack(); 1692 if (stack == null) { 1693 Slog.w(TAG, "resizePinnedStackLocked: pinned stack not found"); 1694 return; 1695 } 1696 1697 // It is possible for the bounds animation from the WM to call this but be delayed by 1698 // another AM call that is holding the AMS lock. In such a case, the pinnedBounds may be 1699 // incorrect if AMS.resizeStackWithBoundsFromWindowManager() is already called while waiting 1700 // for the AMS lock to be freed. So check and make sure these bounds are still good. 1701 final TaskStack stackController = stack.getTaskStack(); 1702 if (stackController.pinnedStackResizeDisallowed()) { 1703 return; 1704 } 1705 1706 Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "am.resizePinnedStack"); 1707 mWindowManager.deferSurfaceLayout(); 1708 try { 1709 ActivityRecord r = stack.topRunningActivityLocked(); 1710 Rect insetBounds = null; 1711 if (tempPinnedTaskBounds != null && stack.isAnimatingBoundsToFullscreen()) { 1712 // Use 0,0 as the position for the inset rect because we are headed for fullscreen. 1713 insetBounds = tempRect; 1714 insetBounds.top = 0; 1715 insetBounds.left = 0; 1716 insetBounds.right = tempPinnedTaskBounds.width(); 1717 insetBounds.bottom = tempPinnedTaskBounds.height(); 1718 } 1719 if (pinnedBounds != null && tempPinnedTaskBounds == null) { 1720 // We have finished the animation into PiP, and are resizing the tasks to match the 1721 // stack bounds, while layouts are deferred, update any task state as a part of 1722 // transitioning it from fullscreen into a floating state. 1723 stack.onPipAnimationEndResize(); 1724 } 1725 stack.resize(pinnedBounds, tempPinnedTaskBounds, insetBounds); 1726 stack.ensureVisibleActivitiesConfigurationLocked(r, false); 1727 } finally { 1728 mWindowManager.continueSurfaceLayout(); 1729 Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER); 1730 } 1731 } 1732 removeStackInSurfaceTransaction(ActivityStack stack)1733 private void removeStackInSurfaceTransaction(ActivityStack stack) { 1734 final ArrayList<TaskRecord> tasks = stack.getAllTasks(); 1735 if (stack.getWindowingMode() == WINDOWING_MODE_PINNED) { 1736 /** 1737 * Workaround: Force-stop all the activities in the pinned stack before we reparent them 1738 * to the fullscreen stack. This is to guarantee that when we are removing a stack, 1739 * that the client receives onStop() before it is reparented. We do this by detaching 1740 * the stack from the display so that it will be considered invisible when 1741 * ensureActivitiesVisibleLocked() is called, and all of its activitys will be marked 1742 * invisible as well and added to the stopping list. After which we process the 1743 * stopping list by handling the idle. 1744 */ 1745 stack.mForceHidden = true; 1746 stack.ensureActivitiesVisibleLocked(null, 0, PRESERVE_WINDOWS); 1747 stack.mForceHidden = false; 1748 activityIdleInternalLocked(null, false /* fromTimeout */, 1749 true /* processPausingActivites */, null /* configuration */); 1750 1751 // Move all the tasks to the bottom of the fullscreen stack 1752 moveTasksToFullscreenStackLocked(stack, !ON_TOP); 1753 } else { 1754 for (int i = tasks.size() - 1; i >= 0; i--) { 1755 removeTaskByIdLocked(tasks.get(i).taskId, true /* killProcess */, 1756 REMOVE_FROM_RECENTS, "remove-stack"); 1757 } 1758 } 1759 } 1760 1761 /** 1762 * Removes the stack associated with the given {@param stack}. If the {@param stack} is the 1763 * pinned stack, then its tasks are not explicitly removed when the stack is destroyed, but 1764 * instead moved back onto the fullscreen stack. 1765 */ removeStack(ActivityStack stack)1766 void removeStack(ActivityStack stack) { 1767 mWindowManager.inSurfaceTransaction(() -> removeStackInSurfaceTransaction(stack)); 1768 } 1769 1770 /** 1771 * See {@link #removeTaskByIdLocked(int, boolean, boolean, boolean)} 1772 */ removeTaskByIdLocked(int taskId, boolean killProcess, boolean removeFromRecents, String reason)1773 boolean removeTaskByIdLocked(int taskId, boolean killProcess, boolean removeFromRecents, 1774 String reason) { 1775 return removeTaskByIdLocked(taskId, killProcess, removeFromRecents, !PAUSE_IMMEDIATELY, 1776 reason); 1777 } 1778 1779 /** 1780 * Removes the task with the specified task id. 1781 * 1782 * @param taskId Identifier of the task to be removed. 1783 * @param killProcess Kill any process associated with the task if possible. 1784 * @param removeFromRecents Whether to also remove the task from recents. 1785 * @param pauseImmediately Pauses all task activities immediately without waiting for the 1786 * pause-complete callback from the activity. 1787 * @return Returns true if the given task was found and removed. 1788 */ removeTaskByIdLocked(int taskId, boolean killProcess, boolean removeFromRecents, boolean pauseImmediately, String reason)1789 boolean removeTaskByIdLocked(int taskId, boolean killProcess, boolean removeFromRecents, 1790 boolean pauseImmediately, String reason) { 1791 final TaskRecord tr = 1792 mRootActivityContainer.anyTaskForId(taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS); 1793 if (tr != null) { 1794 tr.removeTaskActivitiesLocked(pauseImmediately, reason); 1795 cleanUpRemovedTaskLocked(tr, killProcess, removeFromRecents); 1796 mService.getLockTaskController().clearLockedTask(tr); 1797 if (tr.isPersistable) { 1798 mService.notifyTaskPersisterLocked(null, true); 1799 } 1800 return true; 1801 } 1802 Slog.w(TAG, "Request to remove task ignored for non-existent task " + taskId); 1803 return false; 1804 } 1805 cleanUpRemovedTaskLocked(TaskRecord tr, boolean killProcess, boolean removeFromRecents)1806 void cleanUpRemovedTaskLocked(TaskRecord tr, boolean killProcess, boolean removeFromRecents) { 1807 if (removeFromRecents) { 1808 mRecentTasks.remove(tr); 1809 } 1810 ComponentName component = tr.getBaseIntent().getComponent(); 1811 if (component == null) { 1812 Slog.w(TAG, "No component for base intent of task: " + tr); 1813 return; 1814 } 1815 1816 // Find any running services associated with this app and stop if needed. 1817 final Message msg = PooledLambda.obtainMessage(ActivityManagerInternal::cleanUpServices, 1818 mService.mAmInternal, tr.userId, component, new Intent(tr.getBaseIntent())); 1819 mService.mH.sendMessage(msg); 1820 1821 if (!killProcess) { 1822 return; 1823 } 1824 1825 // Determine if the process(es) for this task should be killed. 1826 final String pkg = component.getPackageName(); 1827 ArrayList<Object> procsToKill = new ArrayList<>(); 1828 ArrayMap<String, SparseArray<WindowProcessController>> pmap = 1829 mService.mProcessNames.getMap(); 1830 for (int i = 0; i < pmap.size(); i++) { 1831 1832 SparseArray<WindowProcessController> uids = pmap.valueAt(i); 1833 for (int j = 0; j < uids.size(); j++) { 1834 WindowProcessController proc = uids.valueAt(j); 1835 if (proc.mUserId != tr.userId) { 1836 // Don't kill process for a different user. 1837 continue; 1838 } 1839 if (proc == mService.mHomeProcess) { 1840 // Don't kill the home process along with tasks from the same package. 1841 continue; 1842 } 1843 if (!proc.mPkgList.contains(pkg)) { 1844 // Don't kill process that is not associated with this task. 1845 continue; 1846 } 1847 1848 if (!proc.shouldKillProcessForRemovedTask(tr)) { 1849 // Don't kill process(es) that has an activity in a different task that is also 1850 // in recents, or has an activity not stopped. 1851 return; 1852 } 1853 1854 if (proc.hasForegroundServices()) { 1855 // Don't kill process(es) with foreground service. 1856 return; 1857 } 1858 1859 // Add process to kill list. 1860 procsToKill.add(proc); 1861 } 1862 } 1863 1864 // Kill the running processes. Post on handle since we don't want to hold the service lock 1865 // while calling into AM. 1866 final Message m = PooledLambda.obtainMessage( 1867 ActivityManagerInternal::killProcessesForRemovedTask, mService.mAmInternal, 1868 procsToKill); 1869 mService.mH.sendMessage(m); 1870 } 1871 1872 /** 1873 * Called to restore the state of the task into the stack that it's supposed to go into. 1874 * 1875 * @param task The recent task to be restored. 1876 * @param aOptions The activity options to use for restoration. 1877 * @param onTop If the stack for the task should be the topmost on the display. 1878 * @return true if the task has been restored successfully. 1879 */ restoreRecentTaskLocked(TaskRecord task, ActivityOptions aOptions, boolean onTop)1880 boolean restoreRecentTaskLocked(TaskRecord task, ActivityOptions aOptions, boolean onTop) { 1881 final ActivityStack stack = 1882 mRootActivityContainer.getLaunchStack(null, aOptions, task, onTop); 1883 final ActivityStack currentStack = task.getStack(); 1884 if (currentStack != null) { 1885 // Task has already been restored once. See if we need to do anything more 1886 if (currentStack == stack) { 1887 // Nothing else to do since it is already restored in the right stack. 1888 return true; 1889 } 1890 // Remove current stack association, so we can re-associate the task with the 1891 // right stack below. 1892 currentStack.removeTask(task, "restoreRecentTaskLocked", REMOVE_TASK_MODE_MOVING); 1893 } 1894 1895 stack.addTask(task, onTop, "restoreRecentTask"); 1896 // TODO: move call for creation here and other place into Stack.addTask() 1897 task.createTask(onTop, true /* showForAllUsers */); 1898 if (DEBUG_RECENTS) Slog.v(TAG_RECENTS, 1899 "Added restored task=" + task + " to stack=" + stack); 1900 final ArrayList<ActivityRecord> activities = task.mActivities; 1901 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 1902 activities.get(activityNdx).createAppWindowToken(); 1903 } 1904 return true; 1905 } 1906 1907 @Override onRecentTaskAdded(TaskRecord task)1908 public void onRecentTaskAdded(TaskRecord task) { 1909 task.touchActiveTime(); 1910 } 1911 1912 @Override onRecentTaskRemoved(TaskRecord task, boolean wasTrimmed, boolean killProcess)1913 public void onRecentTaskRemoved(TaskRecord task, boolean wasTrimmed, boolean killProcess) { 1914 if (wasTrimmed) { 1915 // Task was trimmed from the recent tasks list -- remove the active task record as well 1916 // since the user won't really be able to go back to it 1917 removeTaskByIdLocked(task.taskId, killProcess, false /* removeFromRecents */, 1918 !PAUSE_IMMEDIATELY, "recent-task-trimmed"); 1919 } 1920 task.removedFromRecents(); 1921 } 1922 1923 /** 1924 * Returns the reparent target stack, creating the stack if necessary. This call also enforces 1925 * the various checks on tasks that are going to be reparented from one stack to another. 1926 */ 1927 // TODO: Look into changing users to this method to ActivityDisplay.resolveWindowingMode() getReparentTargetStack(TaskRecord task, ActivityStack stack, boolean toTop)1928 ActivityStack getReparentTargetStack(TaskRecord task, ActivityStack stack, boolean toTop) { 1929 final ActivityStack prevStack = task.getStack(); 1930 final int stackId = stack.mStackId; 1931 final boolean inMultiWindowMode = stack.inMultiWindowMode(); 1932 1933 // Check that we aren't reparenting to the same stack that the task is already in 1934 if (prevStack != null && prevStack.mStackId == stackId) { 1935 Slog.w(TAG, "Can not reparent to same stack, task=" + task 1936 + " already in stackId=" + stackId); 1937 return prevStack; 1938 } 1939 1940 // Ensure that we aren't trying to move into a multi-window stack without multi-window 1941 // support 1942 if (inMultiWindowMode && !mService.mSupportsMultiWindow) { 1943 throw new IllegalArgumentException("Device doesn't support multi-window, can not" 1944 + " reparent task=" + task + " to stack=" + stack); 1945 } 1946 1947 // Ensure that we're not moving a task to a dynamic stack if device doesn't support 1948 // multi-display. 1949 if (stack.mDisplayId != DEFAULT_DISPLAY && !mService.mSupportsMultiDisplay) { 1950 throw new IllegalArgumentException("Device doesn't support multi-display, can not" 1951 + " reparent task=" + task + " to stackId=" + stackId); 1952 } 1953 1954 // Ensure that we aren't trying to move into a freeform stack without freeform support 1955 if (stack.getWindowingMode() == WINDOWING_MODE_FREEFORM 1956 && !mService.mSupportsFreeformWindowManagement) { 1957 throw new IllegalArgumentException("Device doesn't support freeform, can not reparent" 1958 + " task=" + task); 1959 } 1960 1961 // Leave the task in its current stack or a fullscreen stack if it isn't resizeable and the 1962 // preferred stack is in multi-window mode. 1963 if (inMultiWindowMode && !task.isResizeable()) { 1964 Slog.w(TAG, "Can not move unresizeable task=" + task + " to multi-window stack=" + stack 1965 + " Moving to a fullscreen stack instead."); 1966 if (prevStack != null) { 1967 return prevStack; 1968 } 1969 stack = stack.getDisplay().createStack( 1970 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), toTop); 1971 } 1972 return stack; 1973 } 1974 goingToSleepLocked()1975 void goingToSleepLocked() { 1976 scheduleSleepTimeout(); 1977 if (!mGoingToSleepWakeLock.isHeld()) { 1978 mGoingToSleepWakeLock.acquire(); 1979 if (mLaunchingActivityWakeLock.isHeld()) { 1980 if (VALIDATE_WAKE_LOCK_CALLER && Binder.getCallingUid() != Process.myUid()) { 1981 throw new IllegalStateException("Calling must be system uid"); 1982 } 1983 mLaunchingActivityWakeLock.release(); 1984 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG); 1985 } 1986 } 1987 1988 mRootActivityContainer.applySleepTokens(false /* applyToStacks */); 1989 1990 checkReadyForSleepLocked(true /* allowDelay */); 1991 } 1992 shutdownLocked(int timeout)1993 boolean shutdownLocked(int timeout) { 1994 goingToSleepLocked(); 1995 1996 boolean timedout = false; 1997 final long endTime = System.currentTimeMillis() + timeout; 1998 while (true) { 1999 if (!mRootActivityContainer.putStacksToSleep( 2000 true /* allowDelay */, true /* shuttingDown */)) { 2001 long timeRemaining = endTime - System.currentTimeMillis(); 2002 if (timeRemaining > 0) { 2003 try { 2004 mService.mGlobalLock.wait(timeRemaining); 2005 } catch (InterruptedException e) { 2006 } 2007 } else { 2008 Slog.w(TAG, "Activity manager shutdown timed out"); 2009 timedout = true; 2010 break; 2011 } 2012 } else { 2013 break; 2014 } 2015 } 2016 2017 // Force checkReadyForSleep to complete. 2018 checkReadyForSleepLocked(false /* allowDelay */); 2019 2020 return timedout; 2021 } 2022 comeOutOfSleepIfNeededLocked()2023 void comeOutOfSleepIfNeededLocked() { 2024 removeSleepTimeouts(); 2025 if (mGoingToSleepWakeLock.isHeld()) { 2026 mGoingToSleepWakeLock.release(); 2027 } 2028 } 2029 activitySleptLocked(ActivityRecord r)2030 void activitySleptLocked(ActivityRecord r) { 2031 mGoingToSleepActivities.remove(r); 2032 final ActivityStack s = r.getActivityStack(); 2033 if (s != null) { 2034 s.checkReadyForSleep(); 2035 } else { 2036 checkReadyForSleepLocked(true); 2037 } 2038 } 2039 checkReadyForSleepLocked(boolean allowDelay)2040 void checkReadyForSleepLocked(boolean allowDelay) { 2041 if (!mService.isSleepingOrShuttingDownLocked()) { 2042 // Do not care. 2043 return; 2044 } 2045 2046 if (!mRootActivityContainer.putStacksToSleep( 2047 allowDelay, false /* shuttingDown */)) { 2048 return; 2049 } 2050 2051 // Send launch end powerhint before going sleep 2052 mRootActivityContainer.sendPowerHintForLaunchEndIfNeeded(); 2053 2054 removeSleepTimeouts(); 2055 2056 if (mGoingToSleepWakeLock.isHeld()) { 2057 mGoingToSleepWakeLock.release(); 2058 } 2059 if (mService.mShuttingDown) { 2060 mService.mGlobalLock.notifyAll(); 2061 } 2062 } 2063 reportResumedActivityLocked(ActivityRecord r)2064 boolean reportResumedActivityLocked(ActivityRecord r) { 2065 // A resumed activity cannot be stopping. remove from list 2066 mStoppingActivities.remove(r); 2067 2068 final ActivityStack stack = r.getActivityStack(); 2069 if (stack.getDisplay().allResumedActivitiesComplete()) { 2070 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS); 2071 // Make sure activity & window visibility should be identical 2072 // for all displays in this stage. 2073 mRootActivityContainer.executeAppTransitionForAllDisplay(); 2074 return true; 2075 } 2076 return false; 2077 } 2078 2079 // Called when WindowManager has finished animating the launchingBehind activity to the back. handleLaunchTaskBehindCompleteLocked(ActivityRecord r)2080 private void handleLaunchTaskBehindCompleteLocked(ActivityRecord r) { 2081 final TaskRecord task = r.getTaskRecord(); 2082 final ActivityStack stack = task.getStack(); 2083 2084 r.mLaunchTaskBehind = false; 2085 mRecentTasks.add(task); 2086 mService.getTaskChangeNotificationController().notifyTaskStackChanged(); 2087 r.setVisibility(false); 2088 2089 // When launching tasks behind, update the last active time of the top task after the new 2090 // task has been shown briefly 2091 final ActivityRecord top = stack.getTopActivity(); 2092 if (top != null) { 2093 top.getTaskRecord().touchActiveTime(); 2094 } 2095 } 2096 scheduleLaunchTaskBehindComplete(IBinder token)2097 void scheduleLaunchTaskBehindComplete(IBinder token) { 2098 mHandler.obtainMessage(LAUNCH_TASK_BEHIND_COMPLETE, token).sendToTarget(); 2099 } 2100 2101 /** Checks whether the userid is a profile of the current user. */ isCurrentProfileLocked(int userId)2102 boolean isCurrentProfileLocked(int userId) { 2103 if (userId == mRootActivityContainer.mCurrentUser) return true; 2104 return mService.mAmInternal.isCurrentProfile(userId); 2105 } 2106 2107 /** 2108 * Returns whether a stopping activity is present that should be stopped after visible, rather 2109 * than idle. 2110 * @return {@code true} if such activity is present. {@code false} otherwise. 2111 */ isStoppingNoHistoryActivity()2112 boolean isStoppingNoHistoryActivity() { 2113 // Activities that are marked as nohistory should be stopped immediately after the resumed 2114 // activity has become visible. 2115 for (ActivityRecord record : mStoppingActivities) { 2116 if (record.isNoHistory()) { 2117 return true; 2118 } 2119 } 2120 2121 return false; 2122 } 2123 processStoppingActivitiesLocked(ActivityRecord idleActivity, boolean remove, boolean processPausingActivities)2124 final ArrayList<ActivityRecord> processStoppingActivitiesLocked(ActivityRecord idleActivity, 2125 boolean remove, boolean processPausingActivities) { 2126 ArrayList<ActivityRecord> stops = null; 2127 2128 final boolean nowVisible = mRootActivityContainer.allResumedActivitiesVisible(); 2129 for (int activityNdx = mStoppingActivities.size() - 1; activityNdx >= 0; --activityNdx) { 2130 ActivityRecord s = mStoppingActivities.get(activityNdx); 2131 2132 final boolean animating = s.mAppWindowToken.isSelfAnimating(); 2133 2134 if (DEBUG_STATES) Slog.v(TAG, "Stopping " + s + ": nowVisible=" + nowVisible 2135 + " animating=" + animating + " finishing=" + s.finishing); 2136 if (nowVisible && s.finishing) { 2137 2138 // If this activity is finishing, it is sitting on top of 2139 // everyone else but we now know it is no longer needed... 2140 // so get rid of it. Otherwise, we need to go through the 2141 // normal flow and hide it once we determine that it is 2142 // hidden by the activities in front of it. 2143 if (DEBUG_STATES) Slog.v(TAG, "Before stopping, can hide: " + s); 2144 s.setVisibility(false); 2145 } 2146 if (remove) { 2147 final ActivityStack stack = s.getActivityStack(); 2148 final boolean shouldSleepOrShutDown = stack != null 2149 ? stack.shouldSleepOrShutDownActivities() 2150 : mService.isSleepingOrShuttingDownLocked(); 2151 if (!animating || shouldSleepOrShutDown) { 2152 if (!processPausingActivities && s.isState(PAUSING)) { 2153 // Defer processing pausing activities in this iteration and reschedule 2154 // a delayed idle to reprocess it again 2155 removeTimeoutsForActivityLocked(idleActivity); 2156 scheduleIdleTimeoutLocked(idleActivity); 2157 continue; 2158 } 2159 2160 if (DEBUG_STATES) Slog.v(TAG, "Ready to stop: " + s); 2161 if (stops == null) { 2162 stops = new ArrayList<>(); 2163 } 2164 stops.add(s); 2165 2166 mStoppingActivities.remove(activityNdx); 2167 } 2168 } 2169 } 2170 2171 return stops; 2172 } 2173 dump(PrintWriter pw, String prefix)2174 public void dump(PrintWriter pw, String prefix) { 2175 pw.println(); 2176 pw.println("ActivityStackSupervisor state:"); 2177 mRootActivityContainer.dump(pw, prefix); 2178 pw.print(prefix); 2179 pw.println("mCurTaskIdForUser=" + mCurTaskIdForUser); 2180 pw.println(prefix + "mUserStackInFront=" + mRootActivityContainer.mUserStackInFront); 2181 if (!mWaitingForActivityVisible.isEmpty()) { 2182 pw.println(prefix + "mWaitingForActivityVisible="); 2183 for (int i = 0; i < mWaitingForActivityVisible.size(); ++i) { 2184 pw.print(prefix + prefix); mWaitingForActivityVisible.get(i).dump(pw, prefix); 2185 } 2186 } 2187 pw.print(prefix); pw.print("isHomeRecentsComponent="); 2188 pw.print(mRecentTasks.isRecentsComponentHomeActivity(mRootActivityContainer.mCurrentUser)); 2189 2190 getKeyguardController().dump(pw, prefix); 2191 mService.getLockTaskController().dump(pw, prefix); 2192 } 2193 printThisActivity(PrintWriter pw, ActivityRecord activity, String dumpPackage, boolean needSep, String prefix)2194 static boolean printThisActivity(PrintWriter pw, ActivityRecord activity, String dumpPackage, 2195 boolean needSep, String prefix) { 2196 if (activity != null) { 2197 if (dumpPackage == null || dumpPackage.equals(activity.packageName)) { 2198 if (needSep) { 2199 pw.println(); 2200 } 2201 pw.print(prefix); 2202 pw.println(activity); 2203 return true; 2204 } 2205 } 2206 return false; 2207 } 2208 dumpHistoryList(FileDescriptor fd, PrintWriter pw, List<ActivityRecord> list, String prefix, String label, boolean complete, boolean brief, boolean client, String dumpPackage, boolean needNL, String header, TaskRecord lastTask)2209 static boolean dumpHistoryList(FileDescriptor fd, PrintWriter pw, List<ActivityRecord> list, 2210 String prefix, String label, boolean complete, boolean brief, boolean client, 2211 String dumpPackage, boolean needNL, String header, TaskRecord lastTask) { 2212 String innerPrefix = null; 2213 String[] args = null; 2214 boolean printed = false; 2215 for (int i=list.size()-1; i>=0; i--) { 2216 final ActivityRecord r = list.get(i); 2217 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) { 2218 continue; 2219 } 2220 if (innerPrefix == null) { 2221 innerPrefix = prefix + " "; 2222 args = new String[0]; 2223 } 2224 printed = true; 2225 final boolean full = !brief && (complete || !r.isInHistory()); 2226 if (needNL) { 2227 pw.println(""); 2228 needNL = false; 2229 } 2230 if (header != null) { 2231 pw.println(header); 2232 header = null; 2233 } 2234 if (lastTask != r.getTaskRecord()) { 2235 lastTask = r.getTaskRecord(); 2236 pw.print(prefix); 2237 pw.print(full ? "* " : " "); 2238 pw.println(lastTask); 2239 if (full) { 2240 lastTask.dump(pw, prefix + " "); 2241 } else if (complete) { 2242 // Complete + brief == give a summary. Isn't that obvious?!? 2243 if (lastTask.intent != null) { 2244 pw.print(prefix); pw.print(" "); 2245 pw.println(lastTask.intent.toInsecureStringWithClip()); 2246 } 2247 } 2248 } 2249 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label); 2250 pw.print(" #"); pw.print(i); pw.print(": "); 2251 pw.println(r); 2252 if (full) { 2253 r.dump(pw, innerPrefix); 2254 } else if (complete) { 2255 // Complete + brief == give a summary. Isn't that obvious?!? 2256 pw.print(innerPrefix); pw.println(r.intent.toInsecureString()); 2257 if (r.app != null) { 2258 pw.print(innerPrefix); pw.println(r.app); 2259 } 2260 } 2261 if (client && r.attachedToProcess()) { 2262 // flush anything that is already in the PrintWriter since the thread is going 2263 // to write to the file descriptor directly 2264 pw.flush(); 2265 try { 2266 TransferPipe tp = new TransferPipe(); 2267 try { 2268 r.app.getThread().dumpActivity( 2269 tp.getWriteFd(), r.appToken, innerPrefix, args); 2270 // Short timeout, since blocking here can deadlock with the application. 2271 tp.go(fd, 2000); 2272 } finally { 2273 tp.kill(); 2274 } 2275 } catch (IOException e) { 2276 pw.println(innerPrefix + "Failure while dumping the activity: " + e); 2277 } catch (RemoteException e) { 2278 pw.println(innerPrefix + "Got a RemoteException while dumping the activity"); 2279 } 2280 needNL = true; 2281 } 2282 } 2283 return printed; 2284 } 2285 scheduleIdleTimeoutLocked(ActivityRecord next)2286 void scheduleIdleTimeoutLocked(ActivityRecord next) { 2287 if (DEBUG_IDLE) Slog.d(TAG_IDLE, 2288 "scheduleIdleTimeoutLocked: Callers=" + Debug.getCallers(4)); 2289 Message msg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG, next); 2290 mHandler.sendMessageDelayed(msg, IDLE_TIMEOUT); 2291 } 2292 scheduleIdleLocked()2293 final void scheduleIdleLocked() { 2294 mHandler.sendEmptyMessage(IDLE_NOW_MSG); 2295 } 2296 2297 /** 2298 * Updates the record of top resumed activity when it changes and handles reporting of the 2299 * state changes to previous and new top activities. It will immediately dispatch top resumed 2300 * state loss message to previous top activity (if haven't done it already). After the previous 2301 * activity releases the top state and reports back, message about acquiring top state will be 2302 * sent to the new top resumed activity. 2303 */ updateTopResumedActivityIfNeeded()2304 void updateTopResumedActivityIfNeeded() { 2305 final ActivityRecord prevTopActivity = mTopResumedActivity; 2306 final ActivityStack topStack = mRootActivityContainer.getTopDisplayFocusedStack(); 2307 if (topStack == null || topStack.mResumedActivity == prevTopActivity) { 2308 return; 2309 } 2310 2311 // Ask previous activity to release the top state. 2312 final boolean prevActivityReceivedTopState = 2313 prevTopActivity != null && !mTopResumedActivityWaitingForPrev; 2314 // mTopResumedActivityWaitingForPrev == true at this point would mean that an activity 2315 // before the prevTopActivity one hasn't reported back yet. So server never sent the top 2316 // resumed state change message to prevTopActivity. 2317 if (prevActivityReceivedTopState 2318 && prevTopActivity.scheduleTopResumedActivityChanged(false /* onTop */)) { 2319 scheduleTopResumedStateLossTimeout(prevTopActivity); 2320 mTopResumedActivityWaitingForPrev = true; 2321 } 2322 2323 // Update the current top activity. 2324 mTopResumedActivity = topStack.mResumedActivity; 2325 scheduleTopResumedActivityStateIfNeeded(); 2326 } 2327 2328 /** Schedule top resumed state change if previous top activity already reported back. */ scheduleTopResumedActivityStateIfNeeded()2329 private void scheduleTopResumedActivityStateIfNeeded() { 2330 if (mTopResumedActivity != null && !mTopResumedActivityWaitingForPrev) { 2331 mTopResumedActivity.scheduleTopResumedActivityChanged(true /* onTop */); 2332 } 2333 } 2334 2335 /** 2336 * Limit the time given to the app to report handling of the state loss. 2337 */ scheduleTopResumedStateLossTimeout(ActivityRecord r)2338 private void scheduleTopResumedStateLossTimeout(ActivityRecord r) { 2339 final Message msg = mHandler.obtainMessage(TOP_RESUMED_STATE_LOSS_TIMEOUT_MSG); 2340 msg.obj = r; 2341 r.topResumedStateLossTime = SystemClock.uptimeMillis(); 2342 mHandler.sendMessageDelayed(msg, TOP_RESUMED_STATE_LOSS_TIMEOUT); 2343 if (DEBUG_STATES) Slog.v(TAG_STATES, "Waiting for top state to be released by " + r); 2344 } 2345 2346 /** 2347 * Handle a loss of top resumed state by an activity - update internal state and inform next top 2348 * activity if needed. 2349 */ handleTopResumedStateReleased(boolean timeout)2350 void handleTopResumedStateReleased(boolean timeout) { 2351 if (DEBUG_STATES) { 2352 Slog.v(TAG_STATES, "Top resumed state released " 2353 + (timeout ? " (due to timeout)" : " (transition complete)")); 2354 } 2355 mHandler.removeMessages(TOP_RESUMED_STATE_LOSS_TIMEOUT_MSG); 2356 if (!mTopResumedActivityWaitingForPrev) { 2357 // Top resumed activity state loss already handled. 2358 return; 2359 } 2360 mTopResumedActivityWaitingForPrev = false; 2361 scheduleTopResumedActivityStateIfNeeded(); 2362 } 2363 removeTimeoutsForActivityLocked(ActivityRecord r)2364 void removeTimeoutsForActivityLocked(ActivityRecord r) { 2365 if (DEBUG_IDLE) Slog.d(TAG_IDLE, "removeTimeoutsForActivity: Callers=" 2366 + Debug.getCallers(4)); 2367 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r); 2368 } 2369 scheduleResumeTopActivities()2370 final void scheduleResumeTopActivities() { 2371 if (!mHandler.hasMessages(RESUME_TOP_ACTIVITY_MSG)) { 2372 mHandler.sendEmptyMessage(RESUME_TOP_ACTIVITY_MSG); 2373 } 2374 } 2375 removeSleepTimeouts()2376 void removeSleepTimeouts() { 2377 mHandler.removeMessages(SLEEP_TIMEOUT_MSG); 2378 } 2379 scheduleSleepTimeout()2380 final void scheduleSleepTimeout() { 2381 removeSleepTimeouts(); 2382 mHandler.sendEmptyMessageDelayed(SLEEP_TIMEOUT_MSG, SLEEP_TIMEOUT); 2383 } 2384 removeRestartTimeouts(ActivityRecord r)2385 void removeRestartTimeouts(ActivityRecord r) { 2386 mHandler.removeMessages(RESTART_ACTIVITY_PROCESS_TIMEOUT_MSG, r); 2387 } 2388 scheduleRestartTimeout(ActivityRecord r)2389 final void scheduleRestartTimeout(ActivityRecord r) { 2390 removeRestartTimeouts(r); 2391 mHandler.sendMessageDelayed(mHandler.obtainMessage(RESTART_ACTIVITY_PROCESS_TIMEOUT_MSG, r), 2392 WindowManagerService.WINDOW_FREEZE_TIMEOUT_DURATION); 2393 } 2394 handleNonResizableTaskIfNeeded(TaskRecord task, int preferredWindowingMode, int preferredDisplayId, ActivityStack actualStack)2395 void handleNonResizableTaskIfNeeded(TaskRecord task, int preferredWindowingMode, 2396 int preferredDisplayId, ActivityStack actualStack) { 2397 handleNonResizableTaskIfNeeded(task, preferredWindowingMode, preferredDisplayId, 2398 actualStack, false /* forceNonResizable */); 2399 } 2400 handleNonResizableTaskIfNeeded(TaskRecord task, int preferredWindowingMode, int preferredDisplayId, ActivityStack actualStack, boolean forceNonResizable)2401 void handleNonResizableTaskIfNeeded(TaskRecord task, int preferredWindowingMode, 2402 int preferredDisplayId, ActivityStack actualStack, boolean forceNonResizable) { 2403 final boolean isSecondaryDisplayPreferred = 2404 (preferredDisplayId != DEFAULT_DISPLAY && preferredDisplayId != INVALID_DISPLAY); 2405 final boolean inSplitScreenMode = actualStack != null 2406 && actualStack.getDisplay().hasSplitScreenPrimaryStack(); 2407 if (((!inSplitScreenMode && preferredWindowingMode != WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) 2408 && !isSecondaryDisplayPreferred) || !task.isActivityTypeStandardOrUndefined()) { 2409 return; 2410 } 2411 2412 // Handle incorrect launch/move to secondary display if needed. 2413 if (isSecondaryDisplayPreferred) { 2414 final int actualDisplayId = task.getStack().mDisplayId; 2415 if (!task.canBeLaunchedOnDisplay(actualDisplayId)) { 2416 throw new IllegalStateException("Task resolved to incompatible display"); 2417 } 2418 2419 final ActivityDisplay preferredDisplay = 2420 mRootActivityContainer.getActivityDisplay(preferredDisplayId); 2421 2422 final boolean singleTaskInstance = preferredDisplay != null 2423 && preferredDisplay.isSingleTaskInstance(); 2424 2425 if (preferredDisplayId != actualDisplayId) { 2426 // Suppress the warning toast if the preferredDisplay was set to singleTask. 2427 // The singleTaskInstance displays will only contain one task and any attempt to 2428 // launch new task will re-route to the default display. 2429 if (singleTaskInstance) { 2430 mService.getTaskChangeNotificationController() 2431 .notifyActivityLaunchOnSecondaryDisplayRerouted(task.getTaskInfo(), 2432 preferredDisplayId); 2433 return; 2434 } 2435 2436 Slog.w(TAG, "Failed to put " + task + " on display " + preferredDisplayId); 2437 // Display a warning toast that we failed to put a task on a secondary display. 2438 mService.getTaskChangeNotificationController() 2439 .notifyActivityLaunchOnSecondaryDisplayFailed(task.getTaskInfo(), 2440 preferredDisplayId); 2441 } else if (!forceNonResizable) { 2442 handleForcedResizableTaskIfNeeded(task, FORCED_RESIZEABLE_REASON_SECONDARY_DISPLAY); 2443 } 2444 // The information about not support secondary display should already be notified, we 2445 // don't want to show another message on default display about split-screen. And it may 2446 // be the case that a resizable activity is launched on a non-resizable task. 2447 return; 2448 } 2449 2450 if (!task.supportsSplitScreenWindowingMode() || forceNonResizable) { 2451 // Dismiss docked stack. If task appeared to be in docked stack but is not resizable - 2452 // we need to move it to top of fullscreen stack, otherwise it will be covered. 2453 2454 final ActivityStack dockedStack = 2455 task.getStack().getDisplay().getSplitScreenPrimaryStack(); 2456 if (dockedStack != null) { 2457 // Display a warning toast that we tried to put an app that doesn't support 2458 // split-screen in split-screen. 2459 mService.getTaskChangeNotificationController() 2460 .notifyActivityDismissingDockedStack(); 2461 moveTasksToFullscreenStackLocked(dockedStack, actualStack == dockedStack); 2462 } 2463 return; 2464 } 2465 2466 handleForcedResizableTaskIfNeeded(task, FORCED_RESIZEABLE_REASON_SPLIT_SCREEN); 2467 } 2468 2469 /** Notifies that the top activity of the task is forced to be resizeable. */ handleForcedResizableTaskIfNeeded(TaskRecord task, int reason)2470 private void handleForcedResizableTaskIfNeeded(TaskRecord task, int reason) { 2471 final ActivityRecord topActivity = task.getTopActivity(); 2472 if (topActivity == null || topActivity.noDisplay 2473 || !topActivity.isNonResizableOrForcedResizable()) { 2474 return; 2475 } 2476 mService.getTaskChangeNotificationController().notifyActivityForcedResizable( 2477 task.taskId, reason, topActivity.appInfo.packageName); 2478 } 2479 activityRelaunchedLocked(IBinder token)2480 void activityRelaunchedLocked(IBinder token) { 2481 mWindowManager.notifyAppRelaunchingFinished(token); 2482 final ActivityRecord r = ActivityRecord.isInStackLocked(token); 2483 if (r != null) { 2484 if (r.getActivityStack().shouldSleepOrShutDownActivities()) { 2485 r.setSleeping(true, true); 2486 } 2487 } 2488 } 2489 activityRelaunchingLocked(ActivityRecord r)2490 void activityRelaunchingLocked(ActivityRecord r) { 2491 mWindowManager.notifyAppRelaunching(r.appToken); 2492 } 2493 logStackState()2494 void logStackState() { 2495 mActivityMetricsLogger.logWindowState(); 2496 } 2497 scheduleUpdateMultiWindowMode(TaskRecord task)2498 void scheduleUpdateMultiWindowMode(TaskRecord task) { 2499 // If the stack is animating in a way where we will be forcing a multi-mode change at the 2500 // end, then ensure that we defer all in between multi-window mode changes 2501 if (task.getStack().deferScheduleMultiWindowModeChanged()) { 2502 return; 2503 } 2504 2505 for (int i = task.mActivities.size() - 1; i >= 0; i--) { 2506 final ActivityRecord r = task.mActivities.get(i); 2507 if (r.attachedToProcess()) { 2508 mMultiWindowModeChangedActivities.add(r); 2509 } 2510 } 2511 2512 if (!mHandler.hasMessages(REPORT_MULTI_WINDOW_MODE_CHANGED_MSG)) { 2513 mHandler.sendEmptyMessage(REPORT_MULTI_WINDOW_MODE_CHANGED_MSG); 2514 } 2515 } 2516 scheduleUpdatePictureInPictureModeIfNeeded(TaskRecord task, ActivityStack prevStack)2517 void scheduleUpdatePictureInPictureModeIfNeeded(TaskRecord task, ActivityStack prevStack) { 2518 final ActivityStack stack = task.getStack(); 2519 if (prevStack == null || prevStack == stack 2520 || (!prevStack.inPinnedWindowingMode() && !stack.inPinnedWindowingMode())) { 2521 return; 2522 } 2523 2524 scheduleUpdatePictureInPictureModeIfNeeded(task, stack.getRequestedOverrideBounds()); 2525 } 2526 scheduleUpdatePictureInPictureModeIfNeeded(TaskRecord task, Rect targetStackBounds)2527 void scheduleUpdatePictureInPictureModeIfNeeded(TaskRecord task, Rect targetStackBounds) { 2528 for (int i = task.mActivities.size() - 1; i >= 0; i--) { 2529 final ActivityRecord r = task.mActivities.get(i); 2530 if (r.attachedToProcess()) { 2531 mPipModeChangedActivities.add(r); 2532 // If we are scheduling pip change, then remove this activity from multi-window 2533 // change list as the processing of pip change will make sure multi-window changed 2534 // message is processed in the right order relative to pip changed. 2535 mMultiWindowModeChangedActivities.remove(r); 2536 } 2537 } 2538 mPipModeChangedTargetStackBounds = targetStackBounds; 2539 2540 if (!mHandler.hasMessages(REPORT_PIP_MODE_CHANGED_MSG)) { 2541 mHandler.sendEmptyMessage(REPORT_PIP_MODE_CHANGED_MSG); 2542 } 2543 } 2544 updatePictureInPictureMode(TaskRecord task, Rect targetStackBounds, boolean forceUpdate)2545 void updatePictureInPictureMode(TaskRecord task, Rect targetStackBounds, boolean forceUpdate) { 2546 mHandler.removeMessages(REPORT_PIP_MODE_CHANGED_MSG); 2547 for (int i = task.mActivities.size() - 1; i >= 0; i--) { 2548 final ActivityRecord r = task.mActivities.get(i); 2549 if (r.attachedToProcess()) { 2550 r.updatePictureInPictureMode(targetStackBounds, forceUpdate); 2551 } 2552 } 2553 } 2554 wakeUp(String reason)2555 void wakeUp(String reason) { 2556 mPowerManager.wakeUp(SystemClock.uptimeMillis(), PowerManager.WAKE_REASON_APPLICATION, 2557 "android.server.am:TURN_ON:" + reason); 2558 } 2559 2560 /** 2561 * Begin deferring resume to avoid duplicate resumes in one pass. 2562 */ beginDeferResume()2563 void beginDeferResume() { 2564 mDeferResumeCount++; 2565 } 2566 2567 /** 2568 * End deferring resume and determine if resume can be called. 2569 */ endDeferResume()2570 void endDeferResume() { 2571 mDeferResumeCount--; 2572 } 2573 2574 /** @return True if resume can be called. */ readyToResume()2575 boolean readyToResume() { 2576 return mDeferResumeCount == 0; 2577 } 2578 2579 private final class ActivityStackSupervisorHandler extends Handler { 2580 ActivityStackSupervisorHandler(Looper looper)2581 public ActivityStackSupervisorHandler(Looper looper) { 2582 super(looper); 2583 } 2584 activityIdleInternal(ActivityRecord r, boolean processPausingActivities)2585 void activityIdleInternal(ActivityRecord r, boolean processPausingActivities) { 2586 synchronized (mService.mGlobalLock) { 2587 activityIdleInternalLocked(r != null ? r.appToken : null, true /* fromTimeout */, 2588 processPausingActivities, null); 2589 } 2590 } 2591 2592 @Override handleMessage(Message msg)2593 public void handleMessage(Message msg) { 2594 switch (msg.what) { 2595 case REPORT_MULTI_WINDOW_MODE_CHANGED_MSG: { 2596 synchronized (mService.mGlobalLock) { 2597 for (int i = mMultiWindowModeChangedActivities.size() - 1; i >= 0; i--) { 2598 final ActivityRecord r = mMultiWindowModeChangedActivities.remove(i); 2599 r.updateMultiWindowMode(); 2600 } 2601 } 2602 } break; 2603 case REPORT_PIP_MODE_CHANGED_MSG: { 2604 synchronized (mService.mGlobalLock) { 2605 for (int i = mPipModeChangedActivities.size() - 1; i >= 0; i--) { 2606 final ActivityRecord r = mPipModeChangedActivities.remove(i); 2607 r.updatePictureInPictureMode(mPipModeChangedTargetStackBounds, 2608 false /* forceUpdate */); 2609 } 2610 } 2611 } break; 2612 case IDLE_TIMEOUT_MSG: { 2613 if (DEBUG_IDLE) Slog.d(TAG_IDLE, 2614 "handleMessage: IDLE_TIMEOUT_MSG: r=" + msg.obj); 2615 // We don't at this point know if the activity is fullscreen, 2616 // so we need to be conservative and assume it isn't. 2617 activityIdleInternal((ActivityRecord) msg.obj, 2618 true /* processPausingActivities */); 2619 } break; 2620 case IDLE_NOW_MSG: { 2621 if (DEBUG_IDLE) Slog.d(TAG_IDLE, "handleMessage: IDLE_NOW_MSG: r=" + msg.obj); 2622 activityIdleInternal((ActivityRecord) msg.obj, 2623 false /* processPausingActivities */); 2624 } break; 2625 case RESUME_TOP_ACTIVITY_MSG: { 2626 synchronized (mService.mGlobalLock) { 2627 mRootActivityContainer.resumeFocusedStacksTopActivities(); 2628 } 2629 } break; 2630 case SLEEP_TIMEOUT_MSG: { 2631 synchronized (mService.mGlobalLock) { 2632 if (mService.isSleepingOrShuttingDownLocked()) { 2633 Slog.w(TAG, "Sleep timeout! Sleeping now."); 2634 checkReadyForSleepLocked(false /* allowDelay */); 2635 } 2636 } 2637 } break; 2638 case LAUNCH_TIMEOUT_MSG: { 2639 synchronized (mService.mGlobalLock) { 2640 if (mLaunchingActivityWakeLock.isHeld()) { 2641 Slog.w(TAG, "Launch timeout has expired, giving up wake lock!"); 2642 if (VALIDATE_WAKE_LOCK_CALLER 2643 && Binder.getCallingUid() != Process.myUid()) { 2644 throw new IllegalStateException("Calling must be system uid"); 2645 } 2646 mLaunchingActivityWakeLock.release(); 2647 } 2648 } 2649 } break; 2650 case LAUNCH_TASK_BEHIND_COMPLETE: { 2651 synchronized (mService.mGlobalLock) { 2652 ActivityRecord r = ActivityRecord.forTokenLocked((IBinder) msg.obj); 2653 if (r != null) { 2654 handleLaunchTaskBehindCompleteLocked(r); 2655 } 2656 } 2657 } break; 2658 case RESTART_ACTIVITY_PROCESS_TIMEOUT_MSG: { 2659 final ActivityRecord r = (ActivityRecord) msg.obj; 2660 String processName = null; 2661 int uid = 0; 2662 synchronized (mService.mGlobalLock) { 2663 if (r.attachedToProcess() 2664 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) { 2665 processName = r.app.mName; 2666 uid = r.app.mUid; 2667 } 2668 } 2669 if (processName != null) { 2670 mService.mAmInternal.killProcess(processName, uid, 2671 "restartActivityProcessTimeout"); 2672 } 2673 } break; 2674 case REPORT_HOME_CHANGED_MSG: { 2675 synchronized (mService.mGlobalLock) { 2676 mHandler.removeMessages(REPORT_HOME_CHANGED_MSG); 2677 2678 // Start home activities on displays with no activities. 2679 mRootActivityContainer.startHomeOnEmptyDisplays("homeChanged"); 2680 } 2681 } break; 2682 case TOP_RESUMED_STATE_LOSS_TIMEOUT_MSG: { 2683 ActivityRecord r = (ActivityRecord) msg.obj; 2684 Slog.w(TAG, "Activity top resumed state loss timeout for " + r); 2685 synchronized (mService.mGlobalLock) { 2686 if (r.hasProcess()) { 2687 mService.logAppTooSlow(r.app, r.topResumedStateLossTime, 2688 "top state loss for " + r); 2689 } 2690 } 2691 handleTopResumedStateReleased(true /* timeout */); 2692 } break; 2693 } 2694 } 2695 } 2696 2697 /** 2698 * Puts a task into resizing mode during the next app transition. 2699 * 2700 * @param task The task to put into resizing mode 2701 */ setResizingDuringAnimation(TaskRecord task)2702 void setResizingDuringAnimation(TaskRecord task) { 2703 mResizingTasksDuringAnimation.add(task.taskId); 2704 task.setTaskDockedResizing(true); 2705 } 2706 startActivityFromRecents(int callingPid, int callingUid, int taskId, SafeActivityOptions options)2707 int startActivityFromRecents(int callingPid, int callingUid, int taskId, 2708 SafeActivityOptions options) { 2709 TaskRecord task = null; 2710 final String callingPackage; 2711 final Intent intent; 2712 final int userId; 2713 int activityType = ACTIVITY_TYPE_UNDEFINED; 2714 int windowingMode = WINDOWING_MODE_UNDEFINED; 2715 final ActivityOptions activityOptions = options != null 2716 ? options.getOptions(this) 2717 : null; 2718 if (activityOptions != null) { 2719 activityType = activityOptions.getLaunchActivityType(); 2720 windowingMode = activityOptions.getLaunchWindowingMode(); 2721 if (activityOptions.freezeRecentTasksReordering() 2722 && mRecentTasks.isCallerRecents(callingUid)) { 2723 mRecentTasks.setFreezeTaskListReordering(); 2724 } 2725 } 2726 if (activityType == ACTIVITY_TYPE_HOME || activityType == ACTIVITY_TYPE_RECENTS) { 2727 throw new IllegalArgumentException("startActivityFromRecents: Task " 2728 + taskId + " can't be launch in the home/recents stack."); 2729 } 2730 2731 mWindowManager.deferSurfaceLayout(); 2732 try { 2733 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) { 2734 mWindowManager.setDockedStackCreateState( 2735 activityOptions.getSplitScreenCreateMode(), null /* initialBounds */); 2736 2737 // Defer updating the stack in which recents is until the app transition is done, to 2738 // not run into issues where we still need to draw the task in recents but the 2739 // docked stack is already created. 2740 deferUpdateRecentsHomeStackBounds(); 2741 // TODO(multi-display): currently recents animation only support default display. 2742 mWindowManager.prepareAppTransition(TRANSIT_DOCK_TASK_FROM_RECENTS, false); 2743 } 2744 2745 task = mRootActivityContainer.anyTaskForId(taskId, 2746 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE, activityOptions, ON_TOP); 2747 if (task == null) { 2748 continueUpdateRecentsHomeStackBounds(); 2749 mWindowManager.executeAppTransition(); 2750 throw new IllegalArgumentException( 2751 "startActivityFromRecents: Task " + taskId + " not found."); 2752 } 2753 2754 if (windowingMode != WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) { 2755 // We always want to return to the home activity instead of the recents activity 2756 // from whatever is started from the recents activity, so move the home stack 2757 // forward. 2758 // TODO (b/115289124): Multi-display supports for recents. 2759 mRootActivityContainer.getDefaultDisplay().moveHomeStackToFront( 2760 "startActivityFromRecents"); 2761 } 2762 2763 // If the user must confirm credentials (e.g. when first launching a work app and the 2764 // Work Challenge is present) let startActivityInPackage handle the intercepting. 2765 if (!mService.mAmInternal.shouldConfirmCredentials(task.userId) 2766 && task.getRootActivity() != null) { 2767 final ActivityRecord targetActivity = task.getTopActivity(); 2768 2769 mRootActivityContainer.sendPowerHintForLaunchStartIfNeeded( 2770 true /* forceSend */, targetActivity); 2771 mActivityMetricsLogger.notifyActivityLaunching(task.intent); 2772 try { 2773 mService.moveTaskToFrontLocked(null /* appThread */, null /* callingPackage */, 2774 task.taskId, 0, options, true /* fromRecents */); 2775 // Apply options to prevent pendingOptions be taken by client to make sure 2776 // the override pending app transition will be applied immediately. 2777 targetActivity.applyOptionsLocked(); 2778 } finally { 2779 mActivityMetricsLogger.notifyActivityLaunched(START_TASK_TO_FRONT, 2780 targetActivity); 2781 } 2782 2783 mService.getActivityStartController().postStartActivityProcessingForLastStarter( 2784 task.getTopActivity(), ActivityManager.START_TASK_TO_FRONT, 2785 task.getStack()); 2786 return ActivityManager.START_TASK_TO_FRONT; 2787 } 2788 callingPackage = task.mCallingPackage; 2789 intent = task.intent; 2790 intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY); 2791 userId = task.userId; 2792 return mService.getActivityStartController().startActivityInPackage( 2793 task.mCallingUid, callingPid, callingUid, callingPackage, intent, null, null, 2794 null, 0, 0, options, userId, task, "startActivityFromRecents", 2795 false /* validateIncomingUser */, null /* originatingPendingIntent */, 2796 false /* allowBackgroundActivityStart */); 2797 } finally { 2798 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY && task != null) { 2799 // If we are launching the task in the docked stack, put it into resizing mode so 2800 // the window renders full-screen with the background filling the void. Also only 2801 // call this at the end to make sure that tasks exists on the window manager side. 2802 setResizingDuringAnimation(task); 2803 2804 final ActivityDisplay display = task.getStack().getDisplay(); 2805 final ActivityStack topSecondaryStack = 2806 display.getTopStackInWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_SECONDARY); 2807 if (topSecondaryStack.isActivityTypeHome()) { 2808 // If the home activity is the top split-screen secondary stack, then the 2809 // primary split-screen stack is in the minimized mode which means it can't 2810 // receive input keys, so we should move the focused app to the home app so that 2811 // window manager can correctly calculate the focus window that can receive 2812 // input keys. 2813 display.moveHomeStackToFront( 2814 "startActivityFromRecents: homeVisibleInSplitScreen"); 2815 2816 // Immediately update the minimized docked stack mode, the upcoming animation 2817 // for the docked activity (WMS.overridePendingAppTransitionMultiThumbFuture) 2818 // will do the animation to the target bounds 2819 mWindowManager.checkSplitScreenMinimizedChanged(false /* animate */); 2820 } 2821 } 2822 mWindowManager.continueSurfaceLayout(); 2823 } 2824 } 2825 2826 /** 2827 * Internal container to store a match qualifier alongside a WaitResult. 2828 */ 2829 static class WaitInfo { 2830 private final ComponentName mTargetComponent; 2831 private final WaitResult mResult; 2832 /** Time stamp when we started to wait for {@link WaitResult}. */ 2833 private final long mStartTimeMs; 2834 WaitInfo(ComponentName targetComponent, WaitResult result, long startTimeMs)2835 WaitInfo(ComponentName targetComponent, WaitResult result, long startTimeMs) { 2836 this.mTargetComponent = targetComponent; 2837 this.mResult = result; 2838 this.mStartTimeMs = startTimeMs; 2839 } 2840 matches(ComponentName targetComponent)2841 public boolean matches(ComponentName targetComponent) { 2842 return mTargetComponent == null || mTargetComponent.equals(targetComponent); 2843 } 2844 getResult()2845 public WaitResult getResult() { 2846 return mResult; 2847 } 2848 getStartTime()2849 public long getStartTime() { 2850 return mStartTimeMs; 2851 } 2852 getComponent()2853 public ComponentName getComponent() { 2854 return mTargetComponent; 2855 } 2856 dump(PrintWriter pw, String prefix)2857 public void dump(PrintWriter pw, String prefix) { 2858 pw.println(prefix + "WaitInfo:"); 2859 pw.println(prefix + " mTargetComponent=" + mTargetComponent); 2860 pw.println(prefix + " mResult="); 2861 mResult.dump(pw, prefix); 2862 } 2863 } 2864 } 2865