应用关闭时如何停止Android服务 [英] How to stop Android service when app is closed
问题描述
我正在尝试保持服务连续运行,直到用户关闭应用为止.
I'm trying to keep service running continously until user close app.
我正在使用主要活动的onCreate()
方法中的startService()
方法,并且使用onDestroy()
方法中的stopService()
.
I'm using startService()
method from onCreate()
method of my main activity and stopService()
in onDestroy()
method.
现在我遇到了问题,因为当我旋转设备或关闭屏幕时,我的主要活动似乎已经死掉并重新创建了.
Now I have problem, because it seems that my main activity dies and is re-created when I rotate device or when I turn off screen.
仅当用户手动停止应用程序时,如何才能停止服务?
How can I stop my service only when user stops app manually?
推荐答案
在清单文件的服务标签中设置以下属性,
Set the below attribute in your service tag in the manifest file,
<service android:name="service" android:stopWithTask="true"/>
添加此内容将在任务删除(从最近的应用程序列表中关闭应用程序)时调用服务的ondestroy()
.
adding this will call the ondestroy()
of the service when the task is removed (app closed from recent apps list).
这篇关于应用关闭时如何停止Android服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!