Handler原理

       Handler是Android给我们提供用于更新UI的一套机制,一套消息处理机制。一般处理程序在UI线程中执行耗时操作,这会导致UI线程阻塞,当UI线程阻塞,屏幕会出现卡死,用户体验会变得非常差,当线程阻塞超过5s,Android系统可能进行干预,弹出对话框询问是否关闭。我们处理方式是创建一个新的线程来实现耗时操作,采用handle机制来实现子线程发送message通知主线程去改变UI组件。另外如果在线程中更新UI,会报“Only the original thread that created a view hierarchy can touch its views.” 
       Handler消息机制由Handler/Looper/MessageQueue/Message等组成。
       Handler框架代码目录:
framework/base/core/java/andorid/os/
 - Handler.java
 - Looper.java
 - Message.java
 - MessageQueue.java
       当一个应用程序运行时,它会创建一个进程。这个进程就是主线程(UI线程&Activity Thread),会运行如下代码:
Frameworks\base\core\java\android\app
- ActivityThread.java
    public static void main(String[] args) {
        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
        SamplingProfilerIntegration.start();

        // CloseGuard defaults to true and can be quite spammy.  We
        // disable it here, but selectively enable it later (via
        // StrictMode) on debug builds, but using DropBox, not logs.
        CloseGuard.setEnabled(false);

        Environment.initForCurrentUser();

        // Set the reporter for event logging in libcore
        EventLogger.setReporter(new EventLoggingReporter());

        // Make sure TrustedCertificateStore looks in the right place for CA certificates
        final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
        TrustedCertificateStore.setDefaultUserDirectory(configDir);

        Process.setArgV0("<pre-initialized>");

        Looper.prepareMainLooper();             //注 1

        ActivityThread thread = new ActivityThread();
        thread.attach(false);

        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }

        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }

        // End of event ActivityThreadMain.
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        Looper.loop();                     //注 2

        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

其中注1 的具体实现如下:
public static void prepareMainLooper() {
        prepare(false);                  //注3
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
}

进一步看注3:
    private static void prepare(boolean quitAllowed) {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        sThreadLocal.set(new Looper(quitAllowed));
}

从prepare()中,确保主线程中有且唯一一个Looper对象,并保存到线程的线程本地存储区(Thread Local Storage,简称为TLS)。Looper构造函数中,创建了MessageQueue对象并在mThread中记录当前线程。 
    private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
}

再来看注2 Looper.loop()的实现:
    public static void loop() {
        final Looper me = myLooper();  // 注 从线程的本地存储区TLS获取当前线程的Looper对象(Looper.prepare()创建存储)。
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        final MessageQueue queue = me.mQueue;   // 注 获取 Looper对象中的消息队列。

        // 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      //注 提取消息队列中待处理message。
            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
            final Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }

            final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;

            final long traceTag = me.mTraceTag;
            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }
            final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            final long end;
            try {
                msg.target.dispatchMessage(msg);                 //分发处理message。  
                end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            if (slowDispatchThresholdMs > 0) {
                final long time = end - start;
                if (time > slowDispatchThresholdMs) {
                    Slog.w(TAG, "Dispatch took " + time + "ms on "
                            + Thread.currentThread().getName() + ", h=" +
                            msg.target + " cb=" + msg.callback + " msg=" + msg.what);
                }
            }

            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.recycleUnchecked();
        }
    }

Looper.loop()核心就是获取Looper对象的消息队列,从消息队列中取出队列头的message,并分发处理。
至此,Hander机制的Looper,MessageQueue,Message都已经出现了,还差主角Handler。 我看看一个app例子:
下面例子在子线程中发message,主线程处理message更新UI显示。 
private TextView mTextView;
private Handler mHandler = new Handler() {                  
    @Override
    public void handleMessage(Message msg) {
        Person person = (Person)msg.obj;
        mTextView.setText("name:" + person.getName()+" age:"+person.getAge());
    }
};
private int index = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mTextView = findViewById(R.id.tv_text);
    new Thread() {
        @Override
        public void run() {
            try {
                Thread.sleep(2000);
                Message message = handler.obtainMessage();    
                Person person = new Person();
                person.setName("张三");
                person.setAge(18);
                message.obj = person;
                mHandler.sendMessage(message);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }.start();
}

创建了一个mHandler对象, 并重写了handleMessage()函数。 同时在子线程中封装创建message对象,并通过mHandler对象的sendMessage()放到Looper的MessageQueue队列中。 具体看handler的实现:
    public Handler() {
        this(null, false);
    }
    public Handler(Callback callback, boolean async) {
        if (FIND_POTENTIAL_LEAKS) {
            final Class<? extends Handler> klass = getClass();
            if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
                    (klass.getModifiers() & Modifier.STATIC) == 0) {
                Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
                    klass.getCanonicalName());
            }
        }

        mLooper = Looper.myLooper();      //获取当前线程,也就是UI主线中的looper对象。
        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;
}-

