我使用flutter_local_notificationworkmanager插件,以便在生成通知时运行一些后台代码(仅限Android).Ffltter_LOCAL_NOTIFICATION的初始化方式如下:

final StreamController<ReceivedNotification> didReceiveLocalNotificationSubject = StreamController<ReceivedNotification>.broadcast();

Future<void> init() async {
    await _configureLocalTimeZone();

    notificationAppLaunchDetails = await flutterLocalNotificationsPlugin.getNotificationAppLaunchDetails();
    if (notificationAppLaunchDetails!.didNotificationLaunchApp) {
      selectedNotificationPayload = notificationAppLaunchDetails!.notificationResponse?.payload;
    }

    const AndroidInitializationSettings initializationSettingsAndroid =
    AndroidInitializationSettings('@mipmap/ic_launcher');

    InitializationSettings initializationSettings = const InitializationSettings(
      android: initializationSettingsAndroid,
    );
    await flutterLocalNotificationsPlugin.initialize(
        initializationSettings,
        onDidReceiveNotificationResponse:
            (NotificationResponse notificationResponse) {
          switch (notificationResponse.notificationResponseType) {
            case NotificationResponseType.selectedNotification:
            case NotificationResponseType.selectedNotificationAction:
              // if (notificationResponse.actionId == navigationActionId) {
                selectNotificationSubject.add(notificationResponse.payload);
                selectedNotificationPayload = notificationResponse.payload;
              // }
                didReceiveLocalNotificationSubject.add(
                  ReceivedNotification(
                    id: notificationResponse.id!,
                    title: notificationResponse.actionId,
                    body: 'stuff',
                    payload: notificationResponse.payload,
                  ),
                );
              break;
          }
      },
      // onDidReceiveBackgroundNotificationResponse: notificationTapBackground,
    );

    _notificationsEnabled = await _isAndroidPermissionGranted();
    _notificationsEnabled = await _requestPermissions();
    _configureDidReceiveLocalNotificationSubject();
  }

下面是使用WorkManager执行的代码:

void _configureDidReceiveLocalNotificationSubject() {
    didReceiveLocalNotificationSubject.stream
        .listen((ReceivedNotification receivedNotification) async {
          var title = receivedNotification.title ?? 'UNKNOWN';
          Workmanager().registerOneOffTask(
            "my.simpleTask",
            "my.simpleTask",
            inputData: <String, dynamic>{
              'string': title,
            },
          );
        });
  }

目前,我对该代码有两个问题:

  • 仅当用户轻触通知时,工作管理器的任务才会运行
  • 如果用户首先终止应用程序,则即使生成(并点击)通知,也不会执行工作经理的任务

如何在应用程序终止或未终止的情况下,在生成通知(无需用户点击)后立即执行WorkManager的任务?

推荐答案

我假设你被安排了本地通知,并在那里执行了一些功能.

TL:DR

  • 第一:计划的本地通知not able to execute function in background

例如:

int randomInt = Random().nextInt();
await flutterLocalNotificationsPlugin.zonedSchedule(
    0,
    'scheduled notif with int $randomInt',
     ....

当您注册此通知时,您将获得randomInt,然后在通知上,它将显示您第一次按计划收到的int.这意味着不执行其唯一的显示通知Random().nextInt.

  • 第二,
void _configureDidReceiveLocalNotificationSubject() {
    didReceiveLocalNotificationSubject.stream

流功能也将在应用程序被终止后终止.只是你把它带到了前台.该流将继续监听任何更改.


我如何才能使工作经理的任务在 生成通知

我想在这一点上我们很想念你.正确的做法是: 寄存器Workmanager,然后在callback函数内部,可以生成local notification.

  • 在您的initState中注册您的WM
Workmanager().registerOneOffTask(
  "task-identifier",
  simpleTaskKey,
  initialDelay: Duration(minutes: 30), // you can use this delay for scheduling
);

然后在回调函数中生成本地通知

@pragma('vm:entry-point')
void callbackDispatcher() {
  Workmanager().executeTask((task, inputData) {
   // you function execute here
   // 例如: final tempInt = Random.nextInt();
   // then we can use the tempInt 

    show local notification function here
    return Future.value(true);
  });
}

Flutter相关问答推荐

如何在容器中移动图标按钮?

如何解决这个错误,同时获得的高度的小部件,因此高度的可用工作区域在Flutter ?

带有可滚动页面(不包括分页区)的Flutter 页面视图

Flutter 对齐:不适用于多行文字

Flutter BLoC et workmanager:如何创建独特的仓库初始化模式?

Flutter creating Constant.dart InputDecoration section put pass in hintText

如何在表格日历标题下方添加文本?

Firebase WHERE过滤器在日期字段中不起作用

Flutter飞溅屏幕即使在修改后仍显示默认徽标和背景色

按一下按钮即可更新 fl_chart

没有固定宽度的小部件可以约束文本小部件吗?

Flutter:在 pubspec.yaml 中找不到assets资源

运行任何 flutter 命令都会显示无法安装 <版本>

Flutter ImagePicker - 在 onPressed 中异步获取图像显示 lint 警告

忽略异步函数上的 context.mounted 访问 linting 错误是否安全?

如何在 Flutter 中测试动画图标

如何获得Flutter 的时差?

使用 onPressed 切换到另一个屏幕无法正常工作

如何使用我拥有的 .jks 文件签署我的应用程序

从 Uint8List 或图像对象创建 InputImageData 用于 Google ML Kit 人脸检测