欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android Handler工作原理解析

 更新時(shí)間:2017年02月28日 14:48:53   作者:kalun527  
這篇文章主要為大家詳細(xì)介紹了Android Handler的原理,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

簡(jiǎn)介

在Android 中,只有主線程才能操作 UI,但是主線程不能進(jìn)行耗時(shí)操作,否則會(huì)阻塞線程,產(chǎn)生 ANR 異常,所以常常把耗時(shí)操作放到其它子線程進(jìn)行。如果在子線程中需要更新 UI,一般是通過(guò) Handler 發(fā)送消息,主線程接受消息并且進(jìn)行相應(yīng)的邏輯處理。除了直接使用 Handler,還可以通過(guò) View 的 post 方法以及 Activity 的 runOnUiThread 方法來(lái)更新 UI,它們內(nèi)部也是利用了Handler 。在上一篇文章 Android AsyncTask源碼分析 中也講到,其內(nèi)部使用了 Handler 把任務(wù)的處理結(jié)果傳回 UI 線程。

本文深入分析 Android 的消息處理機(jī)制,了解 Handler 的工作原理。

Handler

先通過(guò)一個(gè)例子看一下 Handler 的用法。

public class MainActivity extends AppCompatActivity {
  private static final int MESSAGE_TEXT_VIEW = 0;
  
  private TextView mTextView;
  private Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
      switch (msg.what) {
        case MESSAGE_TEXT_VIEW:
          mTextView.setText("UI成功更新");
        default:
          super.handleMessage(msg);
      }
    }
  };

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    mTextView = (TextView) findViewById(R.id.text_view);

    new Thread(new Runnable() {
      @Override
      public void run() {
        try {
          Thread.sleep(3000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        mHandler.obtainMessage(MESSAGE_TEXT_VIEW).sendToTarget();
      }
    }).start();

  }
}

上面的代碼先是新建了一個(gè) Handler的實(shí)例,并且重寫(xiě)了 handleMessage 方法,在這個(gè)方法里,便是根據(jù)接受到的消息的類(lèi)型進(jìn)行相應(yīng)的 UI 更新。那么看一下 Handler的構(gòu)造方法的源碼:

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

在構(gòu)造方法中,通過(guò)調(diào)用 Looper.myLooper() 獲得了 Looper 對(duì)象。如果 mLooper 為空,那么會(huì)拋出異常:"Can't create handler inside thread that has not called Looper.prepare()",意思是:不能在未調(diào)用 Looper.prepare() 的線程創(chuàng)建 handler。上面的例子并沒(méi)有調(diào)用這個(gè)方法,但是卻沒(méi)有拋出異常。其實(shí)是因?yàn)橹骶€程在啟動(dòng)的時(shí)候已經(jīng)幫我們調(diào)用過(guò)了,所以可以直接創(chuàng)建 Handler 。如果是在其它子線程,直接創(chuàng)建 Handler 是會(huì)導(dǎo)致應(yīng)用崩潰的。

在得到 Handler 之后,又獲取了它的內(nèi)部變量 mQueue, 這是 MessageQueue 對(duì)象,也就是消息隊(duì)列,用于保存 Handler 發(fā)送的消息。

到此,Android 消息機(jī)制的三個(gè)重要角色全部出現(xiàn)了,分別是 Handler 、Looper 以及 MessageQueue。 一般在代碼我們接觸比較多的是 Handler ,但 Looper 與 MessageQueue 卻是 Handler 運(yùn)行時(shí)不可或缺的。

Looper

上一節(jié)分析了 Handler 的構(gòu)造,其中調(diào)用了 Looper.myLooper() 方法,下面是它的源碼:

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

public static @Nullable Looper myLooper() {
  return sThreadLocal.get();
}

這個(gè)方法的代碼很簡(jiǎn)單,就是從 sThreadLocal 中獲取 Looper 對(duì)象。sThreadLocal 是 ThreadLocal 對(duì)象,這說(shuō)明 Looper 是線程獨(dú)立的。

在 Handler 的構(gòu)造中,從拋出的異??芍總€(gè)線程想要獲得 Looper 需要調(diào)用 prepare() 方法,繼續(xù)看它的代碼:

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

