【问题标题】:Timer code crashes my app计时器代码使我的应用程序崩溃
【发布时间】:2014-04-12 15:59:27
【问题描述】:

我正在学习android开发,我想做的是有一个从40分钟开始倒计时的标签,当它到达0时它会停止计数并做其他事情。这是我的代码:

@Override
protected void onStart() {
        super.onStart();
        count = 2400;
        final Timer t = new Timer();//Create the object
        t.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                minLeft = (int) Math.floor(count / 60);
                secLeft = count - minLeft * 60;
                counter = minLeft + ":" + secLeft;
                TextView tv = (TextView) findViewById(R.id.timer);

                Log.i(MainActivity.TAG,minLeft+", "+secLeft+", "+counter);
                tv.setText(counter);
                count--;
                if (minLeft <= 0 && secLeft <= 0) {
                    t.cancel();
                    count = 2400;
                    onFinish();
                }
            }
        }, 1000, 1000);
    }

但是,当我通过单击主活动中的按钮进入该活动时,标签具有文本“计时器”(其原始文本),几秒钟后应用程序因 CalledFromWrongThreadException 而崩溃,但导致问题似乎是我设置 TextView 文本的问题。

请帮忙,提前谢谢。

【问题讨论】:

    标签: java android timer android-studio onstart


    【解决方案1】:

    您的计划任务在后台线程上运行。 并且您尝试从该后台线程将文本设置为 textview。 但是在 Android 中,所有与视图相关的操作都必须在主线程上完成。

    在你的计划任务中,你必须使用类似的东西:

    @Override
    protected void onStart() {
        super.onStart();
        count = 2400;
        final Timer t = new Timer();//Create the object
        t.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                minLeft = (int) Math.floor(count / 60);
                secLeft = count - minLeft * 60;
                counter = minLeft + ":" + secLeft;
                // the name of your actual activity
                MyActivity.this.runOnUiThread(new Runnable() {
                   @Override
                   public void run() {
                     TextView tv = (TextView) findViewById(R.id.timer);
                     Log.i(MainActivity.TAG,minLeft+", "+secLeft+", "+counter);
                     tv.setText(counter);
                   }
                });
    
                count--;
                if (minLeft <= 0 && secLeft <= 0) {
                    t.cancel();
                    count = 2400;
                    onFinish();
                }
            }
        }, 1000, 1000);
    }
    

    还请注意,这段代码可以写得更优雅,不需要所有/那么多匿名类,但它应该可以解决问题。

    【讨论】:

      猜你喜欢
      • 2016-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-29
      • 1970-01-01
      • 1970-01-01
      • 2013-10-25
      • 1970-01-01
      相关资源
      最近更新 更多