Flutter推送通知插件pushy_flutter的使用

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

Flutter推送通知插件pushy_flutter的使用

pushy-flutter 是官方为Flutter应用程序提供的Pushy SDK。Pushy是最可靠的推送通知网关,非常适合实时、关键任务的应用程序。

使用方法

以下是使用pushy-flutter插件的完整示例demo,包括如何集成和配置推送通知功能。

1. 添加依赖

首先,在pubspec.yaml文件中添加pushy_flutter依赖:

dependencies:
  flutter:
    sdk: flutter
  pushy_flutter: ^latest_version  # 请替换为最新版本

2. 初始化Pushy

main.dart文件中,添加以下代码来初始化Pushy并注册设备以接收推送通知。

import 'package:flutter/material.dart';
import 'dart:io' show Platform;
import 'dart:async';

import 'package:pushy_flutter/pushy_flutter.dart';

void main() => runApp(Main());

// 背景通知监听器
@pragma('vm:entry-point')
void backgroundNotificationListener(Map<String, dynamic> data) {
  // 打印通知负载数据
  print('Received notification: $data');

  // 通知标题
  String notificationTitle = 'MyApp';

  // 尝试从负载中提取 "message" 属性: {"message":"Hello World!"}
  String notificationText = data['message'] ?? 'Hello World!';

  // Android: 显示系统通知
  // iOS: 显示警告对话框
  Pushy.notify(notificationTitle, notificationText, data);

  // 清除iOS应用图标上的徽章数量
  Pushy.clearBadge();
}

class Main extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Pushy',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        // 光明主题,深色操作栏
        brightness: Brightness.light,
        primaryColor: Colors.grey[900],
        secondaryHeaderColor: Colors.redAccent,
      ),
      home: PushyDemo(),
    );
  }
}

class PushyDemo extends StatefulWidget {
  @override
  _PushyDemoState createState() => _PushyDemoState();
}

class _PushyDemoState extends State<PushyDemo> {
  String _deviceToken = 'Loading...';
  String _instruction = '(please wait)';

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

  // 平台消息是异步的,因此我们在异步方法中初始化
  Future<void> initPlatformState() async {
    // 启动Pushy服务
    Pushy.listen();

    // 设置Pushy应用ID(Web Push所需)
    Pushy.setAppId('550ee57c5b5d72117f51e801');  // 请替换为您的应用ID

    try {
      // 注册设备以接收推送通知
      String deviceToken = await Pushy.register();

      // 打印token到控制台/日志
      print('Device token: $deviceToken');

      // 将token发送到您的后端服务器
      // ...

      // 更新UI显示token
      setState(() {
        _deviceToken = deviceToken;
        _instruction =
            isAndroid() ? '(copy from logcat)' : '(copy from console)';
      });
    } catch (error) {
      // 打印错误信息
      print('Error: ${error.toString()}');

      // 显示错误
      setState(() {
        _deviceToken = 'Registration failed';
        _instruction = '(restart app to try again)';
      });
    }

    // 启用应用内通知横幅(iOS 10+)
    Pushy.toggleInAppBanner(false);

    // 监听接收到的推送通知
    Pushy.setNotificationListener(backgroundNotificationListener);

    // 监听点击的推送通知
    Pushy.setNotificationClickListener((Map<String, dynamic> data) {
      // 打印通知负载数据
      print('Notification clicked: $data');

      // 提取消息内容
      String message = data['message'] ?? 'Hello World!';

      // 显示一个带有消息内容的警告对话框
      showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
              title: Text('Notification clicked'),
              content: Text(message),
              actions: [
                ElevatedButton(
                  child: Text('OK'),
                  onPressed: () {
                    Navigator.of(context, rootNavigator: true).pop('dialog');
                  },
                )
              ]);
        },
      );

      // 清除iOS应用图标上的徽章数量
      Pushy.clearBadge();
    });
  }

  @override
  Widget build(BuildContext context) {
    // 示例应用UI
    return Scaffold(
      appBar: AppBar(
        title: const Text('Pushy'),
        foregroundColor: Colors.white,
        backgroundColor: Colors.grey[900]
      ),
      body: Builder(
        builder: (context) => Center(
            child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
              Image.asset('assets/ic_logo.png', width: 90),  // 请确保您有此图片资源
              Padding(
                padding: const EdgeInsets.all(10),
                child: Text(_deviceToken,
                    style: TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: 18,
                        color: Colors.grey[700])),
              ),
              Text(_instruction,
                  style: TextStyle(fontSize: 13, color: Colors.grey[600])),
            ])),
      ),
    );
  }
}

bool isAndroid() {
  try {
    // 返回设备是否运行在Android上
    return Platform.isAndroid;
  } catch (e) {
    // 如果失败,我们是在Web上
    return false;
  }
}

3. 配置推送通知

Android配置

android/app/build.gradle文件中,确保添加了以下依赖项:

dependencies {
    implementation 'me.pushy:sdk:1.0.48'
}

AndroidManifest.xml文件中,添加以下权限和广播接收器:

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

