如何使用 FCM 在颤振中推送通知

Posted

技术标签:

【中文标题】如何使用 FCM 在颤振中推送通知【英文标题】:How to push notification in flutter using FCM 【发布时间】:2021-09-14 23:49:17 【问题描述】:

我正在尝试按照 youtube 中的代码使用 FCM 从 firebase 推送通知。运行系统时发现这个错误:

[ERROR:flutter/lib/ui/ui_dart_state.cc(199)] 未处理的异常:PlatformException(错误,NotificationChannelGroup 不存在,null,java.lang.IllegalArgumentException:NotificationChannelGroup 不存在

在firebase控制台中,状态为完成,但没有推送到模拟器。任何人都可以帮助我这是什么问题?

main.dart 代码

import 'package:flutter/material.dart';

import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:monger_app/WelcomeScreen/login.dart';
import 'package:monger_app/WelcomeScreen/signup.dart';
import 'package:monger_app/WelcomeScreen/welcome_screen.dart';
import 'package:monger_app/localization/demo_localization.dart';
import 'package:monger_app/page/pushNotification.dart';
import 'package:monger_app/page/root.dart';
import 'package:monger_app/theme/colors.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:provider/provider.dart';
import 'localization/localization_constants.dart';



void main() async 
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  //FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

  return runApp(ChangeNotifierProvider(
    child: MyApp(),
    create: (BuildContext context) => ThemeProvider(isDarkMode: true),
  ));


class MyApp extends StatefulWidget 

  static void setLocale(BuildContext context, Locale locale)
    _MyAppState state = context.findAncestorStateOfType<_MyAppState>();
    state.setLocale(locale);
  
  @override
  _MyAppState createState() => _MyAppState();


class _MyAppState extends State<MyApp> 

  Locale _locale;

  void setLocale(Locale locale)
    setState(() 
      _locale = locale;
    );
  

  FirebaseNotifcation firebase;

  handleAsync() async 
    await firebase.initialize();

    String token = await firebase.getToken();
    print("Firebase token : $token");
  

  @override
  void initState() 
    super.initState();
    firebase = FirebaseNotifcation();
    handleAsync();
  

 @override
  void didChangeDependencies() 
    getLocale().then((locale)
      setState(() 
        this._locale = locale;
      );
    );
    super.didChangeDependencies();
  

  @override
  Widget build(BuildContext context) 
    return Consumer<ThemeProvider>(
      builder: (context, themeProvider, child)
        if (_locale == null) 
          return Container(
            child: Center(
              child: CircularProgressIndicator(),
            ),
          );
         else 
          return MaterialApp(
            theme: themeProvider.getTheme,
            locale: _locale,
            supportedLocales: [
              Locale('en', 'US'),
              Locale('id', 'ID'),
              Locale('zh', 'CN'),
            ],
            localizationsDelegates: [
              DemoLocalization.delegate,
              GlobalMaterialLocalizations.delegate,
              GlobalWidgetsLocalizations.delegate,
              GlobalCupertinoLocalizations.delegate,
            ],
            localeResolutionCallback: (deviceLocale, supportedLocales)
              for (var locale in supportedLocales) 
                if (locale.languageCode == deviceLocale.languageCode && locale.countryCode == deviceLocale.countryCode) 
                  return deviceLocale;
                
              
              return supportedLocales.first;
            ,
            debugShowCheckedModeBanner: false,
            home:

            WelcomeScreen(),

            routes: <String,WidgetBuilder>

              "SignIn" : (BuildContext context)=>LoginPage(),
              "SignUp":(BuildContext context)=>SignUpPage(),
              "start":(BuildContext context)=>Root(),
              "welcome":(BuildContext context)=>WelcomeScreen(),
            ,

          );
        
      
    );
  

puchNotification.dart 代码

import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';

const androidNotificationChannel channel = AndroidNotificationChannel(
    'high_importance_channel',
    "High Importance Notifcations",
    "This channel is used important notification",
    groupId: "Notification_group");

final FlutterLocalNotificationsPlugin flutterLocalNotificationplugin =
FlutterLocalNotificationsPlugin();

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async 
  await Firebase.initializeApp();
  print("Handling a background message : $message.messageId");
  print(message.data);


class FirebaseNotifcation 
  initialize() async 
    await Firebase.initializeApp();
    FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

    await flutterLocalNotificationplugin
        .resolvePlatformSpecificImplementation<
        AndroidFlutterLocalNotificationsPlugin>()
        ?.createNotificationChannel(channel);
    var intializationSettingsAndroid =
    AndroidInitializationSettings('@mipmap/ic_launcher');
    var initializationSettings =
    InitializationSettings(android: intializationSettingsAndroid);

    flutterLocalNotificationplugin.initialize(initializationSettings);
    FirebaseMessaging.onMessage.listen((RemoteMessage message) async 
      RemoteNotification notification = message.notification;
      AndroidNotification android = message.notification?.android;
      if (notification != null && android != null) 
        AndroidNotificationDetails notificationDetails =
        AndroidNotificationDetails(
            channel.id, channel.name, channel.description,
            importance: Importance.max,
            priority: Priority.high,
            groupKey: channel.groupId);
        NotificationDetails notificationDetailsPlatformSpefics =
        NotificationDetails(android: notificationDetails);
        flutterLocalNotificationplugin.show(
            notification.hashCode,
            notification.title,
            notification.body,
            notificationDetailsPlatformSpefics);
      

      List<ActiveNotification> activeNotifications =
      await flutterLocalNotificationplugin
          .resolvePlatformSpecificImplementation<
          AndroidFlutterLocalNotificationsPlugin>()
          ?.getActiveNotifications();
      if (activeNotifications.length > 0) 
        List<String> lines =
        activeNotifications.map((e) => e.title.toString()).toList();
        InboxStyleInformation inboxStyleInformation = InboxStyleInformation(
            lines,
            contentTitle: "$activeNotifications.length - 1 messages",
            summaryText: "$activeNotifications.length - 1 messages");
        AndroidNotificationDetails groupNotificationDetails =
        AndroidNotificationDetails(
            channel.id, channel.name, channel.description,
            styleInformation: inboxStyleInformation,
            setAsGroupSummary: true,
            groupKey: channel.groupId);

        NotificationDetails groupNotificationDetailsPlatformSpefics =
        NotificationDetails(android: groupNotificationDetails);
        await flutterLocalNotificationplugin.show(
            0, '', '', groupNotificationDetailsPlatformSpefics);
      
    );
  

  Future<String> getToken() async 
    String token = await FirebaseMessaging.instance.getToken();
    print(token);
    return token;
  

  subscribeToTopic(String topic) async 
    await FirebaseMessaging.instance.subscribeToTopic(topic);
  

build.gradle 文件

def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) 
    localPropertiesFile.withReader('UTF-8')  reader ->
        localProperties.load(reader)
    


