我在将来使用警报管理器来触发挂起的意图时遇到了麻烦。我已经呆了几个小时,不明白我在做什么错。任何帮助将不胜感激。
这有效,立即发送广播:
_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”(类型为long)打印到控制台,并且这绝对是有效时间(根据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);
最佳答案
有一些注意事项取决于要在其中测试警报的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);