1

Lets say I have a a main activity FirstActivity (when I press the back button here, it just closes the app) and I have another activity called SecondActivity (FirstActivity goes to this when user is logged in). Now when I press the back button, it goes to FirstActivity instead of closing the app. Is there any way I can just close the app from SecondActivity, ignoring any Activity on the back stack? The callback method I use to close the app in my SecondActivity:

@Override
public void onBackPressed() {
    finish();   
}
Loolooii
  • 8,588
  • 14
  • 66
  • 90

2 Answers2

4

The best thing to do is when you start the SecondActivity in the FirstActivity, do this:

Intent i = new Intent(FirstActivity.this, SecondActivity.class);
startActivity(i);
finish(); // finish FirstActivity

Using this, the FirstActivity will be destroyed when the SecondActivity is created.

Michael Yaworski
  • 13,410
  • 19
  • 69
  • 97
SMR
  • 6,628
  • 2
  • 35
  • 56
  • The finish(); does the job entirely. This was exactly what I wanted. Thanks. – Loolooii Jan 29 '14 at 12:52
  • 1
    including `finish()` in the `FirstActivity` destroys the activity and makes sure that it is not reached using the back button. Thus also conservers memory. – SMR Jan 29 '14 at 13:01
  • 1
    Don't forget to do a final clean up of resources you used. – Luis Pena Jan 29 '14 at 16:43
  • @LuisAlberto Could you be more specific? I'm new to Android. – Loolooii Feb 02 '14 at 00:19
  • onFinish() call the method onDestroy(), so there you need to clean the mess you did literally :P. For example: You opened a stream on onCreate(), then you close it to avoid memory leak. – Luis Pena Feb 02 '14 at 05:22
0

You could use something like startActivityForResult kind of like what I had to do in this question, or you could do what I've done here:

public class FirstActivity {
    public static boolean close = false;    

    @Override
    public void onResume()
    {
        super.onResume();
        if (close) {
            finish();
        }
    }
}

public class SecondActivity {

    @Override
    public void onBackPressed() {
        FirstActivity.close = true;
        finish();
    }
}
Community
  • 1
  • 1
Michael Yaworski
  • 13,410
  • 19
  • 69
  • 97
  • @LuisAlberto It doesn't matter. I suggested `startActivityForResult` as well as a flag. They both work fine and a flag could be nice if he only wants the back button to close the app completely in certain situations (change `FirstActivity.close` when he wants). Otherwise, SMR's answer will work for him. – Michael Yaworski Jan 29 '14 at 17:11
  • Yeah, your answer is good, but that's why a finish() method was made, but in some cases using a flag would be the best option. :-) – Luis Pena Jan 31 '14 at 03:39