| 注册
请输入搜索内容

热门搜索

Java Linux MySQL PHP JavaScript Hibernate jQuery Nginx
emxf2777
9年前发布

Handler,Looper,HandlerThread浅析

来自: http://www.cnblogs.com/wingyip/p/5172918.html

Handler想必在大家写Android代码过程中已经运用得炉火纯青,特别是在做阻塞操作线程到UI线程的更新上.Handler用得恰当,能防止很多多线程异常.

而Looper大家也肯定有接触过,只不过写应用的代码一般不会直接用到Looper.但实际Handler处理Message的关键之处全都在于Looper.

以下是我看了<深入理解Android>的有关章节后,写的总结.

Handler

先来看看Handler的构造函数.

public Handler() {          this(null, false);      }    public Handler(Looper looper) {          this(looper, 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;      }

主要关注Handler的2个成员变量mQueue,mLooper

mLooper可以从构造函数传入.如果构造函数不传的话,则直接取当前线程的Looper:mLooper = Looper.myLooper();

mQueue就是mLooper.mQueue.

把Message插入消息队列

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;          if (mAsynchronous) {              msg.setAsynchronous(true);          }          return queue.enqueueMessage(msg, uptimeMillis);      }

上面两个正是把Message插入消息队列的方法.

从中能看出,Message是被插入到mQueue里面,实际是mLooper.mQueue.

每个Message.target = this,也就是target被设置成了当前的Handler实例.

到此,我们有必要看看Looper是做一些什么的了.

Looper

这是Looper一个标准的使用例子.

class LooperThread extends Thread {          public Handler mHandler;          public void run() {          Looper.prepare();                  ......          Looper.loop();         }  }

我们再看看Looper.prepare()和Looper.loop()的实现.

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));      }    public static Looper myLooper() {          return sThreadLocal.get();      }    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.recycleUnchecked();          }      }

prepare()方法给sThreadLocal设置了一个Looper实例.

sThreadLocal是Thread Local Variables,线程本地变量.

每次调用myLooper()方法就能返回prepare()设置的Looper实例.

Looper()方法里面有一个很显眼的无限For循环,它就是用来不断的处理messageQueue中的Message的.

最终会调用message.target.dispatchMessage(msg)方法.前面介绍过,target是handler的实例.下面看看handler.dispatchMessage()方法的实现.

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

实现非常简单,如果callback不为空则用handleCallback(msg)来处理message.

而大多数情况下,我们实例化Handler的时候都没有传callback,所以都会走到handler.handleMessage()方法了.这方法用过Handler的人,都在再熟悉不过了.

这就是Handler和Looper协同工作的原理.消息队列的实现都在Looper,Handler更像是一个辅助类.

HandlerThread

多数情况下,我们都是用Handler来处理UI界面的更新,这时我们要保证handler的Looper是UI线程的Looper.

只需要这样子实例化Handler就能保证在UI线程处理Message了:Handler handler = new Handler(Looper.getMainLooper());

而当我们不希望Handler在UI线程去处理Message时候,就需要新建一个线程然后把线程的Looper传给Handler做实例化.

也许我们会写出下面类似的代码(样例代码引用<深入理解Android>)

class LooperThread extends Thread {          public Looper myLooper = null;      // 定义一个public 的成员myLooper,初值为空。          public void run() {           // 假设run 在线程2 中执行                  Looper.prepare();                  // myLooper 必须在这个线程中赋值                  myLooper = Looper.myLooper();                  Looper.loop();          }  }    // 下面这段代码在线程1 中执行,并且会创建线程2  {          LooperThread lpThread= new LooperThread;          lpThread.start();//start 后会创建线程2          Looper looper = lpThread.myLooper;//<====== 注意          // thread2Handler 和线程2 的Looper 挂上钩          Handler thread2Handler = new Handler(looper);          //sendMessage 发送的消息将由线程2 处理        threadHandler.sendMessage(...)  }

细心的你们可能已经一眼看穿,new Handler(looper);传进来的looper可能为空.

原因是Looper looper = lpThread.myLooper时候,lpThread.myLooper可能为空,因为lpThread还没有开始执行run()方法.

那要怎么样才能保证handler实例化时候,looper不为空呢.

Android给我们提供了完美的解决方案,那就是HandlerThread.

public class HandlerThread extends Thread{          // 线程1 调用getLooper 来获得新线程的Looper          public Looper getLooper() {                  ......                  synchronized (this) {                          while (isAlive() && mLooper == null) {                                  try {                                          wait();// 如果新线程还未创建Looper,则等待                                  } catch (InterruptedException e) {                                  }                          }                  }                  return mLooper;          }            // 线程2 运行它的run 函数,looper 就是在run 线程里创建的。          public void run() {                  mTid = Process.myTid();                  Looper.prepare(); // 创建这个线程上的Looper                  synchronized (this) {              mLooper = Looper.myLooper();                          notifyAll();// 通知取Looper 的线程1,此时Looper 已经创建好了。                  }                  Process.setThreadPriority(mPriority);                  onLooperPrepared();                  Looper.loop();                  mTid = -1;          }  }

HandlerThread.getLooper()方法会等待mLooper被赋值了才返回.

在handler实例化调用handlerThread.getLooper()方法的时候,就能保证得到的Looper一定不为空了.

HandlerThread handlerThread = new HandlerThread();  handlerThread.start();  Handler handler = new Handler(handlerThread.getLooper());

 本文由用户 emxf2777 自行上传分享,仅供网友学习交流。所有权归原作者,若您的权利被侵害,请联系管理员。
 转载本站原创文章,请注明出处,并保留原始链接、图片水印。
 本站是一个以用户分享为主的开源技术平台,欢迎各类分享!
 本文地址:https://www.open-open.com/lib/view/open1454227058667.html
消息系统 安卓开发 Android开发 移动开发