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