简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM