应用程序关闭时的推送通知问题-本机响应

时间:2020-06-28 08:55:57

标签: react-native

我正在使用React native。我通过PHP发送推送通知,当应用程序在后台打开并在后台运行时,通知到达应用程序,但是当我关闭应用程序时,我无法收到通知。我使用react-native-firebase库。这是什么原因呢?我想在应用程序关闭时收到通知。我该怎么办,按如下所示关闭应用程序时,我无法收到通知。

async checkPermission() {
  const enabled = await firebase.messaging().hasPermission();
  if (enabled) {
      this.getToken();
  } else {
      this.requestPermission();
  }
}


async getToken() {
  let fcmToken = await AsyncStorage.getItem('fcmToken');
  if (!fcmToken) {
      fcmToken = await firebase.messaging().getToken();
      if (fcmToken) {
          // user has a device token
          await AsyncStorage.setItem('fcmToken', fcmToken);
      }
  }
}

async requestPermission() {
  try {
      await firebase.messaging().requestPermission();
      // User has authorised
      this.getToken();
  } catch (error) {
  }
}


 async componentDidMount() {
   
  await firebase.messaging().subscribeToTopic('add')    
  this.checkPermission();
  this.createNotificationListeners(); //add this line

    setTimeout(
      function () {
        this.setState({ isLoading: true });
      }.bind(this),
      500
    );
  }

componentWillUnmount() {
  this.notificationListener();
  this.notificationOpenedListener();
}

async createNotificationListeners() {
  this.notificationListener = firebase.notifications().onNotification((notification) => {
      const { title, body } = notification;
      this.showAlert(title, body);
  });

  this.notificationOpenedListener = firebase.notifications().onNotificationOpened((notificationOpen) => {
      const { title, body } = notificationOpen.notification;
      this.showAlert(title, body);
  });

  const notificationOpen = await firebase.notifications().getInitialNotification();
  if (notificationOpen) {
      const { title, body } = notificationOpen.notification;
      this.showAlert(title, body);
  }

  this.messageListener = firebase.messaging().onMessage((message) => {
    //process data message
    console.log(JSON.stringify(message));
  });
}

showAlert(title, body) {
  Alert.alert(
    title, body,
    [
        { text: 'OK', onPress: () => console.log('OK Pressed') },
    ],
    { cancelable: false },
  );
}

0 个答案:

没有答案