当前位置: 移动技术网 > 移动技术>移动开发>Android > Android消息机制Handler的工作过程详解

Android消息机制Handler的工作过程详解

2019年07月24日  | 移动技术网移动技术  | 我要评论

综述

  在android系统中,出于对性能优化的考虑,对于android的ui操作并不是线程安全的。也就是说若是有多个线程来操作ui组件,就会有可能导致线程安全问题。所以在android中规定只能在ui线程中对ui进行操作。这个ui线程是在应用第一次启动时开启的,也称之为主线程(main thread),该线程专门用来操作ui组件,在这个ui线程中我们不能进行耗时操作,否则就会出现anr(application not responding)现象。如果我们在子线程中去操作ui,那么程序就回给我们抛出异常。这是因为在viewrootimpl中对操作ui的线程进行检查。如果操作ui的线程不是主线程则抛出异常(对于在检查线程之前在非ui线程已经操作ui组件的情况除外)。所以这时候我们若是在子线程中更新ui的话可以通过handler来完成这一操作。

handler用法简介

  在开发中,我们对handler的使用也基本上算是家常便饭了。在这里我们就简单的说一下handler的几种用法示例,就不在具体给出demo进行演示。在这里我们只针对后面这一种情形来看一下handler的使用:在子线程完成任务后通过handler发送消息,然后在主线程中去操作ui。
  一般来说我们会在主线程中创建一个handler的匿名内部类,然后重写它的handlemessage方法来处理我们的ui操作。代码如下所示。

private handler mhandler = new handler(){
  @override
  public void handlemessage(message msg) {
    switch (msg.what){
      //根据msg.what的值来处理不同的ui操作
      case what:
        break;
      default:
        super.handlemessage(msg);
        break;
    }

  }
};

  我们还可以不去创建一个handler的子类对象,直接去实现handler里的callback接口,handler通过回调callback接口里的handlemessage方法从而实现对ui的操作。

private handler mhandler = new handler(new handler.callback() {
  @override
  public boolean handlemessage(message msg) {

    return false;
  }
});

  然后我们就可以在子线程中发送消息了。

new thread(new runnable() {
  @override
  public void run() {
    //子线程任务
    ...
    //发送方式一 直接发送一个空的message
    mhandler.sendemptymessage(what);
    //发送方式二 通过sendtotarget发送
    mhandler.obtainmessage(what,arg1,arg2,obj).sendtotarget();
    //发送方式三 创建一个message 通过sendmessage发送
    message message = mhandler.obtainmessage();
    message.what = what;
    mhandler.sendmessage(message);
  }
}).start();

  在上面我们给出了三种不同的发送方式,当然对于我们还可以通过sendmessagedelayed进行延时发送等等。如果我们的handler只需要处理一条消息的时候,我们可以通过post一系列方法进行处理。

private handler mhandler = new handler();

new thread(new runnable() {
  @override
  public void run() {
    mhandler.post(new runnable() {
      @override
      public void run() {
        //ui操作
        ...
      }
    });
  }
}).start();

  在handler中处理ui操作时,上面的handler对象必须是在主线程创建的。如果我们想在子线程中去new一个handler对象的话,就需要为handler指定looper。

private handler mhandler;

new thread(new runnable() {
  @override
  public void run() {
    mhandler = new handler(looper.getmainlooper()){
      @override
      public void handlemessage(message msg) {
        super.handlemessage(msg);
        //ui操作
        ...
      }
    };

  }
}).start();

  对于这个looper是什么,下面我们会详细介绍。对于handler的使用依然存在一个问题,由于我们创建的handler是一个匿名内部类,他会隐式的持有外部类的一个对象(当然内部类也是一样的),而往往在子线程中是一个耗时的操作,而这个线程也持有handler的引用,所以这个子线程间接的持有这个外部类的对象。我们假设这个外部类是一个activity,而有一种情况就是我们的activity已经销毁,而子线程仍在运行。由于这个线程持有activity的对象,所以,在handler中消息处理完之前,这个activity就一直得不到回收,从而导致了内存泄露。如果内存泄露过多,则会导致oom(outofmemory),也就是内存溢出。那么有没有什么好的解决办法呢?
  我们可以通过两种方案来解决,第一种方法我们在activity销毁的同时也杀死这个子线程,并且将相对应的message从消息队列中移除;第二种方案则是我们创建一个继承自handler的静态内部类。因为静态内部类不会持有外部类的对象。可是这时候我们无法去访问外部类的非静态的成员变量,也就无法对ui进行操作。这时候我们就需要在这个静态内部类中使用弱引用的方式去指向这个activity对象。下面我们看一下示例代码。

