[英]How to call some task once app is in resume status in every 15minutes
I want to perform an action on every 15 minutes once the device become sleep mode or app is in background.一旦设备进入睡眠模式或应用程序处于后台,我想每 15 分钟执行一次操作。 I tried it with broadcast Receiver as shown below.
我尝试使用广播接收器,如下所示。 But it's only working for first few minutes.
但它只在最初的几分钟内起作用。 After that the action is not happening.
之后,该动作没有发生。
BroadcastReceiver广播接收器
public class KeepReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
Log.d("Keep","status");
context.sendBroadcast(new Intent("KEEP_RECEIVER"));
}
}
sendBroadcast be like below.:发送广播如下:
BroadcastReceiver broadcastReceiver2 = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("Active","status");
}
});
Here onReceive from KeepReceiver is called but sendBroadcast onReceive is not working after few minutes.这里调用了来自 KeepReceiver 的 onReceive,但几分钟后 sendBroadcast onReceive 不起作用。
Methid called on onPause of main activity Methid 调用主要活动的 onPause
private void timeout() {
Date when = new Date(System.currentTimeMillis());
Calendar now = Calendar.getInstance();
now.set(Calendar.MINUTE, 0);
now.set(Calendar.SECOND, 0);
now.set(Calendar.MILLISECOND, 0);
try {
Intent someIntent = new Intent(getApplicationContext(), KeepReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),0, someIntent, PendingIntent.FLAG_CANCEL_CURRENT);
int repeatingInterval = 100000;
AlarmManager alarmManager =(AlarmManager)getApplicationContext().getSystemService(Activity.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), repeatingInterval , pendingIntent);
} catch(Exception e) {
e.printStackTrace();
}
}
Please advise if anything wrong with the implementation.请告知执行是否有任何问题。 Thanks in advance
提前致谢
There are a few problems here.这里有几个问题。 You cannot reliably set a repeating alarm at 100 second (less than 2 minute) intervals, as you are trying to do.
您无法像您尝试做的那样以 100 秒(少于 2 分钟)的间隔可靠地设置重复警报。 Repeating alarms are also not accurate as Android can delay them to avoid battery drain.
重复警报也不准确,因为 Android 可以延迟警报以避免电池耗尽。
To achieve a repeating alarm with 15 minute intervals, you should set a single alarm using set()
or setExact()
(if you need exact timing) for a time 15 minutes in the future.要实现以 15 分钟为间隔的重复闹钟,您应该使用
set()
或setExact()
(如果您需要精确的时间)设置一个闹钟,时间为未来 15 分钟。 When that alarm goes off, do whatever you need to do and then set another alarm for 15 minutes in the future, etc.当那个闹钟响起时,做你需要做的任何事情,然后在未来设置另一个闹钟 15 分钟,等等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.