Нет звука или вибрации в push-уведомлениях Android в Expo Client

привет, я новичок в реагировании на родной язык, я просто тестирую push-уведомление на Android. но при тестировании на своем устройстве Android через клиент expo нет вибрации или звука.

Однако, когда я открываю приложение на своих устройствах Android через клиент expo, push-уведомление появляется, но не было ни звука, ни вибрации, хотя я уже установил для них значение true.

Я хочу сделать уведомление, чем уведомлять пользователя каждый день в 8 утра, даже если приложение закрыто, могу ли я это сделать?

async componentWillMount() {
    let result = await Permissions.getAsync(Permissions.NOTIFICATIONS);
    if (result.status === "granted" && this.state.switchStatus) {
      console.log("Notification permissions granted.");
      this.setNotifications();
    } else {
      console.log("No Permission", Constants.lisDevice);
    }

    this.listenForNotifications();
  }
  getNotification(date) {
    const localNotification = {
      title: `Notification at ${date.toLocaleTimeString()}`,
      body: "N'oubliez pas de prendre tes medicament",
      ios: {

        sound: true 
      },

      android: {
        sound: true, 
        priority: "max", 
        sticky: false, 
        vibrate: true 
      }
    };
    return localNotification;
  }
  setNotifications() {
    Notifications.cancelAllScheduledNotificationsAsync();

    for (let i = 0; i < 64; i++) {
      //Maximum schedule notification is 64 on ios.
      let t = new Date();
      if (i === 0) {
        t.setSeconds(t.getSeconds() + 1);
      } else {
        t.setMinutes(t.getMinutes() + 1 + i * 1);
      }
      const schedulingOptions = {
        time: t 
      };
      Notifications.scheduleLocalNotificationAsync(
        this.getNotification(t),
        schedulingOptions
      );
    }
  }
  listenForNotifications = () => {
    Notifications.addListener(notification => {
      console.log("received notification", notification);
    });
  };

person Ahmed Essaadi    schedule 13.05.2019    source источник


Ответы (3)


Я нашел решение для звука и вибрации, это не самое лучшее, как я уже сказал, я новичок в RN, но все же оно работает (я использовал это: «Создать Channel Android Async»)

async componentWillMount() {
    let result = await Permissions.getAsync(Permissions.NOTIFICATIONS);
    if (result.status === "granted" && this.state.switchStatus) {
    // i add this :
      if (Platform.OS === 'android') {
  Notifications.createChannelAndroidAsync('chat-messages', {
    name: 'Chat messages',
    sound: true,
    vibrate: true,
  });
}
      console.log("Notification permissions granted.");

      this.setNotifications();
    } else {
      console.log("No Permission", Constants.lisDevice);
    }

    this.listenForNotifications(); 
  }

  getNotification(date) {

    const localNotification = {
      title: `Notification at ${date.toLocaleTimeString()}`,
      body: "N'oubliez pas de prendre tes medicament", 
      ios: {

        sound: true 
      },

      android: {
       "channelId": "chat-messages" //and this
            }
    };
    return localNotification;
  }
  setNotifications() {
    Notifications.cancelAllScheduledNotificationsAsync();

    for (let i = 0; i < 64; i++) {
      //Maximum schedule notification is 64 on ios.
      let t = new Date();
      if (i === 0) {
        t.setSeconds(t.getSeconds() + 1);
      } else {
        t.setMinutes(t.getMinutes() + 1 + i * 1); // 15 Minutes
      }
      const schedulingOptions = {
        time: t 
      };
      Notifications.scheduleLocalNotificationAsync(
        this.getNotification(t),
        schedulingOptions
      );
    }
  }
  listenForNotifications = () => {
    Notifications.addListener(notification => {
      console.log("received notification", notification);
    });
  };
person Ahmed Essaadi    schedule 13.05.2019
comment
Большое спасибо! Ваш код отлично работает для меня, но приходят только первые одно или два уведомления, а затем он останавливается. Есть идеи, почему это может быть? - person Squirrl; 23.03.2020
comment
Спасибо! этот код предназначен только для проблемы с получением уведомлений. Итак, теперь вам нужно запланировать уведомления по своему усмотрению, и он будет работать. извините за поздний ответ ^^ - person Ahmed Essaadi; 30.03.2020

В моем случае я разрешил звук уведомлений в (settings - ›notifications -› your-app-name - ›sound -› allow), и он работал нормально после слов

person sumukha hegde    schedule 19.07.2020

В вашем файле app.json добавьте

android:{useNextNotificationApi:true }

person tanaka    schedule 20.04.2021
comment
Добро пожаловать. Не могли бы вы добавить немного контекста о том, как это помогает, и некоторую справочную информацию. Это может помочь понять ценность решения для будущих поисков. - person Kanekotic; 20.04.2021