如何在 Android O 中动态更改通知声音

How to change notification sound dynamically in Android O

最近在用通知渠道支持android哦。 但问题是我无法动态更改声音 Uri。 我们的应用程序具有通知声音设置,用户可以根据需要更改应用程序通知声音。 但是如您所知,Android 现在不允许开发人员在用户重新安装应用程序之前更新通知渠道。 在那里我考虑了几种可能的解决方案,但看起来不太好。

  1. 用户铃声管理器播放铃声而不是 setSound。但是当用户在应用程序设置中禁用通知时,铃声仍然不会停止播放。 (这将是糟糕的用户体验)

  2. 删除通知频道并在用户更改铃声时创建新的通知频道。但这看起来也很糟糕,因为在应用程序设置中 google 显示删除频道信息的历史记录。(实际上不需要)

有什么好的解决办法吗?

在 Android O+ 设备上,您应该删除应用中的所有通知特定设置,并在设置屏幕中为 open the system's notification channel settings 提供 link,用户可以在其中调整声音直接通知渠道。

@RequiresApi(api = Build.VERSION_CODES.O) 私人无效 createChannels() {

    Nmanager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

    AudioAttributes attributes = new AudioAttributes.Builder()
            .setUsage(AudioAttributes.USAGE_NOTIFICATION)
            .build();

    ArrayList arrayList = new ArrayList<String>();
    Field[] fields = R.raw.class.getFields();
    for (int i = 1; i < fields.length - 1; i++) {
        arrayList.add(fields[i].getName());
    }


    DBRingtone RDB = new DBRingtone(this);
    Cursor cursor = RDB.getringtone();

    if (cursor.getCount() > 0) {

        int ring = parseInt(cursor.getString(0));

         resID = getResources().getIdentifier((String) arrayList.get(ring), "raw", getPackageName());

        i=i+resID;

        uri = Uri.parse("android.resource://" + getPackageName() + "/" + resID);
    } else
        {
            i=i+10;
        uri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.default_sound);
    }

    CHANNEL_ID = CHANNEL_ID+i;

    notificationChannel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
    notificationChannel.enableLights(true);
    notificationChannel.enableVibration(true);
    notificationChannel.setDescription("Your message");
    notificationChannel.setLightColor(Color.RED);
    notificationChannel.setSound(uri, attributes);
    notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
    Nmanager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    Nmanager.createNotificationChannel(notificationChannel);

}

大家好,我已经使用上面的代码解决了这个问题,并且可以正常工作。也可以直接赋值CHANNEL_ID = CHANNEL_ID+resID。为此,我使用变量 i 进行了分配。我已经存储了用户首选的通知声音 resID 是 SQLite 数据库并且在 createchannels class 我已经使用游标检索了 resID 来创建 uri path.Hope 这将帮助你谢谢...