標籤: 雜談 |
使用Handler的大體流程:php
1、首先建立一個Handler對象,能夠直接使用Handler無參構造函數建立Handler對象,也能夠繼承Handler類,重寫handleMessage方法來建立Handler對象。框架
2、在監聽器中,調用Handler的post方法,將要執行的線程對象添加到線程隊列當中。此時將會把該線程對象添加到handler對象的線程隊列中。異步
3、將要執行的操做寫在線程對象的run方法中,通常是一個Runnable對象,複寫其中的run方法就能夠了。ide
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()來得到消息對象。oop
Handler與線程的關係:post
使用Handler的post方法將Runnable對象放到Handler的線程隊列中後,該Runnable的執行其實並未單獨開啓線程,而是仍然在當前Activity線程中執行的,Handler只是調用了Runnable對象的run方法。spa
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對象來進行處理。
view sourceprint?
01 public class HandlerTest2 extends Activity {
02 @Override
03 protected void onCreate(Bundle savedInstanceState) {
04 stub
05 super.onCreate(savedInstanceState);
06 setContentView(R.layout.main);
07 //打印了當前線程的ID
08 System.out.println("Activity-->" + Thread.currentThread().getId());
09 //生成一個HandlerThread對象,實現了使用Looper來處理消息隊列的功能,這個類由Android應用程序框架提供
10 HandlerThread handlerThread = new HandlerThread("handler_thread"); 11 //在使用HandlerThread的getLooper()方法以前,必須先調用該類的start();
12 handlerThread.start();
13 MyHandler myHandler = new MyHandler(handlerThread.getLooper());
14 Message msg = myHandler.obtainMessage();
15 //將msg發送到目標對象,所謂的目標對象,就是生成該msg對象的handler對象
16 Bundle b = new Bundle(); 17 b.putInt("age", 20);
18 b.putString("name", "Jhon");
19 msg.setData(b);
20 msg.sendToTarget();
21 }
22 class MyHandler extends Handler{
24 public MyHandler(){
25
26 }
27 public MyHandler(Looper looper){
28 super(looper); 29 }
30 @Override
31 public void handleMessage(Message msg) {
32 Bundle b = msg.getData();
33 int age = b.getInt("age");
34 String name = b.getString("name");
35 System.out.println("age is " + age + ", name is" + name);
36 System.out.println("Handler--->" + Thread.currentThread().getId());
37 System.out.println("handlerMessage");
38 }
39 } 40 }