gpt4 book ai didi

java - Android Java 取消 CountDownTimer 的问题

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:01:01 26 4
gpt4 key购买 nike

当我通过按下返回按钮(调用 onBackPressed())关闭我的应用程序时,CountDownTimer 不会停止,直到完成计数。如何将 CountDownTimer cancel(); 放入我的 onBackPressed() 中?

因为,当我退出我的应用程序时(下面显示了描述),我不想再在我的屏幕上出现柜台 toast 。

在我的代码之上:

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 = 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();
}

关于java - Android Java 取消 CountDownTimer 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23630828/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com