5

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!

roiberg
  • 13,629
  • 12
  • 60
  • 91

2 Answers2

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
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