Handler源码之再解析

Handler之源码再解析

实例

handler用法已经用法和内存泄漏已经有很多博客写的很好,再次不在赘述,此处仅仅是自己看别人博客时感觉不解的地方再次分析记录,希望看本篇文章的时候结合api会更有收获。
先写一个例子(这个例子是随便从别的地方拷贝的):

public class MainActivity extends AppCompatActivity {

private ProgressBar progress_bar = null;
private Button start = null;

Handler mHandler = new Handler()  {
    @Override
    public void handleMessage(Message msg) {
    //在此处更新UI
        progress_bar.setProgress(msg.arg1);
    }
};

Runnable mRunable = new Runnable(){
    int m = 0;
    public void run() {
        // TODO Auto-generated method stub
        m += 10;
        Message msg = mHandler.obtainMessage();
        msg.arg1 = m;
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        //发送消息
        mHandler.sendMessage(msg);
        if(m == 100)
            //从线程队列中移除线程
            mHandler.removeCallbacks(mRunable);
    }
};

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    progress_bar = (ProgressBar)findViewById(R.id.progress_bar);
    start = (Button)findViewById(R.id.send_msg);

    start.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //让进度条显示出来
            progress_bar.setVisibility(View.VISIBLE);
            //将线程加入到handler的线程队列中
            mHandler.post(mRunable);
        }
    });
}

}

Looper

分析Handler首先从Looper开始,
public final class Looper {
。。。
}
从类的定义来看,Looper是一个final类型的类,final类型的类有以下特点:

final类不能被继承,没有子类,final类中的方法默认是final的

final方法不能被子类的方法覆盖,但可以被继承。

final成员变量表示常量,只能被赋值一次,赋值后值不再改变。

final不能用于修饰构造方法。

注意:父类的private成员方法是不能被子类方法覆盖的,因此private类型的方法默认是final类型的。

1、final类

final类不能被继承,因此final类的成员方法没有机会被覆盖,默认都是final的。在设计类时候,如果这个类不需要有子类,类的实现细节不允许改变,并且确信这个类不会载被扩展,那么就设计为final类。

2、final方法
如果一个类不允许其子类覆盖某个方法,则可以把这个方法声明为final方法。使用final方法的原因有二:
①把方法锁定,防止任何继承类修改它的意义和实现。
②高效,编译器在遇到调用final方法时候会转入内嵌机制,大大提高执行效率。

3、looper的构造方法中初始化了一个队列还有当前线程

private Looper(boolean quitAllowed) {
    mQueue = new MessageQueue(quitAllowed);
    mThread = Thread.currentThread();
}

UI线程也就是主线程默认维持一个Looper也就是mainLooper,所以调用Handler的时候无需手动调用looper,但是其他子线程使用handler之前需要先调用Looper.prepare
(),之后调用Looper.loop(),让我们看看这两个方法到底做了什么。

Looper.prepare()

 /** Initialize the current thread as a looper.
  * This gives you a chance to create handlers that then reference
  * this looper, before actually starting the loop. Be sure to call
  * {@link #loop()} after calling this method, and end it by calling
  * {@link #quit()}.
  */
public static void prepare() {
    prepare(true);
}

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中使用一个sThreadLocal新建一个Looper并且set进去,也就是很多博客说的关联一个looper到该线程,实际就是以此线程为键值,新建一个Looper作为value放到ThreadLocal中。

ThreadLocal的作用简单说一下,是多线程并发处理的一种,把共享变量拷贝一份到线程空间,每个线程有一份数据,所以不存在多线程同步问题,和synchronize以时间换空间方法不同,它是一种以空间换时间的机制。

Looper.loop()

Looper.loop()和prepare一样都是一个静态方法,关键代码,请看下面的汉语注释。

/**
 * Run the message queue in this thread. Be sure to call
 * {@link #quit()} to end the loop.
 */
public static void loop() {
//此处是获取该线程的looper,实际上就是从ThreadLocal中把prepare时候放进去的Looper对象取出来,追入myLooper()就可以发现。
    final Looper me = myLooper();
    if (me == null) {
        throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
    }
	//这个地方很关键,me代表的是当前looper,而当前Looper中的mQueue正是Looper初始化时候的队列
    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,而这个message也正是关键部分,后面会一一解惑。
        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
        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 {
        	//这一步调用的是Handler中的dispatchMessage,也正是这一步完成了msg从子线程到主线程的蜕变,追进去可看到,实际调用的是handleMesage方法。而这个msg.target是如何初始化的,请继续看下面Handler部分分析
            msg.target.dispatchMessage(msg);
            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);
        }
	//这一步是在分发完成Message之后,标记将该Message标记为 *正在使用* 
        msg.recycleUnchecked();
    }
}

dispatchMessage方法源码

/**
 * Handle system messages here.
 */
public void dispatchMessage(Message msg) {
	//此处的msg正是我们sendMessage的时候设置进去的,这一步也完成了主线程中的方法handleMessage回调,所以这里面可以进行UI更新操作。
    if (msg.callback != null) {
        handleCallback(msg);
    } else {
        if (mCallback != null) {
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
        handleMessage(msg);
    }
}

Handler

我们来看一下Handler,同样注意下面的汉语注释

/**
 * Use the {@link Looper} for the current thread with the specified callback interface
 * and set whether the handler should be asynchronous.
 *
 * Handlers are synchronous by default unless this constructor is used to make
 * one that is strictly asynchronous.
 *
 * Asynchronous messages represent interrupts or events that do not require global ordering
 * with respect to synchronous messages.  Asynchronous messages are not subject to
 * the synchronization barriers introduced by {@link MessageQueue#enqueueSyncBarrier(long)}.
 *
 * @param callback The callback interface in which to handle messages, or null.
 * @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for
 * each {@link Message} that is sent to it or {@link Runnable} that is posted to it.
 *
 * @hide
 */
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());
        }
    }

	//同样先获取looper此处的looper是UI线程
    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;
}

什么时候子线程中的msg.target,完成赋值

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
    msg.target = this;
    if (mAsynchronous) {
        msg.setAsynchronous(true);
    }
    return queue.enqueueMessage(msg, uptimeMillis);
}

正是在这一步,而这一步是所有sendMessage,sendMesageDelay等等发送消息的接口全部都会调用到这个方法

总结

综上,可以知道,Looper.prepare()的作用是new一个子线程专属的Looper,并且与之关联。

Looper.loop()的作用是先循环的从队列中获取消息,然后通过dispatchMessage,调用handleMessage回调,完成子线程到主线程的信息发送。

Handler构造的作用是先完成自身队列和looper的初始化,

sendMessage,把Looper中的msg.target赋值为当前handler。

上一篇:《.NET 编程结构》专题汇总


下一篇:1587: 【例 3】Windy 数