【发布时间】: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