blob: 0d66198db03885fa9b80e181d9c65cbd186f891b [file] [log] [blame]
Adam Lesinski0debc9a2014-07-16 19:09:13 -07001/**
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
Amith Yamasaniafbccb72017-11-27 10:44:24 -080019import android.annotation.IntDef;
Amith Yamasanibc813eb2018-03-20 19:37:46 -070020import android.annotation.NonNull;
Michael Wachenschwanz641e3382018-10-23 23:21:48 -070021import android.annotation.Nullable;
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -060022import android.annotation.RequiresPermission;
Amith Yamasaniaf575b92015-05-29 15:35:26 -070023import android.annotation.SystemApi;
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -060024import android.annotation.SystemService;
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -080025import android.annotation.TestApi;
Michael Wachenschwanz36778522018-11-12 11:06:19 -080026import android.app.Activity;
Amith Yamasani62ec27e92018-03-11 14:42:06 -070027import android.app.PendingIntent;
Artur Satayevc895b1b2019-12-10 17:47:51 +000028import android.compat.annotation.UnsupportedAppUsage;
Adam Lesinski0debc9a2014-07-16 19:09:13 -070029import android.content.Context;
Adam Lesinski35168002014-07-21 15:25:30 -070030import android.content.pm.ParceledListSlice;
Mathew Inwood8c854f82018-09-14 12:35:36 +010031import android.os.Build;
Kweku Adams835283f2019-11-20 14:41:22 -080032import android.os.PowerWhitelistManager;
Adam Lesinski0debc9a2014-07-16 19:09:13 -070033import android.os.RemoteException;
Amith Yamasanicf768722015-04-23 20:36:41 -070034import android.os.UserHandle;
Varun Shah3a315202019-07-24 16:33:42 -070035import android.os.UserManager;
Adam Lesinski35168002014-07-21 15:25:30 -070036import android.util.ArrayMap;
Adam Lesinski0debc9a2014-07-16 19:09:13 -070037
Amith Yamasaniafbccb72017-11-27 10:44:24 -080038import java.lang.annotation.Retention;
39import java.lang.annotation.RetentionPolicy;
Varun Shah9f58b7c2019-03-01 10:36:21 -080040import java.time.Duration;
Suprabh Shukla868bde22018-02-20 20:59:52 -080041import java.util.ArrayList;
Adam Lesinski35168002014-07-21 15:25:30 -070042import java.util.Collections;
43import java.util.List;
Adam Lesinskicc562a82014-08-27 11:52:52 -070044import java.util.Map;
Amith Yamasani62ec27e92018-03-11 14:42:06 -070045import java.util.concurrent.TimeUnit;
Adam Lesinski35168002014-07-21 15:25:30 -070046
47/**
48 * Provides access to device usage history and statistics. Usage data is aggregated into
49 * time intervals: days, weeks, months, and years.
50 * <p />
51 * When requesting usage data since a particular time, the request might look something like this:
52 * <pre>
53 * PAST REQUEST_TIME TODAY FUTURE
54 * ————————————————————————————||———————————————————————————¦-----------------------|
55 * YEAR || ¦ |
56 * ————————————————————————————||———————————————————————————¦-----------------------|
57 * MONTH | || MONTH ¦ |
58 * ——————————————————|—————————||———————————————————————————¦-----------------------|
59 * | WEEK | WEEK|| | WEEK | WE¦EK | WEEK |
60 * ————————————————————————————||———————————————————|———————¦-----------------------|
61 * || |DAY|DAY|DAY|DAY¦DAY|DAY|DAY|DAY|DAY|DAY|
62 * ————————————————————————————||———————————————————————————¦-----------------------|
63 * </pre>
64 * A request for data in the middle of a time interval will include that interval.
65 * <p/>
Suprabh Shukla217ccda2018-02-23 17:57:12 -080066 * <b>NOTE:</b> Most methods on this API require the permission
67 * android.permission.PACKAGE_USAGE_STATS. However, declaring the permission implies intention to
68 * use the API and the user of the device still needs to grant permission through the Settings
69 * application.
70 * See {@link android.provider.Settings#ACTION_USAGE_ACCESS_SETTINGS}.
71 * Methods which only return the information for the calling package do not require this permission.
72 * E.g. {@link #getAppStandbyBucket()} and {@link #queryEventsForSelf(long, long)}.
Adam Lesinski35168002014-07-21 15:25:30 -070073 */
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -060074@SystemService(Context.USAGE_STATS_SERVICE)
Adam Lesinski0debc9a2014-07-16 19:09:13 -070075public final class UsageStatsManager {
Adam Lesinski0debc9a2014-07-16 19:09:13 -070076
77 /**
Adam Lesinski35168002014-07-21 15:25:30 -070078 * An interval type that spans a day. See {@link #queryUsageStats(int, long, long)}.
Adam Lesinski0debc9a2014-07-16 19:09:13 -070079 */
Adam Lesinski35168002014-07-21 15:25:30 -070080 public static final int INTERVAL_DAILY = 0;
Adam Lesinski0debc9a2014-07-16 19:09:13 -070081
82 /**
Adam Lesinski35168002014-07-21 15:25:30 -070083 * An interval type that spans a week. See {@link #queryUsageStats(int, long, long)}.
Adam Lesinski0debc9a2014-07-16 19:09:13 -070084 */
Adam Lesinski35168002014-07-21 15:25:30 -070085 public static final int INTERVAL_WEEKLY = 1;
Adam Lesinski0debc9a2014-07-16 19:09:13 -070086
87 /**
Adam Lesinski35168002014-07-21 15:25:30 -070088 * An interval type that spans a month. See {@link #queryUsageStats(int, long, long)}.
Adam Lesinski0debc9a2014-07-16 19:09:13 -070089 */
Adam Lesinski35168002014-07-21 15:25:30 -070090 public static final int INTERVAL_MONTHLY = 2;
Adam Lesinski0debc9a2014-07-16 19:09:13 -070091
92 /**
Adam Lesinski35168002014-07-21 15:25:30 -070093 * An interval type that spans a year. See {@link #queryUsageStats(int, long, long)}.
94 */
95 public static final int INTERVAL_YEARLY = 3;
96
97 /**
98 * An interval type that will use the best fit interval for the given time range.
99 * See {@link #queryUsageStats(int, long, long)}.
100 */
101 public static final int INTERVAL_BEST = 4;
102
103 /**
104 * The number of available intervals. Does not include {@link #INTERVAL_BEST}, since it
105 * is a pseudo interval (it actually selects a real interval).
Adam Lesinski0debc9a2014-07-16 19:09:13 -0700106 * {@hide}
107 */
Adam Lesinski35168002014-07-21 15:25:30 -0700108 public static final int INTERVAL_COUNT = 4;
109
Amith Yamasaniafbccb72017-11-27 10:44:24 -0800110
111 /**
112 * The app is whitelisted for some reason and the bucket cannot be changed.
113 * {@hide}
114 */
115 @SystemApi
116 public static final int STANDBY_BUCKET_EXEMPTED = 5;
117
118 /**
Amith Yamasani853e53f2018-03-16 16:08:57 -0700119 * The app was used very recently, currently in use or likely to be used very soon. Standby
120 * bucket values that are &le; {@link #STANDBY_BUCKET_ACTIVE} will not be throttled by the
121 * system while they are in this bucket. Buckets &gt; {@link #STANDBY_BUCKET_ACTIVE} will most
122 * likely be restricted in some way. For instance, jobs and alarms may be deferred.
Amith Yamasaniafbccb72017-11-27 10:44:24 -0800123 * @see #getAppStandbyBucket()
124 */
125 public static final int STANDBY_BUCKET_ACTIVE = 10;
126
127 /**
Amith Yamasani853e53f2018-03-16 16:08:57 -0700128 * The app was used recently and/or likely to be used in the next few hours. Restrictions will
129 * apply to these apps, such as deferral of jobs and alarms.
Amith Yamasaniafbccb72017-11-27 10:44:24 -0800130 * @see #getAppStandbyBucket()
131 */
132 public static final int STANDBY_BUCKET_WORKING_SET = 20;
133
134 /**
135 * The app was used in the last few days and/or likely to be used in the next few days.
Amith Yamasani853e53f2018-03-16 16:08:57 -0700136 * Restrictions will apply to these apps, such as deferral of jobs and alarms. The delays may be
137 * greater than for apps in higher buckets (lower bucket value). Bucket values &gt;
138 * {@link #STANDBY_BUCKET_FREQUENT} may additionally have network access limited.
Amith Yamasaniafbccb72017-11-27 10:44:24 -0800139 * @see #getAppStandbyBucket()
140 */
141 public static final int STANDBY_BUCKET_FREQUENT = 30;
142
143 /**
144 * The app has not be used for several days and/or is unlikely to be used for several days.
Kweku Adamsc6a9b342020-01-08 18:37:26 -0800145 * Apps in this bucket will have more restrictions, including network restrictions, except
Amith Yamasani853e53f2018-03-16 16:08:57 -0700146 * during certain short periods (at a minimum, once a day) when they are allowed to execute
147 * jobs, access the network, etc.
Amith Yamasaniafbccb72017-11-27 10:44:24 -0800148 * @see #getAppStandbyBucket()
149 */
150 public static final int STANDBY_BUCKET_RARE = 40;
151
152 /**
Kweku Adamsc6a9b342020-01-08 18:37:26 -0800153 * The app has not be used for several days, is unlikely to be used for several days, and has
154 * been misbehaving in some manner.
155 * Apps in this bucket will have the most restrictions, including network restrictions and
156 * additional restrictions on jobs.
157 * @see #getAppStandbyBucket()
158 */
159 public static final int STANDBY_BUCKET_RESTRICTED = 45;
160
161 /**
Amith Yamasaniafbccb72017-11-27 10:44:24 -0800162 * The app has never been used.
163 * {@hide}
164 */
165 @SystemApi
166 public static final int STANDBY_BUCKET_NEVER = 50;
167
Amith Yamasani119be9a2018-02-18 22:23:00 -0800168 /** @hide */
169 public static final int REASON_MAIN_MASK = 0xFF00;
170 /** @hide */
171 public static final int REASON_MAIN_DEFAULT = 0x0100;
Kweku Adamsd18f0732019-12-03 13:39:40 -0800172 /**
173 * The app spent sufficient time in the old bucket without any substantial event so it reached
174 * the timeout threshold to have its bucket lowered.
Kweku Adamsd18f0732019-12-03 13:39:40 -0800175 * @hide
176 */
Amith Yamasani119be9a2018-02-18 22:23:00 -0800177 public static final int REASON_MAIN_TIMEOUT = 0x0200;
Kweku Adamsd18f0732019-12-03 13:39:40 -0800178 /**
179 * The app was used in some way. Look at the REASON_SUB_USAGE_ reason for more details.
180 * @hide
181 */
Amith Yamasani119be9a2018-02-18 22:23:00 -0800182 public static final int REASON_MAIN_USAGE = 0x0300;
Kweku Adamsd18f0732019-12-03 13:39:40 -0800183 /**
Kweku Adamsc182d5e2020-01-08 18:37:26 -0800184 * Forced by the user/developer, either explicitly or implicitly through some action. If user
185 * action was not involved and this is purely due to the system,
186 * {@link #REASON_MAIN_FORCED_BY_SYSTEM} should be used instead.
Kweku Adamsd18f0732019-12-03 13:39:40 -0800187 * @hide
188 */
Kweku Adamsc182d5e2020-01-08 18:37:26 -0800189 public static final int REASON_MAIN_FORCED_BY_USER = 0x0400;
Kweku Adamsd18f0732019-12-03 13:39:40 -0800190 /**
Kweku Adamsc182d5e2020-01-08 18:37:26 -0800191 * Set by a privileged system app. This may be overridden by
192 * {@link #REASON_MAIN_FORCED_BY_SYSTEM} or user action.
Kweku Adamsd18f0732019-12-03 13:39:40 -0800193 * @hide
194 */
Amith Yamasani119be9a2018-02-18 22:23:00 -0800195 public static final int REASON_MAIN_PREDICTED = 0x0500;
Kweku Adamsc182d5e2020-01-08 18:37:26 -0800196 /**
197 * Forced by the system, independent of user action. If user action is involved,
198 * {@link #REASON_MAIN_FORCED_BY_USER} should be used instead. When this is used, only
199 * {@link #REASON_MAIN_FORCED_BY_SYSTEM} or user action can change the bucket.
200 * @hide
201 */
202 public static final int REASON_MAIN_FORCED_BY_SYSTEM = 0x0600;
Amith Yamasaniafbccb72017-11-27 10:44:24 -0800203
Amith Yamasani119be9a2018-02-18 22:23:00 -0800204 /** @hide */
205 public static final int REASON_SUB_MASK = 0x00FF;
Kweku Adamsd18f0732019-12-03 13:39:40 -0800206 /**
207 * The app was interacted with in some way by the system.
208 * @hide
209 */
Amith Yamasani119be9a2018-02-18 22:23:00 -0800210 public static final int REASON_SUB_USAGE_SYSTEM_INTERACTION = 0x0001;
Kweku Adamsd18f0732019-12-03 13:39:40 -0800211 /**
212 * A notification was viewed by the user. This does not mean the user interacted with the
213 * notification.
214 * @hide
215 */
Amith Yamasani119be9a2018-02-18 22:23:00 -0800216 public static final int REASON_SUB_USAGE_NOTIFICATION_SEEN = 0x0002;
Kweku Adamsd18f0732019-12-03 13:39:40 -0800217 /**
218 * The app was interacted with in some way by the user. This includes interacting with
219 * notification.
220 * @hide
221 */
Amith Yamasani119be9a2018-02-18 22:23:00 -0800222 public static final int REASON_SUB_USAGE_USER_INTERACTION = 0x0003;
Kweku Adamsd18f0732019-12-03 13:39:40 -0800223 /**
224 * An {@link android.app.Activity} moved to the foreground.
225 * @hide
226 */
Amith Yamasani119be9a2018-02-18 22:23:00 -0800227 public static final int REASON_SUB_USAGE_MOVE_TO_FOREGROUND = 0x0004;
Kweku Adamsd18f0732019-12-03 13:39:40 -0800228 /**
229 * An {@link android.app.Activity} moved to the background.
230 * @hide
231 */
Amith Yamasani119be9a2018-02-18 22:23:00 -0800232 public static final int REASON_SUB_USAGE_MOVE_TO_BACKGROUND = 0x0005;
Kweku Adamsd18f0732019-12-03 13:39:40 -0800233 /**
234 * There was a system update.
235 * @hide
236 */
Amith Yamasani119be9a2018-02-18 22:23:00 -0800237 public static final int REASON_SUB_USAGE_SYSTEM_UPDATE = 0x0006;
Kweku Adamsd18f0732019-12-03 13:39:40 -0800238 /**
239 * An app is in an elevated bucket because of an active timeout preventing it from being placed
240 * in a lower bucket.
241 * @hide
242 */
Amith Yamasani119be9a2018-02-18 22:23:00 -0800243 public static final int REASON_SUB_USAGE_ACTIVE_TIMEOUT = 0x0007;
Kweku Adamsd18f0732019-12-03 13:39:40 -0800244 /**
245 * This system package's sync adapter has been used for another package's content provider.
246 * @hide
247 */
Amith Yamasani119be9a2018-02-18 22:23:00 -0800248 public static final int REASON_SUB_USAGE_SYNC_ADAPTER = 0x0008;
Kweku Adamsd18f0732019-12-03 13:39:40 -0800249 /**
250 * A slice was pinned by an app.
251 * @hide
252 */
Amith Yamasani80c4be82018-03-26 10:54:04 -0700253 public static final int REASON_SUB_USAGE_SLICE_PINNED = 0x0009;
Kweku Adamsd18f0732019-12-03 13:39:40 -0800254 /** /**
255 * A slice was pinned by the default launcher or the default assistant.
256 * @hide
257 */
Amith Yamasani80c4be82018-03-26 10:54:04 -0700258 public static final int REASON_SUB_USAGE_SLICE_PINNED_PRIV = 0x000A;
Kweku Adamsd18f0732019-12-03 13:39:40 -0800259 /**
260 * A sync operation that is exempt from app standby was scheduled when the device wasn't Dozing.
261 * @hide
262 */
Makoto Onukid5f25d22018-05-22 16:02:17 -0700263 public static final int REASON_SUB_USAGE_EXEMPTED_SYNC_SCHEDULED_NON_DOZE = 0x000B;
Kweku Adamsd18f0732019-12-03 13:39:40 -0800264 /**
265 * A sync operation that is exempt from app standby was scheduled while the device was Dozing.
266 * @hide
267 */
Makoto Onukid5f25d22018-05-22 16:02:17 -0700268 public static final int REASON_SUB_USAGE_EXEMPTED_SYNC_SCHEDULED_DOZE = 0x000C;
Kweku Adamsd18f0732019-12-03 13:39:40 -0800269 /**
270 * A sync operation that is exempt from app standby started.
271 * @hide
272 */
Makoto Onukid5f25d22018-05-22 16:02:17 -0700273 public static final int REASON_SUB_USAGE_EXEMPTED_SYNC_START = 0x000D;
Kweku Adamsd18f0732019-12-03 13:39:40 -0800274 /**
275 * A sync operation that is not exempt from app standby was scheduled.
276 * @hide
277 */
Michael Wachenschwanzc3295202019-02-20 17:19:52 -0800278 public static final int REASON_SUB_USAGE_UNEXEMPTED_SYNC_SCHEDULED = 0x000E;
Kweku Adamsd18f0732019-12-03 13:39:40 -0800279 /**
280 * A foreground service started.
281 * @hide
282 */
Michael Wachenschwanz6ced0ee2019-04-15 16:43:28 -0700283 public static final int REASON_SUB_USAGE_FOREGROUND_SERVICE_START = 0x000F;
Kweku Adamsd18f0732019-12-03 13:39:40 -0800284 /**
285 * The predicted bucket was restored after the app's temporary elevation to the ACTIVE bucket
286 * ended.
287 * @hide
288 */
Amith Yamasani3154dcf2018-03-27 18:24:04 -0700289 public static final int REASON_SUB_PREDICTED_RESTORED = 0x0001;
Kweku Adamsc6a9b342020-01-08 18:37:26 -0800290 /**
Kweku Adamsaa461942020-03-16 11:59:05 -0700291 * The reason the system forced the app into the bucket is unknown or undefined.
Kweku Adamsc6a9b342020-01-08 18:37:26 -0800292 * @hide
293 */
Kweku Adamsaa461942020-03-16 11:59:05 -0700294 public static final int REASON_SUB_FORCED_SYSTEM_FLAG_UNDEFINED = 0;
Kweku Adamsc6a9b342020-01-08 18:37:26 -0800295 /**
296 * The app was unnecessarily using system resources (battery, memory, etc) in the background.
297 * @hide
298 */
Kweku Adamsaa461942020-03-16 11:59:05 -0700299 public static final int REASON_SUB_FORCED_SYSTEM_FLAG_BACKGROUND_RESOURCE_USAGE = 1 << 0;
Kweku Adamsc6a9b342020-01-08 18:37:26 -0800300 /**
301 * The app was deemed to be intentionally abusive.
302 * @hide
303 */
Kweku Adamsaa461942020-03-16 11:59:05 -0700304 public static final int REASON_SUB_FORCED_SYSTEM_FLAG_ABUSE = 1 << 1;
Kweku Adamsc6a9b342020-01-08 18:37:26 -0800305 /**
306 * The app was displaying buggy behavior.
307 * @hide
308 */
Kweku Adamsaa461942020-03-16 11:59:05 -0700309 public static final int REASON_SUB_FORCED_SYSTEM_FLAG_BUGGY = 1 << 2;
Amith Yamasani3154dcf2018-03-27 18:24:04 -0700310
Makoto Onuki75ad2492018-03-28 14:42:42 -0700311
Amith Yamasani3154dcf2018-03-27 18:24:04 -0700312 /** @hide */
Jeff Sharkeyce8db992017-12-13 20:05:05 -0700313 @IntDef(flag = false, prefix = { "STANDBY_BUCKET_" }, value = {
Amith Yamasaniafbccb72017-11-27 10:44:24 -0800314 STANDBY_BUCKET_EXEMPTED,
315 STANDBY_BUCKET_ACTIVE,
316 STANDBY_BUCKET_WORKING_SET,
317 STANDBY_BUCKET_FREQUENT,
318 STANDBY_BUCKET_RARE,
Kweku Adamsc6a9b342020-01-08 18:37:26 -0800319 STANDBY_BUCKET_RESTRICTED,
Amith Yamasaniafbccb72017-11-27 10:44:24 -0800320 STANDBY_BUCKET_NEVER,
321 })
322 @Retention(RetentionPolicy.SOURCE)
323 public @interface StandbyBuckets {}
324
Kweku Adamsaa461942020-03-16 11:59:05 -0700325 /** @hide */
326 @IntDef(flag = true, prefix = {"REASON_SUB_FORCED_SYSTEM_FLAG_FLAG_"}, value = {
327 REASON_SUB_FORCED_SYSTEM_FLAG_UNDEFINED,
328 REASON_SUB_FORCED_SYSTEM_FLAG_BACKGROUND_RESOURCE_USAGE,
329 REASON_SUB_FORCED_SYSTEM_FLAG_ABUSE,
330 REASON_SUB_FORCED_SYSTEM_FLAG_BUGGY,
331 })
332 @Retention(RetentionPolicy.SOURCE)
333 public @interface SystemForcedReasons {
334 }
335
Amith Yamasani62ec27e92018-03-11 14:42:06 -0700336 /**
337 * Observer id of the registered observer for the group of packages that reached the usage
338 * time limit. Included as an extra in the PendingIntent that was registered.
339 * @hide
340 */
341 @SystemApi
342 public static final String EXTRA_OBSERVER_ID = "android.app.usage.extra.OBSERVER_ID";
343
344 /**
345 * Original time limit in milliseconds specified by the registered observer for the group of
346 * packages that reached the usage time limit. Included as an extra in the PendingIntent that
347 * was registered.
348 * @hide
349 */
350 @SystemApi
351 public static final String EXTRA_TIME_LIMIT = "android.app.usage.extra.TIME_LIMIT";
352
353 /**
354 * Actual usage time in milliseconds for the group of packages that reached the specified time
355 * limit. Included as an extra in the PendingIntent that was registered.
356 * @hide
357 */
358 @SystemApi
359 public static final String EXTRA_TIME_USED = "android.app.usage.extra.TIME_USED";
360
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -0800361
362 /**
363 * App usage observers will consider the task root package the source of usage.
364 * @hide
365 */
366 @SystemApi
367 public static final int USAGE_SOURCE_TASK_ROOT_ACTIVITY = 1;
368
369 /**
370 * App usage observers will consider the visible activity's package the source of usage.
371 * @hide
372 */
373 @SystemApi
374 public static final int USAGE_SOURCE_CURRENT_ACTIVITY = 2;
375
376 /** @hide */
377 @IntDef(prefix = { "USAGE_SOURCE_" }, value = {
378 USAGE_SOURCE_TASK_ROOT_ACTIVITY,
379 USAGE_SOURCE_CURRENT_ACTIVITY,
380 })
381 @Retention(RetentionPolicy.SOURCE)
382 public @interface UsageSource {}
383
Mathew Inwood31755f92018-12-20 13:53:36 +0000384 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Adam Lesinski35168002014-07-21 15:25:30 -0700385 private static final UsageEvents sEmptyResults = new UsageEvents();
Adam Lesinski0debc9a2014-07-16 19:09:13 -0700386
Mathew Inwood8c854f82018-09-14 12:35:36 +0100387 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Adam Lesinski0debc9a2014-07-16 19:09:13 -0700388 private final Context mContext;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100389 @UnsupportedAppUsage
Adam Lesinski0debc9a2014-07-16 19:09:13 -0700390 private final IUsageStatsManager mService;
391
392 /**
393 * {@hide}
394 */
395 public UsageStatsManager(Context context, IUsageStatsManager service) {
396 mContext = context;
397 mService = service;
398 }
399
Adam Lesinski35168002014-07-21 15:25:30 -0700400 /**
401 * Gets application usage stats for the given time range, aggregated by the specified interval.
Adam Lesinski35168002014-07-21 15:25:30 -0700402 *
Michael Wachenschwanzd1e659b2019-04-05 11:55:02 -0700403 * <p>
404 * The returned list will contain one or more {@link UsageStats} objects for each package, with
405 * usage data that covers at least the given time range.
406 * Note: The begin and end times of the time range may be expanded to the nearest whole interval
407 * period.
408 * </p>
Adam Lesinski35168002014-07-21 15:25:30 -0700409 *
Suprabh Shukla217ccda2018-02-23 17:57:12 -0800410 * <p> The caller must have {@link android.Manifest.permission#PACKAGE_USAGE_STATS} </p>
Varun Shah3a315202019-07-24 16:33:42 -0700411 * <em>Note: Starting from {@link android.os.Build.VERSION_CODES#R Android R}, if the user's
412 * device is not in an unlocked state (as defined by {@link UserManager#isUserUnlocked()}),
413 * then {@code null} will be returned.</em>
Suprabh Shukla217ccda2018-02-23 17:57:12 -0800414 *
Adam Lesinski35168002014-07-21 15:25:30 -0700415 * @param intervalType The time interval by which the stats are aggregated.
416 * @param beginTime The inclusive beginning of the range of stats to include in the results.
Michael Wachenschwanz17415c22019-04-01 15:40:49 -0700417 * Defined in terms of "Unix time", see
418 * {@link java.lang.System#currentTimeMillis}.
419 * @param endTime The exclusive end of the range of stats to include in the results. Defined
420 * in terms of "Unix time", see {@link java.lang.System#currentTimeMillis}.
Esteban Talaverafa962312017-10-09 14:58:28 +0100421 * @return A list of {@link UsageStats}
Adam Lesinski35168002014-07-21 15:25:30 -0700422 *
423 * @see #INTERVAL_DAILY
424 * @see #INTERVAL_WEEKLY
425 * @see #INTERVAL_MONTHLY
426 * @see #INTERVAL_YEARLY
427 * @see #INTERVAL_BEST
428 */
Adam Lesinski35168002014-07-21 15:25:30 -0700429 public List<UsageStats> queryUsageStats(int intervalType, long beginTime, long endTime) {
Adam Lesinski0debc9a2014-07-16 19:09:13 -0700430 try {
Adam Lesinski7f61e962014-09-02 16:43:52 -0700431 @SuppressWarnings("unchecked")
Adam Lesinski35168002014-07-21 15:25:30 -0700432 ParceledListSlice<UsageStats> slice = mService.queryUsageStats(intervalType, beginTime,
433 endTime, mContext.getOpPackageName());
434 if (slice != null) {
435 return slice.getList();
Adam Lesinski0debc9a2014-07-16 19:09:13 -0700436 }
Adam Lesinski35168002014-07-21 15:25:30 -0700437 } catch (RemoteException e) {
Esteban Talaverafa962312017-10-09 14:58:28 +0100438 // fallthrough and return the empty list.
Adam Lesinski35168002014-07-21 15:25:30 -0700439 }
Adam Lesinski7f61e962014-09-02 16:43:52 -0700440 return Collections.emptyList();
441 }
442
443 /**
444 * Gets the hardware configurations the device was in for the given time range, aggregated by
445 * the specified interval. The results are ordered as in
446 * {@link #queryUsageStats(int, long, long)}.
Suprabh Shukla217ccda2018-02-23 17:57:12 -0800447 * <p> The caller must have {@link android.Manifest.permission#PACKAGE_USAGE_STATS} </p>
Varun Shah3a315202019-07-24 16:33:42 -0700448 * <em>Note: Starting from {@link android.os.Build.VERSION_CODES#R Android R}, if the user's
449 * device is not in an unlocked state (as defined by {@link UserManager#isUserUnlocked()}),
450 * then {@code null} will be returned.</em>
Adam Lesinski7f61e962014-09-02 16:43:52 -0700451 *
452 * @param intervalType The time interval by which the stats are aggregated.
453 * @param beginTime The inclusive beginning of the range of stats to include in the results.
Michael Wachenschwanz17415c22019-04-01 15:40:49 -0700454 * Defined in terms of "Unix time", see
455 * {@link java.lang.System#currentTimeMillis}.
456 * @param endTime The exclusive end of the range of stats to include in the results. Defined
457 * in terms of "Unix time", see {@link java.lang.System#currentTimeMillis}.
Esteban Talaverafa962312017-10-09 14:58:28 +0100458 * @return A list of {@link ConfigurationStats}
Adam Lesinski7f61e962014-09-02 16:43:52 -0700459 */
460 public List<ConfigurationStats> queryConfigurations(int intervalType, long beginTime,
461 long endTime) {
462 try {
463 @SuppressWarnings("unchecked")
464 ParceledListSlice<ConfigurationStats> slice = mService.queryConfigurationStats(
465 intervalType, beginTime, endTime, mContext.getOpPackageName());
466 if (slice != null) {
467 return slice.getList();
468 }
469 } catch (RemoteException e) {
470 // fallthrough and return the empty list.
471 }
472 return Collections.emptyList();
Adam Lesinski35168002014-07-21 15:25:30 -0700473 }
Adam Lesinski0debc9a2014-07-16 19:09:13 -0700474
Adam Lesinski35168002014-07-21 15:25:30 -0700475 /**
Dianne Hackbornced54392018-02-26 13:07:42 -0800476 * Gets aggregated event stats for the given time range, aggregated by the specified interval.
477 * <p>The returned list will contain a {@link EventStats} object for each event type that
478 * is being aggregated and has data for an interval that is a subset of the time range given.
479 *
480 * <p>The current event types that will be aggregated here are:</p>
481 * <ul>
482 * <li>{@link UsageEvents.Event#SCREEN_INTERACTIVE}</li>
483 * <li>{@link UsageEvents.Event#SCREEN_NON_INTERACTIVE}</li>
Dianne Hackborn3378aa92018-03-30 17:43:49 -0700484 * <li>{@link UsageEvents.Event#KEYGUARD_SHOWN}</li>
485 * <li>{@link UsageEvents.Event#KEYGUARD_HIDDEN}</li>
Dianne Hackbornced54392018-02-26 13:07:42 -0800486 * </ul>
487 *
488 * <p> The caller must have {@link android.Manifest.permission#PACKAGE_USAGE_STATS} </p>
Varun Shah3a315202019-07-24 16:33:42 -0700489 * <em>Note: Starting from {@link android.os.Build.VERSION_CODES#R Android R}, if the user's
490 * device is not in an unlocked state (as defined by {@link UserManager#isUserUnlocked()}),
491 * then {@code null} will be returned.</em>
Dianne Hackbornced54392018-02-26 13:07:42 -0800492 *
493 * @param intervalType The time interval by which the stats are aggregated.
494 * @param beginTime The inclusive beginning of the range of stats to include in the results.
Michael Wachenschwanz17415c22019-04-01 15:40:49 -0700495 * Defined in terms of "Unix time", see
496 * {@link java.lang.System#currentTimeMillis}.
497 * @param endTime The exclusive end of the range of stats to include in the results. Defined
498 * in terms of "Unix time", see {@link java.lang.System#currentTimeMillis}.
Dianne Hackbornced54392018-02-26 13:07:42 -0800499 * @return A list of {@link EventStats}
500 *
501 * @see #INTERVAL_DAILY
502 * @see #INTERVAL_WEEKLY
503 * @see #INTERVAL_MONTHLY
504 * @see #INTERVAL_YEARLY
505 * @see #INTERVAL_BEST
506 */
507 public List<EventStats> queryEventStats(int intervalType, long beginTime, long endTime) {
508 try {
509 @SuppressWarnings("unchecked")
510 ParceledListSlice<EventStats> slice = mService.queryEventStats(intervalType, beginTime,
511 endTime, mContext.getOpPackageName());
512 if (slice != null) {
513 return slice.getList();
514 }
515 } catch (RemoteException e) {
516 // fallthrough and return the empty list.
517 }
518 return Collections.emptyList();
519 }
520
521 /**
Adam Lesinski35168002014-07-21 15:25:30 -0700522 * Query for events in the given time range. Events are only kept by the system for a few
523 * days.
Suprabh Shukla217ccda2018-02-23 17:57:12 -0800524 * <p> The caller must have {@link android.Manifest.permission#PACKAGE_USAGE_STATS} </p>
Varun Shah3a315202019-07-24 16:33:42 -0700525 * <em>Note: Starting from {@link android.os.Build.VERSION_CODES#R Android R}, if the user's
526 * device is not in an unlocked state (as defined by {@link UserManager#isUserUnlocked()}),
527 * then {@code null} will be returned.</em>
Adam Lesinski35168002014-07-21 15:25:30 -0700528 *
529 * @param beginTime The inclusive beginning of the range of events to include in the results.
Michael Wachenschwanz17415c22019-04-01 15:40:49 -0700530 * Defined in terms of "Unix time", see
531 * {@link java.lang.System#currentTimeMillis}.
532 * @param endTime The exclusive end of the range of events to include in the results. Defined
533 * in terms of "Unix time", see {@link java.lang.System#currentTimeMillis}.
Adam Lesinski35168002014-07-21 15:25:30 -0700534 * @return A {@link UsageEvents}.
535 */
Adam Lesinski35168002014-07-21 15:25:30 -0700536 public UsageEvents queryEvents(long beginTime, long endTime) {
537 try {
538 UsageEvents iter = mService.queryEvents(beginTime, endTime,
539 mContext.getOpPackageName());
540 if (iter != null) {
541 return iter;
542 }
543 } catch (RemoteException e) {
Esteban Talaverafa962312017-10-09 14:58:28 +0100544 // fallthrough and return empty result.
Adam Lesinski35168002014-07-21 15:25:30 -0700545 }
546 return sEmptyResults;
547 }
Adam Lesinski0debc9a2014-07-16 19:09:13 -0700548
Adam Lesinski35168002014-07-21 15:25:30 -0700549 /**
Suprabh Shukla217ccda2018-02-23 17:57:12 -0800550 * Like {@link #queryEvents(long, long)}, but only returns events for the calling package.
Varun Shah3a315202019-07-24 16:33:42 -0700551 * <em>Note: Starting from {@link android.os.Build.VERSION_CODES#R Android R}, if the user's
552 * device is not in an unlocked state (as defined by {@link UserManager#isUserUnlocked()}),
553 * then {@code null} will be returned.</em>
Suprabh Shukla217ccda2018-02-23 17:57:12 -0800554 *
555 * @param beginTime The inclusive beginning of the range of events to include in the results.
Michael Wachenschwanz17415c22019-04-01 15:40:49 -0700556 * Defined in terms of "Unix time", see
557 * {@link java.lang.System#currentTimeMillis}.
558 * @param endTime The exclusive end of the range of events to include in the results. Defined
559 * in terms of "Unix time", see {@link java.lang.System#currentTimeMillis}.
Suprabh Shukla217ccda2018-02-23 17:57:12 -0800560 * @return A {@link UsageEvents} object.
561 *
562 * @see #queryEvents(long, long)
563 */
564 public UsageEvents queryEventsForSelf(long beginTime, long endTime) {
565 try {
566 final UsageEvents events = mService.queryEventsForPackage(beginTime, endTime,
567 mContext.getOpPackageName());
568 if (events != null) {
569 return events;
570 }
571 } catch (RemoteException e) {
572 // fallthrough
573 }
574 return sEmptyResults;
575 }
576
577 /**
Adam Lesinski35168002014-07-21 15:25:30 -0700578 * A convenience method that queries for all stats in the given range (using the best interval
579 * for that range), merges the resulting data, and keys it by package name.
580 * See {@link #queryUsageStats(int, long, long)}.
Suprabh Shukla217ccda2018-02-23 17:57:12 -0800581 * <p> The caller must have {@link android.Manifest.permission#PACKAGE_USAGE_STATS} </p>
Adam Lesinski35168002014-07-21 15:25:30 -0700582 *
583 * @param beginTime The inclusive beginning of the range of stats to include in the results.
Michael Wachenschwanz17415c22019-04-01 15:40:49 -0700584 * Defined in terms of "Unix time", see
585 * {@link java.lang.System#currentTimeMillis}.
586 * @param endTime The exclusive end of the range of stats to include in the results. Defined
587 * in terms of "Unix time", see {@link java.lang.System#currentTimeMillis}.
Esteban Talaverafa962312017-10-09 14:58:28 +0100588 * @return A {@link java.util.Map} keyed by package name
Adam Lesinski35168002014-07-21 15:25:30 -0700589 */
Adam Lesinskicc562a82014-08-27 11:52:52 -0700590 public Map<String, UsageStats> queryAndAggregateUsageStats(long beginTime, long endTime) {
Adam Lesinski35168002014-07-21 15:25:30 -0700591 List<UsageStats> stats = queryUsageStats(INTERVAL_BEST, beginTime, endTime);
592 if (stats.isEmpty()) {
Adam Lesinskicc562a82014-08-27 11:52:52 -0700593 return Collections.emptyMap();
Adam Lesinski35168002014-07-21 15:25:30 -0700594 }
Adam Lesinski0debc9a2014-07-16 19:09:13 -0700595
Adam Lesinski35168002014-07-21 15:25:30 -0700596 ArrayMap<String, UsageStats> aggregatedStats = new ArrayMap<>();
597 final int statCount = stats.size();
598 for (int i = 0; i < statCount; i++) {
599 UsageStats newStat = stats.get(i);
600 UsageStats existingStat = aggregatedStats.get(newStat.getPackageName());
601 if (existingStat == null) {
602 aggregatedStats.put(newStat.mPackageName, newStat);
603 } else {
604 existingStat.add(newStat);
Adam Lesinski0debc9a2014-07-16 19:09:13 -0700605 }
606 }
607 return aggregatedStats;
608 }
Amith Yamasanicf768722015-04-23 20:36:41 -0700609
610 /**
Amith Yamasanie5f33042015-05-08 13:20:22 -0700611 * Returns whether the specified app is currently considered inactive. This will be true if the
Amith Yamasanicf768722015-04-23 20:36:41 -0700612 * app hasn't been used directly or indirectly for a period of time defined by the system. This
Kweku Adamsf35ed3702020-02-11 17:32:54 -0800613 * could be of the order of several hours or days. Apps are not considered inactive when the
614 * device is charging.
Amith Yamasanicf768722015-04-23 20:36:41 -0700615 * @param packageName The package name of the app to query
Amith Yamasanie5f33042015-05-08 13:20:22 -0700616 * @return whether the app is currently considered inactive
Amith Yamasanicf768722015-04-23 20:36:41 -0700617 */
Amith Yamasanie5f33042015-05-08 13:20:22 -0700618 public boolean isAppInactive(String packageName) {
Amith Yamasanicf768722015-04-23 20:36:41 -0700619 try {
Jeff Sharkeyad357d12018-02-02 13:25:31 -0700620 return mService.isAppInactive(packageName, mContext.getUserId());
Amith Yamasanicf768722015-04-23 20:36:41 -0700621 } catch (RemoteException e) {
622 // fall through and return default
623 }
624 return false;
625 }
Amith Yamasani901e9242015-05-13 18:21:09 -0700626
627 /**
Amith Yamasaniafbccb72017-11-27 10:44:24 -0800628 * {@hide}
Amith Yamasani901e9242015-05-13 18:21:09 -0700629 */
630 public void setAppInactive(String packageName, boolean inactive) {
631 try {
Jeff Sharkeyad357d12018-02-02 13:25:31 -0700632 mService.setAppInactive(packageName, inactive, mContext.getUserId());
Amith Yamasani901e9242015-05-13 18:21:09 -0700633 } catch (RemoteException e) {
634 // fall through
635 }
636 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700637
638 /**
Amith Yamasaniafbccb72017-11-27 10:44:24 -0800639 * Returns the current standby bucket of the calling app. The system determines the standby
640 * state of the app based on app usage patterns. Standby buckets determine how much an app will
Amith Yamasani853e53f2018-03-16 16:08:57 -0700641 * be restricted from running background tasks such as jobs and alarms.
Amith Yamasanie8789312017-12-10 14:34:26 -0800642 * <p>Restrictions increase progressively from {@link #STANDBY_BUCKET_ACTIVE} to
Kweku Adamsc6a9b342020-01-08 18:37:26 -0800643 * {@link #STANDBY_BUCKET_RESTRICTED}, with {@link #STANDBY_BUCKET_ACTIVE} being the least
Amith Yamasaniafbccb72017-11-27 10:44:24 -0800644 * restrictive. The battery level of the device might also affect the restrictions.
Amith Yamasani853e53f2018-03-16 16:08:57 -0700645 * <p>Apps in buckets &le; {@link #STANDBY_BUCKET_ACTIVE} have no standby restrictions imposed.
646 * Apps in buckets &gt; {@link #STANDBY_BUCKET_FREQUENT} may have network access restricted when
647 * running in the background.
648 * <p>The standby state of an app can change at any time either due to a user interaction or a
649 * system interaction or some algorithm determining that the app can be restricted for a period
650 * of time before the user has a need for it.
651 * <p>You can also query the recent history of standby bucket changes by calling
652 * {@link #queryEventsForSelf(long, long)} and searching for
653 * {@link UsageEvents.Event#STANDBY_BUCKET_CHANGED}.
Amith Yamasaniafbccb72017-11-27 10:44:24 -0800654 *
Amith Yamasanie8789312017-12-10 14:34:26 -0800655 * @return the current standby bucket of the calling app. One of STANDBY_BUCKET_* constants.
Amith Yamasani17fffee2017-09-29 13:17:43 -0700656 */
Amith Yamasaniafbccb72017-11-27 10:44:24 -0800657 public @StandbyBuckets int getAppStandbyBucket() {
658 try {
659 return mService.getAppStandbyBucket(mContext.getOpPackageName(),
660 mContext.getOpPackageName(),
661 mContext.getUserId());
662 } catch (RemoteException e) {
663 }
664 return STANDBY_BUCKET_ACTIVE;
665 }
666
667 /**
668 * {@hide}
669 * Returns the current standby bucket of the specified app. The caller must hold the permission
670 * android.permission.PACKAGE_USAGE_STATS.
671 * @param packageName the package for which to fetch the current standby bucket.
672 */
673 @SystemApi
674 @RequiresPermission(android.Manifest.permission.PACKAGE_USAGE_STATS)
Amith Yamasani17fffee2017-09-29 13:17:43 -0700675 public @StandbyBuckets int getAppStandbyBucket(String packageName) {
676 try {
677 return mService.getAppStandbyBucket(packageName, mContext.getOpPackageName(),
678 mContext.getUserId());
679 } catch (RemoteException e) {
680 }
Amith Yamasaniafbccb72017-11-27 10:44:24 -0800681 return STANDBY_BUCKET_ACTIVE;
Amith Yamasani17fffee2017-09-29 13:17:43 -0700682 }
683
684 /**
Amith Yamasaniafbccb72017-11-27 10:44:24 -0800685 * {@hide}
Amith Yamasanie8789312017-12-10 14:34:26 -0800686 * Changes an app's standby bucket to the provided value. The caller can only set the standby
Kweku Adamsc6a9b342020-01-08 18:37:26 -0800687 * bucket for a different app than itself. The caller will not be able to change an app's
688 * standby bucket if that app is in the {@link #STANDBY_BUCKET_RESTRICTED} bucket.
Amith Yamasanie8789312017-12-10 14:34:26 -0800689 * @param packageName the package name of the app to set the bucket for. A SecurityException
690 * will be thrown if the package name is that of the caller.
691 * @param bucket the standby bucket to set it to, which should be one of STANDBY_BUCKET_*.
692 * Setting a standby bucket outside of the range of STANDBY_BUCKET_ACTIVE to
693 * STANDBY_BUCKET_NEVER will result in a SecurityException.
Amith Yamasani17fffee2017-09-29 13:17:43 -0700694 */
Amith Yamasani4470ab92017-10-31 13:29:00 -0700695 @SystemApi
696 @RequiresPermission(android.Manifest.permission.CHANGE_APP_IDLE_STATE)
Amith Yamasani17fffee2017-09-29 13:17:43 -0700697 public void setAppStandbyBucket(String packageName, @StandbyBuckets int bucket) {
698 try {
699 mService.setAppStandbyBucket(packageName, bucket, mContext.getUserId());
700 } catch (RemoteException e) {
Amith Yamasanifd44f272018-05-14 14:47:19 -0700701 throw e.rethrowFromSystemServer();
Amith Yamasani17fffee2017-09-29 13:17:43 -0700702 }
703 }
704
705 /**
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700706 * {@hide}
Amith Yamasanie8789312017-12-10 14:34:26 -0800707 * Returns the current standby bucket of every app that has a bucket assigned to it.
708 * The caller must hold the permission android.permission.PACKAGE_USAGE_STATS. The key of the
709 * returned Map is the package name and the value is the bucket assigned to the package.
710 * @see #getAppStandbyBucket()
711 */
712 @SystemApi
713 @RequiresPermission(android.Manifest.permission.PACKAGE_USAGE_STATS)
714 public Map<String, Integer> getAppStandbyBuckets() {
715 try {
Suprabh Shukla868bde22018-02-20 20:59:52 -0800716 final ParceledListSlice<AppStandbyInfo> slice = mService.getAppStandbyBuckets(
Amith Yamasanie8789312017-12-10 14:34:26 -0800717 mContext.getOpPackageName(), mContext.getUserId());
Suprabh Shukla868bde22018-02-20 20:59:52 -0800718 final List<AppStandbyInfo> bucketList = slice.getList();
719 final ArrayMap<String, Integer> bucketMap = new ArrayMap<>();
720 final int n = bucketList.size();
721 for (int i = 0; i < n; i++) {
722 final AppStandbyInfo bucketInfo = bucketList.get(i);
723 bucketMap.put(bucketInfo.mPackageName, bucketInfo.mStandbyBucket);
724 }
725 return bucketMap;
Amith Yamasanie8789312017-12-10 14:34:26 -0800726 } catch (RemoteException e) {
Amith Yamasanifd44f272018-05-14 14:47:19 -0700727 throw e.rethrowFromSystemServer();
Amith Yamasanie8789312017-12-10 14:34:26 -0800728 }
Amith Yamasanie8789312017-12-10 14:34:26 -0800729 }
730
731 /**
732 * {@hide}
733 * Changes the app standby bucket for multiple apps at once. The Map is keyed by the package
Kweku Adamsc6a9b342020-01-08 18:37:26 -0800734 * name and the value is one of STANDBY_BUCKET_*. The caller will not be able to change an
735 * app's standby bucket if that app is in the {@link #STANDBY_BUCKET_RESTRICTED} bucket.
Amith Yamasanie8789312017-12-10 14:34:26 -0800736 * @param appBuckets a map of package name to bucket value.
737 */
738 @SystemApi
739 @RequiresPermission(android.Manifest.permission.CHANGE_APP_IDLE_STATE)
740 public void setAppStandbyBuckets(Map<String, Integer> appBuckets) {
Suprabh Shukla868bde22018-02-20 20:59:52 -0800741 if (appBuckets == null) {
742 return;
743 }
744 final List<AppStandbyInfo> bucketInfoList = new ArrayList<>(appBuckets.size());
745 for (Map.Entry<String, Integer> bucketEntry : appBuckets.entrySet()) {
746 bucketInfoList.add(new AppStandbyInfo(bucketEntry.getKey(), bucketEntry.getValue()));
747 }
748 final ParceledListSlice<AppStandbyInfo> slice = new ParceledListSlice<>(bucketInfoList);
Amith Yamasanie8789312017-12-10 14:34:26 -0800749 try {
Suprabh Shukla868bde22018-02-20 20:59:52 -0800750 mService.setAppStandbyBuckets(slice, mContext.getUserId());
Amith Yamasanie8789312017-12-10 14:34:26 -0800751 } catch (RemoteException e) {
Amith Yamasanifd44f272018-05-14 14:47:19 -0700752 throw e.rethrowFromSystemServer();
Amith Yamasanie8789312017-12-10 14:34:26 -0800753 }
754 }
755
Amith Yamasani62ec27e92018-03-11 14:42:06 -0700756 /**
757 * @hide
758 * Register an app usage limit observer that receives a callback on the provided intent when
Michael Wachenschwanz36778522018-11-12 11:06:19 -0800759 * the sum of usages of apps and tokens in the {@code observed} array exceeds the
760 * {@code timeLimit} specified. The structure of a token is a String with the reporting
761 * package's name and a token the reporting app will use, separated by the forward slash
762 * character. Example: com.reporting.package/5OM3*0P4QU3-7OK3N
763 * The observer will automatically be unregistered when the time limit is reached and the
764 * intent is delivered. Registering an {@code observerId} that was already registered will
765 * override the previous one. No more than 1000 unique {@code observerId} may be registered by
766 * a single uid at any one time.
Amith Yamasani62ec27e92018-03-11 14:42:06 -0700767 * @param observerId A unique id associated with the group of apps to be monitored. There can
768 * be multiple groups with common packages and different time limits.
Michael Wachenschwanz36778522018-11-12 11:06:19 -0800769 * @param observedEntities The list of packages and token to observe for usage time. Cannot be
770 * null and must include at least one package or token.
Amith Yamasani62ec27e92018-03-11 14:42:06 -0700771 * @param timeLimit The total time the set of apps can be in the foreground before the
Michael Wachenschwanzc8703092018-05-01 16:02:45 -0700772 * callbackIntent is delivered. Must be at least one minute.
Amith Yamasanibc813eb2018-03-20 19:37:46 -0700773 * @param timeUnit The unit for time specified in {@code timeLimit}. Cannot be null.
Varun Shah2546cef2019-01-11 15:50:54 -0800774 * @param callbackIntent The PendingIntent that will be dispatched when the usage limit is
Amith Yamasani62ec27e92018-03-11 14:42:06 -0700775 * exceeded by the group of apps. The delivered Intent will also contain
776 * the extras {@link #EXTRA_OBSERVER_ID}, {@link #EXTRA_TIME_LIMIT} and
Amith Yamasanibc813eb2018-03-20 19:37:46 -0700777 * {@link #EXTRA_TIME_USED}. Cannot be null.
Michael Wachenschwanz641e3382018-10-23 23:21:48 -0700778 * @throws SecurityException if the caller doesn't have the OBSERVE_APP_USAGE permission and
Amith Yamasanibc813eb2018-03-20 19:37:46 -0700779 * is not the profile owner of this user.
Amith Yamasani62ec27e92018-03-11 14:42:06 -0700780 */
781 @SystemApi
Amith Yamasanibc813eb2018-03-20 19:37:46 -0700782 @RequiresPermission(android.Manifest.permission.OBSERVE_APP_USAGE)
Michael Wachenschwanz36778522018-11-12 11:06:19 -0800783 public void registerAppUsageObserver(int observerId, @NonNull String[] observedEntities,
784 long timeLimit, @NonNull TimeUnit timeUnit, @NonNull PendingIntent callbackIntent) {
Amith Yamasani62ec27e92018-03-11 14:42:06 -0700785 try {
Michael Wachenschwanz36778522018-11-12 11:06:19 -0800786 mService.registerAppUsageObserver(observerId, observedEntities,
787 timeUnit.toMillis(timeLimit), callbackIntent, mContext.getOpPackageName());
Amith Yamasani62ec27e92018-03-11 14:42:06 -0700788 } catch (RemoteException e) {
Amith Yamasanifd44f272018-05-14 14:47:19 -0700789 throw e.rethrowFromSystemServer();
Amith Yamasani62ec27e92018-03-11 14:42:06 -0700790 }
791 }
792
793 /**
794 * @hide
Amith Yamasanibc813eb2018-03-20 19:37:46 -0700795 * Unregister the app usage observer specified by the {@code observerId}. This will only apply
796 * to any observer registered by this application. Unregistering an observer that was already
Amith Yamasani62ec27e92018-03-11 14:42:06 -0700797 * unregistered or never registered will have no effect.
798 * @param observerId The id of the observer that was previously registered.
Michael Wachenschwanz641e3382018-10-23 23:21:48 -0700799 * @throws SecurityException if the caller doesn't have the OBSERVE_APP_USAGE permission and is
Amith Yamasanibc813eb2018-03-20 19:37:46 -0700800 * not the profile owner of this user.
Amith Yamasani62ec27e92018-03-11 14:42:06 -0700801 */
802 @SystemApi
Amith Yamasanibc813eb2018-03-20 19:37:46 -0700803 @RequiresPermission(android.Manifest.permission.OBSERVE_APP_USAGE)
Amith Yamasani62ec27e92018-03-11 14:42:06 -0700804 public void unregisterAppUsageObserver(int observerId) {
805 try {
806 mService.unregisterAppUsageObserver(observerId, mContext.getOpPackageName());
807 } catch (RemoteException e) {
Amith Yamasanifd44f272018-05-14 14:47:19 -0700808 throw e.rethrowFromSystemServer();
Amith Yamasani62ec27e92018-03-11 14:42:06 -0700809 }
810 }
811
Michael Wachenschwanz641e3382018-10-23 23:21:48 -0700812 /**
813 * Register a usage session observer that receives a callback on the provided {@code
Michael Wachenschwanz36778522018-11-12 11:06:19 -0800814 * limitReachedCallbackIntent} when the sum of usages of apps and tokens in the {@code
815 * observed} array exceeds the {@code timeLimit} specified within a usage session. The
816 * structure of a token is a String with the reporting packages' name and a token the
817 * reporting app will use, separated by the forward slash character.
818 * Example: com.reporting.package/5OM3*0P4QU3-7OK3N
819 * After the {@code timeLimit} has been reached, the usage session observer will receive a
820 * callback on the provided {@code sessionEndCallbackIntent} when the usage session ends.
821 * Registering another session observer against a {@code sessionObserverId} that has already
822 * been registered will override the previous session observer.
Michael Wachenschwanz641e3382018-10-23 23:21:48 -0700823 *
824 * @param sessionObserverId A unique id associated with the group of apps to be
825 * monitored. There can be multiple groups with common
826 * packages and different time limits.
Michael Wachenschwanz36778522018-11-12 11:06:19 -0800827 * @param observedEntities The list of packages and token to observe for usage time. Cannot be
828 * null and must include at least one package or token.
Michael Wachenschwanz641e3382018-10-23 23:21:48 -0700829 * @param timeLimit The total time the set of apps can be used continuously before the {@code
830 * limitReachedCallbackIntent} is delivered. Must be at least one minute.
Michael Wachenschwanz641e3382018-10-23 23:21:48 -0700831 * @param sessionThresholdTime The time that can take place between usage sessions before the
832 * next session is considered a new session. Must be non-negative.
Michael Wachenschwanz641e3382018-10-23 23:21:48 -0700833 * @param limitReachedCallbackIntent The {@link PendingIntent} that will be dispatched when the
Varun Shah2546cef2019-01-11 15:50:54 -0800834 * usage limit is exceeded by the group of apps. The
835 * delivered Intent will also contain the extras {@link
Michael Wachenschwanz641e3382018-10-23 23:21:48 -0700836 * #EXTRA_OBSERVER_ID}, {@link #EXTRA_TIME_LIMIT} and {@link
837 * #EXTRA_TIME_USED}. Cannot be null.
838 * @param sessionEndCallbackIntent The {@link PendingIntent} that will be dispatched when the
Varun Shah2546cef2019-01-11 15:50:54 -0800839 * session has ended after the usage limit has been exceeded.
840 * The session is considered at its end after the {@code
841 * observed} usage has stopped and an additional {@code
Michael Wachenschwanz641e3382018-10-23 23:21:48 -0700842 * sessionThresholdTime} has passed. The delivered Intent will
843 * also contain the extras {@link #EXTRA_OBSERVER_ID} and {@link
844 * #EXTRA_TIME_USED}. Can be null.
845 * @throws SecurityException if the caller doesn't have the OBSERVE_APP_USAGE permission and
846 * is not the profile owner of this user.
847 * @hide
848 */
849 @SystemApi
850 @RequiresPermission(android.Manifest.permission.OBSERVE_APP_USAGE)
Michael Wachenschwanz36778522018-11-12 11:06:19 -0800851 public void registerUsageSessionObserver(int sessionObserverId,
Michael Wachenschwanzd3cb9982019-03-12 16:05:10 -0700852 @NonNull String[] observedEntities, @NonNull Duration timeLimit,
853 @NonNull Duration sessionThresholdTime,
Michael Wachenschwanz641e3382018-10-23 23:21:48 -0700854 @NonNull PendingIntent limitReachedCallbackIntent,
855 @Nullable PendingIntent sessionEndCallbackIntent) {
856 try {
Michael Wachenschwanz36778522018-11-12 11:06:19 -0800857 mService.registerUsageSessionObserver(sessionObserverId, observedEntities,
Michael Wachenschwanzd3cb9982019-03-12 16:05:10 -0700858 timeLimit.toMillis(), sessionThresholdTime.toMillis(),
Michael Wachenschwanz641e3382018-10-23 23:21:48 -0700859 limitReachedCallbackIntent, sessionEndCallbackIntent,
860 mContext.getOpPackageName());
861 } catch (RemoteException e) {
862 throw e.rethrowFromSystemServer();
863 }
864 }
865
866 /**
867 * Unregister the usage session observer specified by the {@code sessionObserverId}. This will
868 * only apply to any app session observer registered by this application. Unregistering an
869 * observer that was already unregistered or never registered will have no effect.
870 *
871 * @param sessionObserverId The id of the observer that was previously registered.
872 * @throws SecurityException if the caller doesn't have the OBSERVE_APP_USAGE permission and
873 * is not the profile owner of this user.
874 * @hide
875 */
876 @SystemApi
877 @RequiresPermission(android.Manifest.permission.OBSERVE_APP_USAGE)
878 public void unregisterUsageSessionObserver(int sessionObserverId) {
879 try {
880 mService.unregisterUsageSessionObserver(sessionObserverId, mContext.getOpPackageName());
881 } catch (RemoteException e) {
882 throw e.rethrowFromSystemServer();
883 }
884 }
885
Michael Wachenschwanz36778522018-11-12 11:06:19 -0800886 /**
Varun Shah2546cef2019-01-11 15:50:54 -0800887 * Register a usage limit observer that receives a callback on the provided intent when the
888 * sum of usages of apps and tokens in the provided {@code observedEntities} array exceeds the
889 * {@code timeLimit} specified. The structure of a token is a {@link String} with the reporting
890 * package's name and a token that the calling app will use, separated by the forward slash
891 * character. Example: com.reporting.package/5OM3*0P4QU3-7OK3N
892 * <p>
893 * Registering an {@code observerId} that was already registered will override the previous one.
894 * No more than 1000 unique {@code observerId} may be registered by a single uid
895 * at any one time.
Varun Shah54f7f7f2019-02-07 10:21:17 -0800896 * A limit is not cleared when the usage time is exceeded. It needs to be unregistered via
897 * {@link #unregisterAppUsageLimitObserver}.
898 * <p>
899 * Note: usage limits are not persisted in the system and are cleared on reboots. Callers
900 * must reset any limits that they need on reboots.
Varun Shah2546cef2019-01-11 15:50:54 -0800901 * <p>
902 * This method is similar to {@link #registerAppUsageObserver}, but the usage limit set here
903 * will be visible to the launcher so that it can report the limit to the user and how much
904 * of it is remaining.
905 * @see android.content.pm.LauncherApps#getAppUsageLimit
906 *
907 * @param observerId A unique id associated with the group of apps to be monitored. There can
Varun Shah9f58b7c2019-03-01 10:36:21 -0800908 * be multiple groups with common packages and different time limits.
Varun Shah2546cef2019-01-11 15:50:54 -0800909 * @param observedEntities The list of packages and token to observe for usage time. Cannot be
910 * null and must include at least one package or token.
911 * @param timeLimit The total time the set of apps can be in the foreground before the
Varun Shah9f58b7c2019-03-01 10:36:21 -0800912 * {@code callbackIntent} is delivered. Must be at least one minute.
Varun Shah4f76a1e2019-03-12 11:46:10 -0700913 * @param timeUsed The time that has already been used by the set of apps in
914 * {@code observedEntities}. Note: a time used equal to or greater than
915 * {@code timeLimit} can be set to indicate that the user has already exhausted
916 * the limit for a group, in which case, the given {@code callbackIntent} will
917 * be ignored.
Varun Shah54f7f7f2019-02-07 10:21:17 -0800918 * @param callbackIntent The PendingIntent that will be dispatched when the usage limit is
Varun Shah2546cef2019-01-11 15:50:54 -0800919 * exceeded by the group of apps. The delivered Intent will also contain
920 * the extras {@link #EXTRA_OBSERVER_ID}, {@link #EXTRA_TIME_LIMIT} and
Varun Shah54f7f7f2019-02-07 10:21:17 -0800921 * {@link #EXTRA_TIME_USED}. Cannot be {@code null} unless the observer is
Varun Shah4f76a1e2019-03-12 11:46:10 -0700922 * being registered with a {@code timeUsed} equal to or greater than
923 * {@code timeLimit}.
Varun Shahb472b8f2019-09-23 23:01:06 -0700924 * @throws SecurityException if the caller is neither the active supervision app nor does it
925 * have both SUSPEND_APPS and OBSERVE_APP_USAGE permissions.
Varun Shah2546cef2019-01-11 15:50:54 -0800926 * @hide
927 */
928 @SystemApi
929 @RequiresPermission(allOf = {
930 android.Manifest.permission.SUSPEND_APPS,
931 android.Manifest.permission.OBSERVE_APP_USAGE})
932 public void registerAppUsageLimitObserver(int observerId, @NonNull String[] observedEntities,
Varun Shah4f76a1e2019-03-12 11:46:10 -0700933 @NonNull Duration timeLimit, @NonNull Duration timeUsed,
Varun Shah9f58b7c2019-03-01 10:36:21 -0800934 @Nullable PendingIntent callbackIntent) {
Varun Shah2546cef2019-01-11 15:50:54 -0800935 try {
936 mService.registerAppUsageLimitObserver(observerId, observedEntities,
Varun Shah4f76a1e2019-03-12 11:46:10 -0700937 timeLimit.toMillis(), timeUsed.toMillis(), callbackIntent,
Varun Shah9f58b7c2019-03-01 10:36:21 -0800938 mContext.getOpPackageName());
Varun Shah2546cef2019-01-11 15:50:54 -0800939 } catch (RemoteException e) {
940 throw e.rethrowFromSystemServer();
941 }
942 }
943
944 /**
945 * Unregister the app usage limit observer specified by the {@code observerId}.
946 * This will only apply to any observer registered by this application. Unregistering
947 * an observer that was already unregistered or never registered will have no effect.
948 *
949 * @param observerId The id of the observer that was previously registered.
Varun Shahb472b8f2019-09-23 23:01:06 -0700950 * @throws SecurityException if the caller is neither the active supervision app nor does it
951 * have both SUSPEND_APPS and OBSERVE_APP_USAGE permissions.
Varun Shah2546cef2019-01-11 15:50:54 -0800952 * @hide
953 */
954 @SystemApi
955 @RequiresPermission(allOf = {
956 android.Manifest.permission.SUSPEND_APPS,
957 android.Manifest.permission.OBSERVE_APP_USAGE})
958 public void unregisterAppUsageLimitObserver(int observerId) {
959 try {
960 mService.unregisterAppUsageLimitObserver(observerId, mContext.getOpPackageName());
961 } catch (RemoteException e) {
962 throw e.rethrowFromSystemServer();
963 }
964 }
965
966 /**
Michael Wachenschwanz36778522018-11-12 11:06:19 -0800967 * Report usage associated with a particular {@code token} has started. Tokens are app defined
968 * strings used to represent usage of in-app features. Apps with the {@link
969 * android.Manifest.permission#OBSERVE_APP_USAGE} permission can register time limit observers
970 * to monitor the usage of a token. In app usage can only associated with an {@code activity}
971 * and usage will be considered stopped if the activity stops or crashes.
972 * @see #registerAppUsageObserver
973 * @see #registerUsageSessionObserver
Varun Shah2546cef2019-01-11 15:50:54 -0800974 * @see #registerAppUsageLimitObserver
Michael Wachenschwanz36778522018-11-12 11:06:19 -0800975 *
976 * @param activity The activity {@code token} is associated with.
977 * @param token The token to report usage against.
978 * @hide
979 */
980 @SystemApi
981 public void reportUsageStart(@NonNull Activity activity, @NonNull String token) {
982 try {
983 mService.reportUsageStart(activity.getActivityToken(), token,
984 mContext.getOpPackageName());
985 } catch (RemoteException e) {
986 throw e.rethrowFromSystemServer();
987 }
988 }
989
990 /**
991 * Report usage associated with a particular {@code token} had started some amount of time in
992 * the past. Tokens are app defined strings used to represent usage of in-app features. Apps
993 * with the {@link android.Manifest.permission#OBSERVE_APP_USAGE} permission can register time
994 * limit observers to monitor the usage of a token. In app usage can only associated with an
995 * {@code activity} and usage will be considered stopped if the activity stops or crashes.
996 * @see #registerAppUsageObserver
997 * @see #registerUsageSessionObserver
Varun Shah2546cef2019-01-11 15:50:54 -0800998 * @see #registerAppUsageLimitObserver
Michael Wachenschwanz36778522018-11-12 11:06:19 -0800999 *
1000 * @param activity The activity {@code token} is associated with.
1001 * @param token The token to report usage against.
1002 * @param timeAgoMs How long ago the start of usage took place
1003 * @hide
1004 */
1005 @SystemApi
1006 public void reportUsageStart(@NonNull Activity activity, @NonNull String token,
1007 long timeAgoMs) {
1008 try {
1009 mService.reportPastUsageStart(activity.getActivityToken(), token, timeAgoMs,
1010 mContext.getOpPackageName());
1011 } catch (RemoteException e) {
1012 throw e.rethrowFromSystemServer();
1013 }
1014 }
1015
1016 /**
1017 * Report the usage associated with a particular {@code token} has stopped.
1018 *
1019 * @param activity The activity {@code token} is associated with.
1020 * @param token The token to report usage against.
1021 * @hide
1022 */
1023 @SystemApi
1024 public void reportUsageStop(@NonNull Activity activity, @NonNull String token) {
1025 try {
1026 mService.reportUsageStop(activity.getActivityToken(), token,
1027 mContext.getOpPackageName());
1028 } catch (RemoteException e) {
1029 throw e.rethrowFromSystemServer();
1030 }
1031 }
1032
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08001033 /**
1034 * Get what App Usage Observers will consider the source of usage for an activity. Usage Source
1035 * is decided at boot and will not change until next boot.
1036 * @see #USAGE_SOURCE_TASK_ROOT_ACTIVITY
1037 * @see #USAGE_SOURCE_CURRENT_ACTIVITY
1038 *
1039 * @throws SecurityException if the caller doesn't have the OBSERVE_APP_USAGE permission and
1040 * is not the profile owner of this user.
1041 * @hide
1042 */
1043 @SystemApi
1044 public @UsageSource int getUsageSource() {
1045 try {
1046 return mService.getUsageSource();
1047 } catch (RemoteException e) {
1048 throw e.rethrowFromSystemServer();
1049 }
1050 }
1051
1052 /**
1053 * Force the Usage Source be reread from global settings.
1054 * @hide
1055 */
1056 @TestApi
1057 public void forceUsageSourceSettingRead() {
1058 try {
1059 mService.forceUsageSourceSettingRead();
1060 } catch (RemoteException e) {
1061 throw e.rethrowFromSystemServer();
1062 }
1063 }
1064
Amith Yamasani119be9a2018-02-18 22:23:00 -08001065 /** @hide */
1066 public static String reasonToString(int standbyReason) {
Kweku Adamsaa461942020-03-16 11:59:05 -07001067 final int subReason = standbyReason & REASON_SUB_MASK;
Amith Yamasani119be9a2018-02-18 22:23:00 -08001068 StringBuilder sb = new StringBuilder();
1069 switch (standbyReason & REASON_MAIN_MASK) {
1070 case REASON_MAIN_DEFAULT:
1071 sb.append("d");
1072 break;
Kweku Adamsc182d5e2020-01-08 18:37:26 -08001073 case REASON_MAIN_FORCED_BY_SYSTEM:
1074 sb.append("s");
Kweku Adamsaa461942020-03-16 11:59:05 -07001075 if (subReason > 0) {
1076 sb.append("-").append(Integer.toBinaryString(subReason));
Kweku Adamsc6a9b342020-01-08 18:37:26 -08001077 }
Kweku Adamsc182d5e2020-01-08 18:37:26 -08001078 break;
1079 case REASON_MAIN_FORCED_BY_USER:
Amith Yamasani119be9a2018-02-18 22:23:00 -08001080 sb.append("f");
1081 break;
1082 case REASON_MAIN_PREDICTED:
1083 sb.append("p");
Kweku Adamsaa461942020-03-16 11:59:05 -07001084 switch (subReason) {
Amith Yamasani3154dcf2018-03-27 18:24:04 -07001085 case REASON_SUB_PREDICTED_RESTORED:
1086 sb.append("-r");
1087 break;
1088 }
Amith Yamasani119be9a2018-02-18 22:23:00 -08001089 break;
1090 case REASON_MAIN_TIMEOUT:
1091 sb.append("t");
1092 break;
1093 case REASON_MAIN_USAGE:
Amith Yamasani3154dcf2018-03-27 18:24:04 -07001094 sb.append("u");
Kweku Adamsaa461942020-03-16 11:59:05 -07001095 switch (subReason) {
Amith Yamasani119be9a2018-02-18 22:23:00 -08001096 case REASON_SUB_USAGE_SYSTEM_INTERACTION:
Amith Yamasani3154dcf2018-03-27 18:24:04 -07001097 sb.append("-si");
Amith Yamasani119be9a2018-02-18 22:23:00 -08001098 break;
1099 case REASON_SUB_USAGE_NOTIFICATION_SEEN:
Amith Yamasani3154dcf2018-03-27 18:24:04 -07001100 sb.append("-ns");
Amith Yamasani119be9a2018-02-18 22:23:00 -08001101 break;
1102 case REASON_SUB_USAGE_USER_INTERACTION:
Amith Yamasani3154dcf2018-03-27 18:24:04 -07001103 sb.append("-ui");
Amith Yamasani119be9a2018-02-18 22:23:00 -08001104 break;
1105 case REASON_SUB_USAGE_MOVE_TO_FOREGROUND:
Amith Yamasani3154dcf2018-03-27 18:24:04 -07001106 sb.append("-mf");
Amith Yamasani119be9a2018-02-18 22:23:00 -08001107 break;
1108 case REASON_SUB_USAGE_MOVE_TO_BACKGROUND:
Amith Yamasani3154dcf2018-03-27 18:24:04 -07001109 sb.append("-mb");
Amith Yamasani119be9a2018-02-18 22:23:00 -08001110 break;
1111 case REASON_SUB_USAGE_SYSTEM_UPDATE:
Amith Yamasani3154dcf2018-03-27 18:24:04 -07001112 sb.append("-su");
Amith Yamasani119be9a2018-02-18 22:23:00 -08001113 break;
1114 case REASON_SUB_USAGE_ACTIVE_TIMEOUT:
Amith Yamasani3154dcf2018-03-27 18:24:04 -07001115 sb.append("-at");
Amith Yamasani119be9a2018-02-18 22:23:00 -08001116 break;
1117 case REASON_SUB_USAGE_SYNC_ADAPTER:
Amith Yamasani3154dcf2018-03-27 18:24:04 -07001118 sb.append("-sa");
Amith Yamasani119be9a2018-02-18 22:23:00 -08001119 break;
Amith Yamasani80c4be82018-03-26 10:54:04 -07001120 case REASON_SUB_USAGE_SLICE_PINNED:
Makoto Onukid5f25d22018-05-22 16:02:17 -07001121 sb.append("-lp");
Amith Yamasani80c4be82018-03-26 10:54:04 -07001122 break;
1123 case REASON_SUB_USAGE_SLICE_PINNED_PRIV:
Makoto Onukid5f25d22018-05-22 16:02:17 -07001124 sb.append("-lv");
1125 break;
1126 case REASON_SUB_USAGE_EXEMPTED_SYNC_SCHEDULED_NON_DOZE:
1127 sb.append("-en");
1128 break;
1129 case REASON_SUB_USAGE_EXEMPTED_SYNC_SCHEDULED_DOZE:
1130 sb.append("-ed");
Amith Yamasani80c4be82018-03-26 10:54:04 -07001131 break;
Makoto Onuki75ad2492018-03-28 14:42:42 -07001132 case REASON_SUB_USAGE_EXEMPTED_SYNC_START:
Makoto Onukid5f25d22018-05-22 16:02:17 -07001133 sb.append("-es");
Makoto Onuki75ad2492018-03-28 14:42:42 -07001134 break;
Michael Wachenschwanzc3295202019-02-20 17:19:52 -08001135 case REASON_SUB_USAGE_UNEXEMPTED_SYNC_SCHEDULED:
1136 sb.append("-uss");
1137 break;
Michael Wachenschwanz6ced0ee2019-04-15 16:43:28 -07001138 case REASON_SUB_USAGE_FOREGROUND_SERVICE_START:
1139 sb.append("-fss");
1140 break;
Amith Yamasani119be9a2018-02-18 22:23:00 -08001141 }
1142 break;
1143 }
1144 return sb.toString();
1145 }
1146
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08001147 /** @hide */
1148 public static String usageSourceToString(int usageSource) {
1149 switch (usageSource) {
1150 case USAGE_SOURCE_TASK_ROOT_ACTIVITY:
1151 return "TASK_ROOT_ACTIVITY";
1152 case USAGE_SOURCE_CURRENT_ACTIVITY:
1153 return "CURRENT_ACTIVITY";
1154 default:
1155 StringBuilder sb = new StringBuilder();
1156 sb.append("UNKNOWN(");
1157 sb.append(usageSource);
1158 sb.append(")");
1159 return sb.toString();
1160 }
1161 }
1162
Amith Yamasanie8789312017-12-10 14:34:26 -08001163 /**
1164 * {@hide}
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001165 * Temporarily whitelist the specified app for a short duration. This is to allow an app
1166 * receiving a high priority message to be able to access the network and acquire wakelocks
1167 * even if the device is in power-save mode or the app is currently considered inactive.
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001168 * @param packageName The package name of the app to whitelist.
1169 * @param duration Duration to whitelist the app for, in milliseconds. It is recommended that
1170 * this be limited to 10s of seconds. Requested duration will be clamped to a few minutes.
1171 * @param user The user for whom the package should be whitelisted. Passing in a user that is
1172 * not the same as the caller's process will require the INTERACT_ACROSS_USERS permission.
1173 * @see #isAppInactive(String)
Kweku Adams835283f2019-11-20 14:41:22 -08001174 *
1175 * @deprecated Use
1176 * {@link android.os.PowerWhitelistManager#whitelistAppTemporarily(String, long)} instead.
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001177 */
1178 @SystemApi
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -06001179 @RequiresPermission(android.Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST)
Kweku Adams835283f2019-11-20 14:41:22 -08001180 @Deprecated
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001181 public void whitelistAppTemporarily(String packageName, long duration, UserHandle user) {
Kweku Adams835283f2019-11-20 14:41:22 -08001182 mContext.getSystemService(PowerWhitelistManager.class)
1183 .whitelistAppTemporarily(packageName, duration);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001184 }
Amith Yamasani4ec63682016-02-19 12:55:27 -08001185
1186 /**
1187 * Inform usage stats that the carrier privileged apps access rules have changed.
yinxu0016eef2019-12-09 16:51:53 -08001188 * <p> The caller must have {@link android.Manifest.permission#BIND_CARRIER_SERVICES} </p>
Amith Yamasani4ec63682016-02-19 12:55:27 -08001189 * @hide
1190 */
yinxu0016eef2019-12-09 16:51:53 -08001191 @SystemApi
1192 @RequiresPermission(android.Manifest.permission.BIND_CARRIER_SERVICES)
Amith Yamasani4ec63682016-02-19 12:55:27 -08001193 public void onCarrierPrivilegedAppsChanged() {
1194 try {
1195 mService.onCarrierPrivilegedAppsChanged();
1196 } catch (RemoteException re) {
Amith Yamasanifd44f272018-05-14 14:47:19 -07001197 throw re.rethrowFromSystemServer();
Amith Yamasani4ec63682016-02-19 12:55:27 -08001198 }
1199 }
Kang Li53b43142016-11-14 14:38:25 -08001200
1201 /**
1202 * Reports a Chooser action to the UsageStatsManager.
1203 *
1204 * @param packageName The package name of the app that is selected.
1205 * @param userId The user id of who makes the selection.
1206 * @param contentType The type of the content, e.g., Image, Video, App.
1207 * @param annotations The annotations of the content, e.g., Game, Selfie.
1208 * @param action The action type of Intent that invokes ChooserActivity.
1209 * {@link UsageEvents}
1210 * @hide
1211 */
1212 public void reportChooserSelection(String packageName, int userId, String contentType,
1213 String[] annotations, String action) {
1214 try {
1215 mService.reportChooserSelection(packageName, userId, contentType, annotations, action);
1216 } catch (RemoteException re) {
1217 }
1218 }
Adam Lesinski0debc9a2014-07-16 19:09:13 -07001219}