【问题标题】:Create an Android notification with expiration date创建带有到期日期的 Android 通知
【发布时间】:2019-08-02 19:01:21
【问题描述】:

我想在 Android 中创建一个具有到期日期的通知,这意味着在某个日期,如果它没有打开,它将被自动销毁或删除。这可能吗?有人知道怎么做吗?

感谢您的帮助。

【问题讨论】:

  • 您可以使用警报管理器运行后台服务来使用通知 ID 删除通知
  • 任何服务都可以通过拥有其通知 ID 来删除任何应用的通知?

标签: android notifications android-notifications


【解决方案1】:

如果您有通知 ID,则可以通过调用 NotificationManager.cancel 删除自己应用的通知。要实现过期,您可以使用AlarmManager 设置警报以唤醒BroadcastReceiver,这将简单地取消通知。 (如果通知不再存在,那么取消调用将不会执行任何操作。)

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

在您的广播接收器中...

@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)

您可以指定一个持续时间(以毫秒为单位),如果该通知尚未取消,则在此之后应取消该通知。

来自: https://stackoverflow.com/a/56072643/969016

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-13
    • 2015-02-04
    • 2016-01-11
    • 1970-01-01
    • 2020-09-07
    • 2017-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多