• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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_LEVEL_CHANGED}:
151      * Contains list of Bundles representing battery events
152      * @hide
153      */
154     @SystemApi
155     public static final String EXTRA_EVENTS = "android.os.extra.EVENTS";
156 
157     /**
158      * Extra for event in {@link android.content.Intent#ACTION_BATTERY_LEVEL_CHANGED}:
159      * Long value representing time when event occurred as returned by
160      * {@link android.os.SystemClock#elapsedRealtime()}
161      * @hide
162      */
163     @SystemApi
164     public static final String EXTRA_EVENT_TIMESTAMP = "android.os.extra.EVENT_TIMESTAMP";
165 
166     // values for "status" field in the ACTION_BATTERY_CHANGED Intent
167     public static final int BATTERY_STATUS_UNKNOWN = Constants.BATTERY_STATUS_UNKNOWN;
168     public static final int BATTERY_STATUS_CHARGING = Constants.BATTERY_STATUS_CHARGING;
169     public static final int BATTERY_STATUS_DISCHARGING = Constants.BATTERY_STATUS_DISCHARGING;
170     public static final int BATTERY_STATUS_NOT_CHARGING = Constants.BATTERY_STATUS_NOT_CHARGING;
171     public static final int BATTERY_STATUS_FULL = Constants.BATTERY_STATUS_FULL;
172 
173     // values for "health" field in the ACTION_BATTERY_CHANGED Intent
174     public static final int BATTERY_HEALTH_UNKNOWN = Constants.BATTERY_HEALTH_UNKNOWN;
175     public static final int BATTERY_HEALTH_GOOD = Constants.BATTERY_HEALTH_GOOD;
176     public static final int BATTERY_HEALTH_OVERHEAT = Constants.BATTERY_HEALTH_OVERHEAT;
177     public static final int BATTERY_HEALTH_DEAD = Constants.BATTERY_HEALTH_DEAD;
178     public static final int BATTERY_HEALTH_OVER_VOLTAGE = Constants.BATTERY_HEALTH_OVER_VOLTAGE;
179     public static final int BATTERY_HEALTH_UNSPECIFIED_FAILURE = Constants.BATTERY_HEALTH_UNSPECIFIED_FAILURE;
180     public static final int BATTERY_HEALTH_COLD = Constants.BATTERY_HEALTH_COLD;
181 
182     // values of the "plugged" field in the ACTION_BATTERY_CHANGED intent.
183     // These must be powers of 2.
184     /** Power source is an AC charger. */
185     public static final int BATTERY_PLUGGED_AC = OsProtoEnums.BATTERY_PLUGGED_AC; // = 1
186     /** Power source is a USB port. */
187     public static final int BATTERY_PLUGGED_USB = OsProtoEnums.BATTERY_PLUGGED_USB; // = 2
188     /** Power source is wireless. */
189     public static final int BATTERY_PLUGGED_WIRELESS = OsProtoEnums.BATTERY_PLUGGED_WIRELESS; // = 4
190     /** Power source is dock. */
191     public static final int BATTERY_PLUGGED_DOCK = OsProtoEnums.BATTERY_PLUGGED_DOCK; // = 8
192 
193     /** @hide */
194     public static final int BATTERY_PLUGGED_ANY =
195             BATTERY_PLUGGED_AC | BATTERY_PLUGGED_USB | BATTERY_PLUGGED_WIRELESS
196                     | BATTERY_PLUGGED_DOCK;
197 
198     /**
199      * Sent when the device's battery has started charging (or has reached full charge
200      * and the device is on power).  This is a good time to do work that you would like to
201      * avoid doing while on battery (that is to avoid draining the user's battery due to
202      * things they don't care enough about).
203      *
204      * This is paired with {@link #ACTION_DISCHARGING}.  The current state can always
205      * be retrieved with {@link #isCharging()}.
206      */
207     public static final String ACTION_CHARGING = "android.os.action.CHARGING";
208 
209     /**
210      * Sent when the device's battery may be discharging, so apps should avoid doing
211      * extraneous work that would cause it to discharge faster.
212      *
213      * This is paired with {@link #ACTION_CHARGING}.  The current state can always
214      * be retrieved with {@link #isCharging()}.
215      */
216     public static final String ACTION_DISCHARGING = "android.os.action.DISCHARGING";
217 
218     /*
219      * Battery property identifiers.  These must match the values in
220      * frameworks/native/include/batteryservice/BatteryService.h
221      */
222     /** Battery capacity in microampere-hours, as an integer. */
223     public static final int BATTERY_PROPERTY_CHARGE_COUNTER = 1;
224 
225     /**
226      * Instantaneous battery current in microamperes, as an integer.  Positive
227      * values indicate net current entering the battery from a charge source,
228      * negative values indicate net current discharging from the battery.
229      */
230     public static final int BATTERY_PROPERTY_CURRENT_NOW = 2;
231 
232     /**
233      * Average battery current in microamperes, as an integer.  Positive
234      * values indicate net current entering the battery from a charge source,
235      * negative values indicate net current discharging from the battery.
236      * The time period over which the average is computed may depend on the
237      * fuel gauge hardware and its configuration.
238      */
239     public static final int BATTERY_PROPERTY_CURRENT_AVERAGE = 3;
240 
241     /**
242      * Remaining battery capacity as an integer percentage of total capacity
243      * (with no fractional part).
244      */
245     public static final int BATTERY_PROPERTY_CAPACITY = 4;
246 
247     /**
248      * Battery remaining energy in nanowatt-hours, as a long integer.
249      */
250     public static final int BATTERY_PROPERTY_ENERGY_COUNTER = 5;
251 
252     /**
253      * Battery charge status, from a BATTERY_STATUS_* value.
254      */
255     public static final int BATTERY_PROPERTY_STATUS = 6;
256 
257     private final Context mContext;
258     private final IBatteryStats mBatteryStats;
259     private final IBatteryPropertiesRegistrar mBatteryPropertiesRegistrar;
260 
261     /**
262      * @removed Was previously made visible by accident.
263      */
BatteryManager()264     public BatteryManager() {
265         mContext = null;
266         mBatteryStats = IBatteryStats.Stub.asInterface(
267                 ServiceManager.getService(BatteryStats.SERVICE_NAME));
268         mBatteryPropertiesRegistrar = IBatteryPropertiesRegistrar.Stub.asInterface(
269                 ServiceManager.getService("batteryproperties"));
270     }
271 
272     /** {@hide} */
BatteryManager(Context context, IBatteryStats batteryStats, IBatteryPropertiesRegistrar batteryPropertiesRegistrar)273     public BatteryManager(Context context,
274             IBatteryStats batteryStats,
275             IBatteryPropertiesRegistrar batteryPropertiesRegistrar) {
276         mContext = context;
277         mBatteryStats = batteryStats;
278         mBatteryPropertiesRegistrar = batteryPropertiesRegistrar;
279     }
280 
281     /**
282      * Return true if the battery is currently considered to be charging.  This means that
283      * the device is plugged in and is supplying sufficient power that the battery level is
284      * going up (or the battery is fully charged).  Changes in this state are matched by
285      * broadcasts of {@link #ACTION_CHARGING} and {@link #ACTION_DISCHARGING}.
286      */
isCharging()287     public boolean isCharging() {
288         try {
289             return mBatteryStats.isCharging();
290         } catch (RemoteException e) {
291             throw e.rethrowFromSystemServer();
292         }
293     }
294 
295     /**
296      * Query a battery property from the batteryproperties service.
297      *
298      * Returns the requested value, or Long.MIN_VALUE if property not
299      * supported on this system or on other error.
300      */
queryProperty(int id)301     private long queryProperty(int id) {
302         long ret;
303 
304         if (mBatteryPropertiesRegistrar == null) {
305             return Long.MIN_VALUE;
306         }
307 
308         try {
309             BatteryProperty prop = new BatteryProperty();
310 
311             if (mBatteryPropertiesRegistrar.getProperty(id, prop) == 0)
312                 ret = prop.getLong();
313             else
314                 ret = Long.MIN_VALUE;
315         } catch (RemoteException e) {
316             throw e.rethrowFromSystemServer();
317         }
318 
319         return ret;
320     }
321 
322     /**
323      * Return the value of a battery property of integer type.
324      *
325      * @param id identifier of the requested property
326      *
327      * @return the property value. If the property is not supported or there is any other error,
328      *    return (a) 0 if {@code targetSdkVersion < VERSION_CODES.P} or (b) Integer.MIN_VALUE
329      *    if {@code targetSdkVersion >= VERSION_CODES.P}.
330      */
getIntProperty(int id)331     public int getIntProperty(int id) {
332         long value = queryProperty(id);
333         if (value == Long.MIN_VALUE && mContext != null
334                 && mContext.getApplicationInfo().targetSdkVersion
335                     >= android.os.Build.VERSION_CODES.P) {
336             return Integer.MIN_VALUE;
337         }
338 
339         return (int) value;
340     }
341 
342     /**
343      * Return the value of a battery property of long type If the
344      * platform does not provide the property queried, this value will
345      * be Long.MIN_VALUE.
346      *
347      * @param id identifier of the requested property
348      *
349      * @return the property value, or Long.MIN_VALUE if not supported.
350      */
getLongProperty(int id)351     public long getLongProperty(int id) {
352         return queryProperty(id);
353     }
354 
355     /**
356      * Return true if the plugType given is wired
357      * @param plugType {@link #BATTERY_PLUGGED_AC}, {@link #BATTERY_PLUGGED_USB},
358      *        or {@link #BATTERY_PLUGGED_WIRELESS}
359      *
360      * @return true if plugType is wired
361      * @hide
362      */
isPlugWired(int plugType)363     public static boolean isPlugWired(int plugType) {
364         return plugType == BATTERY_PLUGGED_USB || plugType == BATTERY_PLUGGED_AC;
365     }
366 
367     /**
368      * Compute an approximation for how much time (in milliseconds) remains until the battery is
369      * fully charged. Returns -1 if no time can be computed: either there is not enough current
370      * data to make a decision or the battery is currently discharging.
371      *
372      * @return how much time is left, in milliseconds, until the battery is fully charged or -1 if
373      *         the computation fails
374      */
computeChargeTimeRemaining()375     public long computeChargeTimeRemaining() {
376         try {
377             return mBatteryStats.computeChargeTimeRemaining();
378         } catch (RemoteException e) {
379             throw e.rethrowFromSystemServer();
380         }
381     }
382 
383     /**
384      * Sets the delay for reporting battery state as charging after device is plugged in.
385      * This allows machine-learning or heuristics to delay the reporting and the corresponding
386      * broadcast, based on battery level, charging rate, and/or other parameters.
387      *
388      * @param delayMillis the delay in milliseconds, negative value to reset.
389      *
390      * @return True if the delay was set successfully.
391      *
392      * @see ACTION_CHARGING
393      * @hide
394      */
395     @RequiresPermission(permission.POWER_SAVER)
396     @SystemApi
setChargingStateUpdateDelayMillis(int delayMillis)397     public boolean setChargingStateUpdateDelayMillis(int delayMillis) {
398         try {
399             return mBatteryStats.setChargingStateUpdateDelayMillis(delayMillis);
400         } catch (RemoteException e) {
401             throw e.rethrowFromSystemServer();
402         }
403     }
404 }
405