android初步ui线程案例,android – 它是一个bug还是一个功能?在某些情况下,可以从未在UI线程上运行的任务访问UI线程...
developer.android.com說:
Only objects running on the UI thread have access to other objects on
that thread.
也就是說,以下所有示例(例如A..C)都不應該起作用,因為它們試圖修改UI線程中的對象.但實際上案例A和B確實訪問了UI線程中的對象(TextView).
這里我們從MainActivity開始一個新線程:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new ClientThread()).start();
}
案例A(UI線程中的對象被修改)
class ClientThread implements Runnable {
public void run() {
final TextView myTextView = (TextView) findViewById(R.id.myTextView);
myTextView.setText("Hello there!");
}
}
情況B(UI線程中的對象被多次修改)
class ClientThread implements Runnable {
public void run() {
final TextView myTextView = (TextView) findViewById(R.id.myTextView);
for (int i=0; i < 600; i++) {
myTextView.setText("Hello there!");
}
}
}
情況C(稍微延遲后,UI線程中的對象未被修改)
class ClientThread implements Runnable {
public void run() {
final TextView myTextView = (TextView) findViewById(R.id.myTextView);
try {Thread.sleep(900);} catch (InterruptedException e) {};
myTextView.setText("Hello there!");
}
}
只有案例C才會拋出異常:
CalledFromWrongThreadException: Only the original thread that created
a view hierarchy can touch its views.
我錯過了什么嗎?目前看來,在某些情況下,可以從未在UI線程上運行的線程修改UI線程(如果它發生得足夠快).
解決方法:
這是一種樂趣.您無法在后臺線程中更新UI.但在這種情況下,UI尚未繪制,因此它不會像更新UI那樣處理您的代碼,而更像是設置值.無論如何,如果您在顯示UI后更新它,它將被視為UI更新.
標簽:android,multithreading
來源: https://codeday.me/bug/20190708/1401657.html
總結
以上是生活随笔為你收集整理的android初步ui线程案例,android – 它是一个bug还是一个功能?在某些情况下,可以从未在UI线程上运行的任务访问UI线程...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Page.LoadTemplate的使用
- 下一篇: 在一个IIS上同时运行两个版本ASP.N