I have a method that I need to run every few hours even if the user didn't reopen the app. What is the best way to go? Should I use the Timer class or Alarm manager? Thanks!
Asked
Active
Viewed 1.7k times
2 Answers
16
Step 1: Define 'Service' class to define logic to be executed
Ste 2: Define BroadcastReceiver and add in manifest xml. This is responsible for calling 'Service' class to do the task.
May be you need add intent action <action android:name="android.intent.action.BOOT_COMPLETED"/>
under in manifest xml
Step 3: Use 'AlarmManager' to schedule to repeat
couple links might help http://www.vogella.com/articles/AndroidServices/article.html#scheduleservice_scheduling
http://khurramitdeveloper.blogspot.in/2013/06/android-alarm-manager-to-start-service.html

Jayasagar
- 2,046
- 19
- 22
-
Thanks for your answer! I would have accepted it but the other answer was first. – roiberg Oct 29 '13 at 08:40
-
1Thanks. No problem :), I would be happy if it helps you :) – Jayasagar Oct 29 '13 at 08:43
-
@Jayasagar Why would you need a `Service`? – sdabet Aug 24 '16 at 15:23
-
@fiddler to start it after phone reboot. – Acuna Dec 29 '17 at 16:03
-
Thanks a lot, it's really helpful! – Acuna Dec 29 '17 at 16:03
8
You should use AlarmManager to schedule services for this. See this Vogella tutorial.

Amith
- 6,818
- 6
- 34
- 45

Anup Cowkur
- 20,443
- 6
- 51
- 84
-
Will this work even after the phone was reseted or force close of the app? – roiberg Oct 29 '13 at 08:10
-
Nothing works anymore if someone resets the phone to factory settings. Force closing might kill the services for a while, but you can make it boot up again. – Stefan de Bruijn Oct 29 '13 at 08:12
-
I didn't mean factory reset, I meant restarting the phone... Should I use a broadcast receiver for the restarting or will it work without it? – roiberg Oct 29 '13 at 08:13
-
You need to register a broadcast receiver that listens to boot event and sets up the alarm again. See : http://stackoverflow.com/questions/12512717/android-alarmmanager-after-reboot – Anup Cowkur Oct 29 '13 at 08:16