2011-09-25 64 views
0

在这个代码片段中,应用程序会休眠一段时间,但不会将TEXT附加到textStatus(TextView变量),它会显示错误,说明出现错误并且应用程序正在关闭。Android线程不工作

 Thread time_manager = new Thread(){ 
     public void run(){ 
      int interval = 2000; 
      try{ 
        sleep(interval); 
        textStatus.append("\nTEXT\n"); 

      } 
      catch (InterruptedException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
      finally{ 
      } 
     } 
    }; 

我做错了什么部分?

回答

1

要更新用户界面,您还可以像这样使用处理程序,它会在每秒内更新您的用户界面,每次将计数器的值递增1。

int response = 0; 
public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     tv = (TextView)findViewById(R.id.myid); 
     thread t = new thread(); 
     t.start(); 
    } 

public class thread extends Thread { 
    public void run() { 
     while (response < 100) { 
      handler.sendEmptyMessage(0); 
      response++; 
      try { 
       sleep(1000); 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 

    private Handler handler = new Handler() { 
     public void handleMessage(Message msg) { 

      tv.setText("helloworld " + response); 
     } 
    }; 
1

UI部分的所有更改都应在UIThread上完成,您应该使用类似postrunOnUithread函数来更新UI。

+0

如果我改变try块中语句的顺序,它显示的文本一次,然后睡觉,然后给出错误 – Vishal

+0

告诉我们你的错误。 –