Android平视通知未显示

Paw*_*ęba 6 notifications android

我正在尝试使平视通知工作。通知已创建,但未显示在应用程序顶部。这是负责构建通知的代码:

Notification notification = new NotificationCompat.Builder(context)
                                .setSmallIcon(android.R.drawable.arrow_up_float)
                                .setContentTitle("Check running time - click!")
                                .setContentText(String.valueOf(elapsedTime))
                                .setContentIntent(pendingIntent)
                                .setDefaults(Notification.DEFAULT_ALL)
                                .setPriority(Notification.PRIORITY_HIGH)
                                .setVibrate(new long[0])
                                .build();
Run Code Online (Sandbox Code Playgroud)

我试图运行该应用程序的设备是API21。我已经看到很多线程,但是没有给出的解决方案适合我。

Tom*_*m O 6

您需要做两件事:

  1. 确保您的通知已正确配置。请参阅:https//developer.android.com/guide/topics/ui/notifiers/notifications#Heads-up

  2. 并确保手机配置正确(我认为这是大多数卡住的地方)。

步骤1.配置通知。

像这样注册您的通知频道

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        String name = getString(R.string.channel_name);
        String description = getString(R.string.channel_description);
        int importance = NotificationManager.IMPORTANCE_HIGH; //Important for heads-up notification
        NotificationChannel channel = new NotificationChannel("1", name, importance);
        channel.setDescription(description);
        channel.setShowBadge(true);
        channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel);
    }
Run Code Online (Sandbox Code Playgroud)

然后,创建一个通知,如下所示:

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, "1")
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle(textTitle)
        .setContentText(textContent)
        .setDefaults(DEFAULT_SOUND | DEFAULT_VIBRATE) //Important for heads-up notification
        .setPriority(Notification.PRIORITY_MAX); //Important for heads-up notification
Run Code Online (Sandbox Code Playgroud)

最后,像平常一样发送通知,例如:

Notification buildNotification = mBuilder.build();
NotificationManager mNotifyMgr = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
mNotifyMgr.notify(001, buildNotification);
Run Code Online (Sandbox Code Playgroud)

步骤2.配置电话。

我注意到我必须在手机上启用一些其他设置(小米Note 3):

以下是一些进入菜单的方法:

  1. 在通知栏中长按通知。
  2. 转到:设置>已安装的应用程序>选择您的应用程序>通知
  3. 在上一步的基础上,您可以通过以下目的将用户发送到已安装的应用程序菜单中,从而部分帮助用户:

startActivity(new Intent(Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS));

最后,当您到达此菜单时,启用一个称为“浮动通知”的设置(此设置的名称因设备而异)。

  • 我在三星S8上遇到了这个问题(它在Pixel 2上工作)。最终解决问题的是代码的顺序。频道需要首先创建,就像上面的代码一样!卸载并重新安装(以重新创建频道),它开始在S8上运行。 (4认同)
  • 上面马克的评论是关键 - 即我不知道卸载并重新安装应用程序以使通知渠道更改生效 - 谢谢! (3认同)