title: How can I run code on a background thread on Android?
body: <p>I want some code to run in the background continuously. I don't want to do it in a service. Is there any other way possible? </p>
  
  <p>I have tried calling the <code>Thread</code> class in my <code>Activity</code> but my <code>Activity</code> remains in the background for sometime and then it stops. The <code>Thread</code> class also stops working.</p>
  
  <pre><code>class testThread implements Runnable {
          @Override
          public void run() {
              File file = new File( Environment.getExternalStorageDirectory(), "/BPCLTracker/gpsdata.txt" );
              int i = 0;
  
              RandomAccessFile in = null;
  
              try {
                  in = new RandomAccessFile( file, "rw" );
              } catch (FileNotFoundException e) {
  // TODO Auto-generated catch block
                  e.printStackTrace();
              } catch (IOException e) {
  // TODO Auto-generated catch block
                  e.printStackTrace();
              }
  //String line =null;
              while ( true ) {
                  HttpEntity entity = null;
                  try {
                      if ( isInternetOn() ) {
                          while ( ( line = in.readLine() ) != null ) {
  
                              HttpClient client = new DefaultHttpClient();
                              String url = "some url";
                              HttpPost request = new HttpPost( url );
                              StringEntity se = new StringEntity( line );
                              se.setContentEncoding( "UTF-8" );
                              se.setContentEncoding( new BasicHeader( HTTP.CONTENT_TYPE, "application/json" ) );
                              entity = se;
                              request.setEntity( entity );
                              HttpResponse response = client.execute( request );
                              entity = response.getEntity();
                              i++;
                          }
                          if ( ( line = in.readLine() ) == null &amp;&amp; entity != null ) {
                              file.delete();
                              testThread t = new testThread();
                              Thread t1 = new Thread( t );
                              t1.start();
                          }
  
  
                      } else {
                          Thread.sleep( 60000 );
                      } // end of else
  
                  } catch (NullPointerException e1) {
                      e1.printStackTrace();
                  } catch (InterruptedException e2) {
                      e2.printStackTrace();
                  } catch (IOException e1) {
  // TODO Auto-generated catch block
                      e1.printStackTrace();
                  }
              }// end of while
          }// end of run
  
      }
  </code></pre>