Flutter:应用关闭时是否可以发送通知?

问题描述 投票:0回答:1

我正在使用 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);
  }
}
android flutter dart mobile notifications
1个回答
0
投票

在如何发送通知的逻辑中 在主类中创建计划通知,将此通知设置为静态ID,例如用户ID,然后当用户打开应用程序时,该函数将运行来自 DateTime.now().add(Duration(days:7)) 的计划通知 每次用户打开应用程序时,通知日期都会更改为该天后 7 天,但请确保通知 ID 是静态的

© www.soinside.com 2019 - 2024. All rights reserved.