flutter本地推送 flutter_local_notifications的使用记录

flutter_local_notifications

效果

安卓配置(AndroidManifest.xml)

    <uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
    <uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>

可参考下面

<manifest xmlns:android="http://schemas.android.com/apk/res/android"><uses-permission android:name="android.permission.INTERNET"/><uses-permission android:name="android.permission.READ_MEDIA_IMAGES" /><uses-permission android:name="android.permission.READ_MEDIA_VIDEO" /><uses-permission android:name="com.android.alarm.permission.SET_ALARM"/><uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" /><uses-permission android:name="android.permission.POST_NOTIFICATIONS"/><applicationandroid:label="whisp"android:name="${applicationName}"android:icon="@mipmap/launcher_icon"><activityandroid:name=".MainActivity"android:exported="true"android:launchMode="singleTop"android:taskAffinity=""android:theme="@style/LaunchTheme"android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"android:hardwareAccelerated="true"android:windowSoftInputMode="adjustResize"><!-- Specifies an Android theme to apply to this Activity as soon asthe Android process has started. This theme is visible to the userwhile the Flutter UI initializes. After that, this theme continuesto determine the Window background behind the Flutter UI. --><meta-dataandroid:name="io.flutter.embedding.android.NormalTheme"android:resource="@style/NormalTheme"/><intent-filter><action android:name="android.intent.action.MAIN"/><category android:name="android.intent.category.LAUNCHER"/></intent-filter></activity><!-- Don't delete the meta-data below.This is used by the Flutter tool to generate GeneratedPluginRegistrant.java --><meta-dataandroid:name="flutterEmbedding"android:value="2" /></application><!-- Required to query activities that can process text, see:https://developer.android.com/training/package-visibility andhttps://developer.android.com/reference/android/content/Intent#ACTION_PROCESS_TEXT.In particular, this is used by the Flutter engine in io.flutter.plugin.text.ProcessTextPlugin. --><queries><intent><action android:name="android.intent.action.PROCESS_TEXT"/><data android:mimeType="text/plain"/></intent></queries>
</manifest>

ios配置AppDelegate.swift(参考下面)

import flutter_local_notifications

 FlutterLocalNotificationsPlugin.setPluginRegistrantCallback { (registry) in
        GeneratedPluginRegistrant.register(with: registry)
    }

if #available(iOS 10.0, *) {
      UNUserNotificationCenter.current().delegate = self as UNUserNotificationCenterDelegate
}

 (参考下面)

