Android Handler和HandlerThread使用方法

Handler的官方註釋如下:

A Handler allows you to send and process Message and Runnable objects associated with a thread’s MessageQueue. Each Handler instance is associated with a single thread and that thread’s message queue.

Handler會關聯一個單獨的線程和消息隊列。Handler默認關聯主線程,雖然要提供Runnable參數 ,但默認是直接調用Runnable中的run()方法。也就是默認下會在主線程執行,如果在這裏面的操作會有阻塞,界面也會卡住。如果要在其他線程執行,可以使用HandlerThread。

Handler使用方法:

        Handler handler = new Handler() {
 
			@Override
			public void handleMessage(Message msg) {
				// 處理髮送過來的消息
				Bundle b = msg.getData();
				System.out.println("msg:" + msg.arg1);
				System.out.println("msg:" + b.getString("name") + " - age:" + b.getInt("age"));
				super.handleMessage(msg);
			}
 
        };
 
        Message msg = handler.obtainMessage();
        msg.arg1 = 121;
        Bundle b = new Bundle();
        b.putInt("age", 24);
        b.putString("name", "Fatkun");
        msg.setData(b);
        msg.sendToTarget();
 
        handler.post(r);
 
    }
 
    Runnable r = new Runnable() {
 
		public void run() {
			try {
                                // 在這裏只是睡一下
				Thread.sleep(10000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
 
		}
	};

HandlerThread使用方法:

//把上面創建Handler的代碼
Handler handler = new Handler() {
...
}
 
//改爲:
HandlerThread thread = new HandlerThread("athread");
thread.start(); //要把線程啓動
 
Handler handler = new Handler(thread.getLooper()) {
...
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章