Monday, 8 October 2018

Cancelling a CountDownTimer on Physical Back Button Press in a Fragment

I am using a CountDownTimer in a Fragment and trying to stop it if the user hit the physical back button in the phone. I have tried overriding onPause, onDestroy, onStop, onDestroyView but nothing seems to be working. Kind of lost here. Can some one give me a pointer here?

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();

    }

}



from Cancelling a CountDownTimer on Physical Back Button Press in a Fragment

No comments:

Post a Comment