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));