Flutter VoIP推送通知插件flutter_voip_push_notification_v2的使用
Flutter VoIP 推送通知插件 flutter_voip_push_notification_v2
的使用
简介
Flutter VoIP Push Notification - 目前仅支持 iOS >= 8.0。
动机
自 iOS 8.0 起,有一个名为 VoIP Push Notification 的优秀功能(参见 PushKit),而 firebase_messaging
不支持 VoIP 推送通知。因此开发了此插件。
要了解 VoIP 推送通知的好处,请参阅 VoIP 最佳实践。
注意 1:该插件仅适用于 iOS。对于 Android,您可以使用 firebase_messaging
发送高优先级推送通知。
注意 2:该插件受到了 react-native-voip-push-notification 和 firebase_messaging 的启发。
iOS
iOS 版本应为 >= 8.0,因为我们将使用 PushKit。
启用 VoIP 推送通知并获取 VoIP 证书
请参阅 VoIP 最佳实践。
注意:不要遵循上述链接中的 <code>Configure VoIP Push Notification</code>
部分,而是使用以下说明。
AppDelegate.swift
...
import PushKit /* <------ 添加这一行 */
import flutter_voip_push_notification /* <------ 添加这一行 */
...
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate, PKPushRegistryDelegate {
...
/* 添加 PushKit 委托方法 */
// 处理更新的推送凭据
func pushRegistry(_ registry: PKPushRegistry,
didReceiveIncomingPushWith payload: PKPushPayload,
for type: PKPushType,
completion: @escaping () -> Void){
// 注册 VoIP 推送令牌(PKPushCredentials 的属性)
FlutterVoipPushNotificationV2Plugin.didReceiveIncomingPush(with: payload, forType: type.rawValue)
}
// 处理传入的推送
func pushRegistry(_ registry: PKPushRegistry, didUpdate pushCredentials: PKPushCredentials, for type: PKPushType) {
// 处理接收到的推送
FlutterVoipPushNotificationV2Plugin.didUpdate(pushCredentials, forType: type.rawValue);
}
...
}
使用
在您的 pubspec.yaml
文件中添加 flutter_voip_push_notification_v2
作为依赖项。
dependencies:
flutter_voip_push_notification_v2: ^版本号
示例
以下是使用 flutter_voip_push_notification_v2
插件的完整示例代码。
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter_voip_push_notification_v2/flutter_voip_push_notification_v2.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
[@override](/user/override)
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _pushToken = '';
final FlutterVoipPushNotificationV2 _voipPush = FlutterVoipPushNotificationV2();
[@override](/user/override)
void initState() {
super.initState();
configure();
}
// 配置 VoIP 推送通知
Future<void> configure() async {
// 请求权限(必需)
await _voipPush.requestNotificationPermissions();
// 监听 VoIP 设备令牌变化
_voipPush.onTokenRefresh.listen(onToken);
// 配置 VoIP 推送
_voipPush.configure(onMessage: onMessage, onResume: onResume);
}
/// 当设备令牌发生变化时调用
void onToken(String token) {
// 将令牌发送到您的 APN 提供商服务器
setState(() {
_pushToken = token;
});
}
/// 当应用处于前台时接收通知
///
/// [isLocal] 如果是本地通知则为 true,否则为 false(远程通知)
/// [payload] 要处理的通知负载,用于呈现本地通知
Future<dynamic>? onMessage(bool isLocal, Map<String, dynamic> payload) {
// 处理前台通知
print("received on foreground payload: $payload, isLocal=$isLocal");
return null;
}
/// 当应用从后台恢复时接收通知
///
/// [isLocal] 如果是本地通知则为 true,否则为 false(远程通知)
/// [payload] 要处理的通知负载,用于呈现本地通知
Future<dynamic>? onResume(bool isLocal, Map<String, dynamic> payload) {
// 处理后台通知
print("received on background payload: $payload, isLocal=$isLocal");
showLocalNotification(payload);
return null;
}
showLocalNotification(Map<String, dynamic> notification) {
String alert = notification["aps"]["alert"];
_voipPush.presentLocalNotification(LocalNotification(
alertBody: "Hello $alert",
alertAction: '',
));
}
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('插件示例应用'),
),
body: Center(
child: Text('Received Voip Push token: $_pushToken\n'),
),
),
);
}
}
更多关于Flutter VoIP推送通知插件flutter_voip_push_notification_v2的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter VoIP推送通知插件flutter_voip_push_notification_v2的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,下面是一个关于如何使用 flutter_voip_push_notification_v2
插件的简要指南和代码示例。这个插件主要用于在 Flutter 应用中实现 VoIP 推送通知。
环境配置
首先,确保你的 Flutter 项目已经创建,并且在 pubspec.yaml
文件中添加了 flutter_voip_push_notification_v2
依赖:
dependencies:
flutter:
sdk: flutter
flutter_voip_push_notification_v2: ^x.y.z # 替换为最新版本号
然后运行 flutter pub get
来获取依赖。
iOS 配置
对于 iOS,你需要配置你的 Info.plist
和 AppDelegate.swift
或 AppDelegate.m
文件。
- 在
Info.plist
中添加权限请求:
<key>NSVoIPUsageDescription</key>
<string>需要VoIP权限来接收来电</string>
- 在
AppDelegate.swift
中配置:
import UIKit
import Flutter
import flutter_voip_push_notification_v2
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GeneratedPluginRegistrant.register(with: self)
// 注册VoIP推送通知
if let voipRegistration = VoIPPushNotificationManager.shared() {
voipRegistration.setupVoIP()
}
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
override func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable : Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
// 处理VoIP推送通知
if let voipRegistration = VoIPPushNotificationManager.shared() {
voipRegistration.handleVoIPPush(userInfo: userInfo)
}
completionHandler(.newData)
}
override func applicationDidEnterBackground(_ application: UIApplication) {
// 当应用进入后台时,保持VoIP socket连接
if let voipRegistration = VoIPPushNotificationManager.shared() {
voipRegistration.keepAlive()
}
}
}
Android 配置
对于 Android,你需要在 AndroidManifest.xml
和创建一个 VoIPService
。
- 在
AndroidManifest.xml
中添加权限:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
- 创建一个
VoIPService
类:
import android.app.Notification
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.IBinder
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.embedding.engine.FlutterEngineCache
import io.flutter.plugins.generated.VoipPushNotificationPluginRegistrant
import com.example.yourapp.VoIPPushNotificationManager // 替换为你的包名
class VoIPService : Service() {
private lateinit var flutterEngine: FlutterEngine
override fun onCreate() {
super.onCreate()
flutterEngine = FlutterEngine(this)
flutterEngine.navigationChannel.setInitialRoute("/")
VoipPushNotificationPluginRegistrant.registerWith(flutterEngine)
VoIPPushNotificationManager.shared(flutterEngine).setupVoIP(this)
startForeground(1, createNotification())
}
private fun createNotification(): Notification {
val intent = Intent(this, MainActivity::class.java)
val pendingIntent: PendingIntent = PendingIntent.getActivity(this, 0, intent, 0)
val builder: Notification.Builder
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channelId = "voip_channel"
val channelName = "VoIP Channel"
val importance = NotificationManager.IMPORTANCE_HIGH
val channel = NotificationChannel(channelId, channelName, importance).apply {
description = "Channel for VoIP notifications"
}
val notificationManager: NotificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
builder = Notification.Builder(this, channelId)
} else {
builder = Notification.Builder(this)
}
return builder.setContentTitle("VoIP Call")
.setContentText("Incoming call")
.setSmallIcon(R.drawable.ic_notification)
.setContentIntent(pendingIntent)
.build()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
return START_STICKY
}
override fun onBind(intent: Intent?): IBinder? {
return null
}
override fun onDestroy() {
flutterEngine.destroy()
super.onDestroy()
}
}
- 在
AndroidManifest.xml
中注册VoIPService
:
<service android:name=".VoIPService"
android:foregroundServiceType="voip"
android:permission="android.permission.BIND_VOIP_SERVICE"/>
Flutter 代码示例
在 Flutter 端,你可以使用以下代码来初始化并处理 VoIP 推送通知:
import 'package:flutter/material.dart';
import 'package:flutter_voip_push_notification_v2/flutter_voip_push_notification_v2.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
void initState() {
super.initState();
VoIPPushNotificationManager.shared()
..initialize(
onIncomingCall: (Map<String, dynamic> payload) async {
// 处理来电
print('Incoming call payload: $payload');
},
onReportNew: (Map<String, dynamic> payload) {
// 处理其他VoIP事件
print('Report new payload: $payload');
},
)
..registerVoIP();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('VoIP Push Notification Demo'),
),
body: Center(
child: Text('Waiting for VoIP Push Notification...'),
),
),
);
}
}
总结
上述代码展示了如何在 Flutter 项目中集成 flutter_voip_push_notification_v2
插件来处理 VoIP 推送通知。这包括在 iOS 和 Android 上的必要配置以及 Flutter 端的代码实现。确保按照文档和实际需求调整配置和代码。