简体   繁体   English

每x分钟调用一次方法

[英]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). 当前,我有一个可以发送通知的应用程序,我希望该应用程序能够每隔x分钟自动发送这些通知(例如,默认为15分钟)。 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. 经过一番阅读后,我确定这里将使用AlarmManager,但是我不知道如何从中调用方法。 I already have the notification code, I just need a way to call it every x minutes. 我已经有了通知代码,我只需要一种每x分钟调用一次的方法。

I'm very new to this, this is my first practice app (having experience in C#, but little in Java). 我对此很陌生,这是我的第一个练习应用程序(在C#中有经验,但是在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 . 编写一个IntentService Inside it, just start a new Thread . 在其中,只需启动一个新的Thread In the Thread.run() , put an infinite while loop to call your notification code and Thread.sleep(15 * 60 * 1000) .... Thread.run() ,放入一个无限的while循环来调用您的通知代码,然后将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(...) . 如果AlarmManager.RTC指定的时间间隔计划任务,请不要使用带有方法alarm.setRepeating(...)标志AlarmManager.RTCAlarmManager.RTC_WAKEUP 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 . 您必须使用标志AlarmManager.ELAPSED_REALTIMEAlarmManager.ELAPSED_REALTIME_WAKEUP In this case SystemClock.elapsedRealtime() will serve as a basis for scheduling an alarm. 在这种情况下, SystemClock.elapsedRealtime()将用作安排警报的基础。

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

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

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