创建具有到期日在Android的通知 [英] Create an Android notification with expiration date

查看:114
本文介绍了创建具有到期日在Android的通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个Android的通知都有一个有效期,这意味着在某一特定日期,如果它不是开放的,它会自动销毁或删除。这可能吗?是否有人知道如何做到这一点?

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?

感谢您的帮助。

推荐答案

您可以通过调用的 NotificationManager.cancel 。要实现到期,您可以设置 AlarmManager 警报以唤醒一个广播接收器将干脆取消了通知。 (如果通知就不再出现,则取消呼叫会做什么。)

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, pi, PendingIntent.FLAG_UPDATE_CURRENT);

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

在您的BroadcastRecevier ...

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

这篇关于创建具有到期日在Android的通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