您的位置:首页 > 移动开发 > Android开发

Handler的深入了解

2016-07-22 17:00 531 查看
在android开发中,Handler大家会经常看到和用到。这里不说怎么使用,主要想一探Handler究竟。首先来看看Handler这个类是如何实现的:

frameworks\base\core\java\android\os中可以查阅到Handler这个类的实现文件。

重点看看他的构造方法的编写:

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();
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;
}构成方法里面主要工作是对这几个变量的初始化:mLooper、mQueue 下面就从这几个变量开始来解密Handler。
(1)mLooper: 在 Handler中,mLooper可以是通过上面的方法来获取当前创建该Handler的线程的Looper,也可以在创建时候传递一个线程的Looper。那么Looper是什么呢?

Looper 是一个线程特有的,用于管理需要在该线程处理的消息Message。Looper.java有原文的翻译:Class used to run a message loop for a thread. 

             但是,并不是所有运行中的线程都有自己的Looper,如果一个线程需要自己的Looper,可以通过调用prepare()方法来创建,  
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));

/// M: ALPS00297986
if (!IS_USER_BUILD) {
long instances = VMDebug.countInstancesOfClass(Looper.class, false);

// check if the looper instance over a limit, it should has some leakage.
if (100 < instances) {
Log.e(TAG, "WARNING: The Looper class instance count has over a limit(100). There should be some leakage of Looper or HandlerThread.");
Log.e(TAG, "Looper class instance count = " + instances);
Log.e(TAG, "Current Thread Name: " + Thread.currentThread().getName());
Thread.currentThread().getThreadGroup().list();
Thread.currentThread().dumpStack();
} //if
}
/// M: ALPS00297986
}从上面代码可以看出,一个线程只可以创建一个Looper,
Looper又是如何管理其中的message呢,事实上Looper是使用一个MessageQueue来存储其中的message的,当我们把message放在MessageQueue后吗,调用Looper的方法loop()就可以进入一个for (;;)的循环中,不断的从MessageQueue中取出message,并处理,直到MessageQueue中没有需要处理的message。

(2)mQueue 看了上面的介绍,就知道mQueue实际就是上面说的Looper的MessageQueue。

          所以通过Handler的sendMessage(Message msg)等方法send消息,其实就是把消息放入mQueue中,其实就是对Looper中的MessageQueue的数据处理。

  所以使用Handler来处理消息,其实就是这样一个过程:创建Handler时候,Handler就获取一个线程的Looper和他的MessageQueue,通过Handler发送处理的消息,其实就是把需要处理的消息放置于一个线程的Looper的MessageQueue中,而后Looper会运行一个for (;;)的死循环来取出消息,并处理。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息