基本的第二计时器实现

时间:2012-02-23 13:15:34

标签: java android

我对Android平台非常新,因此我有一个非常基本的问题,我正在尝试制作一个简单的第二个计时器,所以这里是我写的代码。我不知道为什么但是方法运行永远不会被执行:

        Timer tmr = new Timer();
        tmr.schedule(new TimerTask()
        {

            @Override
            public void run() {
                TextView txt = (TextView) findViewById(R.id.txtLoading);
                counter++;
                txt.setText(counter);

            }

        }, 1000);

LE:实际上看起来它正在执行,但GUI没有得到更新......为什么?

3 个答案:

答案 0 :(得分:4)

使用像这样的Timer创建一个新线程,并从一个不是主线程的线程更新GUI不是一个好主意。 更好的方法是在此链接中报告的方法:http://developer.android.com/resources/articles/timed-ui-updates.html

希望它有所帮助!

答案 1 :(得分:1)

我想这是因为你没有在UI线程中工作。阅读有关UI线程here

您可能需要考虑使用AsyncTask来处理所有UI线程同步化内容;)

答案 2 :(得分:0)

像这样更改您的代码

Timer tmr = new Timer();
        tmr.schedule(new TimerTask()
        {

            @Override
            public void run() {
                Log.w("this", "is 1");
            }

        },1000, 1000);
相关问题