Android handler异步更新

分享到:

方法一:

package com.example.handlerdemo;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {
    private static final int MSG_SUCCESS = 0;// 获取图片成功的标识
    private static final int MSG_FAILURE = 1;// 获取图片失败的标识
    ImageView mImageView;
    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MSG_SUCCESS:
                mImageView.setImageBitmap((Bitmap) msg.obj);// imageview显示从网络获取到的logo
                break;
            case MSG_FAILURE:
                Toast.makeText(getApplication(), "下载失败", Toast.LENGTH_LONG)
                        .show();
                break;
            }
        }
    };protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mImageView = (ImageView) findViewById(R.id.imageView1);// 显示图片的ImageView

    }

    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.button1:
            mImageView.setImageBitmap(null);
            new Thread(new Runnable() {
                public void run() {
                    HttpClient hc = new DefaultHttpClient();
                    HttpGet hg = new HttpGet(
                            "http://www.baidu.com/img/baidu_sylogo1.gif");// 获取百度的LOGO
                    final Bitmap bm;
                    try {
                        HttpResponse hr = hc.execute(hg);
                        bm = BitmapFactory.decodeStream(hr.getEntity()
                                .getContent());
                    } catch (Exception e) {
                        mHandler.obtainMessage(MSG_FAILURE).sendToTarget();// 获取图片失败
                        return;
                    }
                    mHandler.obtainMessage(MSG_SUCCESS, bm).sendToTarget();// 获取图片成功,向ui线程发送MSG_SUCCESS标识和bitmap对象

                }
            }).start();
            break;
} } }
昵    称:
验证码:

相关文档: