Flutter消息推送插件mpush的使用

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

Flutter消息推送插件mpush的使用

安装

首先,你需要在 pubspec.yaml 文件中添加 mpush 插件,并通过 flutter pub get 命令安装。

dependencies:
  mpush: ^1.0.7
flutter pub get

设置

Android
  1. 在 Firebase 控制台中添加 Android 应用

    • 打开 Firebase 控制台并添加一个 Android 应用。
    • 下载生成的 google-services.json 文件并将其放置在 android/app 目录下。
  2. 修改 build.gradle 文件

    • project/android/build.gradle 中添加以下内容:

      dependencies {
          // 示例现有依赖项
          classpath 'com.android.tools.build:gradle:3.5.3'
          // 添加 Google Services 依赖项
          classpath 'com.google.gms:google-services:4.3.2'
      }
      
  3. app/build.gradle 中应用插件

    • project/android/app/build.gradle 中添加以下内容:

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

注意:如果未完成此步骤,可能会收到错误信息:

java.lang.IllegalStateException:
Default FirebaseApp is not initialized in this process [package name].
Make sure to call FirebaseApp.initializeApp(Context) first.
iOS
  1. 设置 iOS 项目以启用推送通知
    • 打开 Xcode,打开你的项目(如 Runner.xcworkspace)。
    • 在 Signing & Capabilities 菜单中点击 + Capability 按钮,选择 “Push Notifications”。

注意:你必须使用为该应用创建的配置文件,否则无法测试和接收推送通知。

  1. 修改 AppDelegate 类

    • 打开 AppDelegate.swift 文件,在 didFinishLaunchingWithOptions 函数中添加以下代码:

      UNUserNotificationCenter.current().delegate = self
      

    AppDelegate 应该如下所示:

    import UIKit
    import Flutter
    
    @UIApplicationMain
    @objc class AppDelegate: FlutterAppDelegate {
        override func application(
            _ application: UIApplication,
            didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
        ) -> Bool {
            UNUserNotificationCenter.current().delegate = self
            GeneratedPluginRegistrant.register(with: self)
            return super.application(application, didFinishLaunchingWithOptions: launchOptions)
        }
    }
    

使用

  1. 设置 API Token

    • 首先设置 apiToken

      MPush.apiToken = 'YOUR_API_TOKEN';
      
  2. 配置 MPush

    • 配置回调函数和 Android 通知设置:

      MPush.configure(
        onNotificationArrival: (notification) {
          print("Notification arrived: $notification");
        },
        onNotificationTap: (notification) {
          print("Notification tapped: $notification");
        },
        androidNotificationsSettings: MPAndroidNotificationsSettings(
          channelId: 'mpush_example',
          channelName: 'MPush Notifications',
          channelDescription: 'Push notification channel', 
          icon: '@mipmap/icon_notif',
        ),
      );
      

注意:channelIdchannelNamechannelDescription 是可选参数。icon 参数应指向 res 文件夹中的 mipmap 图标,例如 @mipmap/icon_notif

请求令牌

  1. 设置回调函数
    • 设置一个回调函数来处理正确接收的通知令牌:

      MPush.onToken = (token) {
        print("Token retrieved: $token");
      };
      

2 请求令牌

  • 使用 requestToken 方法请求令牌:

    MPush.requestToken();
    

注册到主题

  1. 注册设备
    • 注册设备并注册到主题:

      await MPush.registerDevice(token).catchError((error) => print(error));
      await MPush.registerToTopic(const MPTopic(code: 'Topic')).catchError((error) => print(error));
      print('Registered');
      

注意:MPTopic 类有三个属性:

  • code: 主题 ID
  • title: 可选的主题标题
  • single: 如果这个主题代表单个设备或一组设备,默认为 false

启动通知

  1. 获取启动通知数据
    • 如果应用程序是从通知启动,则可以获取通知数据:

      Map<String, dynamic>? launchNotification = await MPush.launchNotification();
      print(launchNotification);
      

示例代码

