I made an application in android and used timer like this..
try {
CountDownTimer start1 = new CountDownTimer(20000, 1000) {
public void onTick(long millisUntilFinished) {
TextView timeShow = (TextView)findViewById(R.id.showTime);
timeShow.setText(" "+" 00:" +millisUntilFinished / 1000);
}
But my problem is i don't know how to stop timer. Any idea?
I already tried:
quitApplication.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
start1.cancel();
Intent i = new Intent(v.getContext(), startGame.class);
startActivity(i);
// TODO Auto-generated method stub
}
});
start1.cancel()
is the correct method to call to cancel the timer.You did not provide any details about the error you got or why it didn't work for you, but I am assuming your program didn't compile because your variable
start1
is a local variable. It is probably local to whatever method yourtry
block is in. This means yourOnClickListener
construction has no idea whatstart1
is.To fix this simply declare
start1
as a class variable (outside of all methods but within the class):Doing so will allow other methods to recognize and interact with
start1
call start1.cancel() when you want to stop the timer
I know this is a year old but for future readers you just need to call the timer as a final.
like so
that should work