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