Flutter Firebase Cloud Messaging-在后台运行应用程序时发出通知

时间:2019-09-30 09:09:04

标签: firebase flutter firebase-cloud-messaging

我当前正在使用FCM进行推送通知。当我的应用程序打开时,我会收到通知,但是当应用程序关闭或在后台时,我不会收到任何通知,直到我重新打开该应用程序为止。在XCode上,我启用了后台提取并启用了远程通知。接下来我应该检查什么?谢谢。

我正在使用firebase_messaging: ^5.1.6

带有代码

    _firebaseMessaging.configure(
      onMessage: (Map<String, dynamic> message) async {
        print('message is $message');

        setState(
          () {
            showOverlayNotification((context) {
              return GestureDetector(
                onTap: () {},
                child: Platform.isIOS
                    ? MessageNotification(
                        title: message['notification']['title'],
                        body: message['notification']['body'],
                      )
                    : MessageNotification(
                        title: message['notification']['title'],
                        body: message['notification']['body'],
                      ),
              );
              // }
            }, duration: Duration(milliseconds: 4000));
          },
        );
      },
      onLaunch: (Map<String, dynamic> message) async {
        print('launching');
      },
      onResume: (Map<String, dynamic> message) async {
        print('resuming');
        print("onResume: $message");
      },
    );
    _firebaseMessaging.requestNotificationPermissions(
        const IosNotificationSettings(sound: true, badge: true, alert: true));
    _firebaseMessaging.onIosSettingsRegistered
        .listen((IosNotificationSettings settings) {
      print("Settings registered: $settings");
    });
    _firebaseMessaging.getToken().then((String token) {
      assert(token != null);
      setState(() {
        _firebaseMessaging.subscribeToTopic('all');
        print('subscribed');
        _homeScreenText = "Push Messaging token: $token";
        _saveDeviceToken(token);
      });
      print(_homeScreenText);
    }); ```


My flutter doctor response is:

```[✓] Flutter (Channel stable, v1.9.1+hotfix.2, on Mac OS X 10.14.6 18G103, locale en-GB)
    • Flutter version 1.9.1+hotfix.2 at /Users/student/flutter
    • Framework revision 2d2a1ffec9 (3 weeks ago), 2019-09-06 18:39:49 -0700
    • Engine revision b863200c37
    • Dart version 2.5.0


[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.0)
    • Android SDK at /Users/student/Library/Android/sdk
    • Android NDK location not configured (optional; useful for native profiling support)
    • Platform android-29, build-tools 29.0.0
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1343-b01)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 11.0)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 11.0, Build version 11A420a
    • CocoaPods version 1.7.4

[✓] Android Studio (version 3.4)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin version 38.2.1
    • Dart plugin version 183.6270
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1343-b01)

[✓] VS Code (version 1.38.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.4.1

[✓] Connected device (1 available)
    • iPhone • e1100c84b1fc7871a6790337ef23c0fd7af397d5 • ios • iOS 12.4.1

4 个答案:

答案 0 :(得分:1)

移动端

我努力了,终于想出了解决方案

get_it: ^4.0.4添加到您的pubspec.yaml

使用以下内容创建文件Locator.dart:

import 'package:flutter/widgets.dart';

//Open Screen Without Context Service


class NavigationService {
  final  GlobalKey<NavigatorState> navigatorKey =
  new GlobalKey<NavigatorState>();

  navigateTo(String routeName , String name) {
    return navigatorKey.currentState.pushNamed(routeName , arguments: name);
  }

  goBack() {
    return navigatorKey.currentState.pop();
  }


}

使用以下内容创建文件Locator.dart:

import 'package:get_it/get_it.dart';
import 'package:MyProject/Services/NavigationService.dart';

//Open Screen Without Context

GetIt locator = GetIt.instance;

void setupLocator() {
  locator.registerLazySingleton(() => NavigationService());
}

最后,您的main.dart必须是这样的:

import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get_it/get_it.dart';
import 'package:MyProject/Services/NavigationService.dart';
import 'package:MyProject/Utils/locator.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();

  @override
  void initState() {
    GetIt.instance.registerSingleton<NavigationService>(NavigationService());
    getMessage();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'App name',
      navigatorKey: locator<NavigationService>().navigatorKey,
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
          primaryColorDark: Color(0xff440ABC),
          primaryColor: Color(0xff703FF7),
          primaryColorLight: Color(0xff7e51fa),
          accentColor: Color(0xffc09b01),
          hintColor: Color(0xff616161),
          backgroundColor: Color(0xffFEF9F9),
          bottomAppBarColor: Color(0xffFEF9F9),
          fontFamily: 'Sans'),

      ///MyRequestsScreen
      onGenerateRoute: (routeSettings) {
        switch (routeSettings.name) {
          case 'DestinationScreen':
            return MaterialPageRoute(
                builder: (context) => DestinationScreen());
          default:
            return null;
        }
      },
      home: MenuScreen(),
    );
  }

  void getMessage() {
    _firebaseMessaging.configure(onMessage: (Map<String, dynamic> message) async {
      locator<NavigationService>().navigateTo('DestinationScreen', "go");
    }, onResume: (Map<String, dynamic> message) async {
      locator<NavigationService>().navigateTo('DestinationScreen', "data");
    }, onLaunch: (Map<String, dynamic> message) async {
      locator<NavigationService>().navigateTo('DestinationScreen', "data");
    });
  }
}

