Android Handler消息传递机制详解(2)

1 for (;;) { 2 Message msg = queue.next(); // might block 3 if (msg == null) { 4 // No message indicates that the message queue is quitting. 5 return; 6 } 7 8 // This must be in a local variable, in case a UI event sets the logger 9 Printer logging = me.mLogging; 10 if (logging != null) { 11 logging.println(">>>>> Dispatching to " + msg.target + " " + 12 msg.callback + ": " + msg.what); 13 } 14 15 msg.target.dispatchMessage(msg); 16 17 if (logging != null) { 18 logging.println("<<<<< Finished to " + msg.target + " " + msg.callback); 19 } 20 21 // Make sure that during the course of dispatching the 22 // identity of the thread wasn't corrupted. 23 final long newIdent = Binder.clearCallingIdentity(); 24 if (ident != newIdent) { 25 Log.wtf(TAG, "Thread identity changed from 0x" 26 + Long.toHexString(ident) + " to 0x" 27 + Long.toHexString(newIdent) + " while dispatching to " 28 + msg.target.getClass().getName() + " " 29 + msg.callback + " what=" + msg.what); 30 } 31 32 msg.recycleUnchecked(); 33 }

    很明显第1行用了一个死循环,第2行从queue中取出Message,第15行通过dispatchMessage(Message msg)方法将消息发送给Handler。

4.HandlerThread介绍

  Android API解释:

  Handy class for starting a new thread that has a looper. The looper can then be used to create handler classes. Note that start() must still be called.

  意思是说:这个类启动一个新的线程并且创建一个Looper,这个Looper可以用来创建一个Handler类,完了之后一定要启动这个线程。

  什么时候使用HandlerThread?

    1.主线程需要通知子线程执行耗时操作(一般都是子线程执行耗时操作,完了之后,发送消息给主线程更新UI)。

    2.开发中可能会多次创建匿名线程,这样可能会消耗更多的系统资源。而HandlerThread自带Looper使他可以通过消息来多次重复使用当前线程,节省开支;

  下面是HandlerThread应用部分代码:

1   private static final String TAG = "MainActivity"; 2 private static final int FLAG_TEST = 1; 3 4 @Override 5 protected void onCreate(Bundle savedInstanceState) { 6 super.onCreate(savedInstanceState); 7 setContentView(R.layout.activity_main); 8 Log.i(TAG,"main thread:"+Thread.currentThread()); 9 HandlerThread thread = new HandlerThread("handler thread"); 10 thread.start();//一定要启动该线程 11 Handler handler = new Handler(thread.getLooper()){ 12 @Override 13 public void handleMessage(Message msg) { 14 Log.i(TAG,"handler thread:"+Thread.currentThread()); 15 switch (msg.what){ 16 case FLAG_TEST: 17 //耗时操作... 18 break; 19 default: 20 break; 21 } 22 super.handleMessage(msg); 23 } 24 }; 25 handler.sendEmptyMessage(FLAG_TEST); 26 }

    log:

com.example.administrator.handlertest I/MainActivity﹕ main thread:Thread[main,5,main] com.example.administrator.handlertest I/MainActivity﹕ handler thread:Thread[handler thread,5,main]

  通过log可以看出handler处在一个子线程中,这样就能够执行一些耗时操作。

  第十一行通过thread.getLooper()来创建handler,那么我们来看下getLooper()里面的源码:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/b6d25354526072f57dde4f693ff7632b.html