Android开发中Handler的案例分析

一、Handler的定义:
在Android中,我们更新UI的操作必须要在主线程(UI线程)中进行,而下载图片、文件这种操作必须要在子线程中进行,Android为我们提供了Handler机制,实现了子线程与主线程之间的通信。通常做法就是先new出一个子线程Thread,在子线程中完成下载操作后,通过handler发送一条Message给主线程,主线程收到消息后,就可以进行UI的更新工作了,所以总的来说,就是主要接受子线程发送的数据, 并用此数据配合主线程更新UI。

解释:当应用程序启动时,Android首先会开启一个主线程 (也就是UI线程) , 主线程为管理界面中的UI控件, 进行事件分发, 比如说, 你要是点击一个 TextView ,Android会分发事件到TextView 上,来响应你的操作。 如果此时需要一个耗时的操作,例如: 下载图片, 或者读取本地较大的一个文件的时候,你不能把这些操作放在主线程中,如果你放在主线程中的话,界面会出现假死现象, 如果5秒钟还没有完成的话,会收到Android系统的一个错误提示 “强制关闭”。 这个时候我们需要把这些耗时的操作,放在一个子线程中,因为子线程涉及到UI更新,Android主线程是线程不安全的, 也就是说,更新UI只能在主线程中更新,子线程中操作是危险的。 这个时候,Handler就出现了。,来解决这个复杂的问题 ,由于Handler运行在主线程中(UI线程中), 它与子线程可以通过Message对象来传递数据, 这个时候,Handler就承担着接受子线程传过来的(子线程用sedMessage()方法传弟)Message对象,(里面包含数据) , 把这些消息放入主线程队列中,配合主线程进行更新UI。

二、Handler一些特点

handler可以分发Message对象和Runnable对象到主线程中, 每个Handler实例,都会绑定到创建他的线程中(一般是位于主线程),它有两个作用:

(1)安排消息或Runnable 在某个主线程中某个地方执行;

(2)安排一个动作在不同的线程中执行。

Handler中分发消息的一些方法

post(Runnable)

postAtTime(Runnable,long)

postDelayed(Runnable long)

sendEmptyMessage(int)

sendMessage(Message)

sendMessageAtTime(Message,long)

sendMessageDelayed(Message,long)

以上post类方法允许你排列一个Runnable对象到主线程队列中,

sendMessage类方法, 允许你安排一个带数据的Message对象到队列中,等待更新。

三、Handler实例

子类需要继承Handler类,并重写handleMessage(Message msg) 方法, 用于接受线程数据。

以下为一个实例,它实现的功能为:通过线程下载网络图片,并更新UI。

public class MainActivityTest extends Activity {

    private static final String TAG = "MainActivity";
    private String filePath = "http://www.adx.ms/sources/creative/1073741964/98/dc61af744af0f5b4a1822bfa4a65a8a0.jpg";
    private final static String ALBUM_PATH = Environment
            .getExternalStorageDirectory() + "/download_image/";
    private ImageView imageView;
    private TextView textView;
    //当创建一个新的Handler实例时, 它会绑定到当前线程和消息的队列中,开始分发数据 
    // Handler有两个作用, (1) : 定时执行Message和Runnalbe 对象  ,(2): 让一个动作,在不同的线程中执行。 
    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {

            if (msg.what == 1) {
                // 1.得到Bitmap
                //Bitmap bitmap = (Bitmap) msg.obj;
                // 获取当前背景图
                Bitmap bitmap = BitmapFactory.decodeFile(ALBUM_PATH
                        + "adx.jpg", null); 
                // 2.更新UI
                Drawable drawableCurrent = new BitmapDrawable(bitmap);
                // 来自服务端的图片
                imageView.setBackground(drawableCurrent);
            }
        };
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = (TextView) findViewById(R.id.text);
        imageView = (ImageView) findViewById(R.id.imageView);

        textView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                download();
            }
        });
    }

    protected void download() {

        new Thread(new Runnable() {
            @Override
            public void run() {

                // 1.耗时下载任务操作,获取图片bitmap
                Bitmap bitmap = null;
                String mFileName = "adx.jpg";
                try {
                    bitmap = BitmapFactory.decodeStream(getImageStream(filePath));
                    // 保存到本地
                    saveFile(bitmap, mFileName);
                } catch (IOException e) {                   
                    e.printStackTrace();
                };
                // 2.下载完成,向主线程发送Message
                Message msg = Message.obtain();
                msg.obj = bitmap;
                msg.what = 1; // 区分哪个线程发送的
                //向Handler发送消息,更新UI 
                mHandler.sendMessage(msg);
            }
        }).start();
    }

    /***
     * 从网络下载图片
     * @param path
     * @return
     * @throws IOException
     */
    protected InputStream getImageStream(String path) throws IOException {
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(10 * 1000);
        conn.setRequestMethod("GET");
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            return conn.getInputStream();
        }
        return null;
    }
    /**
     * 保存文件
     * @param bitmap
     * @param mFileName
     */
    protected void saveFile(Bitmap bm, String fileName) throws IOException {
        File dirFile = new File(ALBUM_PATH);
        if (!dirFile.exists()) {
            dirFile.mkdir();
        }
        File myCaptureFile = new File(ALBUM_PATH + fileName);
        BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream(myCaptureFile));
        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        bos.flush();
        bos.close();
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值