繁体   English   中英

每x分钟调用一次方法

[英]Call a method every x minutes

当前,我有一个可以发送通知的应用程序,我希望该应用程序能够每隔x分钟自动发送这些通知(例如,默认为15分钟)。 发送此通知时,该应用程序当前可能正在运行或可能未运行。

经过一番阅读后,我确定这里将使用AlarmManager,但是我不知道如何从中调用方法。 我已经有了通知代码,我只需要一种每x分钟调用一次的方法。

我对此很陌生,这是我的第一个练习应用程序(在C#中有经验,但是在Java中却很少)。

谢谢大卫。

您可能要考虑这样的事情:

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

如果你不清楚,经过教程

编写一个IntentService 在其中,只需启动一个新的Thread Thread.run() ,放入一个无限的while循环来调用您的通知代码,然后将Thread.sleep(15 * 60 * 1000) ....

如果AlarmManager.RTC指定的时间间隔计划任务,请不要使用带有方法alarm.setRepeating(...)标志AlarmManager.RTCAlarmManager.RTC_WAKEUP 因为在这种情况下,警报将限制在设备的实时时钟上。 因此,更改系统时间可能会导致警报异常。 您必须使用标志AlarmManager.ELAPSED_REALTIMEAlarmManager.ELAPSED_REALTIME_WAKEUP 在这种情况下, SystemClock.elapsedRealtime()将用作安排警报的基础。

代码如下所示:

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

如果您希望设备在睡眠模式下执行长时间运行的任务,我建议使用CommonsWare的WakefulIntentService库: https : //github.com/commonsguy/cwac-wakeful

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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