【问题标题】:Flutter & Background fetch - How to handle a simple example?Flutter & Background fetch - 如何处理一个简单的例子?
【发布时间】:2020-05-25 19:13:52
【问题描述】:

我真的很想知道如何使用包https://pub.dev/packages/background_fetch

我想运行一个简单的任务来从我的 sqllite 数据库中获取条目以更改状态。

在 main.dart 文件中,我有:

Future main() async {
  WidgetsFlutterBinding.ensureInitialized();
  initPlatformState();

  await DotEnv().load('.env');

  runApp(MyApp());

  // Register to receive BackgroundFetch events after app is terminated.
  // Requires {stopOnTerminate: false, enableHeadless: true}
  BackgroundFetch.registerHeadlessTask(backgroundFetchHeadlessTask);

  BackgroundFetch.start();
}

首先,如果非要说的话,我真的不是:BackgroundFetch.start();?

然后,这是我的函数:

// Platform messages are asynchronous, so we initialize in an async method.
Future<void> initPlatformState() async {
  // Configure BackgroundFetch.
  BackgroundFetch.configure(BackgroundFetchConfig(
      minimumFetchInterval: 15,
      stopOnTerminate: false,
      enableHeadless: false,
      requiresBatteryNotLow: false,
      requiresCharging: false,
      requiresStorageNotLow: false,
      requiresDeviceIdle: false,
      requiredNetworkType: NetworkType.ANY
  ), (String taskId) async {
    // This is the fetch-event callback.
    print("[BackgroundFetch] Event received $taskId");

    // take all photos not uploaded
    final repo = di.get<DossierRepository>();
    final photosNotUploaded = await repo.getPhotosNotUploaded();

    await for (final photo in Stream.fromIterable(photosNotUploaded)) {
      // resend them simply
      repo.resendPhoto(photo.dossierId, photo.photoId);
    }

    // IMPORTANT:  You must signal completion of your task or the OS can punish your app
    // for taking too long in the background.
    BackgroundFetch.finish(taskId);
  }).then((int status) {
    print('[BackgroundFetch] configure success: $status');
  }).catchError((e) {
    print('[BackgroundFetch] configure ERROR: $e');
  });
}

我有这个警告:

[TSBackgroundFetch start] Task flutter_background_fetch already registered

我知道我必须检查任务是否未注册,但是如何?如果我对代码进行更改,我需要“销毁”旧任务并注册新任务?

这是使用这个插件的好方法吗?我的应用程序只有 1 个任务,我希望它一直运行。我必须注册任务吗?或者这就足够了?

【问题讨论】:

    标签: flutter flutter-dependencies


    【解决方案1】:

    flutter_background_fetch 是BackgroundFetch 的默认taskid,在initPlatformState 时会被BackgroundFetch 自动注册。这意味着你不应该使用flutter_background_fetch作为taskid。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-11
      • 2013-02-22
      • 1970-01-01
      • 1970-01-01
      • 2019-03-16
      • 1970-01-01
      相关资源
      最近更新 更多