-6

Im looking for the best way to complete a certain task when a certain date is reached. What is the best way to a achieve this?

ie. 1st of each month I run command y

user3175140
  • 511
  • 3
  • 6
  • 15
  • you should go through android dev docs before posting a question here. – Yash Jan 20 '17 at 05:51
  • Possible duplicate of [Scheduling recurring task in Android](http://stackoverflow.com/questions/14376470/scheduling-recurring-task-in-android) – Yash Jan 20 '17 at 05:52

1 Answers1

2

Use AlarmManager. You'll also need a BroadcastReceiver for the BOOT_COMPLETED message so you can restart the alarm if the phone is rebooted. TO calculate when the 1st day of the next month is, use the Calendar class- get the Calendar for now, then add 1 to the month and set the day to 1. Then you can convert that to ms for the alarm.

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
  • What about `JobScheduler` ? : – OBX Jan 20 '17 at 05:50
  • @Superman The problem with JobScheduler is that it doesn't promise to do a job at a specific time- it promises to do it when a set of constraints are met. Which for a timed job may actually get weird- you can set a minimum delay, and a maximum delay, but it can fire at any time in that window. I'm not sure what happens if you make mintime=maxtime, if that gives you a very small window or if it throws an exception for a bad builder. ALthough it can persist things across reboots which may make it worth using to save a bit of effort there. – Gabe Sechan Jan 20 '17 at 06:01
  • Again from the perspective of battery, wouldn't that be ideal ? :/ – OBX Jan 20 '17 at 06:15
  • @Superman For a once a month task? You're talking such a small energy difference I doubt you could measure it on an mutimeter. Now its possible that for a once a month task the timing doesn't matter much either. Hard to say without knowing all the details of the task. I definitely wouldn't say using JobScheduler was wrong though. Of course also note that JobScheduler is v21+. v19 is still 20+% of the worldwide market. – Gabe Sechan Jan 20 '17 at 06:18
  • I see thanks for the info, I forgot it was once in a month task :) . It seems Firebase job dispatcher is the same JobScheduler with backward compatibility , have you tried it ? – OBX Jan 20 '17 at 06:22
  • https://github.com/firebase/firebase-jobdispatcher-android – OBX Jan 20 '17 at 06:22
  • btw, I've also sent a 'Hi' in Fb, not sure if it's your profile though :) – OBX Jan 20 '17 at 06:22