简体   繁体   English

AlarmManager不定期射击

[英]AlarmManager Not Firing Regularly

I'm working on an app that involves an AlarmManager, and I can't seem to get it to fire. 我正在开发一个涉及AlarmManager的应用程序,我似乎无法解决它。 I was using a Handler originally, but I switched over to the AlarmManager so that I can wake the phone up from sleep. 我最初使用的是Handler,但是我切换到了AlarmManager,这样我就可以将手机从睡眠中唤醒。

Here's what I have so far: 这是我到目前为止所拥有的:

int timeBetweeninMillis = 3 * 60000;    
if (ManagerService.serviceRunning) {
            Intent alarmIntent = new Intent(AlarmReceiver.ACTION_RECEIVE);
            PendingIntent alarmPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 400, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, (SystemClock.elapsedRealtime() + timeBetweeninMillis), alarmPendingIntent);
        }

The AlarmManager either won't fire or will fire extremely late (like 10 minutes after). AlarmManager要么不会开火,要么会非常晚(例如10分钟后)。

The app is written with API 16 and is being tested on a phone with API 19. 该应用程序使用API​​ 16编写,正在使用API​​ 19的手机上进行测试。

Thank you for your help! 谢谢您的帮助!

There's an issue with new PendingIntent s recycling existing PendingIntent s that might cause issues with AlarmManager . 新的PendingIntent回收现有的PendingIntent可能会导致AlarmManager问题。

To workaround that, I always add a unique value to all my PendingIntent s, this one-liner does the trick in most cases: 为了解决这个问题,我总是为我的所有PendingIntent添加一个唯一值,这个PendingIntent在大多数情况下都能解决问题:

Intent alarmIntent = new Intent(AlarmReceiver.ACTION_RECEIVE);

alarmIntent.setData(Uri.parse("custom://" + System.currentTimeMillis())); // MAKE INTENT UNIQUE

PendingIntent alarmPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 400, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, (SystemClock.elapsedRealtime() + timeBetweeninMillis), alarmPendingIntent);

Also, I don't know what's ManagerService.serviceRunning in your code, but I would add some log to the else case to make sure you're actually running that code block. 另外,我不知道代码中的ManagerService.serviceRunning是什么,但我会在else情况下添加一些日志以确保您实际运行该代码块。

EDIT: 编辑:

try using mAlarmManager.setExactAndAllowWhileIdle instead of mAlarmManager.set this will force AlarmManager to call your code exactly when requested, and prevent device idle time from interfering with the alarm. 尝试使用mAlarmManager.setExactAndAllowWhileIdle而不是mAlarmManager.set这将强制AlarmManager在请求时准确调用您的代码,并防止设备空闲时间干扰警报。

See: https://developer.android.com/reference/android/app/AlarmManager.html#setExactAndAllowWhileIdle(int, long, android.app.PendingIntent) 请参阅: https//developer.android.com/reference/android/app/AlarmManager.html#setExactAndAllowWhileIdle(int,long,android.app.PendingIntent)

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

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