I have a simple question, how can I stop timer?
Button bCancel = (Button)findViewById(R.id.bt1);
bCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
startActivity(new Intent("com.jom.testcdt2.CANCELCLASS"));
}
});
final Thread logoTimer = new Thread(){
public void run(){
try {
int logoTimer = 0;
while (logoTimer < 10000) {
sleep(100);
logoTimer = logoTimer + 100;
}
startActivity(new Intent("com.jom.testcdt2.CLEARSCREEN"));
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
finally{
finish();
}
}
};
logoTimer.start();
}
When I press button bCancel, it starts a new activity, but timer is still running and after 10 seconds it starts CLEARSCREEN. On click I want timer to stop. How can I do that?
I would recommend using a CountDownTimer
:
final CountDownTimer myTimer = new CountDownTimer(10000, 5000) {
@Override
public void onFinish() {
//DO SOMETHING AFTER 10 000 ms
}
@Override
public void onTick(long millisUntilFinished) {
//DO SOMETHING EVERY 5 000 ms until stopped
}
}
myTimer.start() //Starts it
myTimer.cancel() //Stops it
And instead of writing
(new Intent("com.jom.testcdt2.CANCELCLASS")
you should use
(new Intent(YOURCLASS.this, CancelClass.class)
Could you try to have a boolean value that you check in the while loop, and set it to true when you press the cancel button?
boolean pressedCancel = false;
....
while (logoTimer < 10000 && !pressedCancel) {
....
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.