blob: cee6b87fd3f1479a80c5e98f370a0665700a87a6 [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;
Mathew Inwood61e8ae62018-08-14 14:17:44 +010026import android.annotation.UnsupportedAppUsage;
Michael Wachenschwanz36778522018-11-12 11:06:19 -080027import android.app.Activity;
Amith Yamasani62ec27e92018-03-11 14:42:06 -070028import android.app.PendingIntent;
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;
Adam Lesinski0debc9a2014-07-16 19:09:13 -070032import android.os.RemoteException;
Amith Yamasanicf768722015-04-23 20:36:41 -070033import android.os.UserHandle;
Adam Lesinski35168002014-07-21 15:25:30 -070034import android.util.ArrayMap;
Adam Lesinski0debc9a2014-07-16 19:09:13 -070035
Amith Yamasaniafbccb72017-11-27 10:44:24 -080036import java.lang.annotation.Retention;
37import java.lang.annotation.RetentionPolicy;
Varun Shah9f58b7c2019-03-01 10:36:21 -080038import java.time.Duration;
Suprabh Shukla868bde22018-02-20 20:59:52 -080039import java.util.ArrayList;
Adam Lesinski35168002014-07-21 15:25:30 -070040import java.util.Collections;
41import java.util.List;
Adam Lesinskicc562a82014-08-27 11:52:52 -070042import java.util.Map;
Amith Yamasani62ec27e92018-03-11 14:42:06 -070043import java.util.concurrent.TimeUnit;
Adam Lesinski35168002014-07-21 15:25:30 -070044
45/**
46 * Provides access to device usage history and statistics. Usage data is aggregated into
47 * time intervals: days, weeks, months, and years.
48 * <p />
49 * When requesting usage data since a particular time, the request might look something like this:
50 * <pre>
51 * PAST REQUEST_TIME TODAY FUTURE
52 * ————————————————————————————||———————————————————————————¦-----------------------|
53 * YEAR || ¦ |
54 * ————————————————————————————||———————————————————————————¦-----------------------|
55 * MONTH | || MONTH ¦ |
56 * ——————————————————|—————————||———————————————————————————¦-----------------------|
57 * | WEEK | WEEK|| | WEEK | WE¦EK | WEEK |
58 * ————————————————————————————||———————————————————|———————¦-----------------------|
59 * || |DAY|DAY|DAY|DAY¦DAY|DAY|DAY|DAY|DAY|DAY|
60 * ————————————————————————————||———————————————————————————¦-----------------------|
61 * </pre>
62 * A request for data in the middle of a time interval will include that interval.
63 * <p/>
Suprabh Shukla217ccda2018-02-23 17:57:12 -080064 * <b>NOTE:</b> Most methods on this API require the permission
65 * android.permission.PACKAGE_USAGE_STATS. However, declaring the permission implies intention to
66 * use the API and the user of the device still needs to grant permission through the Settings
67 * application.
68 * See {@link android.provider.Settings#ACTION_USAGE_ACCESS_SETTINGS}.
69 * Methods which only return the information for the calling package do not require this permission.
70 * E.g. {@link #getAppStandbyBucket()} and {@link #queryEventsForSelf(long, long)}.
Adam Lesinski35168002014-07-21 15:25:30 -070071 */
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -060072@SystemService(Context.USAGE_STATS_SERVICE)
Adam Lesinski0debc9a2014-07-16 19:09:13 -070073public final class UsageStatsManager {
Adam Lesinski0debc9a2014-07-16 19:09:13 -070074
75 /**
Adam Lesinski35168002014-07-21 15:25:30 -070076 * An interval type that spans a day. See {@link #queryUsageStats(int, long, long)}.
Adam Lesinski0debc9a2014-07-16 19:09:13 -070077 */
Adam Lesinski35168002014-07-21 15:25:30 -070078 public static final int INTERVAL_DAILY = 0;
Adam Lesinski0debc9a2014-07-16 19:09:13 -070079
80 /**
Adam Lesinski35168002014-07-21 15:25:30 -070081 * An interval type that spans a week. See {@link #queryUsageStats(int, long, long)}.
Adam Lesinski0debc9a2014-07-16 19:09:13 -070082 */
Adam Lesinski35168002014-07-21 15:25:30 -070083 public static final int INTERVAL_WEEKLY = 1;
Adam Lesinski0debc9a2014-07-16 19:09:13 -070084
85 /**
Adam Lesinski35168002014-07-21 15:25:30 -070086 * An interval type that spans a month. See {@link #queryUsageStats(int, long, long)}.
Adam Lesinski0debc9a2014-07-16 19:09:13 -070087 */
Adam Lesinski35168002014-07-21 15:25:30 -070088 public static final int INTERVAL_MONTHLY = 2;
Adam Lesinski0debc9a2014-07-16 19:09:13 -070089
90 /**
Adam Lesinski35168002014-07-21 15:25:30 -070091 * An interval type that spans a year. See {@link #queryUsageStats(int, long, long)}.
92 */
93 public static final int INTERVAL_YEARLY = 3;
94
95 /**
96 * An interval type that will use the best fit interval for the given time range.
97 * See {@link #queryUsageStats(int, long, long)}.
98 */
99 public static final int INTERVAL_BEST = 4;
100
101 /**
102 * The number of available intervals. Does not include {@link #INTERVAL_BEST}, since it
103 * is a pseudo interval (it actually selects a real interval).
Adam Lesinski0debc9a2014-07-16 19:09:13 -0700104 * {@hide}
105 */
Adam Lesinski35168002014-07-21 15:25:30 -0700106 public static final int INTERVAL_COUNT = 4;
107
Amith Yamasaniafbccb72017-11-27 10:44:24 -0800108
109 /**
110 * The app is whitelisted for some reason and the bucket cannot be changed.
111 * {@hide}
112 */
113 @SystemApi
114 public static final int STANDBY_BUCKET_EXEMPTED = 5;
115
116 /**
Amith Yamasani853e53f2018-03-16 16:08:57 -0700117 * The app was used very recently, currently in use or likely to be used very soon. Standby
118 * bucket values that are &le; {@link #STANDBY_BUCKET_ACTIVE} will not be throttled by the
119 * system while they are in this bucket. Buckets &gt; {@link #STANDBY_BUCKET_ACTIVE} will most
120 * likely be restricted in some way. For instance, jobs and alarms may be deferred.
Amith Yamasaniafbccb72017-11-27 10:44:24 -0800121 * @see #getAppStandbyBucket()
122 */
123 public static final int STANDBY_BUCKET_ACTIVE = 10;
124
125 /**
Amith Yamasani853e53f2018-03-16 16:08:57 -0700126 * The app was used recently and/or likely to be used in the next few hours. Restrictions will
127 * apply to these apps, such as deferral of jobs and alarms.
Amith Yamasaniafbccb72017-11-27 10:44:24 -0800128 * @see #getAppStandbyBucket()
129 */
130 public static final int STANDBY_BUCKET_WORKING_SET = 20;
131
132 /**
133 * 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 -0700134 * Restrictions will apply to these apps, such as deferral of jobs and alarms. The delays may be
135 * greater than for apps in higher buckets (lower bucket value). Bucket values &gt;
136 * {@link #STANDBY_BUCKET_FREQUENT} may additionally have network access limited.
Amith Yamasaniafbccb72017-11-27 10:44:24 -0800137 * @see #getAppStandbyBucket()
138 */
139 public static final int STANDBY_BUCKET_FREQUENT = 30;
140
141 /**
142 * The app has not be used for several days and/or is unlikely to be used for several days.
Amith Yamasani853e53f2018-03-16 16:08:57 -0700143 * Apps in this bucket will have the most restrictions, including network restrictions, except
144 * during certain short periods (at a minimum, once a day) when they are allowed to execute
145 * jobs, access the network, etc.
Amith Yamasaniafbccb72017-11-27 10:44:24 -0800146 * @see #getAppStandbyBucket()
147 */
148 public static final int STANDBY_BUCKET_RARE = 40;
149
150 /**
151 * The app has never been used.
152 * {@hide}
153 */
154 @SystemApi
155 public static final int STANDBY_BUCKET_NEVER = 50;
156
Amith Yamasani119be9a2018-02-18 22:23:00 -0800157 /** @hide */
158 public static final int REASON_MAIN_MASK = 0xFF00;
159 /** @hide */
160 public static final int REASON_MAIN_DEFAULT = 0x0100;
161 /** @hide */
162 public static final int REASON_MAIN_TIMEOUT = 0x0200;
163 /** @hide */
164 public static final int REASON_MAIN_USAGE = 0x0300;
165 /** @hide */
166 public static final int REASON_MAIN_FORCED = 0x0400;
167 /** @hide */
168 public static final int REASON_MAIN_PREDICTED = 0x0500;
Amith Yamasaniafbccb72017-11-27 10:44:24 -0800169
Amith Yamasani119be9a2018-02-18 22:23:00 -0800170 /** @hide */
171 public static final int REASON_SUB_MASK = 0x00FF;
172 /** @hide */
173 public static final int REASON_SUB_USAGE_SYSTEM_INTERACTION = 0x0001;
174 /** @hide */
175 public static final int REASON_SUB_USAGE_NOTIFICATION_SEEN = 0x0002;
176 /** @hide */
177 public static final int REASON_SUB_USAGE_USER_INTERACTION = 0x0003;
178 /** @hide */
179 public static final int REASON_SUB_USAGE_MOVE_TO_FOREGROUND = 0x0004;
180 /** @hide */
181 public static final int REASON_SUB_USAGE_MOVE_TO_BACKGROUND = 0x0005;
182 /** @hide */
183 public static final int REASON_SUB_USAGE_SYSTEM_UPDATE = 0x0006;
184 /** @hide */
185 public static final int REASON_SUB_USAGE_ACTIVE_TIMEOUT = 0x0007;
186 /** @hide */
187 public static final int REASON_SUB_USAGE_SYNC_ADAPTER = 0x0008;
Amith Yamasani80c4be82018-03-26 10:54:04 -0700188 /** @hide */
189 public static final int REASON_SUB_USAGE_SLICE_PINNED = 0x0009;
190 /** @hide */
191 public static final int REASON_SUB_USAGE_SLICE_PINNED_PRIV = 0x000A;
Makoto Onuki75ad2492018-03-28 14:42:42 -0700192 /** @hide */
Makoto Onukid5f25d22018-05-22 16:02:17 -0700193 public static final int REASON_SUB_USAGE_EXEMPTED_SYNC_SCHEDULED_NON_DOZE = 0x000B;
194 /** @hide */
195 public static final int REASON_SUB_USAGE_EXEMPTED_SYNC_SCHEDULED_DOZE = 0x000C;
196 /** @hide */
197 public static final int REASON_SUB_USAGE_EXEMPTED_SYNC_START = 0x000D;
Hui Yue361a232018-10-04 15:05:21 -0700198 /** @hide */
Michael Wachenschwanzc3295202019-02-20 17:19:52 -0800199 public static final int REASON_SUB_USAGE_UNEXEMPTED_SYNC_SCHEDULED = 0x000E;
200 /** @hide */
Amith Yamasani3154dcf2018-03-27 18:24:04 -0700201 public static final int REASON_SUB_PREDICTED_RESTORED = 0x0001;
202
Makoto Onuki75ad2492018-03-28 14:42:42 -0700203
Amith Yamasani3154dcf2018-03-27 18:24:04 -0700204 /** @hide */
Jeff Sharkeyce8db992017-12-13 20:05:05 -0700205 @IntDef(flag = false, prefix = { "STANDBY_BUCKET_" }, value = {
Amith Yamasaniafbccb72017-11-27 10:44:24 -0800206 STANDBY_BUCKET_EXEMPTED,
207 STANDBY_BUCKET_ACTIVE,
208 STANDBY_BUCKET_WORKING_SET,
209 STANDBY_BUCKET_FREQUENT,
210 STANDBY_BUCKET_RARE,
211 STANDBY_BUCKET_NEVER,
212 })
213 @Retention(RetentionPolicy.SOURCE)
214 public @interface StandbyBuckets {}
215
Amith Yamasani62ec27e92018-03-11 14:42:06 -0700216 /**
217 * Observer id of the registered observer for the group of packages that reached the usage
218 * time limit. Included as an extra in the PendingIntent that was registered.
219 * @hide
220 */
221 @SystemApi
222 public static final String EXTRA_OBSERVER_ID = "android.app.usage.extra.OBSERVER_ID";
223
224 /**
225 * Original time limit in milliseconds specified by the registered observer for the group of
226 * packages that reached the usage time limit. Included as an extra in the PendingIntent that
227 * was registered.
228 * @hide
229 */
230 @SystemApi
231 public static final String EXTRA_TIME_LIMIT = "android.app.usage.extra.TIME_LIMIT";
232
233 /**
234 * Actual usage time in milliseconds for the group of packages that reached the specified time
235 * limit. Included as an extra in the PendingIntent that was registered.
236 * @hide
237 */
238 @SystemApi
239 public static final String EXTRA_TIME_USED = "android.app.usage.extra.TIME_USED";
240
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -0800241
242 /**
243 * App usage observers will consider the task root package the source of usage.
244 * @hide
245 */
246 @SystemApi
247 public static final int USAGE_SOURCE_TASK_ROOT_ACTIVITY = 1;
248
249 /**
250 * App usage observers will consider the visible activity's package the source of usage.
251 * @hide
252 */
253 @SystemApi
254 public static final int USAGE_SOURCE_CURRENT_ACTIVITY = 2;
255
256 /** @hide */
257 @IntDef(prefix = { "USAGE_SOURCE_" }, value = {
258 USAGE_SOURCE_TASK_ROOT_ACTIVITY,
259 USAGE_SOURCE_CURRENT_ACTIVITY,
260 })
261 @Retention(RetentionPolicy.SOURCE)
262 public @interface UsageSource {}
263
Mathew Inwood31755f92018-12-20 13:53:36 +0000264 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Adam Lesinski35168002014-07-21 15:25:30 -0700265 private static final UsageEvents sEmptyResults = new UsageEvents();
Adam Lesinski0debc9a2014-07-16 19:09:13 -0700266
Mathew Inwood8c854f82018-09-14 12:35:36 +0100267 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Adam Lesinski0debc9a2014-07-16 19:09:13 -0700268 private final Context mContext;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100269 @UnsupportedAppUsage
Adam Lesinski0debc9a2014-07-16 19:09:13 -0700270 private final IUsageStatsManager mService;
271
272 /**
273 * {@hide}
274 */
275 public UsageStatsManager(Context context, IUsageStatsManager service) {
276 mContext = context;
277 mService = service;
278 }
279
Adam Lesinski35168002014-07-21 15:25:30 -0700280 /**
281 * Gets application usage stats for the given time range, aggregated by the specified interval.
282 * <p>The returned list will contain a {@link UsageStats} object for each package that
283 * has data for an interval that is a subset of the time range given. To illustrate:</p>
284 * <pre>
285 * intervalType = INTERVAL_YEARLY
286 * beginTime = 2013
287 * endTime = 2015 (exclusive)
288 *
289 * Results:
290 * 2013 - com.example.alpha
291 * 2013 - com.example.beta
292 * 2014 - com.example.alpha
293 * 2014 - com.example.beta
294 * 2014 - com.example.charlie
295 * </pre>
296 *
Suprabh Shukla217ccda2018-02-23 17:57:12 -0800297 * <p> The caller must have {@link android.Manifest.permission#PACKAGE_USAGE_STATS} </p>
298 *
Adam Lesinski35168002014-07-21 15:25:30 -0700299 * @param intervalType The time interval by which the stats are aggregated.
300 * @param beginTime The inclusive beginning of the range of stats to include in the results.
301 * @param endTime The exclusive end of the range of stats to include in the results.
Esteban Talaverafa962312017-10-09 14:58:28 +0100302 * @return A list of {@link UsageStats}
Adam Lesinski35168002014-07-21 15:25:30 -0700303 *
304 * @see #INTERVAL_DAILY
305 * @see #INTERVAL_WEEKLY
306 * @see #INTERVAL_MONTHLY
307 * @see #INTERVAL_YEARLY
308 * @see #INTERVAL_BEST
309 */
Adam Lesinski35168002014-07-21 15:25:30 -0700310 public List<UsageStats> queryUsageStats(int intervalType, long beginTime, long endTime) {
Adam Lesinski0debc9a2014-07-16 19:09:13 -0700311 try {
Adam Lesinski7f61e962014-09-02 16:43:52 -0700312 @SuppressWarnings("unchecked")
Adam Lesinski35168002014-07-21 15:25:30 -0700313 ParceledListSlice<UsageStats> slice = mService.queryUsageStats(intervalType, beginTime,
314 endTime, mContext.getOpPackageName());
315 if (slice != null) {
316 return slice.getList();
Adam Lesinski0debc9a2014-07-16 19:09:13 -0700317 }
Adam Lesinski35168002014-07-21 15:25:30 -0700318 } catch (RemoteException e) {
Esteban Talaverafa962312017-10-09 14:58:28 +0100319 // fallthrough and return the empty list.
Adam Lesinski35168002014-07-21 15:25:30 -0700320 }
Adam Lesinski7f61e962014-09-02 16:43:52 -0700321 return Collections.emptyList();
322 }
323
324 /**
325 * Gets the hardware configurations the device was in for the given time range, aggregated by
326 * the specified interval. The results are ordered as in
327 * {@link #queryUsageStats(int, long, long)}.
Suprabh Shukla217ccda2018-02-23 17:57:12 -0800328 * <p> The caller must have {@link android.Manifest.permission#PACKAGE_USAGE_STATS} </p>
Adam Lesinski7f61e962014-09-02 16:43:52 -0700329 *
330 * @param intervalType The time interval by which the stats are aggregated.
331 * @param beginTime The inclusive beginning of the range of stats to include in the results.
332 * @param endTime The exclusive end of the range of stats to include in the results.
Esteban Talaverafa962312017-10-09 14:58:28 +0100333 * @return A list of {@link ConfigurationStats}
Adam Lesinski7f61e962014-09-02 16:43:52 -0700334 */
335 public List<ConfigurationStats> queryConfigurations(int intervalType, long beginTime,
336 long endTime) {
337 try {
338 @SuppressWarnings("unchecked")
339 ParceledListSlice<ConfigurationStats> slice = mService.queryConfigurationStats(
340 intervalType, beginTime, endTime, mContext.getOpPackageName());
341 if (slice != null) {
342 return slice.getList();
343 }
344 } catch (RemoteException e) {
345 // fallthrough and return the empty list.
346 }
347 return Collections.emptyList();
Adam Lesinski35168002014-07-21 15:25:30 -0700348 }
Adam Lesinski0debc9a2014-07-16 19:09:13 -0700349
Adam Lesinski35168002014-07-21 15:25:30 -0700350 /**
Dianne Hackbornced54392018-02-26 13:07:42 -0800351 * Gets aggregated event stats for the given time range, aggregated by the specified interval.
352 * <p>The returned list will contain a {@link EventStats} object for each event type that
353 * is being aggregated and has data for an interval that is a subset of the time range given.
354 *
355 * <p>The current event types that will be aggregated here are:</p>
356 * <ul>
357 * <li>{@link UsageEvents.Event#SCREEN_INTERACTIVE}</li>
358 * <li>{@link UsageEvents.Event#SCREEN_NON_INTERACTIVE}</li>
Dianne Hackborn3378aa92018-03-30 17:43:49 -0700359 * <li>{@link UsageEvents.Event#KEYGUARD_SHOWN}</li>
360 * <li>{@link UsageEvents.Event#KEYGUARD_HIDDEN}</li>
Dianne Hackbornced54392018-02-26 13:07:42 -0800361 * </ul>
362 *
363 * <p> The caller must have {@link android.Manifest.permission#PACKAGE_USAGE_STATS} </p>
364 *
365 * @param intervalType The time interval by which the stats are aggregated.
366 * @param beginTime The inclusive beginning of the range of stats to include in the results.
367 * @param endTime The exclusive end of the range of stats to include in the results.
368 * @return A list of {@link EventStats}
369 *
370 * @see #INTERVAL_DAILY
371 * @see #INTERVAL_WEEKLY
372 * @see #INTERVAL_MONTHLY
373 * @see #INTERVAL_YEARLY
374 * @see #INTERVAL_BEST
375 */
376 public List<EventStats> queryEventStats(int intervalType, long beginTime, long endTime) {
377 try {
378 @SuppressWarnings("unchecked")
379 ParceledListSlice<EventStats> slice = mService.queryEventStats(intervalType, beginTime,
380 endTime, mContext.getOpPackageName());
381 if (slice != null) {
382 return slice.getList();
383 }
384 } catch (RemoteException e) {
385 // fallthrough and return the empty list.
386 }
387 return Collections.emptyList();
388 }
389
390 /**
Adam Lesinski35168002014-07-21 15:25:30 -0700391 * Query for events in the given time range. Events are only kept by the system for a few
392 * days.
Suprabh Shukla217ccda2018-02-23 17:57:12 -0800393 * <p> The caller must have {@link android.Manifest.permission#PACKAGE_USAGE_STATS} </p>
Adam Lesinski35168002014-07-21 15:25:30 -0700394 *
395 * @param beginTime The inclusive beginning of the range of events to include in the results.
396 * @param endTime The exclusive end of the range of events to include in the results.
397 * @return A {@link UsageEvents}.
398 */
Adam Lesinski35168002014-07-21 15:25:30 -0700399 public UsageEvents queryEvents(long beginTime, long endTime) {
400 try {
401 UsageEvents iter = mService.queryEvents(beginTime, endTime,
402 mContext.getOpPackageName());
403 if (iter != null) {
404 return iter;
405 }
406 } catch (RemoteException e) {
Esteban Talaverafa962312017-10-09 14:58:28 +0100407 // fallthrough and return empty result.
Adam Lesinski35168002014-07-21 15:25:30 -0700408 }
409 return sEmptyResults;
410 }
Adam Lesinski0debc9a2014-07-16 19:09:13 -0700411
Adam Lesinski35168002014-07-21 15:25:30 -0700412 /**
Suprabh Shukla217ccda2018-02-23 17:57:12 -0800413 * Like {@link #queryEvents(long, long)}, but only returns events for the calling package.
414 *
415 * @param beginTime The inclusive beginning of the range of events to include in the results.
416 * @param endTime The exclusive end of the range of events to include in the results.
417 * @return A {@link UsageEvents} object.
418 *
419 * @see #queryEvents(long, long)
420 */
421 public UsageEvents queryEventsForSelf(long beginTime, long endTime) {
422 try {
423 final UsageEvents events = mService.queryEventsForPackage(beginTime, endTime,
424 mContext.getOpPackageName());
425 if (events != null) {
426 return events;
427 }
428 } catch (RemoteException e) {
429 // fallthrough
430 }
431 return sEmptyResults;
432 }
433
434 /**
Adam Lesinski35168002014-07-21 15:25:30 -0700435 * A convenience method that queries for all stats in the given range (using the best interval
436 * for that range), merges the resulting data, and keys it by package name.
437 * See {@link #queryUsageStats(int, long, long)}.
Suprabh Shukla217ccda2018-02-23 17:57:12 -0800438 * <p> The caller must have {@link android.Manifest.permission#PACKAGE_USAGE_STATS} </p>
Adam Lesinski35168002014-07-21 15:25:30 -0700439 *
440 * @param beginTime The inclusive beginning of the range of stats to include in the results.
441 * @param endTime The exclusive end of the range of stats to include in the results.
Esteban Talaverafa962312017-10-09 14:58:28 +0100442 * @return A {@link java.util.Map} keyed by package name
Adam Lesinski35168002014-07-21 15:25:30 -0700443 */
Adam Lesinskicc562a82014-08-27 11:52:52 -0700444 public Map<String, UsageStats> queryAndAggregateUsageStats(long beginTime, long endTime) {
Adam Lesinski35168002014-07-21 15:25:30 -0700445 List<UsageStats> stats = queryUsageStats(INTERVAL_BEST, beginTime, endTime);
446 if (stats.isEmpty()) {
Adam Lesinskicc562a82014-08-27 11:52:52 -0700447 return Collections.emptyMap();
Adam Lesinski35168002014-07-21 15:25:30 -0700448 }
Adam Lesinski0debc9a2014-07-16 19:09:13 -0700449
Adam Lesinski35168002014-07-21 15:25:30 -0700450 ArrayMap<String, UsageStats> aggregatedStats = new ArrayMap<>();
451 final int statCount = stats.size();
452 for (int i = 0; i < statCount; i++) {
453 UsageStats newStat = stats.get(i);
454 UsageStats existingStat = aggregatedStats.get(newStat.getPackageName());
455 if (existingStat == null) {
456 aggregatedStats.put(newStat.mPackageName, newStat);
457 } else {
458 existingStat.add(newStat);
Adam Lesinski0debc9a2014-07-16 19:09:13 -0700459 }
460 }
461 return aggregatedStats;
462 }
Amith Yamasanicf768722015-04-23 20:36:41 -0700463
464 /**
Amith Yamasanie5f33042015-05-08 13:20:22 -0700465 * Returns whether the specified app is currently considered inactive. This will be true if the
Amith Yamasanicf768722015-04-23 20:36:41 -0700466 * app hasn't been used directly or indirectly for a period of time defined by the system. This
467 * could be of the order of several hours or days.
468 * @param packageName The package name of the app to query
Amith Yamasanie5f33042015-05-08 13:20:22 -0700469 * @return whether the app is currently considered inactive
Amith Yamasanicf768722015-04-23 20:36:41 -0700470 */
Amith Yamasanie5f33042015-05-08 13:20:22 -0700471 public boolean isAppInactive(String packageName) {
Amith Yamasanicf768722015-04-23 20:36:41 -0700472 try {
Jeff Sharkeyad357d12018-02-02 13:25:31 -0700473 return mService.isAppInactive(packageName, mContext.getUserId());
Amith Yamasanicf768722015-04-23 20:36:41 -0700474 } catch (RemoteException e) {
475 // fall through and return default
476 }
477 return false;
478 }
Amith Yamasani901e9242015-05-13 18:21:09 -0700479
480 /**
Amith Yamasaniafbccb72017-11-27 10:44:24 -0800481 * {@hide}
Amith Yamasani901e9242015-05-13 18:21:09 -0700482 */
483 public void setAppInactive(String packageName, boolean inactive) {
484 try {
Jeff Sharkeyad357d12018-02-02 13:25:31 -0700485 mService.setAppInactive(packageName, inactive, mContext.getUserId());
Amith Yamasani901e9242015-05-13 18:21:09 -0700486 } catch (RemoteException e) {
487 // fall through
488 }
489 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700490
491 /**
Amith Yamasaniafbccb72017-11-27 10:44:24 -0800492 * Returns the current standby bucket of the calling app. The system determines the standby
493 * state of the app based on app usage patterns. Standby buckets determine how much an app will
Amith Yamasani853e53f2018-03-16 16:08:57 -0700494 * be restricted from running background tasks such as jobs and alarms.
Amith Yamasanie8789312017-12-10 14:34:26 -0800495 * <p>Restrictions increase progressively from {@link #STANDBY_BUCKET_ACTIVE} to
Amith Yamasaniafbccb72017-11-27 10:44:24 -0800496 * {@link #STANDBY_BUCKET_RARE}, with {@link #STANDBY_BUCKET_ACTIVE} being the least
497 * restrictive. The battery level of the device might also affect the restrictions.
Amith Yamasani853e53f2018-03-16 16:08:57 -0700498 * <p>Apps in buckets &le; {@link #STANDBY_BUCKET_ACTIVE} have no standby restrictions imposed.
499 * Apps in buckets &gt; {@link #STANDBY_BUCKET_FREQUENT} may have network access restricted when
500 * running in the background.
501 * <p>The standby state of an app can change at any time either due to a user interaction or a
502 * system interaction or some algorithm determining that the app can be restricted for a period
503 * of time before the user has a need for it.
504 * <p>You can also query the recent history of standby bucket changes by calling
505 * {@link #queryEventsForSelf(long, long)} and searching for
506 * {@link UsageEvents.Event#STANDBY_BUCKET_CHANGED}.
Amith Yamasaniafbccb72017-11-27 10:44:24 -0800507 *
Amith Yamasanie8789312017-12-10 14:34:26 -0800508 * @return the current standby bucket of the calling app. One of STANDBY_BUCKET_* constants.
Amith Yamasani17fffee2017-09-29 13:17:43 -0700509 */
Amith Yamasaniafbccb72017-11-27 10:44:24 -0800510 public @StandbyBuckets int getAppStandbyBucket() {
511 try {
512 return mService.getAppStandbyBucket(mContext.getOpPackageName(),
513 mContext.getOpPackageName(),
514 mContext.getUserId());
515 } catch (RemoteException e) {
516 }
517 return STANDBY_BUCKET_ACTIVE;
518 }
519
520 /**
521 * {@hide}
522 * Returns the current standby bucket of the specified app. The caller must hold the permission
523 * android.permission.PACKAGE_USAGE_STATS.
524 * @param packageName the package for which to fetch the current standby bucket.
525 */
526 @SystemApi
527 @RequiresPermission(android.Manifest.permission.PACKAGE_USAGE_STATS)
Amith Yamasani17fffee2017-09-29 13:17:43 -0700528 public @StandbyBuckets int getAppStandbyBucket(String packageName) {
529 try {
530 return mService.getAppStandbyBucket(packageName, mContext.getOpPackageName(),
531 mContext.getUserId());
532 } catch (RemoteException e) {
533 }
Amith Yamasaniafbccb72017-11-27 10:44:24 -0800534 return STANDBY_BUCKET_ACTIVE;
Amith Yamasani17fffee2017-09-29 13:17:43 -0700535 }
536
537 /**
Amith Yamasaniafbccb72017-11-27 10:44:24 -0800538 * {@hide}
Amith Yamasanie8789312017-12-10 14:34:26 -0800539 * Changes an app's standby bucket to the provided value. The caller can only set the standby
540 * bucket for a different app than itself.
541 * @param packageName the package name of the app to set the bucket for. A SecurityException
542 * will be thrown if the package name is that of the caller.
543 * @param bucket the standby bucket to set it to, which should be one of STANDBY_BUCKET_*.
544 * Setting a standby bucket outside of the range of STANDBY_BUCKET_ACTIVE to
545 * STANDBY_BUCKET_NEVER will result in a SecurityException.
Amith Yamasani17fffee2017-09-29 13:17:43 -0700546 */
Amith Yamasani4470ab92017-10-31 13:29:00 -0700547 @SystemApi
548 @RequiresPermission(android.Manifest.permission.CHANGE_APP_IDLE_STATE)
Amith Yamasani17fffee2017-09-29 13:17:43 -0700549 public void setAppStandbyBucket(String packageName, @StandbyBuckets int bucket) {
550 try {
551 mService.setAppStandbyBucket(packageName, bucket, mContext.getUserId());
552 } catch (RemoteException e) {
Amith Yamasanifd44f272018-05-14 14:47:19 -0700553 throw e.rethrowFromSystemServer();
Amith Yamasani17fffee2017-09-29 13:17:43 -0700554 }
555 }
556
557 /**
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700558 * {@hide}
Amith Yamasanie8789312017-12-10 14:34:26 -0800559 * Returns the current standby bucket of every app that has a bucket assigned to it.
560 * The caller must hold the permission android.permission.PACKAGE_USAGE_STATS. The key of the
561 * returned Map is the package name and the value is the bucket assigned to the package.
562 * @see #getAppStandbyBucket()
563 */
564 @SystemApi
565 @RequiresPermission(android.Manifest.permission.PACKAGE_USAGE_STATS)
566 public Map<String, Integer> getAppStandbyBuckets() {
567 try {
Suprabh Shukla868bde22018-02-20 20:59:52 -0800568 final ParceledListSlice<AppStandbyInfo> slice = mService.getAppStandbyBuckets(
Amith Yamasanie8789312017-12-10 14:34:26 -0800569 mContext.getOpPackageName(), mContext.getUserId());
Suprabh Shukla868bde22018-02-20 20:59:52 -0800570 final List<AppStandbyInfo> bucketList = slice.getList();
571 final ArrayMap<String, Integer> bucketMap = new ArrayMap<>();
572 final int n = bucketList.size();
573 for (int i = 0; i < n; i++) {
574 final AppStandbyInfo bucketInfo = bucketList.get(i);
575 bucketMap.put(bucketInfo.mPackageName, bucketInfo.mStandbyBucket);
576 }
577 return bucketMap;
Amith Yamasanie8789312017-12-10 14:34:26 -0800578 } catch (RemoteException e) {
Amith Yamasanifd44f272018-05-14 14:47:19 -0700579 throw e.rethrowFromSystemServer();
Amith Yamasanie8789312017-12-10 14:34:26 -0800580 }
Amith Yamasanie8789312017-12-10 14:34:26 -0800581 }
582
583 /**
584 * {@hide}
585 * Changes the app standby bucket for multiple apps at once. The Map is keyed by the package
586 * name and the value is one of STANDBY_BUCKET_*.
587 * @param appBuckets a map of package name to bucket value.
588 */
589 @SystemApi
590 @RequiresPermission(android.Manifest.permission.CHANGE_APP_IDLE_STATE)
591 public void setAppStandbyBuckets(Map<String, Integer> appBuckets) {
Suprabh Shukla868bde22018-02-20 20:59:52 -0800592 if (appBuckets == null) {
593 return;
594 }
595 final List<AppStandbyInfo> bucketInfoList = new ArrayList<>(appBuckets.size());
596 for (Map.Entry<String, Integer> bucketEntry : appBuckets.entrySet()) {
597 bucketInfoList.add(new AppStandbyInfo(bucketEntry.getKey(), bucketEntry.getValue()));
598 }
599 final ParceledListSlice<AppStandbyInfo> slice = new ParceledListSlice<>(bucketInfoList);
Amith Yamasanie8789312017-12-10 14:34:26 -0800600 try {
Suprabh Shukla868bde22018-02-20 20:59:52 -0800601 mService.setAppStandbyBuckets(slice, mContext.getUserId());
Amith Yamasanie8789312017-12-10 14:34:26 -0800602 } catch (RemoteException e) {
Amith Yamasanifd44f272018-05-14 14:47:19 -0700603 throw e.rethrowFromSystemServer();
Amith Yamasanie8789312017-12-10 14:34:26 -0800604 }
605 }
606
Amith Yamasani62ec27e92018-03-11 14:42:06 -0700607 /**
608 * @hide
609 * Register an app usage limit observer that receives a callback on the provided intent when
Michael Wachenschwanz36778522018-11-12 11:06:19 -0800610 * the sum of usages of apps and tokens in the {@code observed} array exceeds the
611 * {@code timeLimit} specified. The structure of a token is a String with the reporting
612 * package's name and a token the reporting app will use, separated by the forward slash
613 * character. Example: com.reporting.package/5OM3*0P4QU3-7OK3N
614 * The observer will automatically be unregistered when the time limit is reached and the
615 * intent is delivered. Registering an {@code observerId} that was already registered will
616 * override the previous one. No more than 1000 unique {@code observerId} may be registered by
617 * a single uid at any one time.
Amith Yamasani62ec27e92018-03-11 14:42:06 -0700618 * @param observerId A unique id associated with the group of apps to be monitored. There can
619 * be multiple groups with common packages and different time limits.
Michael Wachenschwanz36778522018-11-12 11:06:19 -0800620 * @param observedEntities The list of packages and token to observe for usage time. Cannot be
621 * null and must include at least one package or token.
Amith Yamasani62ec27e92018-03-11 14:42:06 -0700622 * @param timeLimit The total time the set of apps can be in the foreground before the
Michael Wachenschwanzc8703092018-05-01 16:02:45 -0700623 * callbackIntent is delivered. Must be at least one minute.
Amith Yamasanibc813eb2018-03-20 19:37:46 -0700624 * @param timeUnit The unit for time specified in {@code timeLimit}. Cannot be null.
Varun Shah2546cef2019-01-11 15:50:54 -0800625 * @param callbackIntent The PendingIntent that will be dispatched when the usage limit is
Amith Yamasani62ec27e92018-03-11 14:42:06 -0700626 * exceeded by the group of apps. The delivered Intent will also contain
627 * the extras {@link #EXTRA_OBSERVER_ID}, {@link #EXTRA_TIME_LIMIT} and
Amith Yamasanibc813eb2018-03-20 19:37:46 -0700628 * {@link #EXTRA_TIME_USED}. Cannot be null.
Michael Wachenschwanz641e3382018-10-23 23:21:48 -0700629 * @throws SecurityException if the caller doesn't have the OBSERVE_APP_USAGE permission and
Amith Yamasanibc813eb2018-03-20 19:37:46 -0700630 * is not the profile owner of this user.
Amith Yamasani62ec27e92018-03-11 14:42:06 -0700631 */
632 @SystemApi
Amith Yamasanibc813eb2018-03-20 19:37:46 -0700633 @RequiresPermission(android.Manifest.permission.OBSERVE_APP_USAGE)
Michael Wachenschwanz36778522018-11-12 11:06:19 -0800634 public void registerAppUsageObserver(int observerId, @NonNull String[] observedEntities,
635 long timeLimit, @NonNull TimeUnit timeUnit, @NonNull PendingIntent callbackIntent) {
Amith Yamasani62ec27e92018-03-11 14:42:06 -0700636 try {
Michael Wachenschwanz36778522018-11-12 11:06:19 -0800637 mService.registerAppUsageObserver(observerId, observedEntities,
638 timeUnit.toMillis(timeLimit), callbackIntent, mContext.getOpPackageName());
Amith Yamasani62ec27e92018-03-11 14:42:06 -0700639 } catch (RemoteException e) {
Amith Yamasanifd44f272018-05-14 14:47:19 -0700640 throw e.rethrowFromSystemServer();
Amith Yamasani62ec27e92018-03-11 14:42:06 -0700641 }
642 }
643
644 /**
645 * @hide
Amith Yamasanibc813eb2018-03-20 19:37:46 -0700646 * Unregister the app usage observer specified by the {@code observerId}. This will only apply
647 * to any observer registered by this application. Unregistering an observer that was already
Amith Yamasani62ec27e92018-03-11 14:42:06 -0700648 * unregistered or never registered will have no effect.
649 * @param observerId The id of the observer that was previously registered.
Michael Wachenschwanz641e3382018-10-23 23:21:48 -0700650 * @throws SecurityException if the caller doesn't have the OBSERVE_APP_USAGE permission and is
Amith Yamasanibc813eb2018-03-20 19:37:46 -0700651 * not the profile owner of this user.
Amith Yamasani62ec27e92018-03-11 14:42:06 -0700652 */
653 @SystemApi
Amith Yamasanibc813eb2018-03-20 19:37:46 -0700654 @RequiresPermission(android.Manifest.permission.OBSERVE_APP_USAGE)
Amith Yamasani62ec27e92018-03-11 14:42:06 -0700655 public void unregisterAppUsageObserver(int observerId) {
656 try {
657 mService.unregisterAppUsageObserver(observerId, mContext.getOpPackageName());
658 } catch (RemoteException e) {
Amith Yamasanifd44f272018-05-14 14:47:19 -0700659 throw e.rethrowFromSystemServer();
Amith Yamasani62ec27e92018-03-11 14:42:06 -0700660 }
661 }
662
Michael Wachenschwanz641e3382018-10-23 23:21:48 -0700663 /**
664 * Register a usage session observer that receives a callback on the provided {@code
Michael Wachenschwanz36778522018-11-12 11:06:19 -0800665 * limitReachedCallbackIntent} when the sum of usages of apps and tokens in the {@code
666 * observed} array exceeds the {@code timeLimit} specified within a usage session. The
667 * structure of a token is a String with the reporting packages' name and a token the
668 * reporting app will use, separated by the forward slash character.
669 * Example: com.reporting.package/5OM3*0P4QU3-7OK3N
670 * After the {@code timeLimit} has been reached, the usage session observer will receive a
671 * callback on the provided {@code sessionEndCallbackIntent} when the usage session ends.
672 * Registering another session observer against a {@code sessionObserverId} that has already
673 * been registered will override the previous session observer.
Michael Wachenschwanz641e3382018-10-23 23:21:48 -0700674 *
675 * @param sessionObserverId A unique id associated with the group of apps to be
676 * monitored. There can be multiple groups with common
677 * packages and different time limits.
Michael Wachenschwanz36778522018-11-12 11:06:19 -0800678 * @param observedEntities The list of packages and token to observe for usage time. Cannot be
679 * null and must include at least one package or token.
Michael Wachenschwanz641e3382018-10-23 23:21:48 -0700680 * @param timeLimit The total time the set of apps can be used continuously before the {@code
681 * limitReachedCallbackIntent} is delivered. Must be at least one minute.
682 * @param timeUnit The unit for time specified in {@code timeLimit}. Cannot be null.
683 * @param sessionThresholdTime The time that can take place between usage sessions before the
684 * next session is considered a new session. Must be non-negative.
685 * @param sessionThresholdTimeUnit The unit for time specified in {@code sessionThreshold}.
686 * Cannot be null.
687 * @param limitReachedCallbackIntent The {@link PendingIntent} that will be dispatched when the
Varun Shah2546cef2019-01-11 15:50:54 -0800688 * usage limit is exceeded by the group of apps. The
689 * delivered Intent will also contain the extras {@link
Michael Wachenschwanz641e3382018-10-23 23:21:48 -0700690 * #EXTRA_OBSERVER_ID}, {@link #EXTRA_TIME_LIMIT} and {@link
691 * #EXTRA_TIME_USED}. Cannot be null.
692 * @param sessionEndCallbackIntent The {@link PendingIntent} that will be dispatched when the
Varun Shah2546cef2019-01-11 15:50:54 -0800693 * session has ended after the usage limit has been exceeded.
694 * The session is considered at its end after the {@code
695 * observed} usage has stopped and an additional {@code
Michael Wachenschwanz641e3382018-10-23 23:21:48 -0700696 * sessionThresholdTime} has passed. The delivered Intent will
697 * also contain the extras {@link #EXTRA_OBSERVER_ID} and {@link
698 * #EXTRA_TIME_USED}. Can be null.
699 * @throws SecurityException if the caller doesn't have the OBSERVE_APP_USAGE permission and
700 * is not the profile owner of this user.
701 * @hide
702 */
703 @SystemApi
704 @RequiresPermission(android.Manifest.permission.OBSERVE_APP_USAGE)
Michael Wachenschwanz36778522018-11-12 11:06:19 -0800705 public void registerUsageSessionObserver(int sessionObserverId,
706 @NonNull String[] observedEntities, long timeLimit, @NonNull TimeUnit timeUnit,
707 long sessionThresholdTime, @NonNull TimeUnit sessionThresholdTimeUnit,
Michael Wachenschwanz641e3382018-10-23 23:21:48 -0700708 @NonNull PendingIntent limitReachedCallbackIntent,
709 @Nullable PendingIntent sessionEndCallbackIntent) {
710 try {
Michael Wachenschwanz36778522018-11-12 11:06:19 -0800711 mService.registerUsageSessionObserver(sessionObserverId, observedEntities,
Michael Wachenschwanz641e3382018-10-23 23:21:48 -0700712 timeUnit.toMillis(timeLimit),
713 sessionThresholdTimeUnit.toMillis(sessionThresholdTime),
714 limitReachedCallbackIntent, sessionEndCallbackIntent,
715 mContext.getOpPackageName());
716 } catch (RemoteException e) {
717 throw e.rethrowFromSystemServer();
718 }
719 }
720
721 /**
722 * Unregister the usage session observer specified by the {@code sessionObserverId}. This will
723 * only apply to any app session observer registered by this application. Unregistering an
724 * observer that was already unregistered or never registered will have no effect.
725 *
726 * @param sessionObserverId The id of the observer that was previously registered.
727 * @throws SecurityException if the caller doesn't have the OBSERVE_APP_USAGE permission and
728 * is not the profile owner of this user.
729 * @hide
730 */
731 @SystemApi
732 @RequiresPermission(android.Manifest.permission.OBSERVE_APP_USAGE)
733 public void unregisterUsageSessionObserver(int sessionObserverId) {
734 try {
735 mService.unregisterUsageSessionObserver(sessionObserverId, mContext.getOpPackageName());
736 } catch (RemoteException e) {
737 throw e.rethrowFromSystemServer();
738 }
739 }
740
Michael Wachenschwanz36778522018-11-12 11:06:19 -0800741 /**
Varun Shah9f58b7c2019-03-01 10:36:21 -0800742 * @deprecated use
743 * {@link #registerAppUsageLimitObserver(int, String[], Duration, Duration, PendingIntent)}.
744 *
745 * @removed
746 * @hide
747 */
748 @Deprecated
749 @UnsupportedAppUsage
750 // STOPSHIP b/126917290: remove this method once ag/6591106 is merged and it's not being used.
751 public void registerAppUsageLimitObserver(int observerId, @NonNull String[] observedEntities,
752 long timeLimit, @NonNull TimeUnit timeUnit, @Nullable PendingIntent callbackIntent) {
753 final Duration timeLimitDuration = Duration.ofMillis(timeUnit.toMillis(timeLimit));
754 registerAppUsageLimitObserver(observerId, observedEntities,
755 timeLimitDuration, timeLimitDuration, callbackIntent);
756 }
757
758 /**
Varun Shah2546cef2019-01-11 15:50:54 -0800759 * Register a usage limit observer that receives a callback on the provided intent when the
760 * sum of usages of apps and tokens in the provided {@code observedEntities} array exceeds the
761 * {@code timeLimit} specified. The structure of a token is a {@link String} with the reporting
762 * package's name and a token that the calling app will use, separated by the forward slash
763 * character. Example: com.reporting.package/5OM3*0P4QU3-7OK3N
764 * <p>
765 * Registering an {@code observerId} that was already registered will override the previous one.
766 * No more than 1000 unique {@code observerId} may be registered by a single uid
767 * at any one time.
Varun Shah54f7f7f2019-02-07 10:21:17 -0800768 * A limit is not cleared when the usage time is exceeded. It needs to be unregistered via
769 * {@link #unregisterAppUsageLimitObserver}.
770 * <p>
771 * Note: usage limits are not persisted in the system and are cleared on reboots. Callers
772 * must reset any limits that they need on reboots.
Varun Shah2546cef2019-01-11 15:50:54 -0800773 * <p>
774 * This method is similar to {@link #registerAppUsageObserver}, but the usage limit set here
775 * will be visible to the launcher so that it can report the limit to the user and how much
776 * of it is remaining.
777 * @see android.content.pm.LauncherApps#getAppUsageLimit
778 *
779 * @param observerId A unique id associated with the group of apps to be monitored. There can
Varun Shah9f58b7c2019-03-01 10:36:21 -0800780 * be multiple groups with common packages and different time limits.
Varun Shah2546cef2019-01-11 15:50:54 -0800781 * @param observedEntities The list of packages and token to observe for usage time. Cannot be
782 * null and must include at least one package or token.
783 * @param timeLimit The total time the set of apps can be in the foreground before the
Varun Shah9f58b7c2019-03-01 10:36:21 -0800784 * {@code callbackIntent} is delivered. Must be at least one minute.
785 * @param timeRemaining The remaining time the set of apps can be in the foreground before the
786 * {@code callbackIntent} is delivered. Must be greater than
787 * {@code timeLimit}. Note: a limit of 0 can be set to indicate that the
788 * user has already exhausted the limit for a group, in which case,
789 * the given {@code callbackIntent} will be ignored.
Varun Shah54f7f7f2019-02-07 10:21:17 -0800790 * @param callbackIntent The PendingIntent that will be dispatched when the usage limit is
Varun Shah2546cef2019-01-11 15:50:54 -0800791 * exceeded by the group of apps. The delivered Intent will also contain
792 * the extras {@link #EXTRA_OBSERVER_ID}, {@link #EXTRA_TIME_LIMIT} and
Varun Shah54f7f7f2019-02-07 10:21:17 -0800793 * {@link #EXTRA_TIME_USED}. Cannot be {@code null} unless the observer is
Varun Shah9f58b7c2019-03-01 10:36:21 -0800794 * being registered with a {@code timeRemaining} of 0.
Varun Shah2546cef2019-01-11 15:50:54 -0800795 * @throws SecurityException if the caller doesn't have both SUSPEND_APPS and OBSERVE_APP_USAGE
796 * permissions.
797 * @hide
798 */
799 @SystemApi
800 @RequiresPermission(allOf = {
801 android.Manifest.permission.SUSPEND_APPS,
802 android.Manifest.permission.OBSERVE_APP_USAGE})
803 public void registerAppUsageLimitObserver(int observerId, @NonNull String[] observedEntities,
Varun Shah9f58b7c2019-03-01 10:36:21 -0800804 @NonNull Duration timeLimit, @NonNull Duration timeRemaining,
805 @Nullable PendingIntent callbackIntent) {
Varun Shah2546cef2019-01-11 15:50:54 -0800806 try {
807 mService.registerAppUsageLimitObserver(observerId, observedEntities,
Varun Shah9f58b7c2019-03-01 10:36:21 -0800808 timeLimit.toMillis(), timeRemaining.toMillis(), callbackIntent,
809 mContext.getOpPackageName());
Varun Shah2546cef2019-01-11 15:50:54 -0800810 } catch (RemoteException e) {
811 throw e.rethrowFromSystemServer();
812 }
813 }
814
815 /**
816 * Unregister the app usage limit observer specified by the {@code observerId}.
817 * This will only apply to any observer registered by this application. Unregistering
818 * an observer that was already unregistered or never registered will have no effect.
819 *
820 * @param observerId The id of the observer that was previously registered.
821 * @throws SecurityException if the caller doesn't have both SUSPEND_APPS and OBSERVE_APP_USAGE
822 * permissions.
823 * @hide
824 */
825 @SystemApi
826 @RequiresPermission(allOf = {
827 android.Manifest.permission.SUSPEND_APPS,
828 android.Manifest.permission.OBSERVE_APP_USAGE})
829 public void unregisterAppUsageLimitObserver(int observerId) {
830 try {
831 mService.unregisterAppUsageLimitObserver(observerId, mContext.getOpPackageName());
832 } catch (RemoteException e) {
833 throw e.rethrowFromSystemServer();
834 }
835 }
836
837 /**
Michael Wachenschwanz36778522018-11-12 11:06:19 -0800838 * Report usage associated with a particular {@code token} has started. Tokens are app defined
839 * strings used to represent usage of in-app features. Apps with the {@link
840 * android.Manifest.permission#OBSERVE_APP_USAGE} permission can register time limit observers
841 * to monitor the usage of a token. In app usage can only associated with an {@code activity}
842 * and usage will be considered stopped if the activity stops or crashes.
843 * @see #registerAppUsageObserver
844 * @see #registerUsageSessionObserver
Varun Shah2546cef2019-01-11 15:50:54 -0800845 * @see #registerAppUsageLimitObserver
Michael Wachenschwanz36778522018-11-12 11:06:19 -0800846 *
847 * @param activity The activity {@code token} is associated with.
848 * @param token The token to report usage against.
849 * @hide
850 */
851 @SystemApi
852 public void reportUsageStart(@NonNull Activity activity, @NonNull String token) {
853 try {
854 mService.reportUsageStart(activity.getActivityToken(), token,
855 mContext.getOpPackageName());
856 } catch (RemoteException e) {
857 throw e.rethrowFromSystemServer();
858 }
859 }
860
861 /**
862 * Report usage associated with a particular {@code token} had started some amount of time in
863 * the past. Tokens are app defined strings used to represent usage of in-app features. Apps
864 * with the {@link android.Manifest.permission#OBSERVE_APP_USAGE} permission can register time
865 * limit observers to monitor the usage of a token. In app usage can only associated with an
866 * {@code activity} and usage will be considered stopped if the activity stops or crashes.
867 * @see #registerAppUsageObserver
868 * @see #registerUsageSessionObserver
Varun Shah2546cef2019-01-11 15:50:54 -0800869 * @see #registerAppUsageLimitObserver
Michael Wachenschwanz36778522018-11-12 11:06:19 -0800870 *
871 * @param activity The activity {@code token} is associated with.
872 * @param token The token to report usage against.
873 * @param timeAgoMs How long ago the start of usage took place
874 * @hide
875 */
876 @SystemApi
877 public void reportUsageStart(@NonNull Activity activity, @NonNull String token,
878 long timeAgoMs) {
879 try {
880 mService.reportPastUsageStart(activity.getActivityToken(), token, timeAgoMs,
881 mContext.getOpPackageName());
882 } catch (RemoteException e) {
883 throw e.rethrowFromSystemServer();
884 }
885 }
886
887 /**
888 * Report the usage associated with a particular {@code token} has stopped.
889 *
890 * @param activity The activity {@code token} is associated with.
891 * @param token The token to report usage against.
892 * @hide
893 */
894 @SystemApi
895 public void reportUsageStop(@NonNull Activity activity, @NonNull String token) {
896 try {
897 mService.reportUsageStop(activity.getActivityToken(), token,
898 mContext.getOpPackageName());
899 } catch (RemoteException e) {
900 throw e.rethrowFromSystemServer();
901 }
902 }
903
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -0800904 /**
905 * Get what App Usage Observers will consider the source of usage for an activity. Usage Source
906 * is decided at boot and will not change until next boot.
907 * @see #USAGE_SOURCE_TASK_ROOT_ACTIVITY
908 * @see #USAGE_SOURCE_CURRENT_ACTIVITY
909 *
910 * @throws SecurityException if the caller doesn't have the OBSERVE_APP_USAGE permission and
911 * is not the profile owner of this user.
912 * @hide
913 */
914 @SystemApi
915 public @UsageSource int getUsageSource() {
916 try {
917 return mService.getUsageSource();
918 } catch (RemoteException e) {
919 throw e.rethrowFromSystemServer();
920 }
921 }
922
923 /**
924 * Force the Usage Source be reread from global settings.
925 * @hide
926 */
927 @TestApi
928 public void forceUsageSourceSettingRead() {
929 try {
930 mService.forceUsageSourceSettingRead();
931 } catch (RemoteException e) {
932 throw e.rethrowFromSystemServer();
933 }
934 }
935
Amith Yamasani119be9a2018-02-18 22:23:00 -0800936 /** @hide */
937 public static String reasonToString(int standbyReason) {
938 StringBuilder sb = new StringBuilder();
939 switch (standbyReason & REASON_MAIN_MASK) {
940 case REASON_MAIN_DEFAULT:
941 sb.append("d");
942 break;
943 case REASON_MAIN_FORCED:
944 sb.append("f");
945 break;
946 case REASON_MAIN_PREDICTED:
947 sb.append("p");
Amith Yamasani3154dcf2018-03-27 18:24:04 -0700948 switch (standbyReason & REASON_SUB_MASK) {
949 case REASON_SUB_PREDICTED_RESTORED:
950 sb.append("-r");
951 break;
952 }
Amith Yamasani119be9a2018-02-18 22:23:00 -0800953 break;
954 case REASON_MAIN_TIMEOUT:
955 sb.append("t");
956 break;
957 case REASON_MAIN_USAGE:
Amith Yamasani3154dcf2018-03-27 18:24:04 -0700958 sb.append("u");
Amith Yamasani119be9a2018-02-18 22:23:00 -0800959 switch (standbyReason & REASON_SUB_MASK) {
960 case REASON_SUB_USAGE_SYSTEM_INTERACTION:
Amith Yamasani3154dcf2018-03-27 18:24:04 -0700961 sb.append("-si");
Amith Yamasani119be9a2018-02-18 22:23:00 -0800962 break;
963 case REASON_SUB_USAGE_NOTIFICATION_SEEN:
Amith Yamasani3154dcf2018-03-27 18:24:04 -0700964 sb.append("-ns");
Amith Yamasani119be9a2018-02-18 22:23:00 -0800965 break;
966 case REASON_SUB_USAGE_USER_INTERACTION:
Amith Yamasani3154dcf2018-03-27 18:24:04 -0700967 sb.append("-ui");
Amith Yamasani119be9a2018-02-18 22:23:00 -0800968 break;
969 case REASON_SUB_USAGE_MOVE_TO_FOREGROUND:
Amith Yamasani3154dcf2018-03-27 18:24:04 -0700970 sb.append("-mf");
Amith Yamasani119be9a2018-02-18 22:23:00 -0800971 break;
972 case REASON_SUB_USAGE_MOVE_TO_BACKGROUND:
Amith Yamasani3154dcf2018-03-27 18:24:04 -0700973 sb.append("-mb");
Amith Yamasani119be9a2018-02-18 22:23:00 -0800974 break;
975 case REASON_SUB_USAGE_SYSTEM_UPDATE:
Amith Yamasani3154dcf2018-03-27 18:24:04 -0700976 sb.append("-su");
Amith Yamasani119be9a2018-02-18 22:23:00 -0800977 break;
978 case REASON_SUB_USAGE_ACTIVE_TIMEOUT:
Amith Yamasani3154dcf2018-03-27 18:24:04 -0700979 sb.append("-at");
Amith Yamasani119be9a2018-02-18 22:23:00 -0800980 break;
981 case REASON_SUB_USAGE_SYNC_ADAPTER:
Amith Yamasani3154dcf2018-03-27 18:24:04 -0700982 sb.append("-sa");
Amith Yamasani119be9a2018-02-18 22:23:00 -0800983 break;
Amith Yamasani80c4be82018-03-26 10:54:04 -0700984 case REASON_SUB_USAGE_SLICE_PINNED:
Makoto Onukid5f25d22018-05-22 16:02:17 -0700985 sb.append("-lp");
Amith Yamasani80c4be82018-03-26 10:54:04 -0700986 break;
987 case REASON_SUB_USAGE_SLICE_PINNED_PRIV:
Makoto Onukid5f25d22018-05-22 16:02:17 -0700988 sb.append("-lv");
989 break;
990 case REASON_SUB_USAGE_EXEMPTED_SYNC_SCHEDULED_NON_DOZE:
991 sb.append("-en");
992 break;
993 case REASON_SUB_USAGE_EXEMPTED_SYNC_SCHEDULED_DOZE:
994 sb.append("-ed");
Amith Yamasani80c4be82018-03-26 10:54:04 -0700995 break;
Makoto Onuki75ad2492018-03-28 14:42:42 -0700996 case REASON_SUB_USAGE_EXEMPTED_SYNC_START:
Makoto Onukid5f25d22018-05-22 16:02:17 -0700997 sb.append("-es");
Makoto Onuki75ad2492018-03-28 14:42:42 -0700998 break;
Michael Wachenschwanzc3295202019-02-20 17:19:52 -0800999 case REASON_SUB_USAGE_UNEXEMPTED_SYNC_SCHEDULED:
1000 sb.append("-uss");
1001 break;
Amith Yamasani119be9a2018-02-18 22:23:00 -08001002 }
1003 break;
1004 }
1005 return sb.toString();
1006 }
1007
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08001008 /** @hide */
1009 public static String usageSourceToString(int usageSource) {
1010 switch (usageSource) {
1011 case USAGE_SOURCE_TASK_ROOT_ACTIVITY:
1012 return "TASK_ROOT_ACTIVITY";
1013 case USAGE_SOURCE_CURRENT_ACTIVITY:
1014 return "CURRENT_ACTIVITY";
1015 default:
1016 StringBuilder sb = new StringBuilder();
1017 sb.append("UNKNOWN(");
1018 sb.append(usageSource);
1019 sb.append(")");
1020 return sb.toString();
1021 }
1022 }
1023
Amith Yamasanie8789312017-12-10 14:34:26 -08001024 /**
1025 * {@hide}
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001026 * Temporarily whitelist the specified app for a short duration. This is to allow an app
1027 * receiving a high priority message to be able to access the network and acquire wakelocks
1028 * even if the device is in power-save mode or the app is currently considered inactive.
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001029 * @param packageName The package name of the app to whitelist.
1030 * @param duration Duration to whitelist the app for, in milliseconds. It is recommended that
1031 * this be limited to 10s of seconds. Requested duration will be clamped to a few minutes.
1032 * @param user The user for whom the package should be whitelisted. Passing in a user that is
1033 * not the same as the caller's process will require the INTERACT_ACROSS_USERS permission.
1034 * @see #isAppInactive(String)
1035 */
1036 @SystemApi
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -06001037 @RequiresPermission(android.Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST)
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001038 public void whitelistAppTemporarily(String packageName, long duration, UserHandle user) {
1039 try {
1040 mService.whitelistAppTemporarily(packageName, duration, user.getIdentifier());
1041 } catch (RemoteException re) {
Amith Yamasanifd44f272018-05-14 14:47:19 -07001042 throw re.rethrowFromSystemServer();
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001043 }
1044 }
Amith Yamasani4ec63682016-02-19 12:55:27 -08001045
1046 /**
1047 * Inform usage stats that the carrier privileged apps access rules have changed.
1048 * @hide
1049 */
1050 public void onCarrierPrivilegedAppsChanged() {
1051 try {
1052 mService.onCarrierPrivilegedAppsChanged();
1053 } catch (RemoteException re) {
Amith Yamasanifd44f272018-05-14 14:47:19 -07001054 throw re.rethrowFromSystemServer();
Amith Yamasani4ec63682016-02-19 12:55:27 -08001055 }
1056 }
Kang Li53b43142016-11-14 14:38:25 -08001057
1058 /**
1059 * Reports a Chooser action to the UsageStatsManager.
1060 *
1061 * @param packageName The package name of the app that is selected.
1062 * @param userId The user id of who makes the selection.
1063 * @param contentType The type of the content, e.g., Image, Video, App.
1064 * @param annotations The annotations of the content, e.g., Game, Selfie.
1065 * @param action The action type of Intent that invokes ChooserActivity.
1066 * {@link UsageEvents}
1067 * @hide
1068 */
1069 public void reportChooserSelection(String packageName, int userId, String contentType,
1070 String[] annotations, String action) {
1071 try {
1072 mService.reportChooserSelection(packageName, userId, contentType, annotations, action);
1073 } catch (RemoteException re) {
1074 }
1075 }
Adam Lesinski0debc9a2014-07-16 19:09:13 -07001076}