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