1 /**
2  * Copyright (C) 2014 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5  * use this file except in compliance with the License. You may obtain a copy
6  * 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, WITHOUT
12  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13  * License for the specific language governing permissions and limitations
14  * under the License.
15  */
16 
17 package android.app.usage;
18 
19 import android.annotation.CurrentTimeMillisLong;
20 import android.annotation.ElapsedRealtimeLong;
21 import android.annotation.NonNull;
22 import android.annotation.Nullable;
23 import android.annotation.UserIdInt;
24 import android.app.ActivityManager.ProcessState;
25 import android.app.usage.UsageStatsManager.StandbyBuckets;
26 import android.content.ComponentName;
27 import android.content.LocusId;
28 import android.content.res.Configuration;
29 import android.os.IBinder;
30 import android.os.SystemClock;
31 import android.os.UserHandle;
32 import android.os.UserManager;
33 
34 import java.util.List;
35 import java.util.Set;
36 
37 /**
38  * UsageStatsManager local system service interface.
39  *
40  * {@hide} Only for use within the system server.
41  */
42 public abstract class UsageStatsManagerInternal {
43 
44     /**
45      * Reports an event to the UsageStatsManager. <br/>
46      * <em>Note: Starting from {@link android.os.Build.VERSION_CODES#R Android R}, if the user's
47      * device is not in an unlocked state (as defined by {@link UserManager#isUserUnlocked()}),
48      * then this event will be added to a queue and processed once the device is unlocked.</em>
49      *
50      * @param component The component for which this event occurred.
51      * @param userId The user id to which the component belongs to.
52      * @param eventType The event that occurred. Valid values can be found at
53      *                  {@link UsageEvents}
54      * @param instanceId For activity, hashCode of ActivityRecord's appToken.
55      *                   For non-activity, it is not used.
56      * @param taskRoot For activity, the name of the package at the root of the task
57      *                 For non-activity, it is not used.
58      */
reportEvent(ComponentName component, @UserIdInt int userId, int eventType, int instanceId, ComponentName taskRoot)59     public abstract void reportEvent(ComponentName component, @UserIdInt int userId, int eventType,
60             int instanceId, ComponentName taskRoot);
61 
62     /**
63      * Reports an event to the UsageStatsManager. <br/>
64      * <em>Note: Starting from {@link android.os.Build.VERSION_CODES#R Android R}, if the user's
65      * device is not in an unlocked state (as defined by {@link UserManager#isUserUnlocked()}),
66      * then this event will be added to a queue and processed once the device is unlocked.</em>
67      *
68      * @param packageName The package for which this event occurred.
69      * @param userId The user id to which the component belongs to.
70      * @param eventType The event that occurred. Valid values can be found at
71      * {@link UsageEvents}
72      */
reportEvent(String packageName, @UserIdInt int userId, int eventType)73     public abstract void reportEvent(String packageName, @UserIdInt int userId, int eventType);
74 
75     /**
76      * Reports a configuration change to the UsageStatsManager. <br/>
77      * <em>Note: Starting from {@link android.os.Build.VERSION_CODES#R Android R}, if the user's
78      * device is not in an unlocked state (as defined by {@link UserManager#isUserUnlocked()}),
79      * then this event will be added to a queue and processed once the device is unlocked.</em>
80      *
81      * @param config The new device configuration.
82      */
reportConfigurationChange(Configuration config, @UserIdInt int userId)83     public abstract void reportConfigurationChange(Configuration config, @UserIdInt int userId);
84 
85     /**
86      * Reports that an application has posted an interruptive notification. <br/>
87      * <em>Note: Starting from {@link android.os.Build.VERSION_CODES#R Android R}, if the user's
88      * device is not in an unlocked state (as defined by {@link UserManager#isUserUnlocked()}),
89      * then this event will be added to a queue and processed once the device is unlocked.</em>
90      *
91      * @param packageName The package name of the app that posted the notification
92      * @param channelId The ID of the NotificationChannel to which the notification was posted
93      * @param userId The user in which the notification was posted
94      */
reportInterruptiveNotification(String packageName, String channelId, @UserIdInt int userId)95     public abstract void reportInterruptiveNotification(String packageName, String channelId,
96             @UserIdInt int userId);
97 
98     /**
99      * Reports that an action equivalent to a ShortcutInfo is taken by the user. <br/>
100      * <em>Note: Starting from {@link android.os.Build.VERSION_CODES#R Android R}, if the user's
101      * device is not in an unlocked state (as defined by {@link UserManager#isUserUnlocked()}),
102      * then this event will be added to a queue and processed once the device is unlocked.</em>
103      *
104      * @param packageName The package name of the shortcut publisher
105      * @param shortcutId The ID of the shortcut in question
106      * @param userId The user in which the content provider was accessed.
107      *
108      * @see android.content.pm.ShortcutManager#reportShortcutUsed(String)
109      */
reportShortcutUsage(String packageName, String shortcutId, @UserIdInt int userId)110     public abstract void reportShortcutUsage(String packageName, String shortcutId,
111             @UserIdInt int userId);
112 
113     /**
114      * Reports that a content provider has been accessed by a foreground app.
115      * @param name The authority of the content provider
116      * @param pkgName The package name of the content provider
117      * @param userId The user in which the content provider was accessed.
118      */
reportContentProviderUsage(String name, String pkgName, @UserIdInt int userId)119     public abstract void reportContentProviderUsage(String name, String pkgName,
120             @UserIdInt int userId);
121 
122 
123     /**
124      * Reports locusId update for a given activity.
125      *
126      * @param activity The component name of the app.
127      * @param userId The user id of who uses the app.
128      * @param locusId The locusId a unique, stable id that identifies this activity.
129      * @param appToken ActivityRecord's appToken.
130      * {@link UsageEvents}
131      * @hide
132      */
reportLocusUpdate(@onNull ComponentName activity, @UserIdInt int userId, @Nullable LocusId locusId, @NonNull IBinder appToken)133     public abstract void reportLocusUpdate(@NonNull ComponentName activity, @UserIdInt int userId,
134             @Nullable LocusId locusId, @NonNull IBinder appToken);
135 
136     /**
137      * Prepares the UsageStatsService for shutdown.
138      */
prepareShutdown()139     public abstract void prepareShutdown();
140 
141     /**
142      * When the device power button is long pressed for 3.5 seconds, prepareForPossibleShutdown()
143      * is called.
144      */
prepareForPossibleShutdown()145     public abstract void prepareForPossibleShutdown();
146 
147     /**
148      * Returns true if the app has not been used for a certain amount of time. How much time?
149      * Could be hours, could be days, who knows?
150      *
151      * @param packageName
152      * @param uidForAppId The uid of the app, which will be used for its app id
153      * @param userId
154      * @return
155      */
isAppIdle(String packageName, int uidForAppId, @UserIdInt int userId)156     public abstract boolean isAppIdle(String packageName, int uidForAppId, @UserIdInt int userId);
157 
158     /**
159      * Returns the app standby bucket that the app is currently in.  This accessor does
160      * <em>not</em> obfuscate instant apps.
161      *
162      * @param packageName
163      * @param userId
164      * @param nowElapsed The current time, in the elapsedRealtime time base
165      * @return the AppStandby bucket code the app currently resides in.  If the app is
166      *     unknown in the given user, STANDBY_BUCKET_NEVER is returned.
167      */
getAppStandbyBucket(String packageName, @UserIdInt int userId, long nowElapsed)168     @StandbyBuckets public abstract int getAppStandbyBucket(String packageName,
169             @UserIdInt int userId, long nowElapsed);
170 
171     /**
172      * Returns all of the uids for a given user where all packages associating with that uid
173      * are in the app idle state -- there are no associated apps that are not idle.  This means
174      * all of the returned uids can be safely considered app idle.
175      */
getIdleUidsForUser(@serIdInt int userId)176     public abstract int[] getIdleUidsForUser(@UserIdInt int userId);
177 
178     /**  Backup/Restore API */
getBackupPayload(@serIdInt int userId, String key)179     public abstract byte[] getBackupPayload(@UserIdInt int userId, String key);
180 
181     /**
182      * ?
183      * @param userId
184      * @param key
185      * @param payload
186      */
applyRestoredPayload(@serIdInt int userId, String key, byte[] payload)187     public abstract void applyRestoredPayload(@UserIdInt int userId, String key, byte[] payload);
188 
189     /**
190      * Called by DevicePolicyManagerService to inform that a new admin has been added.
191      *
192      * @param packageName the package in which the admin component is part of.
193      * @param userId the userId in which the admin has been added.
194      */
onActiveAdminAdded(String packageName, int userId)195     public abstract void onActiveAdminAdded(String packageName, int userId);
196 
197     /**
198      * Called by DevicePolicyManagerService to inform about the active admins in an user.
199      *
200      * @param adminApps the set of active admins in {@param userId} or null if there are none.
201      * @param userId the userId to which the admin apps belong.
202      */
setActiveAdminApps(Set<String> adminApps, int userId)203     public abstract void setActiveAdminApps(Set<String> adminApps, int userId);
204 
205     /**
206      * Called by DevicePolicyManagerService to inform about the protected packages for a user.
207      * User control will be disabled for protected packages.
208      *
209      * @param packageNames the set of protected packages for {@code userId}.
210      * @param userId the userId to which the protected packages belong.
211      */
setAdminProtectedPackages(@ullable Set<String> packageNames, @UserIdInt int userId)212     public abstract void setAdminProtectedPackages(@Nullable Set<String> packageNames,
213             @UserIdInt int userId);
214 
215     /**
216      * Called by DevicePolicyManagerService during boot to inform that admin data is loaded and
217      * pushed to UsageStatsService.
218      */
onAdminDataAvailable()219     public abstract void onAdminDataAvailable();
220 
221     /**
222      * Return usage stats.
223      *
224      * @param obfuscateInstantApps whether instant app package names need to be obfuscated in the
225      *     result.
226      */
queryUsageStatsForUser(@serIdInt int userId, int interval, long beginTime, long endTime, boolean obfuscateInstantApps)227     public abstract List<UsageStats> queryUsageStatsForUser(@UserIdInt int userId, int interval,
228             long beginTime, long endTime, boolean obfuscateInstantApps);
229 
230     /**
231      * Returns the events for the user in the given time period.
232      *
233      * @param flags defines the visibility of certain usage events - see flags defined in
234      * {@link UsageEvents}.
235      */
queryEventsForUser(@serIdInt int userId, long beginTime, long endTime, int flags)236     public abstract UsageEvents queryEventsForUser(@UserIdInt int userId, long beginTime,
237             long endTime, int flags);
238 
239     /**
240      * Used to persist the last time a job was run for this app, in order to make decisions later
241      * whether a job should be deferred until later. The time passed in should be in elapsed
242      * realtime since boot.
243      * @param packageName the app that executed a job.
244      * @param userId the user associated with the job.
245      * @param elapsedRealtime the time when the job was executed, in elapsed realtime millis since
246      *                        boot.
247      */
setLastJobRunTime(String packageName, @UserIdInt int userId, long elapsedRealtime)248     public abstract void setLastJobRunTime(String packageName, @UserIdInt int userId,
249             long elapsedRealtime);
250 
251     /** Returns the estimated time that the app will be launched, in milliseconds since epoch. */
252     @CurrentTimeMillisLong
getEstimatedPackageLaunchTime(String packageName, @UserIdInt int userId)253     public abstract long getEstimatedPackageLaunchTime(String packageName, @UserIdInt int userId);
254 
255     /**
256      * Returns the time in millis since a job was executed for this app, in elapsed realtime
257      * timebase. This value can be larger than the current elapsed realtime if the job was executed
258      * before the device was rebooted. The default value is {@link Long#MAX_VALUE}.
259      * @param packageName the app you're asking about.
260      * @param userId the user associated with the job.
261      * @return the time in millis since a job was last executed for the app, provided it was
262      * indicated here before by a call to {@link #setLastJobRunTime(String, int, long)}.
263      */
getTimeSinceLastJobRun(String packageName, @UserIdInt int userId)264     public abstract long getTimeSinceLastJobRun(String packageName, @UserIdInt int userId);
265 
266     /**
267      * Report a few data points about an app's job state at the current time.
268      *
269      * @param packageName the app whose job state is being described
270      * @param userId which user the app is associated with
271      * @param numDeferredJobs the number of pending jobs that were deferred
272      *   due to bucketing policy
273      * @param timeSinceLastJobRun number of milliseconds since the last time one of
274      *   this app's jobs was executed
275      */
reportAppJobState(String packageName, @UserIdInt int userId, int numDeferredJobs, long timeSinceLastJobRun)276     public abstract void reportAppJobState(String packageName, @UserIdInt int userId,
277             int numDeferredJobs, long timeSinceLastJobRun);
278 
279     /**
280      * Report a sync that was scheduled.
281      *
282      * @param packageName name of the package that owns the sync adapter.
283      * @param userId which user the app is associated with
284      * @param exempted is sync app standby exempted
285      */
reportSyncScheduled(String packageName, @UserIdInt int userId, boolean exempted)286     public abstract void reportSyncScheduled(String packageName, @UserIdInt int userId,
287                                              boolean exempted);
288 
289     /**
290      * Report a sync that was scheduled by a foreground app is about to be executed.
291      *
292      * @param packageName name of the package that owns the sync adapter.
293      * @param userId which user the app is associated with
294      */
reportExemptedSyncStart(String packageName, @UserIdInt int userId)295     public abstract void reportExemptedSyncStart(String packageName, @UserIdInt int userId);
296 
297     /**
298      * Returns an object describing the app usage limit for the given package which was set via
299      * {@link UsageStatsManager#registerAppUsageLimitObserver}.
300      * If there are multiple limits that apply to the package, the one with the smallest
301      * time remaining will be returned.
302      *
303      * @param packageName name of the package whose app usage limit will be returned
304      * @param user the user associated with the limit
305      * @return an {@link AppUsageLimitData} object describing the app time limit containing
306      * the given package, with the smallest time remaining.
307      */
getAppUsageLimit(String packageName, UserHandle user)308     public abstract AppUsageLimitData getAppUsageLimit(String packageName, UserHandle user);
309 
310     /** A class which is used to share the usage limit data for an app or a group of apps. */
311     public static class AppUsageLimitData {
312         private final long mTotalUsageLimit;
313         private final long mUsageRemaining;
314 
AppUsageLimitData(long totalUsageLimit, long usageRemaining)315         public AppUsageLimitData(long totalUsageLimit, long usageRemaining) {
316             this.mTotalUsageLimit = totalUsageLimit;
317             this.mUsageRemaining = usageRemaining;
318         }
319 
getTotalUsageLimit()320         public long getTotalUsageLimit() {
321             return mTotalUsageLimit;
322         }
getUsageRemaining()323         public long getUsageRemaining() {
324             return mUsageRemaining;
325         }
326     }
327 
328     /**
329      * Called by {@link com.android.server.usage.UsageStatsIdleService} when the device is idle to
330      * prune usage stats data for uninstalled packages.
331      *
332      * @param userId the user associated with the job
333      * @return {@code true} if the pruning was successful, {@code false} otherwise
334      */
pruneUninstalledPackagesData(@serIdInt int userId)335     public abstract boolean pruneUninstalledPackagesData(@UserIdInt int userId);
336 
337     /**
338      * Called by {@link com.android.server.usage.UsageStatsIdleService} between 24 to 48 hours of
339      * when the user is first unlocked to update the usage stats package mappings data that might
340      * be stale or have existed from a restore and belongs to packages that are not installed for
341      * this user anymore.
342      *
343      * @param userId The user to update
344      * @return {@code true} if the updating was successful, {@code false} otherwise
345      */
updatePackageMappingsData(@serIdInt int userId)346     public abstract boolean updatePackageMappingsData(@UserIdInt int userId);
347 
348     /**
349      * Listener interface for usage events.
350      */
351     public interface UsageEventListener {
352         /** Callback to inform listeners of a new usage event. */
onUsageEvent(@serIdInt int userId, @NonNull UsageEvents.Event event)353         void onUsageEvent(@UserIdInt int userId, @NonNull UsageEvents.Event event);
354     }
355 
356     /** Register a listener that will be notified of every new usage event. */
registerListener(@onNull UsageEventListener listener)357     public abstract void registerListener(@NonNull UsageEventListener listener);
358 
359     /** Unregister a listener from being notified of every new usage event. */
unregisterListener(@onNull UsageEventListener listener)360     public abstract void unregisterListener(@NonNull UsageEventListener listener);
361 
362     /**
363      * Listener interface for estimated launch time changes.
364      */
365     public interface EstimatedLaunchTimeChangedListener {
366         /** Callback to inform listeners when estimated launch times change. */
onEstimatedLaunchTimeChanged(@serIdInt int userId, @NonNull String packageName, @CurrentTimeMillisLong long newEstimatedLaunchTime)367         void onEstimatedLaunchTimeChanged(@UserIdInt int userId, @NonNull String packageName,
368                 @CurrentTimeMillisLong long newEstimatedLaunchTime);
369     }
370 
371     /** Register a listener that will be notified of every estimated launch time change. */
registerLaunchTimeChangedListener( @onNull EstimatedLaunchTimeChangedListener listener)372     public abstract void registerLaunchTimeChangedListener(
373             @NonNull EstimatedLaunchTimeChangedListener listener);
374 
375     /** Unregister a listener from being notified of every estimated launch time change. */
unregisterLaunchTimeChangedListener( @onNull EstimatedLaunchTimeChangedListener listener)376     public abstract void unregisterLaunchTimeChangedListener(
377             @NonNull EstimatedLaunchTimeChangedListener listener);
378 
379     /**
380      * Reports a broadcast dispatched event to the UsageStatsManager.
381      *
382      * @param sourceUid uid of the package that sent the broadcast.
383      * @param targetPackage name of the package that the broadcast is targeted to.
384      * @param targetUser user that {@code targetPackage} belongs to.
385      * @param idForResponseEvent ID to be used for recording any response events corresponding
386      *                           to this broadcast.
387      * @param timestampMs time (in millis) when the broadcast was dispatched, in
388      *                    {@link SystemClock#elapsedRealtime()} timebase.
389      * @param targetUidProcState process state of the uid that the broadcast is targeted to.
390      */
reportBroadcastDispatched(int sourceUid, @NonNull String targetPackage, @NonNull UserHandle targetUser, long idForResponseEvent, @ElapsedRealtimeLong long timestampMs, @ProcessState int targetUidProcState)391     public abstract void reportBroadcastDispatched(int sourceUid, @NonNull String targetPackage,
392             @NonNull UserHandle targetUser, long idForResponseEvent,
393             @ElapsedRealtimeLong long timestampMs, @ProcessState int targetUidProcState);
394 
395     /**
396      * Reports a notification posted event to the UsageStatsManager.
397      *
398      * @param packageName name of the package which posted the notification.
399      * @param user user that {@code packageName} belongs to.
400      * @param timestampMs time (in millis) when the notification was posted, in
401      *                    {@link SystemClock#elapsedRealtime()} timebase.
402      */
reportNotificationPosted(@onNull String packageName, @NonNull UserHandle user, @ElapsedRealtimeLong long timestampMs)403     public abstract void reportNotificationPosted(@NonNull String packageName,
404             @NonNull UserHandle user, @ElapsedRealtimeLong long timestampMs);
405 
406     /**
407      * Reports a notification updated event to the UsageStatsManager.
408      *
409      * @param packageName name of the package which updated the notification.
410      * @param user user that {@code packageName} belongs to.
411      * @param timestampMs time (in millis) when the notification was updated, in
412      *                    {@link SystemClock#elapsedRealtime()} timebase.
413      */
reportNotificationUpdated(@onNull String packageName, @NonNull UserHandle user, @ElapsedRealtimeLong long timestampMs)414     public abstract void reportNotificationUpdated(@NonNull String packageName,
415             @NonNull UserHandle user, @ElapsedRealtimeLong long timestampMs);
416 
417     /**
418      * Reports a notification removed event to the UsageStatsManager.
419      *
420      * @param packageName name of the package which removed the notification.
421      * @param user user that {@code packageName} belongs to.
422      * @param timestampMs time (in millis) when the notification was removed, in
423      *                    {@link SystemClock#elapsedRealtime()} timebase.
424      */
reportNotificationRemoved(@onNull String packageName, @NonNull UserHandle user, @ElapsedRealtimeLong long timestampMs)425     public abstract void reportNotificationRemoved(@NonNull String packageName,
426             @NonNull UserHandle user, @ElapsedRealtimeLong long timestampMs);
427 }
428