Handler(管理程序)顧名思義是一個管理者或控制者,專門用來處理 Thread 發送的訊息,然後給 Runnable 來處理事件,可以收發和處理 Runnable(運行類)、Looper(訊息環)和 Message(訊息)與 Thread 的 Message Queue(訊息隊列) 關聯的物件。如果線程需操作 UI 的消息傳遞到主線程,使得主執行緒可根據線程的需求更新 UI,利用 Handler可以避免主線程操作不穩定和不被允許的的問題,長時間的阻塞會導致 ANR(Application No Responding)。
Android Studio Thread Handler Message 的關係 |
- Handler.sendMessage
- Handler.post
- obtainMessage
Runnable 用 for 迴圈來達成由 1 到 10 程式範例:
public class MainActivity extends Activity { Handler mHandler; TextView txtCount;
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
txtCount = (TextView) findViewById(R.id.txtCount);
mHandler = new Handler(); mHandler.post(runnable); }
final Runnable runnable = new Runnable() { public void run() { // TODO Auto-generated method stub // 需要背景作的事 try { for (int i = 0; i < 10; i++) { Thread.sleep(1000); } } catch (Exception e) { e.printStackTrace(); } } }; |
Runnable 用 PostDelaedy 達成由 1 到 10 程式範例:
public class MainActivity extends Activity { Handler mHandler; TextView txtCount;
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
txtCount = (TextView) findViewById(R.id.txtCount);
mHandler = new Handler(); mHandler.post(runnable); }
int count = 0; final Runnable runnable = new Runnable() { public void run() { // TODO Auto-generated method stub // 需要背景作的事 if (count < 10) { count++; txtCount.setText(Integer.toString(count+1)); //可直接更新UI介面 mHandler.postDelayed(runnable, 1000); } } }; |
obtainMessage 程式範例:
class obtainThread extends Thread{ @Override public void run() { isDownloading = true; mHandler.obtainMessage(MSG_DOWN_START).sendToTarget(); try { //讓執行緒睡眠3s。 Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } mHandler.obtainMessage(MSG_DOWN_SUCCESS).sendToTarget(); isDownloading = false; } } |
Activity 被結束時,也請 Handler 把 Runnable 給停掉:
@Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); if (mHandler != null) { mHandler.removeCallbacks(runnable); } } |
沒有留言:
張貼留言