Android的CountDown方法无法正常工作[已编辑]

时间:2016-05-23 06:05:16

标签: java android multithreading timer android-asynctask

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

编辑:询问如何取消后台话题也很好吗? 我尝试使用取消(true)。更改了代码

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;
    }
}
}

3 个答案:

答案 0 :(得分:2)

调用execute方法启动AsyncTask as:

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

答案 1 :(得分:1)

case R.id.startButton:
        timerTask timerTask  =new timerTask(); // here you created the timer task.
              timerTask.execute() //execute has to be called.
        break;

答案 2 :(得分:0)

enter code here

案例R.id.startButton:  new timerTask()。execute();

中断;