title: how to detect when android app in background and foreground to handle some code
body: <p>I need to know when user send my android app to background and then bring it back to foreground</p>
  
  <p>when user send app to background I should perform server call and when back to foreground I have to clear some data </p>
  
  <p>I have implemented it in the following way </p>
  
  <pre><code>public class MyApplication implements Application.ActivityLifecycleCallbacks {
  
  @Override
      public void onActivityStopped(final Activity activity) {
  
  // my logic goes here
  }
  }
  </code></pre>
  
  <p>but this way make a lot of ANRs in background, and when I put my logic inside AsyncTask it does not work and also it close app in background</p>
  
  <p>can any one advice me how to meet my requirement in another way without generating ANR's</p>