最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

android線程消息機(jī)制之Handler詳解

 更新時(shí)間:2017年10月24日 08:32:49   作者:jyb_96  
這篇文章主要為大家詳細(xì)介紹了android線程消息機(jī)制之Handler的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

android線程消息機(jī)制主要由Handler,Looper,Message和MessageQuene四個(gè)部分組成。平常在開(kāi)發(fā)中,我們常用來(lái)在子線程中通知主線程來(lái)更新,其實(shí)整個(gè)安卓生命周期的驅(qū)動(dòng)都是通過(guò)Handler(ActivityThread.H)來(lái)實(shí)現(xiàn)的。

首先我們先介紹這四個(gè)類的作用:

Handler:消息的發(fā)送者。負(fù)責(zé)將Message消息發(fā)送到MessageQueue中。以及通過(guò)Runnable,Callback或者h(yuǎn)andleMessage()來(lái)實(shí)現(xiàn)消息的回調(diào)處理

Looper:是消息的循環(huán)處理器,它負(fù)責(zé)從MessageQueue中取出Message對(duì)象進(jìn)行處理。(Looper含有MessageQueue的引用)

Message:是消息載體,通過(guò)target來(lái)指向handler的引用。通過(guò)object來(lái)包含業(yè)務(wù)邏輯數(shù)據(jù)。其中MessagePool為消息池,用于回收空閑的Message對(duì)象的。

MessageQueue:消息隊(duì)列,負(fù)責(zé)維護(hù)待處理的消息對(duì)象。

通過(guò)上面的圖,我們可以比較清楚地知道他們的作用以及關(guān)系。接下來(lái),我們從源碼角度來(lái)分析這種關(guān)系是如何建立的。

public Handler(Looper looper, Callback callback, boolean async) {
  mLooper = looper;
  mQueue = looper.mQueue;
  mCallback = callback;
  mAsynchronous = async;
}

hander的其它構(gòu)造方法可以自己去查看,通過(guò)這個(gè)構(gòu)造方法,我們知道,handler持有MessageQueue的引用。所以可以方便地將Message加入到隊(duì)列中去。

通過(guò)源碼我們發(fā)現(xiàn),sendMessage->sendMessageDelayed->sendMessageAtTime->enqueueMessage

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

都是通過(guò)enqueueMessage將message將加入到MessageQueue中。

接下來(lái),我們看Message是如何構(gòu)造的。通過(guò)Message的構(gòu)造方法。

public static Message obtain() {
  synchronized (sPoolSync) {
    if (sPool != null) {
      Message m = sPool;
      sPool = m.next;
      m.next = null;
      m.flags = 0; // clear in-use flag
      sPoolSize--;
      return m;
    }
  }
  return new Message();
}

我們看到,Message是通過(guò)obtain的靜態(tài)方法從消息池sPool中拿到的。這樣可以做到消息的復(fù)用。

public static Message obtain(Handler h) {
  Message m = obtain();
  m.target = h;

  return m;
}

其中有一個(gè)重載方法中m.target = h;這段代碼非常重要,便于后面找到消息的目標(biāo)handler進(jìn)行處理。

接下來(lái),我們來(lái)看Looper。我們知道Looper通過(guò)過(guò)Looper.loop來(lái)進(jìn)入循環(huán)的,而循環(huán)是通過(guò)線程的run方法的驅(qū)動(dòng)的。

首先我們知道,我們?cè)趧?chuàng)建Handler的時(shí)候,都沒(méi)有去創(chuàng)建Looper,那么Looper哪里來(lái)的呢?

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.myLooper()

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

ThreadLocal是線程創(chuàng)建線程局部變量的類。表示此變量只屬于當(dāng)前線程。

  public T get() {
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null) {
      ThreadLocalMap.Entry e = map.getEntry(this);
      if (e != null) {
        @SuppressWarnings("unchecked")
        T result = (T)e.value;
        return result;
      }
    }
    return setInitialValue();
  }

我們看到了sThreadLocal.get()的方法實(shí)際是取當(dāng)前線程中的Looper對(duì)象。

那么我們主線程的Looper到底在哪里創(chuàng)建的呢?
而我們清楚地知道,如果在子線程中創(chuàng)建handler調(diào)用,則需要使用Looper.prepare方法。

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

