briankabiro / react-native-get-sms-android

React Native module to get messages on an Android device

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Does this work when app is in the background?

frabanca opened this issue · comments

Thanks for any reply

Hey @frabanca. This totally slipped my mind.

Have you made any progress on this end?

Hi @briankabiro!

After a few minutes of panic I realized I could use this plugin: react-native-background-job.
Usege is really simple. I'll describe how I've done in case someone will need this in the future.

First step, add this to index.js in the root of your app project:

// other code & imports
const smsService = new SMSService();

// Register scheduled background job
BackgroundJob.register({
  jobKey: 'readReceivedSMS',
  job: () => smsService.readSMSList(),
});

// Register react main component
AppRegistry.registerComponent(appName, () => App);

Second step: write SMSService

// Core packages

// Third party packages
import SmsAndroid from 'react-native-get-sms-android';
import {Alert} from 'react-native';
import moment from 'moment';
import 'moment/locale/it';
moment.locale('it');

// Custom packages
import SMSInterface from '../interfaces/sms.interface';
import CONFIG from '../config/';

/**
 * Script start
 */
class SMSService {
  filters = {
    box: 'inbox', // 'inbox' (default), 'sent', 'draft', 'outbox', 'failed', 'queued', and '' for all

    // the next 4 filters should NOT be used together, they are OR-ed so pick one
    read: 0, // 0 for unread SMS, 1 for SMS already read
    // _id: 1234, // specify the msg id
    // address: '+1888------', // sender's phone number
    // body: 'How are you', // content to match

    // the next 2 filters can be used for pagination
    indexFrom: 0, // start from index 0
    maxCount: 200, // count of SMS to return each time

    // minDate: moment().subtract(this.loadSMSTimeout, 'milliseconds').unix(),
    // maxDate: 0,
  };

  /**
   * Read received sms list
   *
   * @since 1.0.0
   */
  async readSMSList(interval?: number, conditions?: any): Promise<void> {
    const filters = conditions || this.filters;
    SmsAndroid.list(
      JSON.stringify(filters),
      (fail: string) => {
        Alert.alert(
          'Warning!',
          fail,
        );
      },
      async (count: number, smsList: string) => {
        const rawItems = JSON.parse(smsList);
        const now = moment();

        // Get all-and-only the items received in the last
        // this.loadSMSTimeout time
        const newItems = rawItems.filter((item: SMSInterface) => {
          const receivedAt = moment(item.date);
          const elapsedMilliseconds = now.diff(receivedAt, 'milliseconds');
          const contingency = CONFIG.READ_SMS_CONTINGENCY * 1000;
          if (
            elapsedMilliseconds <
            CONFIG.READ_SMS_TIMEOUT * 1000 - contingency
          ) {
            return item;
          }
        });
    
        // SMS are now inside 'newItems' const
        // todo handle data (upload, filter, show, ...)
      },
    );
  }

  /**
   * Send an SMS to given 'phoneNumber' with given 'message' and returns
   * a boolean value 'true' if SMS was sent or 'false' if was not sent
   *
   * @since 1.0.0
   */
  async sendSMS(phoneNumber: string, message: string): Promise<ApiResponse> {
    return new Promise(resolve => {
      SmsAndroid.autoSend(
        phoneNumber,
        message,
        (fail: string) => {
          return resolve({
            ok: false,
            status: 500,
            message: fail,
          });
        },
        (success: string) => {
          console.log('success', success);
          return resolve({
            ok: true,
            status: 200,
          });
        },
      );
    });
  }

  // Other methods...
}

export default SMSService;

Third and last step, activate background task:

            BackgroundJob.schedule({
              jobKey: 'readReceivedSMS',
              period: CONFIG.READ_SMS_TIMEOUT * 1000,
              exact: true,
              allowWhileIdle: true,
              allowExecutionInForeground: true,
            });

Config file share plz