androidmultithreadingrunnablehandlers

How do I pass Runnable objects to a Handler?


I am learning via a book and it gives me this example:

Handler handler=new Handler() { 
    @Override 
    public void handleMessage(Message msg) { 
        bar.incrementProgressBy(5); 
    } 
}; 

and

Thread background=new Thread(new Runnable() { 
    public void run() { 
        try { 
            for (int i=0;i<20 && isRunning.get();i++) { 
                Thread.sleep(500); 
                handler.sendMessage(handler.obtainMessage()); 
            } 
        } catch (Throwable t) { 
            // just end the background thread 
        } 
    } 
}); 

Which works out great. But, further down in the book it says:

If you would rather not fuss with Message objects, you can also pass Runnable objects to the Handler, which will run those Runnable objects on the activity UI thread. ...you can use those same methods on any View (i.e., any widget or container). This slightly simplifies your code, in that you can then skip the Handler object.

But there are no examples given of how to do this via a Runnable object. Does anyone have an example?


Solution

  • Something like this:

    Handler h = new Handler();
    

    Thread background=new Thread(new Runnable() { 
              public void run() { 
                try { 
                  for (int i=0;i<20 && isRunning.get();i++) { 
                    Thread.sleep(500); 
                    handler.post(new Runnable() {
                      public void run() {
                        bar.incrementProgressBy(5);
                      }
                    });
                  } 
                } 
                catch (Throwable t) { 
                  // just end the background thread 
                } 
              } 
            });