5

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.

Gett
  • 143
  • 1
  • 11
  • 1
    Do you have an extended Application class? – OneCricketeer Jun 03 '16 at 13:38
  • Can you check if the app is still running in WiFi Direct before broadcasting from it? – liminal Jun 03 '16 at 13:53
  • @liminal The service advertising is launched by the application itself when it launches. So it is obviously running at that time. It's a one time process, not a continuous one. – Gett Jun 03 '16 at 13:59
  • @cricket_007 Should I? – Gett Jun 03 '16 at 14:01
  • Do you `finish()` your main activity explicitly or let Android destroy it when the device is low on memory? If the former is true, I believe you can guarantee the onDestroy being called. – liminal Jun 03 '16 at 14:04
  • 1
    I don't know how the end user will kill it, it may "CLOSE ALL" apps, it may swipe it, etc... In any case I've tested it and onDestroy() is not always called. – Gett Jun 03 '16 at 14:09

2 Answers2

7

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)

Community
  • 1
  • 1
0

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.

ribads
  • 393
  • 3
  • 7
  • 1
    Another service running seems like a possible solution, but there should be something more efficient than just checking every so often if my app is still running. Thanks – Gett Jun 03 '16 at 13:56