Keep Flutter awake to receive notifications from Firebase messaging when app is closed and Locked screen

Viewed 479

I have built my own application in flutter and I have implemented Local notifications and also FirebaseMessaging:

final FirebaseMessaging firebaseMessaging = FirebaseMessaging();
  final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
  FlutterLocalNotificationsPlugin();


  
  @override
  void initState() {
    super.initState();
    registerNotification();
    configLocalNotification();
    firebaseMessaging.requestNotificationPermissions();

  }



  void registerNotification() {
    firebaseMessaging.requestNotificationPermissions();

    firebaseMessaging.configure(onMessage: (Map<String, dynamic> message) {
      print('onMessage: $message');
      Platform.isAndroid
          ? showNotification(message['notification'])
          : showNotification(message['aps']['alert']);
      return ;
    }, onResume: (Map<String, dynamic> message) {
      print('onResume: $message');
      return Navigator.push(
          context,
          MaterialPageRoute(
              builder: (context) => NotificationsScreen()));
    }, onLaunch: (Map<String, dynamic> message) {
      print('onLaunch: $message');
      return;
    });

    firebaseMessaging.getToken().then((token) {
      print('token: $token');
      FirebaseFirestore.instance
          .collection('Consultant')
          .doc(firebaseUser.uid)
          .update({'deviceToken': token});
    }).catchError((err) {
      //Fluttertoast.showToast(msg: err.message.toString());
    });
  }

  Future selectNotification(String payload) async {
    if (payload != null) {
      debugPrint('notification payload: $payload');
    }
    await Navigator.push(
      context,
      MaterialPageRoute<void>(builder: (context) => NotificationsScreen(payload: payload,)),
    );
  }

  void showNotification(message) async {
    var androidPlatformChannelSpecifics = new AndroidNotificationDetails(
      Platform.isAndroid
          ? 'it.wytex.vibeland_pro_app'
          : 'it.wytex.vibeland_pro_app',
      'Vibeland',
      'Vibeland',
      playSound: true,
      enableVibration: true,
      importance: Importance.max,
      priority: Priority.high,
      ongoing: true,
    );
    var iOSPlatformChannelSpecifics = new IOSNotificationDetails();
    var platformChannelSpecifics = new NotificationDetails(
        android: androidPlatformChannelSpecifics, iOS: iOSPlatformChannelSpecifics);

    print(message);
    print(message['body'].toString());
    print(json.encode(message));

    await flutterLocalNotificationsPlugin.show(0, message['title'].toString(),
        message['body'].toString(), platformChannelSpecifics,
        payload: json.encode(message));

    await flutterLocalNotificationsPlugin.show(
      0, ' Hai ricevuto un messaggio  ', 'Controlla subito le Tue notifiche ', platformChannelSpecifics,
      payload: 'item x',
    );
  }

  void configLocalNotification() {
    var initializationSettingsAndroid =
    new AndroidInitializationSettings('vibeland_pro');
    var initializationSettingsIOS = new IOSInitializationSettings(
      requestAlertPermission: true,
      requestBadgePermission: true,
      requestSoundPermission: true,
    );
    var initializationSettings = new InitializationSettings(
        android: initializationSettingsAndroid, iOS: initializationSettingsIOS);
    flutterLocalNotificationsPlugin.initialize(initializationSettings);
  }

I wrote a function into index.js to push also firestore notification when user creates order etc.. Everything works fine, I got Localnotifications when all is open and FCM notifications when app is in background, the problem is when the app sleep... after some minutes the app goes in sleep mode and to start it again you need to restart the application which keep my user Logged:

MultiProvider(
      providers: [
        Provider<AuthenticationProvider>(
          create: (_) => AuthenticationProvider(FirebaseAuth.instance),
        ),
        StreamProvider(
          create: (context) => context.read<AuthenticationProvider>().authState,
        )
      ],
      child: MaterialApp(
        theme: ThemeData(
            pageTransitionsTheme: PageTransitionsTheme(
                builders: {
                  TargetPlatform.android: CupertinoPageTransitionsBuilder(
                  ),
                  TargetPlatform.iOS: CupertinoPageTransitionsBuilder(),
                }
            )
        ),
        debugShowCheckedModeBanner: false,
        title: 'Vibeland Admin Authentication',
        home: Authenticate(),
      ),
    );
  }
}

class Authenticate extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final firebaseUser = context.watch<User>();

    if (firebaseUser != null) {
      return StartScreenLogged();
    }
    return StartScreen();
  }
}

but if I dont run again the app I dont get the notification because the app sleep. what we need to do in this case?

0 Answers
Related