离开应用程序时如何停止CountDownTimer(当我点击智能手机上的主页按钮时)CountDownTimer仍在运行 我尝试使用此代码,但当我离开应用程序时,我的智能手机中会显示一条消息“应用名称已停止”。关闭应用程序 请帮帮我 这是我使用的代码
CountDownTimer timer = new CountDownTimer(120000, 1000) {
@SuppressLint("DefaultLocale")
public void onTick(long millisUntilFinished) {
tv.setText(String.format("%d : %d ",
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))));
}
public void onFinish() {
AlertDialog.Builder builder1 = new AlertDialog.Builder(MainActivity.this);
View view1 = LayoutInflater.from(MainActivity.this).inflate(R.layout.activity_cum, null);
TextView title = (TextView) view1.findViewById(R.id.title);
TextView message = (TextView) view1.findViewById(R.id.message);
ImageView icone = (ImageView) view1.findViewById(R.id.icone);
title.setText("Result");
icone.setImageResource(R.drawable.smile_lost);
message.setText("You have exceeded \n your time of reflection");
builder1.setPositiveButton("Replay", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = getIntent();
overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
}
});
builder1.setView(view1);
builder1.setCancelable(false);
AlertDialog alertDialog1 = builder1.create();
alertDialog1.show();
}
}.start();
}
是onStop()
中的代码@Override
public void onStop() {
super.onStop();
timer.cancel();
}
答案 0 :(得分:0)
我建议双向
<强> 1 强>
创建像
这样的全局变量private isInForgrand = false;
在onStop()或onPause()和onResume()中更改
@Override
public void onStop() {
isInForgrand = false;
super.onStop();
}
@Override
public void onResume() {
super.onResume();
isInForgrand = true;
}
在onFinish()中检查
@Override
public void onFinish() {
if(isInForgrand){
//do what you want
}else{
//your app NOT in Forgrannd
}
<强> 2 强>
您可以在onStop()
中取消CountDownTimer@Override
public void onStop() {
super.onStop();
mCountDownTimer.cancel();
}