101 lines
2.9 KiB
Dart
101 lines
2.9 KiB
Dart
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
||
|
||
class NotifyService {
|
||
static final NotifyService _instance = NotifyService._internal();
|
||
|
||
factory NotifyService() => _instance;
|
||
|
||
NotifyService._internal();
|
||
|
||
late FlutterLocalNotificationsPlugin _notifications;
|
||
|
||
// Android特殊模式,即使设备处于省电模式也能准时触发。
|
||
final scheduleMode = AndroidScheduleMode.exactAllowWhileIdle;
|
||
|
||
// 初始化通知服务
|
||
Future<void> initialize() async {
|
||
_notifications = FlutterLocalNotificationsPlugin();
|
||
|
||
// 设置Android平台的初始化配置 使用应用图标作为通知图标
|
||
const AndroidInitializationSettings androidSettings =
|
||
AndroidInitializationSettings('@mipmap/ic_launcher');
|
||
|
||
// 设置iOS平台的初始化配置
|
||
const DarwinInitializationSettings iosSettings =
|
||
DarwinInitializationSettings(
|
||
requestAlertPermission: true,
|
||
requestBadgePermission: true,
|
||
requestSoundPermission: true,
|
||
);
|
||
|
||
// 初始化设置
|
||
const InitializationSettings settings = InitializationSettings(
|
||
android: androidSettings,
|
||
iOS: iosSettings,
|
||
);
|
||
|
||
await _notifications.initialize(settings: settings);
|
||
}
|
||
|
||
// 创建Android通知详情
|
||
AndroidNotificationDetails _androidNotificationDetails() {
|
||
const channelId = 'com.cxx.sweet_chat_app';
|
||
const channelName = '亲聊';
|
||
const channelDescription = '亲聊通知';
|
||
return const AndroidNotificationDetails(
|
||
channelId,
|
||
channelName,
|
||
channelDescription: channelDescription,
|
||
importance: Importance.high,
|
||
priority: Priority.high,
|
||
playSound: true,
|
||
enableVibration: true,
|
||
);
|
||
}
|
||
|
||
// 创建iOS通知详情
|
||
DarwinNotificationDetails _iosNotificationDetails() {
|
||
return const DarwinNotificationDetails(
|
||
presentAlert: true,
|
||
presentBadge: true,
|
||
presentSound: true,
|
||
);
|
||
}
|
||
|
||
NotificationDetails get _details {
|
||
return NotificationDetails(
|
||
android: _androidNotificationDetails(),
|
||
iOS: _iosNotificationDetails(),
|
||
);
|
||
}
|
||
|
||
// 立即显示通知
|
||
Future<void> showInstantNotification({
|
||
required String title,
|
||
required String body,
|
||
int id = 0,
|
||
}) async {
|
||
await _notifications.show(id: id, title: title, body: body, notificationDetails: _details);
|
||
}
|
||
|
||
// 检查通知权限
|
||
Future<bool> checkPermission() async {
|
||
final bool? result =
|
||
await _notifications
|
||
.resolvePlatformSpecificImplementation<
|
||
AndroidFlutterLocalNotificationsPlugin
|
||
>()
|
||
?.areNotificationsEnabled();
|
||
return result ?? false;
|
||
}
|
||
|
||
// 请求权限
|
||
Future<void> requestPermission() async {
|
||
await _notifications
|
||
.resolvePlatformSpecificImplementation<
|
||
IOSFlutterLocalNotificationsPlugin
|
||
>()
|
||
?.requestPermissions(alert: true, badge: true, sound: true);
|
||
}
|
||
}
|