-2

In fact, I am new to Android App Development. In my application, I have a couple of activities and I have provided my users with an exit option menu to be able to leave the application. But there is a problem. When they hit the Exit button, they are able to leave the application but when they enter the application for the second time, the page that they left off the last time will be launched. Here comes my code:

@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
    switch (item.getItemId()) {
        case 0 :
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            finish();
            Toast.makeText(this, "Goodbye Dear", Toast.LENGTH_LONG).show();
            break;
Behzad Moradi
  • 67
  • 2
  • 3
  • 6
  • 5
    "I have provided my users with an exit option menu to be able to leave the application" -- please don't. http://stackoverflow.com/questions/2033914/quitting-an-application-is-that-frowned-upon/2034238#2034238 – CommonsWare Apr 17 '13 at 15:59
  • better give an example with A and B activity – stinepike Apr 17 '13 at 15:59
  • CommomnsWare already said it. "Exit" is nearly always evil. – Simon Apr 17 '13 at 16:05

4 Answers4

1

Android Activity has two methods onPause and onDestroy where you can do the necessary cleanup.

http://developer.android.com/reference/android/app/Activity.html

smk
  • 5,340
  • 5
  • 27
  • 41
1

Instead of using finish(), use System.exit(0);.

Ali
  • 2,012
  • 3
  • 25
  • 41
  • No, this is quite in conflict with the design of Android, and may well not achieve the desired goal, as it likely will not affect Android's idea of where a recreated process should start. – Chris Stratton Apr 03 '14 at 20:42
0

You have to override onPause and/or onDestroy methods inside your activity and delete your view within these methods.

user1071138
  • 656
  • 3
  • 12
  • 30
0

The problem in your code is that Intent.FLAG_ACTIVITY_NEW_TASK doesn't remove your current Task. Read more about it here: Task and Back Stack | Android Developers.

Try using Intent.FLAG_ACTIVITY_CLEAR_TOP. From the documentation we can see that this gives the desired behavior.

If set, and the activity being launched is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it will be closed and this Intent will be delivered to the (now on top) old activity as a new Intent.

Jozua
  • 1,274
  • 10
  • 18