问题
I have a CountDownTimer which updates a TextView, but when I press the back button it stops.
CountDownTimer timer = new CountDownTimer(600000, 100) {
public void onTick(long millisUntilFinished) {
calendar.setTimeInMillis(millisUntilFinished);
cron.setText(sf.format(calendar.getTime()));
}
public void onFinish() {
}
};
How can I keep it running when I press the back button and the activity gets destroyed?
PS: I also start a GPS service when the timer starts, Is there a way to put the CountDownTimer in the service?
回答1:
If your timer needs to live beyond the lifecycle of your Activity
, then it does not belong there. You can certainly place it into a Service
, or another object (like a singleton) that can stay resident in memory.
回答2:
As prashant and Devunwire pointed out, you need to use a Service. Make sure you call startService()
before binding to it, this causes the Service to stay alive even if the calling Activity is destroyed.
Make sure as well that the service stops itself with stopSelf()
after the timer has finished and did whatever its supposed to do.
回答3:
I think it should be possible to put the countdown timer in a Service. You can trigger the timer to start by sending an intent to the service. Also, you will have to use some mechanism such as a callback or intent or messenger to relay the update time back to your UI.
回答4:
Override the back button and then make it behave like the home button. This way your activity is never destroyed. That said, I don't think this is considered "good practice."
To do what I'm saying you just place this into your activity class.
@Override
public void onBackPressed() {
moveTaskToBack(true);
}
Whatever you do, as an optimization, you should make sure that the TextView is not updated if the TextView isn't visible on the screen. This should save battery life and probably prevent the creation of strings which will reduce garbage collections.
来源:https://stackoverflow.com/questions/11546400/how-keep-a-countdowntimer-running-when-i-press-the-back-button