paul_f
paul_f

Reputation: 1375

Location while in background Android Oreo

I want to build an app like Run Keeper for tracking while out on an actitivty. What is the best way to track the users location while the phone is locked for example. The user will explicitly start the activity and will perhaps lock and unlock there phone to see there progress along the way. This was relatively straight forward before oreo but now my original code will no longer function and the app stops recording location after a few minutes.

At the moment I am registering a service.

startService(Intent(this, EWLocationService::class.java))

I am calling foreground in the Service with a notification:

startForeground(1, notification)

I am sending back locations to the main app through a broadcast where the app can both add the location to the map and save it to Room database.

This worked fine before, but it does not work now. What should I do to achieve the desired functionality?

Upvotes: 0

Views: 398

Answers (2)

Ramees Thattarath
Ramees Thattarath

Reputation: 1093

For Oreo and above you must call ContextCompat.startForegroundService(this, serviceIntent); while launching the service instead of startService(serviceIntent)

source code inside ContextCompat looks like this

/**
 * startForegroundService() was introduced in O, just call startService
 * for before O.
 *
 * @param context Context to start Service from.
 * @param intent The description of the Service to start.
 *
 * @see Context#startForegroundService(Intent)
 * @see Context#startService(Intent)
 */
public static void startForegroundService(@NonNull Context context, @NonNull Intent intent) {
    if (Build.VERSION.SDK_INT >= 26) {
        context.startForegroundService(intent);
    } else {
        // Pre-O behavior.
        context.startService(intent);
    }
}

And inside the service you must call startForeground(int id, Notification notification) as soon as service starts

Upvotes: 1

lazy
lazy

Reputation: 173

You should read oreo update related files.

By default, these changes only affect apps that target Android 8.0 (API level 26) or higher. However, users can enable these restrictions for any app from the Settings screen, even if the app targets an API level lower than 26. You may need to update your app to comply with the new limitations.

Check to see how your app uses services. If your app relies on services that run in the background while your app is idle, you will need to replace them. Possible solutions include:

If your app needs to create a foreground service while the app is in the background, use the startForegroundService() method instead of startService().

If you want to know more about https://developer.android.com/about/versions/oreo/background

Upvotes: 0

Related Questions