0

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

kingston
  • 11,053
  • 14
  • 62
  • 116

4 Answers4

1

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.

Community
  • 1
  • 1
Gan
  • 1,349
  • 2
  • 10
  • 27
  • But fragments are part of the same activity so that method does not work, right? I need something equivalent to that but instead of checking the activities in the task I need to check the fragments in the activity. – kingston Sep 13 '12 at 13:32
  • true, another solution could be to track the fragments. I used to track it with a flag, you could possibly do the same and if you flag identifies current UI as the initial fragment the display the dialog. – Gan Sep 13 '12 at 13:37
  • right I was trying to check whether there are other solutions. The first fragment in my case is always different so it would be a bit messy to track it – kingston Sep 13 '12 at 13:47
0

just override onBackPressed.

Also, see http://developer.android.com/guide/components/tasks-and-back-stack.html for better understanding of the notion of backstack in android

njzk2
  • 38,969
  • 7
  • 69
  • 107
  • You don't say anything about the problem with the fragments – kingston Sep 13 '12 at 13:48
  • thing is, the app stack is getting real complicate these days. your app may not simply be a stack of stuff, but may be intricated with others. – njzk2 Sep 13 '12 at 14:37
0

use this method of Activity

            @Override
        public void onBackPressed() {
            // TODO Auto-generated method stub
                       // Add here  whatever uoy want

        }
Rajendra
  • 1,700
  • 14
  • 17
0

You can override

public void onBackPressed() {
  super.onBackPressed();
}

and check for your condition like,

public void onBackPressed() {
  if(foo == true)
    showDialog();
  else
    super.onBackPressed();
}
Ajmal Salim
  • 4,142
  • 2
  • 33
  • 41