title: How to execute background task when Android app is closed / set to background?
body: <p>My Android 4+ app is connected to a custom web service that is used to sync data every few minutes. To make sure, that the online data is always up to date, I want to trigger the sync when ever the app is closed / send to background.</p>
  
  <p>Under iOS this is quite easy: </p>
  
  <ul>
  <li>Listen to <code>applicationDidEnterBackground:</code> in the AppDelegate</li>
  <li>Use <code>beginBackgroundTaskWithName:</code> to start you long running background task and to avoid being suspended while the task is still running</li>
  </ul>
  
  <p><strong>How to do this on Android?</strong></p>
  
  <p><strong>First problem</strong> is, that there is nothing equivalent to <code>applicationDidEnterBackground:</code>. All solution I found so far propose to use the main Activities <code>onPause()</code> method. However this called any time the main <code>Activity</code> is paused, which is also the case when another <code>Activity</code> is started within the app. The is true for the <code>onActivityPaused()</code> method from <code>ActivityLifecycleCallbacks</code> interface.</p>
  
  <p>So, how to detect that the <strong>app</strong> (not just an <code>Activity</code>) is closed or send to the background?</p>
  
  <p><strong>Second problem</strong> is, that I did not find any information on how to run background task. All solutions point to simply start an <code>AsyncTask</code>, but is this really the correct solution?</p>
  
  <p><code>AsyncTask</code> will start a new task, but will this task also run, when the app is closed/inactive? What do I have to do, to prevent the app and the task from being suspended after a few seconds? How can I make sure, that the task can complete, before the app is completely suspended?</p>