編輯:關於 Android 程式設計
寫一個小應用的時候,我碰到一個關於 Handler、Thread 與 Runnable 的問題,問了群裡不少人仍舊无解,翻查大量資料後才稍微理出頭緒,這裡記錄下來分享。
核心問題是:Thread 與 Runnable 的差別是什麼?它們在搭配 Handler 使用時又會造成什麼影響?先看一段會出錯的程式碼。
public class MainActivity extends Activity {
TextView text1, text2;
Button button;
myThread th;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text1 = (TextView) findViewById(R.id.text1);
text2 = (TextView) findViewById(R.id.text2);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
th = new myThread();
th.start();
}
});
}
Handler myHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
text1.setText(msg.getData().getString("s1"));
text2.setText(msg.getData().getString("s1"));
break;
}
super.handleMessage(msg);
}
};
}
class myThread extends Thread {
MainActivity ma = new MainActivity(); // 問題就在這一行
public void run() {
Bundle bundle = new Bundle();
bundle.putString("s1", "fsdfsgfdsgdfgfdgdhshshs");
bundle.putString("s2", "fsfsdgdshdhdshrehreherh");
Message msg = new Message();
msg.what = 1;
msg.setData(bundle);
ma.myHandler.sendMessage(msg);
}
}
這段程式碼執行到 handler 更新 UI 的部分就會拋出空指標錯誤。
public class MainActivity extends Activity {
TextView text1, text2;
Button button;
Thread th;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text1 = (TextView) findViewById(R.id.text1);
text2 = (TextView) findViewById(R.id.text2);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
th = new Thread(runnable);
th.start();
}
});
}
Handler myHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
text1.setText(msg.getData().getString("s1"));
text2.setText(msg.getData().getString("s1"));
break;
}
super.handleMessage(msg);
}
};
Runnable runnable = new Runnable() {
@Override
public void run() {
Bundle bundle = new Bundle();
bundle.putString("s1", "fsdfsgfdsgdfgfdgdhshshs");
bundle.putString("s2", "fsfsdgdshdhdshrehreherh");
Message msg = new Message();
msg.what = 1;
msg.setData(bundle);
MainActivity.this.myHandler.sendMessage(msg); // 用外部限定符存取
}
};
}
這版本能正確更新 UI。
找到問題後我又做了幾個小實驗,發現 Thread 其實也能用來更新 UI,關鍵在於怎麼參照 Handler:
public class MainActivity extends Activity {
TextView text1, text2;
Button button;
myThread th;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text1 = (TextView) findViewById(R.id.text1);
text2 = (TextView) findViewById(R.id.text2);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
th = new myThread();
th.start();
}
});
}
Handler myHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
text1.setText(msg.getData().getString("s1"));
text2.setText(msg.getData().getString("s1"));
break;
}
super.handleMessage(msg);
}
};
class myThread extends Thread {
public void run() {
Bundle bundle = new Bundle();
bundle.putString("s1", "fsdfsgfdsgdfgfdgdhshshs");
bundle.putString("s2", "fsfsdgdshdhdshrehreherh");
Message msg = new Message();
msg.what = 1;
msg.setData(bundle);
MainActivity.this.myHandler.sendMessage(msg); // 差別只在這裡
}
}
}
三段程式碼擺在一起,差異就很清楚了:錯誤版本在 myThread 裡 new MainActivity(),得到的是一個全新的、尚未執行 onCreate 的 Activity 物件,它的 text1、text2 全是 null,myHandler 也還沒綁上任何有效的 Context。空指標就是這麼來的。
正確做法有兩種,本質相同——都是「直接引用外層那個已存在的 Activity 實例」:
用 Runnable:Runnable 是內部類,可直接存取主執行緒的變數,寫 MainActivity.this.myHandler 即可。
用內部類繼承 Thread:利用內部類能自由存取外部類成員的特性,同樣寫 MainActivity.this.myHandler。
而錯誤版本把 myThread 寫成一個獨立的外部類,失去了這层关联,只能自己 new 一個 Activity,於是拿到的是空殼物件。
結論很簡單:不要在子執行緒中 new Activity。Activity 的生命週期由系統與 ActivityThread 管理,自行 new 出來的實例從未走過完整的初始化流程,任何操作都不可靠。
深入認識 Android 的樣式與主題(Styles and Themes)
只要寫過 Android 應用,你一定見過畫面上那些密密麻麻的 XML 屬性。這篇文章要談的,是這些屬性背後的機制:屬性從哪裡來、為什麼有些屬性用不了、自定義屬性怎麼定義
Android 自訂 View 實作四碼驗證碼
登入、註冊頁面幾乎都會放一個驗證碼。自己動手做一個其實不難,拆成「產生隨機字元」與「自繪 Drawable」兩塊即可。 效果如下: 一、隨機產生四個字母 把 2
Android Chronometer 計時器完整實作:倒數提醒這樣做
Chronometer 是 Android 內建的計時元件,本篇用一個「設定秒數後開始倒數、時間到就跳提醒」的小案例,把它的核心 API 全部走過一遍。 實作思路 整個
深入淺析 Android 消息機制
在 Android 中,線程內部或線程之間傳遞信息時經常會用到消息。這些看似基礎的東西,一旦我們摸透了背後的原理,就能更從容、更好地搭建系統架構,避免一些低級錯誤。 每個