def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) 
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")


def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) 
    flutterVersionCode = '1'


def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) 
    flutterVersionName = '1.0'


apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android 
    compileSdkVersion 30

    sourceSets 
        main.java.srcDirs += 'src/main/kotlin'
    

    defaultConfig 
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.example.monger_app"
        minSdkVersion 21
        targetSdkVersion 30
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
    

    buildTypes 
        release 
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        
    


flutter 
    source '../..'


dependencies 
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation platform('com.google.firebase:firebase-bom:28.0.1')
    implementation "com.google.firebase:firebase-messaging:20.1.0"


apply plugin: 'com.google.gms.google-services'

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.monger_app">

   <application
       tools:replace="android:label"
        android:name=".Application"
        android:label="MONGE"
        android:icon="@mipmap/ic_launcher">
        <activity
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            <!-- Specifies an Android theme to apply to this Activity as soon as
                 the Android process has started. This theme is visible to the user
                 while the Flutter UI initializes. After that, this theme continues
                 to determine the Window background behind the Flutter UI. -->
            <meta-data
              android:name="io.flutter.embedding.android.NormalTheme"
              android:resource="@style/NormalTheme"
              />
            <!-- Displays an Android View that continues showing the launch screen
                 Drawable until Flutter paints its first frame, then this splash
                 screen fades out. A splash screen is useful to avoid any visual
                 gap between the end of Android's launch screen and the painting of
                 Flutter's first frame. -->
            <meta-data
              android:name="io.flutter.embedding.android.SplashScreenDrawable"
              android:resource="@drawable/launch_background"
              />
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
            <intent-filter>
                <action android:name="FLUTTER_NOTIFICATION_CLICK" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <!-- Don't delete the meta-data below.
             This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />
    </application>
</manifest>

【问题讨论】:

【参考方案1】:

如果不需要,可以删除pushNotification.dart中的groupId: "Notification_group"。我的问题就是用这种方法解决的。

【讨论】:

【参考方案2】:

显示错误是因为您将组 ID 传递给通知通道,但您没有创建通知通道组。

解决方案:

如果您不需要通知频道组:

您可以通过从 AndroidNotificationChannel 对象中删除可选的 groupId 参数来消除错误。

将您的 channel 更新为:

const AndroidNotificationChannel channel = AndroidNotificationChannel(
 'high_importance_channel',
 "High Importance Notifcations",
 "This channel is used important notification");

如果您确实需要通知频道组:

创建一个通知通道组,并为其分配与您添加到通知通道相同的组 ID。

这是来自flutter_local_notifications 包example 的代码sn-p,显示了这一点。

const String channelGroupId = 'your channel group id';
// create the group first
const AndroidNotificationChannelGroup androidNotificationChannelGroup =
 AndroidNotificationChannelGroup(
     channelGroupId, 'your channel group name',
     description: 'your channel group description');
await flutterLocalNotificationsPlugin
 .resolvePlatformSpecificImplementation<
     AndroidFlutterLocalNotificationsPlugin>()!
 .createNotificationChannelGroup(androidNotificationChannelGroup);

// create channels associated with the group
await flutterLocalNotificationsPlugin
 .resolvePlatformSpecificImplementation<
     AndroidFlutterLocalNotificationsPlugin>()!
 .createNotificationChannel(const AndroidNotificationChannel(
     'grouped channel id 1',
     'grouped channel name 1',
     'grouped channel description 1',
     groupId: channelGroupId));

【讨论】:

以上是关于如何使用 FCM 在颤振中推送通知的主要内容,如果未能解决你的问题,请参考以下文章

颤振:fcm ios 推送通知在发布模式下不起作用

使用 FCM 推送通知时颤动中的 Kotlin 文件错误

单击推送通知时如何在我的颤振应用程序中打开特定页面

在我的颤振(android)应用程序中 - Firebase 推送通知在一段时间后停止接收每个用户

如何获取 FCM-Django 推送通知的 registration_id (flutter app)

Flutter FCM 推送通知不起作用