[英]AlarmManager not always executing
I'm developing an android app that sends every 5 minutes a post to a server so this way, the server can check if the phone has or not connection. 我正在开发一个Android应用程序,每5分钟发送一个帖子到服务器,这样,服务器可以检查手机是否有连接。
I'm using AlarmManager
, sending a broadcast PendingIntent
to a BroadcastReceiver
which sends a post to a server. 我正在使用AlarmManager
,将广播PendingIntent
发送到BroadcastReceiver
,后者向服务器发送帖子。 The issue is that it is not always executing: 问题是它并不总是执行:
Intent myIntent = new Intent(Inicio.this, NetworkStatusReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(Inicio.this,
0,
myIntent,
0);
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
int interval = 60000*5;
manager.setRepeating(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis(),
interval,
pendingIntent);
Is the AlarmManager
class the right way to do this? AlarmManager
类是否是正确的方法?
Because I've been researching about 5.0+ android versions and the power management is different from the earlier android versions. 因为我一直在研究5.0+以上的Android版本,电源管理与早期的Android版本不同。 Maybe the AlarmManager.RTC_WAKEUP
option is not working on 5.0+ android versions. 也许AlarmManager.RTC_WAKEUP
选项不适用于5.0+以上的Android版本。
I have done some research and I've found something that seems to work. 我做了一些研究,我发现了一些似乎有用的东西。 Since this morning, I implemented it and the behavior has improved very much. 从今天早上开始,我实施了它,行为也得到了很大改善。 I realized that having a BroadcastReceiver
I could just set the alarm once and set another alarm again on the BroadcastReceiver
itself when the alarm was being triggered. 我意识到拥有一个BroadcastReceiver
我可以设置一次警报,并在触发警报时再次在BroadcastReceiver
上设置另一个警报。
I also used the flag PendingIntent.FLAG_UPDATE_CURRENT
for the PendingIntent
(since the alarm PendingIntent
can be triggered from different activities) 我还为PendingIntent
使用了标志PendingIntent.FLAG_UPDATE_CURRENT
(因为可以从不同的活动触发警报PendingIntent
)
The code for the Activity
would be something like this: Activity
的代码是这样的:
Intent myIntent = new Intent(context, NetworkStatusReceiver.class);
final PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
final AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
manager.set(AlarmManager.RTC_WAKEUP,System.currentTimeMillis() + timeInMillis, pendingIntent);
And the code for the BroadcastReceiver.OnReceive()
method would be the same code so the alarm triggers every System.currentTimeMillis() + timeInMillis
again (creating this way the setRepeating()
method) 并且BroadcastReceiver.OnReceive()
方法的代码将是相同的代码,因此警报再次触发每个System.currentTimeMillis() + timeInMillis
(以这种方式创建setRepeating()
方法)
This way it seems that the alarm is always triggered since (I think) set()
method from AlarmManager
works fine with any android version. 这种方式似乎总是触发警报,因为(我认为)来自AlarmManager
set()
方法适用于任何Android版本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.