如何通过自身停止服务? [英] How to stop service by itself?
问题描述
我开始一个活动服务,然后我希望服务一段时间后自行停止。
I start a service in an activity then I want the service to stop itself after awhile.
我在服务名为stopSelf(),但它好好尝试一下工作。
I called stopSelf() in the service but it doens't work.
如何让服务站本身?谢谢!
how to make the service stop itself? thanks!!!
推荐答案
通过说不行,我猜你的意思是,的onDestroy()
-method该服务不会被调用。
By saying "doesn't work", I guess you mean that the onDestroy()
-method of the service is not invoked.
我有同样的问题,因为我bound一些<一href="http://developer.android.com/reference/android/content/ServiceConnection.html">ServiceConnection服务本身使用标志<一href="http://developer.android.com/reference/android/content/Context.html#BIND_AUTO_CREATE">BIND_AUTO_CREATE. 这会导致更让服务,直到每个连接<一个href="http://developer.android.com/reference/android/content/Context.html#unbindService%28android.content.ServiceConnection%29">unbound.
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.
在我改为使用无标志(零),我没有问题,自行查杀服务( stopSelf()
)。
Once I change to use no flag (zero), I had no problem killing the service by itself (stopSelf()
).
例如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.
这篇关于如何通过自身停止服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!