首页 > 解决方案 > 通知通道不播放我在 setsound 中发送的 URI(来自 RAW 文件夹)

问题描述

我正在尝试在 Android 中创建一个通知通道,该通道将播放我的 Raw 文件夹中的声音。

正如您在下面的代码中看到的那样,我已经输入了这一行:

RingtoneManager.getRingtone(a, uri).play();

这让我可以测试 Uri 是否正确,事实确实如此。

  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

        CharSequence name = a.getString(R.string.channel_name);
        NotificationManager notificationManager = a.getSystemService(NotificationManager.class);

        notificationManager.deleteNotificationChannel(a.getString(R.string.default_notification_channel_id));

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(a.getApplicationContext());

        Uri uri;
        uri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE
                + "://" + a.getPackageName() + "/raw/" + prefs.getString("pref_ring", "a1"));

        RingtoneManager.getRingtone(a, uri).play();
        //CORRECT SOUND IS PLAYING, URI IS OK

        String description = a.getString(R.string.channel_description);
        int importance = NotificationManager.IMPORTANCE_DEFAULT;
        NotificationChannel channel = new NotificationChannel(a.getString(R.string.default_notification_channel_id), name, importance);
        channel.setDescription(description);
        AudioAttributes audioAttributes = new AudioAttributes.Builder()
                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                .build();
        channel.setSound(uri, audioAttributes);
        notificationManager.createNotificationChannel(channel);

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(a, a.getString(R.string.default_notification_channel_id))
                .setSmallIcon(R.drawable.logo)
                .setContentTitle("TEST")
                .setContentText("TEST")
                .setAutoCancel(true)
                .setSound(uri)//Just in case, but has no effect
                .setPriority(NotificationCompat.PRIORITY_DEFAULT);

        notificationManager.notify(0, mBuilder.build());
    }

不幸的是,被触发的通知总是播放默认通知铃声

知道我做错了什么吗?

标签: androidnotificationsnotification-channel

解决方案


推荐阅读