对安卓中Handle机制的一些见解

消息队列机制
(1)主线程创建时,系统会同时创建消息队列对象(MessageQueue)和消息轮询器对象(Looper)
(2)轮询器的作用,就是不停的检测消息队列中是否有消息(Message)
(3)消息队列一旦有消息,轮询器会把消息对象传给消息处理器(Handler),处理器会调用handleMessage方法来处理这条消息,handleMessage方法运行在主线程中,所以可以刷新ui

 总结:

(1)只要消息队列有消息,handleMessage方法就会调用

(2)子线程如果需要刷新ui,只需要往消息队列中发一条消息,触发handleMessage方法即可

(3) 子线程使用处理器对象的sendMessage方法发送消息

下面以下载图片做一个实例:

public class MainActivity extends Activity {
    private static final String ADDRESS = "http://192.168.1.105:8080/g.jpg";
    private static final int TIMEOUT = 5000;
    private static ImageView iv;
    private static MainActivity ma;
    
    private static Handler handle = new Handler() {

        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
            case 1:
                Bitmap bitmap = (Bitmap) msg.obj;
                iv.setImageBitmap(bitmap);
                break;

            case 0:
                Toast.makeText(ma, "加载失败", 0).show();
                break;

            default:
                break;
            }

        };

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);
        iv = (ImageView) findViewById(R.id.iv);

    }

    public void btnOnClicked(View v) {

        // 首先判断图片文件在不在手机缓存里
        final File file = new File(InternalStorageUtils.getInternalFilesDir(this), getFileName(ADDRESS));
        if (file.exists()) {
            Log.i("mtag", "图片已经存在");
            Bitmap map = BitmapFactory.decodeFile(file.getAbsolutePath());
            iv.setImageBitmap(map);
        } else {
            // 开启子线程进行图片的下载以及缓存
            new Thread() {
                @Override
                public void run() {
                    HttpURLConnection conn = null;
                    try {
                        URL url = new URL(ADDRESS);
                        conn = (HttpURLConnection) url.openConnection();
                        conn.setReadTimeout(TIMEOUT);
                        conn.setConnectTimeout(TIMEOUT);

                        conn.setRequestMethod("GET");
                        conn.connect();
                        int code = conn.getResponseCode();

                        if (code == 200) {
                            InputStream is = conn.getInputStream();

                            // 保存到内部存储中
                            InternalStorageUtils.saveFileToInternalFilesDir(MainActivity.this,
                                    readFromStream(conn.getInputStream()), getFileName(ADDRESS));
                            // 第一次读完后InputStreame里没有数据了
                            Bitmap map = BitmapFactory.decodeFile(file.getAbsolutePath());
                            Message msg = handle.obtainMessage();
                            msg.obj = map;
                            msg.what = 1;
                            handle.sendMessage(msg);

                        } else {
                            Message msg = handle.obtainMessage();
                            msg.what = 0;
                            handle.sendMessage(msg);
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        if (conn != null) {
                            conn.disconnect();
                            conn = null;
                        }
                    }

                }
            }.start();
        }
    }

    // 将文件输入流写到字节数组输出流中
    private byte[] readFromStream(InputStream in) {
        ByteArrayOutputStream bos = null;

        try {
            bos = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int len = 0;
            while ((len = in.read(buf)) != -1) {
                bos.write(buf, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return bos.toByteArray();
    }

    // 获取文件的名字
    private String getFileName(String address) {
        int index = address.lastIndexOf("/");
        return address.substring(index + 1);

    }

}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值