- Bundle是一個載體,可以存放基本數據類型、對象等內容,相當於一輛汽車,可以裝載很多東西,然后運到需要的地方,例如:
Bundle mBundle=new Bundle(); mBundle.putString("name","zhaolinit"); mBundle.putInt("number",123456); mBundle.putBoolean("flag",false); //然后,放到Intent對象中 Intent mIntent=new Intent(); mIntent.putExtras(mBundle);
- Message:包含描述和任意數據對象的消息,用於發送給Handler
它的成員變量如下:
public final class Message implements Parcelable { public int what; public int arg1; public int arg2; public Object obj; ... }
其中what用於標識這條消息,也可以讓接收者知道消息是關於什么的。arg1和arg2用於發送一些integer類型的值。obj用於傳輸任意類型的值。
- Handler:消息處理者,通過重寫Handler的handleMessage()方法,在方法中處理接收到的不同消息,例如:
Handler mHandler=new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what) { case TestHandler.TEST:
progressValue += msg.arg1; Log.d("progressValue-------------->", progressValue+"");
break;
}
}
}
在其它地方,通過sendMessage()方法,發送消息,以供handleMessage()方法接受
class myThread implements Runnable { public void run() { while (!Thread.currentThread().isInterrupted()) { Message message = new Message(); message.what = TestHandler.TEST; TestHandler.this.myHandler.sendMessage(message); try { Thread.sleep(100); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } }
通過子線程處理一些耗時的操作,然后把處理后的結果通過sendMessage()方法發送到UI主線程。讓主線程的Handler進行UI組件的結果更新。