How to stop Android service when app is closed

雨燕双飞 提交于 2020-07-04 06:22:14

问题


I'm trying to keep service running continously until user close app.

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?


回答1:


Set the below attribute in your service tag in the manifest file,

<service android:name="service" android:stopWithTask="true"/>

adding this will call the ondestroy() of the service when the task is removed (app closed from recent apps list).




回答2:


I mean intentional app close. After user swipe out app on "recent apps" screen.

That is not "closing the app", in terms of Android. That is "removing the task" (or sometimes "stopping the task" -- Google is not very consistent on the terminology).

Your service should be called with onTaskRemoved() when the task is removed. However, that should be both when the user manually removes the task via the overview screen (a.k.a., recent-tasks list) and when the task naturally goes away on Android 4.4 and below because the task is too old.




回答3:


Start by adding the android:configChanges node to your Activity's manifest node for stoping restart activity when device rotate.

android:configChanges="keyboardHidden|orientation"

Now for detecting a closing application event, think the ways user can close app manually. In android, by pressing a back button or home button. So put an event key listener for back & home button and terminate the service.



来源:https://stackoverflow.com/questions/29323317/how-to-stop-android-service-when-app-is-closed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!