我在Fragment中使用了一个CountDownTimer
,并尝试在用户按下手机的物理返回按钮时停止它。我已经尝试覆盖onPause
、onDestroy
、onStop
和onDestroyView
方法,但似乎都没有起作用。有没有人可以给我指点一下?
public class Foo extends Fragment {
CountDownTimer myTimer;
@Override
public void onStop() {
super.onStop();
myTimer.cancel();
}
@Override
public void onPause() {
super.onPause();
myTimer.cancel();
}
@Override
public void onDestroyView() {
super.onDestroyView();
myTimer.cancel();
}
@Override
public void onDestroy() {
super.onDestroy();
myTimer.cancel();
}
@OnClick(R.id.btn_greenleft_no)
public void goBack() {
myTimer.cancel();
Objects.requireNonNull(getActivity()).onBackPressed();
}
@OnClick(R.id.btn_greenright_yes)
public void showSuccess(View view) {
markAll();
myTimer.cancel();
(new MusicPlayer()).playSound(getContext(), "cheers.mp3");
final Snackbar snackbar = Snackbar.make(snackBarView, R.string.congratulations, Snackbar.LENGTH_SHORT);
snackbar.show();
myTimer.cancel();
}
private void startTimer(final View view) {
int Seconds = 5;
myTimer = new CountDownTimer(Seconds * 1000 + 1000, 1000) {
public void onTick(long millisUntilFinished) {
String rem = String.valueOf(millisUntilFinished / 1000);
Log.d("APP_DEBUG", "Timer: " + rem);
}
public void onFinish() {
goBack();
}
}.start();
}
}
onBackPressed
方法。 - Fawzan