Giter Club home page Giter Club logo

react-native-android-sms-listener's Introduction

react-native-android-sms-listener react-native-android-sms-listener

A utility that allows you to listen for incoming SMS messages.

Example

import SmsListener from 'react-native-android-sms-listener'

SmsListener.addListener(message => {
  console.info(message)
})

The contents of message object will be:

{
  originatingAddress: string,
  body: string,
  timestamp: number
}

SmsListener#addListener returns a CancellableSubscription so if you want to stop listening for incoming SMS messages you can simply .remove it:

let subscription = SmsListener.addListener(...)

subscription.remove()

In recent versions of Android you might also have to ask for permissions:

async function requestReadSmsPermission() {
  try {
    await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.READ_SMS,
      {
        title: "(...)",
        message: "Why you're asking for..."
      }
    );
  } catch (err) {}
}

class MyComponent extends Component {
  // ...

  componentDidMount() {
    requestReadSmsPermission();
  }

  // ...
}

Example of using it for verification purposes:

...and if in your sign up process you have the phone number verification step which is done by sending a code via SMS to the specified phone, you might want to verify it automatically when the user receive it — pretty much like what Telegram or WhatsApp does:

let subscription = SmsListener.addListener(message => {
  let verificationCodeRegex = /Your verification code: ([\d]{6})/

  if (verificationCodeRegex.test(message.body)) {
    let verificationCode = message.body.match(verificationCodeRegex)[1]

    YourPhoneVerificationApi.verifyPhoneNumber(
      message.originatingAddress,
      verificationCode
    ).then(verifiedSuccessfully => {
      if (verifiedSuccessfully) {
        subscription.remove()
        return
      }

      if (__DEV__) {
        console.info(
          'Failed to verify phone `%s` using code `%s`',
          message.originatingAddress,
          verificationCode
        )
      }
    })
  }
})

If you're using Twilio or a similar third-party messaging service which you have a fixed phone number to deliver messages you might want to ensure that the message comes from your service by checking message.originatingAddress.

Installation

$ npm install --save react-native-android-sms-listener
$ react-native link react-native-android-sms-listener

Manual Installation

For a manual installation, all you need to do to use this so-called utility is:

android/settings.gradle

include ':react-native-android-sms-listener'
project(':react-native-android-sms-listener').projectDir = new File(rootProject.projectDir,'../node_modules/react-native-android-sms-listener/android')

android/app/build.gradle

dependencies {
  compile project(':react-native-android-sms-listener')
  // (...)
}

MainApplication.java

import com.centaurwarchief.smslistener.SmsListenerPackage;
@Override
protected List<ReactPackage> getPackages() {
  return Arrays.<ReactPackage>asList(
    new MainReactPackage(),
    new SmsListenerPackage()
    // (...)
  );
}

react-native-android-sms-listener's People

Contributors

adrian-tiberius avatar alwx avatar andreyvital avatar bartekczyz avatar bosz avatar bryant1410 avatar daniakash avatar endoooo avatar fgreinus avatar harish2704 avatar mcodex avatar ramongebben avatar samin avatar skb1129 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

react-native-android-sms-listener's Issues

it doesn't work for me at all

i installed the package of react-native-android-sms-listener
and this is my code in a Function :

  SmsRetriever.addSmsListener(event => {
          alert(event.message);
          SmsRetriever.removeSmsListener();
        }); 

and when I press a bottom, this code runs...

and i didn't get any alert in my application

not working in release build

this plugin works in debug mode and when I created a release build the plugin is not working. I am not sure why it is working in debug and not working in release.

Issue: Violation of Permissions policy From Google Playstore

I used this awesome package and since it did not work on newer versions of Android unless you ask for user permissions.
After asking for permissions this way

    async requestReadSmsPermission() {
      try {
      var granted = await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.READ_SMS,
      {
      title: "Auto Verification OTP",
      message: "need access to read sms, to verify OTP"
      }
      );
      if (granted === PermissionsAndroid.RESULTS.GRANTED) {
      console.log("sms read permissions granted", granted); 
      granted = await PermissionsAndroid.request( 
      PermissionsAndroid.PERMISSIONS.RECEIVE_SMS,{ 
      title: "Receive SMS",
      message: "Need access to receive sms, to verify OTP"
      }
      );
      if (granted === PermissionsAndroid.RESULTS.GRANTED) {
      console.log("RECEIVE_SMS permissions granted", granted);
      } else {
      console.log("RECEIVE_SMS permissions denied");
      }
      } else {
      console.log("sms read permissions denied");
      }
      } catch (err) {
      console.log(err);
      }
    }

Everything worked wonderfully well till I tried to submit the app and then Google Review sent this

Publishing status: Rejected
After review, your app has been rejected and wasn't published due to a policy violation. If you submitted an update, the previous version of your app is still available on Google Play. 

Issue: Violation of Permissions policy
--
After reviewing your app, we found that it doesn’t qualify to use the requested permissions

What do I do please

cannot find symbol?

Followed the instructions and got this error.

Using RN 30

