亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Android Handler消息派發(fā)機(jī)制源碼分析

 更新時(shí)間:2016年07月13日 11:45:58   作者:Fndroid  
這篇文章主要為大家詳細(xì)分析了Android Handler消息派發(fā)機(jī)制源碼,感興趣的小伙伴們可以參考一下

注:這里只是說(shuō)一下sendmessage的一個(gè)過(guò)程,post就類似的
如果我們需要發(fā)送消息,會(huì)調(diào)用sendMessage方法

 public final boolean sendMessage(Message msg)
{
 return sendMessageDelayed(msg, 0);
} 

這個(gè)方法會(huì)調(diào)用如下的這個(gè)方法 

public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
 if (delayMillis < 0) {
  delayMillis = 0;
 }
 return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}

接下來(lái)設(shè)定延遲時(shí)間,然后繼續(xù)調(diào)用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);
}

這里獲得了消息隊(duì)列,檢查隊(duì)列是否存在,然后返回enqueMessage的方法的執(zhí)行結(jié)果,這個(gè)結(jié)果是說(shuō)明消息能否進(jìn)入隊(duì)列的一個(gè)布爾值 

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

這里是對(duì)消息進(jìn)行入隊(duì)處理,下面就是在MessageQueue中對(duì)消息進(jìn)行入隊(duì) 

boolean enqueueMessage(Message msg, long when) {
 if (msg.target == null) {
  throw new IllegalArgumentException("Message must have a target.");
 }
 if (msg.isInUse()) {
  throw new IllegalStateException(msg + " This message is already in use.");
 }

 synchronized (this) {
  if (mQuitting) {
   IllegalStateException e = new IllegalStateException(
     msg.target + " sending message to a Handler on a dead thread");
   Log.w(TAG, e.getMessage(), e);
   msg.recycle();
   return false;
  }

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

就是對(duì)傳遞過(guò)來(lái)的消息進(jìn)行一些封裝然后放到隊(duì)列中,至此我們的sendMessage處理完畢,返回的結(jié)果是進(jìn)隊(duì)是否成功的布爾值,那么究竟消息之后是如何被處理的呢?
我們可以看到在Handler構(gòu)造的時(shí)候記錄了一個(gè)Looper對(duì)象,也記錄了一個(gè)回掉函數(shù) 

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

這里的myLooper方法返回的是當(dāng)前線程關(guān)聯(lián)的一個(gè)Looper對(duì)象

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

當(dāng)Looper實(shí)例化了以后會(huì)執(zhí)行自己的prepare方法然后執(zhí)行l(wèi)oop方法,loop方法就是不斷的讀取消息隊(duì)列中的消息然后執(zhí)行相應(yīng)的操作的方法,因?yàn)槭窃谄渌€程中執(zhí)行的循環(huán)所以不會(huì)影響其他線程 

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

在循環(huán)中如果讀取到了消息,就會(huì)執(zhí)行dispatchMessage方法,然后分派完消息之后再執(zhí)行一次recycleUnchecked方法來(lái)重用這個(gè)Message,我們看到dispatchMessage方法 

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

這里看到直接執(zhí)行了一個(gè)handlerMessage方法,這個(gè)方法是一個(gè)回調(diào)方法,我們是必須實(shí)現(xiàn)的,否則Handler什么都不會(huì)做,為什么呢?還記得剛剛說(shuō)構(gòu)造Handler的時(shí)候我們記錄了一個(gè)CallBack的回掉嗎?Handler中的這個(gè)handlerMessage方法是一個(gè)空方法,如果我們重寫了這個(gè)方法,在回調(diào)的時(shí)候就會(huì)執(zhí)行我們先寫下的代碼,也就是接收到消息之后要做什么。 

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

public void handleMessage(Message msg) {
}

這里簡(jiǎn)單說(shuō)下整個(gè)過(guò)程: 
當(dāng)我們實(shí)例化一個(gè)Handler的子類并重寫handleMessage方法之后,這個(gè)時(shí)候系統(tǒng)已經(jīng)幫我們做了幾個(gè)事情 
1.實(shí)例化了一個(gè)消息隊(duì)列MessageQueue 
2.實(shí)例化了一個(gè)關(guān)聯(lián)的Looper對(duì)象,并讓Looper不斷的讀取消息隊(duì)列
3.把我們重寫的handleMessage方法記錄為我們需要回調(diào)的方法 
當(dāng)我們執(zhí)行Handler的sendMessage方法的時(shí)候,系統(tǒng)會(huì)把我們傳過(guò)去的Message對(duì)象添加到消息隊(duì)列,這個(gè)時(shí)候如果Looper讀取到了消息,就會(huì)把消息派發(fā)出去,然后回調(diào)handleMessage方法,執(zhí)行我們?cè)O(shè)定的代碼。

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

相關(guān)文章

最新評(píng)論