handler

来源:互联网 发布:文章网站数据库设计 编辑:程序博客网 时间:2024/06/03 14:20

1:在主线程中定义一个handler

2:在子线程中用handler发消息

handler.sendmMessage(msg);

msg 有obj what属性

3:重写handlemessage()方法,在方法里更新UI

原理:在子线程中handler发送了一条消息,这条消息进入到主线程中的messagequeue中就是主线程的消息队列.而在主线程创建的时候,Looper消息循环器也创建,并实时监听消息队列中的消息,一旦发现消息,调用handler的handlemessage(),执行完成后消息消失.

在Looper中有这样一个方法:

public static void loop() {        final Looper me = myLooper();        if (me == null) {            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");        }        final MessageQueue queue = me.mQueue;        // Make sure the identity of this thread is that of the local process,        // and keep track of what that identity token actually is.        Binder.clearCallingIdentity();        final long ident = Binder.clearCallingIdentity();        for (;;) {            Message msg = queue.next(); // might block            if (msg == null) {                // No message indicates that the message queue is quitting.                return;            }            // This must be in a local variable, in case a UI event sets the logger            Printer logging = me.mLogging;            if (logging != null) {                logging.println(">>>>> Dispatching to " + msg.target + " " +                        msg.callback + ": " + msg.what);            }            msg.target.dispatchMessage(msg);            if (logging != null) {                logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);            }            // Make sure that during the course of dispatching the            // identity of the thread wasn't corrupted.            final long newIdent = Binder.clearCallingIdentity();            if (ident != newIdent) {                Log.wtf(TAG, "Thread identity changed from 0x"                        + Long.toHexString(ident) + " to 0x"                        + Long.toHexString(newIdent) + " while dispatching to "                        + msg.target.getClass().getName() + " "                        + msg.callback + " what=" + msg.what);            }            msg.recycle();        }    }
其中msg.target.dispatchMessage(msg);的target是handler类型,也就是说这行代码执行的是handler下的dispatchMessage(msg)方法,代码如下]

public void dispatchMessage(Message msg) {        if (msg.callback != null) {            handleCallback(msg);        } else {            if (mCallback != null) {                if (mCallback.handleMessage(msg)) {                    return;                }            }            handleMessage(msg);        }    }
可知在该方法中调用了handlermessage()方法,这也是必须重写的原因.