首页 > 解决方案 > 当应用程序关闭和锁定屏幕时,让 Flutter 保持清醒以接收来自 Firebase 消息的通知

问题描述

我在颤振中构建了自己的应用程序,并实现了本地通知和 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);
  }

我在 index.js 中编写了一个函数,以便在用户创建订单等时推送 firestore 通知。一切正常,当所有内容都打开时我得到 Localnotifications,当应用程序在后台时得到 FCM 通知,问题是当应用程序休眠时......几分钟后,应用程序进入睡眠模式并再次启动它,您需要重新启动应用程序以保持我的用户记录:

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();
  }
}

但如果我不再次运行应用程序,我不会收到通知,因为应用程序处于睡眠状态。在这种情况下我们需要做什么?

标签: androidfirebaseflutter

解决方案


推荐阅读