简体   繁体   English

Android中未调用OnDestroy作为后台服务

[英]OnDestroy not being called for background Service in Android

I am facing similar problem as 我面临着类似的问题

Not sure if service onDestroy is called from BroadcastReceiver 不知道是否从BroadcastReceiver调用了服务onDestroy

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. 从ADB日志中可以看到,操作系统多次启动了该服务,并调用了onStartCommand。 But I can't find "StartAtBootService Destroyed" even once. 但是我什至找不到“ StartAtBootService被销毁”。

The device I am testing on is Samsung SM-J120G Android 5.1.1 API 22. 我正在测试的设备是Samsung SM-J120G Android 5.1.1 API 22。

I know Android stops services once a while to release memory. 我知道Android会偶尔停止服务以释放内存。 But is there anyway I can run my cleanup code when Android does so? 但是,无论如何,Android可以运行清理代码吗?

onDestroy will be called in the following scenarios - 在以下情况下,将调用onDestroy:

  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. 当您通过活动或广播接收者的意图呼叫停止服务时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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