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.Manifest;
20 import android.annotation.CurrentTimeMillisLong;
21 import android.annotation.FlaggedApi;
22 import android.annotation.IntDef;
23 import android.annotation.IntRange;
24 import android.annotation.NonNull;
25 import android.annotation.Nullable;
26 import android.annotation.RequiresPermission;
27 import android.annotation.SystemApi;
28 import android.annotation.SystemService;
29 import android.annotation.TestApi;
30 import android.annotation.UserHandleAware;
31 import android.annotation.UserIdInt;
32 import android.app.Activity;
33 import android.app.BroadcastOptions;
34 import android.app.PendingIntent;
35 import android.compat.annotation.UnsupportedAppUsage;
36 import android.content.Context;
37 import android.content.pm.ParceledListSlice;
38 import android.os.Build;
39 import android.os.PersistableBundle;
40 import android.os.PowerWhitelistManager;
41 import android.os.RemoteException;
42 import android.os.UserHandle;
43 import android.os.UserManager;
44 import android.util.ArrayMap;
45 
46 import java.lang.annotation.Retention;
47 import java.lang.annotation.RetentionPolicy;
48 import java.time.Duration;
49 import java.util.ArrayList;
50 import java.util.Collections;
51 import java.util.List;
52 import java.util.Map;
53 import java.util.concurrent.TimeUnit;
54 
55 /**
56  * Provides access to device usage history and statistics. Usage data is aggregated into
57  * time intervals: days, weeks, months, and years.
58  * <p />
59  * When requesting usage data since a particular time, the request might look something like this:
60  * <pre>
61  * PAST                   REQUEST_TIME                    TODAY                   FUTURE
62  * ————————————————————————————||———————————————————————————¦-----------------------|
63  *                        YEAR ||                           ¦                       |
64  * ————————————————————————————||———————————————————————————¦-----------------------|
65  *  MONTH            |         ||                MONTH      ¦                       |
66  * ——————————————————|—————————||———————————————————————————¦-----------------------|
67  *   |      WEEK     |     WEEK||    |     WEEK     |     WE¦EK     |      WEEK     |
68  * ————————————————————————————||———————————————————|———————¦-----------------------|
69  *                             ||           |DAY|DAY|DAY|DAY¦DAY|DAY|DAY|DAY|DAY|DAY|
70  * ————————————————————————————||———————————————————————————¦-----------------------|
71  * </pre>
72  * A request for data in the middle of a time interval will include that interval.
73  * <p/>
74  * <b>NOTE:</b> Most methods on this API require the permission
75  * android.permission.PACKAGE_USAGE_STATS. However, declaring the permission implies intention to
76  * use the API and the user of the device still needs to grant permission through the Settings
77  * application.
78  * See {@link android.provider.Settings#ACTION_USAGE_ACCESS_SETTINGS}.
79  * Methods which only return the information for the calling package do not require this permission.
80  * E.g. {@link #getAppStandbyBucket()} and {@link #queryEventsForSelf(long, long)}.
81  */
82 @SystemService(Context.USAGE_STATS_SERVICE)
83 public final class UsageStatsManager {
84 
85     /**
86      * An interval type that spans a day. See {@link #queryUsageStats(int, long, long)}.
87      */
88     public static final int INTERVAL_DAILY = 0;
89 
90     /**
91      * An interval type that spans a week. See {@link #queryUsageStats(int, long, long)}.
92      */
93     public static final int INTERVAL_WEEKLY = 1;
94 
95     /**
96      * An interval type that spans a month. See {@link #queryUsageStats(int, long, long)}.
97      */
98     public static final int INTERVAL_MONTHLY = 2;
99 
100     /**
101      * An interval type that spans a year. See {@link #queryUsageStats(int, long, long)}.
102      */
103     public static final int INTERVAL_YEARLY = 3;
104 
105     /**
106      * An interval type that will use the best fit interval for the given time range.
107      * See {@link #queryUsageStats(int, long, long)}.
108      */
109     public static final int INTERVAL_BEST = 4;
110 
111     /**
112      * The number of available intervals. Does not include {@link #INTERVAL_BEST}, since it
113      * is a pseudo interval (it actually selects a real interval).
114      * {@hide}
115      */
116     public static final int INTERVAL_COUNT = 4;
117 
118 
119     /**
120      * The app is exempted for some reason and the bucket cannot be changed.
121      * {@hide}
122      */
123     @SystemApi
124     public static final int STANDBY_BUCKET_EXEMPTED = 5;
125 
126     /**
127      * The app was used very recently, currently in use or likely to be used very soon. Standby
128      * bucket values that are &le; {@link #STANDBY_BUCKET_ACTIVE} will not be throttled by the
129      * system while they are in this bucket. Buckets &gt; {@link #STANDBY_BUCKET_ACTIVE} will most
130      * likely be restricted in some way. For instance, jobs and alarms may be deferred.
131      * @see #getAppStandbyBucket()
132      */
133     public static final int STANDBY_BUCKET_ACTIVE = 10;
134 
135     /**
136      * The app was used recently and/or likely to be used in the next few hours. Restrictions will
137      * apply to these apps, such as deferral of jobs and alarms.
138      * @see #getAppStandbyBucket()
139      */
140     public static final int STANDBY_BUCKET_WORKING_SET = 20;
141 
142     /**
143      * The app was used in the last few days and/or likely to be used in the next few days.
144      * Restrictions will apply to these apps, such as deferral of jobs and alarms. The delays may be
145      * greater than for apps in higher buckets (lower bucket value). Bucket values &gt;
146      * {@link #STANDBY_BUCKET_FREQUENT} may additionally have network access limited.
147      * @see #getAppStandbyBucket()
148      */
149     public static final int STANDBY_BUCKET_FREQUENT = 30;
150 
151     /**
152      * The app has not be used for several days and/or is unlikely to be used for several days.
153      * Apps in this bucket will have more restrictions, including network restrictions, except
154      * during certain short periods (at a minimum, once a day) when they are allowed to execute
155      * jobs, access the network, etc.
156      * @see #getAppStandbyBucket()
157      */
158     public static final int STANDBY_BUCKET_RARE = 40;
159 
160     /**
161      * The app has not be used for several days, is unlikely to be used for several days, and has
162      * been misbehaving in some manner.
163      * Apps in this bucket will have the most restrictions, including network restrictions and
164      * additional restrictions on jobs.
165      * <p> Note: this bucket is not enabled in {@link Build.VERSION_CODES#R}.
166      * @see #getAppStandbyBucket()
167      */
168     public static final int STANDBY_BUCKET_RESTRICTED = 45;
169 
170     /**
171      * The app has never been used.
172      * {@hide}
173      */
174     @SystemApi
175     public static final int STANDBY_BUCKET_NEVER = 50;
176 
177     /** @hide */
178     public static final int REASON_MAIN_MASK = 0xFF00;
179     /** @hide */
180     public static final int REASON_MAIN_DEFAULT =   0x0100;
181     /**
182      * The app spent sufficient time in the old bucket without any substantial event so it reached
183      * the timeout threshold to have its bucket lowered.
184      * @hide
185      */
186     public static final int REASON_MAIN_TIMEOUT =   0x0200;
187     /**
188      * The app was used in some way. Look at the REASON_SUB_USAGE_ reason for more details.
189      * @hide
190      */
191     public static final int REASON_MAIN_USAGE =     0x0300;
192     /**
193      * Forced by the user/developer, either explicitly or implicitly through some action. If user
194      * action was not involved and this is purely due to the system,
195      * {@link #REASON_MAIN_FORCED_BY_SYSTEM} should be used instead.
196      * @hide
197      */
198     public static final int REASON_MAIN_FORCED_BY_USER = 0x0400;
199     /**
200      * Set by a privileged system app. This may be overridden by
201      * {@link #REASON_MAIN_FORCED_BY_SYSTEM} or user action.
202      * @hide
203      */
204     public static final int REASON_MAIN_PREDICTED = 0x0500;
205     /**
206      * Forced by the system, independent of user action. If user action is involved,
207      * {@link #REASON_MAIN_FORCED_BY_USER} should be used instead. When this is used, only
208      * {@link #REASON_MAIN_FORCED_BY_SYSTEM} or user action can change the bucket.
209      * @hide
210      */
211     public static final int REASON_MAIN_FORCED_BY_SYSTEM = 0x0600;
212 
213     /** @hide */
214     public static final int REASON_SUB_MASK = 0x00FF;
215     /**
216      * The reason for using the default main reason is unknown or undefined.
217      * @hide
218      */
219     public static final int REASON_SUB_DEFAULT_UNDEFINED = 0x0000;
220     /**
221      * The app was updated.
222      * @hide
223      */
224     public static final int REASON_SUB_DEFAULT_APP_UPDATE = 0x0001;
225     /**
226      * The app was restored.
227      * @hide
228      */
229     public static final int REASON_SUB_DEFAULT_APP_RESTORED = 0x0002;
230     /**
231      * The app was interacted with in some way by the system.
232      * @hide
233      */
234     public static final int REASON_SUB_USAGE_SYSTEM_INTERACTION = 0x0001;
235     /**
236      * A notification was viewed by the user. This does not mean the user interacted with the
237      * notification.
238      * @hide
239      */
240     public static final int REASON_SUB_USAGE_NOTIFICATION_SEEN  = 0x0002;
241     /**
242      * The app was interacted with in some way by the user. This includes interacting with
243      * notification.
244      * @hide
245      */
246     public static final int REASON_SUB_USAGE_USER_INTERACTION   = 0x0003;
247     /**
248      * An {@link android.app.Activity} moved to the foreground.
249      * @hide
250      */
251     public static final int REASON_SUB_USAGE_MOVE_TO_FOREGROUND = 0x0004;
252     /**
253      * An {@link android.app.Activity} moved to the background.
254      * @hide
255      */
256     public static final int REASON_SUB_USAGE_MOVE_TO_BACKGROUND = 0x0005;
257     /**
258      * There was a system update.
259      * @hide
260      */
261     public static final int REASON_SUB_USAGE_SYSTEM_UPDATE      = 0x0006;
262     /**
263      * An app is in an elevated bucket because of an active timeout preventing it from being placed
264      * in a lower bucket.
265      * @hide
266      */
267     public static final int REASON_SUB_USAGE_ACTIVE_TIMEOUT     = 0x0007;
268     /**
269      * This system package's sync adapter has been used for another package's content provider.
270      * @hide
271      */
272     public static final int REASON_SUB_USAGE_SYNC_ADAPTER       = 0x0008;
273     /**
274      * A slice was pinned by an app.
275      * @hide
276      */
277     public static final int REASON_SUB_USAGE_SLICE_PINNED       = 0x0009;
278     /** /**
279      * A slice was pinned by the default launcher or the default assistant.
280      * @hide
281      */
282     public static final int REASON_SUB_USAGE_SLICE_PINNED_PRIV  = 0x000A;
283     /**
284      * A sync operation that is exempt from app standby was scheduled when the device wasn't Dozing.
285      * @hide
286      */
287     public static final int REASON_SUB_USAGE_EXEMPTED_SYNC_SCHEDULED_NON_DOZE = 0x000B;
288     /**
289      * A sync operation that is exempt from app standby was scheduled while the device was Dozing.
290      * @hide
291      */
292     public static final int REASON_SUB_USAGE_EXEMPTED_SYNC_SCHEDULED_DOZE = 0x000C;
293     /**
294      * A sync operation that is exempt from app standby started.
295      * @hide
296      */
297     public static final int REASON_SUB_USAGE_EXEMPTED_SYNC_START = 0x000D;
298     /**
299      * A sync operation that is not exempt from app standby was scheduled.
300      * @hide
301      */
302     public static final int REASON_SUB_USAGE_UNEXEMPTED_SYNC_SCHEDULED = 0x000E;
303     /**
304      * A foreground service started.
305      * @hide
306      */
307     public static final int REASON_SUB_USAGE_FOREGROUND_SERVICE_START = 0x000F;
308     /**
309      * The predicted bucket was restored after the app's temporary elevation to the ACTIVE bucket
310      * ended.
311      * @hide
312      */
313     public static final int REASON_SUB_PREDICTED_RESTORED       = 0x0001;
314     /**
315      * The reason the system forced the app into the bucket is unknown or undefined.
316      * @hide
317      */
318     public static final int REASON_SUB_FORCED_SYSTEM_FLAG_UNDEFINED = 0;
319     /**
320      * The app was unnecessarily using system resources (battery, memory, etc) in the background.
321      * @hide
322      */
323     public static final int REASON_SUB_FORCED_SYSTEM_FLAG_BACKGROUND_RESOURCE_USAGE = 1 << 0;
324     /**
325      * The app was deemed to be intentionally abusive.
326      * @hide
327      */
328     public static final int REASON_SUB_FORCED_SYSTEM_FLAG_ABUSE = 1 << 1;
329     /**
330      * The app was displaying buggy behavior.
331      * @hide
332      */
333     public static final int REASON_SUB_FORCED_SYSTEM_FLAG_BUGGY = 1 << 2;
334     /**
335      * The app was moved to restricted bucket due to user interaction, i.e., toggling FAS.
336      *
337      * <p>
338      * Note: This should be coming from the more end-user facing UX, not from developer
339      * options nor adb command.
340      </p>
341      *
342      * @hide
343      */
344     public static final int REASON_SUB_FORCED_USER_FLAG_INTERACTION = 1 << 1;
345 
346 
347     /** @hide */
348     @IntDef(flag = false, prefix = { "STANDBY_BUCKET_" }, value = {
349             STANDBY_BUCKET_EXEMPTED,
350             STANDBY_BUCKET_ACTIVE,
351             STANDBY_BUCKET_WORKING_SET,
352             STANDBY_BUCKET_FREQUENT,
353             STANDBY_BUCKET_RARE,
354             STANDBY_BUCKET_RESTRICTED,
355             STANDBY_BUCKET_NEVER,
356     })
357     @Retention(RetentionPolicy.SOURCE)
358     public @interface StandbyBuckets {}
359 
360     /** @hide */
361     @IntDef(flag = true, prefix = {"REASON_SUB_FORCED_"}, value = {
362             REASON_SUB_FORCED_SYSTEM_FLAG_UNDEFINED,
363             REASON_SUB_FORCED_SYSTEM_FLAG_BACKGROUND_RESOURCE_USAGE,
364             REASON_SUB_FORCED_SYSTEM_FLAG_ABUSE,
365             REASON_SUB_FORCED_SYSTEM_FLAG_BUGGY,
366             REASON_SUB_FORCED_USER_FLAG_INTERACTION,
367     })
368     @Retention(RetentionPolicy.SOURCE)
369     public @interface ForcedReasons {
370     }
371 
372     /**
373      * Observer id of the registered observer for the group of packages that reached the usage
374      * time limit. Included as an extra in the PendingIntent that was registered.
375      * @hide
376      */
377     @SystemApi
378     public static final String EXTRA_OBSERVER_ID = "android.app.usage.extra.OBSERVER_ID";
379 
380     /**
381      * Original time limit in milliseconds specified by the registered observer for the group of
382      * packages that reached the usage time limit. Included as an extra in the PendingIntent that
383      * was registered.
384      * @hide
385      */
386     @SystemApi
387     public static final String EXTRA_TIME_LIMIT = "android.app.usage.extra.TIME_LIMIT";
388 
389     /**
390      * Actual usage time in milliseconds for the group of packages that reached the specified time
391      * limit. Included as an extra in the PendingIntent that was registered.
392      * @hide
393      */
394     @SystemApi
395     public static final String EXTRA_TIME_USED = "android.app.usage.extra.TIME_USED";
396 
397     /**
398      * A String extra, when used with {@link UsageEvents.Event#getExtras}, that indicates
399      * the category of the user interaction associated with the event. The category cannot
400      * be more than 127 characters, longer value will be truncated to 127 characters.
401      */
402     @FlaggedApi(Flags.FLAG_USER_INTERACTION_TYPE_API)
403     public static final String EXTRA_EVENT_CATEGORY =
404             "android.app.usage.extra.EVENT_CATEGORY";
405 
406     /**
407      * A String extra, when used with {@link UsageEvents.Event#getExtras}, that indicates
408      * the action of the user interaction associated with the event. The action cannot be
409      * more than 127 characters, longer value will be truncated to 127 characters.
410      */
411     @FlaggedApi(Flags.FLAG_USER_INTERACTION_TYPE_API)
412     public static final String EXTRA_EVENT_ACTION =
413             "android.app.usage.extra.EVENT_ACTION";
414 
415     /**
416      * App usage observers will consider the task root package the source of usage.
417      * @hide
418      */
419     @SystemApi
420     public static final int USAGE_SOURCE_TASK_ROOT_ACTIVITY = 1;
421 
422     /**
423      * App usage observers will consider the visible activity's package the source of usage.
424      * @hide
425      */
426     @SystemApi
427     public static final int USAGE_SOURCE_CURRENT_ACTIVITY = 2;
428 
429     /** @hide */
430     @IntDef(prefix = { "USAGE_SOURCE_" }, value = {
431             USAGE_SOURCE_TASK_ROOT_ACTIVITY,
432             USAGE_SOURCE_CURRENT_ACTIVITY,
433     })
434     @Retention(RetentionPolicy.SOURCE)
435     public @interface UsageSource {}
436 
437     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
438     private static final UsageEvents sEmptyResults = new UsageEvents();
439 
440     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
441     private final Context mContext;
442     @UnsupportedAppUsage
443     private final IUsageStatsManager mService;
444 
445     /**
446      * {@hide}
447      */
UsageStatsManager(Context context, IUsageStatsManager service)448     public UsageStatsManager(Context context, IUsageStatsManager service) {
449         mContext = context;
450         mService = service;
451     }
452 
453     /**
454      * Gets application usage stats for the given time range, aggregated by the specified interval.
455      *
456      * <p>
457      * The returned list will contain one or more {@link UsageStats} objects for each package, with
458      * usage data that covers at least the given time range.
459      * Note: The begin and end times of the time range may be expanded to the nearest whole interval
460      * period.
461      * </p>
462      *
463      * <p> The caller must have {@link android.Manifest.permission#PACKAGE_USAGE_STATS} </p>
464      * <em>Note: Starting from {@link android.os.Build.VERSION_CODES#R Android R}, if the user's
465      * device is not in an unlocked state (as defined by {@link UserManager#isUserUnlocked()}),
466      * then {@code null} will be returned.</em>
467      *
468      * @param intervalType The time interval by which the stats are aggregated.
469      * @param beginTime The inclusive beginning of the range of stats to include in the results.
470      *                  Defined in terms of "Unix time", see
471      *                  {@link java.lang.System#currentTimeMillis}.
472      * @param endTime The exclusive end of the range of stats to include in the results. Defined
473      *                in terms of "Unix time", see {@link java.lang.System#currentTimeMillis}.
474      * @return A list of {@link UsageStats}
475      *
476      * @see #INTERVAL_DAILY
477      * @see #INTERVAL_WEEKLY
478      * @see #INTERVAL_MONTHLY
479      * @see #INTERVAL_YEARLY
480      * @see #INTERVAL_BEST
481      */
482     @UserHandleAware
queryUsageStats(int intervalType, long beginTime, long endTime)483     public List<UsageStats> queryUsageStats(int intervalType, long beginTime, long endTime) {
484         try {
485             @SuppressWarnings("unchecked")
486             ParceledListSlice<UsageStats> slice = mService.queryUsageStats(intervalType, beginTime,
487                     endTime, mContext.getOpPackageName(), mContext.getUserId());
488             if (slice != null) {
489                 return slice.getList();
490             }
491         } catch (RemoteException e) {
492             // fallthrough and return the empty list.
493         }
494         return Collections.emptyList();
495     }
496 
497     /**
498      * Gets the hardware configurations the device was in for the given time range, aggregated by
499      * the specified interval. The results are ordered as in
500      * {@link #queryUsageStats(int, long, long)}.
501      * <p> The caller must have {@link android.Manifest.permission#PACKAGE_USAGE_STATS} </p>
502      * <em>Note: Starting from {@link android.os.Build.VERSION_CODES#R Android R}, if the user's
503      * device is not in an unlocked state (as defined by {@link UserManager#isUserUnlocked()}),
504      * then {@code null} will be returned.</em>
505      *
506      * @param intervalType The time interval by which the stats are aggregated.
507      * @param beginTime The inclusive beginning of the range of stats to include in the results.
508      *                  Defined in terms of "Unix time", see
509      *                  {@link java.lang.System#currentTimeMillis}.
510      * @param endTime The exclusive end of the range of stats to include in the results. Defined
511      *                in terms of "Unix time", see {@link java.lang.System#currentTimeMillis}.
512      * @return A list of {@link ConfigurationStats}
513      */
queryConfigurations(int intervalType, long beginTime, long endTime)514     public List<ConfigurationStats> queryConfigurations(int intervalType, long beginTime,
515             long endTime) {
516         try {
517             @SuppressWarnings("unchecked")
518             ParceledListSlice<ConfigurationStats> slice = mService.queryConfigurationStats(
519                     intervalType, beginTime, endTime, mContext.getOpPackageName());
520             if (slice != null) {
521                 return slice.getList();
522             }
523         } catch (RemoteException e) {
524             // fallthrough and return the empty list.
525         }
526         return Collections.emptyList();
527     }
528 
529     /**
530      * Gets aggregated event stats for the given time range, aggregated by the specified interval.
531      * <p>The returned list will contain a {@link EventStats} object for each event type that
532      * is being aggregated and has data for an interval that is a subset of the time range given.
533      *
534      * <p>The current event types that will be aggregated here are:</p>
535      * <ul>
536      *     <li>{@link UsageEvents.Event#SCREEN_INTERACTIVE}</li>
537      *     <li>{@link UsageEvents.Event#SCREEN_NON_INTERACTIVE}</li>
538      *     <li>{@link UsageEvents.Event#KEYGUARD_SHOWN}</li>
539      *     <li>{@link UsageEvents.Event#KEYGUARD_HIDDEN}</li>
540      * </ul>
541      *
542      * <p> The caller must have {@link android.Manifest.permission#PACKAGE_USAGE_STATS} </p>
543      * <em>Note: Starting from {@link android.os.Build.VERSION_CODES#R Android R}, if the user's
544      * device is not in an unlocked state (as defined by {@link UserManager#isUserUnlocked()}),
545      * then {@code null} will be returned.</em>
546      *
547      * @param intervalType The time interval by which the stats are aggregated.
548      * @param beginTime The inclusive beginning of the range of stats to include in the results.
549      *                  Defined in terms of "Unix time", see
550      *                  {@link java.lang.System#currentTimeMillis}.
551      * @param endTime The exclusive end of the range of stats to include in the results. Defined
552      *                in terms of "Unix time", see {@link java.lang.System#currentTimeMillis}.
553      * @return A list of {@link EventStats}
554      *
555      * @see #INTERVAL_DAILY
556      * @see #INTERVAL_WEEKLY
557      * @see #INTERVAL_MONTHLY
558      * @see #INTERVAL_YEARLY
559      * @see #INTERVAL_BEST
560      */
queryEventStats(int intervalType, long beginTime, long endTime)561     public List<EventStats> queryEventStats(int intervalType, long beginTime, long endTime) {
562         try {
563             @SuppressWarnings("unchecked")
564             ParceledListSlice<EventStats> slice = mService.queryEventStats(intervalType, beginTime,
565                     endTime, mContext.getOpPackageName());
566             if (slice != null) {
567                 return slice.getList();
568             }
569         } catch (RemoteException e) {
570             // fallthrough and return the empty list.
571         }
572         return Collections.emptyList();
573     }
574 
575     /**
576      * Query for events in the given time range. Events are only kept by the system for a few
577      * days.
578      * <p> The caller must have {@link android.Manifest.permission#PACKAGE_USAGE_STATS} </p>
579      * <em>Note: Starting from {@link android.os.Build.VERSION_CODES#R Android R}, if the user's
580      * device is not in an unlocked state (as defined by {@link UserManager#isUserUnlocked()}),
581      * then {@code null} will be returned.</em>
582      *
583      * @param beginTime The inclusive beginning of the range of events to include in the results.
584      *                  Defined in terms of "Unix time", see
585      *                  {@link java.lang.System#currentTimeMillis}.
586      * @param endTime The exclusive end of the range of events to include in the results. Defined
587      *                in terms of "Unix time", see {@link java.lang.System#currentTimeMillis}.
588      * @return A {@link UsageEvents}.
589      */
queryEvents(long beginTime, long endTime)590     public UsageEvents queryEvents(long beginTime, long endTime) {
591         try {
592             UsageEvents iter = mService.queryEvents(beginTime, endTime,
593                     mContext.getOpPackageName());
594             if (iter != null) {
595                 return iter;
596             }
597         } catch (RemoteException e) {
598             // fallthrough and return empty result.
599         }
600         return sEmptyResults;
601     }
602 
603     /**
604      * Query for events with specific UsageEventsQuery object.
605      *
606      * <em>Note: if the user's device is not in an unlocked state (as defined by
607      * {@link UserManager#isUserUnlocked()}), then {@code null} will be returned.</em>
608      *
609      * @param query The query object used to specify the query parameters.
610      * @return A {@link UsageEvents} which contains the events matching the query parameters.
611      */
612     @FlaggedApi(Flags.FLAG_FILTER_BASED_EVENT_QUERY_API)
613     @Nullable
614     @RequiresPermission(android.Manifest.permission.PACKAGE_USAGE_STATS)
queryEvents(@onNull UsageEventsQuery query)615     public UsageEvents queryEvents(@NonNull UsageEventsQuery query) {
616         try {
617             UsageEvents iter = mService.queryEventsWithFilter(query, mContext.getOpPackageName());
618             if (iter != null) {
619                 return iter;
620             }
621         } catch (RemoteException e) {
622             // fallthrough and return empty result.
623         }
624         return sEmptyResults;
625     }
626 
627     /**
628      * Like {@link #queryEvents(long, long)}, but only returns events for the calling package.
629      * <em>Note: Starting from {@link android.os.Build.VERSION_CODES#R Android R}, if the user's
630      * device is not in an unlocked state (as defined by {@link UserManager#isUserUnlocked()}),
631      * then {@code null} will be returned.</em>
632      *
633      * @param beginTime The inclusive beginning of the range of events to include in the results.
634      *                  Defined in terms of "Unix time", see
635      *                  {@link java.lang.System#currentTimeMillis}.
636      * @param endTime The exclusive end of the range of events to include in the results. Defined
637      *                in terms of "Unix time", see {@link java.lang.System#currentTimeMillis}.
638      * @return A {@link UsageEvents} object.
639      *
640      * @see #queryEvents(long, long)
641      */
queryEventsForSelf(long beginTime, long endTime)642     public UsageEvents queryEventsForSelf(long beginTime, long endTime) {
643         try {
644             final UsageEvents events = mService.queryEventsForPackage(beginTime, endTime,
645                     mContext.getOpPackageName());
646             if (events != null) {
647                 return events;
648             }
649         } catch (RemoteException e) {
650             // fallthrough
651         }
652         return sEmptyResults;
653     }
654 
655     /**
656      * A convenience method that queries for all stats in the given range (using the best interval
657      * for that range), merges the resulting data, and keys it by package name.
658      * See {@link #queryUsageStats(int, long, long)}.
659      * <p> The caller must have {@link android.Manifest.permission#PACKAGE_USAGE_STATS} </p>
660      *
661      * @param beginTime The inclusive beginning of the range of stats to include in the results.
662      *                  Defined in terms of "Unix time", see
663      *                  {@link java.lang.System#currentTimeMillis}.
664      * @param endTime The exclusive end of the range of stats to include in the results. Defined
665      *                in terms of "Unix time", see {@link java.lang.System#currentTimeMillis}.
666      * @return A {@link java.util.Map} keyed by package name
667      */
queryAndAggregateUsageStats(long beginTime, long endTime)668     public Map<String, UsageStats> queryAndAggregateUsageStats(long beginTime, long endTime) {
669         List<UsageStats> stats = queryUsageStats(INTERVAL_BEST, beginTime, endTime);
670         if (stats.isEmpty()) {
671             return Collections.emptyMap();
672         }
673 
674         ArrayMap<String, UsageStats> aggregatedStats = new ArrayMap<>();
675         final int statCount = stats.size();
676         for (int i = 0; i < statCount; i++) {
677             UsageStats newStat = stats.get(i);
678             UsageStats existingStat = aggregatedStats.get(newStat.getPackageName());
679             if (existingStat == null) {
680                 aggregatedStats.put(newStat.mPackageName, newStat);
681             } else {
682                 existingStat.add(newStat);
683             }
684         }
685         return aggregatedStats;
686     }
687 
688     /**
689      * Returns whether the app standby bucket feature is enabled.
690      * @hide
691      */
692     @TestApi
isAppStandbyEnabled()693     public boolean isAppStandbyEnabled() {
694         try {
695             return mService.isAppStandbyEnabled();
696         } catch (RemoteException e) {
697             throw e.rethrowFromSystemServer();
698         }
699     }
700 
701     /**
702      * Returns whether the specified app is currently considered inactive. This will be true if the
703      * app hasn't been used directly or indirectly for a period of time defined by the system. This
704      * could be of the order of several hours or days. Apps are not considered inactive when the
705      * device is charging.
706      * <p> The caller must have {@link android.Manifest.permission#PACKAGE_USAGE_STATS} to query the
707      * inactive state of other apps</p>
708      *
709      * @param packageName The package name of the app to query
710      * @return whether the app is currently considered inactive or false if querying another app
711      * without {@link android.Manifest.permission#PACKAGE_USAGE_STATS}
712      */
isAppInactive(String packageName)713     public boolean isAppInactive(String packageName) {
714         try {
715             return mService.isAppInactive(packageName, mContext.getUserId(),
716                     mContext.getOpPackageName());
717         } catch (RemoteException e) {
718             // fall through and return default
719         }
720         return false;
721     }
722 
723     /**
724      * {@hide}
725      */
setAppInactive(String packageName, boolean inactive)726     public void setAppInactive(String packageName, boolean inactive) {
727         try {
728             mService.setAppInactive(packageName, inactive, mContext.getUserId());
729         } catch (RemoteException e) {
730             // fall through
731         }
732     }
733 
734     /**
735      * Returns the current standby bucket of the calling app. The system determines the standby
736      * state of the app based on app usage patterns. Standby buckets determine how much an app will
737      * be restricted from running background tasks such as jobs and alarms.
738      * <p>Restrictions increase progressively from {@link #STANDBY_BUCKET_ACTIVE} to
739      * {@link #STANDBY_BUCKET_RESTRICTED}, with {@link #STANDBY_BUCKET_ACTIVE} being the least
740      * restrictive. The battery level of the device might also affect the restrictions.
741      * <p>Apps in buckets &le; {@link #STANDBY_BUCKET_ACTIVE} have no standby restrictions imposed.
742      * Apps in buckets &gt; {@link #STANDBY_BUCKET_FREQUENT} may have network access restricted when
743      * running in the background.
744      * <p>The standby state of an app can change at any time either due to a user interaction or a
745      * system interaction or some algorithm determining that the app can be restricted for a period
746      * of time before the user has a need for it.
747      * <p>You can also query the recent history of standby bucket changes by calling
748      * {@link #queryEventsForSelf(long, long)} and searching for
749      * {@link UsageEvents.Event#STANDBY_BUCKET_CHANGED}.
750      *
751      * @return the current standby bucket of the calling app. One of STANDBY_BUCKET_* constants.
752      */
getAppStandbyBucket()753     public @StandbyBuckets int getAppStandbyBucket() {
754         try {
755             return mService.getAppStandbyBucket(mContext.getOpPackageName(),
756                     mContext.getOpPackageName(),
757                     mContext.getUserId());
758         } catch (RemoteException e) {
759         }
760         return STANDBY_BUCKET_ACTIVE;
761     }
762 
763     /**
764      * {@hide}
765      * Returns the current standby bucket of the specified app. The caller must hold the permission
766      * android.permission.PACKAGE_USAGE_STATS.
767      * @param packageName the package for which to fetch the current standby bucket.
768      */
769     @SystemApi
770     @RequiresPermission(android.Manifest.permission.PACKAGE_USAGE_STATS)
getAppStandbyBucket(String packageName)771     public @StandbyBuckets int getAppStandbyBucket(String packageName) {
772         try {
773             return mService.getAppStandbyBucket(packageName, mContext.getOpPackageName(),
774                     mContext.getUserId());
775         } catch (RemoteException e) {
776         }
777         return STANDBY_BUCKET_ACTIVE;
778     }
779 
780     /**
781      * {@hide}
782      * Changes an app's standby bucket to the provided value. The caller can only set the standby
783      * bucket for a different app than itself. The caller will not be able to change an app's
784      * standby bucket if that app is in the {@link #STANDBY_BUCKET_RESTRICTED} bucket.
785      * @param packageName the package name of the app to set the bucket for. A SecurityException
786      *                    will be thrown if the package name is that of the caller.
787      * @param bucket the standby bucket to set it to, which should be one of STANDBY_BUCKET_*.
788      *               Setting a standby bucket outside of the range of STANDBY_BUCKET_ACTIVE to
789      *               STANDBY_BUCKET_NEVER will result in a SecurityException.
790      */
791     @SystemApi
792     @RequiresPermission(android.Manifest.permission.CHANGE_APP_IDLE_STATE)
setAppStandbyBucket(String packageName, @StandbyBuckets int bucket)793     public void setAppStandbyBucket(String packageName, @StandbyBuckets int bucket) {
794         try {
795             mService.setAppStandbyBucket(packageName, bucket, mContext.getUserId());
796         } catch (RemoteException e) {
797             throw e.rethrowFromSystemServer();
798         }
799     }
800 
801     /**
802      * {@hide}
803      * Returns the current standby bucket of every app that has a bucket assigned to it.
804      * The caller must hold the permission android.permission.PACKAGE_USAGE_STATS. The key of the
805      * returned Map is the package name and the value is the bucket assigned to the package.
806      * @see #getAppStandbyBucket()
807      */
808     @SystemApi
809     @RequiresPermission(android.Manifest.permission.PACKAGE_USAGE_STATS)
getAppStandbyBuckets()810     public Map<String, Integer> getAppStandbyBuckets() {
811         try {
812             final ParceledListSlice<AppStandbyInfo> slice = mService.getAppStandbyBuckets(
813                     mContext.getOpPackageName(), mContext.getUserId());
814             final List<AppStandbyInfo> bucketList = slice.getList();
815             final ArrayMap<String, Integer> bucketMap = new ArrayMap<>();
816             final int n = bucketList.size();
817             for (int i = 0; i < n; i++) {
818                 final AppStandbyInfo bucketInfo = bucketList.get(i);
819                 bucketMap.put(bucketInfo.mPackageName, bucketInfo.mStandbyBucket);
820             }
821             return bucketMap;
822         } catch (RemoteException e) {
823             throw e.rethrowFromSystemServer();
824         }
825     }
826 
827     /**
828      * {@hide}
829      * Changes the app standby bucket for multiple apps at once. The Map is keyed by the package
830      * name and the value is one of STANDBY_BUCKET_*. The caller will not be able to change an
831      * app's standby bucket if that app is in the {@link #STANDBY_BUCKET_RESTRICTED} bucket.
832      * @param appBuckets a map of package name to bucket value.
833      */
834     @SystemApi
835     @RequiresPermission(android.Manifest.permission.CHANGE_APP_IDLE_STATE)
setAppStandbyBuckets(Map<String, Integer> appBuckets)836     public void setAppStandbyBuckets(Map<String, Integer> appBuckets) {
837         if (appBuckets == null) {
838             return;
839         }
840         final List<AppStandbyInfo> bucketInfoList = new ArrayList<>(appBuckets.size());
841         for (Map.Entry<String, Integer> bucketEntry : appBuckets.entrySet()) {
842             bucketInfoList.add(new AppStandbyInfo(bucketEntry.getKey(), bucketEntry.getValue()));
843         }
844         final ParceledListSlice<AppStandbyInfo> slice = new ParceledListSlice<>(bucketInfoList);
845         try {
846             mService.setAppStandbyBuckets(slice, mContext.getUserId());
847         } catch (RemoteException e) {
848             throw e.rethrowFromSystemServer();
849         }
850     }
851 
852     /**
853      * Return the lowest bucket this app can ever enter.
854      *
855      * @param packageName the package for which to fetch the minimum allowed standby bucket.
856      * {@hide}
857      */
858     @StandbyBuckets
859     @RequiresPermission(android.Manifest.permission.PACKAGE_USAGE_STATS)
getAppMinStandbyBucket(String packageName)860     public int getAppMinStandbyBucket(String packageName) {
861         try {
862             return mService.getAppMinStandbyBucket(packageName, mContext.getOpPackageName(),
863                     mContext.getUserId());
864         } catch (RemoteException e) {
865             throw e.rethrowFromSystemServer();
866         }
867     }
868 
869     /**
870      * Changes an app's estimated launch time. An app is considered "launched" when a user opens
871      * one of its {@link android.app.Activity Activities}. The provided time is persisted across
872      * reboots and is used unless 1) the time is more than a week in the future and the platform
873      * thinks the app will be launched sooner, 2) the estimated time has passed. Passing in
874      * {@link Long#MAX_VALUE} effectively clears the previously set launch time for the app.
875      *
876      * @param packageName               The package name of the app to set the bucket for.
877      * @param estimatedLaunchTimeMillis The next time the app is expected to be launched. Units are
878      *                                  in milliseconds since epoch (the same as
879      *                                  {@link System#currentTimeMillis()}).
880      * @hide
881      */
882     @SystemApi
883     @RequiresPermission(android.Manifest.permission.CHANGE_APP_LAUNCH_TIME_ESTIMATE)
setEstimatedLaunchTimeMillis(@onNull String packageName, @CurrentTimeMillisLong long estimatedLaunchTimeMillis)884     public void setEstimatedLaunchTimeMillis(@NonNull String packageName,
885             @CurrentTimeMillisLong long estimatedLaunchTimeMillis) {
886         if (packageName == null) {
887             throw new NullPointerException("package name cannot be null");
888         }
889         if (estimatedLaunchTimeMillis <= 0) {
890             throw new IllegalArgumentException("estimated launch time must be positive");
891         }
892         try {
893             mService.setEstimatedLaunchTime(
894                     packageName, estimatedLaunchTimeMillis, mContext.getUserId());
895         } catch (RemoteException e) {
896             throw e.rethrowFromSystemServer();
897         }
898     }
899 
900     /**
901      * Changes the estimated launch times for multiple apps at once. The map is keyed by the
902      * package name and the value is the estimated launch time.
903      *
904      * @param estimatedLaunchTimesMillis A map of package name to estimated launch time.
905      * @see #setEstimatedLaunchTimeMillis(String, long)
906      * @hide
907      */
908     @SystemApi
909     @RequiresPermission(android.Manifest.permission.CHANGE_APP_LAUNCH_TIME_ESTIMATE)
setEstimatedLaunchTimesMillis( @onNull Map<String, Long> estimatedLaunchTimesMillis)910     public void setEstimatedLaunchTimesMillis(
911             @NonNull Map<String, Long> estimatedLaunchTimesMillis) {
912         if (estimatedLaunchTimesMillis == null) {
913             throw new NullPointerException("estimatedLaunchTimesMillis cannot be null");
914         }
915         final List<AppLaunchEstimateInfo> estimateList =
916                 new ArrayList<>(estimatedLaunchTimesMillis.size());
917         for (Map.Entry<String, Long> estimateEntry : estimatedLaunchTimesMillis.entrySet()) {
918             final String pkgName = estimateEntry.getKey();
919             if (pkgName == null) {
920                 throw new NullPointerException("package name cannot be null");
921             }
922             final Long estimatedLaunchTime = estimateEntry.getValue();
923             if (estimatedLaunchTime == null || estimatedLaunchTime <= 0) {
924                 throw new IllegalArgumentException("estimated launch time must be positive");
925             }
926             estimateList.add(new AppLaunchEstimateInfo(pkgName, estimatedLaunchTime));
927         }
928         final ParceledListSlice<AppLaunchEstimateInfo> slice =
929                 new ParceledListSlice<>(estimateList);
930         try {
931             mService.setEstimatedLaunchTimes(slice, mContext.getUserId());
932         } catch (RemoteException e) {
933             throw e.rethrowFromSystemServer();
934         }
935     }
936 
937     /**
938      * @hide
939      * Register an app usage limit observer that receives a callback on the provided intent when
940      * the sum of usages of apps and tokens in the {@code observed} array exceeds the
941      * {@code timeLimit} specified. The structure of a token is a String with the reporting
942      * package's name and a token the reporting app will use, separated by the forward slash
943      * character. Example: com.reporting.package/5OM3*0P4QU3-7OK3N
944      * The observer will automatically be unregistered when the time limit is reached and the
945      * intent is delivered. Registering an {@code observerId} that was already registered will
946      * override the previous one. No more than 1000 unique {@code observerId} may be registered by
947      * a single uid at any one time.
948      * @param observerId A unique id associated with the group of apps to be monitored. There can
949      *                  be multiple groups with common packages and different time limits.
950      * @param observedEntities The list of packages and token to observe for usage time. Cannot be
951      *                         null and must include at least one package or token.
952      * @param timeLimit The total time the set of apps can be in the foreground before the
953      *                  callbackIntent is delivered. Must be at least one minute.
954      * @param timeUnit The unit for time specified in {@code timeLimit}. Cannot be null.
955      * @param callbackIntent The PendingIntent that will be dispatched when the usage limit is
956      *                       exceeded by the group of apps. The delivered Intent will also contain
957      *                       the extras {@link #EXTRA_OBSERVER_ID}, {@link #EXTRA_TIME_LIMIT} and
958      *                       {@link #EXTRA_TIME_USED}. Cannot be null.
959      * @throws SecurityException if the caller doesn't have the OBSERVE_APP_USAGE permission and
960      *                           is not the profile owner of this user.
961      */
962     @SystemApi
963     @RequiresPermission(android.Manifest.permission.OBSERVE_APP_USAGE)
registerAppUsageObserver(int observerId, @NonNull String[] observedEntities, long timeLimit, @NonNull TimeUnit timeUnit, @NonNull PendingIntent callbackIntent)964     public void registerAppUsageObserver(int observerId, @NonNull String[] observedEntities,
965             long timeLimit, @NonNull TimeUnit timeUnit, @NonNull PendingIntent callbackIntent) {
966         try {
967             mService.registerAppUsageObserver(observerId, observedEntities,
968                     timeUnit.toMillis(timeLimit), callbackIntent, mContext.getOpPackageName());
969         } catch (RemoteException e) {
970             throw e.rethrowFromSystemServer();
971         }
972     }
973 
974     /**
975      * @hide
976      * Unregister the app usage observer specified by the {@code observerId}. This will only apply
977      * to any observer registered by this application. Unregistering an observer that was already
978      * unregistered or never registered will have no effect.
979      * @param observerId The id of the observer that was previously registered.
980      * @throws SecurityException if the caller doesn't have the OBSERVE_APP_USAGE permission and is
981      *                           not the profile owner of this user.
982      */
983     @SystemApi
984     @RequiresPermission(android.Manifest.permission.OBSERVE_APP_USAGE)
unregisterAppUsageObserver(int observerId)985     public void unregisterAppUsageObserver(int observerId) {
986         try {
987             mService.unregisterAppUsageObserver(observerId, mContext.getOpPackageName());
988         } catch (RemoteException e) {
989             throw e.rethrowFromSystemServer();
990         }
991     }
992 
993     /**
994      * Register a usage session observer that receives a callback on the provided {@code
995      * limitReachedCallbackIntent} when the sum of usages of apps and tokens in the {@code
996      * observed} array exceeds the {@code timeLimit} specified within a usage session. The
997      * structure of a token is a String with the reporting packages' name and a token the
998      * reporting app will use, separated by the forward slash character.
999      * Example: com.reporting.package/5OM3*0P4QU3-7OK3N
1000      * After the {@code timeLimit} has been reached, the usage session observer will receive a
1001      * callback on the provided {@code sessionEndCallbackIntent} when the usage session ends.
1002      * Registering another session observer against a {@code sessionObserverId} that has already
1003      * been registered will override the previous session observer.
1004      *
1005      * @param sessionObserverId A unique id associated with the group of apps to be
1006      *                          monitored. There can be multiple groups with common
1007      *                          packages and different time limits.
1008      * @param observedEntities The list of packages and token to observe for usage time. Cannot be
1009      *                         null and must include at least one package or token.
1010      * @param timeLimit The total time the set of apps can be used continuously before the {@code
1011      *                  limitReachedCallbackIntent} is delivered. Must be at least one minute.
1012      * @param sessionThresholdTime The time that can take place between usage sessions before the
1013      *                             next session is considered a new session. Must be non-negative.
1014      * @param limitReachedCallbackIntent The {@link PendingIntent} that will be dispatched when the
1015      *                                   usage limit is exceeded by the group of apps. The
1016      *                                   delivered Intent will also contain the extras {@link
1017      *                                   #EXTRA_OBSERVER_ID}, {@link #EXTRA_TIME_LIMIT} and {@link
1018      *                                   #EXTRA_TIME_USED}. Cannot be null.
1019      * @param sessionEndCallbackIntent The {@link PendingIntent}  that will be dispatched when the
1020      *                                 session has ended after the usage limit has been exceeded.
1021      *                                 The session is considered at its end after the {@code
1022      *                                 observed} usage has stopped and an additional {@code
1023      *                                 sessionThresholdTime} has passed. The delivered Intent will
1024      *                                 also contain the extras {@link #EXTRA_OBSERVER_ID} and {@link
1025      *                                 #EXTRA_TIME_USED}. Can be null.
1026      * @throws SecurityException if the caller doesn't have the OBSERVE_APP_USAGE permission and
1027      *                           is not the profile owner of this user.
1028      * @hide
1029      */
1030     @SystemApi
1031     @RequiresPermission(android.Manifest.permission.OBSERVE_APP_USAGE)
registerUsageSessionObserver(int sessionObserverId, @NonNull String[] observedEntities, @NonNull Duration timeLimit, @NonNull Duration sessionThresholdTime, @NonNull PendingIntent limitReachedCallbackIntent, @Nullable PendingIntent sessionEndCallbackIntent)1032     public void registerUsageSessionObserver(int sessionObserverId,
1033             @NonNull String[] observedEntities, @NonNull Duration timeLimit,
1034             @NonNull Duration sessionThresholdTime,
1035             @NonNull PendingIntent limitReachedCallbackIntent,
1036             @Nullable PendingIntent sessionEndCallbackIntent) {
1037         try {
1038             mService.registerUsageSessionObserver(sessionObserverId, observedEntities,
1039                     timeLimit.toMillis(), sessionThresholdTime.toMillis(),
1040                     limitReachedCallbackIntent, sessionEndCallbackIntent,
1041                     mContext.getOpPackageName());
1042         } catch (RemoteException e) {
1043             throw e.rethrowFromSystemServer();
1044         }
1045     }
1046 
1047     /**
1048      * Unregister the usage session observer specified by the {@code sessionObserverId}. This will
1049      * only apply to any app session observer registered by this application. Unregistering an
1050      * observer that was already unregistered or never registered will have no effect.
1051      *
1052      * @param sessionObserverId The id of the observer that was previously registered.
1053      * @throws SecurityException if the caller doesn't have the OBSERVE_APP_USAGE permission and
1054      *                           is not the profile owner of this user.
1055      * @hide
1056      */
1057     @SystemApi
1058     @RequiresPermission(android.Manifest.permission.OBSERVE_APP_USAGE)
unregisterUsageSessionObserver(int sessionObserverId)1059     public void unregisterUsageSessionObserver(int sessionObserverId) {
1060         try {
1061             mService.unregisterUsageSessionObserver(sessionObserverId, mContext.getOpPackageName());
1062         } catch (RemoteException e) {
1063             throw e.rethrowFromSystemServer();
1064         }
1065     }
1066 
1067     /**
1068      * Register a usage limit observer that receives a callback on the provided intent when the
1069      * sum of usages of apps and tokens in the provided {@code observedEntities} array exceeds the
1070      * {@code timeLimit} specified. The structure of a token is a {@link String} with the reporting
1071      * package's name and a token that the calling app will use, separated by the forward slash
1072      * character. Example: com.reporting.package/5OM3*0P4QU3-7OK3N
1073      * <p>
1074      * Registering an {@code observerId} that was already registered will override the previous one.
1075      * No more than 1000 unique {@code observerId} may be registered by a single uid
1076      * at any one time.
1077      * A limit is not cleared when the usage time is exceeded. It needs to be unregistered via
1078      * {@link #unregisterAppUsageLimitObserver}.
1079      * <p>
1080      * Note: usage limits are not persisted in the system and are cleared on reboots. Callers
1081      * must reset any limits that they need on reboots.
1082      * <p>
1083      * This method is similar to {@link #registerAppUsageObserver}, but the usage limit set here
1084      * will be visible to the launcher so that it can report the limit to the user and how much
1085      * of it is remaining.
1086      * @see android.content.pm.LauncherApps#getAppUsageLimit
1087      *
1088      * @param observerId A unique id associated with the group of apps to be monitored. There can
1089      *                   be multiple groups with common packages and different time limits.
1090      * @param observedEntities The list of packages and token to observe for usage time. Cannot be
1091      *                         null and must include at least one package or token.
1092      * @param timeLimit The total time the set of apps can be in the foreground before the
1093      *                  {@code callbackIntent} is delivered. Must be at least one minute.
1094      * @param timeUsed The time that has already been used by the set of apps in
1095      *                 {@code observedEntities}. Note: a time used equal to or greater than
1096      *                 {@code timeLimit} can be set to indicate that the user has already exhausted
1097      *                 the limit for a group, in which case, the given {@code callbackIntent} will
1098      *                 be ignored.
1099      * @param callbackIntent The PendingIntent that will be dispatched when the usage limit is
1100      *                       exceeded by the group of apps. The delivered Intent will also contain
1101      *                       the extras {@link #EXTRA_OBSERVER_ID}, {@link #EXTRA_TIME_LIMIT} and
1102      *                       {@link #EXTRA_TIME_USED}. Cannot be {@code null} unless the observer is
1103      *                       being registered with a {@code timeUsed} equal to or greater than
1104      *                       {@code timeLimit}.
1105      * @throws SecurityException if the caller is neither the active supervision app nor does it
1106      *                           have both SUSPEND_APPS and OBSERVE_APP_USAGE permissions.
1107      * @hide
1108      */
1109     @SystemApi
1110     @RequiresPermission(allOf = {
1111             android.Manifest.permission.SUSPEND_APPS,
1112             android.Manifest.permission.OBSERVE_APP_USAGE})
registerAppUsageLimitObserver(int observerId, @NonNull String[] observedEntities, @NonNull Duration timeLimit, @NonNull Duration timeUsed, @Nullable PendingIntent callbackIntent)1113     public void registerAppUsageLimitObserver(int observerId, @NonNull String[] observedEntities,
1114             @NonNull Duration timeLimit, @NonNull Duration timeUsed,
1115             @Nullable PendingIntent callbackIntent) {
1116         try {
1117             mService.registerAppUsageLimitObserver(observerId, observedEntities,
1118                     timeLimit.toMillis(), timeUsed.toMillis(), callbackIntent,
1119                     mContext.getOpPackageName());
1120         } catch (RemoteException e) {
1121             throw e.rethrowFromSystemServer();
1122         }
1123     }
1124 
1125     /**
1126      * Unregister the app usage limit observer specified by the {@code observerId}.
1127      * This will only apply to any observer registered by this application. Unregistering
1128      * an observer that was already unregistered or never registered will have no effect.
1129      *
1130      * @param observerId The id of the observer that was previously registered.
1131      * @throws SecurityException if the caller is neither the active supervision app nor does it
1132      *                         have both SUSPEND_APPS and OBSERVE_APP_USAGE permissions.
1133      * @hide
1134      */
1135     @SystemApi
1136     @RequiresPermission(allOf = {
1137             android.Manifest.permission.SUSPEND_APPS,
1138             android.Manifest.permission.OBSERVE_APP_USAGE})
unregisterAppUsageLimitObserver(int observerId)1139     public void unregisterAppUsageLimitObserver(int observerId) {
1140         try {
1141             mService.unregisterAppUsageLimitObserver(observerId, mContext.getOpPackageName());
1142         } catch (RemoteException e) {
1143             throw e.rethrowFromSystemServer();
1144         }
1145     }
1146 
1147     /**
1148      * Reports user interaction with a given package in the given user.
1149      *
1150      * <p><em>This method is only for use by the system</em>
1151      *
1152      * @hide
1153      */
1154     @RequiresPermission(android.Manifest.permission.REPORT_USAGE_STATS)
reportUserInteraction(@onNull String packageName, int userId)1155     public void reportUserInteraction(@NonNull String packageName, int userId) {
1156         try {
1157             mService.reportUserInteraction(packageName, userId);
1158         } catch (RemoteException re) {
1159             throw re.rethrowFromSystemServer();
1160         }
1161     }
1162 
1163     /**
1164      * Reports user interaction with given package and a particular {@code extras}
1165      * in the given user.
1166      *
1167      * <p>
1168      * Note: The structure of {@code extras} is a {@link PersistableBundle} with the
1169      * category {@link #EXTRA_EVENT_CATEGORY} and the action {@link #EXTRA_EVENT_ACTION}.
1170      * Category provides additional detail about the user interaction, the value
1171      * is defined in namespace based. Example: android.app.notification could be used to
1172      * indicate that the reported user interaction is related to notification. Action
1173      * indicates the general action that performed.
1174      * </p>
1175      *
1176      * @param packageName The package name of the app
1177      * @param userId The user id who triggers the user interaction
1178      * @param extras The {@link PersistableBundle} that will be used to specify the
1179      *               extra details for the user interaction event. The {@link PersistableBundle}
1180      *               must contain the extras {@link #EXTRA_EVENT_CATEGORY},
1181      *               {@link #EXTRA_EVENT_ACTION}. Cannot be empty.
1182      * @hide
1183      */
1184     @FlaggedApi(Flags.FLAG_USER_INTERACTION_TYPE_API)
1185     @RequiresPermission(android.Manifest.permission.REPORT_USAGE_STATS)
reportUserInteraction(@onNull String packageName, @UserIdInt int userId, @NonNull PersistableBundle extras)1186     public void reportUserInteraction(@NonNull String packageName, @UserIdInt int userId,
1187             @NonNull PersistableBundle extras) {
1188         try {
1189             mService.reportUserInteractionWithBundle(packageName, userId, extras);
1190         } catch (RemoteException re) {
1191             throw re.rethrowFromSystemServer();
1192         }
1193     }
1194 
1195     /**
1196      * Report usage associated with a particular {@code token} has started. Tokens are app defined
1197      * strings used to represent usage of in-app features. Apps with the {@link
1198      * android.Manifest.permission#OBSERVE_APP_USAGE} permission can register time limit observers
1199      * to monitor the usage of a token. In app usage can only associated with an {@code activity}
1200      * and usage will be considered stopped if the activity stops or crashes.
1201      * @see #registerAppUsageObserver
1202      * @see #registerUsageSessionObserver
1203      * @see #registerAppUsageLimitObserver
1204      *
1205      * @param activity The activity {@code token} is associated with.
1206      * @param token The token to report usage against.
1207      * @hide
1208      */
1209     @SystemApi
reportUsageStart(@onNull Activity activity, @NonNull String token)1210     public void reportUsageStart(@NonNull Activity activity, @NonNull String token) {
1211         try {
1212             mService.reportUsageStart(activity.getActivityToken(), token,
1213                     mContext.getOpPackageName());
1214         } catch (RemoteException e) {
1215             throw e.rethrowFromSystemServer();
1216         }
1217     }
1218 
1219     /**
1220      * Report usage associated with a particular {@code token} had started some amount of time in
1221      * the past. Tokens are app defined strings used to represent usage of in-app features. Apps
1222      * with the {@link android.Manifest.permission#OBSERVE_APP_USAGE} permission can register time
1223      * limit observers to monitor the usage of a token. In app usage can only associated with an
1224      * {@code activity} and usage will be considered stopped if the activity stops or crashes.
1225      * @see #registerAppUsageObserver
1226      * @see #registerUsageSessionObserver
1227      * @see #registerAppUsageLimitObserver
1228      *
1229      * @param activity The activity {@code token} is associated with.
1230      * @param token The token to report usage against.
1231      * @param timeAgoMs How long ago the start of usage took place
1232      * @hide
1233      */
1234     @SystemApi
reportUsageStart(@onNull Activity activity, @NonNull String token, long timeAgoMs)1235     public void reportUsageStart(@NonNull Activity activity, @NonNull String token,
1236                                  long timeAgoMs) {
1237         try {
1238             mService.reportPastUsageStart(activity.getActivityToken(), token, timeAgoMs,
1239                     mContext.getOpPackageName());
1240         } catch (RemoteException e) {
1241             throw e.rethrowFromSystemServer();
1242         }
1243     }
1244 
1245     /**
1246      * Report the usage associated with a particular {@code token} has stopped.
1247      *
1248      * @param activity The activity {@code token} is associated with.
1249      * @param token The token to report usage against.
1250      * @hide
1251      */
1252     @SystemApi
reportUsageStop(@onNull Activity activity, @NonNull String token)1253     public void reportUsageStop(@NonNull Activity activity, @NonNull String token) {
1254         try {
1255             mService.reportUsageStop(activity.getActivityToken(), token,
1256                     mContext.getOpPackageName());
1257         } catch (RemoteException e) {
1258             throw e.rethrowFromSystemServer();
1259         }
1260     }
1261 
1262     /**
1263      * Get what App Usage Observers will consider the source of usage for an activity. Usage Source
1264      * is decided at boot and will not change until next boot.
1265      * @see #USAGE_SOURCE_TASK_ROOT_ACTIVITY
1266      * @see #USAGE_SOURCE_CURRENT_ACTIVITY
1267      *
1268      * @throws SecurityException if the caller doesn't have the OBSERVE_APP_USAGE permission and
1269      *                           is not the profile owner of this user.
1270      * @hide
1271      */
1272     @SystemApi
getUsageSource()1273     public @UsageSource int getUsageSource() {
1274         try {
1275             return mService.getUsageSource();
1276         } catch (RemoteException e) {
1277             throw e.rethrowFromSystemServer();
1278         }
1279     }
1280 
1281     /**
1282      * Force the Usage Source be reread from global settings.
1283      * @hide
1284      */
1285     @TestApi
forceUsageSourceSettingRead()1286     public void forceUsageSourceSettingRead() {
1287         try {
1288             mService.forceUsageSourceSettingRead();
1289         } catch (RemoteException e) {
1290             throw e.rethrowFromSystemServer();
1291         }
1292     }
1293 
1294     /** @hide */
reasonToString(int standbyReason)1295     public static String reasonToString(int standbyReason) {
1296         final int subReason = standbyReason & REASON_SUB_MASK;
1297         StringBuilder sb = new StringBuilder();
1298         switch (standbyReason & REASON_MAIN_MASK) {
1299             case REASON_MAIN_DEFAULT:
1300                 sb.append("d");
1301                 switch (subReason) {
1302                     case REASON_SUB_DEFAULT_UNDEFINED:
1303                         // Historically, undefined didn't have a string, so don't add anything here.
1304                         break;
1305                     case REASON_SUB_DEFAULT_APP_UPDATE:
1306                         sb.append("-au");
1307                         break;
1308                     case REASON_SUB_DEFAULT_APP_RESTORED:
1309                         sb.append("-ar");
1310                         break;
1311                 }
1312                 break;
1313             case REASON_MAIN_FORCED_BY_SYSTEM:
1314                 sb.append("s");
1315                 if (subReason > 0) {
1316                     sb.append("-").append(Integer.toBinaryString(subReason));
1317                 }
1318                 break;
1319             case REASON_MAIN_FORCED_BY_USER:
1320                 sb.append("f");
1321                 if (subReason > 0) {
1322                     sb.append("-").append(Integer.toBinaryString(subReason));
1323                 }
1324                 break;
1325             case REASON_MAIN_PREDICTED:
1326                 sb.append("p");
1327                 switch (subReason) {
1328                     case REASON_SUB_PREDICTED_RESTORED:
1329                         sb.append("-r");
1330                         break;
1331                 }
1332                 break;
1333             case REASON_MAIN_TIMEOUT:
1334                 sb.append("t");
1335                 break;
1336             case REASON_MAIN_USAGE:
1337                 sb.append("u");
1338                 switch (subReason) {
1339                     case REASON_SUB_USAGE_SYSTEM_INTERACTION:
1340                         sb.append("-si");
1341                         break;
1342                     case REASON_SUB_USAGE_NOTIFICATION_SEEN:
1343                         sb.append("-ns");
1344                         break;
1345                     case REASON_SUB_USAGE_USER_INTERACTION:
1346                         sb.append("-ui");
1347                         break;
1348                     case REASON_SUB_USAGE_MOVE_TO_FOREGROUND:
1349                         sb.append("-mf");
1350                         break;
1351                     case REASON_SUB_USAGE_MOVE_TO_BACKGROUND:
1352                         sb.append("-mb");
1353                         break;
1354                     case REASON_SUB_USAGE_SYSTEM_UPDATE:
1355                         sb.append("-su");
1356                         break;
1357                     case REASON_SUB_USAGE_ACTIVE_TIMEOUT:
1358                         sb.append("-at");
1359                         break;
1360                     case REASON_SUB_USAGE_SYNC_ADAPTER:
1361                         sb.append("-sa");
1362                         break;
1363                     case REASON_SUB_USAGE_SLICE_PINNED:
1364                         sb.append("-lp");
1365                         break;
1366                     case REASON_SUB_USAGE_SLICE_PINNED_PRIV:
1367                         sb.append("-lv");
1368                         break;
1369                     case REASON_SUB_USAGE_EXEMPTED_SYNC_SCHEDULED_NON_DOZE:
1370                         sb.append("-en");
1371                         break;
1372                     case REASON_SUB_USAGE_EXEMPTED_SYNC_SCHEDULED_DOZE:
1373                         sb.append("-ed");
1374                         break;
1375                     case REASON_SUB_USAGE_EXEMPTED_SYNC_START:
1376                         sb.append("-es");
1377                         break;
1378                     case REASON_SUB_USAGE_UNEXEMPTED_SYNC_SCHEDULED:
1379                         sb.append("-uss");
1380                         break;
1381                     case REASON_SUB_USAGE_FOREGROUND_SERVICE_START:
1382                         sb.append("-fss");
1383                         break;
1384                 }
1385                 break;
1386         }
1387         return sb.toString();
1388     }
1389 
1390     /** @hide */
usageSourceToString(int usageSource)1391     public static String usageSourceToString(int usageSource) {
1392         switch (usageSource) {
1393             case USAGE_SOURCE_TASK_ROOT_ACTIVITY:
1394                 return "TASK_ROOT_ACTIVITY";
1395             case USAGE_SOURCE_CURRENT_ACTIVITY:
1396                 return "CURRENT_ACTIVITY";
1397             default:
1398                 StringBuilder sb = new StringBuilder();
1399                 sb.append("UNKNOWN(");
1400                 sb.append(usageSource);
1401                 sb.append(")");
1402                 return sb.toString();
1403         }
1404     }
1405 
1406     /** @hide */
standbyBucketToString(int standbyBucket)1407     public static String standbyBucketToString(int standbyBucket) {
1408         switch (standbyBucket) {
1409             case STANDBY_BUCKET_EXEMPTED:
1410                 return "EXEMPTED";
1411             case STANDBY_BUCKET_ACTIVE:
1412                 return "ACTIVE";
1413             case STANDBY_BUCKET_WORKING_SET:
1414                 return "WORKING_SET";
1415             case STANDBY_BUCKET_FREQUENT:
1416                 return "FREQUENT";
1417             case STANDBY_BUCKET_RARE:
1418                 return "RARE";
1419             case STANDBY_BUCKET_RESTRICTED:
1420                 return "RESTRICTED";
1421             case STANDBY_BUCKET_NEVER:
1422                 return "NEVER";
1423             default:
1424                 return String.valueOf(standbyBucket);
1425         }
1426     }
1427 
1428     /**
1429      * {@hide}
1430      * Temporarily allowlist the specified app for a short duration. This is to allow an app
1431      * receiving a high priority message to be able to access the network and acquire wakelocks
1432      * even if the device is in power-save mode or the app is currently considered inactive.
1433      * @param packageName The package name of the app to allowlist.
1434      * @param duration Duration to allowlist the app for, in milliseconds. It is recommended that
1435      * this be limited to 10s of seconds. Requested duration will be clamped to a few minutes.
1436      * @param user The user for whom the package should be allowlisted. Passing in a user that is
1437      * not the same as the caller's process will require the INTERACT_ACROSS_USERS permission.
1438      * @see #isAppInactive(String)
1439      *
1440      * @deprecated Use
1441      * {@link android.os.PowerWhitelistManager#whitelistAppTemporarily(String, long)} instead.
1442      */
1443     @SystemApi
1444     @RequiresPermission(android.Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST)
1445     @Deprecated
whitelistAppTemporarily(String packageName, long duration, UserHandle user)1446     public void whitelistAppTemporarily(String packageName, long duration, UserHandle user) {
1447         mContext.getSystemService(PowerWhitelistManager.class)
1448                 .whitelistAppTemporarily(packageName, duration);
1449     }
1450 
1451     /**
1452      * Inform usage stats that the carrier privileged apps access rules have changed.
1453      * <p> The caller must have {@link android.Manifest.permission#BIND_CARRIER_SERVICES} </p>
1454      * @hide
1455      */
1456     @SystemApi
1457     @RequiresPermission(android.Manifest.permission.BIND_CARRIER_SERVICES)
onCarrierPrivilegedAppsChanged()1458     public void onCarrierPrivilegedAppsChanged() {
1459         try {
1460             mService.onCarrierPrivilegedAppsChanged();
1461         } catch (RemoteException re) {
1462             throw re.rethrowFromSystemServer();
1463         }
1464     }
1465 
1466     /**
1467      * Reports a Chooser action to the UsageStatsManager.
1468      *
1469      * @param packageName The package name of the app that is selected.
1470      * @param userId The user id of who makes the selection.
1471      * @param contentType The type of the content, e.g., Image, Video, App.
1472      * @param annotations The annotations of the content, e.g., Game, Selfie.
1473      * @param action The action type of Intent that invokes ChooserActivity.
1474      * {@link UsageEvents}
1475      * @hide
1476      */
1477     @RequiresPermission(android.Manifest.permission.REPORT_USAGE_STATS)
reportChooserSelection(String packageName, int userId, String contentType, String[] annotations, String action)1478     public void reportChooserSelection(String packageName, int userId, String contentType,
1479                                        String[] annotations, String action) {
1480         try {
1481             mService.reportChooserSelection(packageName, userId, contentType, annotations, action);
1482         } catch (RemoteException re) {
1483         }
1484     }
1485 
1486     /**
1487      * Get the last time a package is used by any users including explicit user interaction and
1488      * component usage, measured in milliseconds since the epoch and truncated to the boundary of
1489      * last day before the exact time. For packages that are never used, the time will be the epoch.
1490      * <p> Note that this usage stats is user-agnostic. </p>
1491      * <p>
1492      * Also note that component usage is only reported for component bindings (e.g. broadcast
1493      * receiver, service, content provider) and only when such a binding would cause an app to leave
1494      * the stopped state.
1495      * See {@link UsageEvents.Event.USER_INTERACTION}, {@link UsageEvents.Event.APP_COMPONENT_USED}.
1496      * </p>
1497      *
1498      * @param packageName The name of the package to be queried.
1499      * @return last time the queried package is used since the epoch.
1500      * @hide
1501      */
1502     @SystemApi
1503     @RequiresPermission(allOf = {
1504             android.Manifest.permission.INTERACT_ACROSS_USERS,
1505             android.Manifest.permission.PACKAGE_USAGE_STATS})
getLastTimeAnyComponentUsed(@onNull String packageName)1506     public long getLastTimeAnyComponentUsed(@NonNull String packageName) {
1507         try {
1508             return mService.getLastTimeAnyComponentUsed(packageName, mContext.getOpPackageName());
1509         } catch (RemoteException re) {
1510             throw re.rethrowFromSystemServer();
1511         }
1512     }
1513 
1514     /**
1515      * Returns the broadcast response stats since the last boot corresponding to
1516      * {@code packageName} and {@code id}.
1517      *
1518      * <p> Broadcast response stats will include the aggregated data of what actions an app took
1519      * upon receiving a broadcast. This data will consider the broadcasts that the caller sent to
1520      * {@code packageName} and explicitly requested to record the response events using
1521      * {@link BroadcastOptions#recordResponseEventWhileInBackground(long)}.
1522      *
1523      * <p> The returned list could one or more {@link BroadcastResponseStats} objects or be empty
1524      * depending on the {@code packageName} and {@code id} and whether there is any data
1525      * corresponding to these. If the {@code packageName} is not {@code null} and {@code id} is
1526      * {@code > 0}, then the returned list would contain at most one {@link BroadcastResponseStats}
1527      * object. Otherwise, the returned list could contain more than one
1528      * {@link BroadcastResponseStats} object in no particular order.
1529      *
1530      * <p> Note: It is possible that same {@code id} was used for broadcasts sent to different
1531      * packages. So, callers can query the data corresponding to
1532      * all broadcasts with a particular {@code id} by passing {@code packageName} as {@code null}.
1533      *
1534      * @param packageName The name of the package that the caller wants to query for
1535      *                    or {@code null} to indicate that data corresponding to all packages
1536      *                    should be returned.
1537      * @param id The ID corresponding to the broadcasts that the caller wants to query for, or
1538      *           {@code 0} to indicate that data corresponding to all IDs should be returned.
1539      *           This is the ID the caller specifies when requesting a broadcast response event
1540      *           to be recorded using
1541      *           {@link BroadcastOptions#recordResponseEventWhileInBackground(long)}.
1542      *
1543      * @return the list of broadcast response stats corresponding to {@code packageName}
1544      *         and {@code id}.
1545      *
1546      * @see #clearBroadcastResponseStats(String, long)
1547      * @hide
1548      */
1549     @SystemApi
1550     @RequiresPermission(android.Manifest.permission.ACCESS_BROADCAST_RESPONSE_STATS)
1551     @UserHandleAware
1552     @NonNull
queryBroadcastResponseStats( @ullable String packageName, @IntRange(from = 0) long id)1553     public List<BroadcastResponseStats> queryBroadcastResponseStats(
1554             @Nullable String packageName, @IntRange(from = 0) long id) {
1555         try {
1556             return mService.queryBroadcastResponseStats(packageName, id,
1557                     mContext.getOpPackageName(), mContext.getUserId()).getList();
1558         } catch (RemoteException re) {
1559             throw re.rethrowFromSystemServer();
1560         }
1561     }
1562 
1563     /**
1564      * Clears the broadcast response stats corresponding to {@code packageName} and {@code id}.
1565      *
1566      * <p> When a caller uses this API, stats related to the events occurring till that point will
1567      * be cleared and subsequent calls to {@link #queryBroadcastResponseStats(String, long)} will
1568      * return stats related to events occurring after this.
1569      *
1570      * @param packageName The name of the package that the caller wants to clear the data for or
1571      *                    {@code null} to indicate that data corresponding to all packages should
1572      *                    be cleared.
1573      * @param id The ID corresponding to the broadcasts that the caller wants to clear the data
1574      *           for, or {code 0} to indicate that data corresponding to all IDs should be deleted.
1575      *           This is the ID the caller specifies when requesting a broadcast response event
1576      *           to be recorded using
1577      *           {@link BroadcastOptions#recordResponseEventWhileInBackground(long)}.
1578      *
1579      * @see #queryBroadcastResponseStats(String, long)
1580      * @hide
1581      */
1582     @SystemApi
1583     @RequiresPermission(android.Manifest.permission.ACCESS_BROADCAST_RESPONSE_STATS)
1584     @UserHandleAware
clearBroadcastResponseStats(@ullable String packageName, @IntRange(from = 0) long id)1585     public void clearBroadcastResponseStats(@Nullable String packageName,
1586             @IntRange(from = 0) long id) {
1587         try {
1588             mService.clearBroadcastResponseStats(packageName, id,
1589                     mContext.getOpPackageName(), mContext.getUserId());
1590         } catch (RemoteException re) {
1591             throw re.rethrowFromSystemServer();
1592         }
1593     }
1594 
1595     /**
1596      * Clears the broadcast events that were sent by the caller uid.
1597      *
1598      * @hide
1599      */
1600     @RequiresPermission(android.Manifest.permission.ACCESS_BROADCAST_RESPONSE_STATS)
1601     @UserHandleAware
clearBroadcastEvents()1602     public void clearBroadcastEvents() {
1603         try {
1604             mService.clearBroadcastEvents(mContext.getOpPackageName(), mContext.getUserId());
1605         } catch (RemoteException re) {
1606             throw re.rethrowFromSystemServer();
1607         }
1608     }
1609 
1610     /**
1611      * Checks whether the given {@code packageName} is exempted from broadcast response tracking.
1612      *
1613      * @hide
1614      */
1615     @RequiresPermission(android.Manifest.permission.DUMP)
1616     @UserHandleAware
isPackageExemptedFromBroadcastResponseStats(@onNull String packageName)1617     public boolean isPackageExemptedFromBroadcastResponseStats(@NonNull String packageName) {
1618         try {
1619             return mService.isPackageExemptedFromBroadcastResponseStats(packageName,
1620                     mContext.getUserId());
1621         } catch (RemoteException re) {
1622             throw re.rethrowFromSystemServer();
1623         }
1624     }
1625 
1626     /** @hide */
1627     @RequiresPermission(Manifest.permission.READ_DEVICE_CONFIG)
1628     @Nullable
getAppStandbyConstant(@onNull String key)1629     public String getAppStandbyConstant(@NonNull String key) {
1630         try {
1631             return mService.getAppStandbyConstant(key);
1632         } catch (RemoteException re) {
1633             throw re.rethrowFromSystemServer();
1634         }
1635     }
1636 }
1637