Frage

How can I determine programmatically the last time I charged my phone? What I'm looking for is something that in a TextView called time shows me:

Last time on charge: 3h ago

and of course if is charging will be

Last time on charge: 0h ago

or something like this. I think I have to register an AlarmManager but I'm nit sure. I just want to create this estimate nothing more. How can do it?

War es hilfreich?

Lösung

I don't think android straight away provides an API for the last-charge time.

Alternatively, you could register for Broadcasts e.g.

ACTION_POWER_DISCONNECTED/ACTION_POWER_CONNECTED

and save the time whenever the charger is disconnected and use that in your app.

Andere Tipps

On Android 5.0 and higher, add the permissions:

<uses-permission android:name="android.permission.DUMP" />
<uses-permission android:name="android.permission.BATTERY_STATS" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Then from your app use Runtime.exec() to execute dumpsys batterystats --checkin --charged. In the output (CSV), you will find a line that looks like this with bt in the 4th column:

9,0,l,bt,6,208938,208938,15441248,15441248,1434662557297,0,0

The number in the 10th column (1434662557297 in this case) is the timestamp (in milliseconds since the Epoch) of the last time the device finished a full charge — i.e., when you disconnected it. Subtracting that from the current date and time (to get the time since the charge) is easy enough.

If you want to do this from an adb shell, I did come up with a somewhat complicated command you could save to a script to yield a 1d 2h 3m style format:

busybox expr $(date +%s) - $(dumpsys batterystats --checkin | grep "l,bt" | busybox awk -F',' '{printf "%i", $10/1000}') | busybox awk '{printf "%id %ih %im\n", $1/60/60/24, $1/60/60 % 24, $1/60 % 60}'

To explain that:

  1. Get the batterystats line that includes the milliseconds-since-the-epoch time of the last charger disconnection
  2. Use awk to strip out that time and convert it to seconds
  3. Subtract it from the current time to get the interval in seconds
  4. Use awk to format it

If you care about any charge rather than the last full charge, look at the 6th column in the batterystats --checkin "bt" line — that's milliseconds since the last disconnection from the charger. This also works on earlier versions of Android with batteryinfo instead of batterystats.


These values do not reflect if the charger is currently connected, so you should listen to the intents described by Gaurav Arora's answer for that.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top