get how much time i have before the battery goes to 0% Android

随声附和 提交于 2019-12-02 08:54:06

Short answer: No.

Long answer: Yes, you can.. But not that easily.. Because you don't know how much energy does the device consume at a time basis, you should first try to find that out and then calculate the remaining time using that data...

As you might have guessed already, it might not be that accurate at first but the more you sample, the more accurate that data will be.. So to conclude here is what you have to do:

First when the user opens the app, because you don't have enough data about energy consumption, You should just display something like Calculating.... Here you should decide to have a sample time. That is something like derivation in math..

Let's say you have a sample time of 10 seconds. ( Your actual one should be bigger I guess. )

You should have a variable named something like level1.. Save the current level to it. Wait for the amount of sample time which is now 10 seconds.. Now save the current value to level2.. Save the level1 - level2 product to another variable like consumed.

Now here is the magic. You know how much power has been consumed in 10 seconds (That is the consumed variable).. From now on you can calculate the remaining time using that data. But remember it's still one 10 second. What if that 10 seconds user was playing a heavy game or even the device was on stand by? That is why it's not accurate. But until now..

What you can do is to add the consumed variable to an array named like sample_data. Let the process go on and sample the consumption every 10 seconds and add it to the array. The more data you get, the more accurate your calculation will be.

Then you can easily calculate the time remaining using the average of samples in the array.. Easy Peasy :p

You can not accurately guess that how much time is remaining for battery discharge, you can just make some estimation.

You can get battery life with help of broadcast receiver by registering a receiver for action Intent.ACTION_BATTERY_CHANGED

battery_level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);

Edit:

What you should do, is periodically get the battery_level and check how much battery is being consumed per minute / per hour, and make some calculations.

So if your battery is 80% an decreasing 4% per hour, you have 20 hours estimated battery life

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!