static class myhandler extends handler{
  private final weakreference<myactivity> mactivity;

  public myhandler(myactivity activity){
    super();
    mactivity = new weakreference<myactivity>(activity);
  }

  @override
  public void handlemessage(message msg) {
    myactivity myactivity = mactivity.get();
    if (myactivity!=null){
      myactivity.textview.settext("123456789");
    }
  }
}

handler工作过程

  在上面我们简单的说明了handler是如何使用的。那么现在我们就来看一下这个handler是如何工作的。在android的消息机制中主要是由handler,looper,messagequeue,message等组成。而handler得运行依赖后三者。那么我们就来看一下它们是如何联系在一起的。

looper

  在一个android应用启动的时候,会创建一个主线程,也就是ui线程。而这个主线程也就是activitythread。在activitythread中有一个静态的main方法。这个main方法也就是我们应用程序的入口点。我们来看一下这个main方法。

public static void main(string[] args) {

  ......

  looper.preparemainlooper();

  activitythread thread = new activitythread();
  thread.attach(false);

  ......

  looper.loop();

  throw new runtimeexception("main thread loop unexpectedly exited");
}

  在上面代码中通过preparemainlooper方法为主线程创建一个looper,而loop则是开启消息循环。从上面代码我们可以猜想到在loop方法中应该存在一个死循环,否则给我们抛出runtimeexception。也就是说主线程的消息循环是不允许被退出的。下面我们就来看一下这个looper类。
  首先我们看一下looper的构造方法。

private looper(boolean quitallowed) {
  mqueue = new messagequeue(quitallowed);
  mthread = thread.currentthread();
}

  在这个构造方法中创建了一个消息队列。并且保存当前线程的对象。其中quitallowed参数表示是否允许退出消息循环。但是我们注意到这个构造方法是private,也就是说我们自己不能手动new一个looper对象。那么我们就来看一下如何创建一个looper对象。之后在looper类中我们找到下面这个方法。

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));
}

  在这里新建了一个looper对象,然后将这个对象保存在threadlocal中,当我们下次需要用到looper的之后直接从这个sthreadlocal中取出即可。在这里简单说明一下threadlocal这个类,threadlocal它实现了本地变量存储,我们将当前线程的数据存放在threadlocal中,若是有多个变量共用一个threadlocal对象,这时候在当前线程只能获取该线程所存储的变量,而无法获取其他线程的数据。在looper这个类中为我们提供了mylooper来获取当前线程的looper对象。从上面的方法还能够看出,一个线程只能创建一次looper对象。然后我们在看一下这个prepare在哪里被使用的。

public static void prepare() {
  prepare(true);
}

public static void preparemainlooper() {
  prepare(false);
  synchronized (looper.class) {
    if (smainlooper != null) {
      throw new illegalstateexception("the main looper has already been prepared.");
    }
    smainlooper = mylooper();
  }
}

    prepare方法:这个是用于在子线程中创建一个looper对象,在子线程中是可以退出消息循环的。
    preparemainlooper方法:这个方法在上面的activitythread中的main方法中我们就已经见到过了。它是为主线程创建一个looper,在主线程创建looper对象中,就设置了不允许退出消息循环。并且将主线程的looper保存在smainlooper中,我们可以通过getmainlooper方法来获取主线程的looper。
  在activitythread中的main方法中除了创建一个looper对象外,还做了另外一件事,那就是通过loop方法开启消息循环。那么我们就来看一下这个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.recycleunchecked();
  }
}

  第2~6行:获取当前线程中的looper,并从looper中获得消息队列。
  第10~11行:确保当前线程属于当前进程,并且记录真实的token。clearcallingidentity的实现是在native层,对于具体是如何实现的就不在进行分析。
  第14~18行:从消息队列中取出消息,并且只有当取出的消息为空的时候才会跳出循环。
  第27行:将消息重新交由handler处理。
  第35~42行:确保调用过程中线程没有被销毁。
  第44行:对消息进行回收处理。
  和我们刚才猜想的一样,在loop中确实存在一个死循环,而唯一退出该循环的方式就是消息队列返回的消息为空。然后我们通过消息队列的next()方法获得消息。msg.target是发送消息的handler,通过handler中的dispatchmessage方法又将消息交由handler处理。消息处理完成之后便对消息进行回收处理。在这里我们也能够通过quit和quitsafely退出消息循环。

public void quit() {
  mqueue.quit(false);
}

