0
TimerTask
을 시작하고 중지하는 간단한 코드를 작성했습니다. 이 코드 Stop
에서 작동 할 수 있지만 다시 시작할 수 없습니다. TimerTask
. 이 문제를 해결하도록 도와주세요.Restart TimerTask Fail
내 코드 :
public class MainActivity extends Activity implements View.OnClickListener {
private TimerThread timerThread;
private boolean timerHasStarted = false;
private Button button;
private TextView text;
private final long startTime = 1000;
private final long interval = 1;
private Handler handler;
private Runnable r;
private MediaPlayer mp;
private TimerTask task;
private Timer timer;
private long delay;
private Boolean play = true;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
button = (Button) this.findViewById(R.id.button);
button.setOnClickListener(this);
text = (TextView) this.findViewById(R.id.timer);
mp = MediaPlayer.create(this, R.raw.cpush);
//mp.start();
delay = 1000;
timer = new Timer();
timerThread = new TimerThread();
timer.scheduleAtFixedRate(task, 0, 10);
}
public long nextLong(Random rng, long n) {
long bits, val;
do {
bits = (rng.nextLong() << 1) >>> 1;
val = bits % n;
} while (bits - val + (n - 1) < 0L);
return val;
}
@Override
public void onClick(View v) {
button.setBackgroundResource(R.drawable.finish);
if(play){
play = false;
task.cancel();
}
else{
play = true;
/* RESTART TimerTask Hear*/
}
}
public class TimerThread extends TimerTask {
@Override
public void run() {
Random rand = new Random();
final long value = nextLong(rand, 9999999999999999L);
runOnUiThread(new Runnable() {
@Override
public void run() {
text.setText("" + value);
}
});
}
}
}