Handler初步学习

最后更新于:2022-04-01 14:43:12

前面介绍了异步任务的处理,这里来学一下Handler和Message机制吧。下面这个代码和之前的一样,都是从网上下载图片的。 ~~~ package com.example.myasynctask; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import org.apache.http.HttpEntity; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.app.Activity; import android.app.ProgressDialog; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; public class MainActivity extends Activity { private Button button; private ImageView iv; private String path = "http://cdn.duitang.com/uploads/item/201310/17/20131017194234_eZfFU.thumb.600_0.png"; private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { Bitmap bm = null; byte[] data = (byte[])msg.obj; bm = BitmapFactory.decodeByteArray(data, 0, data.length); iv.setImageBitmap(bm); }; }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button) this.findViewById(R.id.bt); iv = (ImageView) this.findViewById(R.id.iv); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub new Thread(new myThread()).start(); } }); } private class myThread implements Runnable { @Override public void run() { HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(path); InputStream inputStream = null; try { HttpResponse httpResponse = httpClient.execute(httpGet); if (httpResponse.getStatusLine().getStatusCode() == 200 ) { HttpEntity httpEntity = httpResponse.getEntity(); byte[] data = EntityUtils.toByteArray(httpEntity); Message message = Message.obtain(); message.obj = data; handler.sendMessage(message); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } } } ~~~ ~~~ ~~~ ~~~ ~~~ Looper维护一个消息队列(在loop()函数里面) Message.obtain可回收的获取Message对象(这样就不用多次new对象) Handler通过sendMessage来把Message进行消息队列的入队,并且把Message的target(也就是对应的Handler绑定为自己) 当消息队列循环到相应的Message的时候,会调用Message绑定的Handler的dispatchMessage函数,该函数会调用handleMessage函数,也就是用户实现的handleMessage函数。Handler可以绑定多个Message,通过Message.what来识别身份。 --------源码所得,2014/ 9/ 9 修改
';