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,
- Below method will save current time stamp in preference when battery reach 20%, 15%
- It will calculate approx estimation from above 2 saved times
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;
}