blob: 2ce6a86753a6e449c54e877d7aa3ac94eb7059c2 [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 /**
Kweku Adams917f8a42020-02-26 17:18:03 -0800207 * The reason for using the default main reason is unknown or undefined.
208 * @hide
209 */
210 public static final int REASON_SUB_DEFAULT_UNDEFINED = 0x0000;
211 /**
212 * The app was updated.
213 * @hide
214 */
215 public static final int REASON_SUB_DEFAULT_APP_UPDATE = 0x0001;
216 /**
Kweku Adamsd18f0732019-12-03 13:39:40 -0800217 * The app was interacted with in some way by the system.
218 * @hide
219 */
Amith Yamasani119be9a2018-02-18 22:23:00 -0800220 public static final int REASON_SUB_USAGE_SYSTEM_INTERACTION = 0x0001;
Kweku Adamsd18f0732019-12-03 13:39:40 -0800221 /**
222 * A notification was viewed by the user. This does not mean the user interacted with the
223 * notification.
224 * @hide
225 */
Amith Yamasani119be9a2018-02-18 22:23:00 -0800226 public static final int REASON_SUB_USAGE_NOTIFICATION_SEEN = 0x0002;
Kweku Adamsd18f0732019-12-03 13:39:40 -0800227 /**
228 * The app was interacted with in some way by the user. This includes interacting with
229 * notification.
230 * @hide
231 */
Amith Yamasani119be9a2018-02-18 22:23:00 -0800232 public static final int REASON_SUB_USAGE_USER_INTERACTION = 0x0003;
Kweku Adamsd18f0732019-12-03 13:39:40 -0800233 /**
234 * An {@link android.app.Activity} moved to the foreground.
235 * @hide
236 */
Amith Yamasani119be9a2018-02-18 22:23:00 -0800237 public static final int REASON_SUB_USAGE_MOVE_TO_FOREGROUND = 0x0004;
Kweku Adamsd18f0732019-12-03 13:39:40 -0800238 /**
239 * An {@link android.app.Activity} moved to the background.
240 * @hide
241 */
Amith Yamasani119be9a2018-02-18 22:23:00 -0800242 public static final int REASON_SUB_USAGE_MOVE_TO_BACKGROUND = 0x0005;
Kweku Adamsd18f0732019-12-03 13:39:40 -0800243 /**
244 * There was a system update.
245 * @hide
246 */
Amith Yamasani119be9a2018-02-18 22:23:00 -0800247 public static final int REASON_SUB_USAGE_SYSTEM_UPDATE = 0x0006;
Kweku Adamsd18f0732019-12-03 13:39:40 -0800248 /**
249 * An app is in an elevated bucket because of an active timeout preventing it from being placed
250 * in a lower bucket.
251 * @hide
252 */
Amith Yamasani119be9a2018-02-18 22:23:00 -0800253 public static final int REASON_SUB_USAGE_ACTIVE_TIMEOUT = 0x0007;
Kweku Adamsd18f0732019-12-03 13:39:40 -0800254 /**
255 * This system package's sync adapter has been used for another package's content provider.
256 * @hide
257 */
Amith Yamasani119be9a2018-02-18 22:23:00 -0800258 public static final int REASON_SUB_USAGE_SYNC_ADAPTER = 0x0008;
Kweku Adamsd18f0732019-12-03 13:39:40 -0800259 /**
260 * A slice was pinned by an app.
261 * @hide
262 */
Amith Yamasani80c4be82018-03-26 10:54:04 -0700263 public static final int REASON_SUB_USAGE_SLICE_PINNED = 0x0009;
Kweku Adamsd18f0732019-12-03 13:39:40 -0800264 /** /**
265 * A slice was pinned by the default launcher or the default assistant.
266 * @hide
267 */
Amith Yamasani80c4be82018-03-26 10:54:04 -0700268 public static final int REASON_SUB_USAGE_SLICE_PINNED_PRIV = 0x000A;
Kweku Adamsd18f0732019-12-03 13:39:40 -0800269 /**
270 * A sync operation that is exempt from app standby was scheduled when the device wasn't Dozing.
271 * @hide
272 */
Makoto Onukid5f25d22018-05-22 16:02:17 -0700273 public static final int REASON_SUB_USAGE_EXEMPTED_SYNC_SCHEDULED_NON_DOZE = 0x000B;
Kweku Adamsd18f0732019-12-03 13:39:40 -0800274 /**
275 * A sync operation that is exempt from app standby was scheduled while the device was Dozing.
276 * @hide
277 */
Makoto Onukid5f25d22018-05-22 16:02:17 -0700278 public static final int REASON_SUB_USAGE_EXEMPTED_SYNC_SCHEDULED_DOZE = 0x000C;
Kweku Adamsd18f0732019-12-03 13:39:40 -0800279 /**
280 * A sync operation that is exempt from app standby started.
281 * @hide
282 */
Makoto Onukid5f25d22018-05-22 16:02:17 -0700283 public static final int REASON_SUB_USAGE_EXEMPTED_SYNC_START = 0x000D;
Kweku Adamsd18f0732019-12-03 13:39:40 -0800284 /**
285 * A sync operation that is not exempt from app standby was scheduled.
286 * @hide
287 */
Michael Wachenschwanzc3295202019-02-20 17:19:52 -0800288 public static final int REASON_SUB_USAGE_UNEXEMPTED_SYNC_SCHEDULED = 0x000E;
Kweku Adamsd18f0732019-12-03 13:39:40 -0800289 /**
290 * A foreground service started.
291 * @hide
292 */
Michael Wachenschwanz6ced0ee2019-04-15 16:43:28 -0700293 public static final int REASON_SUB_USAGE_FOREGROUND_SERVICE_START = 0x000F;
Kweku Adamsd18f0732019-12-03 13:39:40 -0800294 /**
295 * The predicted bucket was restored after the app's temporary elevation to the ACTIVE bucket
296 * ended.
297 * @hide
298 */
Amith Yamasani3154dcf2018-03-27 18:24:04 -0700299 public static final int REASON_SUB_PREDICTED_RESTORED = 0x0001;
Kweku Adamsc6a9b342020-01-08 18:37:26 -0800300 /**
Kweku Adamsaa461942020-03-16 11:59:05 -0700301 * The reason the system forced the app into the bucket is unknown or undefined.
Kweku Adamsc6a9b342020-01-08 18:37:26 -0800302 * @hide
303 */
Kweku Adamsaa461942020-03-16 11:59:05 -0700304 public static final int REASON_SUB_FORCED_SYSTEM_FLAG_UNDEFINED = 0;
Kweku Adamsc6a9b342020-01-08 18:37:26 -0800305 /**
306 * The app was unnecessarily using system resources (battery, memory, etc) in the background.
307 * @hide
308 */
Kweku Adamsaa461942020-03-16 11:59:05 -0700309 public static final int REASON_SUB_FORCED_SYSTEM_FLAG_BACKGROUND_RESOURCE_USAGE = 1 << 0;
Kweku Adamsc6a9b342020-01-08 18:37:26 -0800310 /**
311 * The app was deemed to be intentionally abusive.
312 * @hide
313 */
Kweku Adamsaa461942020-03-16 11:59:05 -0700314 public static final int REASON_SUB_FORCED_SYSTEM_FLAG_ABUSE = 1 << 1;
Kweku Adamsc6a9b342020-01-08 18:37:26 -0800315 /**
316 * The app was displaying buggy behavior.
317 * @hide
318 */
Kweku Adamsaa461942020-03-16 11:59:05 -0700319 public static final int REASON_SUB_FORCED_SYSTEM_FLAG_BUGGY = 1 << 2;
Amith Yamasani3154dcf2018-03-27 18:24:04 -0700320
Makoto Onuki75ad2492018-03-28 14:42:42 -0700321
Amith Yamasani3154dcf2018-03-27 18:24:04 -0700322 /** @hide */
Jeff Sharkeyce8db992017-12-13 20:05:05 -0700323 @IntDef(flag = false, prefix = { "STANDBY_BUCKET_" }, value = {
Amith Yamasaniafbccb72017-11-27 10:44:24 -0800324 STANDBY_BUCKET_EXEMPTED,
325 STANDBY_BUCKET_ACTIVE,
326 STANDBY_BUCKET_WORKING_SET,
327 STANDBY_BUCKET_FREQUENT,
328 STANDBY_BUCKET_RARE,
Kweku Adamsc6a9b342020-01-08 18:37:26 -0800329 STANDBY_BUCKET_RESTRICTED,
Amith Yamasaniafbccb72017-11-27 10:44:24 -0800330 STANDBY_BUCKET_NEVER,
331 })
332 @Retention(RetentionPolicy.SOURCE)
333 public @interface StandbyBuckets {}
334
Kweku Adamsaa461942020-03-16 11:59:05 -0700335 /** @hide */
336 @IntDef(flag = true, prefix = {"REASON_SUB_FORCED_SYSTEM_FLAG_FLAG_"}, value = {
337 REASON_SUB_FORCED_SYSTEM_FLAG_UNDEFINED,
338 REASON_SUB_FORCED_SYSTEM_FLAG_BACKGROUND_RESOURCE_USAGE,
339 REASON_SUB_FORCED_SYSTEM_FLAG_ABUSE,
340 REASON_SUB_FORCED_SYSTEM_FLAG_BUGGY,
341 })
342 @Retention(RetentionPolicy.SOURCE)
343 public @interface SystemForcedReasons {
344 }
345
Amith Yamasani62ec27e92018-03-11 14:42:06 -0700346 /**
347 * Observer id of the registered observer for the group of packages that reached the usage
348 * time limit. Included as an extra in the PendingIntent that was registered.
349 * @hide
350 */
351 @SystemApi
352 public static final String EXTRA_OBSERVER_ID = "android.app.usage.extra.OBSERVER_ID";
353
354 /**
355 * Original time limit in milliseconds specified by the registered observer for the group of
356 * packages that reached the usage time limit. Included as an extra in the PendingIntent that
357 * was registered.
358 * @hide
359 */
360 @SystemApi
361 public static final String EXTRA_TIME_LIMIT = "android.app.usage.extra.TIME_LIMIT";
362
363 /**
364 * Actual usage time in milliseconds for the group of packages that reached the specified time
365 * limit. Included as an extra in the PendingIntent that was registered.
366 * @hide
367 */
368 @SystemApi
369 public static final String EXTRA_TIME_USED = "android.app.usage.extra.TIME_USED";
370
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -0800371
372 /**
373 * App usage observers will consider the task root package the source of usage.
374 * @hide
375 */
376 @SystemApi
377 public static final int USAGE_SOURCE_TASK_ROOT_ACTIVITY = 1;
378
379 /**
380 * App usage observers will consider the visible activity's package the source of usage.
381 * @hide
382 */
383 @SystemApi
384 public static final int USAGE_SOURCE_CURRENT_ACTIVITY = 2;
385
386 /** @hide */
387 @IntDef(prefix = { "USAGE_SOURCE_" }, value = {
388 USAGE_SOURCE_TASK_ROOT_ACTIVITY,
389 USAGE_SOURCE_CURRENT_ACTIVITY,
390 })
391 @Retention(RetentionPolicy.SOURCE)
392 public @interface UsageSource {}
393
Mathew Inwood31755f92018-12-20 13:53:36 +0000394 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Adam Lesinski35168002014-07-21 15:25:30 -0700395 private static final UsageEvents sEmptyResults = new UsageEvents();
Adam Lesinski0debc9a2014-07-16 19:09:13 -0700396
Mathew Inwood8c854f82018-09-14 12:35:36 +0100397 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Adam Lesinski0debc9a2014-07-16 19:09:13 -0700398 private final Context mContext;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100399 @UnsupportedAppUsage
Adam Lesinski0debc9a2014-07-16 19:09:13 -0700400 private final IUsageStatsManager mService;
401
402 /**
403 * {@hide}
404 */
405 public UsageStatsManager(Context context, IUsageStatsManager service) {
406 mContext = context;
407 mService = service;
408 }
409
Adam Lesinski35168002014-07-21 15:25:30 -0700410 /**
411 * Gets application usage stats for the given time range, aggregated by the specified interval.
Adam Lesinski35168002014-07-21 15:25:30 -0700412 *
Michael Wachenschwanzd1e659b2019-04-05 11:55:02 -0700413 * <p>
414 * The returned list will contain one or more {@link UsageStats} objects for each package, with
415 * usage data that covers at least the given time range.
416 * Note: The begin and end times of the time range may be expanded to the nearest whole interval
417 * period.
418 * </p>
Adam Lesinski35168002014-07-21 15:25:30 -0700419 *
Suprabh Shukla217ccda2018-02-23 17:57:12 -0800420 * <p> The caller must have {@link android.Manifest.permission#PACKAGE_USAGE_STATS} </p>
Varun Shah3a315202019-07-24 16:33:42 -0700421 * <em>Note: Starting from {@link android.os.Build.VERSION_CODES#R Android R}, if the user's
422 * device is not in an unlocked state (as defined by {@link UserManager#isUserUnlocked()}),
423 * then {@code null} will be returned.</em>
Suprabh Shukla217ccda2018-02-23 17:57:12 -0800424 *
Adam Lesinski35168002014-07-21 15:25:30 -0700425 * @param intervalType The time interval by which the stats are aggregated.
426 * @param beginTime The inclusive beginning of the range of stats to include in the results.
Michael Wachenschwanz17415c22019-04-01 15:40:49 -0700427 * Defined in terms of "Unix time", see
428 * {@link java.lang.System#currentTimeMillis}.
429 * @param endTime The exclusive end of the range of stats to include in the results. Defined
430 * in terms of "Unix time", see {@link java.lang.System#currentTimeMillis}.
Esteban Talaverafa962312017-10-09 14:58:28 +0100431 * @return A list of {@link UsageStats}
Adam Lesinski35168002014-07-21 15:25:30 -0700432 *
433 * @see #INTERVAL_DAILY
434 * @see #INTERVAL_WEEKLY
435 * @see #INTERVAL_MONTHLY
436 * @see #INTERVAL_YEARLY
437 * @see #INTERVAL_BEST
438 */
Adam Lesinski35168002014-07-21 15:25:30 -0700439 public List<UsageStats> queryUsageStats(int intervalType, long beginTime, long endTime) {
Adam Lesinski0debc9a2014-07-16 19:09:13 -0700440 try {
Adam Lesinski7f61e962014-09-02 16:43:52 -0700441 @SuppressWarnings("unchecked")
Adam Lesinski35168002014-07-21 15:25:30 -0700442 ParceledListSlice<UsageStats> slice = mService.queryUsageStats(intervalType, beginTime,
443 endTime, mContext.getOpPackageName());
444 if (slice != null) {
445 return slice.getList();
Adam Lesinski0debc9a2014-07-16 19:09:13 -0700446 }
Adam Lesinski35168002014-07-21 15:25:30 -0700447 } catch (RemoteException e) {
Esteban Talaverafa962312017-10-09 14:58:28 +0100448 // fallthrough and return the empty list.
Adam Lesinski35168002014-07-21 15:25:30 -0700449 }
Adam Lesinski7f61e962014-09-02 16:43:52 -0700450 return Collections.emptyList();
451 }
452
453 /**
454 * Gets the hardware configurations the device was in for the given time range, aggregated by
455 * the specified interval. The results are ordered as in
456 * {@link #queryUsageStats(int, long, long)}.
Suprabh Shukla217ccda2018-02-23 17:57:12 -0800457 * <p> The caller must have {@link android.Manifest.permission#PACKAGE_USAGE_STATS} </p>
Varun Shah3a315202019-07-24 16:33:42 -0700458 * <em>Note: Starting from {@link android.os.Build.VERSION_CODES#R Android R}, if the user's
459 * device is not in an unlocked state (as defined by {@link UserManager#isUserUnlocked()}),
460 * then {@code null} will be returned.</em>
Adam Lesinski7f61e962014-09-02 16:43:52 -0700461 *
462 * @param intervalType The time interval by which the stats are aggregated.
463 * @param beginTime The inclusive beginning of the range of stats to include in the results.
Michael Wachenschwanz17415c22019-04-01 15:40:49 -0700464 * Defined in terms of "Unix time", see
465 * {@link java.lang.System#currentTimeMillis}.
466 * @param endTime The exclusive end of the range of stats to include in the results. Defined
467 * in terms of "Unix time", see {@link java.lang.System#currentTimeMillis}.
Esteban Talaverafa962312017-10-09 14:58:28 +0100468 * @return A list of {@link ConfigurationStats}
Adam Lesinski7f61e962014-09-02 16:43:52 -0700469 */
470 public List<ConfigurationStats> queryConfigurations(int intervalType, long beginTime,
471 long endTime) {
472 try {
473 @SuppressWarnings("unchecked")
474 ParceledListSlice<ConfigurationStats> slice = mService.queryConfigurationStats(
475 intervalType, beginTime, endTime, mContext.getOpPackageName());
476 if (slice != null) {
477 return slice.getList();
478 }
479 } catch (RemoteException e) {
480 // fallthrough and return the empty list.
481 }
482 return Collections.emptyList();
Adam Lesinski35168002014-07-21 15:25:30 -0700483 }
Adam Lesinski0debc9a2014-07-16 19:09:13 -0700484
Adam Lesinski35168002014-07-21 15:25:30 -0700485 /**
Dianne Hackbornced54392018-02-26 13:07:42 -0800486 * Gets aggregated event stats for the given time range, aggregated by the specified interval.
487 * <p>The returned list will contain a {@link EventStats} object for each event type that
488 * is being aggregated and has data for an interval that is a subset of the time range given.
489 *
490 * <p>The current event types that will be aggregated here are:</p>
491 * <ul>
492 * <li>{@link UsageEvents.Event#SCREEN_INTERACTIVE}</li>
493 * <li>{@link UsageEvents.Event#SCREEN_NON_INTERACTIVE}</li>
Dianne Hackborn3378aa92018-03-30 17:43:49 -0700494 * <li>{@link UsageEvents.Event#KEYGUARD_SHOWN}</li>
495 * <li>{@link UsageEvents.Event#KEYGUARD_HIDDEN}</li>
Dianne Hackbornced54392018-02-26 13:07:42 -0800496 * </ul>
497 *
498 * <p> The caller must have {@link android.Manifest.permission#PACKAGE_USAGE_STATS} </p>
Varun Shah3a315202019-07-24 16:33:42 -0700499 * <em>Note: Starting from {@link android.os.Build.VERSION_CODES#R Android R}, if the user's
500 * device is not in an unlocked state (as defined by {@link UserManager#isUserUnlocked()}),
501 * then {@code null} will be returned.</em>
Dianne Hackbornced54392018-02-26 13:07:42 -0800502 *
503 * @param intervalType The time interval by which the stats are aggregated.
504 * @param beginTime The inclusive beginning of the range of stats to include in the results.
Michael Wachenschwanz17415c22019-04-01 15:40:49 -0700505 * Defined in terms of "Unix time", see
506 * {@link java.lang.System#currentTimeMillis}.
507 * @param endTime The exclusive end of the range of stats to include in the results. Defined
508 * in terms of "Unix time", see {@link java.lang.System#currentTimeMillis}.
Dianne Hackbornced54392018-02-26 13:07:42 -0800509 * @return A list of {@link EventStats}
510 *
511 * @see #INTERVAL_DAILY
512 * @see #INTERVAL_WEEKLY
513 * @see #INTERVAL_MONTHLY
514 * @see #INTERVAL_YEARLY
515 * @see #INTERVAL_BEST
516 */
517 public List<EventStats> queryEventStats(int intervalType, long beginTime, long endTime) {
518 try {
519 @SuppressWarnings("unchecked")
520 ParceledListSlice<EventStats> slice = mService.queryEventStats(intervalType, beginTime,
521 endTime, mContext.getOpPackageName());
522 if (slice != null) {
523 return slice.getList();
524 }
525 } catch (RemoteException e) {
526 // fallthrough and return the empty list.
527 }
528 return Collections.emptyList();
529 }
530
531 /**
Adam Lesinski35168002014-07-21 15:25:30 -0700532 * Query for events in the given time range. Events are only kept by the system for a few
533 * days.
Suprabh Shukla217ccda2018-02-23 17:57:12 -0800534 * <p> The caller must have {@link android.Manifest.permission#PACKAGE_USAGE_STATS} </p>
Varun Shah3a315202019-07-24 16:33:42 -0700535 * <em>Note: Starting from {@link android.os.Build.VERSION_CODES#R Android R}, if the user's
536 * device is not in an unlocked state (as defined by {@link UserManager#isUserUnlocked()}),
537 * then {@code null} will be returned.</em>
Adam Lesinski35168002014-07-21 15:25:30 -0700538 *
539 * @param beginTime The inclusive beginning of the range of events to include in the results.
Michael Wachenschwanz17415c22019-04-01 15:40:49 -0700540 * Defined in terms of "Unix time", see
541 * {@link java.lang.System#currentTimeMillis}.
542 * @param endTime The exclusive end of the range of events to include in the results. Defined
543 * in terms of "Unix time", see {@link java.lang.System#currentTimeMillis}.
Adam Lesinski35168002014-07-21 15:25:30 -0700544 * @return A {@link UsageEvents}.
545 */
Adam Lesinski35168002014-07-21 15:25:30 -0700546 public UsageEvents queryEvents(long beginTime, long endTime) {
547 try {
548 UsageEvents iter = mService.queryEvents(beginTime, endTime,
549 mContext.getOpPackageName());
550 if (iter != null) {
551 return iter;
552 }
553 } catch (RemoteException e) {
Esteban Talaverafa962312017-10-09 14:58:28 +0100554 // fallthrough and return empty result.
Adam Lesinski35168002014-07-21 15:25:30 -0700555 }
556 return sEmptyResults;
557 }
Adam Lesinski0debc9a2014-07-16 19:09:13 -0700558
Adam Lesinski35168002014-07-21 15:25:30 -0700559 /**
Suprabh Shukla217ccda2018-02-23 17:57:12 -0800560 * Like {@link #queryEvents(long, long)}, but only returns events for the calling package.
Varun Shah3a315202019-07-24 16:33:42 -0700561 * <em>Note: Starting from {@link android.os.Build.VERSION_CODES#R Android R}, if the user's
562 * device is not in an unlocked state (as defined by {@link UserManager#isUserUnlocked()}),
563 * then {@code null} will be returned.</em>
Suprabh Shukla217ccda2018-02-23 17:57:12 -0800564 *
565 * @param beginTime The inclusive beginning of the range of events to include in the results.
Michael Wachenschwanz17415c22019-04-01 15:40:49 -0700566 * Defined in terms of "Unix time", see
567 * {@link java.lang.System#currentTimeMillis}.
568 * @param endTime The exclusive end of the range of events to include in the results. Defined
569 * in terms of "Unix time", see {@link java.lang.System#currentTimeMillis}.
Suprabh Shukla217ccda2018-02-23 17:57:12 -0800570 * @return A {@link UsageEvents} object.
571 *
572 * @see #queryEvents(long, long)
573 */
574 public UsageEvents queryEventsForSelf(long beginTime, long endTime) {
575 try {
576 final UsageEvents events = mService.queryEventsForPackage(beginTime, endTime,
577 mContext.getOpPackageName());
578 if (events != null) {
579 return events;
580 }
581 } catch (RemoteException e) {
582 // fallthrough
583 }
584 return sEmptyResults;
585 }
586
587 /**
Adam Lesinski35168002014-07-21 15:25:30 -0700588 * A convenience method that queries for all stats in the given range (using the best interval
589 * for that range), merges the resulting data, and keys it by package name.
590 * See {@link #queryUsageStats(int, long, long)}.
Suprabh Shukla217ccda2018-02-23 17:57:12 -0800591 * <p> The caller must have {@link android.Manifest.permission#PACKAGE_USAGE_STATS} </p>
Adam Lesinski35168002014-07-21 15:25:30 -0700592 *
593 * @param beginTime The inclusive beginning of the range of stats to include in the results.
Michael Wachenschwanz17415c22019-04-01 15:40:49 -0700594 * Defined in terms of "Unix time", see
595 * {@link java.lang.System#currentTimeMillis}.
596 * @param endTime The exclusive end of the range of stats to include in the results. Defined
597 * in terms of "Unix time", see {@link java.lang.System#currentTimeMillis}.
Esteban Talaverafa962312017-10-09 14:58:28 +0100598 * @return A {@link java.util.Map} keyed by package name
Adam Lesinski35168002014-07-21 15:25:30 -0700599 */
Adam Lesinskicc562a82014-08-27 11:52:52 -0700600 public Map<String, UsageStats> queryAndAggregateUsageStats(long beginTime, long endTime) {
Adam Lesinski35168002014-07-21 15:25:30 -0700601 List<UsageStats> stats = queryUsageStats(INTERVAL_BEST, beginTime, endTime);
602 if (stats.isEmpty()) {
Adam Lesinskicc562a82014-08-27 11:52:52 -0700603 return Collections.emptyMap();
Adam Lesinski35168002014-07-21 15:25:30 -0700604 }
Adam Lesinski0debc9a2014-07-16 19:09:13 -0700605
Adam Lesinski35168002014-07-21 15:25:30 -0700606 ArrayMap<String, UsageStats> aggregatedStats = new ArrayMap<>();
607 final int statCount = stats.size();
608 for (int i = 0; i < statCount; i++) {
609 UsageStats newStat = stats.get(i);
610 UsageStats existingStat = aggregatedStats.get(newStat.getPackageName());
611 if (existingStat == null) {
612 aggregatedStats.put(newStat.mPackageName, newStat);
613 } else {
614 existingStat.add(newStat);
Adam Lesinski0debc9a2014-07-16 19:09:13 -0700615 }
616 }
617 return aggregatedStats;
618 }
Amith Yamasanicf768722015-04-23 20:36:41 -0700619
620 /**
Amith Yamasanie5f33042015-05-08 13:20:22 -0700621 * Returns whether the specified app is currently considered inactive. This will be true if the
Amith Yamasanicf768722015-04-23 20:36:41 -0700622 * 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 -0800623 * could be of the order of several hours or days. Apps are not considered inactive when the
624 * device is charging.
Michael Wachenschwanzd2b132f2020-04-01 16:28:46 -0700625 * <p> The caller must have {@link android.Manifest.permission#PACKAGE_USAGE_STATS} to query the
626 * inactive state of other apps</p>
627 *
Amith Yamasanicf768722015-04-23 20:36:41 -0700628 * @param packageName The package name of the app to query
Michael Wachenschwanzd2b132f2020-04-01 16:28:46 -0700629 * @return whether the app is currently considered inactive or false if querying another app
630 * without {@link android.Manifest.permission#PACKAGE_USAGE_STATS}
Amith Yamasanicf768722015-04-23 20:36:41 -0700631 */
Amith Yamasanie5f33042015-05-08 13:20:22 -0700632 public boolean isAppInactive(String packageName) {
Amith Yamasanicf768722015-04-23 20:36:41 -0700633 try {
Michael Wachenschwanzd2b132f2020-04-01 16:28:46 -0700634 return mService.isAppInactive(packageName, mContext.getUserId(),
635 mContext.getOpPackageName());
Amith Yamasanicf768722015-04-23 20:36:41 -0700636 } catch (RemoteException e) {
637 // fall through and return default
638 }
639 return false;
640 }
Amith Yamasani901e9242015-05-13 18:21:09 -0700641
642 /**
Amith Yamasaniafbccb72017-11-27 10:44:24 -0800643 * {@hide}
Amith Yamasani901e9242015-05-13 18:21:09 -0700644 */
645 public void setAppInactive(String packageName, boolean inactive) {
646 try {
Jeff Sharkeyad357d12018-02-02 13:25:31 -0700647 mService.setAppInactive(packageName, inactive, mContext.getUserId());
Amith Yamasani901e9242015-05-13 18:21:09 -0700648 } catch (RemoteException e) {
649 // fall through
650 }
651 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700652
653 /**
Amith Yamasaniafbccb72017-11-27 10:44:24 -0800654 * Returns the current standby bucket of the calling app. The system determines the standby
655 * state of the app based on app usage patterns. Standby buckets determine how much an app will
Amith Yamasani853e53f2018-03-16 16:08:57 -0700656 * be restricted from running background tasks such as jobs and alarms.
Amith Yamasanie8789312017-12-10 14:34:26 -0800657 * <p>Restrictions increase progressively from {@link #STANDBY_BUCKET_ACTIVE} to
Kweku Adamsc6a9b342020-01-08 18:37:26 -0800658 * {@link #STANDBY_BUCKET_RESTRICTED}, with {@link #STANDBY_BUCKET_ACTIVE} being the least
Amith Yamasaniafbccb72017-11-27 10:44:24 -0800659 * restrictive. The battery level of the device might also affect the restrictions.
Amith Yamasani853e53f2018-03-16 16:08:57 -0700660 * <p>Apps in buckets &le; {@link #STANDBY_BUCKET_ACTIVE} have no standby restrictions imposed.
661 * Apps in buckets &gt; {@link #STANDBY_BUCKET_FREQUENT} may have network access restricted when
662 * running in the background.
663 * <p>The standby state of an app can change at any time either due to a user interaction or a
664 * system interaction or some algorithm determining that the app can be restricted for a period
665 * of time before the user has a need for it.
666 * <p>You can also query the recent history of standby bucket changes by calling
667 * {@link #queryEventsForSelf(long, long)} and searching for
668 * {@link UsageEvents.Event#STANDBY_BUCKET_CHANGED}.
Amith Yamasaniafbccb72017-11-27 10:44:24 -0800669 *
Amith Yamasanie8789312017-12-10 14:34:26 -0800670 * @return the current standby bucket of the calling app. One of STANDBY_BUCKET_* constants.
Amith Yamasani17fffee2017-09-29 13:17:43 -0700671 */
Amith Yamasaniafbccb72017-11-27 10:44:24 -0800672 public @StandbyBuckets int getAppStandbyBucket() {
673 try {
674 return mService.getAppStandbyBucket(mContext.getOpPackageName(),
675 mContext.getOpPackageName(),
676 mContext.getUserId());
677 } catch (RemoteException e) {
678 }
679 return STANDBY_BUCKET_ACTIVE;
680 }
681
682 /**
683 * {@hide}
684 * Returns the current standby bucket of the specified app. The caller must hold the permission
685 * android.permission.PACKAGE_USAGE_STATS.
686 * @param packageName the package for which to fetch the current standby bucket.
687 */
688 @SystemApi
689 @RequiresPermission(android.Manifest.permission.PACKAGE_USAGE_STATS)
Amith Yamasani17fffee2017-09-29 13:17:43 -0700690 public @StandbyBuckets int getAppStandbyBucket(String packageName) {
691 try {
692 return mService.getAppStandbyBucket(packageName, mContext.getOpPackageName(),
693 mContext.getUserId());
694 } catch (RemoteException e) {
695 }
Amith Yamasaniafbccb72017-11-27 10:44:24 -0800696 return STANDBY_BUCKET_ACTIVE;
Amith Yamasani17fffee2017-09-29 13:17:43 -0700697 }
698
699 /**
Amith Yamasaniafbccb72017-11-27 10:44:24 -0800700 * {@hide}
Amith Yamasanie8789312017-12-10 14:34:26 -0800701 * Changes an app's standby bucket to the provided value. The caller can only set the standby
Kweku Adamsc6a9b342020-01-08 18:37:26 -0800702 * bucket for a different app than itself. The caller will not be able to change an app's
703 * standby bucket if that app is in the {@link #STANDBY_BUCKET_RESTRICTED} bucket.
Amith Yamasanie8789312017-12-10 14:34:26 -0800704 * @param packageName the package name of the app to set the bucket for. A SecurityException
705 * will be thrown if the package name is that of the caller.
706 * @param bucket the standby bucket to set it to, which should be one of STANDBY_BUCKET_*.
707 * Setting a standby bucket outside of the range of STANDBY_BUCKET_ACTIVE to
708 * STANDBY_BUCKET_NEVER will result in a SecurityException.
Amith Yamasani17fffee2017-09-29 13:17:43 -0700709 */
Amith Yamasani4470ab92017-10-31 13:29:00 -0700710 @SystemApi
711 @RequiresPermission(android.Manifest.permission.CHANGE_APP_IDLE_STATE)
Amith Yamasani17fffee2017-09-29 13:17:43 -0700712 public void setAppStandbyBucket(String packageName, @StandbyBuckets int bucket) {
713 try {
714 mService.setAppStandbyBucket(packageName, bucket, mContext.getUserId());
715 } catch (RemoteException e) {
Amith Yamasanifd44f272018-05-14 14:47:19 -0700716 throw e.rethrowFromSystemServer();
Amith Yamasani17fffee2017-09-29 13:17:43 -0700717 }
718 }
719
720 /**
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700721 * {@hide}
Amith Yamasanie8789312017-12-10 14:34:26 -0800722 * Returns the current standby bucket of every app that has a bucket assigned to it.
723 * The caller must hold the permission android.permission.PACKAGE_USAGE_STATS. The key of the
724 * returned Map is the package name and the value is the bucket assigned to the package.
725 * @see #getAppStandbyBucket()
726 */
727 @SystemApi
728 @RequiresPermission(android.Manifest.permission.PACKAGE_USAGE_STATS)
729 public Map<String, Integer> getAppStandbyBuckets() {
730 try {
Suprabh Shukla868bde22018-02-20 20:59:52 -0800731 final ParceledListSlice<AppStandbyInfo> slice = mService.getAppStandbyBuckets(
Amith Yamasanie8789312017-12-10 14:34:26 -0800732 mContext.getOpPackageName(), mContext.getUserId());
Suprabh Shukla868bde22018-02-20 20:59:52 -0800733 final List<AppStandbyInfo> bucketList = slice.getList();
734 final ArrayMap<String, Integer> bucketMap = new ArrayMap<>();
735 final int n = bucketList.size();
736 for (int i = 0; i < n; i++) {
737 final AppStandbyInfo bucketInfo = bucketList.get(i);
738 bucketMap.put(bucketInfo.mPackageName, bucketInfo.mStandbyBucket);
739 }
740 return bucketMap;
Amith Yamasanie8789312017-12-10 14:34:26 -0800741 } catch (RemoteException e) {
Amith Yamasanifd44f272018-05-14 14:47:19 -0700742 throw e.rethrowFromSystemServer();
Amith Yamasanie8789312017-12-10 14:34:26 -0800743 }
Amith Yamasanie8789312017-12-10 14:34:26 -0800744 }
745
746 /**
747 * {@hide}
748 * Changes the app standby bucket for multiple apps at once. The Map is keyed by the package
Kweku Adamsc6a9b342020-01-08 18:37:26 -0800749 * name and the value is one of STANDBY_BUCKET_*. The caller will not be able to change an
750 * app's standby bucket if that app is in the {@link #STANDBY_BUCKET_RESTRICTED} bucket.
Amith Yamasanie8789312017-12-10 14:34:26 -0800751 * @param appBuckets a map of package name to bucket value.
752 */
753 @SystemApi
754 @RequiresPermission(android.Manifest.permission.CHANGE_APP_IDLE_STATE)
755 public void setAppStandbyBuckets(Map<String, Integer> appBuckets) {
Suprabh Shukla868bde22018-02-20 20:59:52 -0800756 if (appBuckets == null) {
757 return;
758 }
759 final List<AppStandbyInfo> bucketInfoList = new ArrayList<>(appBuckets.size());
760 for (Map.Entry<String, Integer> bucketEntry : appBuckets.entrySet()) {
761 bucketInfoList.add(new AppStandbyInfo(bucketEntry.getKey(), bucketEntry.getValue()));
762 }
763 final ParceledListSlice<AppStandbyInfo> slice = new ParceledListSlice<>(bucketInfoList);
Amith Yamasanie8789312017-12-10 14:34:26 -0800764 try {
Suprabh Shukla868bde22018-02-20 20:59:52 -0800765 mService.setAppStandbyBuckets(slice, mContext.getUserId());
Amith Yamasanie8789312017-12-10 14:34:26 -0800766 } catch (RemoteException e) {
Amith Yamasanifd44f272018-05-14 14:47:19 -0700767 throw e.rethrowFromSystemServer();
Amith Yamasanie8789312017-12-10 14:34:26 -0800768 }
769 }
770
Amith Yamasani62ec27e92018-03-11 14:42:06 -0700771 /**
772 * @hide
773 * Register an app usage limit observer that receives a callback on the provided intent when
Michael Wachenschwanz36778522018-11-12 11:06:19 -0800774 * the sum of usages of apps and tokens in the {@code observed} array exceeds the
775 * {@code timeLimit} specified. The structure of a token is a String with the reporting
776 * package's name and a token the reporting app will use, separated by the forward slash
777 * character. Example: com.reporting.package/5OM3*0P4QU3-7OK3N
778 * The observer will automatically be unregistered when the time limit is reached and the
779 * intent is delivered. Registering an {@code observerId} that was already registered will
780 * override the previous one. No more than 1000 unique {@code observerId} may be registered by
781 * a single uid at any one time.
Amith Yamasani62ec27e92018-03-11 14:42:06 -0700782 * @param observerId A unique id associated with the group of apps to be monitored. There can
783 * be multiple groups with common packages and different time limits.
Michael Wachenschwanz36778522018-11-12 11:06:19 -0800784 * @param observedEntities The list of packages and token to observe for usage time. Cannot be
785 * null and must include at least one package or token.
Amith Yamasani62ec27e92018-03-11 14:42:06 -0700786 * @param timeLimit The total time the set of apps can be in the foreground before the
Michael Wachenschwanzc8703092018-05-01 16:02:45 -0700787 * callbackIntent is delivered. Must be at least one minute.
Amith Yamasanibc813eb2018-03-20 19:37:46 -0700788 * @param timeUnit The unit for time specified in {@code timeLimit}. Cannot be null.
Varun Shah2546cef2019-01-11 15:50:54 -0800789 * @param callbackIntent The PendingIntent that will be dispatched when the usage limit is
Amith Yamasani62ec27e92018-03-11 14:42:06 -0700790 * exceeded by the group of apps. The delivered Intent will also contain
791 * the extras {@link #EXTRA_OBSERVER_ID}, {@link #EXTRA_TIME_LIMIT} and
Amith Yamasanibc813eb2018-03-20 19:37:46 -0700792 * {@link #EXTRA_TIME_USED}. Cannot be null.
Michael Wachenschwanz641e3382018-10-23 23:21:48 -0700793 * @throws SecurityException if the caller doesn't have the OBSERVE_APP_USAGE permission and
Amith Yamasanibc813eb2018-03-20 19:37:46 -0700794 * is not the profile owner of this user.
Amith Yamasani62ec27e92018-03-11 14:42:06 -0700795 */
796 @SystemApi
Amith Yamasanibc813eb2018-03-20 19:37:46 -0700797 @RequiresPermission(android.Manifest.permission.OBSERVE_APP_USAGE)
Michael Wachenschwanz36778522018-11-12 11:06:19 -0800798 public void registerAppUsageObserver(int observerId, @NonNull String[] observedEntities,
799 long timeLimit, @NonNull TimeUnit timeUnit, @NonNull PendingIntent callbackIntent) {
Amith Yamasani62ec27e92018-03-11 14:42:06 -0700800 try {
Michael Wachenschwanz36778522018-11-12 11:06:19 -0800801 mService.registerAppUsageObserver(observerId, observedEntities,
802 timeUnit.toMillis(timeLimit), callbackIntent, mContext.getOpPackageName());
Amith Yamasani62ec27e92018-03-11 14:42:06 -0700803 } catch (RemoteException e) {
Amith Yamasanifd44f272018-05-14 14:47:19 -0700804 throw e.rethrowFromSystemServer();
Amith Yamasani62ec27e92018-03-11 14:42:06 -0700805 }
806 }
807
808 /**
809 * @hide
Amith Yamasanibc813eb2018-03-20 19:37:46 -0700810 * Unregister the app usage observer specified by the {@code observerId}. This will only apply
811 * to any observer registered by this application. Unregistering an observer that was already
Amith Yamasani62ec27e92018-03-11 14:42:06 -0700812 * unregistered or never registered will have no effect.
813 * @param observerId The id of the observer that was previously registered.
Michael Wachenschwanz641e3382018-10-23 23:21:48 -0700814 * @throws SecurityException if the caller doesn't have the OBSERVE_APP_USAGE permission and is
Amith Yamasanibc813eb2018-03-20 19:37:46 -0700815 * not the profile owner of this user.
Amith Yamasani62ec27e92018-03-11 14:42:06 -0700816 */
817 @SystemApi
Amith Yamasanibc813eb2018-03-20 19:37:46 -0700818 @RequiresPermission(android.Manifest.permission.OBSERVE_APP_USAGE)
Amith Yamasani62ec27e92018-03-11 14:42:06 -0700819 public void unregisterAppUsageObserver(int observerId) {
820 try {
821 mService.unregisterAppUsageObserver(observerId, mContext.getOpPackageName());
822 } catch (RemoteException e) {
Amith Yamasanifd44f272018-05-14 14:47:19 -0700823 throw e.rethrowFromSystemServer();
Amith Yamasani62ec27e92018-03-11 14:42:06 -0700824 }
825 }
826
Michael Wachenschwanz641e3382018-10-23 23:21:48 -0700827 /**
828 * Register a usage session observer that receives a callback on the provided {@code
Michael Wachenschwanz36778522018-11-12 11:06:19 -0800829 * limitReachedCallbackIntent} when the sum of usages of apps and tokens in the {@code
830 * observed} array exceeds the {@code timeLimit} specified within a usage session. The
831 * structure of a token is a String with the reporting packages' name and a token the
832 * reporting app will use, separated by the forward slash character.
833 * Example: com.reporting.package/5OM3*0P4QU3-7OK3N
834 * After the {@code timeLimit} has been reached, the usage session observer will receive a
835 * callback on the provided {@code sessionEndCallbackIntent} when the usage session ends.
836 * Registering another session observer against a {@code sessionObserverId} that has already
837 * been registered will override the previous session observer.
Michael Wachenschwanz641e3382018-10-23 23:21:48 -0700838 *
839 * @param sessionObserverId A unique id associated with the group of apps to be
840 * monitored. There can be multiple groups with common
841 * packages and different time limits.
Michael Wachenschwanz36778522018-11-12 11:06:19 -0800842 * @param observedEntities The list of packages and token to observe for usage time. Cannot be
843 * null and must include at least one package or token.
Michael Wachenschwanz641e3382018-10-23 23:21:48 -0700844 * @param timeLimit The total time the set of apps can be used continuously before the {@code
845 * limitReachedCallbackIntent} is delivered. Must be at least one minute.
Michael Wachenschwanz641e3382018-10-23 23:21:48 -0700846 * @param sessionThresholdTime The time that can take place between usage sessions before the
847 * next session is considered a new session. Must be non-negative.
Michael Wachenschwanz641e3382018-10-23 23:21:48 -0700848 * @param limitReachedCallbackIntent The {@link PendingIntent} that will be dispatched when the
Varun Shah2546cef2019-01-11 15:50:54 -0800849 * usage limit is exceeded by the group of apps. The
850 * delivered Intent will also contain the extras {@link
Michael Wachenschwanz641e3382018-10-23 23:21:48 -0700851 * #EXTRA_OBSERVER_ID}, {@link #EXTRA_TIME_LIMIT} and {@link
852 * #EXTRA_TIME_USED}. Cannot be null.
853 * @param sessionEndCallbackIntent The {@link PendingIntent} that will be dispatched when the
Varun Shah2546cef2019-01-11 15:50:54 -0800854 * session has ended after the usage limit has been exceeded.
855 * The session is considered at its end after the {@code
856 * observed} usage has stopped and an additional {@code
Michael Wachenschwanz641e3382018-10-23 23:21:48 -0700857 * sessionThresholdTime} has passed. The delivered Intent will
858 * also contain the extras {@link #EXTRA_OBSERVER_ID} and {@link
859 * #EXTRA_TIME_USED}. Can be null.
860 * @throws SecurityException if the caller doesn't have the OBSERVE_APP_USAGE permission and
861 * is not the profile owner of this user.
862 * @hide
863 */
864 @SystemApi
865 @RequiresPermission(android.Manifest.permission.OBSERVE_APP_USAGE)
Michael Wachenschwanz36778522018-11-12 11:06:19 -0800866 public void registerUsageSessionObserver(int sessionObserverId,
Michael Wachenschwanzd3cb9982019-03-12 16:05:10 -0700867 @NonNull String[] observedEntities, @NonNull Duration timeLimit,
868 @NonNull Duration sessionThresholdTime,
Michael Wachenschwanz641e3382018-10-23 23:21:48 -0700869 @NonNull PendingIntent limitReachedCallbackIntent,
870 @Nullable PendingIntent sessionEndCallbackIntent) {
871 try {
Michael Wachenschwanz36778522018-11-12 11:06:19 -0800872 mService.registerUsageSessionObserver(sessionObserverId, observedEntities,
Michael Wachenschwanzd3cb9982019-03-12 16:05:10 -0700873 timeLimit.toMillis(), sessionThresholdTime.toMillis(),
Michael Wachenschwanz641e3382018-10-23 23:21:48 -0700874 limitReachedCallbackIntent, sessionEndCallbackIntent,
875 mContext.getOpPackageName());
876 } catch (RemoteException e) {
877 throw e.rethrowFromSystemServer();
878 }
879 }
880
881 /**
882 * Unregister the usage session observer specified by the {@code sessionObserverId}. This will
883 * only apply to any app session observer registered by this application. Unregistering an
884 * observer that was already unregistered or never registered will have no effect.
885 *
886 * @param sessionObserverId The id of the observer that was previously registered.
887 * @throws SecurityException if the caller doesn't have the OBSERVE_APP_USAGE permission and
888 * is not the profile owner of this user.
889 * @hide
890 */
891 @SystemApi
892 @RequiresPermission(android.Manifest.permission.OBSERVE_APP_USAGE)
893 public void unregisterUsageSessionObserver(int sessionObserverId) {
894 try {
895 mService.unregisterUsageSessionObserver(sessionObserverId, mContext.getOpPackageName());
896 } catch (RemoteException e) {
897 throw e.rethrowFromSystemServer();
898 }
899 }
900
Michael Wachenschwanz36778522018-11-12 11:06:19 -0800901 /**
Varun Shah2546cef2019-01-11 15:50:54 -0800902 * Register a usage limit observer that receives a callback on the provided intent when the
903 * sum of usages of apps and tokens in the provided {@code observedEntities} array exceeds the
904 * {@code timeLimit} specified. The structure of a token is a {@link String} with the reporting
905 * package's name and a token that the calling app will use, separated by the forward slash
906 * character. Example: com.reporting.package/5OM3*0P4QU3-7OK3N
907 * <p>
908 * Registering an {@code observerId} that was already registered will override the previous one.
909 * No more than 1000 unique {@code observerId} may be registered by a single uid
910 * at any one time.
Varun Shah54f7f7f2019-02-07 10:21:17 -0800911 * A limit is not cleared when the usage time is exceeded. It needs to be unregistered via
912 * {@link #unregisterAppUsageLimitObserver}.
913 * <p>
914 * Note: usage limits are not persisted in the system and are cleared on reboots. Callers
915 * must reset any limits that they need on reboots.
Varun Shah2546cef2019-01-11 15:50:54 -0800916 * <p>
917 * This method is similar to {@link #registerAppUsageObserver}, but the usage limit set here
918 * will be visible to the launcher so that it can report the limit to the user and how much
919 * of it is remaining.
920 * @see android.content.pm.LauncherApps#getAppUsageLimit
921 *
922 * @param observerId A unique id associated with the group of apps to be monitored. There can
Varun Shah9f58b7c2019-03-01 10:36:21 -0800923 * be multiple groups with common packages and different time limits.
Varun Shah2546cef2019-01-11 15:50:54 -0800924 * @param observedEntities The list of packages and token to observe for usage time. Cannot be
925 * null and must include at least one package or token.
926 * @param timeLimit The total time the set of apps can be in the foreground before the
Varun Shah9f58b7c2019-03-01 10:36:21 -0800927 * {@code callbackIntent} is delivered. Must be at least one minute.
Varun Shah4f76a1e2019-03-12 11:46:10 -0700928 * @param timeUsed The time that has already been used by the set of apps in
929 * {@code observedEntities}. Note: a time used equal to or greater than
930 * {@code timeLimit} can be set to indicate that the user has already exhausted
931 * the limit for a group, in which case, the given {@code callbackIntent} will
932 * be ignored.
Varun Shah54f7f7f2019-02-07 10:21:17 -0800933 * @param callbackIntent The PendingIntent that will be dispatched when the usage limit is
Varun Shah2546cef2019-01-11 15:50:54 -0800934 * exceeded by the group of apps. The delivered Intent will also contain
935 * the extras {@link #EXTRA_OBSERVER_ID}, {@link #EXTRA_TIME_LIMIT} and
Varun Shah54f7f7f2019-02-07 10:21:17 -0800936 * {@link #EXTRA_TIME_USED}. Cannot be {@code null} unless the observer is
Varun Shah4f76a1e2019-03-12 11:46:10 -0700937 * being registered with a {@code timeUsed} equal to or greater than
938 * {@code timeLimit}.
Varun Shahb472b8f2019-09-23 23:01:06 -0700939 * @throws SecurityException if the caller is neither the active supervision app nor does it
940 * have both SUSPEND_APPS and OBSERVE_APP_USAGE permissions.
Varun Shah2546cef2019-01-11 15:50:54 -0800941 * @hide
942 */
943 @SystemApi
944 @RequiresPermission(allOf = {
945 android.Manifest.permission.SUSPEND_APPS,
946 android.Manifest.permission.OBSERVE_APP_USAGE})
947 public void registerAppUsageLimitObserver(int observerId, @NonNull String[] observedEntities,
Varun Shah4f76a1e2019-03-12 11:46:10 -0700948 @NonNull Duration timeLimit, @NonNull Duration timeUsed,
Varun Shah9f58b7c2019-03-01 10:36:21 -0800949 @Nullable PendingIntent callbackIntent) {
Varun Shah2546cef2019-01-11 15:50:54 -0800950 try {
951 mService.registerAppUsageLimitObserver(observerId, observedEntities,
Varun Shah4f76a1e2019-03-12 11:46:10 -0700952 timeLimit.toMillis(), timeUsed.toMillis(), callbackIntent,
Varun Shah9f58b7c2019-03-01 10:36:21 -0800953 mContext.getOpPackageName());
Varun Shah2546cef2019-01-11 15:50:54 -0800954 } catch (RemoteException e) {
955 throw e.rethrowFromSystemServer();
956 }
957 }
958
959 /**
960 * Unregister the app usage limit observer specified by the {@code observerId}.
961 * This will only apply to any observer registered by this application. Unregistering
962 * an observer that was already unregistered or never registered will have no effect.
963 *
964 * @param observerId The id of the observer that was previously registered.
Varun Shahb472b8f2019-09-23 23:01:06 -0700965 * @throws SecurityException if the caller is neither the active supervision app nor does it
966 * have both SUSPEND_APPS and OBSERVE_APP_USAGE permissions.
Varun Shah2546cef2019-01-11 15:50:54 -0800967 * @hide
968 */
969 @SystemApi
970 @RequiresPermission(allOf = {
971 android.Manifest.permission.SUSPEND_APPS,
972 android.Manifest.permission.OBSERVE_APP_USAGE})
973 public void unregisterAppUsageLimitObserver(int observerId) {
974 try {
975 mService.unregisterAppUsageLimitObserver(observerId, mContext.getOpPackageName());
976 } catch (RemoteException e) {
977 throw e.rethrowFromSystemServer();
978 }
979 }
980
981 /**
Michael Wachenschwanz36778522018-11-12 11:06:19 -0800982 * Report usage associated with a particular {@code token} has started. Tokens are app defined
983 * strings used to represent usage of in-app features. Apps with the {@link
984 * android.Manifest.permission#OBSERVE_APP_USAGE} permission can register time limit observers
985 * to monitor the usage of a token. In app usage can only associated with an {@code activity}
986 * and usage will be considered stopped if the activity stops or crashes.
987 * @see #registerAppUsageObserver
988 * @see #registerUsageSessionObserver
Varun Shah2546cef2019-01-11 15:50:54 -0800989 * @see #registerAppUsageLimitObserver
Michael Wachenschwanz36778522018-11-12 11:06:19 -0800990 *
991 * @param activity The activity {@code token} is associated with.
992 * @param token The token to report usage against.
993 * @hide
994 */
995 @SystemApi
996 public void reportUsageStart(@NonNull Activity activity, @NonNull String token) {
997 try {
998 mService.reportUsageStart(activity.getActivityToken(), token,
999 mContext.getOpPackageName());
1000 } catch (RemoteException e) {
1001 throw e.rethrowFromSystemServer();
1002 }
1003 }
1004
1005 /**
1006 * Report usage associated with a particular {@code token} had started some amount of time in
1007 * the past. Tokens are app defined strings used to represent usage of in-app features. Apps
1008 * with the {@link android.Manifest.permission#OBSERVE_APP_USAGE} permission can register time
1009 * limit observers to monitor the usage of a token. In app usage can only associated with an
1010 * {@code activity} and usage will be considered stopped if the activity stops or crashes.
1011 * @see #registerAppUsageObserver
1012 * @see #registerUsageSessionObserver
Varun Shah2546cef2019-01-11 15:50:54 -08001013 * @see #registerAppUsageLimitObserver
Michael Wachenschwanz36778522018-11-12 11:06:19 -08001014 *
1015 * @param activity The activity {@code token} is associated with.
1016 * @param token The token to report usage against.
1017 * @param timeAgoMs How long ago the start of usage took place
1018 * @hide
1019 */
1020 @SystemApi
1021 public void reportUsageStart(@NonNull Activity activity, @NonNull String token,
1022 long timeAgoMs) {
1023 try {
1024 mService.reportPastUsageStart(activity.getActivityToken(), token, timeAgoMs,
1025 mContext.getOpPackageName());
1026 } catch (RemoteException e) {
1027 throw e.rethrowFromSystemServer();
1028 }
1029 }
1030
1031 /**
1032 * Report the usage associated with a particular {@code token} has stopped.
1033 *
1034 * @param activity The activity {@code token} is associated with.
1035 * @param token The token to report usage against.
1036 * @hide
1037 */
1038 @SystemApi
1039 public void reportUsageStop(@NonNull Activity activity, @NonNull String token) {
1040 try {
1041 mService.reportUsageStop(activity.getActivityToken(), token,
1042 mContext.getOpPackageName());
1043 } catch (RemoteException e) {
1044 throw e.rethrowFromSystemServer();
1045 }
1046 }
1047
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08001048 /**
1049 * Get what App Usage Observers will consider the source of usage for an activity. Usage Source
1050 * is decided at boot and will not change until next boot.
1051 * @see #USAGE_SOURCE_TASK_ROOT_ACTIVITY
1052 * @see #USAGE_SOURCE_CURRENT_ACTIVITY
1053 *
1054 * @throws SecurityException if the caller doesn't have the OBSERVE_APP_USAGE permission and
1055 * is not the profile owner of this user.
1056 * @hide
1057 */
1058 @SystemApi
1059 public @UsageSource int getUsageSource() {
1060 try {
1061 return mService.getUsageSource();
1062 } catch (RemoteException e) {
1063 throw e.rethrowFromSystemServer();
1064 }
1065 }
1066
1067 /**
1068 * Force the Usage Source be reread from global settings.
1069 * @hide
1070 */
1071 @TestApi
1072 public void forceUsageSourceSettingRead() {
1073 try {
1074 mService.forceUsageSourceSettingRead();
1075 } catch (RemoteException e) {
1076 throw e.rethrowFromSystemServer();
1077 }
1078 }
1079
Amith Yamasani119be9a2018-02-18 22:23:00 -08001080 /** @hide */
1081 public static String reasonToString(int standbyReason) {
Kweku Adamsaa461942020-03-16 11:59:05 -07001082 final int subReason = standbyReason & REASON_SUB_MASK;
Amith Yamasani119be9a2018-02-18 22:23:00 -08001083 StringBuilder sb = new StringBuilder();
1084 switch (standbyReason & REASON_MAIN_MASK) {
1085 case REASON_MAIN_DEFAULT:
1086 sb.append("d");
Kweku Adams917f8a42020-02-26 17:18:03 -08001087 switch (subReason) {
1088 case REASON_SUB_DEFAULT_UNDEFINED:
1089 // Historically, undefined didn't have a string, so don't add anything here.
1090 break;
1091 case REASON_SUB_DEFAULT_APP_UPDATE:
1092 sb.append("-au");
1093 break;
1094 }
Amith Yamasani119be9a2018-02-18 22:23:00 -08001095 break;
Kweku Adamsc182d5e2020-01-08 18:37:26 -08001096 case REASON_MAIN_FORCED_BY_SYSTEM:
1097 sb.append("s");
Kweku Adamsaa461942020-03-16 11:59:05 -07001098 if (subReason > 0) {
1099 sb.append("-").append(Integer.toBinaryString(subReason));
Kweku Adamsc6a9b342020-01-08 18:37:26 -08001100 }
Kweku Adamsc182d5e2020-01-08 18:37:26 -08001101 break;
1102 case REASON_MAIN_FORCED_BY_USER:
Amith Yamasani119be9a2018-02-18 22:23:00 -08001103 sb.append("f");
1104 break;
1105 case REASON_MAIN_PREDICTED:
1106 sb.append("p");
Kweku Adamsaa461942020-03-16 11:59:05 -07001107 switch (subReason) {
Amith Yamasani3154dcf2018-03-27 18:24:04 -07001108 case REASON_SUB_PREDICTED_RESTORED:
1109 sb.append("-r");
1110 break;
1111 }
Amith Yamasani119be9a2018-02-18 22:23:00 -08001112 break;
1113 case REASON_MAIN_TIMEOUT:
1114 sb.append("t");
1115 break;
1116 case REASON_MAIN_USAGE:
Amith Yamasani3154dcf2018-03-27 18:24:04 -07001117 sb.append("u");
Kweku Adamsaa461942020-03-16 11:59:05 -07001118 switch (subReason) {
Amith Yamasani119be9a2018-02-18 22:23:00 -08001119 case REASON_SUB_USAGE_SYSTEM_INTERACTION:
Amith Yamasani3154dcf2018-03-27 18:24:04 -07001120 sb.append("-si");
Amith Yamasani119be9a2018-02-18 22:23:00 -08001121 break;
1122 case REASON_SUB_USAGE_NOTIFICATION_SEEN:
Amith Yamasani3154dcf2018-03-27 18:24:04 -07001123 sb.append("-ns");
Amith Yamasani119be9a2018-02-18 22:23:00 -08001124 break;
1125 case REASON_SUB_USAGE_USER_INTERACTION:
Amith Yamasani3154dcf2018-03-27 18:24:04 -07001126 sb.append("-ui");
Amith Yamasani119be9a2018-02-18 22:23:00 -08001127 break;
1128 case REASON_SUB_USAGE_MOVE_TO_FOREGROUND:
Amith Yamasani3154dcf2018-03-27 18:24:04 -07001129 sb.append("-mf");
Amith Yamasani119be9a2018-02-18 22:23:00 -08001130 break;
1131 case REASON_SUB_USAGE_MOVE_TO_BACKGROUND:
Amith Yamasani3154dcf2018-03-27 18:24:04 -07001132 sb.append("-mb");
Amith Yamasani119be9a2018-02-18 22:23:00 -08001133 break;
1134 case REASON_SUB_USAGE_SYSTEM_UPDATE:
Amith Yamasani3154dcf2018-03-27 18:24:04 -07001135 sb.append("-su");
Amith Yamasani119be9a2018-02-18 22:23:00 -08001136 break;
1137 case REASON_SUB_USAGE_ACTIVE_TIMEOUT:
Amith Yamasani3154dcf2018-03-27 18:24:04 -07001138 sb.append("-at");
Amith Yamasani119be9a2018-02-18 22:23:00 -08001139 break;
1140 case REASON_SUB_USAGE_SYNC_ADAPTER:
Amith Yamasani3154dcf2018-03-27 18:24:04 -07001141 sb.append("-sa");
Amith Yamasani119be9a2018-02-18 22:23:00 -08001142 break;
Amith Yamasani80c4be82018-03-26 10:54:04 -07001143 case REASON_SUB_USAGE_SLICE_PINNED:
Makoto Onukid5f25d22018-05-22 16:02:17 -07001144 sb.append("-lp");
Amith Yamasani80c4be82018-03-26 10:54:04 -07001145 break;
1146 case REASON_SUB_USAGE_SLICE_PINNED_PRIV:
Makoto Onukid5f25d22018-05-22 16:02:17 -07001147 sb.append("-lv");
1148 break;
1149 case REASON_SUB_USAGE_EXEMPTED_SYNC_SCHEDULED_NON_DOZE:
1150 sb.append("-en");
1151 break;
1152 case REASON_SUB_USAGE_EXEMPTED_SYNC_SCHEDULED_DOZE:
1153 sb.append("-ed");
Amith Yamasani80c4be82018-03-26 10:54:04 -07001154 break;
Makoto Onuki75ad2492018-03-28 14:42:42 -07001155 case REASON_SUB_USAGE_EXEMPTED_SYNC_START:
Makoto Onukid5f25d22018-05-22 16:02:17 -07001156 sb.append("-es");
Makoto Onuki75ad2492018-03-28 14:42:42 -07001157 break;
Michael Wachenschwanzc3295202019-02-20 17:19:52 -08001158 case REASON_SUB_USAGE_UNEXEMPTED_SYNC_SCHEDULED:
1159 sb.append("-uss");
1160 break;
Michael Wachenschwanz6ced0ee2019-04-15 16:43:28 -07001161 case REASON_SUB_USAGE_FOREGROUND_SERVICE_START:
1162 sb.append("-fss");
1163 break;
Amith Yamasani119be9a2018-02-18 22:23:00 -08001164 }
1165 break;
1166 }
1167 return sb.toString();
1168 }
1169
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08001170 /** @hide */
1171 public static String usageSourceToString(int usageSource) {
1172 switch (usageSource) {
1173 case USAGE_SOURCE_TASK_ROOT_ACTIVITY:
1174 return "TASK_ROOT_ACTIVITY";
1175 case USAGE_SOURCE_CURRENT_ACTIVITY:
1176 return "CURRENT_ACTIVITY";
1177 default:
1178 StringBuilder sb = new StringBuilder();
1179 sb.append("UNKNOWN(");
1180 sb.append(usageSource);
1181 sb.append(")");
1182 return sb.toString();
1183 }
1184 }
1185
Amith Yamasanie8789312017-12-10 14:34:26 -08001186 /**
1187 * {@hide}
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001188 * Temporarily whitelist the specified app for a short duration. This is to allow an app
1189 * receiving a high priority message to be able to access the network and acquire wakelocks
1190 * even if the device is in power-save mode or the app is currently considered inactive.
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001191 * @param packageName The package name of the app to whitelist.
1192 * @param duration Duration to whitelist the app for, in milliseconds. It is recommended that
1193 * this be limited to 10s of seconds. Requested duration will be clamped to a few minutes.
1194 * @param user The user for whom the package should be whitelisted. Passing in a user that is
1195 * not the same as the caller's process will require the INTERACT_ACROSS_USERS permission.
1196 * @see #isAppInactive(String)
Kweku Adams835283f2019-11-20 14:41:22 -08001197 *
1198 * @deprecated Use
1199 * {@link android.os.PowerWhitelistManager#whitelistAppTemporarily(String, long)} instead.
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001200 */
1201 @SystemApi
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -06001202 @RequiresPermission(android.Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST)
Kweku Adams835283f2019-11-20 14:41:22 -08001203 @Deprecated
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001204 public void whitelistAppTemporarily(String packageName, long duration, UserHandle user) {
Kweku Adams835283f2019-11-20 14:41:22 -08001205 mContext.getSystemService(PowerWhitelistManager.class)
1206 .whitelistAppTemporarily(packageName, duration);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001207 }
Amith Yamasani4ec63682016-02-19 12:55:27 -08001208
1209 /**
1210 * Inform usage stats that the carrier privileged apps access rules have changed.
yinxu0016eef2019-12-09 16:51:53 -08001211 * <p> The caller must have {@link android.Manifest.permission#BIND_CARRIER_SERVICES} </p>
Amith Yamasani4ec63682016-02-19 12:55:27 -08001212 * @hide
1213 */
yinxu0016eef2019-12-09 16:51:53 -08001214 @SystemApi
1215 @RequiresPermission(android.Manifest.permission.BIND_CARRIER_SERVICES)
Amith Yamasani4ec63682016-02-19 12:55:27 -08001216 public void onCarrierPrivilegedAppsChanged() {
1217 try {
1218 mService.onCarrierPrivilegedAppsChanged();
1219 } catch (RemoteException re) {
Amith Yamasanifd44f272018-05-14 14:47:19 -07001220 throw re.rethrowFromSystemServer();
Amith Yamasani4ec63682016-02-19 12:55:27 -08001221 }
1222 }
Kang Li53b43142016-11-14 14:38:25 -08001223
1224 /**
1225 * Reports a Chooser action to the UsageStatsManager.
1226 *
1227 * @param packageName The package name of the app that is selected.
1228 * @param userId The user id of who makes the selection.
1229 * @param contentType The type of the content, e.g., Image, Video, App.
1230 * @param annotations The annotations of the content, e.g., Game, Selfie.
1231 * @param action The action type of Intent that invokes ChooserActivity.
1232 * {@link UsageEvents}
1233 * @hide
1234 */
1235 public void reportChooserSelection(String packageName, int userId, String contentType,
1236 String[] annotations, String action) {
1237 try {
1238 mService.reportChooserSelection(packageName, userId, contentType, annotations, action);
1239 } catch (RemoteException re) {
1240 }
1241 }
Adam Lesinski0debc9a2014-07-16 19:09:13 -07001242}