How to stop service by itself?

前端 未结 11 1125
独厮守ぢ
独厮守ぢ 2020-12-02 14:10

I start a service in an activity then I want the service to stop itself after a while.

I called stopSelf() in the service but it doesn\'t work.

How to make t

相关标签:
11条回答
  • 2020-12-02 14:45

    Use stopSelf() to stop a service from itself.

    0 讨论(0)
  • 2020-12-02 14:48

    If by "doesn't work" you mean the process doesn't get killed, then that's how android works. The System.exit(0) or Process.killProcess(Process.myPid()) will kill your process. But that's not the Android way of doing things.

    HTH

    0 讨论(0)
  • 2020-12-02 14:49

    By saying "doesn't work", I guess you mean that the onDestroy()-method of the service is not invoked.

    I had the same problem, because I bound some ServiceConnection to the Service itself using the flag BIND_AUTO_CREATE. This causes the service to be kept alive until every connection is unbound.

    Once I change to use no flag (zero), I had no problem killing the service by itself (stopSelf()).

    Example code:

    final Context appContext = context.getApplicationContext();
    final Intent intent = new Intent(appContext, MusicService.class);
    appContext.startService(intent);
    ServiceConnection connection = new ServiceConnection() {
      // ...
    };
    appContext.bindService(intent, connection, 0);
    

    Killing the service (not process):

    this.stopSelf();
    

    Hope that helped.

    0 讨论(0)
  • 2020-12-02 14:50

    I know this is an old question, but in my case (floating window as service) I had to remove the view first, and then call stopSelf().

    windowManager.removeView(floatingView);
    stopSelf();
    
    0 讨论(0)
  • 2020-12-02 14:57

    Another dirty hack not mentioned here is to throw an exception like NPE. One day I needed to stop InputMethodService and this hack was useful.

    0 讨论(0)
  • 2020-12-02 14:59
       stopForeground(true);
                stopSelf();
    
    0 讨论(0)
提交回复
热议问题