Android Handler怎么使用

发布时间:2021-12-18 16:26:23 作者:iii
来源:亿速云 阅读:133

本篇内容主要讲解“Android Handler怎么使用”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Android Handler怎么使用”吧!

ThreadLocal简介及其使用

对于线程Thread大家都挺熟悉的了,但是对于ThreadLocal可能就要陌生许多了。虽然我们对于它不太了解,但是它早在JDK1.2版本中就已问世并且被广泛的使用,比如hibernate,EventBus,Handler都运用了ThreadLocal进行线程相关的操作。如果单纯地从ThreadLocal这个名字来看,它带着浓浓的“本地线程”的味道;  然而,喝一口之后才发现根本就不是这个味儿。其实,ThreadLocal并不是用来操作什么本地线程而是用于实现不同线程的数据副本。当使用ThreadLocal维护变量时,它会为每个使用该变量的线程提供独立的变量副本;每一个线程都可以独立地改变自己的副本并且不会影响其它线程所持有的对应的副本。所以,ThreadLocal的实际作用并不与它的名字所暗含的意义相吻合,或许改称为ThreadLocalVariable(线程本地变量)会更合适一些。

接下来,我们通过一个实例来瞅瞅ThreadLocal的使用方式

/**      * 原创作者:      * 谷哥的小弟      *      * 博客地址:      * http://blog.csdn.net/lfdfhl      */     private void testThreadLocal(){         mThreadLocal.set("东京热");         new HotThread1().start();         new HotThread2().start();         hot3=mThreadLocal.get();         try{             Thread.sleep(1000*4);             Log.i(TAG,"HotThread1获取到的变量值: "+hot1);             Log.i(TAG,"HotThread2获取到的变量值: "+hot2);             Log.i(TAG,"MainThread获取到的变量值: "+hot3);         }catch (Exception e){          }     }      private class HotThread1  extends Thread{         @Override         public void run() {             super.run();             mThreadLocal.set("北京热");             hot1=mThreadLocal.get();         }     }      private class HotThread2  extends Thread{         @Override         public void run() {             super.run();             mThreadLocal.set("南京热");             hot2=mThreadLocal.get();         }     }

查看输出结果:

HotThread1获取到的变量值: 北京热 HotThread2获取到的变量值: 南京热 MainThread获取到的变量值: 东京热

在这段代码中使用ThreadLocal保存String类型的数据,并且在主线程和两个子线程中为ThreadLocal设置了不同的值,然后再将这些值分别取出。结合输出日志可以发现:在不同的线程中访问了同一个ThreadLocal对象,但是通过mThreadLocal.get()得到的值却是不一样的;也就是说:它们之间没有发生相互的影响而是保持了彼此的独立。明白了ThreadLocal的这个特性之后,我们再去理解Looper的工作机制就会容易得多了。

Looper、线程、消息队列的关系

Google官方建议开发人员使用Handler实现异步刷新UI,我们在平常的工作中也很好地采纳了这个提议:首先在主线程中建立Handler,然后在子线程中利用handler.sendMessage(message)发送消息至主线程,最终消息在handleMessage(Message  msg) {}得到相应的处理。这个套路,大家都再熟悉不过了;现在换个角度,我们试试在子线程中建立Handler