<application>
    <!-- ... -->
    <receiver
        android:name="me.pushy.sdk.receivers.PushReceiver"
        android:exported="true">
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            <category android:name="${applicationId}" />
        </intent-filter>
    </receiver>
</application>

iOS配置

ios/Runner/AppDelegate.swift文件中,添加以下代码:

import UIKit
import Flutter
import Pushy

[@UIApplicationMain](/user/UIApplicationMain)
[@objc](/user/objc) class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    GeneratedPluginRegistrant.register(with: self)

    // Start the Pushy SDK
    Pushy.start(onSuccess: { deviceToken in
        print("Pushy device token: \(deviceToken)")
    }, onFailure: { error in
        print("Failed to register for push notifications: \(error.localizedDescription)")
    })

    // Request push notification permissions on iOS 10+
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
        if let error = error {
            print("Failed to request push notification permissions: \(error.localizedDescription)")
        }
    }

    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }

  override func application(
    _ application: UIApplication,
    didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data
  ) {
    // Forward APNs token to Pushy
    Pushy.setApnsToken(deviceToken)
  }

  override func application(
    _ application: UIApplication,
    didFailToRegisterForRemoteNotificationsWithError error: Error
  ) {
    print("Failed to register for remote notifications: \(error.localizedDescription)")
  }

  override func userNotificationCenter(
    _ center: UNUserNotificationCenter,
    willPresent notification: UNNotification,
    withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void
  ) {
    // Display an alert when a push notification is received in the foreground
    completionHandler([.alert, .badge, .sound])
  }
}

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

1 回复

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


当然,下面是一个关于如何在Flutter项目中使用pushy_flutter插件来实现推送通知的示例代码。pushy_flutter是一个用于处理推送通知的插件,特别适用于需要可靠推送和实时通信的应用。

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

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

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

1. 配置Android项目

修改android/app/src/main/AndroidManifest.xml

确保你已经在AndroidManifest.xml中添加了必要的权限和Pushy的配置:

<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.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
    <uses-permission android:name="android.permission.VIBRATE"/>

    <application
        ... >
        
        <!-- Pushy Service Declaration -->
        <service
            android:name="com.pushy.sdk.PushyService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.pushy.RECEIVE" />
            </intent-filter>
        </service>

        <receiver
            android:name="com.pushy.sdk.PushyBroadcastReceiver"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <category android:name="com.example.yourapp" />
            </intent-filter>
        </receiver>

        <!-- Optional: If you want to handle notifications when the app is closed -->
        <receiver
            android:name="com.pushy.sdk.PushyNotificationReceiver"
            android:exported="true">
            <intent-filter>
                <action android:name="com.pushy.NOTIFICATION_CLICK" />
            </intent-filter>
        </receiver>
    </application>
</manifest>

修改android/app/build.gradle

确保在android/app/build.gradle文件中应用了Pushy的Gradle插件:

android {
    ...
    defaultConfig {
        ...
        applicationId "com.example.yourapp"  // 确保与你的包名一致
        minSdkVersion 21
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        // Pushy-specific configuration
        manifestPlaceholders = [
            pushyApiKey: "YOUR_PUSHY_API_KEY_HERE"  // 替换为你的Pushy API Key
        ]
    }
    ...
}

dependencies {
    ...
    implementation 'com.pushy:pushy-android-sdk:x.y.z'  // 替换为最新版本号
}

2. 配置iOS项目

更新Info.plist

ios/Runner/Info.plist中,添加Pushy的配置:

<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>com.pushy.YOUR_PUSHY_APP_ID</string>  // 替换为你的Pushy App ID
        </array>
    </dict>
</array>

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

<key>UIApplicationExitsOnSuspend</key>
<true/>

AppDelegate.swift中配置Pushy

import UIKit
import Flutter
import Pushy

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    GeneratedPluginRegistrant.register(with: self)
    
    // Initialize Pushy
    Pushy.start(withApiKey: "YOUR_PUSHY_API_KEY_HERE")  // 替换为你的Pushy API Key
    
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
  
  override func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    Pushy.handleRemoteNotification(userInfo, completion: completionHandler)
  }
  
  override func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    Pushy.registerDeviceToken(deviceToken)
  }
}

3. 在Flutter中使用Pushy

在你的Dart代码中,你可以使用pushy_flutter插件来处理推送通知。以下是一个简单的示例:

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

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

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

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

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

    // Initialize Pushy
    PushyFlutter.start(apiKey: "YOUR_PUSHY_API_KEY_HERE");  // 替换为你的Pushy API Key

    // Listen for push notifications
    PushyFlutter.notificationStream.listen((notification) {
      print("Received notification: $notification");
      // 处理收到的通知
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Pushy Flutter Demo'),
      ),
      body: Center(
        child: Text('Waiting for notifications...'),
      ),
    );
  }
}

以上代码展示了如何在Flutter项目中配置和使用pushy_flutter插件来处理推送通知。记得替换YOUR_PUSHY_API_KEY_HEREYOUR_PUSHY_APP_ID为你的实际Pushy API Key和App ID。这样,你就可以在Flutter应用中接收和处理推送通知了。

回到顶部