Service works properly on Android 9 and above facing issues on devices 8<= Notification disappears in some duration and location services stops
I have also disabled battery optimization but it did not work
Is there anyway to perform background services on android 8 and below My Code
@pragma('vm:entry-point')
Future<void> onStart(ServiceInstance service) async {
// Only available for flutter 3.0.0 and later
DartPluginRegistrant.ensureInitialized();
final DatabaseService databaseService = DatabaseService();
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();
});
final stream = Geolocator.getPositionStream(
locationSettings: const LocationSettings(
accuracy: LocationAccuracy.high,
distanceFilter: 0,
timeLimit: Duration(seconds: 10)
),
).listen((position) async {
if (kDebugMode) {
print('Position : $position');
}
flutterLocalNotificationsPlugin.show(
notificationId,
'COOL SERVICE',
position.latitude.toString() + position.longitude.toString() + DateTime.now().toString(),
const NotificationDetails(
android: AndroidNotificationDetails(
notificationChannelId,
'MY FOREGROUND SERVICE',
icon: 'ic_bg_service_small',
ongoing: true,
),
),
);
var now = DateTime.now();
//Month is capital MM to distinct 'minute and month'
//HH means 24 hour format
var formatter = DateFormat('yyyy-MM-dd HH:mm:ss');
var route = MapRoute(createdAt:formatter.format(now),latitude: position.latitude, longitude: position.longitude);
try {
await databaseService.insertBreed(route);
} catch (e) {
if (kDebugMode) {
print(e);
}
}});
}
Thankyou
I found the solution to make Background services work on Android Devices less than 9. I had to disable AllBatteryOptimzation for current app.
Do this
DisableBatteryOptimization.showDisableAllOptimizationsSettings('App Process', 'Enable App Battery Usage', 'Battery Optimization', 'Enable process');
Instead of this
DisableBatteryOptimization.showDisableBatteryOptimizationSettings();