我們看到此方法中,如果此線程中沒(méi)有Looper對(duì)象,則創(chuàng)建一個(gè)Looper對(duì)象。接下來(lái)我們?cè)谠创a中看到一個(gè)熟悉的方法。

  public static void prepareMainLooper() {
    prepare(false);
    synchronized (Looper.class) {
      if (sMainLooper != null) {
        throw new IllegalStateException("The main Looper has already been prepared.");
      }
      sMainLooper = myLooper();
    }
  }


此方法單獨(dú)的創(chuàng)建了一個(gè)sMainLooper用于主線程的Looper。這個(gè)prepareMainLooper到底在哪里調(diào)用呢?

高過(guò)引用指向發(fā)現(xiàn),我們?cè)贏ctivityThread.main()方法中發(fā)現(xiàn)

  public static void main(String[] args) {
    ...
    Looper.prepareMainLooper();

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

    if (sMainThreadHandler == null) {
      sMainThreadHandler = thread.getHandler();
    }

    if (false) {
      Looper.myLooper().setMessageLogging(new
          LogPrinter(Log.DEBUG, "ActivityThread"));
    }

    // End of event ActivityThreadMain.
    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
    Looper.loop();

    throw new RuntimeException("Main thread loop unexpectedly exited");
  }

而ActivityThread.main()是程序的入口方法。這樣我們就非常清楚了,主線程的Looper在程序的啟動(dòng)過(guò)程中就已經(jīng)創(chuàng)建并循環(huán)。

那么如果在子線程中創(chuàng)建Looper該如何正確調(diào)用呢?

class LooperThread extends Thread {
   public Handler mHandler;

   public void run() {
     Looper.prepare();

     mHandler = new Handler() {
       public void handleMessage(Message msg) {
         // process incoming messages here
       }
     };

     Looper.loop();
   }
 }

接下來(lái),我們需要看下Looper.loop()的執(zhí)行方法

public static void loop() {
    final Looper me = myLooper();//拿到當(dāng)前線程的looper
    if (me == null) {
      throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
    }
    final MessageQueue queue = me.mQueue;//拿到當(dāng)前l(fā)ooper的消息隊(duì)列

    // 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 (;;) {//死循環(huán)遍歷消息體。如果為null,則休眠。
      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 slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;

      final long traceTag = me.mTraceTag;
      if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
        Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
      }
      final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
      final long end;
      try {
        msg.target.dispatchMessage(msg);//此處是真正的分發(fā)消息。此處的target即是handler對(duì)象
        end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
      } finally {
        if (traceTag != 0) {
          Trace.traceEnd(traceTag);
        }
      }
      if (slowDispatchThresholdMs > 0) {
        final long time = end - start;
        if (time > slowDispatchThresholdMs) {
          Slog.w(TAG, "Dispatch took " + time + "ms on "
              + Thread.currentThread().getName() + ", h=" +
              msg.target + " cb=" + msg.callback + " msg=" + msg.what);
        }
      }

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

最后我們看下dispatchMessage的處理方法。

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

我們看到,dispatchMessage是優(yōu)化處理msg.callback,然后就是實(shí)現(xiàn)的Callback接口,最后才是handleMessage方法。

重點(diǎn)說(shuō)明:

1、handler在實(shí)例化的時(shí)候,持有Looper的引用。是通過(guò)ThreadLocal與Handler進(jìn)行關(guān)聯(lián)的。

2、Message在實(shí)例化的過(guò)程中,通過(guò)target 持有Handler的引用。

3、通常一個(gè)線程對(duì)應(yīng)一個(gè)Looper.一個(gè)Looper可以屬于多個(gè)Handler。

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

相關(guān)文章

最新評(píng)論

鄂州市| 奉贤区| 高碑店市| 开阳县| 都安| 大方县| 朝阳区| 凭祥市| 沽源县| 农安县| 扎囊县| 曲靖市| 邹平县| 龙南县| 崇信县| 商丘市| 榆树市| 常宁市| 紫阳县| 宁津县| 湘潭县| 蓝田县| 全南县| 利津县| 柞水县| 资阳市| 庆阳市| 个旧市| 大兴区| 台东县| 曲周县| 怀仁县| 皮山县| 日照市| 于都县| 诸暨市| 乐亭县| 合江县| 金阳县| 东港市| 澎湖县|