0

In my application i want to exit the application when clicking the back button.When first time entered into the app when clicking back from this screen means it is exiting.But if i got to next screen and coming back to this screen and clicking back means going to previous screen not exiting.Thanks in advance..

My code:

public boolean onKeyDown(int keyCode, KeyEvent event) 
         {      

            if (keyCode == KeyEvent.KEYCODE_BACK)
            {           
                finish();
                java.lang.System.exit(0);

            }
            return super.onKeyDown(keyCode, event);
         }
prakash .k
  • 635
  • 2
  • 12
  • 24
  • 1
    You don't need to exit the app. You don't need to call `System.exit()`. The normal behaviour of Android is to finish the activity when the user presses the "back" key. What makes you think you need to do anything else? – David Wasser Aug 03 '12 at 10:56
  • 1
    Please see [Quitting an application - is that frowned upon?](http://stackoverflow.com/questions/2033914/quitting-an-application-is-that-frowned-upon/2034238) – cyroxx Aug 03 '12 at 10:56

5 Answers5

1

I would advice against implementing such functionality. The back button works the same way in most applications and users feel safe knowing that the back button eventually always puts them back to home screen. Maybe a TabView could be a better way of switching between the two activities?

ekholm
  • 2,543
  • 18
  • 18
  • Thanks ekholm.but i have some different functionality..When i am clicking back form screen(from which the app should exit) is going to previous screen,That's y i am tryong to inplement this.. – prakash .k Aug 03 '12 at 11:11
0

If you want the back button to always exit the app if pressed from the launcher activity, you can use the following to make it a singletask so that app will exit with back press.

In android manifest file: android:launchMode="singleTask" While directing to this activity using startActivity(), intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

Gautham
  • 3,418
  • 3
  • 30
  • 41
0

one better way to do that is by starting second activity using

startActivityForResult();

then, when the user click back button check the result by overriding

onActivityResult(){}

and finish the first activity too.

code-jaff
  • 9,230
  • 4
  • 35
  • 56
0

call moveTaskToBack(true) on your Activity (it doesn't kill your app but remove it from screen)

surfealokesea
  • 4,971
  • 4
  • 28
  • 38
0

You should use :

if (keyCode == KeyEvent.KEYCODE_BACK)
{           
      finishAffinity();
}
elifekiz
  • 1,456
  • 13
  • 26