0

编辑:我发现了问题,它是 Thread.Sleep 有没有其他方法可以让我的应用程序等待一秒钟?

我正在尝试学习android开发,所以我正在使用android studio。我有一个活动,它不是主要活动,我试图建立一个计时器,从活动开始时的 40 分钟开始计数,但由于某种原因,当我按下应该更改活动的主要活动中的按钮时对于有计时器的人,应用程序崩溃。这是计时器的活动代码:

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;


public class Timer extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_timer);

}

@Override
protected void onStart() {
        String counter;
        int totalSeconds = 2400;
        int minLeft, secLeft;
        for (int i = totalSeconds; i > 0; i--)
        {
            try
            {
                Thread.sleep(1000L);
            }
            catch (InterruptedException e) {e.printStackTrace();}
            minLeft=(int)Math.floor(i/60);
            secLeft=i-(minLeft*60);
            counter = minLeft+":"+secLeft;
            TextView tv = (TextView)findViewById(R.id.timer);
            tv.setText(counter);
        }
    }

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.quiz, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

}
4

2 回答 2

1

您需要将所有计数器逻辑移出主线程。尝试这样的事情:

private int secondsLeft = 2400;

private Handler mHandler = new Handler();

public void onStart() {
    super.onStart();

    final TextView tv = (TextView)findViewById(R.id.timer);

    mHandler.postDelayed(new Runnable() {

        public void run() {
            secondsLeft--;
            int minLeft = (int)Math.floor(secondsLeft / 60);
            int secLeft = secondsLeft - (minLeft * 60);
            tv.setText(minLeft + ":" + secLeft);

            if (secondsLeft > 0)
                mHandler.postDelayed(this, 1000);
        }

    }, 1000);
于 2014-04-12T14:13:04.257 回答
0

你可能错过了调用super.onStart()你的覆盖onStart()

于 2014-04-12T13:48:06.430 回答