Flutter统一推送服务插件unifiedpush_android的使用

UnifiedPush Flutter 连接器 #

UnifiedPush 是一套规范和工具,让用户可以选择如何分发推送通知。所有这些都是免费且开源的方式。

开始使用 #

请查看以下文档:

  1. https://unifiedpush.org/developers/flutter/
  2. 若要将 Firebase 作为回退方案,请参考:https://unifiedpush.org/developers/embedded_fcm/
  3. 一个示例应用可以在这里找到。

示例应用 #

下面是一个简单的 Flutter 应用示例,展示如何使用 UnifiedPush 插件。

设置项目 #

首先,在你的 Flutter 项目中添加 UnifiedPush 插件依赖:

dependencies:
  unifiedpush_android: ^0.0.1

初始化插件 #

在你的 main.dart 文件中初始化 UnifiedPush 插件:

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

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

class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: HomePage(), ); } }

class HomePage extends StatefulWidget { @override _HomePageState createState() => _HomePageState(); }

class _HomePageState extends State<HomePage> { @override void initState() { super.initState(); // 初始化 UnifiedPush 插件 UnifiedPushAndroid.init(); }

@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(‘UnifiedPush 示例’), ), body: Center( child: Text(‘点击按钮获取推送令牌’), ), floatingActionButton: FloatingActionButton( onPressed: () async { // 获取推送令牌 String token = await UnifiedPushAndroid.getPushToken(); print(‘推送令牌: $token’); }, tooltip: ‘获取令牌’, child: Icon(Icons.token), ), ); } }

接收推送通知 #

为了接收推送通知,你需要实现消息处理器:

class _HomePageState extends State<HomePage> {
  [@override](/user/override)
  void initState() {
    super.initState();
    // 初始化 UnifiedPush 插件
    UnifiedPushAndroid.init();
// 设置消息处理器
UnifiedPushAndroid.setOnMessageReceivedHandler((message) {
  print('收到消息: ${message.data}');
});

}

// 其他代码保持不变… }

测试 #

现在你可以运行你的 Flutter 应用,并点击浮动按钮获取推送令牌。你也可以发送测试推送通知来验证是否能正确接收。


更多关于Flutter统一推送服务插件unifiedpush_android的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

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


当然,以下是如何在Flutter项目中集成和使用unifiedpush_android插件的详细步骤,包括相关代码示例。

1. 添加依赖

首先,在你的Flutter项目的pubspec.yaml文件中添加unifiedpush_android依赖:

dependencies:
  flutter:
    sdk: flutter
  unifiedpush_android: ^最新版本号  # 请替换为插件的最新版本号

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

2. 配置Android项目

2.1 在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" />

    <!-- UnifiedPush需要的权限 -->
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <permission android:name="${applicationId}.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />
    <uses-permission android:name="${applicationId}.permission.C2D_MESSAGE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        
        <!-- 其他配置 -->

        <!-- 注册推送服务接收器 -->
        <receiver
            android:name=".MyFirebaseMessagingService"
            android:exported="true"
            android:permission="com.google.android.c2dm.permission.SEND">
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <category android:name="${applicationId}" />
            </intent-filter>
        </receiver>
    </application>
</manifest>

2.2 创建FirebaseMessagingService

android/app/src/main/kotlin/com/example/yourapp/(或java/com/example/yourapp/)目录下创建一个新的Kotlin/Java类,命名为MyFirebaseMessagingService,并继承FirebaseMessagingService

Kotlin示例

package com.example.yourapp

import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.os.Build
import android.os.Bundle
import androidx.core.app.NotificationCompat
import com.google.firebase.messaging.FirebaseMessagingService
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel

class MyFirebaseMessagingService : FirebaseMessagingService() {

    private val CHANNEL_ID = "your_channel_id"

    override fun onMessageReceived(remoteMessage: Bundle) {
        // 处理接收到的消息
        val flutterEngine = FlutterEngine(this)
        val channel = MethodChannel(flutterEngine, "com.example.yourapp/channel")
        channel.invokeMethod("onMessageReceived", remoteMessage.toString())

        // 如果消息包含通知数据,则发送通知
        if (remoteMessage.containsKey("notification")) {
            sendNotification(remoteMessage.getString("notification.title"), remoteMessage.getString("notification.body"))
        }
    }

    private fun sendNotification(title: String?, body: String?) {
        val intent = PendingIntent.getActivity(this, 0, Intent(this, MainActivity::class.java), PendingIntent.FLAG_IMMUTABLE)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                CHANNEL_ID,
                "Channel human readable title",
                NotificationManager.IMPORTANCE_DEFAULT
            ).apply {
                description = "Channel description"
            }
            val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            manager.createNotificationChannel(channel)
        }

        val notification = NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle(title)
            .setContentText(body)
            .setSmallIcon(R.drawable.ic_notification)
            .setContentIntent(intent)
            .setAutoCancel(true)
            .build()

        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.notify(0, notification)
    }

    override fun onNewToken(token: String) {
        super.onNewToken(token)
        // 将新的token发送到服务器
        val flutterEngine = FlutterEngine(this)
        val channel = MethodChannel(flutterEngine, "com.example.yourapp/channel")
        channel.invokeMethod("onNewToken", token)
    }
}

Java示例

package com.example.yourapp;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import androidx.core.app.NotificationCompat;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.MethodChannel;

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String CHANNEL_ID = "your_channel_id";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        // 处理接收到的消息
        FlutterEngine flutterEngine = new FlutterEngine(this);
        MethodChannel channel = new MethodChannel(flutterEngine, "com.example.yourapp/channel");
        channel.invokeMethod("onMessageReceived", remoteMessage.toString());

        // 如果消息包含通知数据,则发送通知
        if (remoteMessage.getNotification() != null) {
            sendNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());
        }
    }

    private void sendNotification(String title, String body) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                CHANNEL_ID,
                "Channel human readable title",
                NotificationManager.IMPORTANCE_DEFAULT
            );
            channel.setDescription("Channel description");
            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(channel);
        }

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle(title)
            .setContentText(body)
            .setSmallIcon(R.drawable.ic_notification)
            .setContentIntent(pendingIntent)
            .setAutoCancel(true);

        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        notificationManager.notify(0, builder.build());
    }

    @Override
    public void onNewToken(String token) {
        super.onNewToken(token);
        // 将新的token发送到服务器
        FlutterEngine flutterEngine = new FlutterEngine(this);
        MethodChannel channel = new MethodChannel(flutterEngine, "com.example.yourapp/channel");
        channel.invokeMethod("onNewToken", token);
    }
}

3. 在Flutter代码中配置和使用

在你的Flutter项目的Dart代码中,初始化unifiedpush_android插件并处理推送消息:

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

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('UnifiedPush Android Demo'),
        ),
        body: Center(
          child: MyHomePage(),
        ),
      ),
    );
  }
}

class MyHomePage extends
回到顶部