UsageStatsManager.java revision 853e53f6e8063362cfa5f6417a1c15cddf01601f
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
17package android.app.usage;
18
19import android.annotation.IntDef;
20import android.annotation.RequiresPermission;
21import android.annotation.SystemApi;
22import android.annotation.SystemService;
23import android.app.PendingIntent;
24import android.content.Context;
25import android.content.pm.ParceledListSlice;
26import android.os.RemoteException;
27import android.os.UserHandle;
28import android.util.ArrayMap;
29
30import java.lang.annotation.Retention;
31import java.lang.annotation.RetentionPolicy;
32import java.util.ArrayList;
33import java.util.Collections;
34import java.util.List;
35import java.util.Map;
36import java.util.concurrent.TimeUnit;
37
38/**
39 * Provides access to device usage history and statistics. Usage data is aggregated into
40 * time intervals: days, weeks, months, and years.
41 * <p />
42 * When requesting usage data since a particular time, the request might look something like this:
43 * <pre>
44 * PAST                   REQUEST_TIME                    TODAY                   FUTURE
45 * ————————————————————————————||———————————————————————————¦-----------------------|
46 *                        YEAR ||                           ¦                       |
47 * ————————————————————————————||———————————————————————————¦-----------------------|
48 *  MONTH            |         ||                MONTH      ¦                       |
49 * ——————————————————|—————————||———————————————————————————¦-----------------------|
50 *   |      WEEK     |     WEEK||    |     WEEK     |     WE¦EK     |      WEEK     |
51 * ————————————————————————————||———————————————————|———————¦-----------------------|
52 *                             ||           |DAY|DAY|DAY|DAY¦DAY|DAY|DAY|DAY|DAY|DAY|
53 * ————————————————————————————||———————————————————————————¦-----------------------|
54 * </pre>
55 * A request for data in the middle of a time interval will include that interval.
56 * <p/>
57 * <b>NOTE:</b> Most methods on this API require the permission
58 * android.permission.PACKAGE_USAGE_STATS. However, declaring the permission implies intention to
59 * use the API and the user of the device still needs to grant permission through the Settings
60 * application.
61 * See {@link android.provider.Settings#ACTION_USAGE_ACCESS_SETTINGS}.
62 * Methods which only return the information for the calling package do not require this permission.
63 * E.g. {@link #getAppStandbyBucket()} and {@link #queryEventsForSelf(long, long)}.
64 */
65@SystemService(Context.USAGE_STATS_SERVICE)
66public final class UsageStatsManager {
67
68    /**
69     * An interval type that spans a day. See {@link #queryUsageStats(int, long, long)}.
70     */
71    public static final int INTERVAL_DAILY = 0;
72
73    /**
74     * An interval type that spans a week. See {@link #queryUsageStats(int, long, long)}.
75     */
76    public static final int INTERVAL_WEEKLY = 1;
77
78    /**
79     * An interval type that spans a month. See {@link #queryUsageStats(int, long, long)}.
80     */
81    public static final int INTERVAL_MONTHLY = 2;
82
83    /**
84     * An interval type that spans a year. See {@link #queryUsageStats(int, long, long)}.
85     */
86    public static final int INTERVAL_YEARLY = 3;
87
88    /**
89     * An interval type that will use the best fit interval for the given time range.
90     * See {@link #queryUsageStats(int, long, long)}.
91     */
92    public static final int INTERVAL_BEST = 4;
93
94    /**
95     * The number of available intervals. Does not include {@link #INTERVAL_BEST}, since it
96     * is a pseudo interval (it actually selects a real interval).
97     * {@hide}
98     */
99    public static final int INTERVAL_COUNT = 4;
100
101
102    /**
103     * The app is whitelisted for some reason and the bucket cannot be changed.
104     * {@hide}
105     */
106    @SystemApi
107    public static final int STANDBY_BUCKET_EXEMPTED = 5;
108
109    /**
110     * The app was used very recently, currently in use or likely to be used very soon. Standby
111     * bucket values that are &le; {@link #STANDBY_BUCKET_ACTIVE} will not be throttled by the
112     * system while they are in this bucket. Buckets &gt; {@link #STANDBY_BUCKET_ACTIVE} will most
113     * likely be restricted in some way. For instance, jobs and alarms may be deferred.
114     * @see #getAppStandbyBucket()
115     */
116    public static final int STANDBY_BUCKET_ACTIVE = 10;
117
118    /**
119     * The app was used recently and/or likely to be used in the next few hours. Restrictions will
120     * apply to these apps, such as deferral of jobs and alarms.
121     * @see #getAppStandbyBucket()
122     */
123    public static final int STANDBY_BUCKET_WORKING_SET = 20;
124
125    /**
126     * The app was used in the last few days and/or likely to be used in the next few days.
127     * Restrictions will apply to these apps, such as deferral of jobs and alarms. The delays may be
128     * greater than for apps in higher buckets (lower bucket value). Bucket values &gt;
129     * {@link #STANDBY_BUCKET_FREQUENT} may additionally have network access limited.
130     * @see #getAppStandbyBucket()
131     */
132    public static final int STANDBY_BUCKET_FREQUENT = 30;
133
134    /**
135     * The app has not be used for several days and/or is unlikely to be used for several days.
136     * Apps in this bucket will have the most restrictions, including network restrictions, except
137     * during certain short periods (at a minimum, once a day) when they are allowed to execute
138     * jobs, access the network, etc.
139     * @see #getAppStandbyBucket()
140     */
141    public static final int STANDBY_BUCKET_RARE = 40;
142
143    /**
144     * The app has never been used.
145     * {@hide}
146     */
147    @SystemApi
148    public static final int STANDBY_BUCKET_NEVER = 50;
149
150    /** @hide */
151    public static final int REASON_MAIN_MASK = 0xFF00;
152    /** @hide */
153    public static final int REASON_MAIN_DEFAULT =   0x0100;
154    /** @hide */
155    public static final int REASON_MAIN_TIMEOUT =   0x0200;
156    /** @hide */
157    public static final int REASON_MAIN_USAGE =     0x0300;
158    /** @hide */
159    public static final int REASON_MAIN_FORCED =    0x0400;
160    /** @hide */
161    public static final int REASON_MAIN_PREDICTED = 0x0500;
162
163    /** @hide */
164    public static final int REASON_SUB_MASK = 0x00FF;
165    /** @hide */
166    public static final int REASON_SUB_USAGE_SYSTEM_INTERACTION = 0x0001;
167    /** @hide */
168    public static final int REASON_SUB_USAGE_NOTIFICATION_SEEN  = 0x0002;
169    /** @hide */
170    public static final int REASON_SUB_USAGE_USER_INTERACTION   = 0x0003;
171    /** @hide */
172    public static final int REASON_SUB_USAGE_MOVE_TO_FOREGROUND = 0x0004;
173    /** @hide */
174    public static final int REASON_SUB_USAGE_MOVE_TO_BACKGROUND = 0x0005;
175    /** @hide */
176    public static final int REASON_SUB_USAGE_SYSTEM_UPDATE      = 0x0006;
177    /** @hide */
178    public static final int REASON_SUB_USAGE_ACTIVE_TIMEOUT     = 0x0007;
179    /** @hide */
180    public static final int REASON_SUB_USAGE_SYNC_ADAPTER       = 0x0008;
181
182    /** @hide */
183    @IntDef(flag = false, prefix = { "STANDBY_BUCKET_" }, value = {
184            STANDBY_BUCKET_EXEMPTED,
185            STANDBY_BUCKET_ACTIVE,
186            STANDBY_BUCKET_WORKING_SET,
187            STANDBY_BUCKET_FREQUENT,
188            STANDBY_BUCKET_RARE,
189            STANDBY_BUCKET_NEVER,
190    })
191    @Retention(RetentionPolicy.SOURCE)
192    public @interface StandbyBuckets {}
193
194    /**
195     * Observer id of the registered observer for the group of packages that reached the usage
196     * time limit. Included as an extra in the PendingIntent that was registered.
197     * @hide
198     */
199    @SystemApi
200    public static final String EXTRA_OBSERVER_ID = "android.app.usage.extra.OBSERVER_ID";
201
202    /**
203     * Original time limit in milliseconds specified by the registered observer for the group of
204     * packages that reached the usage time limit. Included as an extra in the PendingIntent that
205     * was registered.
206     * @hide
207     */
208    @SystemApi
209    public static final String EXTRA_TIME_LIMIT = "android.app.usage.extra.TIME_LIMIT";
210
211    /**
212     * Actual usage time in milliseconds for the group of packages that reached the specified time
213     * limit. Included as an extra in the PendingIntent that was registered.
214     * @hide
215     */
216    @SystemApi
217    public static final String EXTRA_TIME_USED = "android.app.usage.extra.TIME_USED";
218
219    private static final UsageEvents sEmptyResults = new UsageEvents();
220
221    private final Context mContext;
222    private final IUsageStatsManager mService;
223
224    /**
225     * {@hide}
226     */
227    public UsageStatsManager(Context context, IUsageStatsManager service) {
228        mContext = context;
229        mService = service;
230    }
231
232    /**
233     * Gets application usage stats for the given time range, aggregated by the specified interval.
234     * <p>The returned list will contain a {@link UsageStats} object for each package that
235     * has data for an interval that is a subset of the time range given. To illustrate:</p>
236     * <pre>
237     * intervalType = INTERVAL_YEARLY
238     * beginTime = 2013
239     * endTime = 2015 (exclusive)
240     *
241     * Results:
242     * 2013 - com.example.alpha
243     * 2013 - com.example.beta
244     * 2014 - com.example.alpha
245     * 2014 - com.example.beta
246     * 2014 - com.example.charlie
247     * </pre>
248     *
249     * <p> The caller must have {@link android.Manifest.permission#PACKAGE_USAGE_STATS} </p>
250     *
251     * @param intervalType The time interval by which the stats are aggregated.
252     * @param beginTime The inclusive beginning of the range of stats to include in the results.
253     * @param endTime The exclusive end of the range of stats to include in the results.
254     * @return A list of {@link UsageStats}
255     *
256     * @see #INTERVAL_DAILY
257     * @see #INTERVAL_WEEKLY
258     * @see #INTERVAL_MONTHLY
259     * @see #INTERVAL_YEARLY
260     * @see #INTERVAL_BEST
261     */
262    public List<UsageStats> queryUsageStats(int intervalType, long beginTime, long endTime) {
263        try {
264            @SuppressWarnings("unchecked")
265            ParceledListSlice<UsageStats> slice = mService.queryUsageStats(intervalType, beginTime,
266                    endTime, mContext.getOpPackageName());
267            if (slice != null) {
268                return slice.getList();
269            }
270        } catch (RemoteException e) {
271            // fallthrough and return the empty list.
272        }
273        return Collections.emptyList();
274    }
275
276    /**
277     * Gets the hardware configurations the device was in for the given time range, aggregated by
278     * the specified interval. The results are ordered as in
279     * {@link #queryUsageStats(int, long, long)}.
280     * <p> The caller must have {@link android.Manifest.permission#PACKAGE_USAGE_STATS} </p>
281     *
282     * @param intervalType The time interval by which the stats are aggregated.
283     * @param beginTime The inclusive beginning of the range of stats to include in the results.
284     * @param endTime The exclusive end of the range of stats to include in the results.
285     * @return A list of {@link ConfigurationStats}
286     */
287    public List<ConfigurationStats> queryConfigurations(int intervalType, long beginTime,
288            long endTime) {
289        try {
290            @SuppressWarnings("unchecked")
291            ParceledListSlice<ConfigurationStats> slice = mService.queryConfigurationStats(
292                    intervalType, beginTime, endTime, mContext.getOpPackageName());
293            if (slice != null) {
294                return slice.getList();
295            }
296        } catch (RemoteException e) {
297            // fallthrough and return the empty list.
298        }
299        return Collections.emptyList();
300    }
301
302    /**
303     * Query for events in the given time range. Events are only kept by the system for a few
304     * days.
305     * <p> The caller must have {@link android.Manifest.permission#PACKAGE_USAGE_STATS} </p>
306     *
307     * @param beginTime The inclusive beginning of the range of events to include in the results.
308     * @param endTime The exclusive end of the range of events to include in the results.
309     * @return A {@link UsageEvents}.
310     */
311    public UsageEvents queryEvents(long beginTime, long endTime) {
312        try {
313            UsageEvents iter = mService.queryEvents(beginTime, endTime,
314                    mContext.getOpPackageName());
315            if (iter != null) {
316                return iter;
317            }
318        } catch (RemoteException e) {
319            // fallthrough and return empty result.
320        }
321        return sEmptyResults;
322    }
323
324    /**
325     * Like {@link #queryEvents(long, long)}, but only returns events for the calling package.
326     *
327     * @param beginTime The inclusive beginning of the range of events to include in the results.
328     * @param endTime The exclusive end of the range of events to include in the results.
329     * @return A {@link UsageEvents} object.
330     *
331     * @see #queryEvents(long, long)
332     */
333    public UsageEvents queryEventsForSelf(long beginTime, long endTime) {
334        try {
335            final UsageEvents events = mService.queryEventsForPackage(beginTime, endTime,
336                    mContext.getOpPackageName());
337            if (events != null) {
338                return events;
339            }
340        } catch (RemoteException e) {
341            // fallthrough
342        }
343        return sEmptyResults;
344    }
345
346    /**
347     * A convenience method that queries for all stats in the given range (using the best interval
348     * for that range), merges the resulting data, and keys it by package name.
349     * See {@link #queryUsageStats(int, long, long)}.
350     * <p> The caller must have {@link android.Manifest.permission#PACKAGE_USAGE_STATS} </p>
351     *
352     * @param beginTime The inclusive beginning of the range of stats to include in the results.
353     * @param endTime The exclusive end of the range of stats to include in the results.
354     * @return A {@link java.util.Map} keyed by package name
355     */
356    public Map<String, UsageStats> queryAndAggregateUsageStats(long beginTime, long endTime) {
357        List<UsageStats> stats = queryUsageStats(INTERVAL_BEST, beginTime, endTime);
358        if (stats.isEmpty()) {
359            return Collections.emptyMap();
360        }
361
362        ArrayMap<String, UsageStats> aggregatedStats = new ArrayMap<>();
363        final int statCount = stats.size();
364        for (int i = 0; i < statCount; i++) {
365            UsageStats newStat = stats.get(i);
366            UsageStats existingStat = aggregatedStats.get(newStat.getPackageName());
367            if (existingStat == null) {
368                aggregatedStats.put(newStat.mPackageName, newStat);
369            } else {
370                existingStat.add(newStat);
371            }
372        }
373        return aggregatedStats;
374    }
375
376    /**
377     * Returns whether the specified app is currently considered inactive. This will be true if the
378     * app hasn't been used directly or indirectly for a period of time defined by the system. This
379     * could be of the order of several hours or days.
380     * @param packageName The package name of the app to query
381     * @return whether the app is currently considered inactive
382     */
383    public boolean isAppInactive(String packageName) {
384        try {
385            return mService.isAppInactive(packageName, mContext.getUserId());
386        } catch (RemoteException e) {
387            // fall through and return default
388        }
389        return false;
390    }
391
392    /**
393     * {@hide}
394     */
395    public void setAppInactive(String packageName, boolean inactive) {
396        try {
397            mService.setAppInactive(packageName, inactive, mContext.getUserId());
398        } catch (RemoteException e) {
399            // fall through
400        }
401    }
402
403    /**
404     * Returns the current standby bucket of the calling app. The system determines the standby
405     * state of the app based on app usage patterns. Standby buckets determine how much an app will
406     * be restricted from running background tasks such as jobs and alarms.
407     * <p>Restrictions increase progressively from {@link #STANDBY_BUCKET_ACTIVE} to
408     * {@link #STANDBY_BUCKET_RARE}, with {@link #STANDBY_BUCKET_ACTIVE} being the least
409     * restrictive. The battery level of the device might also affect the restrictions.
410     * <p>Apps in buckets &le; {@link #STANDBY_BUCKET_ACTIVE} have no standby restrictions imposed.
411     * Apps in buckets &gt; {@link #STANDBY_BUCKET_FREQUENT} may have network access restricted when
412     * running in the background.
413     * <p>The standby state of an app can change at any time either due to a user interaction or a
414     * system interaction or some algorithm determining that the app can be restricted for a period
415     * of time before the user has a need for it.
416     * <p>You can also query the recent history of standby bucket changes by calling
417     * {@link #queryEventsForSelf(long, long)} and searching for
418     * {@link UsageEvents.Event#STANDBY_BUCKET_CHANGED}.
419     *
420     * @return the current standby bucket of the calling app. One of STANDBY_BUCKET_* constants.
421     */
422    public @StandbyBuckets int getAppStandbyBucket() {
423        try {
424            return mService.getAppStandbyBucket(mContext.getOpPackageName(),
425                    mContext.getOpPackageName(),
426                    mContext.getUserId());
427        } catch (RemoteException e) {
428        }
429        return STANDBY_BUCKET_ACTIVE;
430    }
431
432    /**
433     * {@hide}
434     * Returns the current standby bucket of the specified app. The caller must hold the permission
435     * android.permission.PACKAGE_USAGE_STATS.
436     * @param packageName the package for which to fetch the current standby bucket.
437     */
438    @SystemApi
439    @RequiresPermission(android.Manifest.permission.PACKAGE_USAGE_STATS)
440    public @StandbyBuckets int getAppStandbyBucket(String packageName) {
441        try {
442            return mService.getAppStandbyBucket(packageName, mContext.getOpPackageName(),
443                    mContext.getUserId());
444        } catch (RemoteException e) {
445        }
446        return STANDBY_BUCKET_ACTIVE;
447    }
448
449    /**
450     * {@hide}
451     * Changes an app's standby bucket to the provided value. The caller can only set the standby
452     * bucket for a different app than itself.
453     * @param packageName the package name of the app to set the bucket for. A SecurityException
454     *                    will be thrown if the package name is that of the caller.
455     * @param bucket the standby bucket to set it to, which should be one of STANDBY_BUCKET_*.
456     *               Setting a standby bucket outside of the range of STANDBY_BUCKET_ACTIVE to
457     *               STANDBY_BUCKET_NEVER will result in a SecurityException.
458     */
459    @SystemApi
460    @RequiresPermission(android.Manifest.permission.CHANGE_APP_IDLE_STATE)
461    public void setAppStandbyBucket(String packageName, @StandbyBuckets int bucket) {
462        try {
463            mService.setAppStandbyBucket(packageName, bucket, mContext.getUserId());
464        } catch (RemoteException e) {
465            // Nothing to do
466        }
467    }
468
469    /**
470     * {@hide}
471     * Returns the current standby bucket of every app that has a bucket assigned to it.
472     * The caller must hold the permission android.permission.PACKAGE_USAGE_STATS. The key of the
473     * returned Map is the package name and the value is the bucket assigned to the package.
474     * @see #getAppStandbyBucket()
475     */
476    @SystemApi
477    @RequiresPermission(android.Manifest.permission.PACKAGE_USAGE_STATS)
478    public Map<String, Integer> getAppStandbyBuckets() {
479        try {
480            final ParceledListSlice<AppStandbyInfo> slice = mService.getAppStandbyBuckets(
481                    mContext.getOpPackageName(), mContext.getUserId());
482            final List<AppStandbyInfo> bucketList = slice.getList();
483            final ArrayMap<String, Integer> bucketMap = new ArrayMap<>();
484            final int n = bucketList.size();
485            for (int i = 0; i < n; i++) {
486                final AppStandbyInfo bucketInfo = bucketList.get(i);
487                bucketMap.put(bucketInfo.mPackageName, bucketInfo.mStandbyBucket);
488            }
489            return bucketMap;
490        } catch (RemoteException e) {
491        }
492        return Collections.EMPTY_MAP;
493    }
494
495    /**
496     * {@hide}
497     * Changes the app standby bucket for multiple apps at once. The Map is keyed by the package
498     * name and the value is one of STANDBY_BUCKET_*.
499     * @param appBuckets a map of package name to bucket value.
500     */
501    @SystemApi
502    @RequiresPermission(android.Manifest.permission.CHANGE_APP_IDLE_STATE)
503    public void setAppStandbyBuckets(Map<String, Integer> appBuckets) {
504        if (appBuckets == null) {
505            return;
506        }
507        final List<AppStandbyInfo> bucketInfoList = new ArrayList<>(appBuckets.size());
508        for (Map.Entry<String, Integer> bucketEntry : appBuckets.entrySet()) {
509            bucketInfoList.add(new AppStandbyInfo(bucketEntry.getKey(), bucketEntry.getValue()));
510        }
511        final ParceledListSlice<AppStandbyInfo> slice = new ParceledListSlice<>(bucketInfoList);
512        try {
513            mService.setAppStandbyBuckets(slice, mContext.getUserId());
514        } catch (RemoteException e) {
515        }
516    }
517
518    /**
519     * @hide
520     * Register an app usage limit observer that receives a callback on the provided intent when
521     * the sum of usages of apps in the packages array exceeds the timeLimit specified. The
522     * observer will automatically be unregistered when the time limit is reached and the intent
523     * is delivered.
524     * @param observerId A unique id associated with the group of apps to be monitored. There can
525     *                  be multiple groups with common packages and different time limits.
526     * @param packages The list of packages to observe for foreground activity time. Must include
527     *                 at least one package.
528     * @param timeLimit The total time the set of apps can be in the foreground before the
529     *                  callbackIntent is delivered. Must be greater than 0.
530     * @param timeUnit The unit for time specified in timeLimit.
531     * @param callbackIntent The PendingIntent that will be dispatched when the time limit is
532     *                       exceeded by the group of apps. The delivered Intent will also contain
533     *                       the extras {@link #EXTRA_OBSERVER_ID}, {@link #EXTRA_TIME_LIMIT} and
534     *                       {@link #EXTRA_TIME_USED}.
535     * @throws SecurityException if the caller doesn't have the PACKAGE_USAGE_STATS permission.
536     */
537    @SystemApi
538    @RequiresPermission(android.Manifest.permission.PACKAGE_USAGE_STATS)
539    public void registerAppUsageObserver(int observerId, String[] packages, long timeLimit,
540            TimeUnit timeUnit, PendingIntent callbackIntent) {
541        try {
542            mService.registerAppUsageObserver(observerId, packages, timeUnit.toMillis(timeLimit),
543                    callbackIntent, mContext.getOpPackageName());
544        } catch (RemoteException e) {
545        }
546    }
547
548    /**
549     * @hide
550     * Unregister the app usage observer specified by the observerId. This will only apply to any
551     * observer registered by this application. Unregistering an observer that was already
552     * unregistered or never registered will have no effect.
553     * @param observerId The id of the observer that was previously registered.
554     * @throws SecurityException if the caller doesn't have the PACKAGE_USAGE_STATS permission.
555     */
556    @SystemApi
557    @RequiresPermission(android.Manifest.permission.PACKAGE_USAGE_STATS)
558    public void unregisterAppUsageObserver(int observerId) {
559        try {
560            mService.unregisterAppUsageObserver(observerId, mContext.getOpPackageName());
561        } catch (RemoteException e) {
562        }
563    }
564
565    /** @hide */
566    public static String reasonToString(int standbyReason) {
567        StringBuilder sb = new StringBuilder();
568        switch (standbyReason & REASON_MAIN_MASK) {
569            case REASON_MAIN_DEFAULT:
570                sb.append("d");
571                break;
572            case REASON_MAIN_FORCED:
573                sb.append("f");
574                break;
575            case REASON_MAIN_PREDICTED:
576                sb.append("p");
577                break;
578            case REASON_MAIN_TIMEOUT:
579                sb.append("t");
580                break;
581            case REASON_MAIN_USAGE:
582                sb.append("u-");
583                switch (standbyReason & REASON_SUB_MASK) {
584                    case REASON_SUB_USAGE_SYSTEM_INTERACTION:
585                        sb.append("si");
586                        break;
587                    case REASON_SUB_USAGE_NOTIFICATION_SEEN:
588                        sb.append("ns");
589                        break;
590                    case REASON_SUB_USAGE_USER_INTERACTION:
591                        sb.append("ui");
592                        break;
593                    case REASON_SUB_USAGE_MOVE_TO_FOREGROUND:
594                        sb.append("mf");
595                        break;
596                    case REASON_SUB_USAGE_MOVE_TO_BACKGROUND:
597                        sb.append("mb");
598                        break;
599                    case REASON_SUB_USAGE_SYSTEM_UPDATE:
600                        sb.append("su");
601                        break;
602                    case REASON_SUB_USAGE_ACTIVE_TIMEOUT:
603                        sb.append("at");
604                        break;
605                    case REASON_SUB_USAGE_SYNC_ADAPTER:
606                        sb.append("sa");
607                        break;
608                }
609                break;
610        }
611        return sb.toString();
612    }
613
614    /**
615     * {@hide}
616     * Temporarily whitelist the specified app for a short duration. This is to allow an app
617     * receiving a high priority message to be able to access the network and acquire wakelocks
618     * even if the device is in power-save mode or the app is currently considered inactive.
619     * @param packageName The package name of the app to whitelist.
620     * @param duration Duration to whitelist the app for, in milliseconds. It is recommended that
621     * this be limited to 10s of seconds. Requested duration will be clamped to a few minutes.
622     * @param user The user for whom the package should be whitelisted. Passing in a user that is
623     * not the same as the caller's process will require the INTERACT_ACROSS_USERS permission.
624     * @see #isAppInactive(String)
625     */
626    @SystemApi
627    @RequiresPermission(android.Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST)
628    public void whitelistAppTemporarily(String packageName, long duration, UserHandle user) {
629        try {
630            mService.whitelistAppTemporarily(packageName, duration, user.getIdentifier());
631        } catch (RemoteException re) {
632        }
633    }
634
635    /**
636     * Inform usage stats that the carrier privileged apps access rules have changed.
637     * @hide
638     */
639    public void onCarrierPrivilegedAppsChanged() {
640        try {
641            mService.onCarrierPrivilegedAppsChanged();
642        } catch (RemoteException re) {
643        }
644    }
645
646    /**
647     * Reports a Chooser action to the UsageStatsManager.
648     *
649     * @param packageName The package name of the app that is selected.
650     * @param userId The user id of who makes the selection.
651     * @param contentType The type of the content, e.g., Image, Video, App.
652     * @param annotations The annotations of the content, e.g., Game, Selfie.
653     * @param action The action type of Intent that invokes ChooserActivity.
654     * {@link UsageEvents}
655     * @hide
656     */
657    public void reportChooserSelection(String packageName, int userId, String contentType,
658                                       String[] annotations, String action) {
659        try {
660            mService.reportChooserSelection(packageName, userId, contentType, annotations, action);
661        } catch (RemoteException re) {
662        }
663    }
664}
665