You can try one of below two options or a combination of both, which have solved my problems when I have faced them.
Option 1
For location update to continue running in the background, you must use LocationServices
API with FusedLocationProviderClient
as described here and here in docs or here in CODEPATH.
Option 2
If you would have read the Android Oreo 8.0 Documentation properly somewhere in here, you would have landed on this solution.
Step 1: Make sure you start a service as a foreground service as given in below code
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
mainActivity.startService(new Intent(getContext(), GpsServices.class));
mainActivity.startService(new Intent(getContext(), BluetoothService.class));
mainActivity.startService(new Intent(getContext(), BackgroundApiService.class));
}
else {
mainActivity.startForegroundService(new Intent(getContext(), GpsServices.class));
mainActivity.startForegroundService(new Intent(getContext(), BluetoothService.class));
mainActivity.startForegroundService(new Intent(getContext(), BackgroundApiService.class));
}
Step 2: Use notification to show that your service is running. Add below line of code in onCreate
method of service.
@Override
public void onCreate() {
...
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForeground(NOTIFICATION_ID, notification);
}
...
}
Step 3: Remove the notification
when the service is stopped or destroyed.
@Override
public void onDestroy() {
...
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
stopForeground(true); //true will remove notification
}
...
}
One problem with Option 2 is that it will keep showing the notification
until your GpsService
is running on all devices running on Android Oreo 8.0.
I'm sure that both these options will work even when the app is in the background or in kill state.
I hope this solution might solve your problem.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…