如何在Android Studio 1.0.2中制作计时器?

时间:2015-01-30 20:12:17

标签: java android optimization time android-studio

我有这个代码,我的应用程序在启动时崩溃了。此代码来自onCreate方法。

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

        @Override
        public void run() {
            TextView txtClicks = (TextView) findViewById(R.id.txtClicks);
            // task to be done every 1000 milliseconds
            iClicks = iClicks + 1;
            txtClicks.setText(String.valueOf(iClicks));
        }
    }, 0, 1000);

2 个答案:

答案 0 :(得分:3)

你在另一个thread内。您只能从UIThread修改您的用户界面。你应该使用:

Timer timer = new Timer();
timer.schedule(new TimerTask() {      
    @Override
    public void run() {
       runOnUiThread(new Runnable(){
       @Override
       public void run(){
        TextView txtClicks = (TextView) findViewById(R.id.txtClicks);
        // task to be done every 1000 milliseconds
        iClicks = iClicks + 1;
        txtClicks.setText(String.valueOf(iClicks));
        }
  });

    }
}, 0, 1000);

答案 1 :(得分:0)

这是一段代码,timerLoopScan和scanPeriod是全局变量:

    timerLoopScan = new Timer();
    TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
                    loopScan(); // your processings here
            });
        }
    };
    timerLoopScan.scheduleAtFixedRate(timerTask, 0, scanPeriod);