简体   繁体   中英

onDestroy of a service is never called

I add a local service to my MainActivity, in the onResume, I did this

@Override
public void onResume() {
    super.onResume()
    boolean is_start = isMyServiceRunning(MyService.class)
    if (is_start) {
        bindMyService()
    } else {
        startMyService()
        bindMyService()
    }
}

In onPause I just simply do the "unBindMyService" operation.

Also, I add the Context.BIND_AUTO_CREATE flag to bind the service, the result is very strange.

  1. I can see MyService's "onCreate" and "onBind" with logcat, this goes smoothly
  2. When I switch to another activity or app, The "Unbind" is called, which is correct!
  3. When I "force stop" the service in settings, the "onDestroy" of the Service is called in response, that is OK.
  4. When I remove the app from the "Recent List" of the apps, there are no "onDestroy" of the Service is called, I can explain it as that the service is not terminated. also OK.
  5. What I can't explain is that after 4, I launched my app again, I've noticed that the "onCreate" and "onBind" of the service is called, but without a single "onDestroy" of the Service. Even when "is_start" is true, the Service is created again without an "onDestroy" called.

So what happened between 4 and 5? The service is still alive or is dead?

you need to stop service to call onDestroy. Use this:

@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    stopService(new Intent(this,MyService.class));
}

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