再来看子线程中的操作
                Message message = handler.obtainMessage();    
                Person person = new Person();
                person.setName("张三");
                person.setAge(18);
                message.obj = person;
                mHandler.sendMessage(message);

Handler的sendMessage会依次调用:
  public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
        MessageQueue queue = mQueue;
        if (queue == null) {
            RuntimeException e = new RuntimeException(
                    this + " sendMessageAtTime() called with no mQueue");
            Log.w("Looper", e.getMessage(), e);
            return false;
        }
        return enqueueMessage(queue, msg, uptimeMillis);
    }

    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;     //把handler对象赋予msg.target,消息分发的时候通过这个handler对象dispatchMessage处理。
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
}

最终调用MessageQueue的enqueueMessage()把消息添加到MessageQueue队列中。
总结一下: APP初始化时,创建了私有成员Handler对象。其将自动与主线程的Looper对象绑定。具体ActivityThread初始化了Looper,运行在主线程,这部分对应用开发者来说透明的。 然后子线程中通过mHandler.sendMessage发送消息到队列,sendMessage会依次调用到enqueueMessage,在enqueueMessage中,msg.target会赋予handler对象,Looper队列轮询到后,执行msg.target.dispatchMessage分发到主线程的handler.handleMessage()处理。 

     我们知道使用Handler来更新UI,常用的方法除了上面APP的sendMessage方法,另外一种Post方法。看例子:
private TextView tv_up;
    private String new_str = "";
    /*post方法解决UI更新问题handler创建方式*/
    private Handler handler_post = new Handler();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        new Thread(new Runnable() {

            @Override
            public void run() {
                new_str = "更新UI";
                /*post方法解决UI更新,直接在runnable里面完成更新操作,这个任务会被添加到handler所在线程的消息队列中,即主线程的消息队列中*/
                handler_post.post(new Runnable() {
                    @Override
                    public void run() {
                        tv_up.setText(new_str);
                    }
                });
            }
        }).start();
    }

Handler的post代码:
    public final boolean post(Runnable r)
    {
       return  sendMessageDelayed(getPostMessage(r), 0);
    }
    private static Message getPostMessage(Runnable r) {
        Message m = Message.obtain();
        m.callback = r;  //把Runnable对象赋予Message的callback。接下来还是和sendMessage一致的操作。
        return m;
    }

回过头来,再来看Looper.loop()的消息分发 msg.target.dispatchMessage(msg)。 具体调用handler的dispatchMessage()。
    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {               
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);      
        }
}

对msg.callback的判断,正是两种更新UI方式的消息处理的差异。 sendMessage方式通过handleMessage处理,post方式通过handleCallback()处理。 
    private static void handleCallback(Message message) {
        message.callback.run();
}

总结: Handler的post和sendMessage本质上是没有区别的,只是实际用法中有一点差别。
从之前例子,我们看到,都没有在APP中运行Looper.prepare(), 这是由于Activity的UI主线程默认是有消息队列的。所以在Activity中新建Handler时,不需要先调用Looper.prepare()。默认情况下一个线程是不存在消息循环(message loop)的,需要调用Looper.prepare()来给线程创建一个消息循环,调用Looper.loop()来使消息循环起作用。看个例子,很简单,不做进一步分析:
    private void initThead() {
        new Thread(new Runnable() {
            public void run() {
                Looper.prepare();//启用Looper。 
                handler1 = new Handler(){
                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                   }
                };          
                handler1.sendEmptyMessage( 5 ) ;
                Looper.loop();//  Looper开始工作,从消息队列里取消息,处理消息,让消息处理在该线程中完成。
           }
        }).start();
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值