:app:processDebugResources UP-TO-DATE
:app:generateDebugSources UP-TO-DATE
:app:processDebugJavaRes UP-TO-DATE
:app:compileDebugJavaWithJavac
appProject/MainApplication.java:11: error: cannot find symbol
import com.centaurwarchief.smslistener;
                          ^
  symbol:   class smslistener
  location: package com.centaurwarchief
appProject/MainApplication.java:30: error: cannot find symbol
          new SmsListener()
              ^
  symbol: class SmsListener
2 errors
:app:compileDebugJavaWithJavac FAILED

Any idea why?

Emit receive sms many time.

My code:
`
import SmsListener from 'react-native-android-sms-listener'

SmsListener.addListener( message => {
console.log("add:", message)
})`

And the result:

LOG  add: {"body": "Android is always a sweet treat!000000", "originatingAddress": "123", "timestamp": 1617089036000}
 LOG  add: {"body": "Android is always a sweet treat!000000", "originatingAddress": "123", "timestamp": 1617089036000}
 LOG  add: {"body": "Android is always a sweet treat!000000", "originatingAddress": "123", "timestamp": 1617089036000}
 LOG  add: {"body": "Android is always a sweet treat!000000", "originatingAddress": "123", "timestamp": 1617089036000}
 LOG  add: {"body": "Android is always a sweet treat!000000", "originatingAddress": "123", "timestamp": 1617089036000}
 LOG  add: {"body": "Android is always a sweet treat!000000", "originatingAddress": "123", "timestamp": 1617089036000}
 LOG  add: {"body": "Android is always a sweet treat!111111", "originatingAddress": "123", "timestamp": 1617089045000}
 LOG  add: {"body": "Android is always a sweet treat!111111", "originatingAddress": "123", "timestamp": 1617089045000}
 LOG  add: {"body": "Android is always a sweet treat!111111", "originatingAddress": "123", "timestamp": 1617089045000}
 LOG  add: {"body": "Android is always a sweet treat!111111", "originatingAddress": "123", "timestamp": 1617089045000}

p/s: I run this code on the android emulator

iOS support

I'd love to use this but I will need it for both iOS and android. Do you have any plans to port this to iOS in the near future?

Google play store reject my app because of permission

This is the message google send me :

Based on our review, we found your app’s expressed user experience did not match your declared core functionality {Default SMS handler (and any other core functionality usage while default handler)}. Please remove these permissions from your app.

Default handler capability was listed on your declaration form, but your app does not appear to have default handler capability. Please submit a revised declaration form.

This is my source code :
componentDidMount() {
if(Platform.OS === 'android') {
this._requestReadSmsPermission()
}
}

_requestReadSmsPermission = async () => {
try {
const result = await PermissionsAndroid.requestMultiple([PermissionsAndroid.PERMISSIONS.RECEIVE_SMS, PermissionsAndroid.PERMISSIONS.READ_SMS])

  if (result['android.permission.RECEIVE_SMS'] && result['android.permission.READ_SMS'] === PermissionsAndroid.RESULTS.GRANTED) {
    this.smsListener = SmsListener.addListener(message => {
      if(message.originatingAddress == "MYNAME") {
        let verificationCodeRegex = /: ([\d]{6})/
    
        if (verificationCodeRegex.test(message.body)) {
          let verificationCode = message.body.match(verificationCodeRegex)[1]

          if(codeVerification == verificationCode) {
            alert('Succes verification')
          }
        }
      }
    })
  }
} catch (err) {
  console.warn(err)
}

}

And this is my androidmanifest :

Not listening

Hi! I have added everything like in guide, added listener to my view, but it does not enter listener's callback

React Native 0.56 Support

In React Native 0.56
Android projects are compiled by SDK level 26 as default

https://github.com/react-native-community/react-native-releases/blob/master/CHANGELOG.md#android-projects-are-now-compiled-using-the-android-26-sdk

This causes the following issue with this plugin:

* What went wrong:
A problem occurred configuring project ':app'.
> Could not resolve all dependencies for configuration ':app:_debugApk'.
   > A problem occurred configuring project ':react-native-android-sms-listener'.
      > The SDK Build Tools revision (23.0.2) is too low for project ':react-native-android-sms-listener'. Minimum required is 25.0.0

It'd be helpful to know if any work arounds are available until this plugin supports 0.56

TypeError: Cannot read property 'message' of undefined

after I have setup this module,

I tried to run-android but I get the following error:
TypeError: Cannot read property 'message' of undefined

------ Here's the logs ----------
FAILURE: Build failed with an exception.

  • What went wrong:
    A problem occurred configuring project ':app'.

A problem occurred configuring project ':react-native-android-sms-listener'.
failed to find Build Tools revision 23.0.2

  • Try:
    Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 24.349 secs
Could not install the app on the device, read the error above for details.
Make sure you have an Android emulator running or a device connected and have
set up your Android development environment:
https://facebook.github.io/react-native/docs/android-setup.html

(node:32854) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): TypeError: Cannot read property 'message' of undefined


Wondering if this is an issue with react-native version compatibility.
"react-native": "^0.40.0",

error java.lang.IllegalArgumentException: Receiver not registered: com.centaurwarchief.smslistener.SmsReceiver@b16a902

