flutter_background_service
flutter_background_service copied to clipboard
stop background service is not working
i am using flutter_background_service: 2.4.6 scenario: assume i start a service by clicking of the button and i terminate the app. Now i want to stop the service after reopening the app.
code: Main.dart
void main() async {
WidgetsFlutterBinding.ensureInitialized();
//initializeService();
runApp(const MyApp());
}
const notificationChannelId = "conection_service";
const notificationId = 888;
Future<void> initializeService() async {
final service = FlutterBackgroundService();
const AndroidNotificationChannel channel = AndroidNotificationChannel(
notificationChannelId, "Connection Service",
description: "This channel is used for Connection Service",
importance: Importance.low,
playSound: false
);
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
await flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(channel);
await service.configure(
iosConfiguration: IosConfiguration(),
androidConfiguration: AndroidConfiguration(
onStart: onStart,
isForegroundMode: true,
notificationChannelId: notificationChannelId,
initialNotificationTitle: "Connection Service",
initialNotificationContent: "Initializing",
foregroundServiceNotificationId: notificationId));
}
// to ensure this is executed
// run app from xcode, then from xcode menu, select Simulate Background Fetch
@pragma('vm:entry-point')
Future<bool> onIosBackground(ServiceInstance service) async {
WidgetsFlutterBinding.ensureInitialized();
DartPluginRegistrant.ensureInitialized();
SharedPreferences preferences = await SharedPreferences.getInstance();
await preferences.reload();
final log = preferences.getStringList('log') ?? <String>[];
log.add(DateTime.now().toIso8601String());
await preferences.setStringList('log', log);
return true;
}
@pragma('vm:entry-point')
void onStart(ServiceInstance service) async {
WidgetsFlutterBinding.ensureInitialized();
StreamController controller = StreamController();
int totalconnectedSensors = 0;
// Only available for flutter 3.0.0 and later
DartPluginRegistrant.ensureInitialized();
// For flutter prior to version 3.0.0
// We have to register the plugin manually
/// OPTIONAL when use custom notification
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
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();
});
controller.stream.listen((event) {
flutterLocalNotificationsPlugin.show(
888,
'Polar Connection Service',
'Connected Sensors: $event',
const NotificationDetails(
iOS: DarwinNotificationDetails(
threadIdentifier: "thread1", subtitle: "Service is running"),
android: AndroidNotificationDetails(
'Polar Connection Service',
'Running connection Service',
icon: 'ic_bg_service_small',
ongoing: true,
playSound: false,
),
),
);
});
Timer.periodic(const Duration(seconds: 1), (timer) async {
controller.add(totalconnectedSensors++);
print("Total connectes Sensor $totalconnectedSensors");
});
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const Home(),
);
}
}
calling start service
MaterialButton(
onPressed: () async {
var service = FlutterBackgroundService();
if (await service.isRunning()) {
service.invoke("stopService");
} else {
initializeService();
}
},
color: Colors.blue,
child: const Text(
"Start Service",
style: TextStyle(color: Colors.white),
)),
I have managed by writing line twice
service.on('stopService').listen((event) {
service.stopSelf();
service.stopSelf();
});