Arundale Ramanathan
Arundale Ramanathan

Reputation: 2069

OnDestroy not being called for background Service in Android

I am facing similar problem as

Not sure if service onDestroy is called from BroadcastReceiver

Since it has not been answered, I am creating new question. My Service code looks like below (full code not pasted):

public class GPSLogger extends Service implements LocationListener,
        com.google.android.gms.location.LocationListener,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener {

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(GPSLogger.TAG, "StartAtBootService -- onStartCommand()");
        // lot of init code
        if (isGooglePlayServicesAvailable()) {
            mLocationRequest = LocationRequest.create();
            mLocationRequest.setInterval(freq);
            mLocationRequest.setFastestInterval(freq / 4);
            mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            return START_STICKY;
        }
    }

    @Override
    public void onDestroy() {
        Util.sendNotification("Service", "OnDestroy", this, 100);
        stopLocationUpdates();
        DBHelper.closeDb();
        Log.i(GPSLogger.TAG, "StartAtBootService Destroyed");
        Intent broadcastIntent = new Intent("cc.siara.gpslogger.RestartService");
        sendBroadcast(broadcastIntent);
        super.onDestroy();
    }

}

I can see from the ADB Log that the OS starts the service several times and calls onStartCommand. But I can't find "StartAtBootService Destroyed" even once.

The device I am testing on is Samsung SM-J120G Android 5.1.1 API 22.

I know Android stops services once a while to release memory. But is there anyway I can run my cleanup code when Android does so?

Upvotes: 0

Views: 396

Answers (1)

Ragesh Ramesh
Ragesh Ramesh

Reputation: 3520

onDestroy will be called in the following scenarios -

  1. When you stop self from the service.

  2. When the os runs out of memory and decides to stop your app.

  3. When you call stop service through an intent from activity or broadcast receiver.

Upvotes: 1

Related Questions