Cancelling a CountDownTimer on Physical Back Button Press in a Fragment

Here is my 2 cents. Fragment doesn't have an onBackPressed() method which is present in the Activity class. It gets called when physical back button is pressed by the user. Here is what docs says:

Called when the activity has detected the user's press of the back key. The default implementation simply finishes the current activity, but you can override this to do whatever you want.

What you can do is override the onBackPressed() method in the parent activity of your Foo fragment, then using an interface communicate to the fragment that back button was pressed by the user. Inside the fragment you can have the desired code to cancel the timer. This answer in the question How to implement onBackPressed() in Fragments? can help with sample code.


Try to modify onBackPressed in Your fragment's parent activity.

@Override
public void onBackPressed() {

    // I assume this is the way how You add fragment to fragment manager
    //getSupportFragmentManager().beginTransaction().replace(android.R.id.content, Foo.getInstance(), Foo.TAG).commit()

    // Find fragment by its string TAG and when You get it, call to stop countDownTimer
    Foo foo = (Foo) getSupportFragmentManager().findFragmentByTag(Foo.TAG);
    if (foo != null) {
        foo.stopCountDownTimer();
    }

    super.onBackPressed();
}

Next step is to declare in Your Foo fragment two things:

public static final String TAG = "Foo";

and

public void stopCountDownTimer() {
    myTimer.cancel();
}