当应用程序关闭时 Flutter 发送本地通知(警报)

时间:2021-07-22 02:30:27

标签: flutter

我正在使用颤振很棒的通知

希望在应用关闭(不在后台运行)时发送通知。就像闹钟一样,通知将在特定时间发送。不是从 Firebase 等外部服务推送。

有没有办法做到这一点?或者我需要另一个像 android_alarm_manager 这样的软件包?

1 个答案:

答案 0 :(得分:0)

您可以使用 flutter_local_notification 并且它有一个名为 scheduling-a-notification 的功能,并且您还需要为时区提供 timezone 包才能工作,

导入时区包

import 'package:timezone/data/latest.dart' as tz;
import 'package:timezone/timezone.dart' as tz;

初始化时区数据库

tz.initializeTimeZones();

初始化时区数据库后,开发者可以选择设置默认的本地位置/时区,您可以使用 https://pub.dev/packages/flutter_native_timezone 获取操作系统的本地时区。

tz.setLocalLocation(tz.getLocation(timeZoneName));

假设已经设置了本地位置,则可以通过类似于以下代码的方式调用 zonedScheduled 方法

await flutterLocalNotificationsPlugin.zonedSchedule(
0,
'scheduled title',
'scheduled body',
tz.TZDateTime.now(tz.local).add(const Duration(seconds: 5)),
const NotificationDetails(
    android: AndroidNotificationDetails('your channel id',
        'your channel name', 'your channel description')),
androidAllowWhileIdle: true,
uiLocalNotificationDateInterpretation:
    UILocalNotificationDateInterpretation.absoluteTime);