Flutter实时通信插件pusher_beams的使用

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

Flutter实时通信插件pusher_beams的使用

简介

Pusher Beams for Flutter 是一个用于Flutter应用程序的官方插件,它允许开发者轻松集成Pusher Beams的推送通知功能。该插件使用Pigeon来构建平台插件接口,并遵循Federated Plugin Architecture

  • 支持版本
    • Dart >= 2.12.x
    • Flutter >= 2.x.x

功能概览

以下是该插件在不同平台上的功能实现情况:

功能 iOS Android Web
addDeviceInterest
clearAllState
clearDeviceInterests
getDeviceInterests
onInterestChanges ⬜️
onMessageReceivedInTheForeground ⬜️
getInitialMessage ⬜️
removeDeviceInterest
setDeviceInterests
setUserId ⬜️
start
stop

平台支持

该插件支持Web、Android和iOS平台:

  • Web:Chrome (mobile & desktop),Safari (mobile & desktop),Edge (mobile & desktop),Firefox (mobile & desktop)
  • Mobile:iOS 10及以上,Android 4.4及以上(>= SDK Version 19)

示例代码

下面是一个完整的示例代码,演示如何在Flutter项目中使用pusher_beams插件。

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:pusher_beams/pusher_beams.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  await PusherBeams.instance.start(
      'your-instance-id'); // Supply your own instanceId

  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Pusher Beams Flutter Example',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: const MyHomePage(title: 'Pusher Beams Flutter Example'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  void initState() {
    super.initState();
    initPusherBeams();
  }

  Future<void> getSecure() async {
    final BeamsAuthProvider provider = BeamsAuthProvider()
      ..authUrl = 'https://some-auth-url.com/secure'
      ..headers = {'Content-Type': 'application/json'}
      ..queryParams = {'page': '1'}
      ..credentials = 'omit';

    await PusherBeams.instance.setUserId(
        'user-id',
        provider,
        (error) => {
              if (error != null) {print(error)}

              // Success! Do something...
            });
  }

  Future<void> initPusherBeams() async {
    print(await PusherBeams.instance.getDeviceInterests());

    if (!kIsWeb) {
      await PusherBeams.instance.onInterestChanges((interests) => {print('Interests: $interests')});
      await PusherBeams.instance.onMessageReceivedInTheForeground(_onMessageReceivedInTheForeground);
    }
    await _checkForInitialMessage();
  }

  Future<void> _checkForInitialMessage() async {
    final initialMessage = await PusherBeams.instance.getInitialMessage();
    if (initialMessage != null) {
      _showAlert('Initial Message Is:', initialMessage.toString());
    }
  }

  void _onMessageReceivedInTheForeground(Map<Object?, Object?> data) {
    _showAlert(data["title"].toString(), data["body"].toString());
  }

  void _showAlert(String title, String message) {
    AlertDialog alert = AlertDialog(
        title: Text(title), content: Text(message), actions: const []);

    showDialog(
      context: context,
      builder: (BuildContext context) {
        return alert;
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Plugin example app'),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          OutlinedButton(
              onPressed: () async {
                await PusherBeams.instance.addDeviceInterest('bananas');
              },
              child: const Text('I like bananas')),
          OutlinedButton(
              onPressed: () async {
                await PusherBeams.instance.removeDeviceInterest('bananas');
              },
              child: const Text("I don't like banana anymore")),
          OutlinedButton(
              onPressed: () async {
                await PusherBeams.instance.addDeviceInterest('apples');
              },
              child: const Text('I like apples')),
          OutlinedButton(
              onPressed: () async {
                await PusherBeams.instance.addDeviceInterest('garlic');
              },
              child: const Text('I like garlic')),
          OutlinedButton(onPressed: getSecure, child: const Text('Get Secure')),
          OutlinedButton(
              onPressed: () async {
                await PusherBeams.instance.clearDeviceInterests();
              },
              child: const Text('Clear my interests'))
        ],
      ),
    );
  }
}

安装与初始化

  1. 添加依赖pubspec.yaml文件中添加pusher_beams依赖:

    dependencies:
      pusher_beams: ^1.0.1
    

    或者通过命令行添加:

    flutter pub add pusher_beams
    
  2. 初始化main函数中初始化Pusher Beams:

    void main() async {
      WidgetsFlutterBinding.ensureInitialized();
      await PusherBeams.instance.start('YOUR INSTANCE ID');
      runApp(MyApp());
    }
    
  3. 平台特定配置

    • Android

      • 添加以下内容到android/build.gradle文件中的dependencies部分:
        classpath 'com.google.gms:google-services:4.2.0'
        
      • android/app/build.gradle文件末尾添加:
        apply plugin: 'com.google.gms.google-services'
        
    • Web

      • 创建web/service-worker.js文件并添加以下内容:
        importScripts("https://js.pusher.com/beams/service-worker.js");
        
      • web/index.html文件的<body>标签开头添加以下脚本:
        <script src="https://js.pusher.com/beams/1.0/push-notifications-cdn.js"></script>
        

