我想更新Android中的循环中的UI,但我得到一个错误,说我在错误的线程。我不明白为什么,因为我正在使用处理程序。有没有人有什么建议?线程问题,当想要从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
仅供参考,你已经完全被以这种方式解决它击败了使用'Handler'的目的。 “Handler”的意义在于它为您执行主线程上的代码,但您必须先适当地调用它才能传递消息。 – Devunwired