设置通知音量

Setting notification sound volume

我正在使用 NotificationChannel 来定义我的应用程序的通知。我用下面的代码设置它的声音:

AudioAttributes.Builder constructeurAttributsAudio=new AudioAttributes.Builder();
constructeurAttributsAudio.setUsage(AudioAttributes.USAGE_NOTIFICATION_EVENT);
canalNotification.setSound(Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE    + "://" + contexte.getPackageName() + "/raw/cloche"),constructeurAttributsAudio.build());

当通知出现时,声音会正确发出,但它的音量设置为最大并且没有考虑用户为通知设置的音量。有谁知道我如何让我的应用程序将通知音量设置为用户选择的值?

编辑 #1:如果我复制代码以在应用程序主体(由 Button 单击触发)而不是 BroadcastReceiveronReceive 方法中执行它,通知声音以用户选择的通知声音级别正确发出。

编辑#2:奇怪的是,在模拟器上执行应用程序时,通知音量是正确的!原因可能是 phone 配置中的参数吗? (他们都 运行 在 Android 9 下)。

我使用下面的代码,希望对你也有用:

 private void setvolume(int volume)
 {
AudioManager manager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
manager.setStreamVolume(AudioManager.STREAM_MUSIC, volume, 0);

Uri notification = RingtoneManager
        .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

MediaPlayer player = MediaPlayer.create(getApplicationContext(), notification);
player.start();

}

卸载并重新安装应用程序解决了问题!