In Oreo (8.0.0+) (API 26+), How to get a location services update when the app is in the background or kill

南楼画角 提交于 2019-11-28 16:35:10

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.

The key to solving this problem appears to be a notification generator. The following link describes a working solution better than I can summarize:

https://hackernoon.com/android-location-tracking-with-a-service-80940218f561

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!