Looper,Message,Handler

来源:互联网 发布:windows如何更新系统 编辑:程序博客网 时间:2024/05/17 20:01

Looper负责的创建一个MessageQueue,然后进入一个无限循环体不断从该MessageQueue中读取消息,而消息的创建者就是一个或多个Handler。

1、Looper

Looper主要是prepare()和loop()两个方法。
首先看prepare()方法:
public static final void prepare() {          if (sThreadLocal.get() != null) {              throw new RuntimeException("Only one Looper may be created per thread");          }          sThreadLocal.set(new Looper(true));  }
sThreadLocal是一个ThreadLocal对象,可以在一个线程中存储变量。可以看到,在第5行,将一个Looper的实例放入了ThreadLocal,并且2-4行判断了sThreadLocal是否为null,否则抛出异常。这也就说明了Looper.prepare()方法不能被调用两次,同时也保证了一个线程中只有一个Looper实例。
下面看Looper的构造方法:
private Looper(boolean quitAllowed) {          mQueue = new MessageQueue(quitAllowed);          mRun = true;          mThread = Thread.currentThread();  } 
在构造方法中,创建了一个MessageQueue(消息队列)。
然后我们看loop()方法:
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;            // 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              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              Printer logging = me.mLogging;              if (logging != null) {                  logging.println(">>>>> Dispatching to " + msg.target + " " +                          msg.callback + ": " + msg.what);              }                msg.target.dispatchMessage(msg);                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.recycle();          }  } 
第2行:
public static Looper myLooper() {
return sThreadLocal.get();
}
方法直接返回了sThreadLocal存储的Looper实例,如果me为null则抛出异常,也就是说looper方法必须在prepare方法之后运行。
第6行:拿到该looper实例中的mQueue(消息队列)
13到45行:进入了无限循环。
14行:取出一条消息,如果没有消息则阻塞。
27行:使用调用 msg.target.dispatchMessage(msg);把消息交给msg的target的dispatchMessage方法去处理。Msg的target是什么呢?其实就是handler对象,下面会进行分析。
44行:释放消息占据的资源。
Looper主要作用:
1、 与当前线程绑定,保证一个线程只会有一个Looper实例,同时一个Looper实例也只有一个MessageQueue。
2、 loop()方法,不断从MessageQueue中去取消息,交给消息的target属性的dispatchMessage去处理。

2、Handler

首先看一下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();          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;      }
首先通过Looper.myLooper()获取了当前线程保存的Looper实例,然后又获取了这个Looper实例中保存的MessageQueue(消息队列),这样就保证了handler的实例与我们Looper实例中MessageQueue关联上了。

再看sendMessage方法:

public final boolean sendMessage(Message msg)   {       return sendMessageDelayed(msg, 0);   }  
public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {       Message msg = Message.obtain();       msg.what = what;       return sendMessageDelayed(msg, delayMillis);   } 
public final boolean sendMessageDelayed(Message msg, long delayMillis)     {         if (delayMillis < 0) {             delayMillis = 0;         }         return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);     }
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);     }
最后定位到调用了sendMessageAtTime,在此方法内部获取MessageQueue然后调用了enqueueMessage方法,我们再来看看此方法:

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {         msg.target = this;         if (mAsynchronous) {             msg.setAsynchronous(true);         }         return queue.enqueueMessage(msg, uptimeMillis);  
enqueueMessage中首先为meg.target赋值为this,也就是把当前的handler作为msg的target属性。最终会调用queue的enqueueMessage的方法,也就是说handler发出的消息,最终会保存到消息队列中去。

下面我们再看一看回调的dispathMessage方法:

public void dispatchMessage(Message msg) {          if (msg.callback != null) {              handleCallback(msg);          } else {              if (mCallback != null) {                  if (mCallback.handleMessage(msg)) {                      return;                  }              }              handleMessage(msg);          }      }

再看一下这里调用的handleMessge方法:

public void handleMessage(Message msg) {  } 

可以看到这是一个空方法,为什么呢,因为消息的最终回调是由我们控制的,我们在创建handler的时候都是复写handleMessage方法,然后根据msg.what进行消息处理。










0 0
原创粉丝点击