Flutter Azure通知服务插件azure_notify_hub的使用
Flutter Azure通知服务插件azure_notify_hub的使用
如果您正在寻找一种在多平台应用中发送移动推送通知的方法,Microsoft Azure Notification Hubs 提供了一个强大的解决方案。此插件允许您从任何后端(云端或本地)向任何移动平台发送推送通知。
开始使用
如果您是第一次接触 Notification Hubs,请按照教程开始推送通知到您的应用。
配置
Android集成
要将插件集成到您的Android应用中,请遵循以下步骤:
-
使用Firebase控制台为您的项目添加一个Android应用。按照助手操作,下载生成的
google-services.json
文件,并将其放置在android/app
目录下。<meta-data android:name="NotificationHubName" android:value="" /> <meta-data android:name="NotificationHubConnectionString" android:value="Endpoint=..." />
-
在
android/app/src/main/AndroidManifest.xml
中添加权限。<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.GET_ACCOUNTS"/> <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
iOS集成
要将插件集成到您的iOS应用中,请遵循以下步骤:
-
按照Azure文档生成Apple所需的证书,以便接收推送通知。
-
按照Azure文档注册您的应用以接收推送通知。
-
在Xcode中,选择Runner,然后在Capabilities标签页中启用推送通知和后台模式,并启用后台获取和远程通知。
-
在
Info.plist
中添加通知中心名称和连接字符串。NotificationHubName NotificationHubConnectionString
Dart/Flutter集成
从您的Dart代码中,您需要导入插件并实例化它:
import 'package:azure_notify_hub/azure_notify_hub.dart';
final AzureNotificationhubsFlutter _anh = AzureNotificationhubsFlutter();
请求权限由插件管理,在iOS上请求时会弹出权限对话框。之后,您可以监听通知并编写处理额外数据负载的逻辑。
_anh.configure(
onLaunch: (Map<String, dynamic> notification) async {
print('onLaunch: $notification');
},
onResume: (Map<String, dynamic> notification) async {
print('onResume: $notification');
},
onMessage: (Map<String, dynamic> notification) async {
print('onMessage: $notification');
},
onToken: (Map<String, dynamic> notification) async {
print('onToken: $notification');
},
);
负载
iOS和Android具有不同的负载。整个负载将根据情况发送到Dart的onResume
、onLaunch
和onMessage
。
iOS负载
{
aps: {
alert: {
title: "Hello world",
body: "by chu"
},
badge: 1
},
<!-- extra data payload -->
...
}
Android负载
{
"data": {
"title": "Hello world",
"body": "to you",
<!-- extra data payload -->
...
}
}
订阅标签
每个设备会自动订阅device:deviceID
。对于Android,deviceId
是一个SHA1散列的Firebase Cloud Messaging令牌,因为它超过了标签长度限制。
手动订阅标签目前不受支持,因为这不是我的优先事项。欢迎您提交PR。
为什么我在Android上收到静默通知?
这是功能,而不是错误。在Android上,有时用户不会收到任何头部通知,而这些通知会静默地出现在通知抽屉中。这是因为头部通知有一个内置的速率限制——如果用户将头部通知向上滑动(放回通知栏)或将头部通知向侧面滑动(取消),系统将在一段时间内阻止进一步的头部通知。
下载源代码
要通过git获取我们的包装器的源代码,请执行以下命令:
git clone https://github.com/GhostBman/azure_notify_hub.git
贡献
如果您有任何疑问,请随时提问,或者提交问题或拉取请求。最坏的情况是您会被礼貌地要求更改某些内容。我们欢迎所有友好的贡献。
示例代码
import 'package:azure_notify_hub/azure_notify_hub.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatefulWidget {
const MyApp({super.key});
[@override](/user/override)
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
AzureNotificationhubsFlutter? _anh;
[@override](/user/override)
void initState() {
super.initState();
_anh?.configure(
onMessage: (Map<String, dynamic> message) async {
if (kDebugMode) {
print("onMessage: $message");
}
showDialog(
context: context,
builder: (context) => AlertDialog(
content: ListTile(
title: Text(message['notification']['title']),
subtitle: Text(message['notification']['body']),
),
actions: [
TextButton(
child: const Text('Ok'),
onPressed: () => Navigator.of(context).pop(),
),
],
),
);
},
onResume: (Map<String, dynamic> message) async {
if (kDebugMode) {
print("onResume: $message");
}
},
onLaunch: (Map<String, dynamic> message) async {
if (kDebugMode) {
print("onLaunch: $message");
}
},
onToken: (String token) async {
if (kDebugMode) {
print("onToken: $token");
}
},
);
}
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: const Center(
child: Text('Running'),
),
),
);
}
}
更多关于Flutter Azure通知服务插件azure_notify_hub的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter Azure通知服务插件azure_notify_hub的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是一个关于如何在Flutter项目中使用azure_notify_hub
插件来集成Azure通知服务的代码案例。这个插件允许你通过Azure Notification Hubs发送和接收推送通知。
步骤1:添加依赖
首先,在你的Flutter项目的pubspec.yaml
文件中添加azure_notify_hub
依赖:
dependencies:
flutter:
sdk: flutter
azure_notify_hub: ^最新版本号 # 请替换为实际可用的最新版本号
步骤2:安装依赖
在终端中运行以下命令来安装依赖:
flutter pub get
步骤3:配置Android
在android/app/src/main/AndroidManifest.xml
文件中添加必要的权限和Azure Notification Hubs的配置:
<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="com.google.android.c2dm.permission.RECEIVE"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<application
... >
<!-- 添加Notification Hubs的Service和Receiver -->
<service
android:name="com.microsoft.windowsazure.notifications.NotificationsIntentService"
android:exported="false" />
<receiver android:name="com.microsoft.windowsazure.notifications.NotificationsBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="com.example.yourapp" />
</intent-filter>
</receiver>
<!-- 注册Notification Hubs -->
<meta-data
android:name="com.microsoft.windowsazure.notifications.NotificationHub"
android:value="Your-Notification-Hub-Connection-String-With-Full-Access" />
</application>
</manifest>
请将Your-Notification-Hub-Connection-String-With-Full-Access
替换为你的Azure Notification Hub的连接字符串。
步骤4:配置iOS
对于iOS,你需要在ios/Runner/AppDelegate.swift
和Info.plist
中进行配置。
在AppDelegate.swift
中
import UIKit
import Flutter
import UserNotifications
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GeneratedPluginRegistrant.register(with: self)
// 注册通知
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
(granted, error) in
if granted {
DispatchQueue.main.async {
application.registerForRemoteNotifications()
}
}
}
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
override func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
// 处理收到的远程通知
completionHandler(.newData)
}
}
在Info.plist
中
添加以下键和值:
<key>FirebaseAppDelegateProxyEnabled</key>
<false/>
<key>UIBackgroundModes</key>
<array>
<string>remote-notification</string>
</array>
步骤5:在Flutter中使用插件
在你的Flutter代码中,你可以这样使用azure_notify_hub
插件:
import 'package:flutter/material.dart';
import 'package:azure_notify_hub/azure_notify_hub.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Azure Notify Hub Example'),
),
body: Center(
child: NotificationHubExample(),
),
),
);
}
}
class NotificationHubExample extends StatefulWidget {
@override
_NotificationHubExampleState createState() => _NotificationHubExampleState();
}
class _NotificationHubExampleState extends State<NotificationHubExample> {
String notificationMessage = '';
@override
void initState() {
super.initState();
_initNotificationHub();
}
void _initNotificationHub() async {
// 替换为你的Notification Hub名称和连接字符串
final String hubName = 'Your-Hub-Name';
final String connectionString = 'Your-Connection-String-Listen';
// 初始化Notification Hub
await AzureNotifyHub.init(hubName, connectionString);
// 注册设备
AzureNotifyHub.registerDevice().then((registrationId) {
print('Device registered with ID: $registrationId');
// 你可以将registrationId发送到你的后端服务器,以便后端服务器可以向这个设备发送通知
});
// 监听通知
AzureNotifyHub.notificationListener = (message) {
setState(() {
notificationMessage = message;
});
};
}
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Notification Message: $notificationMessage'),
ElevatedButton(
onPressed: () {
// 发送测试通知(这通常是由后端服务器完成的)
// 这里只是一个示例,实际应用中你应该在后端调用Azure Notification Hub的API来发送通知
AzureNotifyHub.sendTestNotification('Hello from Flutter!');
},
child: Text('Send Test Notification'),
),
],
);
}
}
请注意,AzureNotifyHub.sendTestNotification
只是一个示例方法,用于演示如何在Flutter应用中发送通知。在实际应用中,通知通常是由后端服务器发送的,你需要将设备的registrationId
发送到你的后端服务器,然后后端服务器调用Azure Notification Hub的API来发送通知。
这个代码案例提供了一个基本的框架,你可以根据需要进行扩展和修改。