import UIKit
import Flutter
import flutter_local_notifications@main
@objc class AppDelegate: FlutterAppDelegate {override func application(_ application: UIApplication,didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {// This is required to make any communication available in the action isolate.FlutterLocalNotificationsPlugin.setPluginRegistrantCallback { (registry) inGeneratedPluginRegistrant.register(with: registry)}if #available(iOS 10.0, *) {UNUserNotificationCenter.current().delegate = self as UNUserNotificationCenterDelegate}GeneratedPluginRegistrant.register(with: self)return super.application(application, didFinishLaunchingWithOptions: launchOptions)}
}

封装类

import 'dart:async';
import 'dart:io';import 'package:flutter_local_notifications/flutter_local_notifications.dart';@pragma('vm:entry-point')
void notificationTapBackground(NotificationResponse notificationResponse) {// ignore: avoid_printprint('notification(${notificationResponse.id}) action tapped: ''${notificationResponse.actionId} with'' payload: ${notificationResponse.payload}');if (notificationResponse.input?.isNotEmpty ?? false) {// ignore: avoid_printprint('notification action tapped with input: ${notificationResponse.input}');}
}class NotificationHelper {static NotificationHelper? _instance;static NotificationHelper getInstance() {_instance ??= NotificationHelper._initial();return _instance!;}factory NotificationHelper() => _instance ??= NotificationHelper._initial();//创建命名构造函数NotificationHelper._initial() {initialize();}// FlutterLocalNotificationsPlugin实例final FlutterLocalNotificationsPlugin _notificationsPlugin = FlutterLocalNotificationsPlugin();final StreamController<NotificationResponse> selectNotificationStream = StreamController<NotificationResponse>.broadcast();// 常量定义static const String _channelId = 'message_notifications';static const String _channelName = 'message notification';static const String _channelDescription = 'Notifications for receiving new messages';static const String _ticker = 'ticker';static const String _darwinNotificationCategoryPlain = 'plainCategory';static const String darwinNotificationCategoryText = 'textCategory';int id = 0;bool _notificationsEnabled = false;// 初始化通知插件Future<void> initialize() async {try {const AndroidInitializationSettings initializationSettingsAndroid = AndroidInitializationSettings('@mipmap/launcher_icon');const DarwinInitializationSettings initializationSettingsIOS =DarwinInitializationSettings(requestSoundPermission: false, requestBadgePermission: false, requestAlertPermission: false);const InitializationSettings initializationSettings = InitializationSettings(android: initializationSettingsAndroid,iOS: initializationSettingsIOS,);await _notificationsPlugin.initialize(initializationSettings,onDidReceiveNotificationResponse: selectNotificationStream.add,onDidReceiveBackgroundNotificationResponse: notificationTapBackground,);} catch (e) {print('初始化通知插件失败: $e');}}initPermission() {_isAndroidPermissionGranted();_requestPermissions();_configureSelectNotificationSubject();}closeSubject() {selectNotificationStream.close();}Future<void> _isAndroidPermissionGranted() async {if (Platform.isAndroid) {final bool granted =await _notificationsPlugin.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()?.areNotificationsEnabled() ??false;_notificationsEnabled = granted;}}Future<void> _requestPermissions() async {if (Platform.isIOS) {await _notificationsPlugin.resolvePlatformSpecificImplementation<IOSFlutterLocalNotificationsPlugin>()?.requestPermissions(alert: true,badge: true,sound: true,);} else if (Platform.isAndroid) {final AndroidFlutterLocalNotificationsPlugin? androidImplementation =_notificationsPlugin.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>();final bool? grantedNotificationPermission = await androidImplementation?.requestNotificationsPermission();_notificationsEnabled = grantedNotificationPermission ?? false;}}void _configureSelectNotificationSubject() {selectNotificationStream.stream.listen((NotificationResponse? response) async {// await Navigator.of(context).push(MaterialPageRoute<void>(//   builder: (BuildContext context) =>//       SecondPage(response?.payload, data: response?.data),// ));print("点击消息携带的数据$response");});}// 显示通知Future<void> showNotification({required String title, required String body, String payload = ""}) async {const AndroidNotificationDetails androidNotificationDetails = AndroidNotificationDetails(_channelId,_channelName,channelDescription: _channelDescription,importance: Importance.max,priority: Priority.high,ticker: _ticker,);const DarwinNotificationDetails iosNotificationDetails = DarwinNotificationDetails(categoryIdentifier: _darwinNotificationCategoryPlain);const NotificationDetails notificationDetails = NotificationDetails(android: androidNotificationDetails, iOS: iosNotificationDetails);await _notificationsPlugin.show(id++,title,body,notificationDetails,payload: payload,);}/// 取消全部通知cancelAll() {_notificationsPlugin.cancelAll();}/// 取消对应ID的通知cancelId(int id) {_notificationsPlugin.cancel(id);}
}

使用

main方法中初始化

NotificationHelper.getInstance().initialize();

首页中进行权限和方法回调绑定和卸载

首页的instate
NotificationHelper.getInstance().initPermission();

首页的dispose

NotificationHelper.getInstance().closeSubject();

调用提示 接收消息直接调用

NotificationHelper.getInstance().showNotification(title: "科学研究", body: "研究开始了", payload: "payload");

这里可以监控点击推送后动作,如跳转页面  response?.data 是携带的数据

 void _configureSelectNotificationSubject() {selectNotificationStream.stream.listen((NotificationResponse? response) async {// await Navigator.of(context).push(MaterialPageRoute<void>(//   builder: (BuildContext context) =>//       SecondPage(response?.payload, data: response?.data),// ));print("点击消息携带的数据$response");});}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/web/69897.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

宝塔和docker的区别

宝塔面板 vs Docker&#xff1a;区别、场景与互补使用指南 eepseek回答宝塔和docker的区别 好的&#xff0c;我现在需要回答用户关于宝塔面板和Docker之间的区别的问题。首先&#xff0c;我需要明确这两个工具各自的定义、功能以及它们适用的场景&#xff0c;这样才能准确比较…

【算法专场】哈希表

目录 前言 哈希表 1. 两数之和 - 力扣&#xff08;LeetCode&#xff09; 算法分析 算法代码 面试题 01.02. 判定是否互为字符重排 ​编辑算法分析 算法代码 217. 存在重复元素 算法分析 算法代码 219. 存在重复元素 II 算法分析 算法代码 解法二 算法代码 算法…

PHP本地商家卡券管理系统

本地商家卡券管理系统 —— 引领智慧消费新时代 本地商家卡券管理系统&#xff0c;是基于ThinkPHPUni-appuView尖端技术匠心打造的一款微信小程序&#xff0c;它彻底颠覆了传统优惠方式&#xff0c;开创了多商家联合发行优惠卡、折扣券的全新模式&#xff0c;发卡类型灵活多变…

Kafka分区管理大师指南:扩容、均衡、迁移与限流全解析

#作者&#xff1a;孙德新 文章目录 分区分配操作(kafka-reassign-partitions.sh)1.1 分区扩容、数据均衡、迁移(kafka-reassign-partitions.sh)1.2、修改topic分区partition的副本数&#xff08;扩缩容副本&#xff09;1.3、Partition Reassign场景限流1.4、节点内副本移动到不…

极狐GitLab 17.8 正式发布,多项 DevOps 重点功能解读【二】

GitLab 是一个全球知名的一体化 DevOps 平台&#xff0c;很多人都通过私有化部署 GitLab 来进行源代码托管。极狐GitLab 是 GitLab 在中国的发行版&#xff0c;专门为中国程序员服务。可以一键式部署极狐GitLab。 学习极狐GitLab 的相关资料&#xff1a; 极狐GitLab 官网极狐…

AWTK-WEB 快速入门(4) - JS Http 应用程序

XMLHttpRequest 改变了 Web 应用程序与服务器交换数据的方式&#xff0c;fetch 是 XMLHttpRequest 继任者&#xff0c;具有更简洁的语法和更好的 Promise 集成。本文介绍一下如何使用 JS 语言开发 AWTK-WEB 应用程序&#xff0c;并用 fetch 访问远程数据。 用 AWTK Designer 新…

LabVIEW外腔二极管激光器稳频实验

本项目利用LabVIEW软件开发了一个用于外腔二极管激光器稳频实验的系统。系统能够实现激光器频率的稳定控制和实时监测&#xff0c;为激光实验提供了重要支持。 项目背景&#xff1a; 系统解决了外腔二极管激光器频率不稳定的问题&#xff0c;以满足对激光器频率稳定性要求较高…

计算机毕业设计--基于深度学习技术(Yolov11、v8、v7、v5)算法的高效人脸检测模型设计与实现(含Github代码+Web端在线体验界面)

基于深度学习技术&#xff08;Yolov11、v8、v7、v5&#xff09;算法的高效人脸检测模型 Yolo算法应用之《基于Yolo的花卉识别算法模型设计》&#xff0c;请参考这篇CSDN作品&#x1f447; 计算机毕业设计–基于深度学习技术&#xff08;Yolov11、v8、v7、v5&#xff09;算法的…

国家队出手!DeepSeek上线国家超算互联网平台!

目前,国家超算互联网平台已推出 DeepSeek – R1 模型的 1.5B、7B、8B、14B 版本,后续还会在近期更新 32B、70B 等版本。 DeepSeek太火爆了!在这个春节档,直接成了全民热议的话题。 DeepSeek也毫无悬念地干到了全球增速最快的AI应用。这几天,国内的云计算厂家都在支持Dee…

Android和DLT日志系统

1 Linux Android日志系统 1.1 内核logger机制 drivers/staging/android/logger.c static size_t logger_offset( struct logger_log *log, size_t n) { return n & (log->size - 1); } 写的off存在logger_log中&#xff08;即内核内存buffer&#xff09;&am…

安卓手游内存call综合工具/内部call/安卓注入call/数据分析(类人猿学院)

进程分析注入综合工具总界面 模块分析函数分析遍历 函数分析 so汇编分析 汇编call植入器&#xff0c;支持模拟器x86 x64 和手机arm64指令全平台 防ce搜索数据功能 全国首套发布&#xff0c;阿凡老师学院最好的安卓内存逆向老师&#xff0c;几乎行业最强的&#xff0c;有兴趣可以…

Kotlin 扩展

Kotlin 扩展 引言 Kotlin 作为一种现代编程语言,以其简洁、安全、互操作性强等特点,在 Android 开发领域占据了重要地位。其中,Kotlin 扩展(Extensions)是其一项非常实用的特性,它允许开发者以简洁的方式对类、对象或属性进行扩展。本文将详细介绍 Kotlin 扩展的概念、…

通过例子学 rust 个人精简版 1-1

1-1 Hello World fn main() {println!("Hello World!");// 动手试一试println!("Im a Rustacean!"); }Hello World! Im a Rustacean!要点1 &#xff1a;println 自带换行符 注释 fn main() {let x 5 /* 90 */ 5;println!("Is x 10 or 100? x …

ML.NET库学习007:从SQL数据库中流式读取数据并进行预测分析

文章目录 ML.NET库学习007:从SQL数据库中流式读取数据并进行预测分析项目主要目的和原理项目概述实现的主要功能主要流程步骤使用的主要函数方法关键技术主要功能和步骤功能详细解读实现步骤分步骤代码结构及语法解读使用机器学习进行特征工程:从类别到数值的转换与文本特征提…

闲鱼IP属地是通过电话号码吗?

在闲鱼这样的二手交易平台上&#xff0c;用户的IP属地信息对于维护交易安全、增强用户间的信任至关重要。然而&#xff0c;关于闲鱼IP属地是如何确定的&#xff0c;不少用户存在疑惑&#xff0c;尤其是它与电话号码之间是否存在关联。本文将深入探讨这一问题&#xff0c;揭示闲…

电商小程序(源码+文档+部署+讲解)

引言 随着移动互联网的快速发展&#xff0c;电商小程序成为连接消费者与商家的重要桥梁。电商小程序通过数字化手段&#xff0c;为消费者提供了一个便捷、高效的购物平台&#xff0c;从而提升购物体验和满意度。 系统概述 电商小程序采用前后端分离的架构设计&#xff0c;服…

【20250215】二叉树:94.二叉树的中序遍历

#方法一&#xff1a;递归法 # class Solution: # def inorderTraversal(self,root): # res[] # def dfs(node): # if node is None: # return # #下面代码是不对的&#xff0c;没有体现递归 # #res.a…

Windows环境安装Kafka(集群版)

大家好&#xff0c;最近在准备Java面试&#xff0c;复习到Kafka的相关知识&#xff0c;一时兴起&#xff0c;就想在自己的Windows笔记本上安装一个Kafka集群。下面就记录一下安装步骤。 工具分享 Offset Explorer&#xff1a;Kafka可视化工具 下载地址&#xff1a;https://ww…

完全数和质数算法详解

完全数是指一个正整数&#xff0c;它等于其所有真约数&#xff08;即除了自身以外的所有正因数&#xff09;之和。例如&#xff0c;6 是一个完全数&#xff0c;因为它的真约数是 1、2 和 3&#xff0c;且 1 2 3 6。 1 计算约数和 1.1 遍历 遍历其所有可能的约数并计算它们…

buu-jarvisoj_level2_x64-好久不见37

覆盖缓冲区和 RBP&#xff1a; 使用 128 8 字节覆盖 buf 和 rbp。 构造 ROP 链&#xff1a; pop rdi; ret 地址&#xff1a; 将 pop rdi; ret 指令的地址写入返回地址位置。 /bin/sh 地址&#xff1a; 将 /bin/sh 字符串的地址压入栈顶&#xff0c;作为 system 函数的参数。…