PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, July 11, 2022

[FIXED] How to receive messages in foreground-background - React Native?

 July 11, 2022     background, message, react-native-android     No comments   

Issue

  • 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!


Solution

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.



Answered By - Stepan Nikulenko
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing