How to receive messages in foreground-background - React Native?
Asked Answered
N

2

6
  • I don't know how to get receive message in background by React Native (only for Android)

  • I simply want to receive the latest message in Android then show up on screen

  • Now it only can receive in the foreground.

  • I followed 2 links but still can't overcome this problem

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

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

This is my code

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

Hope anyone giving a solution or a different sample, tutorial,... to solve this! Thank you all in advance!

Nevus answered 24/7, 2017 at 6:4 Comment(1)
BackgroundJob.getAll() in not available in recent version . Link : github.com/vikeri/react-native-background-jobCuman
V
5

You should comment unregisterReceiver(mReceiver) in SmsListenerModule.java

public void onHostPause() {
 //unregisterReceiver(mReceiver);

}

Look at this issue from guys who made react-native-sms-listener https://github.com/CentaurWarchief/react-native-android-sms-listener/issues/6

Hope it helps you.

Volcanism answered 26/7, 2017 at 15:3 Comment(2)
You really saved my life!Nevus
if u close the app, it stops listeningAmpulla
S
0

this plugin save my life react-native-android-sms-listener-background https://www.npmjs.com/package/react-native-android-sms-listener-background

first uninstall old plugin npm uninstall react-native-android-sms-listener

then install this plugin npm install react-native-android-sms-listener-background

then import like this in you components
import SmsListener from 'react-native-android-sms-listener-background'

other all code same as the old plugin but this only run in the background only i think

Schroer answered 23/9, 2022 at 15:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.