我想在我的新 Flutter 移动应用程序中使用 Microsoft Azure 通知中心推送通知,但我在互联网上没有找到任何有关如何实现它的文档或文章。 pub.dev 上可用于 azure 通知中心的软件包没有详细记录,我无法理解它们。我想知道在Flutter上能不能实现?如果是的话我该如何实施呢?请告诉我完整的实施过程。
我使用 azure_notify_hub pakacge 来实现它:
import 'package:azure_notifications_test/fcm_service.dart';
import 'package:azure_notify_hub/azure_notify_hub.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'firebase_options.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
await FCMService.shared.init();
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyAppAzure(),
);
}
}
class MyAppAzure extends StatefulWidget {
const MyAppAzure({super.key});
@override
_MyAppAzureState createState() => _MyAppAzureState();
}
class _MyAppAzureState extends State<MyAppAzure> {
AzureNotificationhubsFlutter? _anh;
@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: <Widget>[
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
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: const Center(
child: Text('Running'),
),
);
}
}
我想知道在Flutter上能不能实现?如果是的话我该如何实施呢?请告诉我完整的实施过程。
是的,您可以使用 Microsoft Azure 通知中心在 Flutter 应用程序中实现推送通知。
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:http/http.dart' as http;
late FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
// Initialize flutter_local_notifications plugin
flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
const AndroidInitializationSettings initializationSettingsAndroid =
AndroidInitializationSettings('app_icon');
final InitializationSettings initializationSettings =
InitializationSettings(android: initializationSettingsAndroid);
await flutterLocalNotificationsPlugin.initialize(initializationSettings,
onSelectNotification: selectNotification);
runApp(MyApp());
}
Future<void> selectNotification(String? payload) async {
if (payload != null) {
debugPrint('notification payload: $payload');
}
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance;
@override
void initState() {
super.initState();
_firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) async {
_showNotification(message);
},
onLaunch: (Map<String, dynamic> message) async {
_showNotification(message);
},
onResume: (Map<String, dynamic> message) async {
_showNotification(message);
},
);
}
Future<void> _showNotification(Map<String, dynamic> message) async {
final String? title = message['notification']['title'];
final String? body = message['notification']['body'];
const AndroidNotificationDetails androidPlatformChannelSpecifics =
AndroidNotificationDetails(
'your channel id',
'your channel name',
'your channel description',
importance: Importance.max,
priority: Priority.high,
ticker: 'ticker',
);
const NotificationDetails platformChannelSpecifics =
NotificationDetails(android: androidPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.show(
0,
title,
body,
platformChannelSpecifics,
payload: 'item x',
);
}
Future<void> _sendTestNotification() async {
final response = await http.post(
Uri.parse('YOUR_AZURE_NOTIFICATION_HUB_SEND_ENDPOINT'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
'Authorization': 'YOUR_NOTIFICATION_HUB_ACCESS_TOKEN',
},
body: <String, dynamic>{
'data': <String, dynamic>{
'title': 'Test Notification',
'body': 'This is a test notification from Azure Notification Hub'
},
'notification': <String, dynamic>{
'title': 'Test Notification',
'body': 'This is a test notification from Azure Notification Hub'
},
'priority': 'high',
'to': '/topics/all',
},
);
if (response.statusCode == 200) {
print('Test notification sent successfully');
} else {
throw Exception('Failed to send test notification');
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Azure Notification Hub Example'),
),
body: Center(
child: ElevatedButton(
onPressed: _sendTestNotification,
child: const Text('Send Test Notification'),
),
),
),
);
}
}
_sendTestNotification()
,用于向订阅该主题 /topics/all
的所有设备发送测试通知。首先,在 Firebase 中创建一个测试项目并在项目中启用消息传递
这是我的服务器密钥,需要添加到天蓝色通知中心。
从 Firebase 消息传递中放置 API 密钥、项目名称、客户电子邮件,如下所示。
参考: