title: Stop background Service When application goes to background
body: <p>I have background service in my android app,i start service from  MainActivity onResume() method and it is work correctly.But how can i stop service when user press home button.Because currently when user press home button then application move to background and then user open some other app then after some time my service method is called and app force stop.Below is my code for start service - </p>
  
  <pre><code>Intent msgIntent = new Intent(mContext, MyBackgroundService.class);
          startService(msgIntent);
  </code></pre>
  
  <p>Thanks in Advance.</p>
  
  <p><strong>EDITED</strong></p>
  
  <p>In My Service i use below code - </p>
  
  <pre><code> public void callAsynchronousTask() {
  final Handler handler = new Handler();
  timer = new Timer();
  TimerTask doAsynchronousTask = new TimerTask() {       
      @Override
      public void run() {
          handler.post(new Runnable() {
              public void run() {       
                  try {
                      callWebservice();
                  } catch (Exception e) {
                      e.printStackTrace();
                  }
              }
          });
      }
  };
  timer.schedule(doAsynchronousTask, START_DELAY, DELAY);
   }
  
  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
      callAsynchronousTask();
      return Service.START_NOT_STICKY;
  }
  
  @Override
  public void onCreate() {
      mContext = this;
      super.onCreate();
  }
  
  @Override
  public IBinder onBind(Intent intent) {
      return null;
  }
  
  @Override
  public void onDestroy() {
      super.onDestroy();
      if(timer!=null){
          timer.cancel();
      }
      stopSelf();
  }
  </code></pre>
  
  <p>in my activity i use below code for stop service -</p>
  
  <pre><code>@Override
  protected void onStop() {
      try{
           stopService(new Intent(this, MyBackgroundService.class));
           isServiceRunning = false;
      }
     catch(Exception e){
      e.printStackTrace();
     }
      super.onStop();
  }
  
  @Override
  protected void onPause() {
      try{
           stopService(new Intent(this, MyBackgroundService.class));
           isServiceRunning = false;
      }
      catch(Exception e){
          e.printStackTrace();
      }
      super.onPause();
  }
  </code></pre>
  
  <p>but my service is run while i use some other app and it force stop app.From background service i call some webservice and then store response of service in database.</p>