-1

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

han cs
  • 13
  • 1

2 Answers2

1

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.

0awawa0
  • 328
  • 2
  • 5
0

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!

Alhanoof
  • 98
  • 1
  • 2
  • 8