Karthi Ponnusamy
Karthi Ponnusamy

Reputation: 2031

Estimate remaining battery time in android

I am trying to estimate the approx. remaining battery time in Android using below method, but it is not accurate in all the times. Please provide any suggestion to improve the accuracy,

Thanks

public static String getBatteryEstimation(Context context){
    String contentText = "";
    try{
        //timestamp recorded when battery reach 20%
        long time1 = PreferencesUtil.getInstance().getLong(PreferencesUtil.KEY_BATTERY_THERESHOLD_TIME_1);

        //timestamp recorded when battery reach 15%
        long time2 = PreferencesUtil.getInstance().getLong(PreferencesUtil.KEY_BATTERY_THERESHOLD_TIME_2);

        long timeDiffInMillis = time2 - time1;
        long timeTakenFor1Percentage = Math.round(timeDiffInMillis/5);
        long timeLastForNext15Percentage = timeTakenFor1Percentage * 15;

        long hoursLast = Math.abs(TimeUnit.MILLISECONDS.toHours(timeLastForNext15Percentage));
        long minutesLast = Math.abs(TimeUnit.MILLISECONDS.toMinutes(timeLastForNext15Percentage)-                             TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(timeLastForNext15Percentage)));

        String timeLastMessage = "";
        if(hoursLast > 0){
            timeLastMessage = String.valueOf(minutesLast)+" hour(s) "+String.valueOf(minutesLast) + " min(s)";
        } else {
            timeLastMessage = String.valueOf(minutesLast) + " min(s)";
        }

        DateFormat dateFormat = new SimpleDateFormat("HH:mm dd MMM");
        Date date = new Date();
        contentText = String.format(context.getString(R.string.battery_low_content_1), timeLastMessage, dateFormat.format(date));
    } catch (Exception e){
        e.printStackTrace();
    }

    return contentText;
}

Upvotes: 3

Views: 3143

Answers (1)

Rikin Prajapati
Rikin Prajapati

Reputation: 1943

Estimating the remaining battery life is based on analytics. As the other people said you have to listen for battery level changes and in addition you have to keep track of them. After some time you will have enough data to calculate what is the average time the battery lasts. In addition you know when the battery drains fast and when drains slow so you can improve your estimation based on this. Also you will know in what time the user charges the devices. There are a lot of events that can be tracked and using the battery level. In addition you can also track when the screen is on or off. The algorithm of calculating the remaining battery life depends on you :)

You can try this :

Collect all information from the battery statistics, and count the usage in total. Then calculate the usage per second, how much the battery was drained per second.

Get the battery capacity in mAh, and calculate the remaining live with this formula: total capacity per speed of the usage

I hope this explains (at least a bit).

Upvotes: 2

Related Questions