Imelza
Imelza

Reputation: 301

How to use MultiThreading in Android for an Event Handling Function (SensorListeners)

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.

How can I use multithreading on event handling functions? I'm trying to do it like this:

  1. Create a global variable writeNow.
  2. When the sensor value changes, set WriteNow = true
  3. Create a thread in the class which looks like this:

    Thread thread1 = new Thread()  
    {  
      public void run()  
      {  
        if(writeNow == true)  
          {  
            try 
            {  
                fos.write(s.getBytes());  
            } 
            catch (IOException e) 
            {  
                 e.printStackTrace();  
            }  
            writeNow = false;  
          }  
      }  
     };  
    

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.

So how do I enclose this event handling mechanism in a single thread, for speeding up a process?

Thanks!

Upvotes: 1

Views: 3585

Answers (2)

Siten
Siten

Reputation: 4533

Handler handler = null;

handler = new Handler();

//create another class for and make consrtuctor as u want. so that u can use that effectively.
//for example.                                                      

popupIndex = new IndexThread(handler,head, target,ltp,price,IndexNifty.this,columsView,call);           

popupIndex.setColumnViewexit(columsView);
handler.postDelayed(popupIndex, 300);


//another class
public IntraThread(Handler handler,String script,int target,int ltp,int price,Intraday intraday,TextView columsView,String call){
        super();
        this.target = target;
        this.ltp = ltp;
        this.price = price;     
        this.intraday = intraday;
        this.columsView = columsView;
        this.script= script;
        this.handler= handler;
        this.call= call;
}

public void run(){
// write ur code here....
}

Upvotes: 0

no.good.at.coding
no.good.at.coding

Reputation: 20371

You can try one of the following approaches:

  1. It looks like you're trying to keep your writer thread running all the time; what you can do is spawn the thread only when you need it. Take a look at the example in the Android documentation for handling expensive operation in the UI thread.

    Here is the example from that page:

    public class MyActivity extends Activity {
    
        [ . . . ]
        // Need handler for callbacks to the UI thread
        final Handler mHandler = new Handler();
    
        // Create runnable for posting
        final Runnable mUpdateResults = new Runnable() {
            public void run() {
                updateResultsInUi();
            }
        };
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            [ . . . ]
        }
    
        protected void startLongRunningOperation() {
    
            // Fire off a thread to do some work that we shouldn't do directly in the UI thread
            Thread t = new Thread() {
                public void run() {
                    mResults = doSomethingExpensive();
                    mHandler.post(mUpdateResults);
                }
            };
            t.start();
        }
    
        private void updateResultsInUi() {
    
            // Back in the UI thread -- update our UI elements based on the data in mResults
            [ . . . ]
        }
    }
    

    Since it doesn't look like you're doing anything in the UI thread once you finish writing you don't really need to bother with a Handler. But you might want to use it to display a Toast once the file has been written to.

  2. On the other hand, if you still want to have a thread running, you might have it sleep() and periodically wake up and check the status of writeNow.

    Thread thread1 = new Thread()  
    {  
        public void run()  
        {  
            while(true)
            {
                if(writeNow == true)  
                {  
                    try 
                    {  
                        fos.write(s.getBytes());  
                    } 
                    catch (IOException e) 
                    {  
                         e.printStackTrace();  
                    }  
    
                    writeNow = false;  
                }
    
                try
                {
                    Thread.sleep(100); //sleep for 100 ms
                }
                catch (InterruptedException e) 
                {  
                     Log.d('', e.getMessage());  
                }  
            }
        }  
     }; 
    

    Note that this will quickly get complicated and you might lose the bytes you want to write if your thread is sleeping when new data comes in and when it wakes up, even newer data has been received and has overwritten the previous bytes. You'd need some sort of a queue to manage that.

  3. I'm not sure what you were doing with the wait() but that should've also worked and is in fact, the approach for problems involving a consumer and producer. The idea is to have your thread synchronize and wait() on a shared object (like perhaps your queue of bytes); a second thread will call notify() on the shared object when there is data available to write and the writer thread will be woken up. The writer thread should then write and reloop. Take a look at this tutorial.

    As for the interruption of your thread, your thread may be interrupted for a number of reasons which is why it is good practice (especially when using wait()) to ensure that the condition you checked before you called wait() is still valid because you could've been woken because of either a call to notify()/notifyAll() or because of an interruption.

Upvotes: 1

Related Questions