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));
相关推荐
Zhijun.li@Studio2 小时前
Mac下的vscode远程ssh免密码登录
vscode·macos·ssh
SoraLuna2 小时前
「Mac玩转仓颉内测版25」基础篇5 - 布尔类型详解
开发语言·算法·macos·cangjie
@解忧杂货铺16 小时前
Android和IOS的区别
android·ios·cocoa
嘟嘟叽17 小时前
初学 flutter 环境变量配置
flutter
iFlyCai17 小时前
深入理解Flutter生命周期函数之StatefulWidget(一)
flutter·生命周期·dart·statefulwidget
sunly_17 小时前
Flutter:photo_view图片预览功能
android·javascript·flutter
黑色叉腰丶大魔王20 小时前
《macOS 开发环境配置与应用开发》
macos
Enougme21 小时前
mac安装appuim
macos·appium
青花瓷1 天前
虚拟机苹果OS当中XCode安装后如何增加对ios的支持
macos·ios·xcode
Summer不秃1 天前
Flutter中sqflite的使用案例
flutter