我正在向我的共享偏好添加一些详细信息(最多 3 个)。此外,我还有后台服务。每当新的详细信息添加到共享首选项时,我都会调用后台服务。但是,当我添加第二组详细信息时,后台服务不会获取它。
我想用我最新的共享首选项更新后台服务,但我可以在控制台中看到:“V/BackgroundService(7959):服务已在运行,使用现有服务。”看起来它只是在运行现有的细节,而不是接受新的细节。
有人可以帮助我找到解决方案吗,例如我如何使用最新的详细信息更新服务?下面是我的代码供您参考。谢谢!
我正在使用 flutter_background_service 5.0.5 包
//This is the screen I'm initialize background service inside my saveDetails
@override
void initState() {
super.initState();
Timer(const Duration(seconds: 5), () {
if (mounted) {
setState(() {
enableOkayButton = true;
});
}
});
saveDetails();
}
//Here I'm adding detail in my shared preferences
Future<void> saveDetails() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
int totalCount = prefs.getInt('idCount') ?? 0;
int currentCount = totalCount + 1;
prefs.setInt('idCount', currentCount);
String key = 'TCID$currentCount';
prefs.setString('$key-itemName', widget.name);
prefs.setDouble('$key-amount', widget.amount);
startService();
}
//This is my class where I had my background service class
Future<void> initializeService() async {
final service = FlutterBackgroundService();
await service.configure(
iosConfiguration: IosConfiguration(),
androidConfiguration: AndroidConfiguration(
autoStart: true, onStart: onStart, isForegroundMode: true));
service.startService();
}
@pragma('vm:entry-point')
Future<bool> onIosBackground(ServiceInstance service) async {
WidgetsFlutterBinding.ensureInitialized();
DartPluginRegistrant.ensureInitialized();
return true;
}
@pragma('vm:entry-point')
void onStart(ServiceInstance service) async {
WidgetsFlutterBinding.ensureInitialized();
if (service is AndroidServiceInstance) {
service.on('setAsForeground').listen((event) {
service.setAsForegroundService();
});
service.on('setAsBackground').listen((event) {
service.setAsBackgroundService();
});
service.on('stopService').listen((event) {
service.stopSelf();
});
}
Timer.periodic(const Duration(seconds: 5), (timer) async {
if (service is AndroidServiceInstance) {
if (await service.isForegroundService()) {
service.setForegroundNotificationInfo(
title: "My App Service",
content: "Updated at ${DateTime.now()}",
);
}
}
SharedPreferences prefs = await SharedPreferences.getInstance();
int totalCount = prefs.getInt('idCount') ?? 0;
print("--------------------->Total idCount stored: $totalCount");
// if (totalCount == 0) {
// service.stopSelf();
// return;
// } else {
for (int i = 1; i <= totalCount; i++) {
String key = 'TCID$i';
String nme = prefs.getDouble('$key-itemName') ?? 0.0;
double amt = prefs.getString('$key-amount') ?? '';
print('TCID $i:');
print(' - Current Radius: $nme');
print(' - Destination Title: $amt');
}
print("---------------------->Background task is running");
// }
});
}
我想用我的新详细信息更新现有服务。
我也面临同样的问题,因为共享偏好。因此,重新加载共享首选项实例帮助我解决了这个问题。
final prefs = await SharedPreferences.getInstance();
await prefs.reload(); //USE THIS
在共享首选项中设置/获取值之前,只需使用这一行。这也将在后台服务中获取最新存储的本地数据。