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

我正在尝试运行该应用程序的设备是API 21.我见过很多线程,但没有解决方案对我有用.

最佳答案 你需要做两件事:

>确保正确配置了通知.见:https://developer.android.com/guide/topics/ui/notifiers/notifications#Heads-up
>并确保手机配置正确(我认为这是大部分卡住的地方).

Step 1. Configure the notification.

像这样注册您的通知渠道

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

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

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

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

Notification buildNotification = mBuilder.build();
NotificationManager mNotifyMgr = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
mNotifyMgr.notify(001, buildNotification);

Step 2. Configure the phone.

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

以下是一些访问菜单的方法:

>长按通知栏中的通知.
>转到:设置>已安装的应用>选择你的应用>通知
>改进上一步,您可以通过使用此意图将用户发送到已安装的应用程序菜单,从而帮助用户:

startActivity(new Intent(Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS));

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

点赞