开发者

Android thread not working

In this code snippet, the application sleeps for the interval, but instead of appending TEXT to textStatus(TextView variable), it displays an error that Something went wrong and application is closing.

     Thread time_manager = new Thread(){
        public void run(){
            int interval = 2000;
            try{
    开发者_StackOverflow社区                sleep(interval);
                    textStatus.append("\nTEXT\n");

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

What part am I doing wrongly?


To update the UI you can also use Handler like this, it will update your UI incrementing the value of counter everytime by 1 within every second.

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);
        }
    };


all the changes to the UI Part should be done on the UIThread, you should use something like post, or runOnUithread functions to update UI.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