Flutter开发之flutter_local_notifications

flutter_local_notifications 消息通知

flutter_local_notifications地址

dart 复制代码
flutter_local_notifications: ^18.0.1
dart 复制代码
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

dart 复制代码
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />

ios

Info.plist

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

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

dart 复制代码
NotificationHelper.getInstance().requestNotificationPermissions();

1.初始化

dart 复制代码
NotificationHelper.getInstance().initialize();

2.使用

dart 复制代码
NotificationHelper.getInstance().zonedScheduleNotification(id: 10001, title: "科学研究", body: "研究开始了", scheduledDateTime: DateUtilss.getNowDateMs15or25DateTime(15));
相关推荐
爱学习的绿叶3 小时前
flutter TabBarView 动态添加删除页面
flutter
_可乐无糖4 小时前
mac终端使用pytest执行iOS UI自动化测试方法
macos·pytest
趴菜小玩家5 小时前
使用 Gradle 插件优化 Flutter Android 插件开发中的 Flutter 依赖缺失问题
android·flutter·gradle
后端常规开发人员6 小时前
在 Mac 上使用 Docker 安装宝塔并部署 LNMP 环境
macos·docker·容器·宝塔
nukix9 小时前
Mac Java 使用 tesseract 进行 ORC 识别
java·开发语言·macos·orc
SoraLuna10 小时前
「Mac玩转仓颉内测版7」入门篇7 - Cangjie控制结构(下)
算法·macos·动态规划·cangjie
Algorithm157611 小时前
mac上使用docker搭建gitlab
macos·docker·gitlab
余清歌11 小时前
macOS解决U盘装完系统容量变小的问题
macos
SoraLuna11 小时前
「Mac玩转仓颉内测版8」入门篇8 - Cangjie函数与方法
算法·macos·cangjie
zhlx283511 小时前
【免越狱】iOS砸壳 可下载AppStore任意版本 旧版本IPA下载
macos·ios·cocoa