Call a method every x minutes

2019-09-17 09:15发布

currently I have a application which can send notifications, I would like this application to be able to send these notifications automatically every x minutes (for example, 15 minutes is the default). The app may or may not be currently running when this notification should be sent.

After some reading, I've determined that an AlarmManager would be used here, but I cannot figure out how to call a method from it. I already have the notification code, I just need a way to call it every x minutes.

I'm very new to this, this is my first practice app (having experience in C#, but little in Java).

Thanks, David.

3条回答
兄弟一词,经得起流年.
2楼-- · 2019-09-17 09:33

If you want to schedule your tasks with the specified interval don't use flags AlarmManager.RTC and AlarmManager.RTC_WAKEUP with method alarm.setRepeating(...). Because in this case alarm will be bounded to the device's real time clock. So changing the system time may cause alarm to misbehave. You must use flags AlarmManager.ELAPSED_REALTIME or AlarmManager.ELAPSED_REALTIME_WAKEUP. In this case SystemClock.elapsedRealtime() will serve as a basis for scheduling an alarm.

The code will look like:

alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + checkIntervalMillis, checkIntervalMillis, pendingIntent);

If you want your long running task to be executed when device in the sleep mode I recommend to use WakefulIntentService library by CommonsWare: https://github.com/commonsguy/cwac-wakeful

查看更多
欢心
3楼-- · 2019-09-17 09:34

Write a IntentService. Inside it, just start a new Thread. In the Thread.run(), put an infinite while loop to call your notification code and Thread.sleep(15 * 60 * 1000)....

查看更多
女痞
4楼-- · 2019-09-17 09:42

You might want to consider something like this:

Intent intent = new Intent(this, MyService.class);
PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0);

AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
// Start every 30 seconds
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 30*1000, pintent); 

If you are unclear, go through this tutorial

查看更多
登录 后发表回答