3. Android Handler

yan_lu edited this page May 29, 2016 · 1 revision

Android Handler

**由于Android的两大限制 **

  1. UI Thread不能访问网络,不能执行耗时操作(ANR)
  2. 只能UI Thread更新UI View)

Android提供了Handler来提供Thread之间的通信

Handler可以发送和处理消息,消息可以带上Runnable、what、obj等信息

这样的话,就可以在UI Thread创建Handler,Worker Thread干完活使用Handler发送消息,Handler在UI Thread更新UI等。

// 创建Handler(on UI Thread)
    mTimeHandler = new MyTimeHandler(msg -> {
        // 更新(on UI Thread)
        mTvTimeCount.setText(getString(R.string.time_counter, ++mSecond));
        continuedOneSecond();
        return true;
    });

// 续一秒(on Worker Thread)
    ExecutorService mExecutor;
    //
    private void continuedOneSecond(){
        mExecutor.submit(this);
        // 避免重复new Thread
        //new Thread(this).start();
    }

    @Override
    public void run() {
        //continued one second
        try {
            Thread.sleep(1000);
            mTimeHandler.sendEmptyMessage(0);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

Handler怎么做到的呢

  1. Handler创建的时候会关联线程和消息队列
    1.1 app运行的时候,创建UI Thread、Looper、MessageQueue
    public Handler(Callback callback, boolean async) {
        ...

        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

1.2 Looper、MessageQueue完成消息的发送和分发

    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;


        for (;;) {
            ...
            
            Message msg = queue.next(); // might block
            
            msg.target.dispatchMessage(msg);

            ...
        }
    }

1.3 Message传递的信息有哪些

    // target 完成消息的分发,包括消息的remove
    Handler target;
    public static Message obtain(Handler h, int what, 
            int arg1, int arg2, Object obj) {
        Message m = obtain();
        m.target = h;
        m.what = what;
        m.arg1 = arg1;
        m.arg2 = arg2;
        m.obj = obj;

        return m;
    }

1.4 消息怎么到达Handler的处理方法 dispatchMessage之后,调用Handler自己的处理方法了。

    /**
     * Handle system messages here.
     */
    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

下一篇 Communicating with the UI Thread in Android

You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.