OSDN Git Service

Merge "Provide app launch count in UsageStats" into pi-dev
[android-x86/frameworks-base.git] / core / java / android / app / usage / UsageStatsManager.java
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.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;
30
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;
36 import java.util.Map;
37 import java.util.concurrent.TimeUnit;
38
39 /**
40  * Provides access to device usage history and statistics. Usage data is aggregated into
41  * time intervals: days, weeks, months, and years.
42  * <p />
43  * When requesting usage data since a particular time, the request might look something like this:
44  * <pre>
45  * PAST                   REQUEST_TIME                    TODAY                   FUTURE
46  * ————————————————————————————||———————————————————————————¦-----------------------|
47  *                        YEAR ||                           ¦                       |
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  * ————————————————————————————||———————————————————————————¦-----------------------|
55  * </pre>
56  * A request for data in the middle of a time interval will include that interval.
57  * <p/>
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
61  * application.
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)}.
65  */
66 @SystemService(Context.USAGE_STATS_SERVICE)
67 public final class UsageStatsManager {
68
69     /**
70      * An interval type that spans a day. See {@link #queryUsageStats(int, long, long)}.
71      */
72     public static final int INTERVAL_DAILY = 0;
73
74     /**
75      * An interval type that spans a week. See {@link #queryUsageStats(int, long, long)}.
76      */
77     public static final int INTERVAL_WEEKLY = 1;
78
79     /**
80      * An interval type that spans a month. See {@link #queryUsageStats(int, long, long)}.
81      */
82     public static final int INTERVAL_MONTHLY = 2;
83
84     /**
85      * An interval type that spans a year. See {@link #queryUsageStats(int, long, long)}.
86      */
87     public static final int INTERVAL_YEARLY = 3;
88
89     /**
90      * An interval type that will use the best fit interval for the given time range.
91      * See {@link #queryUsageStats(int, long, long)}.
92      */
93     public static final int INTERVAL_BEST = 4;
94
95     /**
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).
98      * {@hide}
99      */
100     public static final int INTERVAL_COUNT = 4;
101
102
103     /**
104      * The app is whitelisted for some reason and the bucket cannot be changed.
105      * {@hide}
106      */
107     @SystemApi
108     public static final int STANDBY_BUCKET_EXEMPTED = 5;
109
110     /**
111      * The app was used very recently, currently in use or likely to be used very soon. Standby
112      * bucket values that are &le; {@link #STANDBY_BUCKET_ACTIVE} will not be throttled by the
113      * system while they are in this bucket. Buckets &gt; {@link #STANDBY_BUCKET_ACTIVE} will most
114      * likely be restricted in some way. For instance, jobs and alarms may be deferred.
115      * @see #getAppStandbyBucket()
116      */
117     public static final int STANDBY_BUCKET_ACTIVE = 10;
118
119     /**
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()
123      */
124     public static final int STANDBY_BUCKET_WORKING_SET = 20;
125
126     /**
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 &gt;
130      * {@link #STANDBY_BUCKET_FREQUENT} may additionally have network access limited.
131      * @see #getAppStandbyBucket()
132      */
133     public static final int STANDBY_BUCKET_FREQUENT = 30;
134
135     /**
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()
141      */
142     public static final int STANDBY_BUCKET_RARE = 40;
143
144     /**
145      * The app has never been used.
146      * {@hide}
147      */
148     @SystemApi
149     public static final int STANDBY_BUCKET_NEVER = 50;
150
151     /** @hide */
152     public static final int REASON_MAIN_MASK = 0xFF00;
153     /** @hide */
154     public static final int REASON_MAIN_DEFAULT =   0x0100;
155     /** @hide */
156     public static final int REASON_MAIN_TIMEOUT =   0x0200;
157     /** @hide */
158     public static final int REASON_MAIN_USAGE =     0x0300;
159     /** @hide */
160     public static final int REASON_MAIN_FORCED =    0x0400;
161     /** @hide */
162     public static final int REASON_MAIN_PREDICTED = 0x0500;
163
164     /** @hide */
165     public static final int REASON_SUB_MASK = 0x00FF;
166     /** @hide */
167     public static final int REASON_SUB_USAGE_SYSTEM_INTERACTION = 0x0001;
168     /** @hide */
169     public static final int REASON_SUB_USAGE_NOTIFICATION_SEEN  = 0x0002;
170     /** @hide */
171     public static final int REASON_SUB_USAGE_USER_INTERACTION   = 0x0003;
172     /** @hide */
173     public static final int REASON_SUB_USAGE_MOVE_TO_FOREGROUND = 0x0004;
174     /** @hide */
175     public static final int REASON_SUB_USAGE_MOVE_TO_BACKGROUND = 0x0005;
176     /** @hide */
177     public static final int REASON_SUB_USAGE_SYSTEM_UPDATE      = 0x0006;
178     /** @hide */
179     public static final int REASON_SUB_USAGE_ACTIVE_TIMEOUT     = 0x0007;
180     /** @hide */
181     public static final int REASON_SUB_USAGE_SYNC_ADAPTER       = 0x0008;
182
183     /** @hide */
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,
189             STANDBY_BUCKET_RARE,
190             STANDBY_BUCKET_NEVER,
191     })
192     @Retention(RetentionPolicy.SOURCE)
193     public @interface StandbyBuckets {}
194
195     /**
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.
198      * @hide
199      */
200     @SystemApi
201     public static final String EXTRA_OBSERVER_ID = "android.app.usage.extra.OBSERVER_ID";
202
203     /**
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
206      * was registered.
207      * @hide
208      */
209     @SystemApi
210     public static final String EXTRA_TIME_LIMIT = "android.app.usage.extra.TIME_LIMIT";
211
212     /**
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.
215      * @hide
216      */
217     @SystemApi
218     public static final String EXTRA_TIME_USED = "android.app.usage.extra.TIME_USED";
219
220     private static final UsageEvents sEmptyResults = new UsageEvents();
221
222     private final Context mContext;
223     private final IUsageStatsManager mService;
224
225     /**
226      * {@hide}
227      */
228     public UsageStatsManager(Context context, IUsageStatsManager service) {
229         mContext = context;
230         mService = service;
231     }
232
233     /**
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>
237      * <pre>
238      * intervalType = INTERVAL_YEARLY
239      * beginTime = 2013
240      * endTime = 2015 (exclusive)
241      *
242      * Results:
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
248      * </pre>
249      *
250      * <p> The caller must have {@link android.Manifest.permission#PACKAGE_USAGE_STATS} </p>
251      *
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}
256      *
257      * @see #INTERVAL_DAILY
258      * @see #INTERVAL_WEEKLY
259      * @see #INTERVAL_MONTHLY
260      * @see #INTERVAL_YEARLY
261      * @see #INTERVAL_BEST
262      */
263     public List<UsageStats> queryUsageStats(int intervalType, long beginTime, long endTime) {
264         try {
265             @SuppressWarnings("unchecked")
266             ParceledListSlice<UsageStats> slice = mService.queryUsageStats(intervalType, beginTime,
267                     endTime, mContext.getOpPackageName());
268             if (slice != null) {
269                 return slice.getList();
270             }
271         } catch (RemoteException e) {
272             // fallthrough and return the empty list.
273         }
274         return Collections.emptyList();
275     }
276
277     /**
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>
282      *
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}
287      */
288     public List<ConfigurationStats> queryConfigurations(int intervalType, long beginTime,
289             long endTime) {
290         try {
291             @SuppressWarnings("unchecked")
292             ParceledListSlice<ConfigurationStats> slice = mService.queryConfigurationStats(
293                     intervalType, beginTime, endTime, mContext.getOpPackageName());
294             if (slice != null) {
295                 return slice.getList();
296             }
297         } catch (RemoteException e) {
298             // fallthrough and return the empty list.
299         }
300         return Collections.emptyList();
301     }
302
303     /**
304      * Query for events in the given time range. Events are only kept by the system for a few
305      * days.
306      * <p> The caller must have {@link android.Manifest.permission#PACKAGE_USAGE_STATS} </p>
307      *
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}.
311      */
312     public UsageEvents queryEvents(long beginTime, long endTime) {
313         try {
314             UsageEvents iter = mService.queryEvents(beginTime, endTime,
315                     mContext.getOpPackageName());
316             if (iter != null) {
317                 return iter;
318             }
319         } catch (RemoteException e) {
320             // fallthrough and return empty result.
321         }
322         return sEmptyResults;
323     }
324
325     /**
326      * Like {@link #queryEvents(long, long)}, but only returns events for the calling package.
327      *
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.
331      *
332      * @see #queryEvents(long, long)
333      */
334     public UsageEvents queryEventsForSelf(long beginTime, long endTime) {
335         try {
336             final UsageEvents events = mService.queryEventsForPackage(beginTime, endTime,
337                     mContext.getOpPackageName());
338             if (events != null) {
339                 return events;
340             }
341         } catch (RemoteException e) {
342             // fallthrough
343         }
344         return sEmptyResults;
345     }
346
347     /**
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>
352      *
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
356      */
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();
361         }
362
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);
370             } else {
371                 existingStat.add(newStat);
372             }
373         }
374         return aggregatedStats;
375     }
376
377     /**
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
383      */
384     public boolean isAppInactive(String packageName) {
385         try {
386             return mService.isAppInactive(packageName, mContext.getUserId());
387         } catch (RemoteException e) {
388             // fall through and return default
389         }
390         return false;
391     }
392
393     /**
394      * {@hide}
395      */
396     public void setAppInactive(String packageName, boolean inactive) {
397         try {
398             mService.setAppInactive(packageName, inactive, mContext.getUserId());
399         } catch (RemoteException e) {
400             // fall through
401         }
402     }
403
404     /**
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 &le; {@link #STANDBY_BUCKET_ACTIVE} have no standby restrictions imposed.
412      * Apps in buckets &gt; {@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}.
420      *
421      * @return the current standby bucket of the calling app. One of STANDBY_BUCKET_* constants.
422      */
423     public @StandbyBuckets int getAppStandbyBucket() {
424         try {
425             return mService.getAppStandbyBucket(mContext.getOpPackageName(),
426                     mContext.getOpPackageName(),
427                     mContext.getUserId());
428         } catch (RemoteException e) {
429         }
430         return STANDBY_BUCKET_ACTIVE;
431     }
432
433     /**
434      * {@hide}
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.
438      */
439     @SystemApi
440     @RequiresPermission(android.Manifest.permission.PACKAGE_USAGE_STATS)
441     public @StandbyBuckets int getAppStandbyBucket(String packageName) {
442         try {
443             return mService.getAppStandbyBucket(packageName, mContext.getOpPackageName(),
444                     mContext.getUserId());
445         } catch (RemoteException e) {
446         }
447         return STANDBY_BUCKET_ACTIVE;
448     }
449
450     /**
451      * {@hide}
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.
459      */
460     @SystemApi
461     @RequiresPermission(android.Manifest.permission.CHANGE_APP_IDLE_STATE)
462     public void setAppStandbyBucket(String packageName, @StandbyBuckets int bucket) {
463         try {
464             mService.setAppStandbyBucket(packageName, bucket, mContext.getUserId());
465         } catch (RemoteException e) {
466             // Nothing to do
467         }
468     }
469
470     /**
471      * {@hide}
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()
476      */
477     @SystemApi
478     @RequiresPermission(android.Manifest.permission.PACKAGE_USAGE_STATS)
479     public Map<String, Integer> getAppStandbyBuckets() {
480         try {
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);
489             }
490             return bucketMap;
491         } catch (RemoteException e) {
492         }
493         return Collections.EMPTY_MAP;
494     }
495
496     /**
497      * {@hide}
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.
501      */
502     @SystemApi
503     @RequiresPermission(android.Manifest.permission.CHANGE_APP_IDLE_STATE)
504     public void setAppStandbyBuckets(Map<String, Integer> appBuckets) {
505         if (appBuckets == null) {
506             return;
507         }
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()));
511         }
512         final ParceledListSlice<AppStandbyInfo> slice = new ParceledListSlice<>(bucketInfoList);
513         try {
514             mService.setAppStandbyBuckets(slice, mContext.getUserId());
515         } catch (RemoteException e) {
516         }
517     }
518
519     /**
520      * @hide
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
525      * the previous one.
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.
539      */
540     @SystemApi
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) {
544         try {
545             mService.registerAppUsageObserver(observerId, packages, timeUnit.toMillis(timeLimit),
546                     callbackIntent, mContext.getOpPackageName());
547         } catch (RemoteException e) {
548         }
549     }
550
551     /**
552      * @hide
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.
559      */
560     @SystemApi
561     @RequiresPermission(android.Manifest.permission.OBSERVE_APP_USAGE)
562     public void unregisterAppUsageObserver(int observerId) {
563         try {
564             mService.unregisterAppUsageObserver(observerId, mContext.getOpPackageName());
565         } catch (RemoteException e) {
566         }
567     }
568
569     /** @hide */
570     public static String reasonToString(int standbyReason) {
571         StringBuilder sb = new StringBuilder();
572         switch (standbyReason & REASON_MAIN_MASK) {
573             case REASON_MAIN_DEFAULT:
574                 sb.append("d");
575                 break;
576             case REASON_MAIN_FORCED:
577                 sb.append("f");
578                 break;
579             case REASON_MAIN_PREDICTED:
580                 sb.append("p");
581                 break;
582             case REASON_MAIN_TIMEOUT:
583                 sb.append("t");
584                 break;
585             case REASON_MAIN_USAGE:
586                 sb.append("u-");
587                 switch (standbyReason & REASON_SUB_MASK) {
588                     case REASON_SUB_USAGE_SYSTEM_INTERACTION:
589                         sb.append("si");
590                         break;
591                     case REASON_SUB_USAGE_NOTIFICATION_SEEN:
592                         sb.append("ns");
593                         break;
594                     case REASON_SUB_USAGE_USER_INTERACTION:
595                         sb.append("ui");
596                         break;
597                     case REASON_SUB_USAGE_MOVE_TO_FOREGROUND:
598                         sb.append("mf");
599                         break;
600                     case REASON_SUB_USAGE_MOVE_TO_BACKGROUND:
601                         sb.append("mb");
602                         break;
603                     case REASON_SUB_USAGE_SYSTEM_UPDATE:
604                         sb.append("su");
605                         break;
606                     case REASON_SUB_USAGE_ACTIVE_TIMEOUT:
607                         sb.append("at");
608                         break;
609                     case REASON_SUB_USAGE_SYNC_ADAPTER:
610                         sb.append("sa");
611                         break;
612                 }
613                 break;
614         }
615         return sb.toString();
616     }
617
618     /**
619      * {@hide}
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)
629      */
630     @SystemApi
631     @RequiresPermission(android.Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST)
632     public void whitelistAppTemporarily(String packageName, long duration, UserHandle user) {
633         try {
634             mService.whitelistAppTemporarily(packageName, duration, user.getIdentifier());
635         } catch (RemoteException re) {
636         }
637     }
638
639     /**
640      * Inform usage stats that the carrier privileged apps access rules have changed.
641      * @hide
642      */
643     public void onCarrierPrivilegedAppsChanged() {
644         try {
645             mService.onCarrierPrivilegedAppsChanged();
646         } catch (RemoteException re) {
647         }
648     }
649
650     /**
651      * Reports a Chooser action to the UsageStatsManager.
652      *
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}
659      * @hide
660      */
661     public void reportChooserSelection(String packageName, int userId, String contentType,
662                                        String[] annotations, String action) {
663         try {
664             mService.reportChooserSelection(packageName, userId, contentType, annotations, action);
665         } catch (RemoteException re) {
666         }
667     }
668 }