开发者

How do I pass Runnable objects to a Handler?

开发者 https://www.devze.com 2023-03-22 17:35 出处:网络
I am learning via a book and it gives me this example: Handler handler=new Handler() { @Override public void handleMessage(Message msg) {

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(hand开发者_运维知识库ler.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?


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 
            } 
          } 
        }); 


As per the Android Docs for Handler:

public final boolean post (Runnable r)

Since: API Level 1 Causes the Runnable r to be added to the message queue. The runnable will be run on the thread to which this handler is attached. Parameters

r -- The Runnable that will be executed. Returns

Returns true if the Runnable was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号