title: Want to run accelerometer in background
body: <p>I created an app that records accelerometer values and stores them in a file with a simple start stop button. I want this to keep working even when the screen is off until the stop button is pushed what is the best way to do this. I was told asyncTask but was not sure if i should do the whole class. </p>
  
  <p>public class StartAccelerometer extends Activity implements SensorEventListener,OnClickListener 
  {</p>
  
  <pre><code>private SensorManager SensorManager;
  private Sensor Accelerometer;
  TextView title,tvx,tvy,tvz;
  EditText etshowval;
  RelativeLayout layout;
  private String acc;
  private String read_str = "";
  private final String filepath = "/mnt/sdcard/acc.txt";
  private BufferedWriter BufferedWriter;
  private BufferedReader BufferedReader;
  private float x;
  private float y;
  private float z;
  
  public static final int MSG_DONE = 1;
  public static final int MSG_ERROR = 2;
  public static final int MSG_STOP = 3;
  
  private boolean running;
  private Handler Handler;
  private HandlerThread HandlerThread;
  
  
  Button stop,start;
  
  
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) 
  {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_accelerometer);
      SensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
      Accelerometer = SensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
      SensorManager.registerListener(this, Accelerometer, android.hardware.SensorManager.SENSOR_DELAY_NORMAL);
    //get layout
      layout = (RelativeLayout) findViewById(R.id.relative);
  
      //get textviews
      title = (TextView)findViewById(R.id.name);   
      tvx = (TextView)findViewById(R.id.xval);
      tvy = (TextView)findViewById(R.id.yval);
      tvz = (TextView)findViewById(R.id.zval);
      etshowval = (EditText)findViewById(R.id.showval);
      title.setText("Accelerator");
  
      HandlerThread = new HandlerThread("Working Thread");
      HandlerThread.start();
  
      Handler = new Handler(HandlerThread.getLooper());
      Handler.post(Run);
  
      start= (Button) findViewById(R.id.startAccel);
      stop= (Button) findViewById(R.id.button2);
      start.setOnClickListener(this);
      stop.setOnClickListener(this);
  }
  
  private Runnable Run = new Runnable(){
      @Override
      public void run ()
      {
          while(true)
          {
              if (running)
              {
  
                  try 
                  {
                      WriteFile(filepath,acc);
  
                                        } 
                  catch (Exception e) 
                  {
  
                  }
  
              }
  
  
              try {
                  Thread.sleep(50);
              } catch (InterruptedException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              }
          }
      }
  };
  
  public void onClick(View view) 
  {
      if(view.getId() == R.id.startAccel){
          start();
  
      }
      else if(view.getId() == R.id.button2){
          stop();
      }
  
  }
  
  
  private synchronized void start()
  {
      running = true;
  }
  
  private synchronized void stop()
  {
      running = false;
  }
  
  
  
  @Override
  public void onAccuracyChanged(Sensor sensor, int accuracy) 
  {
  }
  
  @Override
  public void onSensorChanged(SensorEvent sensorEvent) 
  {
      // TODO Auto-generated method stub
  
      if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) 
      {
          x = sensorEvent.values[0]; 
          y = sensorEvent.values[1]; 
          z = sensorEvent.values[2]; 
          acc= String.valueOf(x) + ", " + String.valueOf(y) + ", " + String.valueOf(z);
  
          tvx.setText("X = "+ String.valueOf(x));
          tvy.setText("Y = "+ String.valueOf(y));
          tvz.setText("Z = "+ String.valueOf(z));
      }
  }
  
  public void CreateFile(String path)
  {
      File f = new File(path);
      try {
          Log.d("ACTIVITY", "Create a File.");
          f.createNewFile();
      } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
      }
  }
  
  public String ReadFile (String filepath)
  {
      BufferedReader = null;
      String tmp = null;
  
      if (!FileIsExist(filepath))
          CreateFile(filepath);
  
      try 
      {
          BufferedReader = new BufferedReader(new FileReader(filepath));
          // Read string
          while ((tmp = BufferedReader.readLine()) != null) 
          {
              tmp += "\n";
              read_str += tmp;
          }
      } 
      catch (IOException e) 
      {
          // TODO Auto-generated catch block
          e.printStackTrace();
      }
      return read_str;
  }
  
  public void WriteFile(String filepath, String str)
  {
      BufferedWriter = null;
  
      if (!FileIsExist(filepath))
          CreateFile(filepath);
  
      try 
      {
          BufferedWriter = new BufferedWriter(new FileWriter(filepath, true));
          BufferedWriter.write(str);
          BufferedWriter.newLine();
          BufferedWriter.flush();
          BufferedWriter.close();
      }
      catch (IOException e) 
      {
          // TODO Auto-generated catch block
          e.printStackTrace();
      }
  }
  
  public boolean FileIsExist(String filepath)
  {
      File f = new File(filepath);
  
      if (! f.exists())
      {
          Log.e("ACTIVITY", "File does not exist.");
          return false;
      }
      else
          return true;
  }
  
  @Override
  protected void onPause()
  {
  // TODO Auto-generated method stub
     // mSensorManager.unregisterListener(this);
     // Toast.makeText(this, "Unregister accelerometerListener", Toast.LENGTH_LONG).show();
      //super.onPause();
  
      super.onPause();
      if (running == true) {
          SensorManager.unregisterListener(this);
  } 
  </code></pre>
  
  <p>}
  }</p>