简体   繁体   中英

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. I tried the solution by Karakuri here https://stackoverflow.com/a/23874764 , but nothing happened. The alarm not working and the broadcast receiver is not called.

The alarm manager in service 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:

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.

Also, you set time wrong. It has to be System.currentTimeMillis() + 180000 if you want alarm to fire 3 minutes from current moment.

Finally, check if you have added SET_ALARM permission and declared your broadcast receiver in your AndroidManifest.xml .

You can use Handler it's easier than using Alarm Manager. Since you are working in Service, use a Looper

Here already accepted answers will guide you:

Clearing notification after a few seconds

Using Handler inside service

I hope I could help!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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