工作管理器(注册周期任务)与颤振,但我的应用程序每次在后台运行时都会崩溃



正在开发一个颤振应用程序,该应用程序必须在backgound中检索和更新我的sqlite数据库。为了实现这一点,我尝试设置和使用颤振提供的工作管理器插件。但每次它在后台运行时,它都会显示"不幸的是,myapp 已停止"。

这是我的主要.dart。

void callbackDispatcher() {
Workmanager.executeTask((task, inputData){
try {
var connectivityResult = await (Connectivity().checkConnectivity());
final result = await InternetAddress.lookup('google.com');
if (connectivityResult == ConnectivityResult.mobile) {
// I am connected to a mobile network.
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
print('connected');
}
} else if (connectivityResult == ConnectivityResult.wifi) {
// I am connected to a wifi network.
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
print('connected');
}
}
} on SocketException catch (_) {
print('not connected');
}
return Future.value(true);
});
}
void main() {
WidgetsFlutterBinding.ensureInitialized();
Workmanager.initialize(
callbackDispatcher, // The top level function, aka callbackDispatcher
isInDebugMode: 
false // If enabled it will post a notification whenever the task is running. Handy for debugging tasks
);
// Periodic task registration
Workmanager.registerPeriodicTask("2", "syncfirebase",
// When no frequency is provided the default 15 minutes is set.
// Minimum frequency is 15 min. Android will automatically change your frequency to 15 min if you have configured a lower frequency.
frequency: Duration(minutes: 15),
initialDelay: Duration(seconds: 10),
constraints: Constraints(networkType: NetworkType.connected));
runApp(new MyApp());
}

如果我不得不猜测,你在callbackDispatcher中错过了WidgetsFlutterBinding.ensureInitialized()的电话。callbackDispatcherWorkManager生成的后台隔离(实际上是Dart线程(的入口点,因此您需要重新初始化WidgetsFlutterBinding(这实际上应该由插件完成,但看起来作者并没有决定这样做(。

最新更新