问题
This isn't working the way I expected. However, the way I expect it to work is probably wrong.
I have an application that implements a Countdown timer. When the back button on the android phone is clicked the user is navigated back to the main screen. However, the countdown timer still runs in the background. I can tell as it performs a beer at certain intervals.
I thought if I implemented onPause() I would be able to call countdowntimer.cancel(). And it would cancel the count down timer when the user exits the activity via the back button. However, the application fails instead.
I have also tried a similar approach with onStop() but it just doesn't work.
I don't have my code with me at the moment, it's just on my mind. Also sorry if there are any mistakes on this post, I have written it on my phone.
回答1:
onPause() call when one Activity transfer control to another Activity, and onStop() method call when Activity in finish mode.
回答2:
Try:
movetasktoback(true);//in the onbackpressed
Then use the:
countdowntimer.cancel();// in onpause
After that you can call finish() in onpause().
回答3:
why dont you call countdowntimer.cancel() when back key is pressed you can override back click like
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
countdowntimer.cancel();
}
return super.onKeyDown(keyCode, event);
}
来源:https://stackoverflow.com/questions/15658751/onpause-or-onstop