UsageStatsManager.java revision 3154dcf94a4f451d2b32607b30cdd070e61bd2ae
1/** 2 * Copyright (C) 2014 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not 5 * use this file except in compliance with the License. You may obtain a copy 6 * of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 * License for the specific language governing permissions and limitations 14 * under the License. 15 */ 16 17package android.app.usage; 18 19import android.annotation.IntDef; 20import android.annotation.NonNull; 21import android.annotation.RequiresPermission; 22import android.annotation.SystemApi; 23import android.annotation.SystemService; 24import android.app.PendingIntent; 25import android.content.Context; 26import android.content.pm.ParceledListSlice; 27import android.os.RemoteException; 28import android.os.UserHandle; 29import android.util.ArrayMap; 30 31import java.lang.annotation.Retention; 32import java.lang.annotation.RetentionPolicy; 33import java.util.ArrayList; 34import java.util.Collections; 35import java.util.List; 36import java.util.Map; 37import java.util.concurrent.TimeUnit; 38 39/** 40 * Provides access to device usage history and statistics. Usage data is aggregated into 41 * time intervals: days, weeks, months, and years. 42 * <p /> 43 * When requesting usage data since a particular time, the request might look something like this: 44 * <pre> 45 * PAST REQUEST_TIME TODAY FUTURE 46 * ————————————————————————————||———————————————————————————¦-----------------------| 47 * YEAR || ¦ | 48 * ————————————————————————————||———————————————————————————¦-----------------------| 49 * MONTH | || MONTH ¦ | 50 * ——————————————————|—————————||———————————————————————————¦-----------------------| 51 * | WEEK | WEEK|| | WEEK | WE¦EK | WEEK | 52 * ————————————————————————————||———————————————————|———————¦-----------------------| 53 * || |DAY|DAY|DAY|DAY¦DAY|DAY|DAY|DAY|DAY|DAY| 54 * ————————————————————————————||———————————————————————————¦-----------------------| 55 * </pre> 56 * A request for data in the middle of a time interval will include that interval. 57 * <p/> 58 * <b>NOTE:</b> Most methods on this API require the permission 59 * android.permission.PACKAGE_USAGE_STATS. However, declaring the permission implies intention to 60 * use the API and the user of the device still needs to grant permission through the Settings 61 * application. 62 * See {@link android.provider.Settings#ACTION_USAGE_ACCESS_SETTINGS}. 63 * Methods which only return the information for the calling package do not require this permission. 64 * E.g. {@link #getAppStandbyBucket()} and {@link #queryEventsForSelf(long, long)}. 65 */ 66@SystemService(Context.USAGE_STATS_SERVICE) 67public final class UsageStatsManager { 68 69 /** 70 * An interval type that spans a day. See {@link #queryUsageStats(int, long, long)}. 71 */ 72 public static final int INTERVAL_DAILY = 0; 73 74 /** 75 * An interval type that spans a week. See {@link #queryUsageStats(int, long, long)}. 76 */ 77 public static final int INTERVAL_WEEKLY = 1; 78 79 /** 80 * An interval type that spans a month. See {@link #queryUsageStats(int, long, long)}. 81 */ 82 public static final int INTERVAL_MONTHLY = 2; 83 84 /** 85 * An interval type that spans a year. See {@link #queryUsageStats(int, long, long)}. 86 */ 87 public static final int INTERVAL_YEARLY = 3; 88 89 /** 90 * An interval type that will use the best fit interval for the given time range. 91 * See {@link #queryUsageStats(int, long, long)}. 92 */ 93 public static final int INTERVAL_BEST = 4; 94 95 /** 96 * The number of available intervals. Does not include {@link #INTERVAL_BEST}, since it 97 * is a pseudo interval (it actually selects a real interval). 98 * {@hide} 99 */ 100 public static final int INTERVAL_COUNT = 4; 101 102 103 /** 104 * The app is whitelisted for some reason and the bucket cannot be changed. 105 * {@hide} 106 */ 107 @SystemApi 108 public static final int STANDBY_BUCKET_EXEMPTED = 5; 109 110 /** 111 * The app was used very recently, currently in use or likely to be used very soon. Standby 112 * bucket values that are ≤ {@link #STANDBY_BUCKET_ACTIVE} will not be throttled by the 113 * system while they are in this bucket. Buckets > {@link #STANDBY_BUCKET_ACTIVE} will most 114 * likely be restricted in some way. For instance, jobs and alarms may be deferred. 115 * @see #getAppStandbyBucket() 116 */ 117 public static final int STANDBY_BUCKET_ACTIVE = 10; 118 119 /** 120 * The app was used recently and/or likely to be used in the next few hours. Restrictions will 121 * apply to these apps, such as deferral of jobs and alarms. 122 * @see #getAppStandbyBucket() 123 */ 124 public static final int STANDBY_BUCKET_WORKING_SET = 20; 125 126 /** 127 * The app was used in the last few days and/or likely to be used in the next few days. 128 * Restrictions will apply to these apps, such as deferral of jobs and alarms. The delays may be 129 * greater than for apps in higher buckets (lower bucket value). Bucket values > 130 * {@link #STANDBY_BUCKET_FREQUENT} may additionally have network access limited. 131 * @see #getAppStandbyBucket() 132 */ 133 public static final int STANDBY_BUCKET_FREQUENT = 30; 134 135 /** 136 * The app has not be used for several days and/or is unlikely to be used for several days. 137 * Apps in this bucket will have the most restrictions, including network restrictions, except 138 * during certain short periods (at a minimum, once a day) when they are allowed to execute 139 * jobs, access the network, etc. 140 * @see #getAppStandbyBucket() 141 */ 142 public static final int STANDBY_BUCKET_RARE = 40; 143 144 /** 145 * The app has never been used. 146 * {@hide} 147 */ 148 @SystemApi 149 public static final int STANDBY_BUCKET_NEVER = 50; 150 151 /** @hide */ 152 public static final int REASON_MAIN_MASK = 0xFF00; 153 /** @hide */ 154 public static final int REASON_MAIN_DEFAULT = 0x0100; 155 /** @hide */ 156 public static final int REASON_MAIN_TIMEOUT = 0x0200; 157 /** @hide */ 158 public static final int REASON_MAIN_USAGE = 0x0300; 159 /** @hide */ 160 public static final int REASON_MAIN_FORCED = 0x0400; 161 /** @hide */ 162 public static final int REASON_MAIN_PREDICTED = 0x0500; 163 164 /** @hide */ 165 public static final int REASON_SUB_MASK = 0x00FF; 166 /** @hide */ 167 public static final int REASON_SUB_USAGE_SYSTEM_INTERACTION = 0x0001; 168 /** @hide */ 169 public static final int REASON_SUB_USAGE_NOTIFICATION_SEEN = 0x0002; 170 /** @hide */ 171 public static final int REASON_SUB_USAGE_USER_INTERACTION = 0x0003; 172 /** @hide */ 173 public static final int REASON_SUB_USAGE_MOVE_TO_FOREGROUND = 0x0004; 174 /** @hide */ 175 public static final int REASON_SUB_USAGE_MOVE_TO_BACKGROUND = 0x0005; 176 /** @hide */ 177 public static final int REASON_SUB_USAGE_SYSTEM_UPDATE = 0x0006; 178 /** @hide */ 179 public static final int REASON_SUB_USAGE_ACTIVE_TIMEOUT = 0x0007; 180 /** @hide */ 181 public static final int REASON_SUB_USAGE_SYNC_ADAPTER = 0x0008; 182 183 /** @hide */ 184 public static final int REASON_SUB_PREDICTED_RESTORED = 0x0001; 185 186 /** @hide */ 187 @IntDef(flag = false, prefix = { "STANDBY_BUCKET_" }, value = { 188 STANDBY_BUCKET_EXEMPTED, 189 STANDBY_BUCKET_ACTIVE, 190 STANDBY_BUCKET_WORKING_SET, 191 STANDBY_BUCKET_FREQUENT, 192 STANDBY_BUCKET_RARE, 193 STANDBY_BUCKET_NEVER, 194 }) 195 @Retention(RetentionPolicy.SOURCE) 196 public @interface StandbyBuckets {} 197 198 /** 199 * Observer id of the registered observer for the group of packages that reached the usage 200 * time limit. Included as an extra in the PendingIntent that was registered. 201 * @hide 202 */ 203 @SystemApi 204 public static final String EXTRA_OBSERVER_ID = "android.app.usage.extra.OBSERVER_ID"; 205 206 /** 207 * Original time limit in milliseconds specified by the registered observer for the group of 208 * packages that reached the usage time limit. Included as an extra in the PendingIntent that 209 * was registered. 210 * @hide 211 */ 212 @SystemApi 213 public static final String EXTRA_TIME_LIMIT = "android.app.usage.extra.TIME_LIMIT"; 214 215 /** 216 * Actual usage time in milliseconds for the group of packages that reached the specified time 217 * limit. Included as an extra in the PendingIntent that was registered. 218 * @hide 219 */ 220 @SystemApi 221 public static final String EXTRA_TIME_USED = "android.app.usage.extra.TIME_USED"; 222 223 private static final UsageEvents sEmptyResults = new UsageEvents(); 224 225 private final Context mContext; 226 private final IUsageStatsManager mService; 227 228 /** 229 * {@hide} 230 */ 231 public UsageStatsManager(Context context, IUsageStatsManager service) { 232 mContext = context; 233 mService = service; 234 } 235 236 /** 237 * Gets application usage stats for the given time range, aggregated by the specified interval. 238 * <p>The returned list will contain a {@link UsageStats} object for each package that 239 * has data for an interval that is a subset of the time range given. To illustrate:</p> 240 * <pre> 241 * intervalType = INTERVAL_YEARLY 242 * beginTime = 2013 243 * endTime = 2015 (exclusive) 244 * 245 * Results: 246 * 2013 - com.example.alpha 247 * 2013 - com.example.beta 248 * 2014 - com.example.alpha 249 * 2014 - com.example.beta 250 * 2014 - com.example.charlie 251 * </pre> 252 * 253 * <p> The caller must have {@link android.Manifest.permission#PACKAGE_USAGE_STATS} </p> 254 * 255 * @param intervalType The time interval by which the stats are aggregated. 256 * @param beginTime The inclusive beginning of the range of stats to include in the results. 257 * @param endTime The exclusive end of the range of stats to include in the results. 258 * @return A list of {@link UsageStats} 259 * 260 * @see #INTERVAL_DAILY 261 * @see #INTERVAL_WEEKLY 262 * @see #INTERVAL_MONTHLY 263 * @see #INTERVAL_YEARLY 264 * @see #INTERVAL_BEST 265 */ 266 public List<UsageStats> queryUsageStats(int intervalType, long beginTime, long endTime) { 267 try { 268 @SuppressWarnings("unchecked") 269 ParceledListSlice<UsageStats> slice = mService.queryUsageStats(intervalType, beginTime, 270 endTime, mContext.getOpPackageName()); 271 if (slice != null) { 272 return slice.getList(); 273 } 274 } catch (RemoteException e) { 275 // fallthrough and return the empty list. 276 } 277 return Collections.emptyList(); 278 } 279 280 /** 281 * Gets the hardware configurations the device was in for the given time range, aggregated by 282 * the specified interval. The results are ordered as in 283 * {@link #queryUsageStats(int, long, long)}. 284 * <p> The caller must have {@link android.Manifest.permission#PACKAGE_USAGE_STATS} </p> 285 * 286 * @param intervalType The time interval by which the stats are aggregated. 287 * @param beginTime The inclusive beginning of the range of stats to include in the results. 288 * @param endTime The exclusive end of the range of stats to include in the results. 289 * @return A list of {@link ConfigurationStats} 290 */ 291 public List<ConfigurationStats> queryConfigurations(int intervalType, long beginTime, 292 long endTime) { 293 try { 294 @SuppressWarnings("unchecked") 295 ParceledListSlice<ConfigurationStats> slice = mService.queryConfigurationStats( 296 intervalType, beginTime, endTime, mContext.getOpPackageName()); 297 if (slice != null) { 298 return slice.getList(); 299 } 300 } catch (RemoteException e) { 301 // fallthrough and return the empty list. 302 } 303 return Collections.emptyList(); 304 } 305 306 /** 307 * Gets aggregated event stats for the given time range, aggregated by the specified interval. 308 * <p>The returned list will contain a {@link EventStats} object for each event type that 309 * is being aggregated and has data for an interval that is a subset of the time range given. 310 * 311 * <p>The current event types that will be aggregated here are:</p> 312 * <ul> 313 * <li>{@link UsageEvents.Event#SCREEN_INTERACTIVE}</li> 314 * <li>{@link UsageEvents.Event#SCREEN_NON_INTERACTIVE}</li> 315 * </ul> 316 * 317 * <p> The caller must have {@link android.Manifest.permission#PACKAGE_USAGE_STATS} </p> 318 * 319 * @param intervalType The time interval by which the stats are aggregated. 320 * @param beginTime The inclusive beginning of the range of stats to include in the results. 321 * @param endTime The exclusive end of the range of stats to include in the results. 322 * @return A list of {@link EventStats} 323 * 324 * @see #INTERVAL_DAILY 325 * @see #INTERVAL_WEEKLY 326 * @see #INTERVAL_MONTHLY 327 * @see #INTERVAL_YEARLY 328 * @see #INTERVAL_BEST 329 */ 330 public List<EventStats> queryEventStats(int intervalType, long beginTime, long endTime) { 331 try { 332 @SuppressWarnings("unchecked") 333 ParceledListSlice<EventStats> slice = mService.queryEventStats(intervalType, beginTime, 334 endTime, mContext.getOpPackageName()); 335 if (slice != null) { 336 return slice.getList(); 337 } 338 } catch (RemoteException e) { 339 // fallthrough and return the empty list. 340 } 341 return Collections.emptyList(); 342 } 343 344 /** 345 * Query for events in the given time range. Events are only kept by the system for a few 346 * days. 347 * <p> The caller must have {@link android.Manifest.permission#PACKAGE_USAGE_STATS} </p> 348 * 349 * @param beginTime The inclusive beginning of the range of events to include in the results. 350 * @param endTime The exclusive end of the range of events to include in the results. 351 * @return A {@link UsageEvents}. 352 */ 353 public UsageEvents queryEvents(long beginTime, long endTime) { 354 try { 355 UsageEvents iter = mService.queryEvents(beginTime, endTime, 356 mContext.getOpPackageName()); 357 if (iter != null) { 358 return iter; 359 } 360 } catch (RemoteException e) { 361 // fallthrough and return empty result. 362 } 363 return sEmptyResults; 364 } 365 366 /** 367 * Like {@link #queryEvents(long, long)}, but only returns events for the calling package. 368 * 369 * @param beginTime The inclusive beginning of the range of events to include in the results. 370 * @param endTime The exclusive end of the range of events to include in the results. 371 * @return A {@link UsageEvents} object. 372 * 373 * @see #queryEvents(long, long) 374 */ 375 public UsageEvents queryEventsForSelf(long beginTime, long endTime) { 376 try { 377 final UsageEvents events = mService.queryEventsForPackage(beginTime, endTime, 378 mContext.getOpPackageName()); 379 if (events != null) { 380 return events; 381 } 382 } catch (RemoteException e) { 383 // fallthrough 384 } 385 return sEmptyResults; 386 } 387 388 /** 389 * A convenience method that queries for all stats in the given range (using the best interval 390 * for that range), merges the resulting data, and keys it by package name. 391 * See {@link #queryUsageStats(int, long, long)}. 392 * <p> The caller must have {@link android.Manifest.permission#PACKAGE_USAGE_STATS} </p> 393 * 394 * @param beginTime The inclusive beginning of the range of stats to include in the results. 395 * @param endTime The exclusive end of the range of stats to include in the results. 396 * @return A {@link java.util.Map} keyed by package name 397 */ 398 public Map<String, UsageStats> queryAndAggregateUsageStats(long beginTime, long endTime) { 399 List<UsageStats> stats = queryUsageStats(INTERVAL_BEST, beginTime, endTime); 400 if (stats.isEmpty()) { 401 return Collections.emptyMap(); 402 } 403 404 ArrayMap<String, UsageStats> aggregatedStats = new ArrayMap<>(); 405 final int statCount = stats.size(); 406 for (int i = 0; i < statCount; i++) { 407 UsageStats newStat = stats.get(i); 408 UsageStats existingStat = aggregatedStats.get(newStat.getPackageName()); 409 if (existingStat == null) { 410 aggregatedStats.put(newStat.mPackageName, newStat); 411 } else { 412 existingStat.add(newStat); 413 } 414 } 415 return aggregatedStats; 416 } 417 418 /** 419 * Returns whether the specified app is currently considered inactive. This will be true if the 420 * app hasn't been used directly or indirectly for a period of time defined by the system. This 421 * could be of the order of several hours or days. 422 * @param packageName The package name of the app to query 423 * @return whether the app is currently considered inactive 424 */ 425 public boolean isAppInactive(String packageName) { 426 try { 427 return mService.isAppInactive(packageName, mContext.getUserId()); 428 } catch (RemoteException e) { 429 // fall through and return default 430 } 431 return false; 432 } 433 434 /** 435 * {@hide} 436 */ 437 public void setAppInactive(String packageName, boolean inactive) { 438 try { 439 mService.setAppInactive(packageName, inactive, mContext.getUserId()); 440 } catch (RemoteException e) { 441 // fall through 442 } 443 } 444 445 /** 446 * Returns the current standby bucket of the calling app. The system determines the standby 447 * state of the app based on app usage patterns. Standby buckets determine how much an app will 448 * be restricted from running background tasks such as jobs and alarms. 449 * <p>Restrictions increase progressively from {@link #STANDBY_BUCKET_ACTIVE} to 450 * {@link #STANDBY_BUCKET_RARE}, with {@link #STANDBY_BUCKET_ACTIVE} being the least 451 * restrictive. The battery level of the device might also affect the restrictions. 452 * <p>Apps in buckets ≤ {@link #STANDBY_BUCKET_ACTIVE} have no standby restrictions imposed. 453 * Apps in buckets > {@link #STANDBY_BUCKET_FREQUENT} may have network access restricted when 454 * running in the background. 455 * <p>The standby state of an app can change at any time either due to a user interaction or a 456 * system interaction or some algorithm determining that the app can be restricted for a period 457 * of time before the user has a need for it. 458 * <p>You can also query the recent history of standby bucket changes by calling 459 * {@link #queryEventsForSelf(long, long)} and searching for 460 * {@link UsageEvents.Event#STANDBY_BUCKET_CHANGED}. 461 * 462 * @return the current standby bucket of the calling app. One of STANDBY_BUCKET_* constants. 463 */ 464 public @StandbyBuckets int getAppStandbyBucket() { 465 try { 466 return mService.getAppStandbyBucket(mContext.getOpPackageName(), 467 mContext.getOpPackageName(), 468 mContext.getUserId()); 469 } catch (RemoteException e) { 470 } 471 return STANDBY_BUCKET_ACTIVE; 472 } 473 474 /** 475 * {@hide} 476 * Returns the current standby bucket of the specified app. The caller must hold the permission 477 * android.permission.PACKAGE_USAGE_STATS. 478 * @param packageName the package for which to fetch the current standby bucket. 479 */ 480 @SystemApi 481 @RequiresPermission(android.Manifest.permission.PACKAGE_USAGE_STATS) 482 public @StandbyBuckets int getAppStandbyBucket(String packageName) { 483 try { 484 return mService.getAppStandbyBucket(packageName, mContext.getOpPackageName(), 485 mContext.getUserId()); 486 } catch (RemoteException e) { 487 } 488 return STANDBY_BUCKET_ACTIVE; 489 } 490 491 /** 492 * {@hide} 493 * Changes an app's standby bucket to the provided value. The caller can only set the standby 494 * bucket for a different app than itself. 495 * @param packageName the package name of the app to set the bucket for. A SecurityException 496 * will be thrown if the package name is that of the caller. 497 * @param bucket the standby bucket to set it to, which should be one of STANDBY_BUCKET_*. 498 * Setting a standby bucket outside of the range of STANDBY_BUCKET_ACTIVE to 499 * STANDBY_BUCKET_NEVER will result in a SecurityException. 500 */ 501 @SystemApi 502 @RequiresPermission(android.Manifest.permission.CHANGE_APP_IDLE_STATE) 503 public void setAppStandbyBucket(String packageName, @StandbyBuckets int bucket) { 504 try { 505 mService.setAppStandbyBucket(packageName, bucket, mContext.getUserId()); 506 } catch (RemoteException e) { 507 // Nothing to do 508 } 509 } 510 511 /** 512 * {@hide} 513 * Returns the current standby bucket of every app that has a bucket assigned to it. 514 * The caller must hold the permission android.permission.PACKAGE_USAGE_STATS. The key of the 515 * returned Map is the package name and the value is the bucket assigned to the package. 516 * @see #getAppStandbyBucket() 517 */ 518 @SystemApi 519 @RequiresPermission(android.Manifest.permission.PACKAGE_USAGE_STATS) 520 public Map<String, Integer> getAppStandbyBuckets() { 521 try { 522 final ParceledListSlice<AppStandbyInfo> slice = mService.getAppStandbyBuckets( 523 mContext.getOpPackageName(), mContext.getUserId()); 524 final List<AppStandbyInfo> bucketList = slice.getList(); 525 final ArrayMap<String, Integer> bucketMap = new ArrayMap<>(); 526 final int n = bucketList.size(); 527 for (int i = 0; i < n; i++) { 528 final AppStandbyInfo bucketInfo = bucketList.get(i); 529 bucketMap.put(bucketInfo.mPackageName, bucketInfo.mStandbyBucket); 530 } 531 return bucketMap; 532 } catch (RemoteException e) { 533 } 534 return Collections.EMPTY_MAP; 535 } 536 537 /** 538 * {@hide} 539 * Changes the app standby bucket for multiple apps at once. The Map is keyed by the package 540 * name and the value is one of STANDBY_BUCKET_*. 541 * @param appBuckets a map of package name to bucket value. 542 */ 543 @SystemApi 544 @RequiresPermission(android.Manifest.permission.CHANGE_APP_IDLE_STATE) 545 public void setAppStandbyBuckets(Map<String, Integer> appBuckets) { 546 if (appBuckets == null) { 547 return; 548 } 549 final List<AppStandbyInfo> bucketInfoList = new ArrayList<>(appBuckets.size()); 550 for (Map.Entry<String, Integer> bucketEntry : appBuckets.entrySet()) { 551 bucketInfoList.add(new AppStandbyInfo(bucketEntry.getKey(), bucketEntry.getValue())); 552 } 553 final ParceledListSlice<AppStandbyInfo> slice = new ParceledListSlice<>(bucketInfoList); 554 try { 555 mService.setAppStandbyBuckets(slice, mContext.getUserId()); 556 } catch (RemoteException e) { 557 } 558 } 559 560 /** 561 * @hide 562 * Register an app usage limit observer that receives a callback on the provided intent when 563 * the sum of usages of apps in the packages array exceeds the {@code timeLimit} specified. The 564 * observer will automatically be unregistered when the time limit is reached and the intent 565 * is delivered. Registering an {@code observerId} that was already registered will override 566 * the previous one. 567 * @param observerId A unique id associated with the group of apps to be monitored. There can 568 * be multiple groups with common packages and different time limits. 569 * @param packages The list of packages to observe for foreground activity time. Cannot be null 570 * and must include at least one package. 571 * @param timeLimit The total time the set of apps can be in the foreground before the 572 * callbackIntent is delivered. Must be greater than 0. 573 * @param timeUnit The unit for time specified in {@code timeLimit}. Cannot be null. 574 * @param callbackIntent The PendingIntent that will be dispatched when the time limit is 575 * exceeded by the group of apps. The delivered Intent will also contain 576 * the extras {@link #EXTRA_OBSERVER_ID}, {@link #EXTRA_TIME_LIMIT} and 577 * {@link #EXTRA_TIME_USED}. Cannot be null. 578 * @throws SecurityException if the caller doesn't have the OBSERVE_APP_USAGE permission or 579 * is not the profile owner of this user. 580 */ 581 @SystemApi 582 @RequiresPermission(android.Manifest.permission.OBSERVE_APP_USAGE) 583 public void registerAppUsageObserver(int observerId, @NonNull String[] packages, long timeLimit, 584 @NonNull TimeUnit timeUnit, @NonNull PendingIntent callbackIntent) { 585 try { 586 mService.registerAppUsageObserver(observerId, packages, timeUnit.toMillis(timeLimit), 587 callbackIntent, mContext.getOpPackageName()); 588 } catch (RemoteException e) { 589 } 590 } 591 592 /** 593 * @hide 594 * Unregister the app usage observer specified by the {@code observerId}. This will only apply 595 * to any observer registered by this application. Unregistering an observer that was already 596 * unregistered or never registered will have no effect. 597 * @param observerId The id of the observer that was previously registered. 598 * @throws SecurityException if the caller doesn't have the OBSERVE_APP_USAGE permission or is 599 * not the profile owner of this user. 600 */ 601 @SystemApi 602 @RequiresPermission(android.Manifest.permission.OBSERVE_APP_USAGE) 603 public void unregisterAppUsageObserver(int observerId) { 604 try { 605 mService.unregisterAppUsageObserver(observerId, mContext.getOpPackageName()); 606 } catch (RemoteException e) { 607 } 608 } 609 610 /** @hide */ 611 public static String reasonToString(int standbyReason) { 612 StringBuilder sb = new StringBuilder(); 613 switch (standbyReason & REASON_MAIN_MASK) { 614 case REASON_MAIN_DEFAULT: 615 sb.append("d"); 616 break; 617 case REASON_MAIN_FORCED: 618 sb.append("f"); 619 break; 620 case REASON_MAIN_PREDICTED: 621 sb.append("p"); 622 switch (standbyReason & REASON_SUB_MASK) { 623 case REASON_SUB_PREDICTED_RESTORED: 624 sb.append("-r"); 625 break; 626 } 627 break; 628 case REASON_MAIN_TIMEOUT: 629 sb.append("t"); 630 break; 631 case REASON_MAIN_USAGE: 632 sb.append("u"); 633 switch (standbyReason & REASON_SUB_MASK) { 634 case REASON_SUB_USAGE_SYSTEM_INTERACTION: 635 sb.append("-si"); 636 break; 637 case REASON_SUB_USAGE_NOTIFICATION_SEEN: 638 sb.append("-ns"); 639 break; 640 case REASON_SUB_USAGE_USER_INTERACTION: 641 sb.append("-ui"); 642 break; 643 case REASON_SUB_USAGE_MOVE_TO_FOREGROUND: 644 sb.append("-mf"); 645 break; 646 case REASON_SUB_USAGE_MOVE_TO_BACKGROUND: 647 sb.append("-mb"); 648 break; 649 case REASON_SUB_USAGE_SYSTEM_UPDATE: 650 sb.append("-su"); 651 break; 652 case REASON_SUB_USAGE_ACTIVE_TIMEOUT: 653 sb.append("-at"); 654 break; 655 case REASON_SUB_USAGE_SYNC_ADAPTER: 656 sb.append("-sa"); 657 break; 658 } 659 break; 660 } 661 return sb.toString(); 662 } 663 664 /** 665 * {@hide} 666 * Temporarily whitelist the specified app for a short duration. This is to allow an app 667 * receiving a high priority message to be able to access the network and acquire wakelocks 668 * even if the device is in power-save mode or the app is currently considered inactive. 669 * @param packageName The package name of the app to whitelist. 670 * @param duration Duration to whitelist the app for, in milliseconds. It is recommended that 671 * this be limited to 10s of seconds. Requested duration will be clamped to a few minutes. 672 * @param user The user for whom the package should be whitelisted. Passing in a user that is 673 * not the same as the caller's process will require the INTERACT_ACROSS_USERS permission. 674 * @see #isAppInactive(String) 675 */ 676 @SystemApi 677 @RequiresPermission(android.Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST) 678 public void whitelistAppTemporarily(String packageName, long duration, UserHandle user) { 679 try { 680 mService.whitelistAppTemporarily(packageName, duration, user.getIdentifier()); 681 } catch (RemoteException re) { 682 } 683 } 684 685 /** 686 * Inform usage stats that the carrier privileged apps access rules have changed. 687 * @hide 688 */ 689 public void onCarrierPrivilegedAppsChanged() { 690 try { 691 mService.onCarrierPrivilegedAppsChanged(); 692 } catch (RemoteException re) { 693 } 694 } 695 696 /** 697 * Reports a Chooser action to the UsageStatsManager. 698 * 699 * @param packageName The package name of the app that is selected. 700 * @param userId The user id of who makes the selection. 701 * @param contentType The type of the content, e.g., Image, Video, App. 702 * @param annotations The annotations of the content, e.g., Game, Selfie. 703 * @param action The action type of Intent that invokes ChooserActivity. 704 * {@link UsageEvents} 705 * @hide 706 */ 707 public void reportChooserSelection(String packageName, int userId, String contentType, 708 String[] annotations, String action) { 709 try { 710 mService.reportChooserSelection(packageName, userId, contentType, annotations, action); 711 } catch (RemoteException re) { 712 } 713 } 714} 715