I want to run some task (i.e. get my web site news page) periodically (once a week/ a day), even if my application is closed. Is it possible?
3 Answers
Yes it is, you need to look at the AlarmManager to setup a reoccurring "Alarm". This is better for battery life on the device, as unlike a service it does not run constantly in the background. The Alarm triggers a broadcast receiver which will execute your custom code.
As a final note - there are enum values for the timing of the Alarm including daily, half daily and many more although you can just set an actual value.
A good example can be found in the follow SO post:
Update
Newer features have been added to Android. If you are reading this then I would advise you now look into GcmNetworkManager. This optimises battery life and works pre-lollipop. For Lollipop onwards you can use JobScheduler. I would advise using these classes over the AlarmManager.

- 1
- 1

- 25,627
- 10
- 46
- 69
-
@Graham Smith Out of interest, did you write your own? – Jake Graham Arnold Apr 30 '13 at 08:04
-
@Graham Smith The link you provided is broken. Can you provide a working link? – Zapnologica Oct 07 '13 at 21:45
-
@Zapnologica There is a good example now on SO - my link worked at the time of posting. Hope this helps – Graham Smith Oct 08 '13 at 11:06
-
1I think now the right tool for this task is shifting towards [GcmNetworkManager](https://developers.google.com/android/reference/com/google/android/gms/gcm/GcmNetworkManager). – surlac Feb 29 '16 at 18:17
I think the best fit is GcmNetworkManager. Basically it has everything you need from AlarmManager plus persistence, so job can proceed executing after reboot.
Example:
PeriodicTask task = new PeriodicTask.Builder()
.setService(MyTaskService.class)
.setTag(TASK_TAG_PERIODIC)
.setPeriod(5L)
.build();
mGcmNetworkManager.schedule(task);

- 2,961
- 2
- 22
- 31
-
1You are right - this is probably going to become the normal way of doing this. I wrote my answer 2,5 years ago so things move on. I would argue you need to add about the Lollipop Job Scheduler for Android 5+ as you don't HAVE to use the `GcmNetworkManager`. I upvoted btw. – Graham Smith Feb 29 '16 at 22:41
As an alternative I'm comparing the current week:
Calendar cal = Calendar.getInstance();
int currentWeekOfYear = cal.get(Calendar.WEEK_OF_YEAR);
SharedPreferences sharedPreferences= this.getSharedPreferences("appInfo", 0);
int weekOfYear = sharedPreferences.getInt("weekOfYear", 0);
if(weekOfYear != currentWeekOfYear){
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("weekOfYear", currentWeekOfYear);
editor.commit();
// Your once a week code here
}
I'm not advocating this is better than the Alarm solution. I'm just showing a different approach.

- 2,774
- 2
- 25
- 36
-
But where is this code actually contained? As the app is closed (not running) at this point. – Adam Burley Apr 22 '21 at 19:18