1 /** 2 * Copyright (C) 2014 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not 5 * use this file except in compliance with the License. You may obtain a copy 6 * of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 * License for the specific language governing permissions and limitations 14 * under the License. 15 */ 16 17 package android.app.usage; 18 19 import android.annotation.CurrentTimeMillisLong; 20 import android.annotation.ElapsedRealtimeLong; 21 import android.annotation.NonNull; 22 import android.annotation.Nullable; 23 import android.annotation.UserIdInt; 24 import android.app.ActivityManager.ProcessState; 25 import android.app.usage.UsageStatsManager.StandbyBuckets; 26 import android.content.ComponentName; 27 import android.content.LocusId; 28 import android.content.res.Configuration; 29 import android.os.IBinder; 30 import android.os.PersistableBundle; 31 import android.os.SystemClock; 32 import android.os.UserHandle; 33 import android.os.UserManager; 34 35 import java.util.List; 36 import java.util.Set; 37 38 /** 39 * UsageStatsManager local system service interface. 40 * 41 * {@hide} Only for use within the system server. 42 */ 43 public abstract class UsageStatsManagerInternal { 44 45 /** 46 * Reports an event to the UsageStatsManager. <br/> 47 * <em>Note: Starting from {@link android.os.Build.VERSION_CODES#R Android R}, if the user's 48 * device is not in an unlocked state (as defined by {@link UserManager#isUserUnlocked()}), 49 * then this event will be added to a queue and processed once the device is unlocked.</em> 50 * 51 * @param component The component for which this event occurred. 52 * @param userId The user id to which the component belongs to. 53 * @param eventType The event that occurred. Valid values can be found at 54 * {@link UsageEvents} 55 * @param instanceId For activity, hashCode of ActivityRecord's appToken. 56 * For non-activity, it is not used. 57 * @param taskRoot For activity, the name of the package at the root of the task 58 * For non-activity, it is not used. 59 */ reportEvent(ComponentName component, @UserIdInt int userId, int eventType, int instanceId, ComponentName taskRoot)60 public abstract void reportEvent(ComponentName component, @UserIdInt int userId, int eventType, 61 int instanceId, ComponentName taskRoot); 62 63 /** 64 * Reports an event to the UsageStatsManager. <br/> 65 * <em>Note: Starting from {@link android.os.Build.VERSION_CODES#R Android R}, if the user's 66 * device is not in an unlocked state (as defined by {@link UserManager#isUserUnlocked()}), 67 * then this event will be added to a queue and processed once the device is unlocked.</em> 68 * 69 * @param packageName The package for which this event occurred. 70 * @param userId The user id to which the component belongs to. 71 * @param eventType The event that occurred. Valid values can be found at 72 * {@link UsageEvents} 73 */ reportEvent(String packageName, @UserIdInt int userId, int eventType)74 public abstract void reportEvent(String packageName, @UserIdInt int userId, int eventType); 75 76 /** 77 * Reports an event to the UsageStatsManager for all users. <br/> 78 * <em>Note: Starting from {@link android.os.Build.VERSION_CODES#R Android R}, if the user's 79 * device is not in an unlocked state (as defined by {@link UserManager#isUserUnlocked()}), 80 * then this event will be added to a queue and processed once the device is unlocked.</em> 81 * 82 * @param packageName The package for which this event occurred. 83 * @param eventType The event that occurred. Valid values can be found at 84 * {@link UsageEvents} 85 */ reportEventForAllUsers(String packageName, int eventType)86 public abstract void reportEventForAllUsers(String packageName, int eventType); 87 88 /** 89 * Reports a configuration change to the UsageStatsManager. <br/> 90 * <em>Note: Starting from {@link android.os.Build.VERSION_CODES#R Android R}, if the user's 91 * device is not in an unlocked state (as defined by {@link UserManager#isUserUnlocked()}), 92 * then this event will be added to a queue and processed once the device is unlocked.</em> 93 * 94 * @param config The new device configuration. 95 */ reportConfigurationChange(Configuration config, @UserIdInt int userId)96 public abstract void reportConfigurationChange(Configuration config, @UserIdInt int userId); 97 98 /** 99 * Reports that an application has posted an interruptive notification. <br/> 100 * <em>Note: Starting from {@link android.os.Build.VERSION_CODES#R Android R}, if the user's 101 * device is not in an unlocked state (as defined by {@link UserManager#isUserUnlocked()}), 102 * then this event will be added to a queue and processed once the device is unlocked.</em> 103 * 104 * @param packageName The package name of the app that posted the notification 105 * @param channelId The ID of the NotificationChannel to which the notification was posted 106 * @param userId The user in which the notification was posted 107 */ reportInterruptiveNotification(String packageName, String channelId, @UserIdInt int userId)108 public abstract void reportInterruptiveNotification(String packageName, String channelId, 109 @UserIdInt int userId); 110 111 /** 112 * Reports that an action equivalent to a ShortcutInfo is taken by the user. <br/> 113 * <em>Note: Starting from {@link android.os.Build.VERSION_CODES#R Android R}, if the user's 114 * device is not in an unlocked state (as defined by {@link UserManager#isUserUnlocked()}), 115 * then this event will be added to a queue and processed once the device is unlocked.</em> 116 * 117 * @param packageName The package name of the shortcut publisher 118 * @param shortcutId The ID of the shortcut in question 119 * @param userId The user in which the content provider was accessed. 120 * 121 * @see android.content.pm.ShortcutManager#reportShortcutUsed(String) 122 */ reportShortcutUsage(String packageName, String shortcutId, @UserIdInt int userId)123 public abstract void reportShortcutUsage(String packageName, String shortcutId, 124 @UserIdInt int userId); 125 126 /** 127 * Reports that a content provider has been accessed by a foreground app. 128 * @param name The authority of the content provider 129 * @param pkgName The package name of the content provider 130 * @param userId The user in which the content provider was accessed. 131 */ reportContentProviderUsage(String name, String pkgName, @UserIdInt int userId)132 public abstract void reportContentProviderUsage(String name, String pkgName, 133 @UserIdInt int userId); 134 135 136 /** 137 * Reports locusId update for a given activity. 138 * 139 * @param activity The component name of the app. 140 * @param userId The user id of who uses the app. 141 * @param locusId The locusId a unique, stable id that identifies this activity. 142 * @param appToken ActivityRecord's appToken. 143 * {@link UsageEvents} 144 * @hide 145 */ reportLocusUpdate(@onNull ComponentName activity, @UserIdInt int userId, @Nullable LocusId locusId, @NonNull IBinder appToken)146 public abstract void reportLocusUpdate(@NonNull ComponentName activity, @UserIdInt int userId, 147 @Nullable LocusId locusId, @NonNull IBinder appToken); 148 149 /** 150 * Report a user interaction event to UsageStatsManager 151 * 152 * @param pkgName The package for which this user interaction event occurred. 153 * @param userId The user id to which component belongs to. 154 * @param extras The extra details about this user interaction event. 155 * {@link UsageEvents.Event#USER_INTERACTION} 156 * {@link UsageStatsManager#reportUserInteraction(String, int, PersistableBundle)} 157 */ reportUserInteractionEvent(@onNull String pkgName, @UserIdInt int userId, @NonNull PersistableBundle extras)158 public abstract void reportUserInteractionEvent(@NonNull String pkgName, @UserIdInt int userId, 159 @NonNull PersistableBundle extras); 160 161 /** 162 * Prepares the UsageStatsService for shutdown. 163 */ prepareShutdown()164 public abstract void prepareShutdown(); 165 166 /** 167 * When the device power button is long pressed for 3.5 seconds, prepareForPossibleShutdown() 168 * is called. 169 */ prepareForPossibleShutdown()170 public abstract void prepareForPossibleShutdown(); 171 172 /** 173 * Returns true if the app has not been used for a certain amount of time. How much time? 174 * Could be hours, could be days, who knows? 175 * 176 * @param packageName 177 * @param uidForAppId The uid of the app, which will be used for its app id 178 * @param userId 179 * @return 180 */ isAppIdle(String packageName, int uidForAppId, @UserIdInt int userId)181 public abstract boolean isAppIdle(String packageName, int uidForAppId, @UserIdInt int userId); 182 183 /** 184 * Returns the app standby bucket that the app is currently in. This accessor does 185 * <em>not</em> obfuscate instant apps. 186 * 187 * @param packageName 188 * @param userId 189 * @param nowElapsed The current time, in the elapsedRealtime time base 190 * @return the AppStandby bucket code the app currently resides in. If the app is 191 * unknown in the given user, STANDBY_BUCKET_NEVER is returned. 192 */ getAppStandbyBucket(String packageName, @UserIdInt int userId, long nowElapsed)193 @StandbyBuckets public abstract int getAppStandbyBucket(String packageName, 194 @UserIdInt int userId, long nowElapsed); 195 196 /** 197 * Returns all of the uids for a given user where all packages associating with that uid 198 * are in the app idle state -- there are no associated apps that are not idle. This means 199 * all of the returned uids can be safely considered app idle. 200 */ getIdleUidsForUser(@serIdInt int userId)201 public abstract int[] getIdleUidsForUser(@UserIdInt int userId); 202 203 /** Backup/Restore API */ getBackupPayload(@serIdInt int userId, String key)204 public abstract byte[] getBackupPayload(@UserIdInt int userId, String key); 205 206 /** 207 * ? 208 * @param userId 209 * @param key 210 * @param payload 211 */ applyRestoredPayload(@serIdInt int userId, String key, byte[] payload)212 public abstract void applyRestoredPayload(@UserIdInt int userId, String key, byte[] payload); 213 214 /** 215 * Called by DevicePolicyManagerService to inform that a new admin has been added. 216 * 217 * @param packageName the package in which the admin component is part of. 218 * @param userId the userId in which the admin has been added. 219 */ onActiveAdminAdded(String packageName, int userId)220 public abstract void onActiveAdminAdded(String packageName, int userId); 221 222 /** 223 * Called by DevicePolicyManagerService to inform about the active admins in an user. 224 * 225 * @param adminApps the set of active admins in {@param userId} or null if there are none. 226 * @param userId the userId to which the admin apps belong. 227 */ setActiveAdminApps(Set<String> adminApps, int userId)228 public abstract void setActiveAdminApps(Set<String> adminApps, int userId); 229 230 /** 231 * Called by DevicePolicyManagerService to inform about the protected packages for a user. 232 * User control will be disabled for protected packages. 233 * 234 * @param packageNames the set of protected packages for {@code userId}. 235 * @param userId the userId to which the protected packages belong. 236 */ setAdminProtectedPackages(@ullable Set<String> packageNames, @UserIdInt int userId)237 public abstract void setAdminProtectedPackages(@Nullable Set<String> packageNames, 238 @UserIdInt int userId); 239 240 /** 241 * Called by DevicePolicyManagerService during boot to inform that admin data is loaded and 242 * pushed to UsageStatsService. 243 */ onAdminDataAvailable()244 public abstract void onAdminDataAvailable(); 245 246 /** 247 * Return usage stats. 248 * 249 * @param obfuscateInstantApps whether instant app package names need to be obfuscated in the 250 * result. 251 */ queryUsageStatsForUser(@serIdInt int userId, int interval, long beginTime, long endTime, boolean obfuscateInstantApps)252 public abstract List<UsageStats> queryUsageStatsForUser(@UserIdInt int userId, int interval, 253 long beginTime, long endTime, boolean obfuscateInstantApps); 254 255 /** 256 * Returns the events for the user in the given time period. 257 * 258 * @param flags defines the visibility of certain usage events - see flags defined in 259 * {@link UsageEvents}. 260 */ queryEventsForUser(@serIdInt int userId, long beginTime, long endTime, int flags)261 public abstract UsageEvents queryEventsForUser(@UserIdInt int userId, long beginTime, 262 long endTime, int flags); 263 264 /** 265 * Used to persist the last time a job was run for this app, in order to make decisions later 266 * whether a job should be deferred until later. The time passed in should be in elapsed 267 * realtime since boot. 268 * @param packageName the app that executed a job. 269 * @param userId the user associated with the job. 270 * @param elapsedRealtime the time when the job was executed, in elapsed realtime millis since 271 * boot. 272 */ setLastJobRunTime(String packageName, @UserIdInt int userId, long elapsedRealtime)273 public abstract void setLastJobRunTime(String packageName, @UserIdInt int userId, 274 long elapsedRealtime); 275 276 /** Returns the estimated time that the app will be launched, in milliseconds since epoch. */ 277 @CurrentTimeMillisLong getEstimatedPackageLaunchTime(String packageName, @UserIdInt int userId)278 public abstract long getEstimatedPackageLaunchTime(String packageName, @UserIdInt int userId); 279 280 /** 281 * Returns the time in millis since a job was executed for this app, in elapsed realtime 282 * timebase. This value can be larger than the current elapsed realtime if the job was executed 283 * before the device was rebooted. The default value is {@link Long#MAX_VALUE}. 284 * @param packageName the app you're asking about. 285 * @param userId the user associated with the job. 286 * @return the time in millis since a job was last executed for the app, provided it was 287 * indicated here before by a call to {@link #setLastJobRunTime(String, int, long)}. 288 */ getTimeSinceLastJobRun(String packageName, @UserIdInt int userId)289 public abstract long getTimeSinceLastJobRun(String packageName, @UserIdInt int userId); 290 291 /** 292 * Report a few data points about an app's job state at the current time. 293 * 294 * @param packageName the app whose job state is being described 295 * @param userId which user the app is associated with 296 * @param numDeferredJobs the number of pending jobs that were deferred 297 * due to bucketing policy 298 * @param timeSinceLastJobRun number of milliseconds since the last time one of 299 * this app's jobs was executed 300 */ reportAppJobState(String packageName, @UserIdInt int userId, int numDeferredJobs, long timeSinceLastJobRun)301 public abstract void reportAppJobState(String packageName, @UserIdInt int userId, 302 int numDeferredJobs, long timeSinceLastJobRun); 303 304 /** 305 * Report a sync that was scheduled. 306 * 307 * @param packageName name of the package that owns the sync adapter. 308 * @param userId which user the app is associated with 309 * @param exempted is sync app standby exempted 310 */ reportSyncScheduled(String packageName, @UserIdInt int userId, boolean exempted)311 public abstract void reportSyncScheduled(String packageName, @UserIdInt int userId, 312 boolean exempted); 313 314 /** 315 * Report a sync that was scheduled by a foreground app is about to be executed. 316 * 317 * @param packageName name of the package that owns the sync adapter. 318 * @param userId which user the app is associated with 319 */ reportExemptedSyncStart(String packageName, @UserIdInt int userId)320 public abstract void reportExemptedSyncStart(String packageName, @UserIdInt int userId); 321 322 /** 323 * Returns an object describing the app usage limit for the given package which was set via 324 * {@link UsageStatsManager#registerAppUsageLimitObserver}. 325 * If there are multiple limits that apply to the package, the one with the smallest 326 * time remaining will be returned. 327 * 328 * @param packageName name of the package whose app usage limit will be returned 329 * @param user the user associated with the limit 330 * @return an {@link AppUsageLimitData} object describing the app time limit containing 331 * the given package, with the smallest time remaining. 332 */ getAppUsageLimit(String packageName, UserHandle user)333 public abstract AppUsageLimitData getAppUsageLimit(String packageName, UserHandle user); 334 335 /** A class which is used to share the usage limit data for an app or a group of apps. */ 336 public static class AppUsageLimitData { 337 private final long mTotalUsageLimit; 338 private final long mUsageRemaining; 339 AppUsageLimitData(long totalUsageLimit, long usageRemaining)340 public AppUsageLimitData(long totalUsageLimit, long usageRemaining) { 341 this.mTotalUsageLimit = totalUsageLimit; 342 this.mUsageRemaining = usageRemaining; 343 } 344 getTotalUsageLimit()345 public long getTotalUsageLimit() { 346 return mTotalUsageLimit; 347 } getUsageRemaining()348 public long getUsageRemaining() { 349 return mUsageRemaining; 350 } 351 } 352 353 /** 354 * Called by {@link com.android.server.usage.UsageStatsIdleService} when the device is idle to 355 * prune usage stats data for uninstalled packages. 356 * 357 * @param userId the user associated with the job 358 * @return {@code true} if the pruning was successful, {@code false} otherwise 359 */ pruneUninstalledPackagesData(@serIdInt int userId)360 public abstract boolean pruneUninstalledPackagesData(@UserIdInt int userId); 361 362 /** 363 * Called by {@link com.android.server.usage.UsageStatsIdleService} between 24 to 48 hours of 364 * when the user is first unlocked to update the usage stats package mappings data that might 365 * be stale or have existed from a restore and belongs to packages that are not installed for 366 * this user anymore. 367 * 368 * @param userId The user to update 369 * @return {@code true} if the updating was successful, {@code false} otherwise 370 */ updatePackageMappingsData(@serIdInt int userId)371 public abstract boolean updatePackageMappingsData(@UserIdInt int userId); 372 373 /** 374 * Listener interface for usage events. 375 */ 376 public interface UsageEventListener { 377 /** Callback to inform listeners of a new usage event. */ onUsageEvent(@serIdInt int userId, @NonNull UsageEvents.Event event)378 void onUsageEvent(@UserIdInt int userId, @NonNull UsageEvents.Event event); 379 } 380 381 /** Register a listener that will be notified of every new usage event. */ registerListener(@onNull UsageEventListener listener)382 public abstract void registerListener(@NonNull UsageEventListener listener); 383 384 /** Unregister a listener from being notified of every new usage event. */ unregisterListener(@onNull UsageEventListener listener)385 public abstract void unregisterListener(@NonNull UsageEventListener listener); 386 387 /** 388 * Listener interface for estimated launch time changes. 389 */ 390 public interface EstimatedLaunchTimeChangedListener { 391 /** Callback to inform listeners when estimated launch times change. */ onEstimatedLaunchTimeChanged(@serIdInt int userId, @NonNull String packageName, @CurrentTimeMillisLong long newEstimatedLaunchTime)392 void onEstimatedLaunchTimeChanged(@UserIdInt int userId, @NonNull String packageName, 393 @CurrentTimeMillisLong long newEstimatedLaunchTime); 394 } 395 396 /** Register a listener that will be notified of every estimated launch time change. */ registerLaunchTimeChangedListener( @onNull EstimatedLaunchTimeChangedListener listener)397 public abstract void registerLaunchTimeChangedListener( 398 @NonNull EstimatedLaunchTimeChangedListener listener); 399 400 /** Unregister a listener from being notified of every estimated launch time change. */ unregisterLaunchTimeChangedListener( @onNull EstimatedLaunchTimeChangedListener listener)401 public abstract void unregisterLaunchTimeChangedListener( 402 @NonNull EstimatedLaunchTimeChangedListener listener); 403 404 /** 405 * Reports a broadcast dispatched event to the UsageStatsManager. 406 * 407 * @param sourceUid uid of the package that sent the broadcast. 408 * @param targetPackage name of the package that the broadcast is targeted to. 409 * @param targetUser user that {@code targetPackage} belongs to. 410 * @param idForResponseEvent ID to be used for recording any response events corresponding 411 * to this broadcast. 412 * @param timestampMs time (in millis) when the broadcast was dispatched, in 413 * {@link SystemClock#elapsedRealtime()} timebase. 414 * @param targetUidProcState process state of the uid that the broadcast is targeted to. 415 */ reportBroadcastDispatched(int sourceUid, @NonNull String targetPackage, @NonNull UserHandle targetUser, long idForResponseEvent, @ElapsedRealtimeLong long timestampMs, @ProcessState int targetUidProcState)416 public abstract void reportBroadcastDispatched(int sourceUid, @NonNull String targetPackage, 417 @NonNull UserHandle targetUser, long idForResponseEvent, 418 @ElapsedRealtimeLong long timestampMs, @ProcessState int targetUidProcState); 419 420 /** 421 * Reports a notification posted event to the UsageStatsManager. 422 * 423 * @param packageName name of the package which posted the notification. 424 * @param user user that {@code packageName} belongs to. 425 * @param timestampMs time (in millis) when the notification was posted, in 426 * {@link SystemClock#elapsedRealtime()} timebase. 427 */ reportNotificationPosted(@onNull String packageName, @NonNull UserHandle user, @ElapsedRealtimeLong long timestampMs)428 public abstract void reportNotificationPosted(@NonNull String packageName, 429 @NonNull UserHandle user, @ElapsedRealtimeLong long timestampMs); 430 431 /** 432 * Reports a notification updated event to the UsageStatsManager. 433 * 434 * @param packageName name of the package which updated the notification. 435 * @param user user that {@code packageName} belongs to. 436 * @param timestampMs time (in millis) when the notification was updated, in 437 * {@link SystemClock#elapsedRealtime()} timebase. 438 */ reportNotificationUpdated(@onNull String packageName, @NonNull UserHandle user, @ElapsedRealtimeLong long timestampMs)439 public abstract void reportNotificationUpdated(@NonNull String packageName, 440 @NonNull UserHandle user, @ElapsedRealtimeLong long timestampMs); 441 442 /** 443 * Reports a notification removed event to the UsageStatsManager. 444 * 445 * @param packageName name of the package which removed the notification. 446 * @param user user that {@code packageName} belongs to. 447 * @param timestampMs time (in millis) when the notification was removed, in 448 * {@link SystemClock#elapsedRealtime()} timebase. 449 */ reportNotificationRemoved(@onNull String packageName, @NonNull UserHandle user, @ElapsedRealtimeLong long timestampMs)450 public abstract void reportNotificationRemoved(@NonNull String packageName, 451 @NonNull UserHandle user, @ElapsedRealtimeLong long timestampMs); 452 } 453