Why is my foreground service killed by Android System?

Viewed 949

My app is a tracking app where I want to track user location in a service and then display every location in a fragment. I have a problem with background service: my service is stopped after some minutes (sometimes < 10 minutes, sometimes > 30 minutes). I start my location service in this fragment and everything goes fine when I use my app. The problem is when I close (not kill) my app and start something else on my phone (or just block it), after a few minutes my service is stopped and I don't know why. I show a foreground notification when my service is running but android system still stops it, I notice this because my notification disappear and my app restarts.

Here is my code for the service:

public class LocationService extends Service {

private static final String TAG = "LocationService";
public static final String NEW_VALUE_INTENT_ACTION = "service_new_value";
public static final String INTENT_LATITUDE = "latitude";
public static final String INTENT_LONGITUDE = "longitude";
public static final String INTENT_SPEED = "speed";
public static final String INTENT_ACCURACY = "accuracy";
private static final long TWO_MINUTES = 1000 * 60 * 2;
private static final long INTERVAL = 5000;
private static final long FASTEST_INTERVAL = 2000;
private int ONGOING_NOTIFICATION = 1111;

private Location currentLocation;
NotificationCompat.Builder builder = null;

private LocationRequest mLocationRequest;

/**
 * Provides access to the Fused Location Provider API.
 */
private FusedLocationProviderClient mFusedLocationClient;

/**
 * Callback for changes in location.
 */
private LocationCallback mLocationCallback;

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

@Override
public void onCreate() {
    Log.d(LocationService.TAG, "LocationService ---> onCreate()");
    super.onCreate();
}

@Override
public void onDestroy() {
    Log.d(LocationService.TAG, "LocationService ---> onDestroy()");
    super.onDestroy();
    stopForeground(true);
     mFusedLocationClient.removeLocationUpdates(mLocationCallback);

}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d(LocationService.TAG, "LocationService ---> onStartCommand()");
    startServiceTask();
    return super.onStartCommand(intent, flags, startId);
}

@Override
public boolean onUnbind(Intent intent) {
    Log.d(LocationService.TAG, "LocationService ---> onUnbind()");
    return super.onUnbind(intent);
}

private void startServiceTask() {
    Log.d(LocationService.TAG, "GpsService ---> Starting ...");

    setServiceAsForeground();

    initFusedLocationProvider();

    Log.d(LocationService.TAG, "MyStartedService ---> Starting ...");


}

private void initFusedLocationProvider() {
    mFusedLocationClient = new FusedLocationProviderClient(this);

    mLocationRequest = new LocationRequest();

    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    mLocationRequest.setInterval(INTERVAL);
    mLocationRequest.setFastestInterval(FASTEST_INTERVAL);

    mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback = new LocationCallback() {
        @Override
        public void onLocationResult(LocationResult locationResult) {
            super.onLocationResult(locationResult);
            if (currentLocation == null)
                currentLocation = locationResult.getLastLocation();

            else if (isBetterLocation(locationResult.getLastLocation(), currentLocation)) {
                Log.d(TAG, "onLocationChanged(): Updating Location ... " + currentLocation.getProvider());
                currentLocation = locationResult.getLastLocation();
        }
            notifyValueUpdate();
    } }, getMainLooper());
}


protected boolean isBetterLocation(Location location, Location currentBestLocation) {
    if (currentBestLocation == null) {
        // A new location is always better than no location
        return true;
    }

    // Check whether the new location fix is newer or older
    long timeDelta = location.getTime() - currentBestLocation.getTime();
    boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
    boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
    boolean isNewer = timeDelta > 0;

    // If it's been more than two minutes since the current location, use
    // the new location
    // because the user has likely moved
    if (isSignificantlyNewer) {
        return true;
        // If the new location is more than two minutes older, it must be
        // worse
    } else if (isSignificantlyOlder) {
        return false;
    }

    // Check whether the new location fix is more or less accurate
    int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation
            .getAccuracy());
    boolean isLessAccurate = accuracyDelta > 0;
    boolean isMoreAccurate = accuracyDelta < 0;
    boolean isSignificantlyLessAccurate = accuracyDelta > 200;

    // Check if the old and new location are from the same provider
    boolean isFromSameProvider = isSameProvider(location.getProvider(),
            currentBestLocation.getProvider());

    // Determine location quality using a combination of timeliness and
    // accuracy
    if (isMoreAccurate) {
        return true;
    } else if (isNewer && !isLessAccurate) {
        return true;
    } else if (isNewer && !isSignificantlyLessAccurate
            && isFromSameProvider) {
        return true;
    }
    return false;
}