import 'package:flutter/material.dart';
import 'package:mpush/mp_android_notifications_settings.dart';
import 'package:mpush/mp_topic.dart';
import 'package:mpush/mpush.dart';

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

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  [@override](/user/override)
  void initState() {
    _initMPush();
    super.initState();
  }

  _initMPush() async {
    MPush.apiToken = 'YOUR_API_KEY';
    MPush.onToken = (token) async {
      debugPrint("Token received $token");
      await MPush.registerDevice(token).catchError(
        (error) => debugPrint(error),
      );
      await MPush.registerToTopic(const MPTopic(code: 'Topic')).catchError(
        (error) => debugPrint(error),
      );
      debugPrint('Registered');
    };

    MPush.configure(
      onNotificationArrival: (notification) {
        debugPrint("Notification arrived: $notification");
      },
      onNotificationTap: (notification) {
        debugPrint("Notification tapped: $notification");
      },
      androidNotificationsSettings: const MPAndroidNotificationsSettings(
        channelId: 'mpush_example',
        channelName: 'mpush',
        channelDescription: 'mpush',
        icon: '@mipmap/icon_notif',
      ),
    );

    Map<String, dynamic>? launchNotification = await MPush.launchNotification();
    debugPrint(launchNotification?.toString());
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('MPush Example'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ElevatedButton(
                onPressed: () => MPush.requestToken(),
                child: const Text('Request token'),
              ),
              const SizedBox(height: 10),
              ElevatedButton(
                onPressed: () => _setCustomReplacements(),
                child: const Text('Set custom replacements'),
              ),
              const SizedBox(height: 10),
              ElevatedButton(
                onPressed: () => _removeCustomReplacements(),
                child: const Text('Remove custom replacements'),
              ),
              const SizedBox(height: 10),
              ElevatedButton(
                onPressed: () => _printCustomReplacements(),
                child: const Text('Print custom replacements'),
              ),
              const SizedBox(height: 10),
              ElevatedButton(
                onPressed: () => _printNotificationPermissionStatus(),
                child: const Text('Print notification permission status'),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Future<void> _setCustomReplacements() async {
    await MPush.addCustomReplacements(
      customData: {'Test Key': 'Test Value'},
    );
  }

  Future<void> _removeCustomReplacements() async {
    await MPush.removeCustomReplacements();
  }

  Future<void> _printCustomReplacements() async {
    Map<String, String>? customReplacements =
        await MPush.getCustomReplacements();
    debugPrint(customReplacements?.toString());
  }

  Future<void> _printNotificationPermissionStatus() async {
    MPushNotificationPermission? permissionStatus =
        await MPush.notificationPermission();
    debugPrint(permissionStatus.toString());
  }
}

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

1 回复

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


在Flutter中集成和使用消息推送插件mpush,可以遵循以下步骤进行配置和实现。以下是一个基本的代码案例,展示了如何在Flutter项目中集成mpush并实现消息推送功能。

1. 添加依赖

首先,在你的pubspec.yaml文件中添加mpush插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  mpush: ^最新版本号  # 请替换为实际可用的最新版本号

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

2. 配置Android和iOS

Android配置

android/app/src/main/AndroidManifest.xml中添加必要的权限和配置:

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

    <!-- 添加必要的权限 -->
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.WAKE_LOCK"/>

    <!-- 配置MPush的Service和Receiver -->
    <application
        ...>
        
        <!-- MPush Service -->
        <service
            android:name="com.alibaba.mobile.push.service.MPushService"
            android:exported="false"
            android:process=":mpush"
            android:permission="android.permission.BIND_JOB_SERVICE">
            <intent-filter>
                <action android:name="com.alibaba.mobile.push.service.MPushService" />
            </intent-filter>
        </service>

        <!-- MPush Receiver -->
        <receiver
            android:name="com.alibaba.mobile.push.receivers.MPushReceiver"
            android:exported="true"
            android:permission="android.permission.BROADCAST_STICKY">
            <intent-filter>
                <action android:name="com.alibaba.mobile.push.ACTION_MESSAGE" />
                <action android:name="com.alibaba.mobile.push.ACTION_NOTIFICATION_CLICKED" />
                <action android:name="com.alibaba.mobile.push.ACTION_CONNECTION_CHANGED" />
                <category android:name="com.example.yourapp" />
            </intent-filter>
        </receiver>
        
        <!-- 其他配置 -->
        ...
    </application>
</manifest>

iOS配置

ios/Runner/Info.plist中添加必要的配置(具体配置根据MPush的iOS SDK文档进行):

<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>your_app_scheme</string> <!-- 替换为你的App Scheme -->
        </array>
    </dict>
</array>

确保在Xcode中配置了必要的后台模式和推送通知权限。

3. 初始化MPush

在你的Flutter应用的入口文件(通常是main.dart)中初始化MPush:

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

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化MPush
  MPush.init(
    appId: 'your_app_id', // 替换为你的MPush App ID
    appSecret: 'your_app_secret', // 替换为你的MPush App Secret
    appKey: 'your_app_key', // 替换为你的MPush App Key
    channel: 'flutter', // 渠道标识
  ).then((result) {
    if (result) {
      print('MPush initialized successfully.');
    } else {
      print('MPush initialization failed.');
    }
  }).catchError((error) {
    print('MPush initialization error: $error');
  });

  runApp(MyApp());
}

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

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter MPush Demo'),
      ),
      body: Center(
        child: Text('Check the console for MPush initialization status.'),
      ),
    );
  }
}

4. 监听消息推送

为了处理接收到的消息推送,你可以使用MPush提供的监听方法:

void initState() {
  super.initState();

  // 监听消息到达事件
  MPush.onMessageReceived.listen((message) {
    print('Received message: ${message.toMap()}');
  });

  // 监听通知点击事件
  MPush.onNotificationClicked.listen((notification) {
    print('Notification clicked: ${notification.toMap()}');
  });
}

将上述监听代码添加到你的页面或组件的initState方法中。

总结

以上代码案例展示了如何在Flutter项目中集成mpush插件并实现基本的消息推送功能。请确保根据MPush的官方文档和SDK更新调整代码和配置。

回到顶部