Search code examples
androidandroid-fragmentsback

disable back press only when the application would otherwise go to the background in Android


My application should ask the user for a confirmation before putting the application in the background when the user presses the back button.

I tried to override dispatchKeyEvent. The problem is that I also have fragments that are pushed in the backStack.

I should not ask the confirmation when there is still a fragment in the back stack because in that case the application won't go to the background: it will pop up the fragment from the stack.

Is there a way to distinguish between the case when the application will go to the background and when another fragment will be popped up from the stack in dispatchKeyEvent? If not is there another way to do it?

Thanks


Solution

  • You can override the onBackPressed method and get a list of current tasks from the activity manager and then decide weather to ask the user for conformation or just go back. This solutions is discussed here.