0

I am developing an app which tracks the user location. I've implemented a custom Service which manages the location request part and it works fine in every Activity. The service even appears in 'Running Services' settings panel.

The problem starts when I minimize the app or lock the screen.

My desired effect would be to keep receiving location updates even when the app is minimized or the screen is locked, but stop everything app related when the user swipes the app from Recent Apps (exactly how Google Maps or Waze behaves - displaying a notification when the app is minimized - with the possibility to close the app straight from the notification).

I've already tried a lot of the suggested solutions, and the only one which ever came close was startForegroundService(), but that doesn't stop the service even if the app is dismissed.

I am running tests on a Google Pixel (8.1) and emulators with 5.0 and 8.0.

Min SDK version: 21. Target SDK version: 26.

This is my code so far:

AndroidManifest.xml

<service android:name=".logic.service.LocationService"/>

MainActivity.java

if (checkNeedLocationPermission(this)) {
        startService(new Intent(getBaseContext(), LocationService.class));
    }

LocationService.java

public class LocationService extends Service {

private FusedLocationProviderClient fusedLocationProviderClient;
private LocationRequest locationRequest;
private LocationCallback locationCallback;

@Override
public IBinder onBind(final Intent intent) {
    return null;
}

@Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
    startFusedLocationProviderClient();
    return START_STICKY;
}

@Override
public void onDestroy() {
}

/**
 * Configures and starts Google Api Client for location services.
 */
private void startFusedLocationProviderClient() {
    fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

    getCurrentLocation();
}

/**
 * Gets the current location of the device.
 */
@SuppressLint("MissingPermission")
private void getCurrentLocation() {
    createLocationRequestAndCallback();

    fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, null);
}

/**
 * Creates the location request with the specified settings.
 */
private void createLocationRequestAndCallback() {
    locationRequest = new LocationRequest();
    locationRequest.setInterval(LOCATION_REQUEST_INTERVAL);
    locationRequest.setFastestInterval(LOCATION_REQUEST_FASTEST_INTERVAL);
    locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

    locationCallback = new LocationCallback() {
        @Override
        public void onLocationResult(final LocationResult locationResult) {
            for (Location location : locationResult.getLocations()) {
                Log.d("lat", String.valueOf(location.getLatitude()));
            }
        }
    };
}

In the class above, LocationService.java, Log.d("lat", String.valueOf(location.getLatitude())); stops logging when the app is minimized or the screen is locked.

Any help or suggestion will be appreciated!

Dima Kozhevin
  • 3,602
  • 9
  • 39
  • 52
RayzaN
  • 41
  • 1
  • 2
  • 6
  • Did you get any solution or should I paste my code ? Same scenario I had and I am getting everything fine. Do let me know – coder_baba Jan 10 '18 at 12:59
  • There's this: https://stackoverflow.com/questions/3856767/android-keeping-a-background-service-alive-preventing-process-death And this: https://stackoverflow.com/questions/30525784/android-keep-service-running-when-app-is-killed – Jonathon Reinhart Jan 10 '18 at 13:00
  • @nihal_softy He asked the question 7 minutes ago; he didn't get a solution already. Yes, you should write an answer, but Stack Overflow isn't just a code-sharing service. Don't simply dump your code - explain the solution, showing relevant snippets for details, and ideally including links to reference documentation. – Jonathon Reinhart Jan 10 '18 at 13:03
  • @JonathonReinhart I welcome your suggestion sir. I will try to explain here. Actually I also tried this but in my case its working fine... I don;t know Why He is getting issue – coder_baba Jan 10 '18 at 13:09
  • I don't have any working solution at this moment, but I'm trying some more suggestions. Also, android:stopWithTask="false" doesn't work for me. – RayzaN Jan 10 '18 at 13:58

1 Answers1

1

As of Android Oreo you can't do this as they have introduced background service limitations. Refer documentation

But for API level below 26 you can achieve this by setting

 <service
            android:name=".YourLocationService"
            android:exported="false"
            android:process=":YourLocationService"
            android:stopWithTask="false" />

and

@Override
    public void onTaskRemoved(Intent rootIntent) {

        Intent restartService = new Intent(getApplicationContext(), this.getClass());
        PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 1, restartService, PendingIntent.FLAG_ONE_SHOT);
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarmManager.set(AlarmManager.ELAPSED_REALTIME, 5000, pendingIntent);


    }
lakshman.pasala
  • 565
  • 6
  • 16