简体   繁体   中英

Call a method every x minutes

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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM