How to stop service by itself?

前端 未结 11 1224
独厮守ぢ
独厮守ぢ 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: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.

提交回复
热议问题