Running task periodicaly(once a day/once a week)

匿名 (未验证) 提交于 2019-12-03 09:02:45

问题:

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?

回答1:

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:

Alarm Manager Example

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.



回答2:

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


回答3:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!