jjzjj

android - Lollipop : heads-up notification is canceled when clicked

coder 2023-12-20 原文

我已经搜索了很长时间,但找不到答案。我的应用程序显示带有 Notification.PRIORITY_HIGH 的通知这导致它在 Lollipop 上显示为提醒通知。

问题是,当点击通知本身(即启动它的 contentIntent )时,通知会自动清除,即使 Notification.FLAG_AUTO_CANCEL 也是如此。 设置并且通知有Notification.FLAG_NO_CANCEL放。我尝试了各种标志组合,包括 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());
}

编辑:我注意到,当发布通知的应用程序位于前台时,通知会变成常规通知,正如我所期望的那样。将抬头通知滑开(无论当前的前台应用程序如何)也会产生常规通知。

最佳答案

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

  1. 向 contentIntent 添加额外内容,表明它是从通知中启动的。
  2. 在启动的 Activity
  3. 中检查额外的内容
  4. 如果存在额外信息,请重新发布通知,但要确保它不会成为提醒通知。

代码:

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

关于android - Lollipop : heads-up notification is canceled when clicked,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26786589/

有关android - Lollipop : heads-up notification is canceled when clicked的更多相关文章

随机推荐