当我按下BACK按钮(onBackPressed()调用)关闭我的应用程序时,CountDownTimer
不会停止,直到完成计数。如何将CountDownTimer
取消(); 放入我的onBackPressed()
?
因为,当我退出我的应用程序时(如下面的说明所示),我不再想在屏幕上反击。
在我的代码之上:
boolean network_connected = false;
onCreate()
中的内容:
if (check_network.isInternetAvailable(this)) {
network_connected = true;
new connect_task_main().execute("");
} else {
network_connected = false;
}
if (network_connected == false) {
new CountDownTimer(11000, 1000) {
public void onTick(long millisUntilFinished) {
global.toast.setText("No Internet Connection!" + "\n" + "Automatic Refresh In: " + millisUntilFinished / 1000); //set text for toast
global.toast.show(); //show toast
}
public void onFinish() {
if (network_connected == false) {
global.cancel_toast(0); //stop all toasts
finish(); //quit activity
startActivity(new Intent(main_activity.this, main_activity.class)); //start activity
} else {
}
}
}.start(); //start the countdowntimer
} else {
network_connected = true;
}
onBackPressed()
方法
@Override
public void onBackPressed() {
if (page_number > global.page_number_min) { //does not matter
page_number--; //does not matter
global.cancel_toast(0); //stop all toasts
network_connected = true;
finish();
} else {
global.cancel_toast(0);
network_connected = true;
finish(); //quit activity
super.onBackPressed(); //quit application
}
}
感谢。
答案 0 :(得分:12)
创建CountDownTimer
的全局对象,例如
在main_activity类集之上:CountDownTimer timer;
之后执行以下操作。
timer = new CountDownTimer(11000, 1000)
{
public void onTick(long millisUntilFinished)
{
global.toast.setText("No Internet Connection!" + "\n" + "Automatic Refresh In: " + millisUntilFinished / 1000); //set text for toast
global.toast.show(); //show toast
}
public void onFinish()
{
if (network_connected == false)
{
global.cancel_toast(0); //stop all toasts
finish(); //quit activity
startActivity(new Intent(main_activity.this, main_activity.class)); //start activity
}
else
{
}
}
}.start(); //start the countdowntimer
}
并onBackPressed
致电timer.cancel();
,如
@Override
public void onBackPressed()
{
if (page_number > global.page_number_min)
{ //does not matter
page_number--; //does not matter
global.cancel_toast(0); //stop all toasts
network_connected = true;
finish();
}
else
{
global.cancel_toast(0);
network_connected = true;
finish(); //quit activity
super.onBackPressed(); //quit application
}
timer.cancel();
}