2 * Copyright (C) 2014 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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
17 package android.app.usage;
19 import android.annotation.IntDef;
20 import android.annotation.NonNull;
21 import android.annotation.RequiresPermission;
22 import android.annotation.SystemApi;
23 import android.annotation.SystemService;
24 import android.app.PendingIntent;
25 import android.content.Context;
26 import android.content.pm.ParceledListSlice;
27 import android.os.RemoteException;
28 import android.os.UserHandle;
29 import android.util.ArrayMap;
31 import java.lang.annotation.Retention;
32 import java.lang.annotation.RetentionPolicy;
33 import java.util.ArrayList;
34 import java.util.Collections;
35 import java.util.List;
37 import java.util.concurrent.TimeUnit;
40 * Provides access to device usage history and statistics. Usage data is aggregated into
41 * time intervals: days, weeks, months, and years.
43 * When requesting usage data since a particular time, the request might look something like this:
45 * PAST REQUEST_TIME TODAY FUTURE
46 * ————————————————————————————||———————————————————————————¦-----------------------|
48 * ————————————————————————————||———————————————————————————¦-----------------------|
49 * MONTH | || MONTH ¦ |
50 * ——————————————————|—————————||———————————————————————————¦-----------------------|
51 * | WEEK | WEEK|| | WEEK | WE¦EK | WEEK |
52 * ————————————————————————————||———————————————————|———————¦-----------------------|
53 * || |DAY|DAY|DAY|DAY¦DAY|DAY|DAY|DAY|DAY|DAY|
54 * ————————————————————————————||———————————————————————————¦-----------------------|
56 * A request for data in the middle of a time interval will include that interval.
58 * <b>NOTE:</b> Most methods on this API require the permission
59 * android.permission.PACKAGE_USAGE_STATS. However, declaring the permission implies intention to
60 * use the API and the user of the device still needs to grant permission through the Settings
62 * See {@link android.provider.Settings#ACTION_USAGE_ACCESS_SETTINGS}.
63 * Methods which only return the information for the calling package do not require this permission.
64 * E.g. {@link #getAppStandbyBucket()} and {@link #queryEventsForSelf(long, long)}.
66 @SystemService(Context.USAGE_STATS_SERVICE)
67 public final class UsageStatsManager {
70 * An interval type that spans a day. See {@link #queryUsageStats(int, long, long)}.
72 public static final int INTERVAL_DAILY = 0;
75 * An interval type that spans a week. See {@link #queryUsageStats(int, long, long)}.
77 public static final int INTERVAL_WEEKLY = 1;
80 * An interval type that spans a month. See {@link #queryUsageStats(int, long, long)}.
82 public static final int INTERVAL_MONTHLY = 2;
85 * An interval type that spans a year. See {@link #queryUsageStats(int, long, long)}.
87 public static final int INTERVAL_YEARLY = 3;
90 * An interval type that will use the best fit interval for the given time range.
91 * See {@link #queryUsageStats(int, long, long)}.
93 public static final int INTERVAL_BEST = 4;
96 * The number of available intervals. Does not include {@link #INTERVAL_BEST}, since it
97 * is a pseudo interval (it actually selects a real interval).
100 public static final int INTERVAL_COUNT = 4;
104 * The app is whitelisted for some reason and the bucket cannot be changed.
108 public static final int STANDBY_BUCKET_EXEMPTED = 5;
111 * The app was used very recently, currently in use or likely to be used very soon. Standby
112 * bucket values that are ≤ {@link #STANDBY_BUCKET_ACTIVE} will not be throttled by the
113 * system while they are in this bucket. Buckets > {@link #STANDBY_BUCKET_ACTIVE} will most
114 * likely be restricted in some way. For instance, jobs and alarms may be deferred.
115 * @see #getAppStandbyBucket()
117 public static final int STANDBY_BUCKET_ACTIVE = 10;
120 * The app was used recently and/or likely to be used in the next few hours. Restrictions will
121 * apply to these apps, such as deferral of jobs and alarms.
122 * @see #getAppStandbyBucket()
124 public static final int STANDBY_BUCKET_WORKING_SET = 20;
127 * The app was used in the last few days and/or likely to be used in the next few days.
128 * Restrictions will apply to these apps, such as deferral of jobs and alarms. The delays may be
129 * greater than for apps in higher buckets (lower bucket value). Bucket values >
130 * {@link #STANDBY_BUCKET_FREQUENT} may additionally have network access limited.
131 * @see #getAppStandbyBucket()
133 public static final int STANDBY_BUCKET_FREQUENT = 30;
136 * The app has not be used for several days and/or is unlikely to be used for several days.
137 * Apps in this bucket will have the most restrictions, including network restrictions, except
138 * during certain short periods (at a minimum, once a day) when they are allowed to execute
139 * jobs, access the network, etc.
140 * @see #getAppStandbyBucket()
142 public static final int STANDBY_BUCKET_RARE = 40;
145 * The app has never been used.
149 public static final int STANDBY_BUCKET_NEVER = 50;
152 public static final int REASON_MAIN_MASK = 0xFF00;
154 public static final int REASON_MAIN_DEFAULT = 0x0100;
156 public static final int REASON_MAIN_TIMEOUT = 0x0200;
158 public static final int REASON_MAIN_USAGE = 0x0300;
160 public static final int REASON_MAIN_FORCED = 0x0400;
162 public static final int REASON_MAIN_PREDICTED = 0x0500;
165 public static final int REASON_SUB_MASK = 0x00FF;
167 public static final int REASON_SUB_USAGE_SYSTEM_INTERACTION = 0x0001;
169 public static final int REASON_SUB_USAGE_NOTIFICATION_SEEN = 0x0002;
171 public static final int REASON_SUB_USAGE_USER_INTERACTION = 0x0003;
173 public static final int REASON_SUB_USAGE_MOVE_TO_FOREGROUND = 0x0004;
175 public static final int REASON_SUB_USAGE_MOVE_TO_BACKGROUND = 0x0005;
177 public static final int REASON_SUB_USAGE_SYSTEM_UPDATE = 0x0006;
179 public static final int REASON_SUB_USAGE_ACTIVE_TIMEOUT = 0x0007;
181 public static final int REASON_SUB_USAGE_SYNC_ADAPTER = 0x0008;
184 @IntDef(flag = false, prefix = { "STANDBY_BUCKET_" }, value = {
185 STANDBY_BUCKET_EXEMPTED,
186 STANDBY_BUCKET_ACTIVE,
187 STANDBY_BUCKET_WORKING_SET,
188 STANDBY_BUCKET_FREQUENT,
190 STANDBY_BUCKET_NEVER,
192 @Retention(RetentionPolicy.SOURCE)
193 public @interface StandbyBuckets {}
196 * Observer id of the registered observer for the group of packages that reached the usage
197 * time limit. Included as an extra in the PendingIntent that was registered.
201 public static final String EXTRA_OBSERVER_ID = "android.app.usage.extra.OBSERVER_ID";
204 * Original time limit in milliseconds specified by the registered observer for the group of
205 * packages that reached the usage time limit. Included as an extra in the PendingIntent that
210 public static final String EXTRA_TIME_LIMIT = "android.app.usage.extra.TIME_LIMIT";
213 * Actual usage time in milliseconds for the group of packages that reached the specified time
214 * limit. Included as an extra in the PendingIntent that was registered.
218 public static final String EXTRA_TIME_USED = "android.app.usage.extra.TIME_USED";
220 private static final UsageEvents sEmptyResults = new UsageEvents();
222 private final Context mContext;
223 private final IUsageStatsManager mService;
228 public UsageStatsManager(Context context, IUsageStatsManager service) {
234 * Gets application usage stats for the given time range, aggregated by the specified interval.
235 * <p>The returned list will contain a {@link UsageStats} object for each package that
236 * has data for an interval that is a subset of the time range given. To illustrate:</p>
238 * intervalType = INTERVAL_YEARLY
240 * endTime = 2015 (exclusive)
243 * 2013 - com.example.alpha
244 * 2013 - com.example.beta
245 * 2014 - com.example.alpha
246 * 2014 - com.example.beta
247 * 2014 - com.example.charlie
250 * <p> The caller must have {@link android.Manifest.permission#PACKAGE_USAGE_STATS} </p>
252 * @param intervalType The time interval by which the stats are aggregated.
253 * @param beginTime The inclusive beginning of the range of stats to include in the results.
254 * @param endTime The exclusive end of the range of stats to include in the results.
255 * @return A list of {@link UsageStats}
257 * @see #INTERVAL_DAILY
258 * @see #INTERVAL_WEEKLY
259 * @see #INTERVAL_MONTHLY
260 * @see #INTERVAL_YEARLY
261 * @see #INTERVAL_BEST
263 public List<UsageStats> queryUsageStats(int intervalType, long beginTime, long endTime) {
265 @SuppressWarnings("unchecked")
266 ParceledListSlice<UsageStats> slice = mService.queryUsageStats(intervalType, beginTime,
267 endTime, mContext.getOpPackageName());
269 return slice.getList();
271 } catch (RemoteException e) {
272 // fallthrough and return the empty list.
274 return Collections.emptyList();
278 * Gets the hardware configurations the device was in for the given time range, aggregated by
279 * the specified interval. The results are ordered as in
280 * {@link #queryUsageStats(int, long, long)}.
281 * <p> The caller must have {@link android.Manifest.permission#PACKAGE_USAGE_STATS} </p>
283 * @param intervalType The time interval by which the stats are aggregated.
284 * @param beginTime The inclusive beginning of the range of stats to include in the results.
285 * @param endTime The exclusive end of the range of stats to include in the results.
286 * @return A list of {@link ConfigurationStats}
288 public List<ConfigurationStats> queryConfigurations(int intervalType, long beginTime,
291 @SuppressWarnings("unchecked")
292 ParceledListSlice<ConfigurationStats> slice = mService.queryConfigurationStats(
293 intervalType, beginTime, endTime, mContext.getOpPackageName());
295 return slice.getList();
297 } catch (RemoteException e) {
298 // fallthrough and return the empty list.
300 return Collections.emptyList();
304 * Query for events in the given time range. Events are only kept by the system for a few
306 * <p> The caller must have {@link android.Manifest.permission#PACKAGE_USAGE_STATS} </p>
308 * @param beginTime The inclusive beginning of the range of events to include in the results.
309 * @param endTime The exclusive end of the range of events to include in the results.
310 * @return A {@link UsageEvents}.
312 public UsageEvents queryEvents(long beginTime, long endTime) {
314 UsageEvents iter = mService.queryEvents(beginTime, endTime,
315 mContext.getOpPackageName());
319 } catch (RemoteException e) {
320 // fallthrough and return empty result.
322 return sEmptyResults;
326 * Like {@link #queryEvents(long, long)}, but only returns events for the calling package.
328 * @param beginTime The inclusive beginning of the range of events to include in the results.
329 * @param endTime The exclusive end of the range of events to include in the results.
330 * @return A {@link UsageEvents} object.
332 * @see #queryEvents(long, long)
334 public UsageEvents queryEventsForSelf(long beginTime, long endTime) {
336 final UsageEvents events = mService.queryEventsForPackage(beginTime, endTime,
337 mContext.getOpPackageName());
338 if (events != null) {
341 } catch (RemoteException e) {
344 return sEmptyResults;
348 * A convenience method that queries for all stats in the given range (using the best interval
349 * for that range), merges the resulting data, and keys it by package name.
350 * See {@link #queryUsageStats(int, long, long)}.
351 * <p> The caller must have {@link android.Manifest.permission#PACKAGE_USAGE_STATS} </p>
353 * @param beginTime The inclusive beginning of the range of stats to include in the results.
354 * @param endTime The exclusive end of the range of stats to include in the results.
355 * @return A {@link java.util.Map} keyed by package name
357 public Map<String, UsageStats> queryAndAggregateUsageStats(long beginTime, long endTime) {
358 List<UsageStats> stats = queryUsageStats(INTERVAL_BEST, beginTime, endTime);
359 if (stats.isEmpty()) {
360 return Collections.emptyMap();
363 ArrayMap<String, UsageStats> aggregatedStats = new ArrayMap<>();
364 final int statCount = stats.size();
365 for (int i = 0; i < statCount; i++) {
366 UsageStats newStat = stats.get(i);
367 UsageStats existingStat = aggregatedStats.get(newStat.getPackageName());
368 if (existingStat == null) {
369 aggregatedStats.put(newStat.mPackageName, newStat);
371 existingStat.add(newStat);
374 return aggregatedStats;
378 * Returns whether the specified app is currently considered inactive. This will be true if the
379 * app hasn't been used directly or indirectly for a period of time defined by the system. This
380 * could be of the order of several hours or days.
381 * @param packageName The package name of the app to query
382 * @return whether the app is currently considered inactive
384 public boolean isAppInactive(String packageName) {
386 return mService.isAppInactive(packageName, mContext.getUserId());
387 } catch (RemoteException e) {
388 // fall through and return default
396 public void setAppInactive(String packageName, boolean inactive) {
398 mService.setAppInactive(packageName, inactive, mContext.getUserId());
399 } catch (RemoteException e) {
405 * Returns the current standby bucket of the calling app. The system determines the standby
406 * state of the app based on app usage patterns. Standby buckets determine how much an app will
407 * be restricted from running background tasks such as jobs and alarms.
408 * <p>Restrictions increase progressively from {@link #STANDBY_BUCKET_ACTIVE} to
409 * {@link #STANDBY_BUCKET_RARE}, with {@link #STANDBY_BUCKET_ACTIVE} being the least
410 * restrictive. The battery level of the device might also affect the restrictions.
411 * <p>Apps in buckets ≤ {@link #STANDBY_BUCKET_ACTIVE} have no standby restrictions imposed.
412 * Apps in buckets > {@link #STANDBY_BUCKET_FREQUENT} may have network access restricted when
413 * running in the background.
414 * <p>The standby state of an app can change at any time either due to a user interaction or a
415 * system interaction or some algorithm determining that the app can be restricted for a period
416 * of time before the user has a need for it.
417 * <p>You can also query the recent history of standby bucket changes by calling
418 * {@link #queryEventsForSelf(long, long)} and searching for
419 * {@link UsageEvents.Event#STANDBY_BUCKET_CHANGED}.
421 * @return the current standby bucket of the calling app. One of STANDBY_BUCKET_* constants.
423 public @StandbyBuckets int getAppStandbyBucket() {
425 return mService.getAppStandbyBucket(mContext.getOpPackageName(),
426 mContext.getOpPackageName(),
427 mContext.getUserId());
428 } catch (RemoteException e) {
430 return STANDBY_BUCKET_ACTIVE;
435 * Returns the current standby bucket of the specified app. The caller must hold the permission
436 * android.permission.PACKAGE_USAGE_STATS.
437 * @param packageName the package for which to fetch the current standby bucket.
440 @RequiresPermission(android.Manifest.permission.PACKAGE_USAGE_STATS)
441 public @StandbyBuckets int getAppStandbyBucket(String packageName) {
443 return mService.getAppStandbyBucket(packageName, mContext.getOpPackageName(),
444 mContext.getUserId());
445 } catch (RemoteException e) {
447 return STANDBY_BUCKET_ACTIVE;
452 * Changes an app's standby bucket to the provided value. The caller can only set the standby
453 * bucket for a different app than itself.
454 * @param packageName the package name of the app to set the bucket for. A SecurityException
455 * will be thrown if the package name is that of the caller.
456 * @param bucket the standby bucket to set it to, which should be one of STANDBY_BUCKET_*.
457 * Setting a standby bucket outside of the range of STANDBY_BUCKET_ACTIVE to
458 * STANDBY_BUCKET_NEVER will result in a SecurityException.
461 @RequiresPermission(android.Manifest.permission.CHANGE_APP_IDLE_STATE)
462 public void setAppStandbyBucket(String packageName, @StandbyBuckets int bucket) {
464 mService.setAppStandbyBucket(packageName, bucket, mContext.getUserId());
465 } catch (RemoteException e) {
472 * Returns the current standby bucket of every app that has a bucket assigned to it.
473 * The caller must hold the permission android.permission.PACKAGE_USAGE_STATS. The key of the
474 * returned Map is the package name and the value is the bucket assigned to the package.
475 * @see #getAppStandbyBucket()
478 @RequiresPermission(android.Manifest.permission.PACKAGE_USAGE_STATS)
479 public Map<String, Integer> getAppStandbyBuckets() {
481 final ParceledListSlice<AppStandbyInfo> slice = mService.getAppStandbyBuckets(
482 mContext.getOpPackageName(), mContext.getUserId());
483 final List<AppStandbyInfo> bucketList = slice.getList();
484 final ArrayMap<String, Integer> bucketMap = new ArrayMap<>();
485 final int n = bucketList.size();
486 for (int i = 0; i < n; i++) {
487 final AppStandbyInfo bucketInfo = bucketList.get(i);
488 bucketMap.put(bucketInfo.mPackageName, bucketInfo.mStandbyBucket);
491 } catch (RemoteException e) {
493 return Collections.EMPTY_MAP;
498 * Changes the app standby bucket for multiple apps at once. The Map is keyed by the package
499 * name and the value is one of STANDBY_BUCKET_*.
500 * @param appBuckets a map of package name to bucket value.
503 @RequiresPermission(android.Manifest.permission.CHANGE_APP_IDLE_STATE)
504 public void setAppStandbyBuckets(Map<String, Integer> appBuckets) {
505 if (appBuckets == null) {
508 final List<AppStandbyInfo> bucketInfoList = new ArrayList<>(appBuckets.size());
509 for (Map.Entry<String, Integer> bucketEntry : appBuckets.entrySet()) {
510 bucketInfoList.add(new AppStandbyInfo(bucketEntry.getKey(), bucketEntry.getValue()));
512 final ParceledListSlice<AppStandbyInfo> slice = new ParceledListSlice<>(bucketInfoList);
514 mService.setAppStandbyBuckets(slice, mContext.getUserId());
515 } catch (RemoteException e) {
521 * Register an app usage limit observer that receives a callback on the provided intent when
522 * the sum of usages of apps in the packages array exceeds the {@code timeLimit} specified. The
523 * observer will automatically be unregistered when the time limit is reached and the intent
524 * is delivered. Registering an {@code observerId} that was already registered will override
526 * @param observerId A unique id associated with the group of apps to be monitored. There can
527 * be multiple groups with common packages and different time limits.
528 * @param packages The list of packages to observe for foreground activity time. Cannot be null
529 * and must include at least one package.
530 * @param timeLimit The total time the set of apps can be in the foreground before the
531 * callbackIntent is delivered. Must be greater than 0.
532 * @param timeUnit The unit for time specified in {@code timeLimit}. Cannot be null.
533 * @param callbackIntent The PendingIntent that will be dispatched when the time limit is
534 * exceeded by the group of apps. The delivered Intent will also contain
535 * the extras {@link #EXTRA_OBSERVER_ID}, {@link #EXTRA_TIME_LIMIT} and
536 * {@link #EXTRA_TIME_USED}. Cannot be null.
537 * @throws SecurityException if the caller doesn't have the OBSERVE_APP_USAGE permission or
538 * is not the profile owner of this user.
541 @RequiresPermission(android.Manifest.permission.OBSERVE_APP_USAGE)
542 public void registerAppUsageObserver(int observerId, @NonNull String[] packages, long timeLimit,
543 @NonNull TimeUnit timeUnit, @NonNull PendingIntent callbackIntent) {
545 mService.registerAppUsageObserver(observerId, packages, timeUnit.toMillis(timeLimit),
546 callbackIntent, mContext.getOpPackageName());
547 } catch (RemoteException e) {
553 * Unregister the app usage observer specified by the {@code observerId}. This will only apply
554 * to any observer registered by this application. Unregistering an observer that was already
555 * unregistered or never registered will have no effect.
556 * @param observerId The id of the observer that was previously registered.
557 * @throws SecurityException if the caller doesn't have the OBSERVE_APP_USAGE permission or is
558 * not the profile owner of this user.
561 @RequiresPermission(android.Manifest.permission.OBSERVE_APP_USAGE)
562 public void unregisterAppUsageObserver(int observerId) {
564 mService.unregisterAppUsageObserver(observerId, mContext.getOpPackageName());
565 } catch (RemoteException e) {
570 public static String reasonToString(int standbyReason) {
571 StringBuilder sb = new StringBuilder();
572 switch (standbyReason & REASON_MAIN_MASK) {
573 case REASON_MAIN_DEFAULT:
576 case REASON_MAIN_FORCED:
579 case REASON_MAIN_PREDICTED:
582 case REASON_MAIN_TIMEOUT:
585 case REASON_MAIN_USAGE:
587 switch (standbyReason & REASON_SUB_MASK) {
588 case REASON_SUB_USAGE_SYSTEM_INTERACTION:
591 case REASON_SUB_USAGE_NOTIFICATION_SEEN:
594 case REASON_SUB_USAGE_USER_INTERACTION:
597 case REASON_SUB_USAGE_MOVE_TO_FOREGROUND:
600 case REASON_SUB_USAGE_MOVE_TO_BACKGROUND:
603 case REASON_SUB_USAGE_SYSTEM_UPDATE:
606 case REASON_SUB_USAGE_ACTIVE_TIMEOUT:
609 case REASON_SUB_USAGE_SYNC_ADAPTER:
615 return sb.toString();
620 * Temporarily whitelist the specified app for a short duration. This is to allow an app
621 * receiving a high priority message to be able to access the network and acquire wakelocks
622 * even if the device is in power-save mode or the app is currently considered inactive.
623 * @param packageName The package name of the app to whitelist.
624 * @param duration Duration to whitelist the app for, in milliseconds. It is recommended that
625 * this be limited to 10s of seconds. Requested duration will be clamped to a few minutes.
626 * @param user The user for whom the package should be whitelisted. Passing in a user that is
627 * not the same as the caller's process will require the INTERACT_ACROSS_USERS permission.
628 * @see #isAppInactive(String)
631 @RequiresPermission(android.Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST)
632 public void whitelistAppTemporarily(String packageName, long duration, UserHandle user) {
634 mService.whitelistAppTemporarily(packageName, duration, user.getIdentifier());
635 } catch (RemoteException re) {
640 * Inform usage stats that the carrier privileged apps access rules have changed.
643 public void onCarrierPrivilegedAppsChanged() {
645 mService.onCarrierPrivilegedAppsChanged();
646 } catch (RemoteException re) {
651 * Reports a Chooser action to the UsageStatsManager.
653 * @param packageName The package name of the app that is selected.
654 * @param userId The user id of who makes the selection.
655 * @param contentType The type of the content, e.g., Image, Video, App.
656 * @param annotations The annotations of the content, e.g., Game, Selfie.
657 * @param action The action type of Intent that invokes ChooserActivity.
658 * {@link UsageEvents}
661 public void reportChooserSelection(String packageName, int userId, String contentType,
662 String[] annotations, String action) {
664 mService.reportChooserSelection(packageName, userId, contentType, annotations, action);
665 } catch (RemoteException re) {