部分代码如下:
消息处理代码:
- private Handler handler = new Handler() {
- public void handleMessage(Message msg) {
- switch (msg.what) {
- case 1 :
- bt.setText("正在下载...");
- break;
- case 2 :
- Bitmap bm = (Bitmap) msg.obj;
- iv.setImageBitmap(bm);
- break;
- case 3 :
- Bundle bundle = msg.getData();
- String data = bundle.getString("text");
- bt.setText(data);
- break;
- }
- }
- };
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 1 :
bt.setText("正在下载...");
break;
case 2 :
Bitmap bm = (Bitmap) msg.obj;
iv.setImageBitmap(bm);
break;
case 3 :
Bundle bundle = msg.getData();
String data = bundle.getString("text");
bt.setText(data);
break;
}
}
};
消息发送代码:
方式一:
示例1:
Message.obtain(handler,1).sendToTarget();
示例2:
Bitmap bm = NetUtil.downloadNewImg();
Message.obtain(handler, 2, bm).sendToTarget();
示例3:
// 这条消息,不携带数据,而是携带一段代码, 主线程处理这条消息时,会执行它携带的代码,而不执行其他代码
Message.obtain(handler, new Runnable() {
public void run() {
bt.setText("下载内涵图");
}
}).sendToTarget();
方式二:
示例1:
handler.obtainMessage(1).sendToTarget();
示例2:
Bitmap bm = NetUtil.downloadNewImg();
handler.obtainMessage(2, bm).sendToTarget();
方式三:
示例1:
Message msg = new Message();
msg.what
=1;
handler.sendMessage(msg);
示例2:
Message msg = new Message();
msg.what =2;
msg.obj =
bm;
handler.sendMessage(msg);
示例3:
Message msg = new Message();
Bundle data = new
Bundle();
data.putString("text", "正在下载...");
msg.what =
3;
msg.setData(data);
handler.sendMessage(msg);
示例4:
- // 创建一个携带代码的消息对象,并发送给主线程执行
- handler.post(new Runnable() {
- public void run() {
- // 在主线程中,处理消息时执行
- Toast.makeText(
- MainActivity.this,
- "下载结束",
- Toast.LENGTH_SHORT).show();
- }
- });