public void quitsafely() {
  mqueue.quit(true);
}

  我们可以看出对于消息循环的退出,实际上就是调用消息队列的quit方法。这时候从messagequeue的next方法中取出的消息也就是null了。下面我们来看一下这个messagequeue。

messagequeue

  messagequeue翻译为消息队里,在这个消息队列中是采用单链表的方式实现的,提高插入删除的效率。对于messagequeue在这里我们也只看一下它的入队和出队操作。
  messagequeue入队方法。

boolean enqueuemessage(message msg, long when) {

  ......

  synchronized (this) {

    ......

    msg.markinuse();
    msg.when = when;
    message p = mmessages;
    boolean needwake;
    if (p == null || when == 0 || when < p.when) {
      // new head, wake up the event queue if blocked.
      msg.next = p;
      mmessages = msg;
      needwake = mblocked;
    } else {
      // inserted within the middle of the queue. usually we don't have to wake
      // up the event queue unless there is a barrier at the head of the queue
      // and the message is the earliest asynchronous message in the queue.
      needwake = mblocked && p.target == null && msg.isasynchronous();
      message prev;
      for (;;) {
        prev = p;
        p = p.next;
        if (p == null || when < p.when) {
          break;
        }
        if (needwake && p.isasynchronous()) {
          needwake = false;
        }
      }
      msg.next = p; // invariant: p == prev.next
      prev.next = msg;
    }

    // we can assume mptr != 0 because mquitting is false.
    if (needwake) {
      nativewake(mptr);
    }
  }
  return true;
}

  在这里我们简单说一下这个入队的方法。消息的插入过程是在第13~36行完成了。在这里首先判断首先判断消息队列里有没有消息,没有的话则将当前插入的消息作为队头,并且这时消息队列如果处于等待状态的话则将其唤醒。若是在中间插入,则根据message创建的时间进行插入。
  messagequeue出队方法。

message next() {

  ......

  int nextpolltimeoutmillis = 0;
  for (;;) {
    if (nextpolltimeoutmillis != 0) {
      binder.flushpendingcommands();
    }

    nativepollonce(ptr, nextpolltimeoutmillis);

    synchronized (this) {
      // try to retrieve the next message. return if found.
      final long now = systemclock.uptimemillis();
      message prevmsg = null;
      message msg = mmessages;
      if (msg != null && msg.target == null) {
        // stalled by a barrier. find the next asynchronous message in the queue.
        do {
          prevmsg = msg;
          msg = msg.next;
        } while (msg != null && !msg.isasynchronous());
      }
      if (msg != null) {
        if (now < msg.when) {
          // next message is not ready. set a timeout to wake up when it is ready.
          nextpolltimeoutmillis = (int) math.min(msg.when - now, integer.max_value);
        } else {
          // got a message.
          mblocked = false;
          if (prevmsg != null) {
            prevmsg.next = msg.next;
          } else {
            mmessages = msg.next;
          }
          msg.next = null;
          if (debug) log.v(tag, "returning message: " + msg);
          msg.markinuse();
          return msg;
        }
      } else {
        // no more messages.
        nextpolltimeoutmillis = -1;
      }

      // process the quit message now that all pending messages have been handled.
      if (mquitting) {
        dispose();
        return null;
      }

      ......
    }

    .....
  }
}

  第11行:nativepollonce方法在native层,若是nextpolltimeoutmillis为-1,这时候消息队列处于等待状态。
  第25~42行:按照我们设置的时间取出消息。
  第43~45行:这时候消息队列中没有消息,将nextpolltimeoutmillis设为-1,下次循环消息队列则处于等待状态。
  第48~52行:退出消息队列,返回null,这时候looper中的消息循环也会终止。
  最后我们在看一下退出消息队列的方法:

void quit(boolean safe) {
  if (!mquitallowed) {
    throw new illegalstateexception("main thread not allowed to quit.");
  }

  synchronized (this) {
    if (mquitting) {
      return;
    }
    mquitting = true;

    if (safe) {
      removeallfuturemessageslocked();
    } else {
      removeallmessageslocked();
    }

    // we can assume mptr != 0 because mquitting was previously false.
    nativewake(mptr);
  }
}

  从上面我们可以看到主线程的消息队列是不允许被退出的。并且在这里通过将mquitting设为true从而退出消息队列。也使得消息循环被退出。到这里我们介绍了looper和messagequeue,就来看一下二者在handler中的作用。

handler

  在这里我们首先看一下handler的构造方法。

