Android开发:Handler的简单使用(一)

1.Handler是什么?

原文:

A Handler allows you to send and process Message and Runnable objects associated with a thread’s MessageQueue. Each Handler instance is associated with a single thread and that thread’s message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it – from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.

翻译:

handler是用来接收和处理线程的消息队列里的message/runnable对象的工具。每个handler实例关联一个单独的线程和这个的线程的消息队列,handler实例会绑定到创建这个handler的线程。从那一刻起,handler会发送message/runnable到消息队列,然后在message/runnable从消息队列出来的时候处理它。

用法:处理线程之间消息的传递

2.为什么用handler?

考虑到java多线程的线程安全问题,android规定只能在UI线程修改Activity中的UI。为了在其他线程中可以修改UI,所以引入Handler,从其他线程传消息到UI线程,然后UI线程接受到消息时更新线程。

3.handler用法

Message可携带的数据

//通常作标志位,作区分
message.what;(int)

//携带简单数据
message.arg1;(int)
message.arg2;(int)

//携带object数据类型
message.obj;(object)

sendMessage 方式

接受消息并处理

private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            //处理消息
            return false;
        }
    });

发送消息

mHandler.sendMessage(msg);

post 方式

因为需要等待之前发送到消息队列里的消息执行完才能执行,所以需要异步等待。

new Thread(new Runnable() {
            @Override
            public void run() {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {

                    }
                });
            }
        }).start();

未完待续。。。

原文地址:https://www.cnblogs.com/JasonLGJnote/p/11159860.html