private class LooperThread  extends Thread{         @Override         public void run() {             super.run();             Handler handler=new Handler();             //doing something         }     }

此处的代码很简单:LooperThread继承自Thread,并且在其run( )方法中新建一个Handler。

嗯哼,再运行一下,喔哦,报错了:

Can’t create handler inside thread that has not called Looper.prepare().

咦,有点出师不利呢,刚开始试就出错了…….没事,生活不就是无尽的挫折和希望嘛,这点小事嘛也不算。既然是在调用Handler的构造方法时报的错那就从该构造方法的源码入手,一探究竟:

public Handler() {     this(null, false); }  public Handler(Callback callback) {     this(callback, 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");         }     }      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; }

请注意第20行代码:

如果mLooper == null那么系统就会抛出刚才的错误:Can&rsquo;t create handler inside thread that has  not called  Looper.prepare()。这句话的意思是:如果在线程内创建handler必须调用Looper.prepare()。既然这个提示已经提示了我们该怎么做,那就加上这一行代码:

private class LooperThread  extends Thread{         @Override         public void run() {             super.run();             Looper.prepare();             Handler handler=new Handler();             System.out.println("add code : Looper.prepare()");             //doing something         }     }

既然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  * loop() after calling this method, and end it by calling 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()中利用一个Looper来初始化当前线程或者说初始化一个带有Looper的线程。

请注意第14行代码,它是这段源码的核心,现对其详细分析:

sThreadLocal.set(new Looper(quitAllowed));

在该行代码中一共执行了两个操作

(1) 构造Looper

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

在Looper的构造方法中初始化了一个消息队列MessageQueue和一个线程Thread。从这可看出:一个Looper对应着一个消息队列以及当前线程。

当收到消息Message后系统会将其存入消息队列中等候处理。至于Looper,它在Android的消息机制中担负着消息轮询的职责,它会不间断地查看MessageQueue中是否有新的未处理的消息;若有则立刻处理,若无则进入阻塞。

(2) 将此Looper保存到sThreadLocal中。

此处的sThreadLocal是定义在Looper类中的一个ThreadLocal类型变量

static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();

Looper是framework中的一个类,sThreadLocal是它的一个static  final变量。当在某一个Thread中执行Looper.prepare()时系统就会将与该Thread所对应的Looper保存到sThreadLocal中。不同的线程对着不同的Looper,但它们均由系统保存在sThreadLocal中并且互不影响,相互独立;并且可以通过sThreadLocal.get()获取不同线程所对应的Looper.

在调用prepare()方法后需要调用loop()方法开始消息的轮询,并且在需要的时候调用quit()方法停止消息的轮询

假若再次执行Looper.prepare()系统发现sThreadLocal.get()的值不再为null于是抛出异常:

Only one Looper may be created per thread,一个线程只能创建一个Looper!

小结:

  1. 一个线程对应一个Looper

  2. 一个Looper对应一个消息队列

  3. 一个线程对应一个消息队列

  4. 线程,Looper,消息队列三者一一对应

所以,在一个子线程中使用Handler的方式应该是这样的:

class LooperThread extends Thread {      public Handler mHandler;     public void run() {          Looper.prepare();          mHandler = new Handler() {              public void handleMessage(Message msg) {               }          };         Looper.loop();        }    }

看到这个范例,有的人可能心里就犯嘀咕了:为什么我们平常在MainActivity中使用Handler时并没有调用Looper.prepare()也没有报错呢?

这是因为UI线程是主线程,系统会自动调用Looper.prepareMainLooper()方法创建主线程的Looper和消息队列MessageQueue

Message的发送和处理过程

在讨论完Looper、线程、消息队列这三者的关系之后我们再来瞅瞅Android消息机制中对于Message的发送和处理。

平常最常用的方式:

handler.sendMessage(message)&mdash;&mdash;>发送消息

handleMessage(Message msg){}&mdash;&mdash;>处理消息

先来分析消息的入队。

Handler可以通过post()、postAtTime()、postDelayed()、postAtFrontOfQueue()等方法发送消息,除了postAtFrontOfQueue()之外这几个方法均会执行到sendMessageAtTime(Message  msg, long uptimeMillis)方法,源码如下:

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); }  public final boolean sendMessageAtFrontOfQueue(Message msg) {     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, 0); }  private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {     msg.target = this;     if (mAsynchronous) {         msg.setAsynchronous(true);     }     return queue.enqueueMessage(msg, uptimeMillis); }

在这里可以看到sendMessageAtTime()内部又调用了enqueueMessage(),在该方法内的重要操作:

给msg设置了target,请参见代码第25行此处的this就是当前Handler对象本身。在这就指明了该msg的来源&mdash;&mdash;它是由哪个Handler发出的,与此同时也指明了该msg的归宿&mdash;&mdash;它该由哪个Handler处理。不难发现,哪个Handler发出了消息就由哪个Handler负责处理。

将消息放入消息队列中,请参见代码第29行在enqueueMessage(msg,uptimeMillis)中将消息Message存放进消息队列中,距离触发时间最短的message排在队列最前面,同理距离触发时间最长的message排在队列的最尾端。若调用sendMessageAtFrontOfQueue()方法发送消息它会直接调用该enqueueMessage(msg,uptimeMillis)让消息入队只不过时间为延迟时间为0,也就是说该消息会被插入到消息队列头部优先得到执行。直觉告诉我们此处的消息队列mQueue就是该线程所对应的消息队列。可是光有直觉是不够的甚至是不可靠的。我们再回过头瞅瞅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");         }     }      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; }

(1) 获取Looper,请参见代码第10行

(2) 利用Looper的消息队列为mQueue赋值,请参见代码第15行

(3) 为mCallback赋值,,请参见代码第16行

(4) 为mAsynchronous赋值,,请参见代码第17行

嗯哼,看到了吧,这个mQueue就是从Looper中取出来的。在之前我们也详细地分析了Looper、线程、消息队列这三者的一一对应关系,所以此处的mQueue正是线程所对应的消息队列。

看完了消息的入队,再来分析消息的出队。

请看Looper中的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         final Printer logging = me.mLogging;         if (logging != null) {             logging.println(">>>>> Dispatching to " + msg.target + " " +                     msg.callback + ": " + msg.what);         }          final long traceTag = me.mTraceTag;         if (traceTag != 0) {             Trace.traceBegin(traceTag, msg.target.getTraceName(msg));         }         try {             msg.target.dispatchMessage(msg);         } finally {             if (traceTag != 0) {                 Trace.traceEnd(traceTag);             }         }          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();     } }

我们发现关于消息的处理是在一个死循环中就行的,请参见代码第13-55行。也就是说在该段代码中Looper一直在轮询消息队列MessageQueue。假若消息队列中没有未处理的消息(即queue.next()==null)则其进入阻塞block状态,假若消息队列中有待处理消息(即queue.next()!=null)则利用msg.target.dispatchMessage(msg)将该消息派发至对应的Handler。

到了这,可能有的人会有一个疑问:系统怎么知道把消息发送给哪个Handler呢?

嘿嘿,还记不记得enqueueMessage()中系统给msg设置了target从而确定了其目标Handler么?嗯哼,所以只要通过msg.target.dispatchMessage(msg)就可以将消息派发至对应的Handler了。那在dispatchMessage()中又会对消息做哪些操作呢?我们继续跟进源码

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

哇哈,看到这,心情就舒畅多了,基本上回到了我们熟悉的地方;在此处对Message消息进行了处理,我们来瞅瞅主要的步骤

处理Message的回调callback,请参见代码第3行

比如调用handler.post(Runnable runnable)时,该runnable就会被系统封装为Message的callback。

关于这点在源码中也有非常直观的体现:

private static Message getPostMessage(Runnable r) {    Message m = Message.obtain();    m.callback = r;    return m; }

处理Handler的回调callback,请参见代码第6行

比如执行Handler handler=Handler(Callback  callback)时就会将callback赋值给mCallback,关于这点已经在介绍Handler构造方法时分析过了,不再赘述。

第三步:

调用handleMessage()处理消息Message,请参见代码第10行

handleMessage()的源码如下:

public void handleMessage(Message msg) {  }

嗯哼,它是一个空的方法。所以Handler的子类需要覆写该方法,并在其中处理接收到的消息。

梳理Handler工作机制

至此,关于Handler的异步机制及其实现原理已经分析完了。在此,对其作一个全面的梳理和总结。

Android异步消息机制中主要涉及到:Thread、Handler、MessageQueue、Looper,在整个机制中它们扮演着不同的角色也承担着各自的不同责任。

线程中的操作是由各自的业务逻辑所决定的,视具体情况进行。

通常的做法是在主线程中建立Handler并利用它在子线程中向主线程发送消息,在主线程接收到消息后会对其进行处理

Handler发出的消息均会被保存到消息队列MessageQueue中,系统会根据Message距离触发时间的长短决定该消息在队列中位置。在队列中的消息会依次出队得到相应的处理。

Looper使用其loop()方法一直轮询消息队列,并在消息出队时将其派发至对应的Handler.

到此,相信大家对“Android Handler怎么使用”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

推荐阅读:
  1. android_handler简单使用,测试
  2. Android学习笔记:Handler初步

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

android handler

上一篇:SwitchGlass for Mac是什么

下一篇:如何进行springboot配置templates直接访问的实现

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》