【发布时间】: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