注意事项

  • Prerequisites:确保你已经有一个Pusher Beams账户并获取了instanceId
  • Android Additional:需要Firebase账号和google-services.json文件。
  • iOS Additional:启用相关能力并配置APNs。

通过以上步骤,你可以顺利地在Flutter应用中集成Pusher Beams进行实时通信和推送通知。


更多关于Flutter实时通信插件pusher_beams的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter实时通信插件pusher_beams的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何在Flutter中使用pusher_beams插件来实现实时通信的示例代码。pusher_beams是一个用于Flutter的插件,可以让你轻松地集成Pusher Beams进行实时消息推送。

前提条件

  1. 确保你已经安装了Flutter和Dart开发环境。
  2. 确保你已经在Firebase或其他推送服务中配置了你的应用以接收推送通知。
  3. 确保你已经在Pusher Beams控制台中创建了应用并获取了必要的密钥。

安装pusher_beams插件

在你的Flutter项目的根目录下,打开pubspec.yaml文件并添加以下依赖:

dependencies:
  flutter:
    sdk: flutter
  pusher_beams: ^x.y.z  # 替换为最新版本号

然后在终端中运行以下命令来安装依赖:

flutter pub get

配置Android和iOS推送权限

Android

android/app/src/main/AndroidManifest.xml中添加必要的权限和接收器:

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

<application
    ...>
    <receiver android:name=".MyFirebaseMessagingService" android:exported="true">
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
        </intent-filter>
    </receiver>
    ...
</application>

创建MyFirebaseMessagingService.kt(Kotlin)或MyFirebaseMessagingService.java(Java)来处理Firebase消息:

// MyFirebaseMessagingService.kt
package com.example.yourapp

import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import android.util.Log

class MyFirebaseMessagingService: FirebaseMessagingService() {
    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        // 处理接收到的消息
        Log.d("FirebaseMessage", "Message received: ${remoteMessage.data}")
    }
}

iOS

ios/Runner/AppDelegate.swift中添加Firebase消息处理:

import UIKit
import Flutter
import Firebase
import FirebaseMessaging

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

// UNUserNotificationCenterDelegate
extension AppDelegate: UNUserNotificationCenterDelegate {
  func userNotificationCenter(_ center: UNUserNotificationCenter,
                              willPresent notification: UNNotification,
                              withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    completionHandler([.alert, .sound])
  }

  func userNotificationCenter(_ center: UNUserNotificationCenter,
                              didReceive response: UNNotificationResponse,
                              withCompletionHandler completionHandler: @escaping () -> Void) {
    completionHandler()
  }
}

// MessagingDelegate
extension AppDelegate: MessagingDelegate {
  func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
    print("Received data message: \(remoteMessage.appData)")
  }
}

使用pusher_beams进行实时通信

在你的Flutter应用中,初始化并使用pusher_beams

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Pusher Beams Example'),
        ),
        body: Center(
          child: BeamsExample(),
        ),
      ),
    );
  }
}

class BeamsExample extends StatefulWidget {
  @override
  _BeamsExampleState createState() => _BeamsExampleState();
}

class _BeamsExampleState extends State<BeamsExample> {
  late BeamsClient beamsClient;

  @override
  void initState() {
    super.initState();

    // 替换为你的Pusher Beams密钥
    const instanceId = 'your-instance-id';
    const secretKey = 'your-secret-key';

    beamsClient = BeamsClient(
      instanceId: instanceId,
      secretKey: secretKey,
      environment: 'production', // 或 'development'
    );

    // 订阅一个兴趣
    beamsClient.subscribeToInterests(['news', 'updates']).then((_) {
      print('Subscribed to interests');
    });

    // 处理接收到的推送通知
    beamsClient.onMessageReceived = (message) {
      print('Received message: ${message.data}');
      // 在这里处理推送通知,例如显示通知
    };
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Text('Check your console for logs'),
        ElevatedButton(
          onPressed: () {
            // 发送一个测试消息
            beamsClient.publishToInterest('news', {
              'message': 'Hello, this is a test message!',
            }).then((_) {
              print('Message sent to news interest');
            });
          },
          child: Text('Send Test Message'),
        ),
      ],
    );
  }
}

注意事项

  1. 确保你已经替换了your-instance-idyour-secret-key为你的Pusher Beams实例ID和密钥。
  2. 根据你的应用需求,调整订阅的兴趣和发送的消息内容。
  3. 在实际项目中,请确保妥善保管你的密钥,不要将其硬编码在客户端代码中。

这个示例展示了如何初始化pusher_beams客户端,订阅兴趣,并处理接收到的推送通知。你可以根据需要进行扩展和自定义。

回到顶部