Handler定義:
主要接受子線程發送來的數據,並用此數據配合主線程更新UI。
為什么要用Handler?
我們手機當中的很多功能或操作是不能都放在Activity當中的,比如下載文件、處理大量數據、復雜錯操作之類的。如果放在Activity中(即主線程中)的話,會出現長時間沒響應,甚至會出現ANR之類的錯誤(即5秒內沒響應),這樣的話就會造成一個很差的用戶體驗,所以這就顯示出了Handler的必要性。如果我們把那些費時費力的操作放在另外一個線程操作當中,這樣就能夠和主線程(UI)線程同步操作,不會出現長時間等待或沒響應的操作,是的用戶體驗大大提高。Handler就是實現上面的功能的一個東西。
【一】
下面我們先用一個簡單的例子演示一下Handler的最基本使用:
1、首先創建一個Handler對象,可以直接使用Handler無參構造函數創建Handler對象,
2、在監聽器中,調用Handler的post方法,將要執行的線程對象添加到線程隊列當中。此時將會把該線程對象添加到handler
3、將要執行的操作寫在線程對象的run方法中,一般是一個Runnable對象,復寫其中的run方法就可以了。
運行效果圖:
我們點擊starthandler按鈕之后,輸出框中就會每隔三秒輸出一次start,直到我們點擊endhandler按鈕之后,輸出框中的信息便不會輸出了。
主要代碼:
1 public class MainActivity extends Activity { 2 3 private Button mStartButton,mEndButton; 4 @Override 5 public void onCreate(Bundle savedInstanceState) { 6 super.onCreate(savedInstanceState); 7 setContentView(R.layout.activity_main); 8 mStartButton = (Button)findViewById(R.id.start); 9 mEndButton = (Button)findViewById(R.id.end); 10 11 mStartButton.setOnClickListener(new StartButtonListener()); 12 mEndButton.setOnClickListener(new EndButtonListener()); 13 } 14 15 private class StartButtonListener implements OnClickListener{ 16 @Override 17 public void onClick(View v) { 18 //立即將線程對象加入到handler消息隊列當中去,隊列是一種先進先出的數據結構,線程對象從消息隊列取出之后就會執行run()方法。 19 handler.post(runnable); 20 } 21 } 22 private class EndButtonListener implements OnClickListener{ 23 @Override 24 public void onClick(View v) { 25 /*將runnable此線程對象從handler消息隊列中remove掉, 26 之后消息隊列中將不會有runnable此線程對象,也就不會執行run()方法了*/ 27 handler.removeCallbacks(runnable); 28 } 29 } 30 //創建一個handler對象,每一個handler都有一個與之關聯的消息隊列 31 Handler handler = new Handler(); 32 //將要執行的操作寫在線程對象的run()方法中 33 Runnable runnable = new Runnable() { 34 @Override 35 public void run() { 36 System.out.println("start"); 37 //延遲3000毫秒把線程對象加入到消息隊列當中去,每3000毫秒再加進去一次,循環進行 38 handler.postDelayed(runnable, 3000); 39 } 40 }; 41 }
【二】
下面在用Handler實現一個progressbar自動更新的效果:
運行效果圖:
當我們點擊starthandler按鈕的時候,progressbar會自己更新,每秒增加相同的單位。
1、首先創建一個Handler對象,繼承Handler類,重寫handleMessage方法來創建Handler對象。
2、在監聽器中,調用Handler的post方法,將要執行的線程對象添加到線程隊列當中。此時將會把該線程對象添加到handler對象的線程隊列中。
3、將要執行的操作寫在線程對象的run方法中,一般是一個Runnable對象,復寫其中的run方法就可以了。
Handler包含了兩個隊列,其中一個是線程隊列,另外一個是消息隊列。使用post方法會將線程對象放到該handler的線程隊列中,使用sendMessage(Message message)將消息放到消息隊列中。
如果想要這個流程一直執行的話,可以在run方法內部執行postDelayed或者post方法,再將該線程對象添加到消息隊列中,重復執行。想要線程停止執行,調用Handler對象的removeCallbacks(Runnable r) 方法從線程隊列中移除線程對象,使線程停止執行。
Handler為Android 提供了一種異步消息處理機制,當向消息隊列中發送消息 (sendMessage)后就立即返回,而從消息隊列中讀取消息時會阻塞,其中從消息隊列中讀取消息時會執行Handler中的public void handleMessage(Message msg) 方法,因此在創建Handler時應該使用匿名內部類重寫該方法,在該方法中寫上讀取到消息后的操作,使用Handler的 obtainMessage() 來獲得消息對象。
主要代碼:
1 public class MainActivity extends Activity { 2 3 private Button mStartButton = null; 4 private ProgressBar mProgressBar = null; 5 private int i=0; 6 @Override 7 public void onCreate(Bundle savedInstanceState) { 8 super.onCreate(savedInstanceState); 9 setContentView(R.layout.activity_main); 10 11 mStartButton = (Button)findViewById(R.id.start); 12 mProgressBar = (ProgressBar)findViewById(R.id.progressBar); 13 14 mStartButton.setOnClickListener(new StartListener()); 15 } 16 public class StartListener implements OnClickListener{ 17 @Override 18 public void onClick(View arg0) { 19 handler.post(runnable); 20 } 21 } 22 Handler handler = new Handler(){ 23 @Override 24 public void handleMessage(Message msg) { 25 super.handleMessage(msg); 26 mProgressBar.setProgress(msg.arg1); 27 handler.post(runnable); 28 if(msg.arg1==100){ 29 handler.removeCallbacks(runnable); 30 mProgressBar.setProgress(0); 31 handler.post(runnable); 32 i=0; 33 } 34 } 35 }; 36 Runnable runnable = new Runnable() { 37 @Override 38 public void run() { 39 i = i+10; 40 Message message = handler.obtainMessage(); 41 //將message對象的的參數的值設置為i 42 message.arg1 = i; 43 try { 44 Thread.sleep(1000); 45 } catch (InterruptedException e) { 46 // TODO Auto-generated catch block 47 e.printStackTrace(); 48 } 49 if(i==100){ 50 handler.removeCallbacks(runnable); 51 mProgressBar.setProgress(0); 52 } 53 handler.sendMessage(message); 54 } 55 }; 56 }
【三】
Handler與線程的關系:
使用Handler的post方法將Runnable對象放到Handler的線程隊列中后,該Runnable的執行其實並未單獨開啟線程,而是仍然在當前Activity線程中執行的,Handler只是調用了Runnable對象的run方法。
下面我們用一個例子來證明一下,我們用打印線程的ID證明他們其實是在同一個線程運行。
運行效果圖:
如果在代碼中我們用:
//Thread thread = new Thread(runnable);
//thread.start();
這樣的方式啟動線程的話線程的ID和name就會不一樣,運行效果圖如下:
主要代碼如下:
1 public class MainActivity extends Activity { 2 Handler handler = new Handler(); 3 @Override 4 public void onCreate(Bundle savedInstanceState) { 5 super.onCreate(savedInstanceState); 6 //handler.post(runnable); 7 8 setContentView(R.layout.activity_main); 9 Thread thread = new Thread(runnable); 10 thread.start(); 11 System.out.println("ID============:"+Thread.currentThread().getId()); 12 System.out.println("NAME:"+Thread.currentThread().getName()); 13 } 14 Runnable runnable = new Runnable() { 15 @Override 16 public void run() { 17 System.out.println("RUNABLEID:::::::::::"+Thread.currentThread().getId()); 18 System.out.println("RUNABLENAME:"+Thread.currentThread().getName()); 19 try { 20 Thread.sleep(10000); 21 } catch (InterruptedException e) { 22 // TODO Auto-generated catch block 23 e.printStackTrace(); 24 } 25 } 26 }; 27 }
【四】
我們通過message傳遞數據,最后在handleMessage()方法中打印出我們所傳遞的數據。
Bundle是什么:
Bundle是一個特殊的map,它是傳遞信息的工具,它的鍵只能是string類型,而且值也只能是常見的基本數據類型。
如何讓Handler執行Runnable時打開新的線程:
1、首先生成一個HandlerThread對象,實現了使用Looper來處理消息隊列的功能,這個類由Android應用程序 框架提供
HandlerThread handlerThread = new HandlerThread("handler_thread");
2、在使用HandlerThread的getLooper()方法之前,必須先調用該類的start(); handlerThread.start();
3、根據這個HandlerThread對象得到其中的Looper對象。4、創建自定義的繼承於Handler類的子類,其中實現一個參數為Looper對象的構造方法,方法內容調用父類的構造函數即可。
5、使用第三步得到的Looper對象創建自定義的Handler子類的對象,再將消息(Message)發送到該Handler的消息隊列中,Handler復寫的handleMessage()將會執行來處理消息隊列中的消息。
消息,即Message對象,可以傳遞一些信息,可以使用arg1.arg2,Object傳遞一些整形或者對象,還可以使用Message對象的 setData(Bundle bundle)來講Bundle對象傳遞給新創建的線程,新創建的線程在執行handleMessage(Message msg)時可以從message中利用getData()提取出Bundle對象來進行處理。
執行效果圖:
主要代碼:
1 public class MainActivity extends Activity { 2 3 @Override 4 public void onCreate(Bundle savedInstanceState) { 5 super.onCreate(savedInstanceState); 6 setContentView(R.layout.activity_main); 7 System.out.println("Activity------------->"+ Thread.currentThread().getId()); 8 9 HandlerThread handlerThread = new HandlerThread("handlerThread"); 10 //在使用handlerThread的getLopper()方法之前必須先調用該類的start()方法,不然會報空指針 11 handlerThread.start(); 12 13 MyHandler myHandler = new MyHandler(handlerThread.getLooper()); 14 Message message = myHandler.obtainMessage(); 15 //將msg發送到目標對象,所謂的目標對象,就是生成該msg對象的handler對象 16 Bundle bundle = new Bundle(); 17 bundle.putInt("age", 23); 18 bundle.putString("name", "gaojicai"); 19 message.setData(bundle); 20 21 message.sendToTarget(); 22 } 23 24 public class MyHandler extends Handler{ 25 26 public MyHandler() { 27 super(); 28 } 29 public MyHandler(Looper looper) { 30 super(looper); 31 32 } 33 34 @Override 35 public void handleMessage(Message msg) { 36 super.handleMessage(msg); 37 Bundle bundle = msg.getData(); 38 int age = bundle.getInt("age"); 39 String name = bundle.getString("name"); 40 System.out.println("age---->"+age+",name------->"+name); 41 42 System.out.println("Handler------------->"+ Thread.currentThread().getId()); 43 System.out.println("handleMessage"); 44 } 45 } 46 }
所有項目代碼下載地址:http://download.csdn.net/detail/gaojiecaiandroid/5430585