Android通知生成器:显示没有图标的通知。

13
 String ns = Context.NOTIFICATION_SERVICE;
 NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);

 int icon = R.drawable.ic_notification_icon;
 android.app.Notification.Builder nbuilder = new Notification.Builder(this);

 nbuilder.setContentTitle(getString(R.string.notifcation_title,mProfile.mName));
 nbuilder.setContentText(msg);
 nbuilder.setOnlyAlertOnce(true);
 nbuilder.setOngoing(true);
 nbuilder.setSmallIcon(icon,level.level);

我该如何隐藏或者完全删除smallIcon?我尝试不使用nbuilder.setSmallIcon,但结果是通知根本没有显示!


4
我所知道的唯一方法是使用透明图像作为图标,然后设置通知的顺序,使您的通知排在最后(最右边),这将使用户看起来好像没有图标。 - FoamyGuy
3
为什么这符合用户的利益? - CommonsWare
@CommonsWare: 一个使用场景:运行在隐身模式的通讯应用程序想要在消息到达时通知用户,但又不想显示应用程序图标或任何图标,以防他人看到。 - Harish Vishwakarma
6个回答

17

在Jelly Bean及更高版本中,您可以使用nbuilder.setPriority(Notification.PRIORITY_MIN);这个优先级的确切解释留给系统UI来决定,但在AOSP中,这会导致通知的图标被隐藏。

这适用于不需要引起用户注意的“环境”或“后台”信息,但如果用户碰巧正在浏览通知面板,则可能会感兴趣。有关如何最好使用通知优先级,请参见Android Design网站的通知部分


9

更新:不要在Android 7上使用,会崩溃


使用反射,在Lollipop(模拟器和Moto G设备)和Marshmallow(模拟器)中可以正常工作。

Notification notification = NotificationCompat.Builder.blabla().build();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
  int smallIconViewId = context.getResources().getIdentifier("right_icon", "id", android.R.class.getPackage().getName());

  if (smallIconViewId != 0) {
    if (notification.contentView != null)
      notification.contentView.setViewVisibility(smallIconViewId, View.INVISIBLE);

    if (notification.headsUpContentView != null)
      notification.headsUpContentView.setViewVisibility(smallIconViewId, View.INVISIBLE);

    if (notification.bigContentView != null)
      notification.bigContentView.setViewVisibility(smallIconViewId, View.INVISIBLE);
  }
}

我找不到更好的方法。

一旦他们更改视图的id或更改通知内RemoteViews字段的任何内容,这种方法可能会停止工作,因此请自行决定是否使用。


3

如果没有使用 setSmallIcon(icon,level.level);,则无法实现该功能。通知不会显示。


0

在您的通知构建器中尝试添加以下行:
.setPriority(Notification.PRIORITY_MIN)
这样您的通知将会像这样:

Notification notification = new Notification.Builder(this)
            .setSmallIcon(R.drawable.stat_notify_chat)
            .setContentTitle("my app")
            .setContentText("my app ")
            .setPriority(Notification.PRIORITY_MIN)
            .setContentIntent(pendingIntent).build();

所以在这种情况下,您可以在通知栏中看到您的图标,并且它将隐藏在状态栏中。希望这可以帮助您。


0

我之前遇到过这个问题,解决方法如下:

private int getNotificationIcon() {
    boolean useWhiteIcon = (android.os.Build.VERSION.SDK_INT>=android.os.Build.VERSION_CODES.LOLLIPOP);
    // Lollipop or Marshmellow >>>>>>>>>>>>>>>>>>>>> KitKat or less
    return useWhiteIcon ? R.drawable.logo_new : R.drawable.logo;
}

然后在setSmallIcon()中调用此函数即可。

nbuilder.setSmallIcon(getNotificationIcon());

0

您可以设置没有图标的自定义布局:

RemoteViews notificationView = new RemoteViews(
                context.getPackageName(),
                R.layout.notify
        );
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
      .setContent(notificationView)

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