[英]AlarmManager not waking up a BroadcastReceiver after the specified time
I have notifications that work perfectly.我有完美的通知。 These notifications are created by the service.
这些通知由服务创建。 When I'm trying to dismiss the notification when the user didn't tap on it for 3 minutes.
当我试图在用户没有点击它 3 分钟时关闭通知时。 I tried the solution by Karakuri here https://stackoverflow.com/a/23874764 , but nothing happened.
我在这里尝试了 Karakuri 的解决方案https://stackoverflow.com/a/23874764 ,但什么也没发生。 The alarm not working and the broadcast receiver is not called.
警报不起作用,广播接收器没有被调用。
The alarm manager in service class:服务中的警报管理器 class:
notificationManager.notify(notificationId, n);
//set up alarm
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent = new Intent(context, MyReceiver.class); intent.setAction("com.example.example.action.CANCEL_NOTIFICATION");
intent.putExtra("notification_id", notificationId);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP,180000,pi);
The broadcast receiver onReceive
method:广播接收器
onReceive
方法:
public void onReceive(Context context, Intent intent) {
// do something
final String action = intent.getAction();
Log.d("Reciver","onReceive lunched");
if ("com.example.example.action.CANCEL_NOTIFICATION".equals(action)) {
int id = intent.getIntExtra("notification_id", -1);
if (id != -1) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(id);
Log.d("Noti "+id," canceled ");
}}}
I didn't deal with the alarm manager before.我之前没有和警报管理器打过交道。 I researched to know the reason but I didn't find, I hope anyone help me with this
我研究了知道原因,但我没有找到,希望有人能帮助我解决这个问题
You should use alarmManager.setExactAndAllowWhileIdle
method instead of alarmManager.set
if you need it to fire exactly at requested time.如果您需要在请求的时间准确触发,您应该使用
alarmManager.setExactAndAllowWhileIdle
方法而不是alarmManager.set
。
Also, you set time wrong.另外,您设置的时间错误。 It has to be
System.currentTimeMillis() + 180000
if you want alarm to fire 3 minutes from current moment.如果您希望警报从当前时刻开始 3 分钟触发,则它必须是
System.currentTimeMillis() + 180000
。
Finally, check if you have added SET_ALARM
permission and declared your broadcast receiver in your AndroidManifest.xml
.最后,检查您是否添加了
SET_ALARM
权限并在您的AndroidManifest.xml
中声明了您的广播接收器。
You can use Handler it's easier than using Alarm Manager.您可以使用 Handler,它比使用 Alarm Manager 更容易。 Since you are working in Service, use a Looper
由于您在 Service 中工作,因此请使用 Looper
Here already accepted answers will guide you:这里已经接受的答案将指导您:
Clearing notification after a few seconds 几秒钟后清除通知
Using Handler inside service 在服务内部使用 Handler
I hope I could help!我希望我能帮上忙!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.