Android中Handler詳解

本文通過例子來驗證和說明使用Handler對象開啟的線程是否和主線程為在同一線程中。

程序結構圖如下:

  

[1] HandlerActivity.java中的源碼如下:
[html]
• package com.andyidea.handlerdemo2; 
•  
• import android.app.Activity; 
• import android.os.Bundle; 
• import android.os.Handler; 
• import android.os.HandlerThread; 
• import android.os.Looper; 
• import android.os.Message; 
• import android.util.Log; 
•  
• public class HandlerActivity extends Activity { 
•      
•     private Handler handler = new Handler(); 
•      
•     @Override 
•     public void onCreate(Bundle savedInstanceState) { 
•         super.onCreate(savedInstanceState); 
•         //handler.post(r); 
•         setContentView(R.layout.main); 
•         Log.e("activity–>" ,Thread.currentThread().getId() + ""); 
•         Log.e("activityname–>" ,Thread.currentThread().getName() + ""); 
•         
•         //與主線程同一線程 
•         handler.post(r); 
•          
•         //與主線程不同線程 
•         HandlerThread handlerThread = new HandlerThread("handler_thread"); 
•         handlerThread.start(); 
•         //HandlerThread線程對象要啟動後, 
•         //通過handlerThread.getLooper()方法才能獲得Looper對象 
•         MyHandler myHandler = new MyHandler(handlerThread.getLooper()); 
•         Message msg  = myHandler.obtainMessage(); 
•         msg.sendToTarget();  //發送消息的方式 
•     } 
•      
•     //創建一個線程對象 www..aiwalls.com  
•     Runnable r = new Runnable() { 
•          
•         @Override 
•         public void run() { 
•             Log.e("handler–>" ,Thread.currentThread().getId() + ""); 
•             Log.e("handlername–>" ,Thread.currentThread().getName() + ""); 
•             try{ 
•                 Thread.sleep(10*1000); 
•             }catch(InterruptedException e){ 
•                 e.printStackTrace(); 
•             } 
•         } 
•     }; 
•      
•     //創建Handler對象 
•     class MyHandler extends Handler{ 
•          
•         public MyHandler(){ 
•              
•         } 
•          
•         public MyHandler(Looper looper){ 
•             super(looper); 
•         } 
•  
•         @Override 
•         public void handleMessage(Message msg) { 
•             Log.e("handler–>" ,Thread.currentThread().getId() + ""); 
•             Log.e("handler–>" ,Thread.currentThread().getName() + ""); 
•         } 
•          
•     } 
• } 
 
運行程序後,我們通過Logcat控制臺的log.e輸出可以看到結果如下:
 
 
 

通過驗證,可以看到如果隻是通過Handler對象的post()方法,隻是把一個子線程對象放到主線程隊列中,並不是開啟瞭一個子線程。通過HandlerThread對象方式才是開啟瞭一個新的線程去執行程序。

摘自  黎明&歲月
 

發佈留言