Listen Incoming SMS

Setup

To listen to incoming SMS add the RECEIVE_SMS permission to your AndroidManifest.xml file and register the BroadcastReceiver.

AndroidManifest.xml
<manifest>
    <uses-permission android:name="android.permission.RECEIVE_SMS"/>

    <application>
        ...
        ...

        <receiver android:name="com.shounakmulay.telephony.sms.IncomingSmsReceiver"
            android:permission="android.permission.BROADCAST_SMS" android:exported="true">
            <intent-filter>
            <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
            </intent-filter>
        </receiver>

    </application>
</manifest>

Usage

1. Create a top-level static function to handle incoming messages when app is not is foreground.

backgrounMessageHandler(SmsMessage message) async {
    //Handle background message    
}

void main() {
  runApp(MyApp());
}

2. Call listenIncomingSms with a foreground MessageHandler and pass in the static backgrounMessageHandler.

Multipart message will be grouped together and delivered as a single SMS to the listenIncomingSms() function.

telephony.listenIncomingSms(
     onNewMessage: (SmsMessage message) {
         // Handle message
     },
     onBackgroundMessage: backgroundMessageHandler
 );

Preferably should be called early in app lifecycle.

3. As of the 1.12 release of Flutter, plugins are automatically registered. This will allow you to use plugins as you normally do even in the background execution context.

backgrounMessageHandler(SmsMessage message) async {
     // Handle background message

     // Use plugins
     Vibration.vibrate(duration: 500);
 }

4. If you do not wish to receive incoming SMS when the app is in background, just do not pass the onBackgroundMessage parameter.

Alternatively if you prefer to expecility disable background execution, set the listenInBackground flag to false.

telephony.listenIncomingSms(
     onNewMessage: (SmsMessage message) {
         // Handle message
     },
     listenInBackground: false
 );

Last updated

Was this helpful?