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条回答
\"骚年 ilove
2楼-- · 2020-02-28 00:40

I had this problem and searching I found this thread. My app's problem is that when service calls stopSelf(), the foreground activity that binds the service is still running. Thne stopSelf is called but the service is not destroyed as the foreground activity is still bound. When I leave the activity by pressing back or going to home screen, then the service is destroyed. In short, stopSelf won't work when a foreground activity is bound.

查看更多
家丑人穷心不美
3楼-- · 2020-02-28 00:45
Emotional °昔
4楼-- · 2020-02-28 00:45

I was facing same problem too.

As we all know that Service runs on App's UI Thread. So, until you've Thread that is running in background in your service and you are calling stopSelf() then it won't work. For that you have to stop that Thread first and then execute stopSelf().

After stoping all background Thread from your Service stopSelf() method will definitely work.

查看更多
我欲成王,谁敢阻挡
5楼-- · 2020-02-28 00:49

if you both called startService and bindService.you should unbindService frist,otherwish the stopSelf will not work.

查看更多
Viruses.
6楼-- · 2020-02-28 00:53

The only way I have found to stop a service with certainty is to use:

android.os.Process.killProcess(android.os.Process.myPid());

This behavior can be caused by using worker threads that have not finished when the stopSelf is called. If you are using worker threads, be careful how you employ this - you may leak memory if you don't clean up before executing the line.

查看更多
爷、活的狠高调
7楼-- · 2020-02-28 00:56

If you use a foreground service, you should call:

stopForeground(true);

Just like you start it with startForeground.

stopSelf is meant to be used for normal services. a foreground service is special... :)

By the way, in case your app should work on older devices, you should check the compatibility code offered here.

查看更多
登录 后发表回答