title: How to run a Service always in background (Non-Stop) - Android
body: <p>I have created a <code>Service</code> in my android application which starts running on <code>BOOT_COMPLETE</code>. I want to run my <code>Service</code> non-stop (run always), and for that I have used <code>while(true)</code> inside <code>onStartCommand()</code> method. So is this fine to use <code>while(true)</code> or there is any other better way to run a service always in background?</p>
  
  <p><strong>This is code of my Service:</strong></p>
  
  <pre><code>package com.example.abc.project1;
  
  import android.app.Service;
  import android.content.Intent;
  import android.os.IBinder;
  import org.json.*;
  import java.io.*;
  import java.net.*;
  import java.util.*;
  
  
  public class HelloService extends Service {
  
      private static final String TAG = "HelloService";
      private boolean isRunning  = false;
  
      @Override
      public IBinder onBind(Intent arg0) {
          return null;
      }
  
      @Override
      public void onCreate() {
          super.onCreate();
          isRunning = true;
      }
  
  
      @Override
      public int onStartCommand(Intent intent, int flags, int startId) {
          new Thread(new Runnable() {
              @Override
              public void run() {
                  while(true) {
                      /*non-stop work to be done in background always*/
                  }
              }
          }).start();
          return Service.START_STICKY;
      }
  
  
      @Override
      public void onDestroy() {
          isRunning = false;
      }
  
  }
  </code></pre>