[英]Stop CountDownTimer when we click on the home button
如何在我離開應用程序時停止 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();
}
我建議兩種方式
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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.