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 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
I hope I could help!