Search code examples
androidperformanceandroid-locationandroid-8.0-oreo

Will startService() still work if my app targeting nougat devices


This is how i start Location service.

private void initLocationService() {

    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    if(getPermissions(android.Manifest.permission.ACCESS_FINE_LOCATION,GET_LOCATION_PERMISSION)){
        startService(new Intent(HomeActivity.this, LocationUpdateService.class));
    }
}

and in LocationUpdateService, i start it as STICKY service. So it keeps working in the background.

public class LocationUpdateService extends Service implements
        LocationListener,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        IServiceResponse {


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "onStartCommand: ");
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(BACKGROUND_INTERVAL);
        mLocationRequest.setFastestInterval(BACKGROUND_INTERVAL);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

        super.onStartCommand(intent, flags, startId);
        return START_STICKY;
    }

As my app is currently targeting Api 25 (Nougat), what changes do i need to make in this particular service to make this work in Oreo

I still don't have access to startForegroundService() method when using compileSdkVersion 25.

These are my gradle settings.

compileSdkVersion 25
buildToolsVersion "25.0.3"

defaultConfig {

    minSdkVersion 21
    targetSdkVersion 25
}

Solution

  • startForegroundService() is available form API level 26 NOT from API level 25.

    Change compileSdkVersion 25 and buildToolsVersion "25.0.3" to latest it and try.

    For example, in my case I am using below:

    compileSdkVersion 26
    buildToolsVersion '27.0.3'