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

qncylg1j  于 2022-11-17  发布在  Flutter
关注(0)|答案(3)|浏览(207)

我正在使用flutter真棒通知
希望在应用程序关闭(不在后台运行)时发送通知。就像闹钟一样,通知将在特定时间发送。而不是从外部服务(如firebase)推送。
有没有办法做到这一点?或者我需要另一个包,如android_alarm_manager

czfnxgou

czfnxgou1#

您可以使用flutter_local_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);
3htmauhk

3htmauhk2#

您可以在创建通知时使用schedule参数实现此操作
示例:

String localTimeZone =
    await AwesomeNotifications().getLocalTimeZoneIdentifier();

AwesomeNotifications().createNotification(
  content: NotificationContent(
    payload: {},
    id: id,
    channelKey: 'scheduled',
    title: 'title',
    body: 'body',
  ),
  schedule: NotificationCalendar(
    day: day,
    month: month,
    year: year,
    second: second,
    millisecond: millisecond,
    timeZone: localTimeZone,
    repeats: false,
  ),
);
rjee0c15

rjee0c153#

如果在Android上使用Awesome_notifications with flutter,请使用schedule参数作为Sneh Mehta的回复,但也要确保您的手机没有电池节省模式,并在发布模式下运行应用程序与“flutter run --release”

相关问题