Android的线程不工作 [英] Android thread not working

查看:96
本文介绍了Android的线程不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此code段,应用程序休眠的时间间隔,但不是添加文本textStatus(TextView的变量),它会显示一个错误,出现错误,应用程序正在关闭。

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内每秒钟更新UI递增计数器,每次的值。

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

这篇关于Android的线程不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