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!