同樣很簡(jiǎn)單,就是給 sThreadLocal 設(shè)置一個(gè) Looper。不過(guò)需要注意的是如果 sThreadLocal 已經(jīng)設(shè)置過(guò)了,那么會(huì)拋出異常,也就是說(shuō)一個(gè)線程只會(huì)有一個(gè) Looper。創(chuàng)建 Looper 的時(shí)候,內(nèi)部會(huì)創(chuàng)建一個(gè)消息隊(duì)列:

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

現(xiàn)在的問(wèn)題是, Looper看上去很重要的樣子,它到底是干嘛的?
回答: Looper 開(kāi)啟消息循環(huán)系統(tǒng),不斷從消息隊(duì)列 MessageQueue 取出消息交由 Handler 處理。

為什么這樣說(shuō)呢,看一下 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();
  
  //無(wú)限循環(huán)
  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();
  }
}

這個(gè)方法的代碼有點(diǎn)長(zhǎng),不去追究細(xì)節(jié),只看整體邏輯??梢钥闯?,在這個(gè)方法內(nèi)部有個(gè)死循環(huán),里面通過(guò) MessageQueue 的next() 方法獲取下一條消息,沒(méi)有獲取到會(huì)阻塞。如果成功獲取新消息,便調(diào)用 msg.target.dispatchMessage(msg),msg.target是 Handler 對(duì)象(下一節(jié)會(huì)看到),dispatchMessage 則是分發(fā)消息(此時(shí)已經(jīng)運(yùn)行在 UI 線程),下面分析消息的發(fā)送及處理流程。

消息發(fā)送與處理

在子線程發(fā)送消息時(shí),是調(diào)用一系列的 sendMessage、sendMessageDelayed 以及 sendMessageAtTime 等方法,最終會(huì)輾轉(zhuǎn)調(diào)用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);
}

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
  msg.target = this;
  if (mAsynchronous) {
    msg.setAsynchronous(true);
  }
  return queue.enqueueMessage(msg, uptimeMillis);
}

這個(gè)方法就是調(diào)用 enqueueMessage 在消息隊(duì)列中插入一條消息,在 enqueueMessage總中,會(huì)把 msg.target 設(shè)置為當(dāng)前的Handler 對(duì)象。

消息插入消息隊(duì)列后, Looper 負(fù)責(zé)從隊(duì)列中取出,然后調(diào)用 Handler 的 dispatchMessage 方法。接下來(lái)看看這個(gè)方法是怎么處理消息的:

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

首先,如果消息的 callback 不是空,便調(diào)用 handleCallback 處理。否則判斷 Handler 的 mCallback 是否為空,不為空則調(diào)用它的 handleMessage方法。如果仍然為空,才調(diào)用 Handler 自身的 handleMessage,也就是我們創(chuàng)建 Handler 時(shí)重寫(xiě)的方法。

如果發(fā)送消息時(shí)調(diào)用 Handler 的 post(Runnable r)方法,會(huì)把 Runnable封裝到消息對(duì)象的 callback,然后調(diào)用sendMessageDelayed,相關(guān)代碼如下:

public final boolean post(Runnable r)
{
  return sendMessageDelayed(getPostMessage(r), 0);
}
private static Message getPostMessage(Runnable r) {
  Message m = Message.obtain();
  m.callback = r;
  return m;
}

此時(shí)在 dispatchMessage中便會(huì)調(diào)用 handleCallback進(jìn)行處理:

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

可以看到是直接調(diào)用了 run 方法處理消息。

如果在創(chuàng)建 Handler時(shí),直接提供一個(gè) Callback 對(duì)象,消息就交給這個(gè)對(duì)象的 handleMessage 方法處理。Callback 是 Handler內(nèi)部的一個(gè)接口:

public interface Callback {
  public boolean handleMessage(Message msg);
}

以上便是消息發(fā)送與處理的流程,發(fā)送時(shí)是在子線程,但處理時(shí) dispatchMessage 方法運(yùn)行在主線程。

總結(jié)

至此,Android消息處理機(jī)制的原理就分析結(jié)束了?,F(xiàn)在可以知道,消息處理是通過(guò) Handler 、Looper 以及 MessageQueue共同完成。 Handler 負(fù)責(zé)發(fā)送以及處理消息,Looper 創(chuàng)建消息隊(duì)列并不斷從隊(duì)列中取出消息交給 Handler, MessageQueue 則用于保存消息。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論