UsageStatsManager.java revision 75ad2496ebd8162771687510dfe40b5316cb38bc
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.NonNull;
21import android.annotation.RequiresPermission;
22import android.annotation.SystemApi;
23import android.annotation.SystemService;
24import android.app.PendingIntent;
25import android.content.Context;
26import android.content.pm.ParceledListSlice;
27import android.os.RemoteException;
28import android.os.UserHandle;
29import android.util.ArrayMap;
30
31import java.lang.annotation.Retention;
32import java.lang.annotation.RetentionPolicy;
33import java.util.ArrayList;
34import java.util.Collections;
35import java.util.List;
36import java.util.Map;
37import 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)
67public 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    /** @hide */
183    public static final int REASON_SUB_USAGE_SLICE_PINNED       = 0x0009;
184    /** @hide */
185    public static final int REASON_SUB_USAGE_SLICE_PINNED_PRIV  = 0x000A;
186    /** @hide */
187    public static final int REASON_SUB_USAGE_EXEMPTED_SYNC_START = 0x000B;
188
189    /** @hide */
190    public static final int REASON_SUB_PREDICTED_RESTORED       = 0x0001;
191
192
193    /** @hide */
194    @IntDef(flag = false, prefix = { "STANDBY_BUCKET_" }, value = {
195            STANDBY_BUCKET_EXEMPTED,
196            STANDBY_BUCKET_ACTIVE,
197            STANDBY_BUCKET_WORKING_SET,
198            STANDBY_BUCKET_FREQUENT,
199            STANDBY_BUCKET_RARE,
200            STANDBY_BUCKET_NEVER,
201    })
202    @Retention(RetentionPolicy.SOURCE)
203    public @interface StandbyBuckets {}
204
205    /**
206     * Observer id of the registered observer for the group of packages that reached the usage
207     * time limit. Included as an extra in the PendingIntent that was registered.
208     * @hide
209     */
210    @SystemApi
211    public static final String EXTRA_OBSERVER_ID = "android.app.usage.extra.OBSERVER_ID";
212
213    /**
214     * Original time limit in milliseconds specified by the registered observer for the group of
215     * packages that reached the usage time limit. Included as an extra in the PendingIntent that
216     * was registered.
217     * @hide
218     */
219    @SystemApi
220    public static final String EXTRA_TIME_LIMIT = "android.app.usage.extra.TIME_LIMIT";
221
222    /**
223     * Actual usage time in milliseconds for the group of packages that reached the specified time
224     * limit. Included as an extra in the PendingIntent that was registered.
225     * @hide
226     */
227    @SystemApi
228    public static final String EXTRA_TIME_USED = "android.app.usage.extra.TIME_USED";
229
230    private static final UsageEvents sEmptyResults = new UsageEvents();
231
232    private final Context mContext;
233    private final IUsageStatsManager mService;
234
235    /**
236     * {@hide}
237     */
238    public UsageStatsManager(Context context, IUsageStatsManager service) {
239        mContext = context;
240        mService = service;
241    }
242
243    /**
244     * Gets application usage stats for the given time range, aggregated by the specified interval.
245     * <p>The returned list will contain a {@link UsageStats} object for each package that
246     * has data for an interval that is a subset of the time range given. To illustrate:</p>
247     * <pre>
248     * intervalType = INTERVAL_YEARLY
249     * beginTime = 2013
250     * endTime = 2015 (exclusive)
251     *
252     * Results:
253     * 2013 - com.example.alpha
254     * 2013 - com.example.beta
255     * 2014 - com.example.alpha
256     * 2014 - com.example.beta
257     * 2014 - com.example.charlie
258     * </pre>
259     *
260     * <p> The caller must have {@link android.Manifest.permission#PACKAGE_USAGE_STATS} </p>
261     *
262     * @param intervalType The time interval by which the stats are aggregated.
263     * @param beginTime The inclusive beginning of the range of stats to include in the results.
264     * @param endTime The exclusive end of the range of stats to include in the results.
265     * @return A list of {@link UsageStats}
266     *
267     * @see #INTERVAL_DAILY
268     * @see #INTERVAL_WEEKLY
269     * @see #INTERVAL_MONTHLY
270     * @see #INTERVAL_YEARLY
271     * @see #INTERVAL_BEST
272     */
273    public List<UsageStats> queryUsageStats(int intervalType, long beginTime, long endTime) {
274        try {
275            @SuppressWarnings("unchecked")
276            ParceledListSlice<UsageStats> slice = mService.queryUsageStats(intervalType, beginTime,
277                    endTime, mContext.getOpPackageName());
278            if (slice != null) {
279                return slice.getList();
280            }
281        } catch (RemoteException e) {
282            // fallthrough and return the empty list.
283        }
284        return Collections.emptyList();
285    }
286
287    /**
288     * Gets the hardware configurations the device was in for the given time range, aggregated by
289     * the specified interval. The results are ordered as in
290     * {@link #queryUsageStats(int, long, long)}.
291     * <p> The caller must have {@link android.Manifest.permission#PACKAGE_USAGE_STATS} </p>
292     *
293     * @param intervalType The time interval by which the stats are aggregated.
294     * @param beginTime The inclusive beginning of the range of stats to include in the results.
295     * @param endTime The exclusive end of the range of stats to include in the results.
296     * @return A list of {@link ConfigurationStats}
297     */
298    public List<ConfigurationStats> queryConfigurations(int intervalType, long beginTime,
299            long endTime) {
300        try {
301            @SuppressWarnings("unchecked")
302            ParceledListSlice<ConfigurationStats> slice = mService.queryConfigurationStats(
303                    intervalType, beginTime, endTime, mContext.getOpPackageName());
304            if (slice != null) {
305                return slice.getList();
306            }
307        } catch (RemoteException e) {
308            // fallthrough and return the empty list.
309        }
310        return Collections.emptyList();
311    }
312
313    /**
314     * Gets aggregated event stats for the given time range, aggregated by the specified interval.
315     * <p>The returned list will contain a {@link EventStats} object for each event type that
316     * is being aggregated and has data for an interval that is a subset of the time range given.
317     *
318     * <p>The current event types that will be aggregated here are:</p>
319     * <ul>
320     *     <li>{@link UsageEvents.Event#SCREEN_INTERACTIVE}</li>
321     *     <li>{@link UsageEvents.Event#SCREEN_NON_INTERACTIVE}</li>
322     * </ul>
323     *
324     * <p> The caller must have {@link android.Manifest.permission#PACKAGE_USAGE_STATS} </p>
325     *
326     * @param intervalType The time interval by which the stats are aggregated.
327     * @param beginTime The inclusive beginning of the range of stats to include in the results.
328     * @param endTime The exclusive end of the range of stats to include in the results.
329     * @return A list of {@link EventStats}
330     *
331     * @see #INTERVAL_DAILY
332     * @see #INTERVAL_WEEKLY
333     * @see #INTERVAL_MONTHLY
334     * @see #INTERVAL_YEARLY
335     * @see #INTERVAL_BEST
336     */
337    public List<EventStats> queryEventStats(int intervalType, long beginTime, long endTime) {
338        try {
339            @SuppressWarnings("unchecked")
340            ParceledListSlice<EventStats> slice = mService.queryEventStats(intervalType, beginTime,
341                    endTime, mContext.getOpPackageName());
342            if (slice != null) {
343                return slice.getList();
344            }
345        } catch (RemoteException e) {
346            // fallthrough and return the empty list.
347        }
348        return Collections.emptyList();
349    }
350
351    /**
352     * Query for events in the given time range. Events are only kept by the system for a few
353     * days.
354     * <p> The caller must have {@link android.Manifest.permission#PACKAGE_USAGE_STATS} </p>
355     *
356     * @param beginTime The inclusive beginning of the range of events to include in the results.
357     * @param endTime The exclusive end of the range of events to include in the results.
358     * @return A {@link UsageEvents}.
359     */
360    public UsageEvents queryEvents(long beginTime, long endTime) {
361        try {
362            UsageEvents iter = mService.queryEvents(beginTime, endTime,
363                    mContext.getOpPackageName());
364            if (iter != null) {
365                return iter;
366            }
367        } catch (RemoteException e) {
368            // fallthrough and return empty result.
369        }
370        return sEmptyResults;
371    }
372
373    /**
374     * Like {@link #queryEvents(long, long)}, but only returns events for the calling package.
375     *
376     * @param beginTime The inclusive beginning of the range of events to include in the results.
377     * @param endTime The exclusive end of the range of events to include in the results.
378     * @return A {@link UsageEvents} object.
379     *
380     * @see #queryEvents(long, long)
381     */
382    public UsageEvents queryEventsForSelf(long beginTime, long endTime) {
383        try {
384            final UsageEvents events = mService.queryEventsForPackage(beginTime, endTime,
385                    mContext.getOpPackageName());
386            if (events != null) {
387                return events;
388            }
389        } catch (RemoteException e) {
390            // fallthrough
391        }
392        return sEmptyResults;
393    }
394
395    /**
396     * A convenience method that queries for all stats in the given range (using the best interval
397     * for that range), merges the resulting data, and keys it by package name.
398     * See {@link #queryUsageStats(int, long, long)}.
399     * <p> The caller must have {@link android.Manifest.permission#PACKAGE_USAGE_STATS} </p>
400     *
401     * @param beginTime The inclusive beginning of the range of stats to include in the results.
402     * @param endTime The exclusive end of the range of stats to include in the results.
403     * @return A {@link java.util.Map} keyed by package name
404     */
405    public Map<String, UsageStats> queryAndAggregateUsageStats(long beginTime, long endTime) {
406        List<UsageStats> stats = queryUsageStats(INTERVAL_BEST, beginTime, endTime);
407        if (stats.isEmpty()) {
408            return Collections.emptyMap();
409        }
410
411        ArrayMap<String, UsageStats> aggregatedStats = new ArrayMap<>();
412        final int statCount = stats.size();
413        for (int i = 0; i < statCount; i++) {
414            UsageStats newStat = stats.get(i);
415            UsageStats existingStat = aggregatedStats.get(newStat.getPackageName());
416            if (existingStat == null) {
417                aggregatedStats.put(newStat.mPackageName, newStat);
418            } else {
419                existingStat.add(newStat);
420            }
421        }
422        return aggregatedStats;
423    }
424
425    /**
426     * Returns whether the specified app is currently considered inactive. This will be true if the
427     * app hasn't been used directly or indirectly for a period of time defined by the system. This
428     * could be of the order of several hours or days.
429     * @param packageName The package name of the app to query
430     * @return whether the app is currently considered inactive
431     */
432    public boolean isAppInactive(String packageName) {
433        try {
434            return mService.isAppInactive(packageName, mContext.getUserId());
435        } catch (RemoteException e) {
436            // fall through and return default
437        }
438        return false;
439    }
440
441    /**
442     * {@hide}
443     */
444    public void setAppInactive(String packageName, boolean inactive) {
445        try {
446            mService.setAppInactive(packageName, inactive, mContext.getUserId());
447        } catch (RemoteException e) {
448            // fall through
449        }
450    }
451
452    /**
453     * Returns the current standby bucket of the calling app. The system determines the standby
454     * state of the app based on app usage patterns. Standby buckets determine how much an app will
455     * be restricted from running background tasks such as jobs and alarms.
456     * <p>Restrictions increase progressively from {@link #STANDBY_BUCKET_ACTIVE} to
457     * {@link #STANDBY_BUCKET_RARE}, with {@link #STANDBY_BUCKET_ACTIVE} being the least
458     * restrictive. The battery level of the device might also affect the restrictions.
459     * <p>Apps in buckets &le; {@link #STANDBY_BUCKET_ACTIVE} have no standby restrictions imposed.
460     * Apps in buckets &gt; {@link #STANDBY_BUCKET_FREQUENT} may have network access restricted when
461     * running in the background.
462     * <p>The standby state of an app can change at any time either due to a user interaction or a
463     * system interaction or some algorithm determining that the app can be restricted for a period
464     * of time before the user has a need for it.
465     * <p>You can also query the recent history of standby bucket changes by calling
466     * {@link #queryEventsForSelf(long, long)} and searching for
467     * {@link UsageEvents.Event#STANDBY_BUCKET_CHANGED}.
468     *
469     * @return the current standby bucket of the calling app. One of STANDBY_BUCKET_* constants.
470     */
471    public @StandbyBuckets int getAppStandbyBucket() {
472        try {
473            return mService.getAppStandbyBucket(mContext.getOpPackageName(),
474                    mContext.getOpPackageName(),
475                    mContext.getUserId());
476        } catch (RemoteException e) {
477        }
478        return STANDBY_BUCKET_ACTIVE;
479    }
480
481    /**
482     * {@hide}
483     * Returns the current standby bucket of the specified app. The caller must hold the permission
484     * android.permission.PACKAGE_USAGE_STATS.
485     * @param packageName the package for which to fetch the current standby bucket.
486     */
487    @SystemApi
488    @RequiresPermission(android.Manifest.permission.PACKAGE_USAGE_STATS)
489    public @StandbyBuckets int getAppStandbyBucket(String packageName) {
490        try {
491            return mService.getAppStandbyBucket(packageName, mContext.getOpPackageName(),
492                    mContext.getUserId());
493        } catch (RemoteException e) {
494        }
495        return STANDBY_BUCKET_ACTIVE;
496    }
497
498    /**
499     * {@hide}
500     * Changes an app's standby bucket to the provided value. The caller can only set the standby
501     * bucket for a different app than itself.
502     * @param packageName the package name of the app to set the bucket for. A SecurityException
503     *                    will be thrown if the package name is that of the caller.
504     * @param bucket the standby bucket to set it to, which should be one of STANDBY_BUCKET_*.
505     *               Setting a standby bucket outside of the range of STANDBY_BUCKET_ACTIVE to
506     *               STANDBY_BUCKET_NEVER will result in a SecurityException.
507     */
508    @SystemApi
509    @RequiresPermission(android.Manifest.permission.CHANGE_APP_IDLE_STATE)
510    public void setAppStandbyBucket(String packageName, @StandbyBuckets int bucket) {
511        try {
512            mService.setAppStandbyBucket(packageName, bucket, mContext.getUserId());
513        } catch (RemoteException e) {
514            // Nothing to do
515        }
516    }
517
518    /**
519     * {@hide}
520     * Returns the current standby bucket of every app that has a bucket assigned to it.
521     * The caller must hold the permission android.permission.PACKAGE_USAGE_STATS. The key of the
522     * returned Map is the package name and the value is the bucket assigned to the package.
523     * @see #getAppStandbyBucket()
524     */
525    @SystemApi
526    @RequiresPermission(android.Manifest.permission.PACKAGE_USAGE_STATS)
527    public Map<String, Integer> getAppStandbyBuckets() {
528        try {
529            final ParceledListSlice<AppStandbyInfo> slice = mService.getAppStandbyBuckets(
530                    mContext.getOpPackageName(), mContext.getUserId());
531            final List<AppStandbyInfo> bucketList = slice.getList();
532            final ArrayMap<String, Integer> bucketMap = new ArrayMap<>();
533            final int n = bucketList.size();
534            for (int i = 0; i < n; i++) {
535                final AppStandbyInfo bucketInfo = bucketList.get(i);
536                bucketMap.put(bucketInfo.mPackageName, bucketInfo.mStandbyBucket);
537            }
538            return bucketMap;
539        } catch (RemoteException e) {
540        }
541        return Collections.EMPTY_MAP;
542    }
543
544    /**
545     * {@hide}
546     * Changes the app standby bucket for multiple apps at once. The Map is keyed by the package
547     * name and the value is one of STANDBY_BUCKET_*.
548     * @param appBuckets a map of package name to bucket value.
549     */
550    @SystemApi
551    @RequiresPermission(android.Manifest.permission.CHANGE_APP_IDLE_STATE)
552    public void setAppStandbyBuckets(Map<String, Integer> appBuckets) {
553        if (appBuckets == null) {
554            return;
555        }
556        final List<AppStandbyInfo> bucketInfoList = new ArrayList<>(appBuckets.size());
557        for (Map.Entry<String, Integer> bucketEntry : appBuckets.entrySet()) {
558            bucketInfoList.add(new AppStandbyInfo(bucketEntry.getKey(), bucketEntry.getValue()));
559        }
560        final ParceledListSlice<AppStandbyInfo> slice = new ParceledListSlice<>(bucketInfoList);
561        try {
562            mService.setAppStandbyBuckets(slice, mContext.getUserId());
563        } catch (RemoteException e) {
564        }
565    }
566
567    /**
568     * @hide
569     * Register an app usage limit observer that receives a callback on the provided intent when
570     * the sum of usages of apps in the packages array exceeds the {@code timeLimit} specified. The
571     * observer will automatically be unregistered when the time limit is reached and the intent
572     * is delivered. Registering an {@code observerId} that was already registered will override
573     * the previous one.
574     * @param observerId A unique id associated with the group of apps to be monitored. There can
575     *                  be multiple groups with common packages and different time limits.
576     * @param packages The list of packages to observe for foreground activity time. Cannot be null
577     *                 and must include at least one package.
578     * @param timeLimit The total time the set of apps can be in the foreground before the
579     *                  callbackIntent is delivered. Must be greater than 0.
580     * @param timeUnit The unit for time specified in {@code timeLimit}. Cannot be null.
581     * @param callbackIntent The PendingIntent that will be dispatched when the time limit is
582     *                       exceeded by the group of apps. The delivered Intent will also contain
583     *                       the extras {@link #EXTRA_OBSERVER_ID}, {@link #EXTRA_TIME_LIMIT} and
584     *                       {@link #EXTRA_TIME_USED}. Cannot be null.
585     * @throws SecurityException if the caller doesn't have the OBSERVE_APP_USAGE permission or
586     *                           is not the profile owner of this user.
587     */
588    @SystemApi
589    @RequiresPermission(android.Manifest.permission.OBSERVE_APP_USAGE)
590    public void registerAppUsageObserver(int observerId, @NonNull String[] packages, long timeLimit,
591            @NonNull TimeUnit timeUnit, @NonNull PendingIntent callbackIntent) {
592        try {
593            mService.registerAppUsageObserver(observerId, packages, timeUnit.toMillis(timeLimit),
594                    callbackIntent, mContext.getOpPackageName());
595        } catch (RemoteException e) {
596        }
597    }
598
599    /**
600     * @hide
601     * Unregister the app usage observer specified by the {@code observerId}. This will only apply
602     * to any observer registered by this application. Unregistering an observer that was already
603     * unregistered or never registered will have no effect.
604     * @param observerId The id of the observer that was previously registered.
605     * @throws SecurityException if the caller doesn't have the OBSERVE_APP_USAGE permission or is
606     *                           not the profile owner of this user.
607     */
608    @SystemApi
609    @RequiresPermission(android.Manifest.permission.OBSERVE_APP_USAGE)
610    public void unregisterAppUsageObserver(int observerId) {
611        try {
612            mService.unregisterAppUsageObserver(observerId, mContext.getOpPackageName());
613        } catch (RemoteException e) {
614        }
615    }
616
617    /** @hide */
618    public static String reasonToString(int standbyReason) {
619        StringBuilder sb = new StringBuilder();
620        switch (standbyReason & REASON_MAIN_MASK) {
621            case REASON_MAIN_DEFAULT:
622                sb.append("d");
623                break;
624            case REASON_MAIN_FORCED:
625                sb.append("f");
626                break;
627            case REASON_MAIN_PREDICTED:
628                sb.append("p");
629                switch (standbyReason & REASON_SUB_MASK) {
630                    case REASON_SUB_PREDICTED_RESTORED:
631                        sb.append("-r");
632                        break;
633                }
634                break;
635            case REASON_MAIN_TIMEOUT:
636                sb.append("t");
637                break;
638            case REASON_MAIN_USAGE:
639                sb.append("u");
640                switch (standbyReason & REASON_SUB_MASK) {
641                    case REASON_SUB_USAGE_SYSTEM_INTERACTION:
642                        sb.append("-si");
643                        break;
644                    case REASON_SUB_USAGE_NOTIFICATION_SEEN:
645                        sb.append("-ns");
646                        break;
647                    case REASON_SUB_USAGE_USER_INTERACTION:
648                        sb.append("-ui");
649                        break;
650                    case REASON_SUB_USAGE_MOVE_TO_FOREGROUND:
651                        sb.append("-mf");
652                        break;
653                    case REASON_SUB_USAGE_MOVE_TO_BACKGROUND:
654                        sb.append("-mb");
655                        break;
656                    case REASON_SUB_USAGE_SYSTEM_UPDATE:
657                        sb.append("-su");
658                        break;
659                    case REASON_SUB_USAGE_ACTIVE_TIMEOUT:
660                        sb.append("-at");
661                        break;
662                    case REASON_SUB_USAGE_SYNC_ADAPTER:
663                        sb.append("-sa");
664                        break;
665                    case REASON_SUB_USAGE_SLICE_PINNED:
666                        sb.append("slp");
667                        break;
668                    case REASON_SUB_USAGE_SLICE_PINNED_PRIV:
669                        sb.append("slpp");
670                        break;
671                    case REASON_SUB_USAGE_EXEMPTED_SYNC_START:
672                        sb.append("es");
673                        break;
674                }
675                break;
676        }
677        return sb.toString();
678    }
679
680    /**
681     * {@hide}
682     * Temporarily whitelist the specified app for a short duration. This is to allow an app
683     * receiving a high priority message to be able to access the network and acquire wakelocks
684     * even if the device is in power-save mode or the app is currently considered inactive.
685     * @param packageName The package name of the app to whitelist.
686     * @param duration Duration to whitelist the app for, in milliseconds. It is recommended that
687     * this be limited to 10s of seconds. Requested duration will be clamped to a few minutes.
688     * @param user The user for whom the package should be whitelisted. Passing in a user that is
689     * not the same as the caller's process will require the INTERACT_ACROSS_USERS permission.
690     * @see #isAppInactive(String)
691     */
692    @SystemApi
693    @RequiresPermission(android.Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST)
694    public void whitelistAppTemporarily(String packageName, long duration, UserHandle user) {
695        try {
696            mService.whitelistAppTemporarily(packageName, duration, user.getIdentifier());
697        } catch (RemoteException re) {
698        }
699    }
700
701    /**
702     * Inform usage stats that the carrier privileged apps access rules have changed.
703     * @hide
704     */
705    public void onCarrierPrivilegedAppsChanged() {
706        try {
707            mService.onCarrierPrivilegedAppsChanged();
708        } catch (RemoteException re) {
709        }
710    }
711
712    /**
713     * Reports a Chooser action to the UsageStatsManager.
714     *
715     * @param packageName The package name of the app that is selected.
716     * @param userId The user id of who makes the selection.
717     * @param contentType The type of the content, e.g., Image, Video, App.
718     * @param annotations The annotations of the content, e.g., Game, Selfie.
719     * @param action The action type of Intent that invokes ChooserActivity.
720     * {@link UsageEvents}
721     * @hide
722     */
723    public void reportChooserSelection(String packageName, int userId, String contentType,
724                                       String[] annotations, String action) {
725        try {
726            mService.reportChooserSelection(packageName, userId, contentType, annotations, action);
727        } catch (RemoteException re) {
728        }
729    }
730}
731