Create an Android notification with expiration date

拜拜、爱过 提交于 2019-11-30 08:48:18

问题


I would like to create a notification in Android that has an expiration date, meaning that on a certain date, if it's not open, it will be automatically destroyed or removed. Is this possible? Does someone knows how to do this?

Thanks for your help.


回答1:


You can remove your own app's notifications if you have the notification ID by calling NotificationManager.cancel. To implement the expiration, you can set an alarm with AlarmManager to wake up a BroadcastReceiver that will simply cancel the notification. (If the notification is no longer there, then the call to cancel will do nothing.)

// post notification
notificationManager.notify(id, notification);

// set up alarm
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, MyBroadcastReceiver.class);
intent.setAction("com.your.package.action.CANCEL_NOTIFICATION");
intent.putExtra("notification_id", id);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

// note: starting with KitKat, use setExact if you need exact timing
alarmManager.set(..., pi);

In your BroadcastRecevier...

@Override
public void onReceive(Context context, Intent intent) {
    final String action = intent.getAction();
    if ("com.your.package.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);
        }
    }
}



回答2:


https://developer.android.com/reference/android/app/Notification.Builder.html#setTimeoutAfter(long)

you can specify a duration in milliseconds after which this notification should be canceled, if it is not already canceled.

from: https://stackoverflow.com/a/56072643/969016



来源:https://stackoverflow.com/questions/23874203/create-an-android-notification-with-expiration-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!