我正在尝试在 Android 中循环更新 UI,但我收到一条错误消息,提示我在错误的线程上。我不明白为什么,因为我使用的是处理程序。有没有人有什么建议?
TextView textView;
protected Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
textView.setText((String)msg.obj);
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_thread_sleep);
textView=(TextView) findViewById(R.id.TextView1);
init();
}
public void init()
{
CounterThread counterThread=new CounterThread();
counterThread.start();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_thread_sleep, menu);
return true;
}
class CounterThread extends Thread {
@Override
public void run() {
super.run();
int counter=0;
handleString("in Thread handler");
try{Thread.sleep(2000); }catch(Exception e){Log.d("Exception", e.toString());}
while(counter<10)
{
counter++;
String counterString=String.valueOf(counter);
handleString(counterString);
try{Thread.sleep(2000); }catch(Exception e){Log.d("Exception", e.toString());}
}//while
}//run
public void handleString(String string)
{
Message msg=handler.obtainMessage();
msg.obj="counter"+" "+string;
handler.handleMessage(msg);
}
}//thread