android初步ui线程案例,android – 它是一个bug还是一个功能?在某些情况下,可以从未在UI线程上运行的任务访问UI线程...
developer.android.com說(shuō):
Only objects running on the UI thread have access to other objects on
that thread.
也就是說(shuō),以下所有示例(例如A..C)都不應(yīng)該起作用,因?yàn)樗鼈冊(cè)噲D修改UI線程中的對(duì)象.但實(shí)際上案例A和B確實(shí)訪問(wèn)了UI線程中的對(duì)象(TextView).
這里我們從MainActivity開(kāi)始一個(gè)新線程:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new ClientThread()).start();
}
案例A(UI線程中的對(duì)象被修改)
class ClientThread implements Runnable {
public void run() {
final TextView myTextView = (TextView) findViewById(R.id.myTextView);
myTextView.setText("Hello there!");
}
}
情況B(UI線程中的對(duì)象被多次修改)
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線程中的對(duì)象未被修改)
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才會(huì)拋出異常:
CalledFromWrongThreadException: Only the original thread that created
a view hierarchy can touch its views.
我錯(cuò)過(guò)了什么嗎?目前看來(lái),在某些情況下,可以從未在UI線程上運(yùn)行的線程修改UI線程(如果它發(fā)生得足夠快).
解決方法:
這是一種樂(lè)趣.您無(wú)法在后臺(tái)線程中更新UI.但在這種情況下,UI尚未繪制,因此它不會(huì)像更新UI那樣處理您的代碼,而更像是設(shè)置值.無(wú)論如何,如果您在顯示UI后更新它,它將被視為UI更新.
標(biāo)簽:android,multithreading
來(lái)源: https://codeday.me/bug/20190708/1401657.html
總結(jié)
以上是生活随笔為你收集整理的android初步ui线程案例,android – 它是一个bug还是一个功能?在某些情况下,可以从未在UI线程上运行的任务访问UI线程...的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Page.LoadTemplate的使用
- 下一篇: Web.config详解