Кнопка «Включить звук» в канале уведомлений - PullRequest
0 голосов
/ 05 ноября 2018

In MI Note 5 Pro с последним MI UI 10.0 с Oreo , поэтому при попытке отправить push-уведомление по умолчанию sound отключен, поэтому я не могу включить звук программно, когда я создаю канал для этого.

В других устройствах Oreo слышен звук уведомления, но в пользовательском интерфейсе MI звук Oreo OS по умолчанию отключен

Позвольте мне показать мой код для уведомления :

    var intent = Intent(mContext, HomeActivity::class.java)
    intent.putExtra(Constants.EXTRA_FROM_NOTIFICATION, true)
    var pendingIntent = PendingIntent.getActivity(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)

    var uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)

    var mBuilder = NotificationCompat.Builder(mContext, NOTIFICATION_CHANNEL_ID)
            .setContentTitle(mContext.getString(R.string.app_name))
            .setContentText(mFirstContactName + " : " + mListChatWindow[0].message)
            .setPriority(if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) NotificationManager.IMPORTANCE_HIGH else Notification.PRIORITY_HIGH)
            .setContentIntent(pendingIntent)
            .setSound(uri)
            .setSmallIcon(R.drawable.ic_app_icon)
            .setColor(ContextCompat.getColor(mContext, R.color.colorPrimary))
            .setVibrate(longArrayOf(0, 100, 1000, 300))
            .setAutoCancel(true)

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        var channel = NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", NotificationManager.IMPORTANCE_HIGH)
        channel.description = "NOTIFICATION_DESCRIPTION"
        channel.lightColor = Color.LTGRAY
        channel.enableVibration(true)
        channel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC

        val attributes = AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_NOTIFICATION).build()
        channel.setSound(uri, attributes)
        var notificationManager = mContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.createNotificationChannel(channel)
    }

    var notificationManager = NotificationManagerCompat.from(mContext)
    notificationManager.notify(NOTIFICATION_CHAT_ID, mBuilder.build())

У меня также установлено channel.setSound (uri, атрибуты) в канале, но звук не идет

Вот скриншот канала уведомлений: там значок звука отключен, как включить?

Пожалуйста, помогите

enter image description here

1 Ответ

0 голосов
/ 28 мая 2019

У меня была похожая проблема в MIUI Global 10.1 с oreo, но это было только при использовании нестандартного звука, а не вашего, звука по умолчанию. В любом случае, позвольте мне объяснить, как я это решаю, и надеюсь, что это может решить ваш.

Первое, на что нужно обратить внимание, - это где выполняется регистрация канала уведомлений. Он должен быть выполнен в Application.onCreate, чтобы канал был создан еще до того, как пришло уведомление. Я делал это в onMessageReceived.

Во-вторых, как я уже сказал, он работает для звука уведомления по умолчанию, а не для пользовательского, я вставил ниже код при создании канала уведомления, и он работал.

NotificationCompat.BuildertificationBuilder = новый NotificationCompat.Builder (this, CHANNEL_ID);

    if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.O) {
        notificationBuilder.setDefaults(Notification.DEFAULT_SOUND); // This line did the magic for me.

        Uri sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.sound_notification_plucky);
        AudioAttributes audioAttributes = new AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                .build();

        CharSequence name = "MyChild";
        String description = "All MyChild messages";
        int importance = NotificationManager.IMPORTANCE_HIGH;

        NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, name, importance);
        notificationChannel.setDescription(description);
        notificationChannel.enableVibration(true);
        notificationChannel.setSound(sound, audioAttributes);

        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notificationManager.createNotificationChannel(notificationChannel);
    }
...