Android中Handler的post和sendMessage的区别

Handler的post和sendMessage的区别

  1. post和sendMessage功能其实差不多,post其实也是通过sendMessage来实现的,都是发送消息到Handler所在的线程的消息队列中
  2. post的用法更方便,经常会post一个Runnable,处理的代码直接写在Runnable的run方法中,其实就是将这个Runnable发送到Handler所在线程(一般是主线程)的消息队列中。sendMessage方法主线程处理方法一般则是写在handleMessage中。代码示例如下:

post

final Handler handler = new Handler();
new Thread(new Runnable() {
            @Override
            public void run() {
                final String response = get(url);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        //doSomeThing
                    }
                });
            }
        }).start();

sendMessage

final Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == 1) {
                    //doSomeThing
                }
            }
        };

        new Thread(new Runnable() {
            @Override
            public void run() {
                Message msg = new Message();
                msg.what = 1;
                handler.sendMessage(msg);
            }
        });

view.post和handler.post区别

view.post其实内部是获取到了view所在线程(即ui线程)的handler,并且调用了handler的post方法

你可能感兴趣的:(Android)