【问题标题】:Add an Action to Notification to show Notification again but later, like a snooze timer for notifications?向通知添加一个操作以再次显示通知,但稍后会显示通知,例如通知的打盹计时器?
【发布时间】:2013-02-18 13:14:24
【问题描述】:

我的应用显示通知。我想通过 addAction 向通知添加一个操作,导致通知消失并在一小时后重新出现,但是我不想为此打开一个活动,最好的情况是:用户单击操作,通知消失并且然后在一小时后重新出现,就像通知的打盹计时器一样。

有没有办法在不打开活动的情况下做到这一点?

感谢您的帮助

【问题讨论】:

    标签: android notifications action delay


    【解决方案1】:

    每个通知动作都来自一个 PendingIntent。当然,您不想启动活动,也不必这样做。

    根据您的情况,最好的选择是使用以下方法创建您的 PendingIntent:

    public static PendingIntent getBroadcast (Context context, int requestCode, Intent intent, int flags)
    

    这样,每当用户点击通知时,它都会在系统上生成一个广播。然后您必须创建一个BroadcastReceiver,以接收此广播并使用AlarmManager 安排另一个PendingIntent。第二个待处理的 Intent 将是一个不同的广播,只要它被触发,您的 BroadcastReceiver 就可以接收并显示新的通知。

    有意义吗?

    **编辑:

    只是为了澄清一个伪示例:

    • 您的应用在 Manifest 中注册了一个 BroadcastReceiver,以接收“com.yourapp.mybroadcast”的广播
    • 通知有一个 com.yourapp.mybroadcast PendingIntent,带有额外的 boolean isSchedule = true 和 int time = 60(60 分钟)
    • 用户点击通知,这个广播被触发,你的 BroadcastReceiver 接收到onReceive(Context context, Intent intent)
    • 在您的 onReceive 中,您读取 isSchedule=true(这意味着它必须创建一个新的计划和时间 = 60 分钟。所以它使用 AlarmManager 使用 isSchedule = 创建一个新的 Broadcast PendingIntent 错误的;将在 60 分钟内发射
    • AlarmManager 将在 60 分钟内再次调用您的 BroadcastReceiver,但这次 isSchedule = false,因此您的 BroadcastReceiver 知道它的 是时候再次显示通知了。

    【讨论】:

    • 嘿,谢谢你的回答,我明白了逻辑,但似乎无法使用以下代码:d = b.getInt("deltaMillis");日期时间警报时间 = 新日期时间();警报时间.plusMillis(d); Intent delayI = new Intent(context, MBroadcastReceiver.class); PendingIntent pi = PendingIntent.getBroadcast(context, 0, delayedIntent, PendingIntent.FLAG_CANCEL_CURRENT); AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); am.set(AlarmManager.RTC_WAKEUP, alarmTime.getMillis(), pi);从 logcat 我看到代码被执行了,但是广播没有被触发
    • 没关系,问题出在 Joda Time 上。它似乎与系统时间不完全同步。当我使用 System.currentTimeMillis()+scheduleDelta 作为通知的时间时,它起作用了!
    猜你喜欢
    • 1970-01-01
    • 2019-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多