【问题标题】:CountDown Method for Android not Working [Edited]Android 的倒计时方法不起作用 [已编辑]
【发布时间】:2025-12-11 08:25:02
【问题描述】:

我正在使用 Android Studio。所以这是完整的代码。我正在尝试通过单击开始按钮来开始倒计时。计划是倒计时正在下降,而我仍然可以单击另一个按钮。另一个按钮(incrementButton)递增。我得到了增量工作,但是当我单击 startButton 时计时器不工作。我做错了什么吗?

编辑:请问如何取消后台线程也很好? 我尝试使用取消(真)。改了代码

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
TextView seconds;
TextView increment;
int count;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    seconds = (TextView) findViewById(R.id.seconds);
    increment = (TextView) findViewById(R.id.increment);
    Button incrementButton = (Button) findViewById(R.id.incrementButton);
    Button startButton = (Button) findViewById(R.id.startButton);
    Button stopButton= (Button) findViewById(R.id.stopButton);
    incrementButton.setOnClickListener(this);
    startButton.setOnClickListener(this);
}
@Override
public void onClick(View view) {
    switch(view.getId()){
        case R.id.incrementButton:
            count++;
            increment.setText(Integer.toString(count));
            break;
        case R.id.startButton:
            new timerTask();
            break;
        case R.id.stopButton:
            new timerTask().cancel(true);
            break;
    }
}
private void updateSeconds(final int count) {
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            seconds.setText(Integer.toString(count));
        }
    });
}
public class timerTask extends AsyncTask<Void, Void, Void> {
    private int i;
    private int savedSecond;
    public timerTask() {
    }
    @Override
    protected Void doInBackground(Void... voids) {
        try {
            for(i = 10; i > 0; i--){
                savedSecond = i;
                updateSeconds(savedSecond);
                Thread.sleep(1000); //1000 = 1 seconds
                if(isCancelled())
                break;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }
}
}

【问题讨论】:

    标签: java android multithreading timer android-asynctask


    【解决方案1】:

    调用execute方法启动AsyncTask为:

    case R.id.startButton:
      new timerTask().execute();
     break;
    

    【讨论】:

    • 我真的在笑我的脚 XD Ty。
    【解决方案2】:
    case R.id.startButton:
            timerTask timerTask  =new timerTask(); // here you created the timer task.
                  timerTask.execute() //execute has to be called.
            break;
    

    【讨论】:

    • timerTask 这里的 'T' 需要大写作为它的类声明。
    • 哦。我不知道。谢谢,我现在就去做:)