alarmmanager在指定时间后未唤醒broadcastreceiver

ua4mk5z4  于 2021-07-09  发布在  Java
关注(0)|答案(2)|浏览(411)

我收到的通知非常有效。这些通知由服务创建。当我试图取消通知时,用户有3分钟没有点击它。我试过卡拉库里的方法https://stackoverflow.com/a/23874764,但什么也没发生。警报不工作,广播接收器未被调用。
服务类中的报警管理器:

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);

广播接收器 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 ");
}}}

我以前没和报警经理打过交道。我想知道原因,但没找到,希望有人能帮我

g6baxovj

g6baxovj1#

你应该使用 alarmManager.setExactAndAllowWhileIdle 方法而不是 alarmManager.set 如果你需要它在要求的时间开火。
而且,你把时间定错了。一定是的 System.currentTimeMillis() + 180000 如果你想从当前时刻开始3分钟后报警。
最后,检查是否添加了 SET_ALARM 允许并声明您的广播接收器在您的 AndroidManifest.xml .

jtw3ybtb

jtw3ybtb2#

您可以使用处理程序,这比使用报警管理器更简单。既然你在服役,就用活套
这里已经接受的答案将指导您:
几秒钟后清除通知
在服务内部使用处理程序
希望我能帮上忙!

相关问题