0

I'm trying to make an app that does certain tasks according to a certain battery level (say a notification when battery level reaches 10%). The problem is when i launch it the app just checks the event once instead of continuous monitoring. e.g. (say i launched the app when battery was 11%. Since the notification is scheduled at 10% it wont give any notification. It just check the event a single time instead of continuously monitoring i.e. when battery drains to 10% while running the app,nothing happens) What is the possible solution to make the code run continuously ?

codenamered5
  • 63
  • 1
  • 1
  • 10
  • Using a service. And having a timed, looped check on the battery level. Or if you just want to check when your activity is open, just add the timed loop on there instead. – IAmGroot Sep 23 '16 at 08:21
  • Could you use the AlarmManager class set to a certain number of seconds into the future but only trigger a notification if the battery level has dropped to one of your margins? – Ben Sep 23 '16 at 08:28
  • @Doomsknight that's exactly i wanted to know..how to implement a timed loop – codenamered5 Sep 23 '16 at 08:51
  • @Ben sorry but i didn't actually understood what you're suggesting. Can you please elaborate it more ? – codenamered5 Sep 23 '16 at 08:55
  • Alarm manager is a good way of achieving a timed loop. [some solutions](http://stackoverflow.com/questions/21726055/android-loop-part-of-the-code-every-5-seconds) and some more [alarmmanager example](http://stackoverflow.com/questions/11434056/how-to-run-a-method-every-x-seconds) – IAmGroot Sep 23 '16 at 10:21
  • The solutions Doomsknight sent should help, I also found this: https://developer.android.com/training/scheduling/alarms.html. I've used the Alarm manager in previous applications to send a notification a certain time into the future. So thought you could instead use it to trigger your battery check. – Ben Sep 24 '16 at 10:02

1 Answers1

0

Try using the Alarm Manager Class: developer.android.com/training/scheduling/alarms.html.

If you pass in your battery check as the pending intent, the trigger time which is when you first want to check (In your case probably the interval time after the current time) and then an interval time (Too often can slow things down a lot, so try to find a time that suits your application, e.g. every few minutes.)

This should then fire on each interval which you could use to trigger your battery check and further functionality.

Ben
  • 102
  • 1
  • 2
  • 11