編輯:關於 Android 程式設計
Handler 是 Android 提供的一套消息處理機制,同時也是更新 UI 的官方通道。我們可以用它發送消息,也可以用它處理消息。
Android 在設計之初就把消息的創建、傳遞、處理封裝成了一整套框架。繞過這套機制直接從子線程更新界面,系統會拋出異常。這正是 Handler 存在的理由。
public class MainActivity extends Activity {
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv1);
new Thread() {
public void run() {
try {
Thread.sleep(1000);
// 更新文本信息
tv.setText("update Thread");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
}
}
運行後會拋出異常,原因很直接:只能在原線程(主線程)中更新 UI。

把更新動作拋給 Handler,就能正常執行:
public class MainActivity extends Activity {
private TextView tv;
private Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv1);
new Thread() {
public void run() {
try {
Thread.sleep(1000);
handler.post(new Runnable() {
@Override
public void run() {
// 更新文本信息
tv.setText("update Thread");
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
}
}
新建 Handler 時不傳 Looper,默認綁定當前線程的 Looper;在主線程中創建,自然也就綁到了主線程。post 進去的 Runnable 會被投遞到主線程的消息隊列執行。
利用 postDelayed 讓 Runnable 週期性重投自己,就能實現定時切換:
public class MainActivity extends Activity {
private TextView tv;
private ImageView img;
private Handler handler = new Handler();
private int images[] = {R.drawable.one, R.drawable.two, R.drawable.three};
private int index;
private MyRunnable myRunnable = new MyRunnable();
class MyRunnable implements Runnable {
@Override
public void run() {
index++;
index = index % 3;
img.setImageResource(images[index]);
handler.postDelayed(myRunnable, 1000); // 一秒後再次投遞自己
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv1);
img = (ImageView) findViewById(R.id.imageView1);
handler.postDelayed(myRunnable, 1000);
}
}
其一,記得在 Activity 的 onDestroy 中調用 handler.removeCallbacksAndMessages(null),否則延遲任務會持有 Activity 引用,造成內存洩漏。
其二,如果在子線程中創建 Handler,必須先調用 Looper.prepare() 再 Looper.loop(),否則會拋出「Can't create handler inside thread that has not called Looper.prepare()」。日常開發中更常見的做法始終是在主線程持有 Handler,子線程只做計算並回投結果。
刷機精靈怎麼用?一鍵刷機流程介紹
刷機精靈是一款 Android 一鍵刷機工具,適合不想手動操作 Recovery 的使用者。 使用流程 1. 下載 ROM 包,保持 ZIP 格式,不用解壓。 2. 在
Android 資料儲存之檔案儲存完整指南
檔案儲存是 Android 中最基本的一種資料儲存方式,它完全不對內容做任何格式化處理,所有資料都原封不動地寫入檔案。核心概念其實就是輸入流與輸出流。 一、Androi
自研 Android 下拉刷新庫:基於 ViewDragHelper 實現刷新、加載更多與初始 Loading
下拉刷新幾乎是移動應用的標配交互。市面上成熟方案不少,但自己動手實現一遍,能把 ViewDragHelper、嵌套滑動、Header/Footer 狀態機這幾塊知識真正串
Android Studio 主題與字體大小設定教學
Android Studio 主題與字體設定 Android Studio 的外觀可以依個人習慣調整。常見需求包含切換內建主題、匯入第三方主題,以及調整編輯器字體大小。適