我剛剛開始使用Android Concurrency/Loopers/Handers進行遊戲,而且我剛剛面臨奇怪的異常。下面的代碼不會阻止我從不同線程的TextView上設置文本。在後臺線程異常情況下在TextView上設置文本
TextView tv;
Handler backgroundHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.sample_text);
Runnable run = new Runnable() {
@Override
public void run() {
Looper.prepare();
backgroundHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
String text = (String) msg.obj;
tv.setText(Thread.currentThread().getName() + " " + text);
}
};
Looper.loop();
}
};
Thread thread = new Thread(run);
thread.setName("Background thread");
thread.start();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
Message message = backgroundHandler.obtainMessage();
message.obj = "message from UI";
backgroundHandler.sendMessage(message);
}
你猜怎麼發生
但是,當我睡覺後臺線程一會兒
backgroundHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
String text = (String) msg.obj;
tv.setText(Thread.currentThread().getName() + " " + text);
}
};
它確實如我所料
07-03 18:54:40.506 5996-6025/com.stasbar.tests E/AndroidRuntime: FATAL EXCEPTION: Background thread
Process: com.stasbar.tests, PID: 5996
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:7275)
拋出異常0
有人可以解釋我發生了什麼事嗎?爲什麼我能夠從不同的線程設置文本?
我知道了,請再閱讀我的文章。我想知道爲什麼當我從不同的線程訪問TextView時工作。 –