Android AlarmManager.setExact()未触发

时间:2018-03-15 20:18:26

标签: java android android-intent broadcastreceiver alarmmanager

我在将来使用警报管理器触发待处理的意图时遇到问题。我已经好几个小时了,不明白我做错了什么。任何帮助将不胜感激。

这很有效,立即发送广播:

_context.startService(notificationIntent);

这可行,在~30秒内发送广播:

if (mgr != null) 
mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,  SystemClock.elapsedRealtime() + 30000, AlarmManager.INTERVAL_DAY * 7, pendingNotificationIntent);

这可行,在~30秒内发送广播:

if (mgr != null) 
mgr.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 30000, AlarmManager.INTERVAL_DAY * 7, pendingNotificationIntent);

但由于某些未知原因,这样做失败了。广播永远不会被触发。当我使用System.currentTimeMillis(),并从我的触发器中减去它...它表明触发器确实在将来:

if (mgr != null) 
mgr.setExact(AlarmManager.RTC_WAKEUP, trigger, pendingNotificationIntent);

我正在将变量'trigger'(长型)打印到控制台,这绝对是一个有效的时间(根据epochconverter.com)。它当前正在打印的值(仅供参考)是1521144300000,几分钟前就已经过去了......就没有发出警报;

以下是大部分设置:

Intent notificationIntent = new Intent(_context, com.example.example.NotificationReceiver.class)
                            .setAction(ACTION_SHOW_NOTIFICATION)
                            .putExtra(EXTRA_NOTIFICATION_TITLE, _title)
                            .putExtra(EXTRA_NOTIFICATION_BODY, newBody)
                            .putExtra(EXTRA_NOTIFICATION_TRIGGER_TIME, trigger);


                    AlarmManager mgr = (AlarmManager) _context.getSystemService(Context.ALARM_SERVICE);

                    PendingIntent pendingNotificationIntent = PendingIntent.getBroadcast(_context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

                    Log.d(TAG, "trigger time: " + trigger);

                    if (mgr != null) mgr.setExact(AlarmManager.RTC_WAKEUP, trigger, pendingNotificationIntent);

我从后端收到触发时间,这在每个响应中都是正确的。

这也永远不会发生:

if (mgr != null) mgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, trigger, AlarmManager.INTERVAL_DAY * 7, pendingNotificationIntent);

1 个答案:

答案 0 :(得分:1)

在您测试闹钟的Android版本中有一些注意事项,但如果您正在测试Android 6或更高版本,请尝试下一个代码:

// Init the Alarm Manager.
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); 

// Setting the PendingIntent to be fired when alarm triggers.
Intent serviceIntent = new Intent(context.getApplicationContext(), YourService.class);
PendingIntent pendingServiceIntent = PendingIntent.getService(context, 0, serviceIntent, 0);

// Set the alarm for the next seconds.  
alarmManager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + seconds * 1000, pendingServiceIntent);