In Android O (8.0.0+) (API 26+), How to get a location services update when the app is in the background or kill. In "Strava" Android App (Available on Play Store), location services run properly when the app is in the background or kill. I need to build same functionality in my app. Whenever I start service using
startService(new Intent(this, GpsServices.class));
Then the onDestroy method is called after 10 sec when an app is an idle mode (the app is in the background or kill). Below is my code.
public class GpsServices extends Service implements LocationListener, Listener {
@Override
public void onCreate() {
mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
if (mLocationManager != null) {
mLocationManager.addGpsStatusListener(this);
}
if (mLocationManager != null) {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
500,
0,
this);
}
}
public void onLocationChanged(Location location) {
System.out.println("location = [" + location + "]");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// If we get killed, after returning from here, restart
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
// We don't provide binding, so return null
return null;
}
/* Remove the locationlistener updates when Services is stopped */
@Override
public void onDestroy() {
try {
mLocationManager.removeUpdates(this);
mLocationManager.removeGpsStatusListener(this);
stopForeground(true);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Any help would be appreciated.