[英]Problems To Cancel A CountDownTimer Android Java
當我按下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
}
}
謝謝。
創建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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.