我正在使用 Flutter 开发 Android 应用程序,目前正在致力于实现通知。我已经成功设置了每周通知,但我想添加一个条件:仅当应用程序一周未打开时才触发通知。即使应用程序关闭,这也应该有效。
如何在 Flutter 中实现这个逻辑?
我已经探索了
flutter_local_notifications
和后台执行的选项,但我不确定跟踪应用程序上次打开时间并相应触发通知的最佳方法。
这是我的代码:
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
class NotificationService {
final FlutterLocalNotificationsPlugin notificationsPlugin = FlutterLocalNotificationsPlugin();
Future<void> initNotification() async {
notificationsPlugin.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()?.requestNotificationsPermission();
notificationsPlugin.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()?.requestExactAlarmsPermission();
}
Future<void> scheduleNotification() async {
const AndroidNotificationDetails androidNotificationDetails =
AndroidNotificationDetails(
'repeating channel id', 'repeating channel name',
channelDescription: 'repeating description',
icon: '@drawable/sn_invent');
const NotificationDetails notificationDetails =
NotificationDetails(android: androidNotificationDetails);
await notificationsPlugin.periodicallyShow(0, 'Ziele in Angriff genommen?',
'Schau doch gerne mal wieder deinen Zielplan an', RepeatInterval.weekly, notificationDetails,
androidAllowWhileIdle: true);
}
}
您需要跟踪应用程序何时打开以及应用程序何时关闭。您可以通过
shared_preferences
来做到这一点
具体方法如下:
Future<void> scheduleNotification() async {
if (await shouldTriggerNotification()) {
const AndroidNotificationDetails androidNotificationDetails =
AndroidNotificationDetails(
'repeating channel id',
'repeating channel name',
channelDescription: 'repeating description',
icon: '@drawable/sn_invent',
);
const NotificationDetails notificationDetails =
NotificationDetails(android: androidNotificationDetails);
await notificationsPlugin.periodicallyShow(
0,
'Ziele in Angriff genommen?',
'Schau doch gerne mal wieder deinen Zielplan an',
RepeatInterval.weekly,
notificationDetails,
androidAllowWhileIdle: true,
);
await updateLastOpenedTime();
}
}
Future<bool> shouldTriggerNotification() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
DateTime lastOpenedTime =
DateTime.parse(prefs.getString('lastOpenedTime') ?? '');
int daysDifference = DateTime.now().difference(lastOpenedTime).inDays;
return daysDifference >= 7;
}
Future<void> updateLastOpenedTime() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('lastOpenedTime', DateTime.now().toIso8601String());
}
}
在如何发送通知的逻辑中 在主类中创建计划通知,将此通知设置为静态ID,例如用户ID,然后当用户打开应用程序时,该函数将运行来自 DateTime.now().add(Duration(days:7)) 的计划通知 每次用户打开应用程序时,通知日期都会更改为该天后 7 天,但请确保通知 ID 是静态的