当前位置: 首页 > article >正文

Flutter开发之flutter_local_notifications

flutter_local_notifications 消息通知

flutter_local_notifications地址

flutter_local_notifications: ^18.0.1
class NotificationHelper {
  //工厂模式调用该类时,默认调用此方法,将实例对象返回出去
  static NotificationHelper? _instance = null;

  static NotificationHelper getInstance() {
    _instance ??= NotificationHelper._initial();
    return _instance!;
  }

  factory NotificationHelper() => _instance ??= NotificationHelper._initial();

  //创建命名构造函数
  NotificationHelper._initial() {
    initialize();
  }


  // FlutterLocalNotificationsPlugin实例
  final FlutterLocalNotificationsPlugin _notificationsPlugin =
  FlutterLocalNotificationsPlugin();

  // 常量定义
  static const String _channelId = 'your.channel.id';
  static const String _channelName = 'your channel name';
  static const String _channelDescription = 'your channel description';
  static const String _ticker = 'ticker';
  static const String _darwinNotificationCategoryPlain = 'plainCategory';

  // 初始化通知插件
  Future<void> initialize() async {
    try {
      final AndroidInitializationSettings initializationSettingsAndroid =
      AndroidInitializationSettings('@mipmap/ic_launcher');
      final DarwinInitializationSettings initializationSettingsIOS =
      DarwinInitializationSettings();
      final InitializationSettings initializationSettings =
      InitializationSettings(
          android: initializationSettingsAndroid,
          iOS: initializationSettingsIOS);
      await _notificationsPlugin.initialize(initializationSettings);
    } catch (e) {
      print('初始化通知插件失败: $e');
    }
  }

  Future<void> requestNotificationPermissions() async {
    if (await Permission.notification.isDenied) {
      final status = await Permission.notification.request();
      final status1 = await Permission.scheduleExactAlarm.request();
      LogUtils.d("requestNotificationPermissions :通知权限status1 $status1");
      if (status.isGranted) {
        LogUtils.d("requestNotificationPermissions :通知权限已授予");
        print('通知权限已授予');
      } else {
        LogUtils.d("requestNotificationPermissions :通知权限被拒绝");
        print('通知权限被拒绝');
      }
    } else {
      LogUtils.d("requestNotificationPermissions :通知权限已授予");
      print('通知权限已授予');
    }
  }

  // 显示通知
  Future<void> showNotification(
      {required String title, required String body}) async {
    try {
      final AndroidNotificationDetails androidNotificationDetails =
      AndroidNotificationDetails(
          _channelId, _channelName,
          channelDescription: _channelDescription,
          importance: Importance.max,
          priority: Priority.high,
          ticker: _ticker);

      final DarwinNotificationDetails iosNotificationDetails =
      DarwinNotificationDetails(
          categoryIdentifier: _darwinNotificationCategoryPlain);

      final NotificationDetails platformChannelSpecifics =
      NotificationDetails(
          android: androidNotificationDetails, iOS: iosNotificationDetails);

      await _notificationsPlugin.show(
        1,
        title,
        body,
        platformChannelSpecifics,
      );
    } catch (e) {
      print('显示通知失败: $e');
    }
  }

