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