如何在前台后台接收消息 - React Native?

How to receive messages in foreground-background - React Native?

https://www.npmjs.com/package/react-native-android-sms-listener

https://www.npmjs.com/package/react-native-background-job

这是我的代码

import React, { Component } from 'react';
import {
  AppRegistry,
  Text,
  View
} from 'react-native';

import BackgroundJob from 'react-native-background-job';
import SmsListener from 'react-native-android-sms-listener';

/*
Register background job with jobKey
*/
const myJobKey = 'Hej';

BackgroundJob.register({
  jobKey: myJobKey,
  job: () => console.log('Background Job fired!')
});

export default class ListenMessageApp extends Component {

  //constructor include last message
  constructor(props) {
    super(props);
    this.state = { lastMessage: 1 };
  }

  componentDidMount() {
    this.getAll();
    BackgroundJob.schedule({
      jobKey: myJobKey,
      period: 1000,
      timeout: 1000
    });
  }

  //Schedule function in background job

  getAll() {
    BackgroundJob.getAll({
      callback: () => {
       SmsListener.addListener(message => {
          this.setState({ lastMessage: message.body });
        });
      }
    });
  }

  render() {
    return (
      <View>
        <Text> Scheduled jobs: {this.state.lastMessage} </Text>
      </View>
    );
  }
}

AppRegistry.registerComponent('ListenMessageApp', () => ListenMessageApp);

希望任何人提供解决方案或不同的示例、教程...来解决这个问题! 提前谢谢大家!

您应该在 SmsListenerModule.java

中评论 unregisterReceiver(mReceiver)
public void onHostPause() {
 //unregisterReceiver(mReceiver);

}

从制作 react-native-sms-listener 的人那里看这个问题 https://github.com/CentaurWarchief/react-native-android-sms-listener/issues/6

希望对您有所帮助。