title: How to execute code before Android app is killed
body: <p>I have an Android app that connects to surrounding devices <strong>currently running the same app</strong>, <strong>even if in background</strong>.</p>
  
  <p>To do this, I use WiF-Direct to advertise the fact that I am currently running said application.</p>
  
  <p>Therefore I need to stop advertising this as soon as the app is killed.</p>
  
  <ul>
  <li><code>onDestroy()</code> cannot be used since it is not guaranteed to be called.</li>
  <li><code>onStop()</code> and <code>onPause()</code> cannot be used since the app is still running.</li>
  </ul>
  
  <p>How can I achieve this?</p>
  
  <p>Currently the service is still being advertised even when the application is closed/killed.</p>