1 /* 2 * Copyright (C) 2008 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.Manifest.permission; 20 import android.annotation.RequiresPermission; 21 import android.annotation.SystemApi; 22 import android.annotation.SystemService; 23 import android.compat.annotation.UnsupportedAppUsage; 24 import android.content.Context; 25 import android.content.Intent; 26 import android.hardware.health.V1_0.Constants; 27 28 import com.android.internal.app.IBatteryStats; 29 30 /** 31 * The BatteryManager class contains strings and constants used for values 32 * in the {@link android.content.Intent#ACTION_BATTERY_CHANGED} Intent, and 33 * provides a method for querying battery and charging properties. 34 */ 35 @SystemService(Context.BATTERY_SERVICE) 36 public class BatteryManager { 37 /** 38 * Extra for {@link android.content.Intent#ACTION_BATTERY_CHANGED}: 39 * integer containing the current status constant. 40 */ 41 public static final String EXTRA_STATUS = "status"; 42 43 /** 44 * Extra for {@link android.content.Intent#ACTION_BATTERY_CHANGED}: 45 * integer containing the current health constant. 46 */ 47 public static final String EXTRA_HEALTH = "health"; 48 49 /** 50 * Extra for {@link android.content.Intent#ACTION_BATTERY_CHANGED}: 51 * boolean indicating whether a battery is present. 52 */ 53 public static final String EXTRA_PRESENT = "present"; 54 55 /** 56 * Extra for {@link android.content.Intent#ACTION_BATTERY_CHANGED}: 57 * integer field containing the current battery level, from 0 to 58 * {@link #EXTRA_SCALE}. 59 */ 60 public static final String EXTRA_LEVEL = "level"; 61 62 /** 63 * Extra for {@link android.content.Intent#ACTION_BATTERY_CHANGED}: 64 * Boolean field indicating whether the battery is currently considered to be 65 * low, that is whether a {@link Intent#ACTION_BATTERY_LOW} broadcast 66 * has been sent. 67 */ 68 public static final String EXTRA_BATTERY_LOW = "battery_low"; 69 70 /** 71 * Extra for {@link android.content.Intent#ACTION_BATTERY_CHANGED}: 72 * integer containing the maximum battery level. 73 */ 74 public static final String EXTRA_SCALE = "scale"; 75 76 /** 77 * Extra for {@link android.content.Intent#ACTION_BATTERY_CHANGED}: 78 * integer containing the resource ID of a small status bar icon 79 * indicating the current battery state. 80 */ 81 public static final String EXTRA_ICON_SMALL = "icon-small"; 82 83 /** 84 * Extra for {@link android.content.Intent#ACTION_BATTERY_CHANGED}: 85 * integer indicating whether the device is plugged in to a power 86 * source; 0 means it is on battery, other constants are different 87 * types of power sources. 88 */ 89 public static final String EXTRA_PLUGGED = "plugged"; 90 91 /** 92 * Extra for {@link android.content.Intent#ACTION_BATTERY_CHANGED}: 93 * integer containing the current battery voltage level. 94 */ 95 public static final String EXTRA_VOLTAGE = "voltage"; 96 97 /** 98 * Extra for {@link android.content.Intent#ACTION_BATTERY_CHANGED}: 99 * integer containing the current battery temperature. 100 */ 101 public static final String EXTRA_TEMPERATURE = "temperature"; 102 103 /** 104 * Extra for {@link android.content.Intent#ACTION_BATTERY_CHANGED}: 105 * String describing the technology of the current battery. 106 */ 107 public static final String EXTRA_TECHNOLOGY = "technology"; 108 109 /** 110 * Extra for {@link android.content.Intent#ACTION_BATTERY_CHANGED}: 111 * Int value set to nonzero if an unsupported charger is attached 112 * to the device. 113 * {@hide} 114 */ 115 @UnsupportedAppUsage 116 public static final String EXTRA_INVALID_CHARGER = "invalid_charger"; 117 118 /** 119 * Extra for {@link android.content.Intent#ACTION_BATTERY_CHANGED}: 120 * Int value set to the maximum charging current supported by the charger in micro amperes. 121 * {@hide} 122 */ 123 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 124 public static final String EXTRA_MAX_CHARGING_CURRENT = "max_charging_current"; 125 126 /** 127 * Extra for {@link android.content.Intent#ACTION_BATTERY_CHANGED}: 128 * Int value set to the maximum charging voltage supported by the charger in micro volts. 129 * {@hide} 130 */ 131 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 132 public static final String EXTRA_MAX_CHARGING_VOLTAGE = "max_charging_voltage"; 133 134 /** 135 * Extra for {@link android.content.Intent#ACTION_BATTERY_CHANGED}: 136 * integer containing the charge counter present in the battery. 137 * {@hide} 138 */ 139 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 140 public static final String EXTRA_CHARGE_COUNTER = "charge_counter"; 141 142 /** 143 * Extra for {@link android.content.Intent#ACTION_BATTERY_CHANGED}: 144 * Current int sequence number of the update. 145 * {@hide} 146 */ 147 public static final String EXTRA_SEQUENCE = "seq"; 148 149 /** 150 * Extra for {@link android.content.Intent#ACTION_BATTERY_CHANGED}: 151 * Int value representing the battery charging cycle count. 152 */ 153 public static final String EXTRA_CYCLE_COUNT = "android.os.extra.CYCLE_COUNT"; 154 155 /** 156 * Extra for {@link android.content.Intent#ACTION_BATTERY_CHANGED}: 157 * Int value representing the battery charging status. 158 */ 159 public static final String EXTRA_CHARGING_STATUS = "android.os.extra.CHARGING_STATUS"; 160 161 /** 162 * Extra for {@link android.content.Intent#ACTION_BATTERY_LEVEL_CHANGED}: 163 * Contains list of Bundles representing battery events 164 * @hide 165 */ 166 @SystemApi 167 public static final String EXTRA_EVENTS = "android.os.extra.EVENTS"; 168 169 /** 170 * Extra for event in {@link android.content.Intent#ACTION_BATTERY_LEVEL_CHANGED}: 171 * Long value representing time when event occurred as returned by 172 * {@link android.os.SystemClock#elapsedRealtime()} 173 * @hide 174 */ 175 @SystemApi 176 public static final String EXTRA_EVENT_TIMESTAMP = "android.os.extra.EVENT_TIMESTAMP"; 177 178 // values for "status" field in the ACTION_BATTERY_CHANGED Intent 179 public static final int BATTERY_STATUS_UNKNOWN = Constants.BATTERY_STATUS_UNKNOWN; 180 public static final int BATTERY_STATUS_CHARGING = Constants.BATTERY_STATUS_CHARGING; 181 public static final int BATTERY_STATUS_DISCHARGING = Constants.BATTERY_STATUS_DISCHARGING; 182 public static final int BATTERY_STATUS_NOT_CHARGING = Constants.BATTERY_STATUS_NOT_CHARGING; 183 public static final int BATTERY_STATUS_FULL = Constants.BATTERY_STATUS_FULL; 184 185 // values for "health" field in the ACTION_BATTERY_CHANGED Intent 186 public static final int BATTERY_HEALTH_UNKNOWN = Constants.BATTERY_HEALTH_UNKNOWN; 187 public static final int BATTERY_HEALTH_GOOD = Constants.BATTERY_HEALTH_GOOD; 188 public static final int BATTERY_HEALTH_OVERHEAT = Constants.BATTERY_HEALTH_OVERHEAT; 189 public static final int BATTERY_HEALTH_DEAD = Constants.BATTERY_HEALTH_DEAD; 190 public static final int BATTERY_HEALTH_OVER_VOLTAGE = Constants.BATTERY_HEALTH_OVER_VOLTAGE; 191 public static final int BATTERY_HEALTH_UNSPECIFIED_FAILURE = Constants.BATTERY_HEALTH_UNSPECIFIED_FAILURE; 192 public static final int BATTERY_HEALTH_COLD = Constants.BATTERY_HEALTH_COLD; 193 194 // values of the "plugged" field in the ACTION_BATTERY_CHANGED intent. 195 // These must be powers of 2. 196 /** Power source is an AC charger. */ 197 public static final int BATTERY_PLUGGED_AC = OsProtoEnums.BATTERY_PLUGGED_AC; // = 1 198 /** Power source is a USB port. */ 199 public static final int BATTERY_PLUGGED_USB = OsProtoEnums.BATTERY_PLUGGED_USB; // = 2 200 /** Power source is wireless. */ 201 public static final int BATTERY_PLUGGED_WIRELESS = OsProtoEnums.BATTERY_PLUGGED_WIRELESS; // = 4 202 /** Power source is dock. */ 203 public static final int BATTERY_PLUGGED_DOCK = OsProtoEnums.BATTERY_PLUGGED_DOCK; // = 8 204 205 // values for "charge policy" property 206 /** 207 * Default policy (e.g. normal). 208 * @hide 209 */ 210 @SystemApi 211 public static final int CHARGING_POLICY_DEFAULT = OsProtoEnums.CHARGING_POLICY_DEFAULT; // = 1 212 /** 213 * Optimized for battery health using static thresholds (e.g stop at 80%). 214 * @hide 215 */ 216 @SystemApi 217 public static final int CHARGING_POLICY_ADAPTIVE_AON = 218 OsProtoEnums.CHARGING_POLICY_ADAPTIVE_AON; // = 2 219 /** 220 * Optimized for battery health using adaptive thresholds. 221 * @hide 222 */ 223 @SystemApi 224 public static final int CHARGING_POLICY_ADAPTIVE_AC = 225 OsProtoEnums.CHARGING_POLICY_ADAPTIVE_AC; // = 3 226 /** 227 * Optimized for battery health, devices always connected to power. 228 * @hide 229 */ 230 @SystemApi 231 public static final int CHARGING_POLICY_ADAPTIVE_LONGLIFE = 232 OsProtoEnums.CHARGING_POLICY_ADAPTIVE_LONGLIFE; // = 4 233 234 /** @hide */ 235 public static final int BATTERY_PLUGGED_ANY = 236 BATTERY_PLUGGED_AC | BATTERY_PLUGGED_USB | BATTERY_PLUGGED_WIRELESS 237 | BATTERY_PLUGGED_DOCK; 238 239 /** 240 * Sent when the device's battery has started charging (or has reached full charge 241 * and the device is on power). This is a good time to do work that you would like to 242 * avoid doing while on battery (that is to avoid draining the user's battery due to 243 * things they don't care enough about). 244 * 245 * This is paired with {@link #ACTION_DISCHARGING}. The current state can always 246 * be retrieved with {@link #isCharging()}. 247 */ 248 public static final String ACTION_CHARGING = "android.os.action.CHARGING"; 249 250 /** 251 * Sent when the device's battery may be discharging, so apps should avoid doing 252 * extraneous work that would cause it to discharge faster. 253 * 254 * This is paired with {@link #ACTION_CHARGING}. The current state can always 255 * be retrieved with {@link #isCharging()}. 256 */ 257 public static final String ACTION_DISCHARGING = "android.os.action.DISCHARGING"; 258 259 /* 260 * Battery property identifiers. These must match the values in 261 * frameworks/native/include/batteryservice/BatteryService.h 262 */ 263 /** Battery capacity in microampere-hours, as an integer. */ 264 public static final int BATTERY_PROPERTY_CHARGE_COUNTER = 1; 265 266 /** 267 * Instantaneous battery current in microamperes, as an integer. Positive 268 * values indicate net current entering the battery from a charge source, 269 * negative values indicate net current discharging from the battery. 270 */ 271 public static final int BATTERY_PROPERTY_CURRENT_NOW = 2; 272 273 /** 274 * Average battery current in microamperes, as an integer. Positive 275 * values indicate net current entering the battery from a charge source, 276 * negative values indicate net current discharging from the battery. 277 * The time period over which the average is computed may depend on the 278 * fuel gauge hardware and its configuration. 279 */ 280 public static final int BATTERY_PROPERTY_CURRENT_AVERAGE = 3; 281 282 /** 283 * Remaining battery capacity as an integer percentage of total capacity 284 * (with no fractional part). 285 */ 286 public static final int BATTERY_PROPERTY_CAPACITY = 4; 287 288 /** 289 * Battery remaining energy in nanowatt-hours, as a long integer. 290 */ 291 public static final int BATTERY_PROPERTY_ENERGY_COUNTER = 5; 292 293 /** 294 * Battery charge status, from a BATTERY_STATUS_* value. 295 */ 296 public static final int BATTERY_PROPERTY_STATUS = 6; 297 298 /** 299 * Battery manufacturing date is reported in epoch. The 0 timepoint 300 * begins at midnight Coordinated Universal Time (UTC) on January 1, 1970. 301 * It is a long integer in seconds. 302 * 303 * <p class="note"> 304 * The sender must hold the {@link android.Manifest.permission#BATTERY_STATS} permission. 305 * 306 * Example: <code> 307 * // The value returned from the API can be used to create a Date, used 308 * // to set the time on a calendar and coverted to a string. 309 * import java.util.Date; 310 * 311 * mBatteryManager = mContext.getSystemService(BatteryManager.class); 312 * final long manufacturingDate = 313 * mBatteryManager.getLongProperty(BatteryManager.BATTERY_PROPERTY_MANUFACTURING_DATE); 314 * Date date = new Date(manufacturingDate); 315 * Calendar calendar = Calendar.getInstance(); 316 * calendar.setTime(date); 317 * // Convert to yyyy-MM-dd HH:mm:ss format string 318 * SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 319 * String dateString = sdf.format(date); 320 * </code> 321 * @hide 322 */ 323 @RequiresPermission(permission.BATTERY_STATS) 324 @SystemApi 325 public static final int BATTERY_PROPERTY_MANUFACTURING_DATE = 7; 326 327 /** 328 * The date of first usage is reported in epoch. The 0 timepoint 329 * begins at midnight Coordinated Universal Time (UTC) on January 1, 1970. 330 * It is a long integer in seconds. 331 * 332 * <p class="note"> 333 * The sender must hold the {@link android.Manifest.permission#BATTERY_STATS} permission. 334 * 335 * {@link BATTERY_PROPERTY_MANUFACTURING_DATE for sample code} 336 * @hide 337 */ 338 @RequiresPermission(permission.BATTERY_STATS) 339 @SystemApi 340 public static final int BATTERY_PROPERTY_FIRST_USAGE_DATE = 8; 341 342 /** 343 * Battery charging policy from a CHARGING_POLICY_* value.. 344 * 345 * <p class="note"> 346 * The sender must hold the {@link android.Manifest.permission#BATTERY_STATS} permission. 347 * 348 * @hide 349 */ 350 @RequiresPermission(permission.BATTERY_STATS) 351 @SystemApi 352 public static final int BATTERY_PROPERTY_CHARGING_POLICY = 9; 353 354 /** 355 * 356 * Percentage representing the measured battery state of health (remaining 357 * estimated full charge capacity relative to the rated capacity in %). 358 * 359 * <p class="note"> 360 * The sender must hold the {@link android.Manifest.permission#BATTERY_STATS} permission. 361 * 362 * @hide 363 */ 364 @RequiresPermission(permission.BATTERY_STATS) 365 @SystemApi 366 public static final int BATTERY_PROPERTY_STATE_OF_HEALTH = 10; 367 368 private final Context mContext; 369 private final IBatteryStats mBatteryStats; 370 private final IBatteryPropertiesRegistrar mBatteryPropertiesRegistrar; 371 372 /** 373 * @removed Was previously made visible by accident. 374 */ BatteryManager()375 public BatteryManager() { 376 mContext = null; 377 mBatteryStats = IBatteryStats.Stub.asInterface( 378 ServiceManager.getService(BatteryStats.SERVICE_NAME)); 379 mBatteryPropertiesRegistrar = IBatteryPropertiesRegistrar.Stub.asInterface( 380 ServiceManager.getService("batteryproperties")); 381 } 382 383 /** {@hide} */ BatteryManager(Context context, IBatteryStats batteryStats, IBatteryPropertiesRegistrar batteryPropertiesRegistrar)384 public BatteryManager(Context context, 385 IBatteryStats batteryStats, 386 IBatteryPropertiesRegistrar batteryPropertiesRegistrar) { 387 mContext = context; 388 mBatteryStats = batteryStats; 389 mBatteryPropertiesRegistrar = batteryPropertiesRegistrar; 390 } 391 392 /** 393 * Return true if the battery is currently considered to be charging. This means that 394 * the device is plugged in and is supplying sufficient power that the battery level is 395 * going up (or the battery is fully charged). Changes in this state are matched by 396 * broadcasts of {@link #ACTION_CHARGING} and {@link #ACTION_DISCHARGING}. 397 */ isCharging()398 public boolean isCharging() { 399 try { 400 return mBatteryStats.isCharging(); 401 } catch (RemoteException e) { 402 throw e.rethrowFromSystemServer(); 403 } 404 } 405 406 /** 407 * Query a battery property from the batteryproperties service. 408 * 409 * Returns the requested value, or Long.MIN_VALUE if property not 410 * supported on this system or on other error. 411 */ queryProperty(int id)412 private long queryProperty(int id) { 413 long ret; 414 415 if (mBatteryPropertiesRegistrar == null) { 416 return Long.MIN_VALUE; 417 } 418 419 try { 420 BatteryProperty prop = new BatteryProperty(); 421 if (mBatteryPropertiesRegistrar.getProperty(id, prop) == 0) 422 ret = prop.getLong(); 423 else 424 ret = Long.MIN_VALUE; 425 } catch (RemoteException e) { 426 throw e.rethrowFromSystemServer(); 427 } 428 429 return ret; 430 } 431 432 /** 433 * Return the value of a battery property of integer type. 434 * 435 * @param id identifier of the requested property 436 * 437 * @return the property value. If the property is not supported or there is any other error, 438 * return (a) 0 if {@code targetSdkVersion < VERSION_CODES.P} or (b) Integer.MIN_VALUE 439 * if {@code targetSdkVersion >= VERSION_CODES.P}. 440 */ getIntProperty(int id)441 public int getIntProperty(int id) { 442 long value = queryProperty(id); 443 if (value == Long.MIN_VALUE && mContext != null 444 && mContext.getApplicationInfo().targetSdkVersion 445 >= android.os.Build.VERSION_CODES.P) { 446 return Integer.MIN_VALUE; 447 } 448 449 return (int) value; 450 } 451 452 /** 453 * Return the value of a battery property of long type If the 454 * platform does not provide the property queried, this value will 455 * be Long.MIN_VALUE. 456 * 457 * @param id identifier of the requested property 458 * 459 * @return the property value, or Long.MIN_VALUE if not supported. 460 */ getLongProperty(int id)461 public long getLongProperty(int id) { 462 return queryProperty(id); 463 } 464 465 /** 466 * Return true if the plugType given is wired 467 * @param plugType {@link #BATTERY_PLUGGED_AC}, {@link #BATTERY_PLUGGED_USB}, 468 * or {@link #BATTERY_PLUGGED_WIRELESS} 469 * 470 * @return true if plugType is wired 471 * @hide 472 */ isPlugWired(int plugType)473 public static boolean isPlugWired(int plugType) { 474 return plugType == BATTERY_PLUGGED_USB || plugType == BATTERY_PLUGGED_AC; 475 } 476 477 /** 478 * Compute an approximation for how much time (in milliseconds) remains until the battery is 479 * fully charged. Returns -1 if no time can be computed: either there is not enough current 480 * data to make a decision or the battery is currently discharging. 481 * 482 * @return how much time is left, in milliseconds, until the battery is fully charged or -1 if 483 * the computation fails 484 */ computeChargeTimeRemaining()485 public long computeChargeTimeRemaining() { 486 try { 487 return mBatteryStats.computeChargeTimeRemaining(); 488 } catch (RemoteException e) { 489 throw e.rethrowFromSystemServer(); 490 } 491 } 492 493 /** 494 * Sets the delay for reporting battery state as charging after device is plugged in. 495 * This allows machine-learning or heuristics to delay the reporting and the corresponding 496 * broadcast, based on battery level, charging rate, and/or other parameters. 497 * 498 * @param delayMillis the delay in milliseconds, negative value to reset. 499 * 500 * @return True if the delay was set successfully. 501 * 502 * @see ACTION_CHARGING 503 * @hide 504 */ 505 @RequiresPermission(permission.POWER_SAVER) 506 @SystemApi setChargingStateUpdateDelayMillis(int delayMillis)507 public boolean setChargingStateUpdateDelayMillis(int delayMillis) { 508 try { 509 return mBatteryStats.setChargingStateUpdateDelayMillis(delayMillis); 510 } catch (RemoteException e) { 511 throw e.rethrowFromSystemServer(); 512 } 513 } 514 } 515