response-native-firebase Пользовательский звук не работает на Android 8, Android 9 - PullRequest
1 голос
/ 08 июля 2019

Я работаю над пользовательскими функциями звукового оповещения.Пользовательский звук работает должным образом на iOS и Android ниже версии 8. Уведомления также поступают во всех версиях Android.Но пользовательский звук не работает на Android 8 и 9. Я также создал Id канала.

Ниже я поделился своим кодом.Кто-нибудь может мне помочь, пожалуйста?Заранее спасибо.

  async checkPermission() {
    const enabled = await firebase.messaging().hasPermission();
    if (enabled) {
        this.getToken();
      } else {
        this.requestPermission();
     }
    let channel = new firebase.notifications.Android.Channel(
      "channelId",
      "Channel Name",
      firebase.notifications.Android.Importance.Max
    ).setDescription("A natural description of the channel");
    firebase.notifications().android.createChannel(channel);


    firebase
      .notifications()
      .getInitialNotification()
      .then(notificationOpen => {
        if (notificationOpen) {
          const action = notificationOpen.action;
          const notification = notificationOpen.notification;
        }
      });

    // the listener returns a function you can use to unsubscribe
    this.unsubscribeFromNotificationListener = firebase
      .notifications()
      .onNotification(notification => {

        if (Platform.OS === "android") {
          const channel = new firebase.notifications.Android.Channel(
            "channelId",
            "Channel Name",
            firebase.notifications.Android.Importance.Max
          )
            .setDescription("A natural description of the channel")
            .setSound(
              notification.data.sound ? notification.data.sound : "default"
            );

          firebase.notifications().android.createChannel(channel);

          const localNotification = new firebase.notifications.Notification({
            sound: notification.data.sound
              ? notification.data.sound
              : "default",
            show_in_foreground: true
          })
            .setNotificationId(notification.notificationId)
            .setTitle(notification.title)
            .setSubtitle(notification.subtitle)
            .setBody(notification.body)
            .setData(notification.data)
            .setSound(
              notification.data.sound ? notification.data.sound : "default"
            )
            .android.setSmallIcon("notification_icon_black")
            .android.setChannelId("channelId") 
            .android.setAutoCancel(true)
            .android.setVibrate(1000)
            .android.setColor("#000000") // you can set a color here
            .android.setGroup(notification.notificationId)
            .android.setPriority(firebase.notifications.Android.Priority.High);

          firebase
            .notifications()
            .displayNotification(localNotification)
            .catch(err => console.error(err));
        } else if (Platform.OS === "ios") {
          const localNotification = new firebase.notifications.Notification()
            .setNotificationId(notification.notificationId)
            .setTitle(notification.title)
            .setSound(
              notification.data.sound ? notification.data.sound : "default"
            )
            .setSubtitle(notification.subtitle)
            .setBody(notification.body)
            .setData(notification.data)
            .ios.setBadge(notification.ios.badge);

          firebase
            .notifications()
            .displayNotification(localNotification)
            .catch(err => console.error(err));
        }

      });

    const notificationOpen = await firebase
      .notifications()
      .getInitialNotification();
    if (notificationOpen) {
      const action = notificationOpen.action;
      const notification = notificationOpen.notification;
      if (notification.data) {
        //handle data
      }
    }

    this.notificationOpenedListener = firebase
      .notifications()
      .onNotificationOpened(notificationOpen => {

        const notification = notificationOpen.notification;
        if (notification.data) {
          //handle data
        }
      });
  }



 async requestPermission() {
    try {
      await firebase.messaging().requestPermission();
      // User has authorised
      this.getToken();
    } catch (error) {
      // User has rejected permissions
      console.log("permission rejected");
    }
  }

  async getToken() {
    let fcmToken = await firebase.messaging().getToken();
    if (fcmToken) {
      console.log("fcm token===>", fcmToken);
    }
  }

Ответы [ 2 ]

1 голос
/ 08 июля 2019

Потратив целый день, я нашел решение. Я только что очистил данные приложения и перезагрузил телефон, и он работает нормально.

Существует проблема, потому что я использовал собственный звук для определенного типа уведомлений.

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

{
    "to" : "DEVICE_TOKEN",

    "notification" : {
      "body"  : "NOTIFICATION BODY",
      "title" : "NOTIFICATION TITILE",
      "sound" : "default", //change your sound based on your requirement
      "android_channel_id":"CHANEEL_NAME", 
    }
  }
1 голос
/ 08 июля 2019

Попробуйте.

Прежде всего поместите ваш звуковой файл в папку res / raw, а также включите setSound () в канал уведомлений,

Второй момент, благодаря @ PatelDhara также убедитесь, что удалили ваше приложение с устройства, чтобы новая конфигурация канала работала правильно.

Затем поставьте строку кода ниже, у меня все работает.

Сначала создайте канал.

const channel = new firebase.notifications.Android.Channel(name, Description, firebase.notifications.Android.Importance.High)
.setDescription(ChannelName)
.setSound(default.mp3) //Set audio here
...
firebase.notifications().android.createChannel(channel);

Тогда:

const notification = new firebase.notifications.Notification()
.setNotificationId(id)
.setTitle(title)
.setSound(channel.sound); //Get sound from channel and set in notification builder

notification
.android.setChannelId(channel.channelId)
firebase.notifications().displayNotification(notification);

Также убедитесь, что всякий раз, когда вы получаете полезную нагрузку, имя вашего аудиофайла, расположенного в папке res / raw, и значение звука, которое вы получаете в полезной нагрузке, должны совпадать.

Как это:

{
    "to" : "DEVICE-TOKEN",

    "notification" : {
      "body"  : "NOTIFICATION BODY",
      "title" : "NOTIFICATION TITILE",
      "sound" : "default"
    }
  }

Примечание. В реакции на нативные были проблемы с Android O в версиях до 0.56.0 (реагировать на нативную версию), поэтому попробуйте обновить версию.

...