Reputation: 431
I have build an Android application, where I'm using CountDownTimer, everything works fine. Every time I change switch from a different fragment to the current one the CountDownTimer gets reset.
and i am running this in an ArrayAdapter.
How to keep running this CountDownTimer one switching fragments or even app close and open? I am also using SharedPreferences for saving data.
my sample Code is here for reference :
startTimer11.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
float sonuc2 = floatET1 * 60;
DecimalFormat format = new DecimalFormat();
format.setDecimalSeparatorAlwaysShown(false);
Log.e("HEHEHEHE", String.valueOf(format.format(sonuc2)));
String getMinutes = String.valueOf(format.format(sonuc2));//Get minutes from edittexf
if (!getMinutes.equals("") && getMinutes.length() > 0) {
int noOfMinutes = Integer.parseInt(getMinutes) * 60 * 1000;//Convert minutes into milliseconds
countDownTimer[0] = new CountDownTimer(noOfMinutes, 1000) {
public void onTick(long millisUntilFinished) {
long millis = millisUntilFinished;
//Convert milliseconds into hour,minute and seconds
String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis), TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)), TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
countdownTimerText11.setText(hms);//set text
}
public void onFinish() {
countdownTimerText11.setText("TIME'S UP!!"); //On finish change timer text
countdownTimerText11.setTextColor(Color.RED);
countDownTimer[0] = null;//set CountDownTimer to null
}
}.start();
startTimer.setText(getContext().getString(R.string.stop_timer));
} else
Toast.makeText(getContext(), "Please enter no. of Minutes.", Toast.LENGTH_SHORT).show();//Display toast if edittext is empty
} else {
//Else stop timer and change text
if (countDownTimer[0] != null) {
countDownTimer[0].cancel();
countDownTimer[0] = null;
}
startTimer11.setText(getContext().getString(R.string.start_timer));
}
Toast.makeText(getContext(), "Works", Toast.LENGTH_SHORT).show();
alertDialog.cancel();
}
});
Upvotes: 0
Views: 484
Reputation: 101
Save the time they clicked the button to start the timer to the shared preferences.
You can then use that as the time started and calculate the elapsed time by getting the difference between this and the current time.
Upvotes: 1