  // 周期性通知
  Future<void> scheduleNotification({
    required int id,
    required String title,
    required String body,
  }) async {
    const AndroidNotificationDetails androidNotificationDetails =
    AndroidNotificationDetails('your.channel.id', 'your channel name',
        channelDescription: 'your channel description',
        importance: Importance.max,
        priority: Priority.high,
        ticker: 'ticker');

    // ios的通知
    const String darwinNotificationCategoryPlain = 'plainCategory';
    const DarwinNotificationDetails iosNotificationDetails =
    DarwinNotificationDetails(
      categoryIdentifier: darwinNotificationCategoryPlain, // 通知分类
    );
    // 创建跨平台通知
    const NotificationDetails platformChannelSpecifics = NotificationDetails(
        android: androidNotificationDetails, iOS: iosNotificationDetails);
// 发起通知
    await _notificationsPlugin.periodicallyShow(
        id, title, body, RepeatInterval.everyMinute, platformChannelSpecifics);
  }


// 定时通知
  Future<void> zonedScheduleNotification({required int id,
    required String title,
    required String body,
    required DateTime scheduledDateTime}) async {
    const AndroidNotificationDetails androidNotificationDetails =
    AndroidNotificationDetails('10001', '唤醒',
        channelDescription: 'your channel description',
        importance: Importance.max,
        priority: Priority.high,
        ticker: 'ticker');

    // ios的通知
    const String darwinNotificationCategoryPlain = 'plainCategory';
    const DarwinNotificationDetails iosNotificationDetails =
    DarwinNotificationDetails(
      categoryIdentifier: darwinNotificationCategoryPlain, // 通知分类
    );
    // 创建跨平台通知
    const NotificationDetails platformChannelSpecifics = NotificationDetails(
        android: androidNotificationDetails, iOS: iosNotificationDetails);

    // 获取本地时区
    final location = tz.getLocation(tz.local.name);
    // 发起通知
     _notificationsPlugin.zonedSchedule(
      id, title, body,
      TZDateTime.from(scheduledDateTime, location), // 使用本地时区的时间
      platformChannelSpecifics,
      uiLocalNotificationDateInterpretation:
      UILocalNotificationDateInterpretation.wallClockTime, // 设置通知的触发时间是觉得时间
    );
  }


  /// 取消全部通知
  cancelAll(){
    _notificationsPlugin.cancelAll();
  }

  /// 取消对应ID的通知
  cancelId(int id){
    _notificationsPlugin.cancel(id);
  }
}

使用步骤:

0.请求通知权限
android
manifest.xml

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

ios
Info.plist

<key>NSUserNotificationAlertIdentifier</key>
<string>我们需要您的许可来发送通知</string>
<key>NSUserNotificationAlertTitle</key>
<string>请求通知权限</string>
<key>NSUserNotificationAlertBody</key>
<string>我们希望能够在您允许的情况下发送通知。</string>

使用之前一定要代码里边获取通知权限

NotificationHelper.getInstance().requestNotificationPermissions();

1.初始化

NotificationHelper.getInstance().initialize();

2.使用

NotificationHelper.getInstance().zonedScheduleNotification(id: 10001, title: "科学研究", body: "研究开始了", scheduledDateTime: DateUtilss.getNowDateMs15or25DateTime(15));


http://www.kler.cn/a/399432.html

相关文章:

  • Android Osmdroid + 天地图 (一)
  • 哈希表学习分享
  • 丹摩征文活动|丹摩助力selenium实现大麦网抢票
  • java.sql.SQLException Parameter index out of range
  • 【Electron】Electron Forge如何支持Element plus?
  • FFmpeg 4.3 音视频-多路H265监控录放C++开发十四,总结编码过程,从摄像头获得数据后,转成AVFrame,然后再次转成AVPacket,
  • 2024年了,TCP分析工具有哪些?
  • 力扣-Hot100-链表其一【算法学习day.34】
  • websocket身份验证
  • 网络技术-定义配置ACL规则的语法和命令
  • 学了Arcgis的水文分析——捕捉倾泻点,河流提取与河网分级,3D图层转要素失败的解决方法,测量学综合实习网站存着
  • htm + vue + quill 富文本编辑器案例
  • ubuntu连接orangepi-zero-2w桌面的几种方法
  • 【逐行注释】三维容积卡尔曼滤波(CKF)的MATLAB例程,附下载链接
  • 探秘Spring Boot中的@Conditional注解
  • 千帆启航,人才先行 | 讯方技术HarmonyOS人才训练营
  • 基于springboot家教管理系统源码和论文
  • 【linux】如何扩展磁盘容量(VMware虚拟机)-转载
  • SpringMVC学习笔记(一)
  • 23种设计模式的Flutter实现第一篇创建型模式(一)
  • 号卡分销系统,号卡系统,物联网卡系统源码安装教程
  • Tomcat 与 Servlet 的关系:传统与 Spring Boot 中的差异
  • 「人眼视觉不再是视频消费的唯一形式」丨智能编解码和 AI 视频生成专场回顾@RTE2024
  • Kafka 与 RabbitMQ 的联系
  • 基于YOLOv8深度学习的智慧城市管理井盖状态检测系统(PyQt5界面+数据集+训练代码)
  • Python 网络爬虫入门教程