我一直在努力与新的NotificationChannels这是在api 26和更高版本中引入的。
我正在开发一个应用程序,可以选择在四种情况下是否通知:
声音和振动。
只有声音。
仅振动。
没有声音或振动,只是一个弹出窗口。
在所有情况下,我的应用程序通知与声音和振动,无论我选择。
我的代码是:

NotificationCompat.Builder builder;
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        builder = new NotificationCompat.Builder(context, CHANNEL_ID);
        int importance;
        NotificationChannel channel;

        //Boolean for choosing Sound
        if(sound) {
            importance = NotificationManager.IMPORTANCE_DEFAULT;
        } else {
            importance = NotificationManager.IMPORTANCE_LOW;
        }

        channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, importance);
        channel.setDescription(CHANNEL_DESC);

        //Boolean for choosing Vibrate
        if(vibrate) {
            channel.enableVibration(true);
        } else {
            channel.enableVibration(false);
        }

        notificationManager.createNotificationChannel(channel);
    } else {
        builder = new NotificationCompat.Builder(context);
    }

    if(sound && vibrate) {
        //Sound and Vibrate
        builder.setDefaults(Notification.DEFAULT_ALL);
    } else if(sound && !vibrate) {
        //Sound
        builder.setDefaults(Notification.DEFAULT_SOUND);
    } else if(!sound && vibrate) {
        //Vibrate
        builder.setDefaults(Notification.DEFAULT_VIBRATE);
    } else if(!sound && !vibrate) {
        //None
        //Do nothing! just notification with no sound or vibration
    }

    builder.setSmallIcon(R.drawable.ic_logo)
            .setContentTitle(title)
            .setContentText(text)
            .setAutoCancel(true)
            .setOnlyAlertOnce(false)
            .setPriority(Notification.PRIORITY_MAX);

另外,我每次运行应用程序时都会更改CHANNEL_ID,因此每次都会获得一个新的频道ID,以便在找到解决方案之前进行测试。
当然,它在api小于26的情况下运行良好。
谢谢你们,伙计们!

最佳答案

我在文件里找到的。也许它会帮助你:
在android 8.0(api级别26)及更高版本上,通知的重要性取决于通知发布到的通道的重要性。用户可以在系统设置中更改通知通道的重要性(图12)。在android 7.1(api级别25)及以下版本中,每个通知的重要性由通知的优先级决定。
还有:
android o引入了通知通道,以提供一个统一的系统来帮助用户管理通知。当您以android o为目标时,必须实现一个或多个通知通道以向用户显示通知。如果你没有针对android o,那么你的应用程序在androido设备上运行时的行为与android 7.0上的相同。
最后:
现在必须将单个通知放入特定频道。
用户现在可以关闭每个频道的通知,而不是关闭应用程序中的所有通知。
具有活动通知的应用程序在主/启动程序屏幕上的应用程序图标顶部显示通知“徽章”。
用户现在可以从抽屉中暂停通知。您可以设置通知的自动超时。
一些关于通知行为的api已从通知移动到notificationchannel。例如,对于Android 8.0及更高版本,使用NotificationChannel.setImportance()而不是NotificationCompat.Builder.setPriority()。

08-18 18:16
查看更多