/** Checks whether two providers are the same */
private boolean isSameProvider(String provider1, String provider2) {
    if (provider1 == null) {
        return provider2 == null;
    }
    return provider1.equals(provider2);
}

private void setServiceAsForeground() {
    Log.d(LocationService.TAG, "GpsService ---> setServiceAsForeground()");

    // Prepare the intent triggered if the notification is selected
    Intent intent = new Intent(this, LocationService.class);
    PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);

    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    builder = null;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        int importance = NotificationManager.IMPORTANCE_LOW;
        NotificationChannel notificationChannel = new NotificationChannel("ID", "Name", importance);
        notificationManager.createNotificationChannel(notificationChannel);
        builder = new NotificationCompat.Builder(getApplicationContext(), notificationChannel.getId());
    } else {
        builder = new NotificationCompat.Builder(getApplicationContext());
    }

    Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        v.vibrate(VibrationEffect.createOneShot(500, VibrationEffect.DEFAULT_AMPLITUDE));
    } else {
        //deprecated in API 26
        v.vibrate(500);
    }
    // Build the notification
    // Use NotificationCompat.Builder instead of just Notification.Builder to support older Android versions
    Notification notification = builder.setContentTitle("MyMovements")
            .setContentText("Running ...")
            .setSmallIcon(getNotificationIcon())
            .setBadgeIconType(getNotificationIcon())
            .setContentIntent(pIntent)
            .setAutoCancel(true).build();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        startForeground(ONGOING_NOTIFICATION, notification, FOREGROUND_SERVICE_TYPE_LOCATION);
    }
    else {
        startForeground(ONGOING_NOTIFICATION,notification);
    }
}

private int getNotificationIcon(){

    SharedPreferences settings = this.getSharedPreferences(MainActivity.PREFERENCE,0);
    String icon = settings.getString(MapFragment.NOTIFICATION_PREF, " ");
    switch (icon) {
        case "Walking":
            return R.drawable.walk;
        case "Public Transportation":
            return R.drawable.bus;
        case "Driving":
            return R.drawable.car;
        default:
            return 0;
    }
}

private void updateNotification(){
    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    String conc = "Running...\n" + "Lat: " + currentLocation.getLatitude() + " " + "Lng: " + currentLocation.getLongitude();
    Notification notification = builder.setStyle(new NotificationCompat.BigTextStyle()
            .bigText(conc))
            .setContentText(conc).build();
    notificationManager.notify(ONGOING_NOTIFICATION, notification);
}

private void notifyValueUpdate(){
    Log.d(TAG, "MyStartedService ---> notifyValueUpdate()");

    if(currentLocation != null) {
        updateNotification();
        Log.d(LocationService.TAG, currentLocation.getProvider());
        Intent broadcastIntent = new Intent();
        broadcastIntent.setAction(NEW_VALUE_INTENT_ACTION);

        Bundle bundle = new Bundle();
        bundle.putDouble(INTENT_LATITUDE, currentLocation.getLatitude());
        bundle.putDouble(INTENT_LONGITUDE, currentLocation.getLongitude());
        bundle.putDouble(INTENT_SPEED, currentLocation.getSpeed()*3.6);
        bundle.putDouble(INTENT_ACCURACY, currentLocation.getAccuracy());
        broadcastIntent.putExtras(bundle);

        LocalBroadcastManager.getInstance(this).sendBroadcast(broadcastIntent);
    }
}

}

I started my service in OnServiceCommand() -> startServiceTask() -> setServiceAsForeground()

I will really appreciate any tips for my code (this is a scholar project and this is my first app, so probably I am doing something wrong).

Thanks to everyone

0 Answers
Related