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

时间:2017-07-24 06:04:27

标签: background message react-native-android

  • 我不知道如何通过React Native在后台接收消息 (仅适用于Android)

  • 我只想在Android中收到最新消息然后显示出来 在屏幕上

  • 现在它只能在前台接收。

  • 我关注了2个链接,但仍无法解决此问题

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);

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

1 个答案:

答案 0 :(得分:1)

您应该在SmsListenerModule.java

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

}

从制作react-native-sms-listener https://github.com/CentaurWarchief/react-native-android-sms-listener/issues/6

的人那里看这个问题

希望它对你有所帮助。