senzacionale
senzacionale

Reputation: 20916

Android get battey time from battery view

Here I can see how long will phone work on battery? Can I somehow get this information in my application?

Here is code for getting battery health temperature, but I don't need this. I just need time as shown in this view:

enter image description here

Upvotes: 0

Views: 2516

Answers (3)

sak
sak

Reputation: 21

I guess you can using BatterStatusImpl and an IInterface called IBatteryStats these are private apis fork them from android git

Upvotes: 2

Aleks G
Aleks G

Reputation: 57326

I don't think you can get this value directly from the battery info. What you can do however is this.

  1. Read percentage remaining (e.g. x%) and current timestamp
  2. Register a broadcast receiver for battery level changes - and in onReceive read the new percentage (e.g. y%, usually it would be x - 1, but it may be x - 2 or whatever) and get the timestamp again
  3. Get the difference between the two timestamps and the two percentages (x - y) - this will show how much time the (x - y)% of battery lasts. Now just extrapolate that to y% - and you have your answer

And you can use the code in the question that you linked to determine the percentage.

For example, you get 80% battery at timestamp 1361882535654. Then when you get 79%, your timestamp is 1361882801234. This means that 1% of battery lasts about 265 seconds, hence the remaining time on the battery is approximately 79 * 265 = 209305 seconds, which is 2 days 10 hours 8 minutes and 25 seconds.

Yes, this naturally takes some time (i.e. you have to wait those 200 or whatever seconds for the battery power to go down). The reason your system app can display it immediately is because the system process runs in the background continuously and most likely does that as it goes along.

Upvotes: 5

g00dy
g00dy

Reputation: 6778

Take a look at Intent.ACTION_POWER_USAGE_SUMMARY

Upvotes: 1

Related Questions