【问题标题】:Oreo & Pie Notifications奥利奥和派通知
【发布时间】:2019-02-23 07:04:11
【问题描述】:

问题:我的应用需要用户可以自定义的通知。例如。为通知设置不同的声音、标题、文本

问题:我知道通知通道只设置一次并且不能修改,所以我认为我可以只使用变量,但是即使使用变量,一旦我选择了一个声音,它就会保持那个声音并且根本无法改变。我能想到的唯一解决方案是每次更改某些内容时都会创建一个新频道,这看起来很愚蠢。 肯定还有别的办法吗??

此外,在 Android Pie 上,通知声音根本不起作用,我不知道为什么。

Uri soundUri = Uri.parse(notificationSound);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "CH_ID")
        .setSmallIcon(R.mipmap.ic_launcher)
        .setContentTitle(customTextTitle)
        .setContentText(customTextBody)
        .setAutoCancel(true)
        .setSound(soundUri)
        .setContentIntent(pendingIntent);

NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {

    if(soundUri != null){
        // Changing Default mode of notification
        notificationBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
        // Creating an Audio Attribute
        AudioAttributes audioAttributes = new AudioAttributes.Builder()
                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                .setUsage(AudioAttributes.USAGE_ALARM)
                .build();

        // Creating Channel
        NotificationChannel notificationChannel = new NotificationChannel("CH_ID","Testing_Audio",NotificationManager.IMPORTANCE_HIGH);
        notificationChannel.setSound(soundUri,audioAttributes);
        mNotificationManager.createNotificationChannel(notificationChannel);
    }
}
mNotificationManager.notify(0, notificationBuilder.build());
}

【问题讨论】:

  • 多声道应该支持多种声音。根据不同的声音创建不同的频道。
  • 谢谢,因为用户可能有这么多不同的声音,我觉得每次一个新频道都会变得非常过分。 (对于可能使用它们并且可能看起来有问题的用户)
  • 频道的想法是让用户控制通知。您只能拥有有限数量的通知类型。

标签: java android


【解决方案1】:

我已经解决了这个问题,尽管是以一种 hacky 的方式:( 如果 >=Oreo,我最终将声音设置为 null 并使用媒体播放器播放通知声音,还将 audioStream 设置为 STREAM_NOTIFICATION。显然不理想,但作为这是一个通知而不是警报,音频不应超过在 onReceive 期间执行任务所设置的时间。

我可以看到此解决方案的唯一问题是用户是否决定将通知静音/对其手机上的频道进行调整。在那里静音显然不会对媒体播放器播放的声音产生影响,并且很可能无论如何都会显示为没有声音,这是不幸的。

 try {
                    mp.setDataSource(context.getApplicationContext(), soundUri);
                    mp.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
                    mp.prepare();
                    mp.start();
                } catch (Exception e) {
                    //exception caught in the end zone
                }

对于遇到此问题的其他人,我在这里找到了一个非常棒的帖子,它与我的解决方案相同,但更强大、更深入。 Android O - Notification Channels - Change Vibration Pattern or Sound Type

【讨论】:

    【解决方案2】:

    你有错误的实现,设置如下声音

    notificationBuilder.setSound(soundUri,audioAttributes);
    

    【讨论】:

    • 我试过了,但是 builder.setSound 不允许我添加它要求 int 的音频属性。声音以另一种方式工作,但它只是卡在那个特定的声音中,没有用户自定义..