服务器端

添加:

"data": {
        "click_action": "FLUTTER_NOTIFICATION_CLICK"
    }

在您的json中,如下所示:

{
    "to": "YOUR_PUSH_ID",
    "notification": {
        "body": "YOUR_MESSAGE",
        "OrganizationId": "2",
        "content_available": true,
        "priority": "high",
        "subtitle": "Elementary School",
        "title": "YOUR_TITLE"
    },
    "data": {
        "click_action": "FLUTTER_NOTIFICATION_CLICK"
    }
}

答案 1 :(得分:0)

如果您想通过Firebase功能进行后台通知 然后您可以查看下面的代码并实现输出。... Flutter automatic notification function

答案 2 :(得分:0)

我设法通过删除对Flutter Local Notification插件的任何引用来解决此问题。我随后将其删除:

constructor( private storage: Storage) {

   }


    async get(key: string): Promise<any> {
    try {
      const result = await this.storage.get(key);
      console.log('storageGET: ' + key + ': ' + result);
      if (result != null) {
      return result;
      }
      return null;
    } catch (reason) {
    console.log(reason);
    return null;
    }
    }


    async ready() : Promise<any>{
      try {
        this.storage.ready();
        return true; 
      }
      catch(err) {
        console.log(err)
      }
    }

来自ios / runner / AppDelegate.m或ios / runner / AppDelegate.swift文件。

通知随后开始正常运行。

答案 3 :(得分:0)

发生这种情况可能有两个原因,这是什么,有什么解决办法,如下所示。

  1. 要将插件集成到应用程序的iOS部分,然后首先必须执行以下步骤,如果尚未完成,请先执行以下操作:

    使用工作区在Xcode中打开您的项目。在项目浏览器中选择“运行器”。在“功能”选项卡中,打开Push NotificationsBackground Modes,然后在Background fetch下启用Remote notificationsBackground Modes

  2. 如果您需要启用FCM iOS SDK完成的方法转换(例如,以便可以将此插件与其他通知插件一起使用),则将以下内容删除到应用程序的Info.plist文件中。

  3. >
    <key>FirebaseAppDelegateProxyEnabled</key>
    <false/>
    

    然后,将以下行删除到iOS项目(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions中的AppDelegate.m/AppDelegate.swift方法中。

    迅速:

    if #available(iOS 10.0, *) {
      UNUserNotificationCenter.current().delegate = self as? 
     UNUserNotificationCenterDelegate
    }
    

    Objective-C:

    if (@available(iOS 10.0, *)) {
       [UNUserNotificationCenter currentNotificationCenter].delegate = 
       (id<UNUserNotificationCenterDelegate>) self;
     }
    

注意 如果您需要禁用FCM iOS SDK进行的方法修改,请添加以下行和代码