1 /*
2  * Copyright (C) 2014 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 android.app;
18 
19 import android.annotation.NonNull;
20 import android.annotation.Nullable;
21 import android.content.ComponentName;
22 import android.content.IIntentReceiver;
23 import android.content.IIntentSender;
24 import android.content.Intent;
25 import android.content.pm.ActivityInfo;
26 import android.content.pm.ActivityPresentationInfo;
27 import android.content.pm.ApplicationInfo;
28 import android.content.pm.UserInfo;
29 import android.os.Bundle;
30 import android.os.IBinder;
31 import android.os.TransactionTooLargeException;
32 
33 import java.util.ArrayList;
34 import java.util.List;
35 
36 /**
37  * Activity manager local system service interface.
38  *
39  * @hide Only for use within the system server.
40  */
41 public abstract class ActivityManagerInternal {
42 
43 
44     // Access modes for handleIncomingUser.
45     public static final int ALLOW_NON_FULL = 0;
46     public static final int ALLOW_NON_FULL_IN_PROFILE = 1;
47     public static final int ALLOW_FULL_ONLY = 2;
48 
49     /**
50      * Verify that calling app has access to the given provider.
51      */
checkContentProviderAccess(String authority, int userId)52     public abstract String checkContentProviderAccess(String authority, int userId);
53 
54     // Called by the power manager.
onWakefulnessChanged(int wakefulness)55     public abstract void onWakefulnessChanged(int wakefulness);
56 
57     /**
58      * @return {@code true} if process start is successful, {@code false} otherwise.
59      */
startIsolatedProcess(String entryPoint, String[] mainArgs, String processName, String abiOverride, int uid, Runnable crashHandler)60     public abstract boolean startIsolatedProcess(String entryPoint, String[] mainArgs,
61             String processName, String abiOverride, int uid, Runnable crashHandler);
62 
63     /**
64      * Kill foreground apps from the specified user.
65      */
killForegroundAppsForUser(int userHandle)66     public abstract void killForegroundAppsForUser(int userHandle);
67 
68     /**
69      *  Sets how long a {@link PendingIntent} can be temporarily whitelist to by bypass restrictions
70      *  such as Power Save mode.
71      */
setPendingIntentWhitelistDuration(IIntentSender target, IBinder whitelistToken, long duration)72     public abstract void setPendingIntentWhitelistDuration(IIntentSender target,
73             IBinder whitelistToken, long duration);
74 
75     /**
76      * Allows for a {@link PendingIntent} to be whitelisted to start activities from background.
77      */
setPendingIntentAllowBgActivityStarts( IIntentSender target, IBinder whitelistToken, int flags)78     public abstract void setPendingIntentAllowBgActivityStarts(
79             IIntentSender target, IBinder whitelistToken, int flags);
80 
81     /**
82      * Voids {@link PendingIntent}'s privilege to be whitelisted to start activities from
83      * background.
84      */
clearPendingIntentAllowBgActivityStarts(IIntentSender target, IBinder whitelistToken)85     public abstract void clearPendingIntentAllowBgActivityStarts(IIntentSender target,
86             IBinder whitelistToken);
87 
88     /**
89      * Allow DeviceIdleController to tell us about what apps are whitelisted.
90      */
setDeviceIdleWhitelist(int[] allAppids, int[] exceptIdleAppids)91     public abstract void setDeviceIdleWhitelist(int[] allAppids, int[] exceptIdleAppids);
92 
93     /**
94      * Update information about which app IDs are on the temp whitelist.
95      */
updateDeviceIdleTempWhitelist(int[] appids, int changingAppId, boolean adding)96     public abstract void updateDeviceIdleTempWhitelist(int[] appids, int changingAppId,
97             boolean adding);
98 
99     /**
100      * Get the procstate for the UID.  The return value will be between
101      * {@link ActivityManager#MIN_PROCESS_STATE} and {@link ActivityManager#MAX_PROCESS_STATE}.
102      * Note if the UID doesn't exist, it'll return {@link ActivityManager#PROCESS_STATE_NONEXISTENT}
103      * (-1).
104      */
getUidProcessState(int uid)105     public abstract int getUidProcessState(int uid);
106 
107     /**
108      * @return {@code true} if system is ready, {@code false} otherwise.
109      */
isSystemReady()110     public abstract boolean isSystemReady();
111 
112     /**
113      * Sets if the given pid has an overlay UI or not.
114      *
115      * @param pid The pid we are setting overlay UI for.
116      * @param hasOverlayUi True if the process has overlay UI.
117      * @see android.view.WindowManager.LayoutParams#TYPE_APPLICATION_OVERLAY
118      */
setHasOverlayUi(int pid, boolean hasOverlayUi)119     public abstract void setHasOverlayUi(int pid, boolean hasOverlayUi);
120 
121     /**
122      * Called after the network policy rules are updated by
123      * {@link com.android.server.net.NetworkPolicyManagerService} for a specific {@param uid} and
124      * {@param procStateSeq}.
125      */
notifyNetworkPolicyRulesUpdated(int uid, long procStateSeq)126     public abstract void notifyNetworkPolicyRulesUpdated(int uid, long procStateSeq);
127 
128     /**
129      * @return true if runtime was restarted, false if it's normal boot
130      */
isRuntimeRestarted()131     public abstract boolean isRuntimeRestarted();
132 
133     /**
134      * Returns if more users can be started without stopping currently running users.
135      */
canStartMoreUsers()136     public abstract boolean canStartMoreUsers();
137 
138     /**
139      * Sets the user switcher message for switching from {@link android.os.UserHandle#SYSTEM}.
140      */
setSwitchingFromSystemUserMessage(String switchingFromSystemUserMessage)141     public abstract void setSwitchingFromSystemUserMessage(String switchingFromSystemUserMessage);
142 
143     /**
144      * Sets the user switcher message for switching to {@link android.os.UserHandle#SYSTEM}.
145      */
setSwitchingToSystemUserMessage(String switchingToSystemUserMessage)146     public abstract void setSwitchingToSystemUserMessage(String switchingToSystemUserMessage);
147 
148     /**
149      * Returns maximum number of users that can run simultaneously.
150      */
getMaxRunningUsers()151     public abstract int getMaxRunningUsers();
152 
153     /**
154      * Whether an UID is active or idle.
155      */
isUidActive(int uid)156     public abstract boolean isUidActive(int uid);
157 
158     /**
159      * Returns a list of running processes along with corresponding uids, pids and their oom score.
160      *
161      * Only processes managed by ActivityManagerService are included.
162      */
getMemoryStateForProcesses()163     public abstract List<ProcessMemoryState> getMemoryStateForProcesses();
164 
165     /**
166      * Checks to see if the calling pid is allowed to handle the user. Returns adjusted user id as
167      * needed.
168      */
handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll, int allowMode, String name, String callerPackage)169     public abstract int handleIncomingUser(int callingPid, int callingUid, int userId,
170             boolean allowAll, int allowMode, String name, String callerPackage);
171 
172     /** Checks if the calling binder pid as the permission. */
enforceCallingPermission(String permission, String func)173     public abstract void enforceCallingPermission(String permission, String func);
174 
175     /** Returns the current user id. */
getCurrentUserId()176     public abstract int getCurrentUserId();
177 
178     /** Returns true if the user is running. */
isUserRunning(int userId, int flags)179     public abstract boolean isUserRunning(int userId, int flags);
180 
181     /** Trims memory usage in the system by removing/stopping unused application processes. */
trimApplications()182     public abstract void trimApplications();
183 
184     /** Kill the processes in the list due to their tasks been removed. */
killProcessesForRemovedTask(ArrayList<Object> procsToKill)185     public abstract void killProcessesForRemovedTask(ArrayList<Object> procsToKill);
186 
187     /** Kill the process immediately. */
killProcess(String processName, int uid, String reason)188     public abstract void killProcess(String processName, int uid, String reason);
189 
190     /**
191      * Returns {@code true} if {@code uid} is running an activity from {@code packageName}.
192      */
hasRunningActivity(int uid, @Nullable String packageName)193     public abstract boolean hasRunningActivity(int uid, @Nullable String packageName);
194 
updateOomAdj()195     public abstract void updateOomAdj();
updateCpuStats()196     public abstract void updateCpuStats();
197 
198     /**
199      * Update battery stats on activity usage.
200      * @param activity
201      * @param uid
202      * @param userId
203      * @param started
204      */
updateBatteryStats( ComponentName activity, int uid, int userId, boolean resumed)205     public abstract void updateBatteryStats(
206             ComponentName activity, int uid, int userId, boolean resumed);
207 
208     /**
209      * Update UsageStats of the activity.
210      * @param activity
211      * @param userId
212      * @param event
213      * @param appToken ActivityRecord's appToken.
214      * @param taskRoot TaskRecord's root
215      */
updateActivityUsageStats( ComponentName activity, int userId, int event, IBinder appToken, ComponentName taskRoot)216     public abstract void updateActivityUsageStats(
217             ComponentName activity, int userId, int event, IBinder appToken,
218             ComponentName taskRoot);
updateForegroundTimeIfOnBattery( String packageName, int uid, long cpuTimeDiff)219     public abstract void updateForegroundTimeIfOnBattery(
220             String packageName, int uid, long cpuTimeDiff);
sendForegroundProfileChanged(int userId)221     public abstract void sendForegroundProfileChanged(int userId);
222 
223     /**
224      * Returns whether the given user requires credential entry at this time. This is used to
225      * intercept activity launches for work apps when the Work Challenge is present.
226      */
shouldConfirmCredentials(int userId)227     public abstract boolean shouldConfirmCredentials(int userId);
228 
getCurrentProfileIds()229     public abstract int[] getCurrentProfileIds();
getCurrentUser()230     public abstract UserInfo getCurrentUser();
ensureNotSpecialUser(int userId)231     public abstract void ensureNotSpecialUser(int userId);
isCurrentProfile(int userId)232     public abstract boolean isCurrentProfile(int userId);
hasStartedUserState(int userId)233     public abstract boolean hasStartedUserState(int userId);
finishUserSwitch(Object uss)234     public abstract void finishUserSwitch(Object uss);
235 
236     /** Schedule the execution of all pending app GCs. */
scheduleAppGcs()237     public abstract void scheduleAppGcs();
238 
239     /** Gets the task id for a given activity. */
getTaskIdForActivity(@onNull IBinder token, boolean onlyRoot)240     public abstract int getTaskIdForActivity(@NonNull IBinder token, boolean onlyRoot);
241 
242     /** Gets the basic info for a given activity. */
getActivityPresentationInfo(@onNull IBinder token)243     public abstract ActivityPresentationInfo getActivityPresentationInfo(@NonNull IBinder token);
244 
setBooting(boolean booting)245     public abstract void setBooting(boolean booting);
isBooting()246     public abstract boolean isBooting();
setBooted(boolean booted)247     public abstract void setBooted(boolean booted);
isBooted()248     public abstract boolean isBooted();
finishBooting()249     public abstract void finishBooting();
250 
tempWhitelistForPendingIntent(int callerPid, int callerUid, int targetUid, long duration, String tag)251     public abstract void tempWhitelistForPendingIntent(int callerPid, int callerUid, int targetUid,
252             long duration, String tag);
broadcastIntentInPackage(String packageName, int uid, int realCallingUid, int realCallingPid, Intent intent, String resolvedType, IIntentReceiver resultTo, int resultCode, String resultData, Bundle resultExtras, String requiredPermission, Bundle bOptions, boolean serialized, boolean sticky, int userId, boolean allowBackgroundActivityStarts)253     public abstract int broadcastIntentInPackage(String packageName, int uid, int realCallingUid,
254             int realCallingPid, Intent intent, String resolvedType, IIntentReceiver resultTo,
255             int resultCode, String resultData, Bundle resultExtras, String requiredPermission,
256             Bundle bOptions, boolean serialized, boolean sticky, int userId,
257             boolean allowBackgroundActivityStarts);
startServiceInPackage(int uid, Intent service, String resolvedType, boolean fgRequired, String callingPackage, int userId, boolean allowBackgroundActivityStarts)258     public abstract ComponentName startServiceInPackage(int uid, Intent service,
259             String resolvedType, boolean fgRequired, String callingPackage, int userId,
260             boolean allowBackgroundActivityStarts) throws TransactionTooLargeException;
261 
disconnectActivityFromServices(Object connectionHolder, Object conns)262     public abstract void disconnectActivityFromServices(Object connectionHolder, Object conns);
cleanUpServices(int userId, ComponentName component, Intent baseIntent)263     public abstract void cleanUpServices(int userId, ComponentName component, Intent baseIntent);
getActivityInfoForUser(ActivityInfo aInfo, int userId)264     public abstract ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId);
ensureBootCompleted()265     public abstract void ensureBootCompleted();
updateOomLevelsForDisplay(int displayId)266     public abstract void updateOomLevelsForDisplay(int displayId);
isActivityStartsLoggingEnabled()267     public abstract boolean isActivityStartsLoggingEnabled();
268     /** Returns true if the background activity starts is enabled. */
isBackgroundActivityStartsEnabled()269     public abstract boolean isBackgroundActivityStartsEnabled();
reportCurKeyguardUsageEvent(boolean keyguardShowing)270     public abstract void reportCurKeyguardUsageEvent(boolean keyguardShowing);
271 
272     /** Input dispatch timeout to a window, start the ANR process. */
inputDispatchingTimedOut(int pid, boolean aboveSystem, String reason)273     public abstract long inputDispatchingTimedOut(int pid, boolean aboveSystem, String reason);
inputDispatchingTimedOut(Object proc, String activityShortComponentName, ApplicationInfo aInfo, String parentShortComponentName, Object parentProc, boolean aboveSystem, String reason)274     public abstract boolean inputDispatchingTimedOut(Object proc, String activityShortComponentName,
275             ApplicationInfo aInfo, String parentShortComponentName, Object parentProc,
276             boolean aboveSystem, String reason);
277 
278     /**
279      * Sends {@link android.content.Intent#ACTION_CONFIGURATION_CHANGED} with all the appropriate
280      * flags.
281      */
broadcastGlobalConfigurationChanged(int changes, boolean initLocale)282     public abstract void broadcastGlobalConfigurationChanged(int changes, boolean initLocale);
283 
284     /**
285      * Sends {@link android.content.Intent#ACTION_CLOSE_SYSTEM_DIALOGS} with all the appropriate
286      * flags.
287      */
broadcastCloseSystemDialogs(String reason)288     public abstract void broadcastCloseSystemDialogs(String reason);
289 
290     /**
291      * Kills all background processes, except those matching any of the specified properties.
292      *
293      * @param minTargetSdk the target SDK version at or above which to preserve processes,
294      *                     or {@code -1} to ignore the target SDK
295      * @param maxProcState the process state at or below which to preserve processes,
296      *                     or {@code -1} to ignore the process state
297      */
killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState)298     public abstract void killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState);
299 
300     /** Starts a given process. */
startProcess(String processName, ApplicationInfo info, boolean knownToBeDead, boolean isTop, String hostingType, ComponentName hostingName)301     public abstract void startProcess(String processName, ApplicationInfo info,
302             boolean knownToBeDead, boolean isTop, String hostingType, ComponentName hostingName);
303 
304     /** Starts up the starting activity process for debugging if needed.
305      * This function needs to be called synchronously from WindowManager context so the caller
306      * passes a lock {@code wmLock} and waits to be notified.
307      *
308      * @param wmLock calls {@code notify} on the object to wake up the caller.
309     */
setDebugFlagsForStartingActivity(ActivityInfo aInfo, int startFlags, ProfilerInfo profilerInfo, Object wmLock)310     public abstract void setDebugFlagsForStartingActivity(ActivityInfo aInfo, int startFlags,
311             ProfilerInfo profilerInfo, Object wmLock);
312 
313     /** Returns mount mode for process running with given pid */
getStorageMountMode(int pid, int uid)314     public abstract int getStorageMountMode(int pid, int uid);
315 
316     /** Returns true if the given uid is the app in the foreground. */
isAppForeground(int uid)317     public abstract boolean isAppForeground(int uid);
318 
319     /** Returns true if the given uid is currently marked 'bad' */
isAppBad(ApplicationInfo info)320     public abstract boolean isAppBad(ApplicationInfo info);
321 
322     /** Remove pending backup for the given userId. */
clearPendingBackup(int userId)323     public abstract void clearPendingBackup(int userId);
324 
325     /**
326      * When power button is very long pressed, call this interface to do some pre-shutdown work
327      * like persisting database etc.
328      */
prepareForPossibleShutdown()329     public abstract void prepareForPossibleShutdown();
330 
331     /**
332      * Returns {@code true} if {@code uid} is running a foreground service of a specific
333      * {@code foregroundServiceType}.
334      */
hasRunningForegroundService(int uid, int foregroundServiceType)335     public abstract boolean hasRunningForegroundService(int uid, int foregroundServiceType);
336 
337     /**
338      * Registers the specified {@code processObserver} to be notified of future changes to
339      * process state.
340      */
registerProcessObserver(IProcessObserver processObserver)341     public abstract void registerProcessObserver(IProcessObserver processObserver);
342 
343     /**
344      * Unregisters the specified {@code processObserver}.
345      */
unregisterProcessObserver(IProcessObserver processObserver)346     public abstract void unregisterProcessObserver(IProcessObserver processObserver);
347 
348     /** Returns true if the given UID is registered as an active instrumentation. */
isActiveInstrumentation(int uid)349     public abstract boolean isActiveInstrumentation(int uid);
350 }
351