listenIncomingSms method

void listenIncomingSms({
  1. required MessageHandler onNewMessage,
  2. MessageHandler? onBackgroundMessage,
  3. bool listenInBackground = true,
})

Listens to incoming SMS.

Requires RECEIVE_SMS permission.

Parameters:

  • onNewMessage : Called on every new message received when app is in foreground.
  • onBackgroundMessage (optional) : Called on every new message received when app is in background.
  • listenInBackground (optional) : Defaults to true. Set to false to only listen to messages in foreground. listenInBackground is ignored if onBackgroundMessage is not set.

Implementation

void listenIncomingSms(
    {required MessageHandler onNewMessage,
    MessageHandler? onBackgroundMessage,
    bool listenInBackground = true}) {
  assert(_platform.isAndroid == true, "Can only be called on Android.");
  assert(
      listenInBackground
          ? onBackgroundMessage != null
          : onBackgroundMessage == null,
      listenInBackground
          ? "`onBackgroundMessage` cannot be null when `listenInBackground` is true. Set `listenInBackground` to false if you don't need background processing."
          : "You have set `listenInBackground` to false. `onBackgroundMessage` can only be set when `listenInBackground` is true");

  _onNewMessage = onNewMessage;

  if (listenInBackground && onBackgroundMessage != null) {
    _onBackgroundMessages = onBackgroundMessage;
    final CallbackHandle backgroundSetupHandle =
        PluginUtilities.getCallbackHandle(_flutterSmsSetupBackgroundChannel)!;
    final CallbackHandle? backgroundMessageHandle =
        PluginUtilities.getCallbackHandle(_onBackgroundMessages);

    if (backgroundMessageHandle == null) {
      throw ArgumentError(
        '''Failed to setup background message handler! `onBackgroundMessage`
        should be a TOP-LEVEL OR STATIC FUNCTION and should NOT be tied to a
        class or an anonymous function.''',
      );
    }

    _foregroundChannel.invokeMethod<bool>(
      'startBackgroundService',
      <String, dynamic>{
        'setupHandle': backgroundSetupHandle.toRawHandle(),
        'backgroundHandle': backgroundMessageHandle.toRawHandle()
      },
    );
  } else {
    _foregroundChannel.invokeMethod('disableBackgroundService');
  }
}