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:
- Get the batterystats line that includes the milliseconds-since-the-epoch time of the last charger disconnection
- Use awk to strip out that time and convert it to seconds
- Subtract it from the current time to get the interval in seconds
- 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.