title: Background Service getting killed in android
body: <p>We have developed an Android Application which involves a service in the background. To implement this background service we have used <code>IntentService</code>. We want the application to poll the server every <code>60 seconds</code>. So in the <code>IntentService</code>, the server is polled in a while loop. At the end of the while loop we have used <code>Thread.sleep(60000)</code> so that the next iteration starts only after 60 seconds.<bR> But in the <code>Logcat</code>, I see that sometimes it takes the application more than 5 minutes to wake up (come out of that sleep and start the next iteration). It is never <code>1 minute</code> as we want it to be.</p>
  
  <p>What is the reason for this? Should background Services be implemented in a different way?</p>
  
  <p><strong>Problem2</strong></p>
  
  <p>Android kills this background process (intent service) after sometime. Can't exactly say when. But sometimes its hours and sometimes days before the background service gets killed. I would appreciate it if you would tell me the reason for this. Because Services are not meant to be killed. They are meant to run in background as long as we want it to.</p>
  
  <p><strong>Code :</strong></p>
  
  <pre><code>@Override
   protected void onHandleIntent(Intent intent) {
    boolean temp=true;
    while(temp==true) {
      try {
        //connect to the server 
        //get the data and store it in the sqlite data base
      }
      catch(Exception e) {
        Log.v("Exception", "in while loop : "+e.toString());
      }
      //Sleep for 60 seconds
      Log.v("Sleeping", "Sleeping");
      Thread.sleep(60000);
      Log.v("Woke up", "Woke up");
  
      //After this a value is extracted from a table
      final Cursor cur=db.query("run_in_bg", null, null, null, null, null, null);
      cur.moveToLast();
      String present_value=cur.getString(0);
      if(present_value==null) {
         //Do nothing, let the while loop continue  
      }
      else if( present_value.equals("false") || present_value.equals("False") ) {
         //break out of the while loop
         db.close();
         temp=false;
         Log.v("run_in_bg", "false");
         Log.v("run_in_bg", "exiting while loop");
         break;
      }
    }
  
  }
  </code></pre>
  
  <p>But whenever the service is killed, it happens when the the process is asleep. The last log reads - <code>Sleeping : Sleeping</code>. Why does the service gets killed?</p>