为什么我的 flutter_background_fetch 在应用程序终止时不起作用?

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

嗨,我希望我的 Android 应用程序在后台工作,即使程序完全关闭(终止)。我使用 flutter_background_fetch 来实现。通知每 15 分钟正确显示一次,应用程序打开或进入后台,但是当我终止应用程序时,background_fetch 不起作用,不再显示通知或执行任何操作。 这是我的主文件配置:

void main() async {

  WidgetsFlutterBinding.ensureInitialized();
  BackgroundFetch.registerHeadlessTask(backgroundFetchHeadlessTask);
  initializeNotificationService();
  runApp(const MyApp());
}


@pragma('vm:entry-point')
void backgroundFetchHeadlessTask(HeadlessTask task) async {
  String taskId = task.taskId;
  bool isTimeout = task.timeout;
  if (isTimeout) {
    // This task has exceeded its allowed running-time.
    // You must stop what you're doing and immediately .finish(taskId)
    BackgroundFetch.finish(taskId);
    return;
  }
  // Do your work here...
  BackgroundFetch.finish(taskId);
}

这是我的background_fetch控制器主体的一部分:

class Controller extends GetxController {
  
  @override
  void onInit() {
    // TODO: implement onInit

    super.onInit();
    startListeningNotificationEvents();
    initPlatformState();
  }
  
  Future<void> initPlatformState() async {
    var status = await BackgroundFetch.configure(
        BackgroundFetchConfig(
          minimumFetchInterval: 15,
          forceAlarmManager: false,
          stopOnTerminate: false,
          startOnBoot: true,
          enableHeadless: true,
          requiresBatteryNotLow: false,
          requiresCharging: false,
          requiresStorageNotLow: false,
          requiresDeviceIdle: false,
          requiredNetworkType: NetworkType.NONE,

        ),
        _onBackgroundFetch,
        _onBackgroundFetchTimeout);
    BackgroundFetch.scheduleTask(TaskConfig(
        taskId: "test",
        delay: 1000,
        periodic: false,
        stopOnTerminate: false,
        enableHeadless: true));
    BackgroundFetch.start();
  }

  void _onBackgroundFetchTimeout(String taskId) {
    //BackgroundFetch.finish(taskId);


    }
    
      void _onBackgroundFetch(String taskId) async {
        if (taskId == "test") {
        

  random();
      createNotification();
    }
  }

}

文档中说,如果我们希望应用程序在终止后仍能工作,我们应该将“stopOnTerminate”设置为 false。但仍然不工作。如何解决这个问题?请帮忙。

android flutter background-service background-fetch
1个回答
0
投票

经过多次尝试,对我有用的是使用 Workmanager。但是直接通过 Android Studio 中的“运行”按钮运行,回调调度程序仅在应用程序运行时(无论是在前台还是后台)运行。当我关闭应用程序时,任务停止工作。然而,当在终端中通过“flutter run”运行时,一切都运行良好,即使在最近的应用程序中关闭了该应用程序。所以我建议您先使用“flutter run”进行测试,如果不起作用,请尝试从Background_Fetch迁移到Workmanager并在终端中通过“flutter run”运行。

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