Retrieve a reference to CountDownTimer after Closed activuty
My activity has a simple menuItem that start a counter... the counter is stored in a field of the activity the problem is with the "back button" after closing the activity (back button), the timer (as in my intention) continues, and restarting the activity behave correctly by reshowing the timer... but I lost the reference to the counter and so I cannot stop it Any ideas?
following there is a part of the code of the function boolean onOptionsItemSelected(MenuI开发者_Go百科tem item)
switch (item.getItemId()) {
case R.id.STARTSTOP:
running = !running;
if (!running) {
item.setTitle("START");
if (counter!=null) {
counter.cancel();
counter = null;
}
}
else {
item.setTitle("STOP");
counter = new CountDownTimer(1000*60*20/*20min*/,1000){
@Override
public void onFinish() {
TextView tv = (TextView) findViewById(R.id.counter);
tv.setText("done!");
}
@Override
public void onTick(long millisUntilFinished) {
TextView tv = (TextView) findViewById(R.id.counter);
tv.setText(millisUntilFinished);
Log.d("XXXDEBUGXXX",millisUntilFinished);
}
};
counter.start();
}
}
I'd suggest to use AlarmManager
instead.
Or you could use SharedPreferences
to store intermediate value that's read in onResume(..)
to restart the timer and saved in onPause(..)
.
精彩评论