Flutter消息处理插件bdaya_fcm_handler的使用

发布于 1周前 作者 htzhanglong 来自 Flutter

bdaya_fcm_handler

bdaya_fcm_handler 是一个用于处理 Firebase Cloud Messaging (FCM) 消息的 Flutter 插件。本指南将展示如何在你的 Flutter 应用中集成和使用该插件。

开始使用

首先,你需要在你的 Flutter 项目中添加 bdaya_fcm_handler 依赖。打开 pubspec.yaml 文件,并在 dependencies 部分添加以下内容:

dependencies:
  flutter:
    sdk: flutter
  bdaya_fcm_handler: ^1.0.0 # 请确保使用最新版本

然后运行 flutter pub get 命令来安装依赖。

初始化插件

在应用启动时,你需要初始化 bdaya_fcm_handler 插件。通常在 main.dart 文件中的 main() 函数里进行初始化。

import 'package:flutter/material.dart';
import 'package:bdaya_fcm_handler/bdaya_fcm_handler.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await BdayaFcmHandler().initialize();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter FCM Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter FCM Demo'),
    );
  }
}

注册通知权限

在 Android 和 iOS 上,你可能需要请求用户授予通知权限。以下是在 AndroidManifest.xmlInfo.plist 中的配置示例。

Android (AndroidManifest.xml)

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.fcm_example">
    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        ...
        <service
            android:name=".MyFirebaseMessagingService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            </intent-filter>
        </service>
    </application>
</manifest>

iOS (Info.plist)

<key>UIBackgroundModes</key>
<array>
    <string>remote-notification</string>
</array>

处理消息

创建一个类继承自 FirebaseMessagingService 来处理消息。

import 'package:flutter/material.dart';
import 'package:bdaya_fcm_handler/bdaya_fcm_handler.dart';

class MyFirebaseMessagingService extends BdayaFcmHandler {
  @override
  void onMessage(Map<String, dynamic> message) {
    // 当应用处于前台时接收到消息
    print('Received message: $message');
  }

  @override
  void onBackgroundMessage(Map<String, dynamic> message) {
    // 当应用处于后台或关闭状态时接收到消息
    print('Received background message: $message');
  }

  @override
  void onLaunch(Map<String, dynamic> message) {
    // 当用户点击通知栏中的消息时,从关闭状态启动应用时调用
    print('Received launch message: $message');
  }

  @override
  void onResume(Map<String, dynamic> message) {
    // 当应用从后台恢复到前台时调用
    print('Received resume message: $message');
  }
}

在应用中注册服务

确保在 AndroidManifest.xml 中注册了上述服务类。

<service
    android:name=".MyFirebaseMessagingService"
    android:exported="false">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT"/>
    </intent-filter>
</service>

显示通知

你可以通过 showNotification 方法手动显示通知。

import 'package:flutter/material.dart';
import 'package:bdaya_fcm_handler/bdaya_fcm_handler.dart';

void showNotification() async {
  await BdayaFcmHandler().showNotification(
    title: 'Hello',
    body: 'This is a test notification',
    data: {'key': 'value'}, // 可选数据
  );
}

更多关于Flutter消息处理插件bdaya_fcm_handler的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter消息处理插件bdaya_fcm_handler的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何使用Flutter消息处理插件 bdaya_fcm_handler 的代码示例。这个插件通常用于处理Firebase Cloud Messaging (FCM) 的消息,包括数据消息和通知消息。

首先,确保你已经在 pubspec.yaml 文件中添加了 bdaya_fcm_handler 依赖:

dependencies:
  flutter:
    sdk: flutter
  bdaya_fcm_handler: ^最新版本号

然后,运行 flutter pub get 来获取依赖。

配置 Android 项目

android/app/src/main/AndroidManifest.xml 中,确保你有以下权限和服务声明:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"/>

<application
    ...>
    <service
        android:name=".MyFirebaseMessagingService"
        android:exported="true">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>
    ...
</application>

然后,创建一个 MyFirebaseMessagingService 类来处理 FCM 消息:

// android/app/src/main/java/com/your/package/MyFirebaseMessagingService.java
package com.your.package;

import androidx.annotation.NonNull;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.embedding.engine.FlutterEngineCache;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugins.GeneratedPluginRegistrant;

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String CHANNEL = "com.your.package/fcm";

    @Override
    public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
        // Handle incoming message
        String from = remoteMessage.getFrom();

        if (remoteMessage.getData().size() > 0) {
            // Handle data messages
            Map<String, String> data = remoteMessage.getData();
            sendDataMessage(data);
        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            // Handle notification messages
            String title = remoteMessage.getNotification().getTitle();
            String body = remoteMessage.getNotification().getBody();
            sendNotificationMessage(title, body);
        }
    }

    private void sendDataMessage(Map<String, String> data) {
        FlutterEngine flutterEngine = FlutterEngineCache
                .getInstance()
                .get("my_engine_id"); // Replace with your engine ID or use a cached engine

        if (flutterEngine != null) {
            MethodChannel channel = new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL);
            channel.invokeMethod("onMessageReceived", data);
        }
    }

    private void sendNotificationMessage(String title, String body) {
        // Optionally handle notifications here if needed
    }

    @Override
    public void onNewToken(@NonNull String token) {
        super.onNewToken(token);
        // Send token to your server
    }
}

配置 Flutter 项目

lib/main.dart 中,设置 bdaya_fcm_handler 插件并处理消息:

import 'package:flutter/material.dart';
import 'package:bdaya_fcm_handler/bdaya_fcm_handler.dart';

void main() {
  runApp(MyApp());

  // Initialize FCM handler
  BdayaFcmHandler.initialize(
    onMessageReceived: (Map<String, dynamic> message) {
      print("FCM Message Received: $message");
      // Handle the message here
    },
    onNewToken: (String token) {
      print("FCM Token: $token");
      // Send token to your server
    },
  );
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter FCM Handler Demo'),
        ),
        body: Center(
          child: Text('Check the console for FCM messages'),
        ),
      ),
    );
  }
}

注意事项

  1. 确保你已经在 Firebase 控制台中配置了你的应用,并启用了 Cloud Messaging。
  2. 在 Android 项目中,确保你添加了 google-services.json 文件。
  3. 在 iOS 项目中,你需要配置 FCM 的相关设置,这超出了本示例的范围,但 bdaya_fcm_handler 的文档会有详细说明。

这个示例展示了如何设置 bdaya_fcm_handler 来处理 FCM 消息,并在 Flutter 中处理这些消息。根据具体需求,你可能需要进一步定制消息处理逻辑。

回到顶部