Android thread not working

[亡魂溺海] 提交于 2020-02-06 18:02:52

问题


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{
                    sleep(interval);
                    textStatus.append("\nTEXT\n");

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

What part am I doing wrongly?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/7546609/android-thread-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!