How to execute code before Android app is killed

允我心安 提交于 2019-12-01 05:23:56

问题


I have an Android app that connects to surrounding devices currently running the same app, even if in background.

To do this, I use WiF-Direct to advertise the fact that I am currently running said application.

Therefore I need to stop advertising this as soon as the app is killed.

  • onDestroy() cannot be used since it is not guaranteed to be called.
  • onStop() and onPause() cannot be used since the app is still running.

How can I achieve this?

Currently the service is still being advertised even when the application is closed/killed.


回答1:


You should be able to do this with a Service.

Start a service when your app was started. Override the onTaskRemoved method

@Override
public void onTaskRemoved(Intent rootIntent)
{
}

In this method do what you have to do. More detailed answer can be found here: How to know when my app has been killed? (2 answer)




回答2:


The best implementation might be to have another service running that queries the your app is in foreground(i.e. running)

You can run the query to check periodically say every 60 sec. Then if the app isn't running. You can stop the WiFi Direct service and subsequently stop self.



来源:https://stackoverflow.com/questions/37615791/how-to-execute-code-before-android-app-is-killed

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