我正在尝试更改计时器的时间段
package com.chukree.thumbsdown;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Timer;
import java.util.TimerTask;
public class GameActivity extends Activity {
Button btnTap;
Timer timer = new Timer();
int seconds = 0;
long timerPeriod = 1000;
private int multiple = 3;
private int score = 0;
TextView tvScore;
TimerTask myTimerTask;
private boolean gameStarted = false;
String TAG = GameActivity.class.toString();
private class OnTapTimerTask extends TimerTask{
@Override
public void run() {
seconds += 1;
if(score > 2){
restartTimer();
}
if(seconds > 200){
Log.d(TAG, "Timer Period: " + timerPeriod);
timer.cancel();
}
runOnUiThread(new Runnable() {
@Override
public void run() {
btnTap.setText(String.valueOf(seconds));
Toast.makeText(getApplicationContext(), "" + timerPeriod, Toast.LENGTH_SHORT).show();
}
});
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
btnTap = (Button) findViewById(R.id.button_tap);
tvScore = (TextView) findViewById(R.id.tvScore);
myTimerTask = new OnTapTimerTask();
btnTap.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (timerPeriod > 500 && gameStarted) {
timerPeriod -= 50;
}
if (btnTap.getText().toString().equals("Start")) {
//Enable timer
timer.schedule(myTimerTask, 0, timerPeriod);
// Enable Pause Button
// Set "GameStarted" to true
gameStarted = true;
// set "lastTapNum" to 0
} else if (Integer.parseInt(btnTap.getText().toString()) % multiple == 0) {
score += 1;
tvScore.setText("" + score);
}
}
});
}
private void restartTimer() {
myTimerTask.cancel();
timer.purge();
// timer = new Timer();
myTimerTask = new OnTapTimerTask();
timer.schedule(myTimerTask, 0, timerPeriod);
}
@Override
protected void onPause() {
timer.cancel();
super.onPause();
}
}
但是当(得分> 2)在不到一秒的时间内发射超过200次时,计时器会非常快速地发射。
对这种奇怪的行为有任何可能的解释吗?