棒棒糖系统:当点击后,悬浮通知会被取消。

4

我已经搜索了相当长的一段时间,但是无法找到答案。我的应用程序使用Notification.PRIORITY_HIGH显示通知,这会导致它在Lollipop上显示为悬浮通知。

问题在于,即使未设置Notification.FLAG_AUTO_CANCEL并且通知已设置Notification.FLAG_NO_CANCEL,单击通知本身(即启动其contentIntent),通知也会自动清除。我尝试过各种标志组合,包括Notification.FLAG_ONGOING_EVENT,但行为仍然相同。

我希望通知变成“普通”通知,而不是被取消...有任何解决方法吗?文档对此问题并不清楚...

重现代码:

private void showHeadsUpNotification()
{
    final Notification.Builder nb = new Notification.Builder(this);
    nb.setContentTitle("Foobar");
    nb.setContentText("I am the content text");
    nb.setDefaults(Notification.DEFAULT_ALL);
    nb.setOngoing(true);
    nb.setSmallIcon(android.R.drawable.ic_dialog_info);
    nb.setContentIntent(PendingIntent.getActivity(this, 0, getIntent(), 0));

    // Commenting this line 'fixes' it by not making it heads-up, but that's
    // not what I want...
    nb.setPriority(Notification.PRIORITY_HIGH);

    ((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).notify(0, nb.build());
}

编辑:我注意到当应用程序在前台时发布通知时,通知变成了普通的通知,就像我所期望的那样。无论当前前台应用是什么,滑动 Heads-up 通知都会产生一个普通通知。

2个回答

2

目前,我想到了以下解决方案:

  1. 在contentIntent中添加一个额外的参数,表明它是从通知中启动的。
  2. 在启动的 Activity 中检查该额外参数。
  3. 如果该额外参数存在,则重新发布通知,但确保它不成为悬浮通知。

代码:

@Override
protected void onResume()
{
    super.onResume();

    if (getIntent().getBooleanExtra("launched_from_notification", false)) {
        showNotification(false);
        getIntent().putExtra("launched_from_notification", false);
    }
}

// If your Activity uses singleTop as launchMode, don't forget this
@Override
protected void onNewIntent(Intent intent)
{
    super.onNewIntent(intent);
    setIntent(intent);
}    

private void showNotification(boolean showAsHeadsUp)
{
    final Intent intent = getIntent();
    intent.putExtra("launched_from_notification", true);

    final Notification.Builder nb = new Notification.Builder(this);
    nb.setContentTitle("Foobar");
    nb.setContentText("I am the content text");
    nb.setOngoing(true);
    nb.setSmallIcon(android.R.drawable.ic_dialog_info);
    nb.setContentIntent(PendingIntent.getActivity(
            this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
    nb.setPriority(Notification.PRIORITY_HIGH);

    // Notifications without sound or vibrate will never be heads-up
    nb.setDefaults(showAsHeadsUp ? Notification.DEFAULT_ALL : 0);

    ((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).notify(0, nb.build());
}

1
我想到了一个简单的技巧,就是将您的contentIntent设置为执行任何操作再次发送声明为PRIORITY_DEFAULT或其他内容的同一通知。当然要使用相同的notyId

几天前我也遇到了同样的问题......问题在于Google有意将此行为用作通知行为。这意味着,如果您想将通知声明为重要通知并建议使用PRIORITY_HIGHMAX,则表明这是需要立即处理的紧急情况。因此,在这种情况下,用户只能通过左右滑动使其消失(通知不会出现在通知抽屉中)或单击通知本身并启动contentIntent(这将导致通知消失,因为已经采取了您打算的操作)。

如果有一种方法可以避免这种行为,那对我来说将是新鲜事。

希望我能够帮到您。


我实际上更喜欢通知栏不要弹出,但同时我想保留PRIORITY_HIGH。由于声音和/或振动也是使通知栏弹出的必要条件,我的方法只是禁用了第二个通知的这些功能。这样,它仍然是PRIORITY_HIGH,但不会弹出通知栏。 - jclehner

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接