How can I receive SMS while the app is closed in flutter

Viewed 43

I have tried using flutter telephony Telephony but not working I want to run this service in the background when the app is not running how can I do this? Please help me so I can solve my problem

onBackgroundMessage(SmsMessage message) {
    print("onBackgroundMessage: $message");
}
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatefulWidget {
      @override
      _MyAppState createState() => _MyAppState();
    }
    
    class _MyAppState extends State<MyApp> {
      String _message = "";
      final telephony = Telephony.instance;
    
      @override
      void initState() {
        super.initState();
        initPlatformState();
      }
    
      onMessage(SmsMessage message) async {
        setState(() {
          _message = message.body ?? "Error reading message body.";
        });
      }
    
      // Platform messages are asynchronous, so we initialize in an async method.
      Future<void> initPlatformState() async {
        final bool? result = await telephony.requestPhoneAndSmsPermissions;
    
        if (result != null && result) {
          telephony.listenIncomingSms(
              onNewMessage: onMessage,
              onBackgroundMessage: onBackgroundMessage,
              listenInBackground: true);
        }
    
        if (!mounted) return;
      }
    
      @override
      Widget build(BuildContext context) {
        return Container();
      }
    }
0 Answers
Related