title: How to use MultiThreading in Android for an Event Handling Function (SensorListeners)
body: <p>I have an event handling mechanism in my Android code to dump the sensor values in a file. Right now, I'm doing it in the main UI thread and hence the UI button responsiveness is very sluggish and I would like to speed it up. </p>
  
  <p>How can I use multithreading on event handling functions? I'm trying to do it like this:</p>
  
  <ol>
  <li>Create a global variable writeNow. </li>
  <li>When the sensor value changes, set WriteNow = true</li>
  <li><p>Create a thread in the class which looks like this:</p>
  
  <pre><code>Thread thread1 = new Thread()  
  {  
    public void run()  
    {  
      if(writeNow == true)  
        {  
          try 
          {  
              fos.write(s.getBytes());  
          } 
          catch (IOException e) 
          {  
               e.printStackTrace();  
          }  
          writeNow = false;  
        }  
    }  
   };  
  </code></pre></li>
  </ol>
  
  <p>Thus, whenever writeNow is true, it will write to a File and then set WriteNow to false. However, I realize this is not the right approach, because the thread will execute once and then stop executing. When I tried a simple example with a while(true) and wait(), I found that the thread is interrupted millions of times. </p>
  
  <p>So how do I enclose this event handling mechanism in a single thread, for speeding up a process?</p>
  
  <p>Thanks!</p>