如何制作不弹出的Android本地通知,而仅显示在通知列表中?

时间:2019-01-21 09:00:14

标签: android notifications android-8.0-oreo

我正在制作一种警报应用程序。我有一个特殊的警报屏幕,警报时间到时会显示。很好但我也希望如果用户暂停警报,则通知列表中会有一个条目。但是,当我尝试使用NotificationBuilder使用常规Notification时,它会在与我的警报活动相同的情况下在屏幕上弹出(不是全屏-使用透明性)。必须有一种将通知添加到列表中的方法,以便用户可以在此处看到通知,但不会在警报时间弹出。

2 个答案:

答案 0 :(得分:1)

您需要为创建的频道使用低优先级

NotificationManager.IMPORTANCE_LOW  or NotificationManager.IMPORTANCE_MIN 

在Android Oreo中,您需要使用通知渠道来创建通知。

例如:创建ID为“ Alerts”的频道时, 您可以定义其属性,例如重要性,声音等...

使用的各种重要性属性如下

IMPORTANCE_DEFAULT: 默认的通知重要性:显示在任何地方,会产生噪音,但不会在视觉上造成干扰。 恒定值:3

IMPORTANCE_HIGH: 通知重要性更高:随处可见,喧闹和窥视。 可以使用全屏意图。

[这将继续显示在其他应用上,并且再次显示类似whatsapp消息通知的内容] 之所以如此,是因为其重要性。 恒定值:4

IMPORTANCE_LOW 通知重要性低:在任何地方显示,但不具干扰性。 恒定值:2

IMPORTANCE_MIN 最低通知重要性:仅显示在折叠下方的阴影中。 恒定值:1

因此,一旦您定义了渠道属性,只有用户可以通过通知意图对其进行更改。 我在这里提到的:https://stackoverflow.com/a/54199316/7039593

使用低优先级/最小/最小重要性可能会解决您的问题

答案 1 :(得分:0)

这是通过将通知优先级设置为MINIMUM来完成的。 例如:

NotificationCompat.Builder b = new NotificationCompat.Builder(context, "MyReminder");
b.setPriority(NotificationCompat.PRIORITY_MIN);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    String id = MyApp.getNotificationChannel(context);
    b.setChannelId(id);
}

对于Oreo及更高版本的注释,您还需要设置通知渠道的优先级:

final private static String MyChannelID = "MyChannel_1";
private static NotificationChannel channel;

static private String getNotificationChannel(Context context) {
    // Create the NotificationChannel, but only on API 26+ because
    // the NotificationChannel class is new and not in the support library
    if (channel == null) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            CharSequence name = "My Reminders";
            String description = "My Reminders pre-scheduled using My app";
            int importance = NotificationManager.IMPORTANCE_MIN;
            channel = new NotificationChannel(MyChannelID, name, importance);
            channel.setDescription(description);
            channel.enableLights(true);
            // Sets the notification light color for notifications posted to this
            // channel, if the device supports this feature.
            channel.setLightColor(Color.RED);

            channel.enableVibration(true);

            // Register the channel with the system; you can't change the importance
            // or other notification behaviors after this
            getNotificationManager().createNotificationChannel(channel);
        }
    }
    return MyChannelID;
}


static public NotificationManager getNotificationManager() {
    Context context = App.getContext();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        return context.getSystemService(NotificationManager.class);
    }
    else {
        return (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
    }
}

我没有检查每个优先级的行为,但是MINIMUM和IMPORTANCE_MIN起作用。如果您想要获得更具体的行为,可以查看文档并使用其他优先级。