网上有很多关于Handler的帖子,但是看了那么多,不自己亲自分析一下,还是虚得很
哪些地方用到了Handler?
1.
runOnUiThread(Runnable action)
我们在Activity中写处理逻辑的时候,经常会用到这个方法,用来保证代码在UI线程中执行。
来看看它是怎么实现的:
/**
* Runs the specified action on the UI thread. If the current thread is the UI
* thread, then the action is executed immediately. If the current thread is
* not the UI thread, the action is posted to the event queue of the UI thread.
*
* @param action the action to run on the UI thread
*/
public final void runOnUiThread(Runnable action) {
if (Thread.currentThread() != mUiThread) {
mHandler.post(action);
} else {
action.run();
}
}
可以看到,如果当前线程是UI线程,则调用Handler的post方法。否则直接运行。
那么就来看看Handler的post方法: