2015年7月20日 星期一

Send message by handler

Reference:

http://blog.csdn.net/ahuier/article/details/17012923
http://blog.csdn.net/ahuier/article/details/17013647

Handler sendMessage:

1. sendEmptyMessage(int what)
Example:
new Thread(new Runnable() { 
    @Override 
    public void run() { 
        mHandler.sendEmptyMessage(3); 
    } 
}).start();

protected static Handler mHandler = new Handler() {
     @Override 
     public void handleMessage(android.os.Message msg) { 
         System.out.println("--> what: " + msg.what); 
     } 
}; 

2. sendEmptyMessageAtTime(int what,long uptimeMillis)

3. sendEmptyMessageDelayed (int what, long delayMillis)

4. sendMessage (Message msg)
Example:
new Thread(new Runnable() { 
    @Override 
    public void run() { 
        Message msg = mHandler.obtainMessage();  
        msg.arg1 = 1; 
        msg.what = 3; 
        msg.obj = "AHuier"; 
        mHandler.sendMessage(msg); 
    } 
}).start(); 

Handler obtainMessage:

obtainMessage(int what, int arg1, int arg2, Object obj)
Ex:
mHandler.obtainMessage(Constants.MESSAGE_READ, bytes, -1, buffer).sendToTarget();

Message obtain:

1. obtain()
Ex:
Message message = Message.obtain(); 
message.what = 1; 
message.arg1 = 1; 
message.arg2 = 3; 
message.obj = "AHuier"; 
handler.sendMessage(message);

2. obtain(Handler h)
Ex:
Message message = Message.obtain(handler); 
message.what = 1; 
message.arg1 = 1; 
message.arg2 = 3; 
message.obj = "AHuier"; 
message.sendToTarget();

3. obtain(Handler h, int what)

4. obtain(Handler h, int what, int arg1, int arg2, Object obj)

5.使用 Bundle來傳遞複雜的資料型態
Ex:
Message message = Message.obtain(handler, 1, 1, 3, "AHuier"); 
Bundle data = new Bundle(); 
data.putStringArray("str", new String[]{"AHui", "AHui1", "AHui2"}); 
message.setData(data); 
message.sendToTarget();


Relative reference:

http://givemepass-blog.logdown.com/posts/296606-how-to-use-a-handler
http://j796160836.pixnet.net/blog/post/28766165




沒有留言: