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