2017-08-26 37 views
0
后台服务

我面临着类似的问题,因为的onDestroy没有被要求在Android的

Not sure if service onDestroy is called from BroadcastReceiver

因为它没有得到答复,我创建了新的问题。我的服务代码看起来像下面(完整的代码不粘贴):

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(); 
    } 

} 

我可以从亚行日志中看到该操作系统启动服务几次,并呼吁onStartCommand。但是我找不到“StartAtBootService销毁”一次。

我测试上的设备是三星SM-J120G的Android 5.1.1 API 22

我知道Android的停止服务一次,一段时间来释放内存。但是,无论如何,Android可以运行我的清理代码吗?

回答

1

的onDestroy将被称为在以下情况下 -

1.当您从服务停止自我。

2.当OS耗尽内存并决定停止您的应用程序时。

3.当您通过活动或广播接收者的意图呼叫停止服务时。

+0

好的,我不会自己或通过意向来阻止它。我的场景是你提到过的No.2 ..但仍然onDestroy似乎没有被调用。其他人在我的问题中遇到同样的问题。 –

+1

#2是错误的,它不会运行onDestroy,它只会杀死跳过onDestroy的服务/活动。 –

+0

如果是这样,有没有其他方式可以清理/关闭#2的情况? –

相关问题