You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
cloudsolutions-atoms/lib/controllers/notification/notification_manger.dart

165 lines
6.9 KiB
Dart

import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
4 years ago
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:permission_handler/permission_handler.dart';
2 years ago
import 'package:timezone/timezone.dart' as tz;
4 years ago
class NotificationManger {
4 years ago
// private constructor to avoid create object
NotificationManger._();
static late FlutterLocalNotificationsPlugin localNotificationsPlugin;
4 years ago
/// initialisation setting for all platform
/// onNotificationPressed action when notification pressed to open tap
/// onIOSNotificationPressed action when notification pressed
/// to open tap in iOS versions older than 10
static Future<void> initialisation(Function(NotificationResponse) onNotificationPressed, DidReceiveLocalNotificationCallback onIOSNotificationPressed) async {
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
4 years ago
// initialise the plugin. app_icon needs to be a added as a drawable resource to the Android head project
const AndroidInitializationSettings initializationSettingsAndroid = AndroidInitializationSettings('@drawable/ic_stat_name');
4 years ago
final DarwinInitializationSettings initializationSettingsDarwin = DarwinInitializationSettings(onDidReceiveLocalNotification: onIOSNotificationPressed);
4 years ago
final InitializationSettings initializationSettings = InitializationSettings(android: initializationSettingsAndroid, iOS: initializationSettingsDarwin, macOS: initializationSettingsDarwin);
localNotificationsPlugin = flutterLocalNotificationsPlugin;
if (Platform.isIOS) {
await localNotificationsPlugin.resolvePlatformSpecificImplementation<IOSFlutterLocalNotificationsPlugin>()?.requestPermissions(alert: true, badge: true, sound: true);
} else if (Platform.isAndroid) {
final AndroidFlutterLocalNotificationsPlugin? androidImplementation = localNotificationsPlugin.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>();
final bool granted = await androidImplementation?.requestNotificationsPermission() ?? false;
if (!granted) {
if (kDebugMode) {
print("-------------------- Permission Granted ------------------------");
print(granted);
}
await Permission.notification.request();
}
}
4 years ago
await localNotificationsPlugin.initialize(initializationSettings, onDidReceiveNotificationResponse: onNotificationPressed);
} // push new notification
static AndroidNotificationDetails androidNotificationDetails(String? groupId, String? channelId) => AndroidNotificationDetails(
channelId ?? 'com.hmg.atoms',
'ATOMS',
channelDescription: 'Push notification service for ATOMS',
importance: Importance.max,
priority: Priority.max,
icon: "@drawable/ic_stat_name",
playSound: true,
channelShowBadge: true,
visibility: NotificationVisibility.public,
enableVibration: true,
groupKey: groupId ?? 'com.hmg.atoms',
1 month ago
setAsGroupSummary: false,
);
static DarwinNotificationDetails iosNotificationDetails(String? threadId) => DarwinNotificationDetails(categoryIdentifier: "atoms", threadIdentifier: threadId);
static Future<void> showNotification({required BuildContext context, required String title, required String subtext, required int hashcode, String? payload}) async {
var dataPayload = json.decode(payload ?? "{}");
String? groupId = dataPayload["group_id"];
NotificationDetails platformChannel = NotificationDetails(android: androidNotificationDetails(groupId, groupId), iOS: iosNotificationDetails(groupId), macOS: iosNotificationDetails(groupId));
4 years ago
await localNotificationsPlugin.show(hashcode, title, subtext, platformChannel, payload: payload);
// If there's a group_id, also show/update the summary notification
if (groupId != null && Platform.isAndroid) {
await _showGroupSummary(groupId);
}
}
static final Map<String, int> _groupCounts = {};
static Future<void> _showGroupSummary(String groupId) async {
// Increment count for this group
_groupCounts[groupId] = (_groupCounts[groupId] ?? 0) + 1;
final count = _groupCounts[groupId]!;
// Only show summary if we have 2+ notifications
if (count < 2) return;
final AndroidNotificationDetails summaryDetails = AndroidNotificationDetails(
'com.hmg.atoms',
'ATOMS',
channelDescription: 'Push notification service for ATOMS',
importance: Importance.max,
priority: Priority.max,
icon: "@drawable/ic_stat_name",
groupKey: groupId,
setAsGroupSummary: true,
1 month ago
onlyAlertOnce: true,
autoCancel: true,
styleInformation: InboxStyleInformation(
[],
contentTitle: 'ATOMS',
summaryText: 'You have $count new notifications',
),
);
// Use group_id's hashCode as the summary notification ID to ensure uniqueness
final int summaryId = groupId.hashCode;
await localNotificationsPlugin.show(
summaryId,
'ATOMS',
'$count new notifications',
NotificationDetails(android: summaryDetails),
);
4 years ago
}
2 years ago
static Future scheduleNotification({int? id, String? title, String? body, String? payLoad, required DateTime scheduledNotificationDateTime}) async {
2 years ago
return localNotificationsPlugin.zonedSchedule(
id ?? 0,
2 years ago
title,
body,
// tz.TZDateTime.now(tz.local).add(const Duration(seconds: 5)),
tz.TZDateTime.from(
scheduledNotificationDateTime,
tz.local,
),
NotificationDetails(android: androidNotificationDetails(null, null), iOS: iosNotificationDetails(null), macOS: iosNotificationDetails(null)),
2 years ago
androidScheduleMode: AndroidScheduleMode.exactAllowWhileIdle,
uiLocalNotificationDateInterpretation: UILocalNotificationDateInterpretation.absoluteTime);
2 years ago
}
static Future<void> cancelNotificationById(int notificationId) async {
await localNotificationsPlugin.cancel(notificationId);
}
/// Show group summary notification (for background isolate)
static Future<void> _showGroupSummaryBackground(String groupId, FlutterLocalNotificationsPlugin plugin) async {
final AndroidNotificationDetails summaryDetails = AndroidNotificationDetails(
'com.hmg.atoms',
'ATOMS',
channelDescription: 'Push notification service for ATOMS',
importance: Importance.max,
priority: Priority.max,
icon: "@drawable/ic_stat_name",
groupKey: groupId,
setAsGroupSummary: true,
autoCancel: true,
onlyAlertOnce: true,
styleInformation: InboxStyleInformation(
[],
contentTitle: 'ATOMS',
summaryText: 'New notifications',
),
);
final int summaryId = groupId.hashCode;
await plugin.show(
summaryId,
'ATOMS',
'New notifications',
NotificationDetails(android: summaryDetails),
);
}
}