Search code examples
c#androidbattery

Calculate Time left for Device to be fully Charged android


I have an activity that contains a TextView that should show the time left for the android device that is plugged in to be fully charged... I used BatteryManager class to achieve this...i created an object from that class and discovered there is a method called ComputeChargeTimeRemaining Only problem is that the result of that method is of the data type long, and i don't know how to convert this data type to time values... That's exactly why I decided to reach out for help... Here is the code am using to do it...

class Notes : AppCompatActivity{
//TextView to show remaining charge time
TextView mytext;
//Timer to update the value of the TextView every Second 
System.Timers.Timer _timer;
protected override void OnCreate(Bundle SavedInstanceState){
  mytext=(TextView)FindViewById(Resource.Id.textView1);
_timer=new System.Timers.Timer(1000);
_timer.Enabled =true;
_timer.Elapsed += Timer_Elapsed;
  } 
private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) {
RunOnUiThread(()=>{
BatteryManager batteryManager=(BatteryManager)GetSystemService(Context.BatteryService);
long remaining_time=batteryManager.ComputeRemainingChargeTime();
//Here is where I have a problem converting the long to real hours,minutes time format, please help
}) ;
} 
} 

Solution

  • Let's visit the documentation:

    computeChargeTimeRemaining

    Compute an approximation for how much time (in milliseconds) remains until the battery is fully charged. Returns -1 if no time can be computed: either there is not enough current data to make a decision or the battery is currently discharging.

    So how can we deal with it?

    A TimeSpan should do

    var timeSpan = TimeSpan.FromMilliseconds(remaining_time);
    

    Now you have the features of TimeSpan likes Hours, Minutes, Seconds. TotalMinutes etc, you also have the format specifiers Standard TimeSpan format strings:

        var hours timeSpan.Hours;
        var minutes = timeSpan.Minutes;
        // or
        var str = timespan.ToString("hh\\:mm\\:ss"));