-2

I'm trying to raise a method to get the battery level every 20 minutes. so my application should run in a normal way, while my method is getting called every 20 minutes in the background.

So for getting the battery level I'm using Xam.plugin.Battery from Nuget, so that's not a problem. As for the other part, I think I should use another thread for that so that my app works in a normal way while my method of getting battery is getting called in the background every 20 minutes. The thing is: I don't know how to do this.

Thank you

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Shahid Od
  • 103
  • 4
  • 13
  • first you have to read, how to create a background service, those will restart automatically. Something like this: https://xamarinhelp.com/xamarin-background-tasks/ Then you can just use a normal timer. i would set a timestamp on "20 min task run" and save timestamp to some config file. then on timer.tick compare timestamp to current time. if its time to run your task then go for it. – Charles Nov 23 '19 at 12:34
  • Possible duplicate of [Does Xamarin.Forms support periodic background tasks?](https://stackoverflow.com/questions/34923444/does-xamarin-forms-support-periodic-background-tasks) – Ivan Ičin Nov 23 '19 at 22:39

1 Answers1

0

Start timer is what you want.

    Device.StartTimer(TimeSpan.FromMinutes(20), () => //Will start after 20 min
    {
        Task.Run(async () =>
  {
    var time = await DoYourBatteryWork();
    // do something with time...
  });

        return true; // To repeat timer,always return true.If you want to stop the timer,return false
    });    
}
bhavya joshi
  • 1,096
  • 10
  • 20