public handler(callback callback, boolean async) {

  ......

  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的线程中是无法创建一个handler对象的。所以说我们在子线程中创建一个handler时首先需要创建looper,并且开启消息循环才能够使用这个handler。但是在上面的例子中我们确实在子线程中new了一个handler对象。我们再来看一下上面那个例子的构造方法。

public handler(looper looper, callback callback, boolean async) {
  mlooper = looper;
  mqueue = looper.mqueue;
  mcallback = callback;
  masynchronous = async;
}

  在这个构造方法中我们为handler指定了一个looper对象。也就说在上面的例子中我们在子线程创建的handler中为其指定了主线程的looper,也就等价于在主线程中创建handler对象。下面我们就来看一下handler是如何发送消息的。
  对于handler的发送方式可以分为post和send两种方式。我们先来看一下这个post的发送方式。

public final boolean post(runnable r)
{
  return sendmessagedelayed(getpostmessage(r), 0);
}

  在这里很明显可以看出来,将post参数中的runnable转换成了message对象,然后还是通过send方式发出消息。我们就来看一下这个getpostmessage方法。

private static message getpostmessage(runnable r) {
  message m = message.obtain();
  m.callback = r;
  return m;
}

  在这里也是将我们实现的runnable交给了message对象的callback属性。并返回该message对象。
  既然post发送也是由send发送方式进行的,那么我们一路找下去,最终消息的发送交由sendmessageattime方法进行处理。我们就来看一下这个sendmessageattime方法。

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);
}

  然后再来看一下enqueuemessage方法。

private boolean enqueuemessage(messagequeue queue, message msg, long uptimemillis) {
  msg.target = this;
  if (masynchronous) {
    msg.setasynchronous(true);
  }
  return queue.enqueuemessage(msg, uptimemillis);
}

  到这里我们可以看出来了所谓通过handler发送消息只不过是在looper创建的消息队列中插入一条消息而已。而在looper中只不过通过loop取出消息,然后交由handler中的dispatchmessage方发进行消息分发处理。下面我们来看一下dispatchmessage方法。

public void dispatchmessage(message msg) {
  if (msg.callback != null) {
    handlecallback(msg);
  } else {
    if (mcallback != null) {
      if (mcallback.handlemessage(msg)) {
        return;
      }
    }
    handlemessage(msg);
  }
}

  这里面的逻辑也是非常的简单,msg.callback就是我们通过post里的runnable对象。而handlecallback也就是去执行runnable中的run方法。

private static void handlecallback(message message) {
  message.callback.run();
}

  mcallback就是我们所实现的回调接口。最后才是对我们继承handler类中重写的handlemessage进行执行。可见其中的优先级顺序为post>callback>send;
  到这里我们对整个handler的工作过程也就分析完了。现在我们想要通过主线程发送消息给子线程,然后由子线程接收消息并进行处理。这样一种操作也就很容易实现了。我们来看一下怎么实现。

package com.example.ljd.myapplication;

import android.os.bundle;
import android.os.handler;
import android.os.looper;
import android.os.message;
import android.util.log;
import android.support.v7.app.appcompatactivity;
import android.view.view;
import android.widget.button;


public class myactivity extends appcompatactivity {

  private final string tag = "myactivity";
  public handler mhandler;
  public button button;

  @override
  protected void oncreate(bundle savedinstancestate) {
    super.oncreate(savedinstancestate);
    setcontentview(r.layout.activity_main);
    button = (button) findviewbyid(r.id.send_btn);
    button.setonclicklistener(new view.onclicklistener() {
      @override
      public void onclick(view v) {
        if (mhandler != null){
          mhandler.obtainmessage(0,"你好,我是从主线程过来的").sendtotarget();
        }
      }
    });
    new thread(new runnable() {
      @override
      public void run() {
        //在子线程中创建一个looper对象
        looper.prepare();
        mhandler = new handler(){
          @override
          public void handlemessage(message msg) {
            if (msg.what == 0){
              log.d(tag,(string)msg.obj);
            }
          }
        };
        //开启消息循环
        looper.loop();
      }
    }).start();

  }
}

  点击按钮我们看一下运行结果。


总结

  在这里我们重新整理一下我们的思路,看一下这个handler的整个工作流程。在主线程创建的时候为主线程创建一个looper,创建looper的同时在looper内部创建一个消息队列。而在创键handler的时候取出当前线程的looper,并通过该looper对象获得消息队列,然后handler在子线程中发送消息也就是在该消息队列中添加一条message。最后通过looper中的消息循环取得这条message并且交由handler处理。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网