如何停止通过 Android 代码发布单挑通知?

How to stop heads-up notification being posted via Android Code?

我正在构建一个 android 应用程序来替换通知抽屉并在其自己的 window 中显示通知。当通过覆盖 onNotificationPosted() 方法发布通知时,我设法在我的抽屉上显示通知。但是,android 也会显示相同的通知。所以,我希望通知只显示在我的 window 上,还有其他应用程序已经做到了,所以这并非不可能。请告诉我如何覆盖 android 的默认行为。提前致谢。 :)

编辑

我想要的是禁用提醒通知。有什么解决办法吗?

咦!看起来 Android 无法通过代码禁用其他应用程序的提醒通知。

这是一个小窍门!

所以,我们需要的是,不显示来自任何其他应用程序的任何提醒通知。要解决这个问题,我们需要了解屏幕上一次只能显示一个提示通知。

黑客是,在您收听任何正在发布的通知后立即发送您自己的通知,即在 NotificationListener 子类的 onNotificationPosted() 中。

this.mNotificationManager.notify(12321, new Notification.Builder(this)
                .setContentTitle("").setContentText("")
                .setSmallIcon(R.drawable.transparent)
                .setPriority(Notification.PRIORITY_DEFAULT)
                .setFullScreenIntent(this.mBlankIntent, true)
                .setAutoCancel(true)
                .build());

它将用您几乎空白的通知替换第三个应用程序的通知。哇哦!等待!!这看起来很难看。

当然,现在我们需要在用户看到之前删除这个通知。

现在您知道 android 的包名称了。您可以像这样显示取消通知。

if(packageName.equals("com.my.package")){
        mNotificationManager.cancel(12321);
        return;
    }

所以,我们正在做的是显示我们的通知,当任何其他提醒通知出现时,然后删除我们自己的通知。所有这一切发生得如此之快以至于用户看不到任何提醒通知,为此,我什至不需要将通知存储在内存中。

我将 NotificationManager.IMPORTANCE_DEFAULTsetPriority(NotificationCompat.PRIORITY_DEFAULT) 一起使用,它似乎有效(Oneplus 3 和 Note 8)。

String channelId = "ch01";
String channelName = "Status";
int importance = NotificationManager.IMPORTANCE_DEFAULT;

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
    NotificationChannel mChannel = new NotificationChannel(
            channelId, channelName, importance);
    notificationManager.createNotificationChannel(mChannel);
}

NotificationCompat.Builder nb = new NotificationCompat.Builder(this, channelId);
    nb.setSmallIcon(R.drawable.ic_logo);
    nb.setContentTitle(notificationText);
    nb.setContentText("");
    nb.setContentIntent(mainActivityPendingIntent);
    nb.setPriority(NotificationCompat.PRIORITY_DEFAULT);
    nb.setOnlyAlertOnce(true);
    nb.setOngoing(true);
    nb.setWhen(System.currentTimeMillis());

Oreo 及更高版本中 OS 它在通知通道中,您必须在其中设置优先级任何小于 NotificationManager.IMPORTANCE_HIGH 或类似的东西下面这个停止抬头横幅。

NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
                                   CHANNEL_NAME, 
                                   NotificationManager.IMPORTANCE_DEFAULT)

Pre-Oreo 设备上,通知优先级本身帮助系统 show/hide 抬头横幅。 还请记住,当您进行此更改时,您必须删除应用程序并重新安装才能看到更改!

将重要性设置为低,将优先级设置为低。 对我有用

var notificationChannel = NotificationChannel(channelId, "Call" , NotificationManager.IMPORTANCE_LOW)
            var notification = NotificationCompat.Builder(context,channelId)
                    .setContentTitle("Calling")
                    .setContentText("Call")
                    .setContentIntent(pendingIntent)
                    .setAutoCancel(true)
                    .setPriority(NotificationCompat.PRIORITY_LOW)