Description

This error happens when the application goes to background using the back button of the system, if I put the application on background by hitting "home" or "see background application button" this error is not triggered.

What I have done by now is to set a try catch on the unregister method, even when it avoid the application to crash it doesn't solve the right problem.

screenshot_6_26_16__7_15_pm

snippet to avoid this:

// line 42 of SmsListenerModule.java
private void unregisterReceiver(BroadcastReceiver receiver) {
        try {
            mActivity.unregisterReceiver(receiver);
            mReceiver = null;
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
    }

Version of module

0.2.0

Device

HTC M8 - OS 6.0

Error

messagedemographic_java_-wobe-___mobile_client_wobe

Trigger multiple callbacks when received one sms

if (subscription == null) { subscription = SmsListener.addListener(message => { console.info(message); this._smsAnalysis(message.body) }); }
Uploading image.png…

_smsAnalysis function is called multiple times when received one sms

pls support RN 0.47+

on android, method createJSModules has been deprecated, can you fix it and release new version of this plugin? thanks very much.

"Couldnt find a declaration module"

image

I get that error when importing the module in my file.

Checking I have seen that the index.js of the module have some errors for me:
image

Any solution?

Facing issue in broadcast listener

Hi

Hope all is good

I'm using this plugin to detect the incoming message. Me and my team are facing stability issue in the broadcast receiver. Sometimes we are getting the output sometimes the SMS is not getting listened. We tried to implement the functionality in native android and it was working fine. While receiving the SMS it's not getting entered in the onReceive method.

My doubt here is does this issues is happening because of any kind of react-native restrictions? also the SMS is not getting detected in when the app is in background state

From code point of view we added the lines only present in the documentation given by your team. Kindly note

Device used for testing:

  1. Redmi 6 pro - Pie OS

Please do the needful

listener not working

react-native : 0.51
when i get a sms ,my app doesn't alert any message!

this.SMSReadSubscription = SmsListener.addListener(message => {
alert(message);
});

(1) Multiple registrations of Receiver (2) doesn't work when app is closed

(1) If the app is closed (doesn't matter whether or not it is cleared from recent apps) and then re-opened, then a new instance of the listener gets registered, while the previous ones still persist. Therefore, each new SMS starts triggering all registered receivers.

(2) Even though registered receivers persist across closing / re-opening of app, they don't respond if the app has been closed (doesn't matter whether or not it is cleared from recent apps). That is even though the registered receivers are alive, they don't get triggered until the app is in the foreground.

While the first limitation above could be handled by simply unregistering the listener before the app closes (which function do i invoke for doing that?), the 2nd limitation seems more inhibiting and seriously confines the usage of package.

SmsListener.addListener is not working on real device of android 12 but it's working on emulator.

Same code is working on emulator but it's not working on real device.

All the permissions are provided:
await PermissionsAndroid.request("android.permission.RECEIVE_SMS");
await PermissionsAndroid.request("android.permission.READ_SMS");
await PermissionsAndroid.request("android.permission.SEND_SMS");
await PermissionsAndroid.request("android.permission.READ_CALL_LOG");
await PermissionsAndroid.request("android.permission.READ_PHONE_STATE");

useEffect(() => {
console.log("Start SMS Listener")
let subscription = SmsListener.addListener((message) => {
console.log("Message", message);
setMessage(message);
});
return () => {
console.log("Stop SMS Listener")
subscription.remove();
};
}, []);

Please help me out.
Thanks.

listener not working for android

react-native :0.47.2
android device OS: marshmallow, nougat,
device manufacturer: Moto
inside package.json "react-native-android-sms-listener": "^0.5.0",
//code inside
let subscription = SmsListener.addListener(message => {
let verificationCodeRegex = /Your verification code: ([\d]{7})/
if (verificationCodeRegex.test(message.body)) {
let verificationCode = message.body.match(verificationCodeRegex)[1]
newThis.setState({ verificationCode: verificationCode })
}
alert(message)
console.log('message', message)
})

I have followed all installation steps and i have used alert inside listener, even added log for message but listener not working

Changes needed for gradle 3.0.1 compatibility

Some minor changes are needed for gradle 3.0.1 compatibility: in android/build.gradle:

We are currently hacking these changes with a script in status.im, and would rather it is fixed upstream. Thanks!

Parent issue: status-im/status-mobile#3037

RN0.29+

Hello, first of all I would like to thank you!! It's an awesome module =D But I was wondering if you have any plans to release a new version which is compatible with RN0.29+?

Again, thank you!

Error: Cannot find symbol com.centaurwarchief.smslistener

I have React Native 0.29.1 version. I followed the instructions given to install the package. However, when I run react-native run-android it gives the following error

error: cannot find symbol import com.centaurwarchief.smslistener; and
error: cannot find symbol new SmsListener()

Deprecation message

Hi,

I'm starting to use your library and I've noticed that a message appears during compilation:

Note: [path]/node_modules/react-native-push-notification/android/src/main/java/com/dieam/reactnativepushnotification/helpers/ApplicationBadgeHelper.java uses or overrides a deprecated API.

I don't know if you already know that, looks like something with the icon badge.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.