1 /* 2 * Copyright (C) 2018 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 android.annotation.NonNull; 20 import android.annotation.Nullable; 21 import android.annotation.UserIdInt; 22 import android.app.ActivityManager; 23 import android.app.AppProtoEnums; 24 import android.app.IActivityManager; 25 import android.app.IApplicationThread; 26 import android.app.ProfilerInfo; 27 import android.content.ComponentName; 28 import android.content.IIntentSender; 29 import android.content.Intent; 30 import android.content.pm.ApplicationInfo; 31 import android.content.res.CompatibilityInfo; 32 import android.os.Bundle; 33 import android.os.IBinder; 34 import android.os.LocaleList; 35 import android.os.RemoteException; 36 import android.service.voice.IVoiceInteractionSession; 37 import android.util.IntArray; 38 import android.util.proto.ProtoOutputStream; 39 import android.window.TaskSnapshot; 40 41 import com.android.internal.annotations.VisibleForTesting; 42 import com.android.internal.app.IVoiceInteractor; 43 import com.android.server.am.PendingIntentRecord; 44 import com.android.server.am.UserState; 45 46 import java.io.FileDescriptor; 47 import java.io.PrintWriter; 48 import java.lang.ref.WeakReference; 49 import java.util.List; 50 import java.util.Set; 51 52 /** 53 * Activity Task manager local system service interface. 54 * @hide Only for use within system server 55 */ 56 public abstract class ActivityTaskManagerInternal { 57 58 /** 59 * Type for {@link #notifyAppTransitionStarting}: The transition was started because we drew 60 * the splash screen. 61 */ 62 public static final int APP_TRANSITION_SPLASH_SCREEN = 63 AppProtoEnums.APP_TRANSITION_SPLASH_SCREEN; // 1 64 65 /** 66 * Type for {@link #notifyAppTransitionStarting}: The transition was started because we all 67 * app windows were drawn 68 */ 69 public static final int APP_TRANSITION_WINDOWS_DRAWN = 70 AppProtoEnums.APP_TRANSITION_WINDOWS_DRAWN; // 2 71 72 /** 73 * Type for {@link #notifyAppTransitionStarting}: The transition was started because of a 74 * timeout. 75 */ 76 public static final int APP_TRANSITION_TIMEOUT = 77 AppProtoEnums.APP_TRANSITION_TIMEOUT; // 3 78 79 /** 80 * Type for {@link #notifyAppTransitionStarting}: The transition was started because of a 81 * we drew a task snapshot. 82 */ 83 public static final int APP_TRANSITION_SNAPSHOT = 84 AppProtoEnums.APP_TRANSITION_SNAPSHOT; // 4 85 86 /** 87 * Type for {@link #notifyAppTransitionStarting}: The transition was started because it was a 88 * recents animation and we only needed to wait on the wallpaper. 89 */ 90 public static final int APP_TRANSITION_RECENTS_ANIM = 91 AppProtoEnums.APP_TRANSITION_RECENTS_ANIM; // 5 92 93 /** 94 * The id of the task source of assist state. 95 */ 96 public static final String ASSIST_TASK_ID = "taskId"; 97 98 /** 99 * The id of the activity source of assist state. 100 */ 101 public static final String ASSIST_ACTIVITY_ID = "activityId"; 102 103 /** 104 * The bundle key to extract the assist data. 105 */ 106 public static final String ASSIST_KEY_DATA = "data"; 107 108 /** 109 * The bundle key to extract the assist structure. 110 */ 111 public static final String ASSIST_KEY_STRUCTURE = "structure"; 112 113 /** 114 * The bundle key to extract the assist content. 115 */ 116 public static final String ASSIST_KEY_CONTENT = "content"; 117 118 /** 119 * The bundle key to extract the assist receiver extras. 120 */ 121 public static final String ASSIST_KEY_RECEIVER_EXTRAS = "receiverExtras"; 122 123 public interface ScreenObserver { onAwakeStateChanged(boolean isAwake)124 void onAwakeStateChanged(boolean isAwake); onKeyguardStateChanged(boolean isShowing)125 void onKeyguardStateChanged(boolean isShowing); 126 } 127 128 /** 129 * Sleep tokens cause the activity manager to put the top activity to sleep. 130 * They are used by components such as dreams that may hide and block interaction 131 * with underlying activities. 132 * The Acquirer provides an interface that encapsulates the underlying work, so the user does 133 * not need to handle the token by him/herself. 134 */ 135 public interface SleepTokenAcquirer { 136 137 /** 138 * Acquires a sleep token. 139 * @param displayId The display to apply to. 140 */ acquire(int displayId)141 void acquire(int displayId); 142 143 /** 144 * Releases the sleep token. 145 * @param displayId The display to apply to. 146 */ release(int displayId)147 void release(int displayId); 148 } 149 150 /** 151 * Creates a sleep token acquirer for the specified display with the specified tag. 152 * 153 * @param tag A string identifying the purpose (eg. "Dream"). 154 */ createSleepTokenAcquirer(@onNull String tag)155 public abstract SleepTokenAcquirer createSleepTokenAcquirer(@NonNull String tag); 156 157 /** 158 * Returns home activity for the specified user. 159 * 160 * @param userId ID of the user or {@link android.os.UserHandle#USER_ALL} 161 */ getHomeActivityForUser(int userId)162 public abstract ComponentName getHomeActivityForUser(int userId); 163 onLocalVoiceInteractionStarted(IBinder callingActivity, IVoiceInteractionSession mSession, IVoiceInteractor mInteractor)164 public abstract void onLocalVoiceInteractionStarted(IBinder callingActivity, 165 IVoiceInteractionSession mSession, 166 IVoiceInteractor mInteractor); 167 168 /** 169 * Returns the top activity from each of the currently visible root tasks, and the related task 170 * id. The first entry will be the focused activity. 171 */ getTopVisibleActivities()172 public abstract List<ActivityAssistInfo> getTopVisibleActivities(); 173 174 /** 175 * Returns whether {@code uid} has any resumed activity. 176 */ hasResumedActivity(int uid)177 public abstract boolean hasResumedActivity(int uid); 178 179 /** 180 * Start activity {@code intents} as if {@code packageName/featureId} on user {@code userId} did 181 * it. 182 * 183 * - DO NOT call it with the calling UID cleared. 184 * - All the necessary caller permission checks must be done at callsites. 185 * 186 * @return error codes used by {@link IActivityManager#startActivity} and its siblings. 187 */ startActivitiesAsPackage(String packageName, String featureId, int userId, Intent[] intents, Bundle bOptions)188 public abstract int startActivitiesAsPackage(String packageName, String featureId, 189 int userId, Intent[] intents, Bundle bOptions); 190 191 /** 192 * Start intents as a package. 193 * 194 * @param uid Make a call as if this UID did. 195 * @param realCallingPid PID of the real caller. 196 * @param realCallingUid UID of the real caller. 197 * @param callingPackage Make a call as if this package did. 198 * @param callingFeatureId Make a call as if this feature in the package did. 199 * @param intents Intents to start. 200 * @param userId Start the intents on this user. 201 * @param validateIncomingUser Set true to skip checking {@code userId} with the calling UID. 202 * @param originatingPendingIntent PendingIntentRecord that originated this activity start or 203 * null if not originated by PendingIntent 204 * @param allowBackgroundActivityStart Whether the background activity start should be allowed 205 * from originatingPendingIntent 206 */ startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid, String callingPackage, @Nullable String callingFeatureId, Intent[] intents, String[] resolvedTypes, IBinder resultTo, SafeActivityOptions options, int userId, boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent, boolean allowBackgroundActivityStart)207 public abstract int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid, 208 String callingPackage, @Nullable String callingFeatureId, Intent[] intents, 209 String[] resolvedTypes, IBinder resultTo, SafeActivityOptions options, int userId, 210 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent, 211 boolean allowBackgroundActivityStart); 212 startActivityInPackage(int uid, int realCallingPid, int realCallingUid, String callingPackage, @Nullable String callingFeaturId, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, SafeActivityOptions options, int userId, Task inTask, String reason, boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent, boolean allowBackgroundActivityStart)213 public abstract int startActivityInPackage(int uid, int realCallingPid, int realCallingUid, 214 String callingPackage, @Nullable String callingFeaturId, Intent intent, 215 String resolvedType, IBinder resultTo, String resultWho, int requestCode, 216 int startFlags, SafeActivityOptions options, int userId, Task inTask, String reason, 217 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent, 218 boolean allowBackgroundActivityStart); 219 220 /** 221 * Callback to be called on certain activity start scenarios. 222 * 223 * @see BackgroundActivityStartCallback 224 */ setBackgroundActivityStartCallback( @ullable BackgroundActivityStartCallback callback)225 public abstract void setBackgroundActivityStartCallback( 226 @Nullable BackgroundActivityStartCallback callback); 227 228 /** 229 * Sets the list of UIDs that contain an active accessibility service. 230 */ setAccessibilityServiceUids(IntArray uids)231 public abstract void setAccessibilityServiceUids(IntArray uids); 232 233 /** 234 * Start activity {@code intent} without calling user-id check. 235 * 236 * - DO NOT call it with the calling UID cleared. 237 * - The caller must do the calling user ID check. 238 * 239 * @return error codes used by {@link IActivityManager#startActivity} and its siblings. 240 */ startActivityAsUser(IApplicationThread caller, String callingPackage, @Nullable String callingFeatureId, Intent intent, @Nullable IBinder resultTo, int startFlags, @Nullable Bundle options, int userId)241 public abstract int startActivityAsUser(IApplicationThread caller, String callingPackage, 242 @Nullable String callingFeatureId, Intent intent, @Nullable IBinder resultTo, 243 int startFlags, @Nullable Bundle options, int userId); 244 245 /** 246 * Called after virtual display Id is updated by 247 * {@link com.android.server.vr.Vr2dDisplay} with a specific 248 * {@param vr2dDisplayId}. 249 */ setVr2dDisplayId(int vr2dDisplayId)250 public abstract void setVr2dDisplayId(int vr2dDisplayId); 251 252 /** 253 * Set focus on an activity. 254 * @param token The activity token. 255 */ setFocusedActivity(IBinder token)256 public abstract void setFocusedActivity(IBinder token); 257 registerScreenObserver(ScreenObserver observer)258 public abstract void registerScreenObserver(ScreenObserver observer); 259 260 /** 261 * Returns is the caller has the same uid as the Recents component 262 */ isCallerRecents(int callingUid)263 public abstract boolean isCallerRecents(int callingUid); 264 265 /** 266 * Returns whether the recents component is the home activity for the given user. 267 */ isRecentsComponentHomeActivity(int userId)268 public abstract boolean isRecentsComponentHomeActivity(int userId); 269 270 /** 271 * Returns true if the app can close system dialogs. Otherwise it either throws a {@link 272 * SecurityException} or returns false with a logcat message depending on whether the app 273 * targets SDK level {@link android.os.Build.VERSION_CODES#S} or not. 274 */ checkCanCloseSystemDialogs(int pid, int uid, @Nullable String packageName)275 public abstract boolean checkCanCloseSystemDialogs(int pid, int uid, 276 @Nullable String packageName); 277 278 /** 279 * Returns whether the app can close system dialogs or not. 280 */ canCloseSystemDialogs(int pid, int uid)281 public abstract boolean canCloseSystemDialogs(int pid, int uid); 282 283 /** 284 * Called after the voice interaction service has changed. 285 */ notifyActiveVoiceInteractionServiceChanged(ComponentName component)286 public abstract void notifyActiveVoiceInteractionServiceChanged(ComponentName component); 287 288 /** 289 * Called when the device changes its dreaming state. 290 * 291 * @param activeDreamComponent The currently active dream. If null, the device is not dreaming. 292 */ notifyActiveDreamChanged(@ullable ComponentName activeDreamComponent)293 public abstract void notifyActiveDreamChanged(@Nullable ComponentName activeDreamComponent); 294 295 /** 296 * Set a uid that is allowed to bypass stopped app switches, launching an app 297 * whenever it wants. 298 * 299 * @param type Type of the caller -- unique string the caller supplies to identify itself 300 * and disambiguate with other calles. 301 * @param uid The uid of the app to be allowed, or -1 to clear the uid for this type. 302 * @param userId The user it is allowed for. 303 */ setAllowAppSwitches(@onNull String type, int uid, int userId)304 public abstract void setAllowAppSwitches(@NonNull String type, int uid, int userId); 305 306 /** 307 * Called when a user has been stopped. 308 * 309 * @param userId The user being stopped. 310 */ onUserStopped(int userId)311 public abstract void onUserStopped(int userId); isGetTasksAllowed(String caller, int callingPid, int callingUid)312 public abstract boolean isGetTasksAllowed(String caller, int callingPid, int callingUid); 313 onProcessAdded(WindowProcessController proc)314 public abstract void onProcessAdded(WindowProcessController proc); onProcessRemoved(String name, int uid)315 public abstract void onProcessRemoved(String name, int uid); onCleanUpApplicationRecord(WindowProcessController proc)316 public abstract void onCleanUpApplicationRecord(WindowProcessController proc); getTopProcessState()317 public abstract int getTopProcessState(); clearHeavyWeightProcessIfEquals(WindowProcessController proc)318 public abstract void clearHeavyWeightProcessIfEquals(WindowProcessController proc); finishHeavyWeightApp()319 public abstract void finishHeavyWeightApp(); 320 isSleeping()321 public abstract boolean isSleeping(); isShuttingDown()322 public abstract boolean isShuttingDown(); shuttingDown(boolean booted, int timeout)323 public abstract boolean shuttingDown(boolean booted, int timeout); enableScreenAfterBoot(boolean booted)324 public abstract void enableScreenAfterBoot(boolean booted); showStrictModeViolationDialog()325 public abstract boolean showStrictModeViolationDialog(); showSystemReadyErrorDialogsIfNeeded()326 public abstract void showSystemReadyErrorDialogsIfNeeded(); 327 onProcessMapped(int pid, WindowProcessController proc)328 public abstract void onProcessMapped(int pid, WindowProcessController proc); onProcessUnMapped(int pid)329 public abstract void onProcessUnMapped(int pid); 330 onPackageDataCleared(String name, int userId)331 public abstract void onPackageDataCleared(String name, int userId); onPackageUninstalled(String name, int userId)332 public abstract void onPackageUninstalled(String name, int userId); onPackageAdded(String name, boolean replacing)333 public abstract void onPackageAdded(String name, boolean replacing); onPackageReplaced(ApplicationInfo aInfo)334 public abstract void onPackageReplaced(ApplicationInfo aInfo); 335 compatibilityInfoForPackage(ApplicationInfo ai)336 public abstract CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai); 337 338 public final class ActivityTokens { 339 private final @NonNull IBinder mActivityToken; 340 private final @NonNull IBinder mAssistToken; 341 private final @NonNull IBinder mShareableActivityToken; 342 private final @NonNull IApplicationThread mAppThread; 343 private final int mUid; 344 ActivityTokens(@onNull IBinder activityToken, @NonNull IBinder assistToken, @NonNull IApplicationThread appThread, @NonNull IBinder shareableActivityToken, int uid)345 public ActivityTokens(@NonNull IBinder activityToken, 346 @NonNull IBinder assistToken, @NonNull IApplicationThread appThread, 347 @NonNull IBinder shareableActivityToken, int uid) { 348 mActivityToken = activityToken; 349 mAssistToken = assistToken; 350 mAppThread = appThread; 351 mShareableActivityToken = shareableActivityToken; 352 mUid = uid; 353 } 354 355 /** 356 * @return The activity token. 357 */ getActivityToken()358 public @NonNull IBinder getActivityToken() { 359 return mActivityToken; 360 } 361 362 /** 363 * @return The assist token. 364 */ getAssistToken()365 public @NonNull IBinder getAssistToken() { 366 return mAssistToken; 367 } 368 369 /** 370 * @return The sharable activity token.. 371 */ getShareableActivityToken()372 public @NonNull IBinder getShareableActivityToken() { 373 return mShareableActivityToken; 374 } 375 376 /** 377 * @return The assist token. 378 */ getApplicationThread()379 public @NonNull IApplicationThread getApplicationThread() { 380 return mAppThread; 381 } 382 383 /** 384 * @return The UID of the activity 385 */ getUid()386 public int getUid() { 387 return mUid; 388 } 389 } 390 sendActivityResult(int callingUid, IBinder activityToken, String resultWho, int requestCode, int resultCode, Intent data)391 public abstract void sendActivityResult(int callingUid, IBinder activityToken, 392 String resultWho, int requestCode, int resultCode, Intent data); clearPendingResultForActivity( IBinder activityToken, WeakReference<PendingIntentRecord> pir)393 public abstract void clearPendingResultForActivity( 394 IBinder activityToken, WeakReference<PendingIntentRecord> pir); 395 396 /** Returns the component name of the activity token. */ 397 @Nullable getActivityName(IBinder activityToken)398 public abstract ComponentName getActivityName(IBinder activityToken); 399 400 /** 401 * Returns non-finishing Activity that have a process attached for the given task and the token 402 * with the activity token and the IApplicationThread or null if there is no Activity with a 403 * valid process. Given the null token for the task will return the top Activity in the task. 404 * 405 * @param taskId the Activity task id. 406 * @param token the Activity token, set null if get top Activity for the given task id. 407 */ 408 @Nullable getAttachedNonFinishingActivityForTask(int taskId, IBinder token)409 public abstract ActivityTokens getAttachedNonFinishingActivityForTask(int taskId, 410 IBinder token); 411 getIntentSender(int type, String packageName, @Nullable String featureId, int callingUid, int userId, IBinder token, String resultWho, int requestCode, Intent[] intents, String[] resolvedTypes, int flags, Bundle bOptions)412 public abstract IIntentSender getIntentSender(int type, String packageName, 413 @Nullable String featureId, int callingUid, int userId, IBinder token, String resultWho, 414 int requestCode, Intent[] intents, String[] resolvedTypes, int flags, 415 Bundle bOptions); 416 417 /** @return the service connection holder for a given activity token. */ getServiceConnectionsHolder(IBinder token)418 public abstract ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token); 419 420 /** @return The intent used to launch the home activity. */ getHomeIntent()421 public abstract Intent getHomeIntent(); startHomeActivity(int userId, String reason)422 public abstract boolean startHomeActivity(int userId, String reason); 423 /** 424 * This starts home activity on displays that can have system decorations based on displayId - 425 * Default display always use primary home component. 426 * For Secondary displays, the home activity must have category SECONDARY_HOME and then resolves 427 * according to the priorities listed below. 428 * - If default home is not set, always use the secondary home defined in the config. 429 * - Use currently selected primary home activity. 430 * - Use the activity in the same package as currently selected primary home activity. 431 * If there are multiple activities matched, use first one. 432 * - Use the secondary home defined in the config. 433 */ startHomeOnDisplay(int userId, String reason, int displayId, boolean allowInstrumenting, boolean fromHomeKey)434 public abstract boolean startHomeOnDisplay(int userId, String reason, int displayId, 435 boolean allowInstrumenting, boolean fromHomeKey); 436 /** Start home activities on all displays that support system decorations. */ startHomeOnAllDisplays(int userId, String reason)437 public abstract boolean startHomeOnAllDisplays(int userId, String reason); 438 /** @return true if the given process is the factory test process. */ isFactoryTestProcess(WindowProcessController wpc)439 public abstract boolean isFactoryTestProcess(WindowProcessController wpc); updateTopComponentForFactoryTest()440 public abstract void updateTopComponentForFactoryTest(); handleAppDied(WindowProcessController wpc, boolean restarting, Runnable finishInstrumentationCallback)441 public abstract void handleAppDied(WindowProcessController wpc, boolean restarting, 442 Runnable finishInstrumentationCallback); closeSystemDialogs(String reason)443 public abstract void closeSystemDialogs(String reason); 444 445 /** Removes all components (e.g. activities, recents, ...) belonging to a disabled package. */ cleanupDisabledPackageComponents( String packageName, Set<String> disabledClasses, int userId, boolean booted)446 public abstract void cleanupDisabledPackageComponents( 447 String packageName, Set<String> disabledClasses, int userId, boolean booted); 448 449 /** Called whenever AM force stops a package. */ onForceStopPackage(String packageName, boolean doit, boolean evenPersistent, int userId)450 public abstract boolean onForceStopPackage(String packageName, boolean doit, 451 boolean evenPersistent, int userId); 452 /** 453 * Resumes all top activities in the system if they aren't resumed already. 454 * @param scheduleIdle If the idle message should be schedule after the top activities are 455 * resumed. 456 */ resumeTopActivities(boolean scheduleIdle)457 public abstract void resumeTopActivities(boolean scheduleIdle); 458 459 /** Called by AM just before it binds to an application process. */ preBindApplication(WindowProcessController wpc)460 public abstract void preBindApplication(WindowProcessController wpc); 461 462 /** Called by AM when an application process attaches. */ attachApplication(WindowProcessController wpc)463 public abstract boolean attachApplication(WindowProcessController wpc) throws RemoteException; 464 465 /** @see IActivityManager#notifyLockedProfile(int) */ notifyLockedProfile(@serIdInt int userId, int currentUserId)466 public abstract void notifyLockedProfile(@UserIdInt int userId, int currentUserId); 467 468 /** @see IActivityManager#startConfirmDeviceCredentialIntent(Intent, Bundle) */ startConfirmDeviceCredentialIntent(Intent intent, Bundle options)469 public abstract void startConfirmDeviceCredentialIntent(Intent intent, Bundle options); 470 471 /** Writes current activity states to the proto stream. */ writeActivitiesToProto(ProtoOutputStream proto)472 public abstract void writeActivitiesToProto(ProtoOutputStream proto); 473 474 /** Dump the current state based on the command. */ dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, boolean dumpClient, String dumpPackage)475 public abstract void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, 476 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage); 477 478 /** Dump the current state for inclusion in process dump. */ dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll, String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode, int wakefulness)479 public abstract boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll, 480 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode, 481 int wakefulness); 482 483 /** Writes the current window process states to the proto stream. */ writeProcessesToProto(ProtoOutputStream proto, String dumpPackage, int wakeFullness, boolean testPssMode)484 public abstract void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage, 485 int wakeFullness, boolean testPssMode); 486 487 /** Dump the current activities state. */ dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args, int opti, boolean dumpAll, boolean dumpVisibleRootTasksOnly, boolean dumpFocusedRootTaskOnly, @UserIdInt int userId)488 public abstract boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, 489 String[] args, int opti, boolean dumpAll, boolean dumpVisibleRootTasksOnly, 490 boolean dumpFocusedRootTaskOnly, @UserIdInt int userId); 491 492 /** Dump the current state for inclusion in oom dump. */ dumpForOom(PrintWriter pw)493 public abstract void dumpForOom(PrintWriter pw); 494 495 /** @return true if it the activity management system is okay with GC running now. */ canGcNow()496 public abstract boolean canGcNow(); 497 498 /** @return the process for the top-most resumed activity in the system. */ getTopApp()499 public abstract WindowProcessController getTopApp(); 500 501 /** Destroy all activities. */ scheduleDestroyAllActivities(String reason)502 public abstract void scheduleDestroyAllActivities(String reason); 503 504 /** Remove user association with activities. */ removeUser(int userId)505 public abstract void removeUser(int userId); 506 507 /** Switch current focused user for activities. */ switchUser(int userId, UserState userState)508 public abstract boolean switchUser(int userId, UserState userState); 509 510 /** Called whenever an app crashes. */ onHandleAppCrash(WindowProcessController wpc)511 public abstract void onHandleAppCrash(WindowProcessController wpc); 512 513 /** 514 * Finish the topmost activities in all stacks that belong to the crashed app. 515 * @param crashedApp The app that crashed. 516 * @param reason Reason to perform this action. 517 * @return The task id that was finished in this stack, or INVALID_TASK_ID if none was finished. 518 */ finishTopCrashedActivities( WindowProcessController crashedApp, String reason)519 public abstract int finishTopCrashedActivities( 520 WindowProcessController crashedApp, String reason); 521 onUidActive(int uid, int procState)522 public abstract void onUidActive(int uid, int procState); onUidInactive(int uid)523 public abstract void onUidInactive(int uid); onUidProcStateChanged(int uid, int procState)524 public abstract void onUidProcStateChanged(int uid, int procState); 525 526 /** Handle app crash event in {@link android.app.IActivityController} if there is one. */ handleAppCrashInActivityController(String processName, int pid, String shortMsg, String longMsg, long timeMillis, String stackTrace, Runnable killCrashingAppCallback)527 public abstract boolean handleAppCrashInActivityController(String processName, int pid, 528 String shortMsg, String longMsg, long timeMillis, String stackTrace, 529 Runnable killCrashingAppCallback); 530 removeRecentTasksByPackageName(String packageName, int userId)531 public abstract void removeRecentTasksByPackageName(String packageName, int userId); cleanupRecentTasksForUser(int userId)532 public abstract void cleanupRecentTasksForUser(int userId); loadRecentTasksForUser(int userId)533 public abstract void loadRecentTasksForUser(int userId); onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId)534 public abstract void onPackagesSuspendedChanged(String[] packages, boolean suspended, 535 int userId); 536 /** Flush recent tasks to disk. */ flushRecentTasks()537 public abstract void flushRecentTasks(); 538 clearLockedTasks(String reason)539 public abstract void clearLockedTasks(String reason); updateUserConfiguration()540 public abstract void updateUserConfiguration(); canShowErrorDialogs()541 public abstract boolean canShowErrorDialogs(); 542 setProfileApp(String profileApp)543 public abstract void setProfileApp(String profileApp); setProfileProc(WindowProcessController wpc)544 public abstract void setProfileProc(WindowProcessController wpc); setProfilerInfo(ProfilerInfo profilerInfo)545 public abstract void setProfilerInfo(ProfilerInfo profilerInfo); 546 getLaunchObserverRegistry()547 public abstract ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry(); 548 549 /** 550 * Returns the URI permission owner associated with the given activity (see 551 * {@link ActivityRecord#getUriPermissionsLocked()}). If the passed-in activity token is 552 * invalid, returns null. 553 */ 554 @Nullable getUriPermissionOwnerForActivity(@onNull IBinder activityToken)555 public abstract IBinder getUriPermissionOwnerForActivity(@NonNull IBinder activityToken); 556 557 /** 558 * Gets bitmap snapshot of the provided task id. 559 * 560 * <p>Warning! this may restore the snapshot from disk so can block, don't call in a latency 561 * sensitive environment. 562 */ getTaskSnapshotBlocking(int taskId, boolean isLowResolution)563 public abstract TaskSnapshot getTaskSnapshotBlocking(int taskId, 564 boolean isLowResolution); 565 566 /** Returns true if uid is considered foreground for activity start purposes. */ isUidForeground(int uid)567 public abstract boolean isUidForeground(int uid); 568 569 /** 570 * Called by DevicePolicyManagerService to set the uid of the device owner. 571 */ setDeviceOwnerUid(int uid)572 public abstract void setDeviceOwnerUid(int uid); 573 574 /** 575 * Set all associated companion app that belongs to a userId. 576 * @param userId 577 * @param companionAppUids ActivityTaskManager will take ownership of this Set, the caller 578 * shouldn't touch the Set after calling this interface. 579 */ setCompanionAppUids(int userId, Set<Integer> companionAppUids)580 public abstract void setCompanionAppUids(int userId, Set<Integer> companionAppUids); 581 582 /** 583 * @param packageName The package to check 584 * @return Whether the package is the base of any locked task 585 */ isBaseOfLockedTask(String packageName)586 public abstract boolean isBaseOfLockedTask(String packageName); 587 588 /** 589 * Creates an interface to update configuration for the calling application. 590 */ createPackageConfigurationUpdater()591 public abstract PackageConfigurationUpdater createPackageConfigurationUpdater(); 592 593 /** 594 * Creates an interface to update configuration for an arbitrary application specified by it's 595 * packageName and userId. 596 */ createPackageConfigurationUpdater( String packageName, int userId)597 public abstract PackageConfigurationUpdater createPackageConfigurationUpdater( 598 String packageName, int userId); 599 600 /** 601 * Retrieves and returns the app-specific configuration for an arbitrary application specified 602 * by its packageName and userId. Returns null if no app-specific configuration has been set. 603 */ 604 @Nullable getApplicationConfig(String packageName, int userId)605 public abstract PackageConfig getApplicationConfig(String packageName, 606 int userId); 607 608 /** 609 * Holds app-specific configurations. 610 */ 611 public static class PackageConfig { 612 /** 613 * nightMode for the application, null if app-specific nightMode is not set. 614 */ 615 @Nullable 616 public final Integer mNightMode; 617 618 /** 619 * {@link LocaleList} for the application, null if app-specific locales are not set. 620 */ 621 @Nullable 622 public final LocaleList mLocales; 623 624 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE) PackageConfig(Integer nightMode, LocaleList locales)625 public PackageConfig(Integer nightMode, LocaleList locales) { 626 mNightMode = nightMode; 627 mLocales = locales; 628 } 629 630 /** 631 * Returns the string representation of the app-specific configuration. 632 */ 633 @Override toString()634 public String toString() { 635 return "PackageConfig: nightMode " + mNightMode + " locales " + mLocales; 636 } 637 } 638 639 /** 640 * An interface to update configuration for an application, and will persist override 641 * configuration for this package. 642 */ 643 public interface PackageConfigurationUpdater { 644 /** 645 * Sets the dark mode for the current application. This setting is persisted and will 646 * override the system configuration for this application. 647 */ setNightMode(int nightMode)648 PackageConfigurationUpdater setNightMode(int nightMode); 649 650 /** 651 * Sets the app-specific locales for the application referenced by this updater. 652 * This setting is persisted and will overlay on top of the system locales for 653 * the said application. 654 * @return the current {@link PackageConfigurationUpdater} updated with the provided locale. 655 * 656 * <p>NOTE: This method should not be called by clients directly to set app locales, 657 * instead use the {@link LocaleManagerService#setApplicationLocales} 658 */ setLocales(LocaleList locales)659 PackageConfigurationUpdater setLocales(LocaleList locales); 660 661 /** 662 * Commit changes. 663 * @return true if the configuration changes were persisted, 664 * false if there were no changes, or if erroneous inputs were provided, such as: 665 * <ui> 666 * <li>Invalid packageName</li> 667 * <li>Invalid userId</li> 668 * <li>no WindowProcessController found for the package</li> 669 * </ui> 670 */ commit()671 boolean commit(); 672 } 673 674 /** 675 * A utility method to check AppOps and PackageManager for SYSTEM_ALERT_WINDOW permission. 676 */ hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage)677 public abstract boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, 678 String callingPackage); 679 680 /** 681 * Registers a callback which can intercept activity starts. 682 * @throws IllegalArgumentException if duplicate ids are provided 683 */ registerActivityStartInterceptor( @ctivityInterceptorCallback.OrderedId int id, ActivityInterceptorCallback callback)684 public abstract void registerActivityStartInterceptor( 685 @ActivityInterceptorCallback.OrderedId int id, 686 ActivityInterceptorCallback callback); 687 688 /** Get the most recent task excluding the first running task (the one on the front most). */ getMostRecentTaskFromBackground()689 public abstract ActivityManager.RecentTaskInfo getMostRecentTaskFromBackground(); 690 691 /** Get the app tasks for a package */ getAppTasks(String pkgName, int uid)692 public abstract List<ActivityManager.AppTask> getAppTasks(String pkgName, int uid); 693 694 /** 695 * Determine if there exists a task which meets the criteria set by the PermissionPolicyService 696 * to show a system-owned permission dialog over, for a given package 697 * @see PermissionPolicyInternal.shouldShowNotificationDialogForTask 698 * 699 * @param pkgName The package whose activity must be top 700 * @param uid The uid that must have a top activity 701 * @return a task ID if a valid task ID is found. Otherwise, return INVALID_TASK_ID 702 */ getTaskToShowPermissionDialogOn(String pkgName, int uid)703 public abstract int getTaskToShowPermissionDialogOn(String pkgName, int uid); 704 705 /** 706 * Attempts to restart the process associated with the top most Activity associated with the 707 * given {@code packageName} in the task associated with the given {@code taskId}. 708 * 709 * This will request the process of the activity to restart with its saved state (via 710 * {@link android.app.Activity#onSaveInstanceState(Bundle)}) if possible. If the activity is in 711 * background the process will be killed keeping its record. 712 */ restartTaskActivityProcessIfVisible( int taskId, @NonNull String packageName)713 public abstract void restartTaskActivityProcessIfVisible( 714 int taskId, @NonNull String packageName); 715 } 716