StopSelf does not stop my service

2020-02-28 00:03发布

Googling around, I have seen this problem posted many times, some of the posts on this forum over that last few years. I have never seen anyone get a straight answer.

I have a foreground service that tries to stop itself after running for 2 hours by doing a this.StopSelf(). I've tried it when it's bound and when it's unbound. On the AVD and on a device.

It simply does not work. Is this a bug in Android? (running 2.3.3).

How can a service stop itself?

8条回答
叼着烟拽天下
2楼-- · 2020-02-28 00:57

I encounter this issue of selfStop() that not working too.

The main idea to understand is that the Service WILL NOT stop,

if a running loop is still running (while(mDoWhile) for example).

Or any other issue that need to be destroyed / unregistered first.

So to make the stopSelf() or stopService(intent) works,

implement onDestroy() within your service:

@Override
public void onDestroy()
{
    // Unregistered or disconnect what you need to
    // For example: mGoogleApiClient.disconnect();

    // Or break the while loop condition
    // mDoWhile = false;

    super.onDestroy();
}
查看更多
Evening l夕情丶
3楼-- · 2020-02-28 01:01

stopSelf might not destroy the service if the conditions are not favorable, but you can stopService with the application context. But make sure the service doesn't restart before calling stopService inside service.

stopService(applicationContext, MyService::class.java)
查看更多
登录 后发表回答