欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Handler、Message几种发送消息形式总结

程序员文章站 2022-07-14 16:44:10
...

部分代码如下:

 

消息处理代码:

 

  1. private Handler handler = new Handler() {
  2. public void handleMessage(Message msg) {
  3. switch (msg.what) {
  4. case 1 :
  5. bt.setText("正在下载...");
  6. break;
  7. case 2 :
  8. Bitmap bm = (Bitmap) msg.obj;
  9. iv.setImageBitmap(bm);
  10. break;
  11. case 3 :
  12. Bundle bundle = msg.getData();
  13. String data = bundle.getString("text");
  14. bt.setText(data);
  15. break;
  16. }
  17. }
  18. };
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:

 

    1. // 创建一个携带代码的消息对象,并发送给主线程执行
    2. handler.post(new Runnable() {
    3. public void run() {
    4. // 在主线程中,处理消息时执行
    5. Toast.makeText(
    6. MainActivity.this,
    7. "下载结束",
    8. Toast.LENGTH_SHORT).show();
    9. }
    10. });