1 /* 2 * Copyright (C) 2020 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy 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, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package android.os; 18 19 import android.annotation.IntDef; 20 import android.annotation.NonNull; 21 import android.util.IntArray; 22 23 import com.android.internal.os.MonotonicClock; 24 25 import java.lang.annotation.Retention; 26 import java.lang.annotation.RetentionPolicy; 27 import java.util.Arrays; 28 import java.util.concurrent.TimeUnit; 29 30 /** 31 * Query parameters for the {@link BatteryStatsManager#getBatteryUsageStats()} call. 32 * 33 * @hide 34 */ 35 @android.ravenwood.annotation.RavenwoodKeepWholeClass 36 public final class BatteryUsageStatsQuery implements Parcelable { 37 38 @NonNull 39 public static final BatteryUsageStatsQuery DEFAULT = 40 new BatteryUsageStatsQuery.Builder().build(); 41 42 /** 43 * Flags for the {@link BatteryStatsManager#getBatteryUsageStats()} method. 44 * @hide 45 */ 46 @IntDef(flag = true, prefix = { "FLAG_BATTERY_USAGE_STATS_" }, value = { 47 FLAG_BATTERY_USAGE_STATS_POWER_PROFILE_MODEL, 48 FLAG_BATTERY_USAGE_STATS_INCLUDE_HISTORY, 49 FLAG_BATTERY_USAGE_STATS_INCLUDE_PROCESS_STATE_DATA, 50 FLAG_BATTERY_USAGE_STATS_INCLUDE_VIRTUAL_UIDS, 51 }) 52 @Retention(RetentionPolicy.SOURCE) 53 public @interface BatteryUsageStatsFlags {} 54 55 /** 56 * Indicates that power estimations should be based on the usage time and 57 * average power constants provided in the PowerProfile, even if on-device power monitoring 58 * is available. 59 * 60 * @hide 61 */ 62 public static final int FLAG_BATTERY_USAGE_STATS_POWER_PROFILE_MODEL = 0x0001; 63 64 /** 65 * Indicates that battery history should be included in the BatteryUsageStats. 66 * @hide 67 */ 68 public static final int FLAG_BATTERY_USAGE_STATS_INCLUDE_HISTORY = 0x0002; 69 70 public static final int FLAG_BATTERY_USAGE_STATS_INCLUDE_PROCESS_STATE_DATA = 0x0008; 71 72 public static final int FLAG_BATTERY_USAGE_STATS_INCLUDE_VIRTUAL_UIDS = 0x0010; 73 74 public static final int FLAG_BATTERY_USAGE_STATS_INCLUDE_SCREEN_STATE = 0x0020; 75 76 public static final int FLAG_BATTERY_USAGE_STATS_INCLUDE_POWER_STATE = 0x0040; 77 78 public static final int FLAG_BATTERY_USAGE_STATS_ACCUMULATED = 0x0080; 79 80 private static final long DEFAULT_MAX_STATS_AGE_MS = 5 * 60 * 1000; 81 private static final long DEFAULT_PREFERRED_HISTORY_DURATION_MS = TimeUnit.HOURS.toMillis(2); 82 83 private final int mFlags; 84 @NonNull 85 private final int[] mUserIds; 86 private final long mMaxStatsAgeMs; 87 88 private final long mAggregatedFromTimestamp; 89 private final long mAggregatedToTimestamp; 90 private long mMonotonicStartTime; 91 private long mMonotonicEndTime; 92 private final double mMinConsumedPowerThreshold; 93 private final @BatteryConsumer.PowerComponentId int[] mPowerComponents; 94 private final long mPreferredHistoryDurationMs; 95 BatteryUsageStatsQuery(@onNull Builder builder)96 private BatteryUsageStatsQuery(@NonNull Builder builder) { 97 mFlags = builder.mFlags; 98 mUserIds = builder.mUserIds != null ? builder.mUserIds.toArray() 99 : new int[]{UserHandle.USER_ALL}; 100 mMaxStatsAgeMs = builder.mMaxStatsAgeMs; 101 mMinConsumedPowerThreshold = builder.mMinConsumedPowerThreshold; 102 mAggregatedFromTimestamp = builder.mAggregateFromTimestamp; 103 mAggregatedToTimestamp = builder.mAggregateToTimestamp; 104 mMonotonicStartTime = builder.mMonotonicStartTime; 105 mMonotonicEndTime = builder.mMonotonicEndTime; 106 mPowerComponents = builder.mPowerComponents; 107 mPreferredHistoryDurationMs = builder.mPreferredHistoryDurationMs; 108 } 109 110 @BatteryUsageStatsFlags getFlags()111 public int getFlags() { 112 return mFlags; 113 } 114 115 /** 116 * Returns an array of users for which the attribution is requested. It may 117 * contain {@link UserHandle#USER_ALL} to indicate that the attribution 118 * should be performed for all users. Battery consumed by users <b>not</b> included 119 * in this array will be returned in the aggregated form as {@link UserBatteryConsumer}'s. 120 */ 121 @NonNull getUserIds()122 public int[] getUserIds() { 123 return mUserIds; 124 } 125 126 /** 127 * Returns true if the power calculations must be based on the PowerProfile constants, 128 * even if measured energy data is available. 129 */ shouldForceUsePowerProfileModel()130 public boolean shouldForceUsePowerProfileModel() { 131 return (mFlags & FLAG_BATTERY_USAGE_STATS_POWER_PROFILE_MODEL) != 0; 132 } 133 isProcessStateDataNeeded()134 public boolean isProcessStateDataNeeded() { 135 return (mFlags & FLAG_BATTERY_USAGE_STATS_INCLUDE_PROCESS_STATE_DATA) != 0; 136 } 137 isScreenStateDataNeeded()138 public boolean isScreenStateDataNeeded() { 139 return (mFlags & FLAG_BATTERY_USAGE_STATS_INCLUDE_SCREEN_STATE) != 0; 140 } 141 isPowerStateDataNeeded()142 public boolean isPowerStateDataNeeded() { 143 return (mFlags & FLAG_BATTERY_USAGE_STATS_INCLUDE_POWER_STATE) != 0; 144 } 145 146 /** 147 * Returns the power components that should be estimated or null if all power components 148 * are being requested. 149 */ 150 @BatteryConsumer.PowerComponentId getPowerComponents()151 public int[] getPowerComponents() { 152 return mPowerComponents; 153 } 154 155 /** 156 * Returns the client's tolerance for stale battery stats. The data is allowed to be up to 157 * this many milliseconds out-of-date. 158 */ getMaxStatsAge()159 public long getMaxStatsAge() { 160 return mMaxStatsAgeMs; 161 } 162 163 /** 164 * Returns the minimal power component consumed power threshold. The small power consuming 165 * components will be reported as zero. 166 */ getMinConsumedPowerThreshold()167 public double getMinConsumedPowerThreshold() { 168 return mMinConsumedPowerThreshold; 169 } 170 171 /** 172 * Returns the exclusive lower bound of the battery history that should be included in 173 * the aggregated battery usage stats. 174 */ getMonotonicStartTime()175 public long getMonotonicStartTime() { 176 return mMonotonicStartTime; 177 } 178 179 /** 180 * Returns the inclusive upper bound of the battery history that should be included in 181 * the aggregated battery usage stats. 182 */ getMonotonicEndTime()183 public long getMonotonicEndTime() { 184 return mMonotonicEndTime; 185 } 186 187 /** 188 * Returns the exclusive lower bound of the stored snapshot timestamps that should be included 189 * in the aggregation. Ignored if {@link #getAggregatedToTimestamp()} is zero. 190 */ getAggregatedFromTimestamp()191 public long getAggregatedFromTimestamp() { 192 return mAggregatedFromTimestamp; 193 } 194 195 /** 196 * Returns the inclusive upper bound of the stored snapshot timestamps that should 197 * be included in the aggregation. The default is to include only the current stats 198 * accumulated since the latest battery reset. 199 */ getAggregatedToTimestamp()200 public long getAggregatedToTimestamp() { 201 return mAggregatedToTimestamp; 202 } 203 204 /** 205 * Returns the preferred duration of battery history (tail) to be included in the query result. 206 */ getPreferredHistoryDurationMs()207 public long getPreferredHistoryDurationMs() { 208 return mPreferredHistoryDurationMs; 209 } 210 211 @Override toString()212 public String toString() { 213 return "BatteryUsageStatsQuery{" 214 + "mFlags=" + Integer.toHexString(mFlags) 215 + ", mUserIds=" + Arrays.toString(mUserIds) 216 + ", mMaxStatsAgeMs=" + mMaxStatsAgeMs 217 + ", mAggregatedFromTimestamp=" + mAggregatedFromTimestamp 218 + ", mAggregatedToTimestamp=" + mAggregatedToTimestamp 219 + ", mMonotonicStartTime=" + mMonotonicStartTime 220 + ", mMonotonicEndTime=" + mMonotonicEndTime 221 + ", mMinConsumedPowerThreshold=" + mMinConsumedPowerThreshold 222 + ", mPowerComponents=" + Arrays.toString(mPowerComponents) 223 + ", mMaxHistoryDurationMs=" + mPreferredHistoryDurationMs 224 + '}'; 225 } 226 BatteryUsageStatsQuery(Parcel in)227 private BatteryUsageStatsQuery(Parcel in) { 228 mMonotonicStartTime = in.readLong(); 229 mMonotonicEndTime = in.readLong(); 230 mFlags = in.readInt(); 231 mUserIds = new int[in.readInt()]; 232 in.readIntArray(mUserIds); 233 mMaxStatsAgeMs = in.readLong(); 234 mMinConsumedPowerThreshold = in.readDouble(); 235 mAggregatedFromTimestamp = in.readLong(); 236 mAggregatedToTimestamp = in.readLong(); 237 mPowerComponents = in.createIntArray(); 238 mPreferredHistoryDurationMs = in.readLong(); 239 } 240 241 @Override writeToParcel(Parcel dest, int flags)242 public void writeToParcel(Parcel dest, int flags) { 243 dest.writeLong(mMonotonicStartTime); 244 dest.writeLong(mMonotonicEndTime); 245 dest.writeInt(mFlags); 246 dest.writeInt(mUserIds.length); 247 dest.writeIntArray(mUserIds); 248 dest.writeLong(mMaxStatsAgeMs); 249 dest.writeDouble(mMinConsumedPowerThreshold); 250 dest.writeLong(mAggregatedFromTimestamp); 251 dest.writeLong(mAggregatedToTimestamp); 252 dest.writeIntArray(mPowerComponents); 253 dest.writeLong(mPreferredHistoryDurationMs); 254 } 255 256 @Override describeContents()257 public int describeContents() { 258 return 0; 259 } 260 261 @NonNull 262 public static final Creator<BatteryUsageStatsQuery> CREATOR = 263 new Creator<BatteryUsageStatsQuery>() { 264 @Override 265 public BatteryUsageStatsQuery createFromParcel(Parcel in) { 266 return new BatteryUsageStatsQuery(in); 267 } 268 269 @Override 270 public BatteryUsageStatsQuery[] newArray(int size) { 271 return new BatteryUsageStatsQuery[size]; 272 } 273 }; 274 275 /** 276 * Builder for BatteryUsageStatsQuery. 277 */ 278 public static final class Builder { 279 private int mFlags; 280 private IntArray mUserIds; 281 private long mMaxStatsAgeMs = DEFAULT_MAX_STATS_AGE_MS; 282 private long mMonotonicStartTime = MonotonicClock.UNDEFINED; 283 private long mMonotonicEndTime = MonotonicClock.UNDEFINED; 284 private long mAggregateFromTimestamp; 285 private long mAggregateToTimestamp; 286 private double mMinConsumedPowerThreshold = 0; 287 private @BatteryConsumer.PowerComponentId int[] mPowerComponents; 288 private long mPreferredHistoryDurationMs = DEFAULT_PREFERRED_HISTORY_DURATION_MS; 289 290 /** 291 * Builds a read-only BatteryUsageStatsQuery object. 292 */ build()293 public BatteryUsageStatsQuery build() { 294 return new BatteryUsageStatsQuery(this); 295 } 296 297 /** 298 * Specifies the time range for the requested stats, in terms of MonotonicClock 299 * @param monotonicStartTime Inclusive starting monotonic timestamp 300 * @param monotonicEndTime Exclusive ending timestamp. Can be MonotonicClock.UNDEFINED 301 */ monotonicTimeRange(long monotonicStartTime, long monotonicEndTime)302 public Builder monotonicTimeRange(long monotonicStartTime, long monotonicEndTime) { 303 mMonotonicStartTime = monotonicStartTime; 304 mMonotonicEndTime = monotonicEndTime; 305 return this; 306 } 307 308 /** 309 * Add a user whose battery stats should be included in the battery usage stats. 310 * {@link UserHandle#USER_ALL} will be used by default if no users are added explicitly. 311 */ addUser(@onNull UserHandle userHandle)312 public Builder addUser(@NonNull UserHandle userHandle) { 313 if (mUserIds == null) { 314 mUserIds = new IntArray(1); 315 } 316 mUserIds.add(userHandle.getIdentifier()); 317 return this; 318 } 319 320 /** 321 * Requests that battery history be included in the BatteryUsageStats. 322 */ includeBatteryHistory()323 public Builder includeBatteryHistory() { 324 mFlags |= BatteryUsageStatsQuery.FLAG_BATTERY_USAGE_STATS_INCLUDE_HISTORY; 325 return this; 326 } 327 328 /** 329 * Set the preferred amount of battery history to be included in the result, provided 330 * that `includeBatteryHistory` is also called. The actual amount of history included in 331 * the result may vary for performance reasons and may exceed the specified preference. 332 */ setPreferredHistoryDurationMs(long preferredHistoryDurationMs)333 public Builder setPreferredHistoryDurationMs(long preferredHistoryDurationMs) { 334 mPreferredHistoryDurationMs = preferredHistoryDurationMs; 335 return this; 336 } 337 338 /** 339 * Requests that per-process state data be included in the BatteryUsageStats, if 340 * available. Check {@link BatteryUsageStats#isProcessStateDataIncluded()} on the result 341 * to see if the data is available. 342 */ includeProcessStateData()343 public Builder includeProcessStateData() { 344 mFlags |= BatteryUsageStatsQuery.FLAG_BATTERY_USAGE_STATS_INCLUDE_PROCESS_STATE_DATA; 345 return this; 346 } 347 348 /** 349 * Requests to return modeled battery usage stats only, even if on-device 350 * power monitoring data is available. 351 * 352 * Should only be used for testing and debugging. 353 * 354 * @deprecated PowerModel is no longer supported 355 */ 356 @Deprecated powerProfileModeledOnly()357 public Builder powerProfileModeledOnly() { 358 mFlags |= BatteryUsageStatsQuery.FLAG_BATTERY_USAGE_STATS_POWER_PROFILE_MODEL; 359 return this; 360 } 361 362 /** 363 * Requests to return identifiers of models that were used for estimation 364 * of power consumption. 365 * 366 * Should only be used for testing and debugging. 367 * @deprecated PowerModel is no longer supported 368 */ 369 @Deprecated includePowerModels()370 public Builder includePowerModels() { 371 return this; 372 } 373 374 /** 375 * Requests to return only statistics for the specified power components. The default 376 * is all power components. 377 */ includePowerComponents( @atteryConsumer.PowerComponentId int[] powerComponents)378 public Builder includePowerComponents( 379 @BatteryConsumer.PowerComponentId int[] powerComponents) { 380 mPowerComponents = powerComponents; 381 return this; 382 } 383 384 /** 385 * Requests to return attribution data for virtual UIDs such as 386 * {@link Process#SDK_SANDBOX_VIRTUAL_UID}. 387 */ includeVirtualUids()388 public Builder includeVirtualUids() { 389 mFlags |= BatteryUsageStatsQuery.FLAG_BATTERY_USAGE_STATS_INCLUDE_VIRTUAL_UIDS; 390 return this; 391 } 392 393 /** 394 * Requests that screen state data (screen-on, screen-other) be included in the 395 * BatteryUsageStats, if available. 396 */ includeScreenStateData()397 public Builder includeScreenStateData() { 398 mFlags |= BatteryUsageStatsQuery.FLAG_BATTERY_USAGE_STATS_INCLUDE_SCREEN_STATE; 399 return this; 400 } 401 402 /** 403 * Requests that power state data (on-battery, power-other) be included in the 404 * BatteryUsageStats, if available. 405 */ includePowerStateData()406 public Builder includePowerStateData() { 407 mFlags |= BatteryUsageStatsQuery.FLAG_BATTERY_USAGE_STATS_INCLUDE_POWER_STATE; 408 return this; 409 } 410 411 /** 412 * Requests the full continuously accumulated battery usage stats: across reboots 413 * and most battery stats resets. 414 */ accumulated()415 public Builder accumulated() { 416 mFlags |= FLAG_BATTERY_USAGE_STATS_ACCUMULATED 417 | FLAG_BATTERY_USAGE_STATS_INCLUDE_POWER_STATE 418 | FLAG_BATTERY_USAGE_STATS_INCLUDE_SCREEN_STATE 419 | FLAG_BATTERY_USAGE_STATS_INCLUDE_PROCESS_STATE_DATA; 420 return this; 421 } 422 423 /** 424 * Requests to aggregate stored snapshots between the two supplied timestamps 425 * @param fromTimestamp Exclusive starting timestamp, as per System.currentTimeMillis() 426 * @param toTimestamp Inclusive ending timestamp, as per System.currentTimeMillis() 427 */ 428 // TODO(b/298459065): switch to monotonic clock aggregateSnapshots(long fromTimestamp, long toTimestamp)429 public Builder aggregateSnapshots(long fromTimestamp, long toTimestamp) { 430 mAggregateFromTimestamp = fromTimestamp; 431 mAggregateToTimestamp = toTimestamp; 432 return this; 433 } 434 435 /** 436 * Set the client's tolerance for stale battery stats. The data may be up to 437 * this many milliseconds out-of-date. 438 */ setMaxStatsAgeMs(long maxStatsAgeMs)439 public Builder setMaxStatsAgeMs(long maxStatsAgeMs) { 440 mMaxStatsAgeMs = maxStatsAgeMs; 441 return this; 442 } 443 444 /** 445 * Set the minimal power component consumed power threshold. The small power consuming 446 * components will be reported as zero. 447 */ setMinConsumedPowerThreshold(double minConsumedPowerThreshold)448 public Builder setMinConsumedPowerThreshold(double minConsumedPowerThreshold) { 449 mMinConsumedPowerThreshold = minConsumedPowerThreshold; 450 return this; 451 } 452 } 453 } 454