26

The application looks something like this: MainActivity -> UserActivity -> DetailsActivity. (approximate order of activities).

I would like to close the application when the back button is clicked in DetailsActivity (third activity in the row).

Wanted to know if it's good practice to do that and what would be the best way to do that?

  • Use action bar on click of app icon navigate to ap home screen click back button exit app. back button is used to navigate to previous activity. pls check this link http://developer.android.com/design/patterns/navigation.html – Raghunandan Oct 01 '13 at 06:42

14 Answers14

34

If I understand you correctly, you want to close activity even when the stack isn't empty, meaning there is more than 1 activity in stack?

Well if there is only one... just :

finish();

Otherwise the trick is :

Intent intent = new Intent(Main.this, Main.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);

And in the same activity in onCreate :

if (getIntent().getBooleanExtra("EXIT", false)) {
    finish();
}

So you clear the stack and then kill the single one left... you can do this in any activity and of course use it in onBackPressed :)

Drarig29
  • 1,902
  • 1
  • 19
  • 42
Jony-Y
  • 1,579
  • 1
  • 13
  • 30
  • 7
    finish() will end the current activity only! – Ahmad Dwaik 'Warlock' Oct 01 '13 at 06:55
  • 2
    Warlock read the entire answer please... :) this solution works... i know finish() ends the current activity but since you cleared the stack you only have 1 single activity ...your current one... – Jony-Y Oct 01 '13 at 07:01
  • 1
    You don't need to do that manually! since android provides a direct call to move your activity to most bottom of the stack moveTaskToBack(true); – Ahmad Dwaik 'Warlock' Oct 01 '13 at 07:11
  • 1
    Warlock, the issue here was to EXIT the program on back press... if you reoerder the stack its still not empty...so once you use the back press button the activity from the top of the stack will be called...it still wont exit... what you need to do is clear the stack. otherwise you will just return to a different activity – Jony-Y Oct 01 '13 at 07:16
  • @Jony-Y will clearing the stack affect other open applications as well? – Pdksock Mar 10 '14 at 18:06
  • clearing the stack will remove all the stacked activities from your current app... this will not effect any other applications, what it does is just remove the "application history" so you wont go back to previous activities... but this will not affect other applications – Jony-Y Apr 15 '14 at 16:36
  • Does this solution really always work in given case (3 activities)? In the question there are 3 activities and if they are opened in this order: MainActivity -> UserActivity -> DetailsActivity, now if I will press back button I don't think the application will be closed. The app will go to UserActivity, then again if back button is pressed, it will go to Main Activity. Isn't it? This solution works perfectly for 2 activities though. – kunal18 Dec 03 '14 at 06:19
  • this solution will remove all past activities in the stack and so you can have 10..doesnt matter , you clear all stack and then you are only left with yours... so not a problem...havent tried @Ahmad Dwaik 'Warlock solution... but what I posted will work – Jony-Y Dec 03 '14 at 11:21
20

You can accomplish that by overriding the back button event to add no history for specific activity on specific condition.

@Override
public void onBackPressed()
{
    if ( ! getIntent().getExtras().getBoolean(FROM_SETTINGS_KEY))
        moveTaskToBack(true); // exist app
    else
        finish();
}

in my example it check for a flag that is from where i had launched my activity, if launched from settings then act normally, else make it on top and exit app on back pressed

Ahmad Dwaik 'Warlock'
  • 5,953
  • 5
  • 34
  • 56
8

Try this, Add noHistory in you mainifest file each and every activity.

android:noHistory="true"
Murali Ganesan
  • 2,925
  • 4
  • 20
  • 31
7

try this.

 quitBtn.setOnClickListener(new View.OnClickListener() {         
    @Override
    public void onClick(View paramView) 
  {
        finish();          
        moveTaskToBack(true);
    }
});
Amit Jayaswal
  • 1,725
  • 2
  • 19
  • 36
4

When you start UserActivity from MainActivity put finish() after startActivity(). do the same in UserActivity when you start DetailsActivity

Piyush
  • 2,040
  • 16
  • 14
  • Excellent!!! Works like a charm And saves us from having to clear the stack when you want to close the app since each activity you nolonger intend to use can be closed as soon as you've navigated to the next activity in your workflow! :) – Migisha Mar 31 '15 at 21:58
4

Inside your current activity:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK ) {
        Intent intent = new Intent(CurrentActivity.this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("EXIT", true);
        startActivity(intent);
    }
    return super.onKeyDown(keyCode, event);
}

Inside MainActivity OnCreate:

if (getIntent().getBooleanExtra("EXIT", false)) {
    finish();
    return;
}
Nido
  • 89
  • 1
  • 8
2

This works for me:

public void onBackPressed(){
Intent a = new Intent(Intent.ACTION_MAIN);
a.addCategory(Intent.CATEGORY_HOME);
a.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(a);
}
Stephy Samaniego
  • 242
  • 1
  • 3
  • 15
2

If you call UserActivity from MainActivity the call finish() after the startActivity().Below is the code:

Intent userActivity = new Intent(MainActivity.this, UserActivity.class);
       userActivity.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
       MainActivity.this.startActivity(userActivity );
       finish();
Sumant Singh
  • 904
  • 1
  • 14
  • 16
1

1) Create a file named Constants.java in the project

2) Add this code to that file

    public static void killAll() {

    for (Activity act : Constants.activity_stack) {
        act.finish();
    }
    Constants.activity_stack.clear();

}

3)Now when you are in Main Activity in onCreate() add the below snippet

        // add to stack
    Constants.activity_stack.add(this);

4)Similarly add User activity to the stack

5)In Delivery Details in onBackPressed() use the below snippet

Constants.killAll();//will kill all the activities and bring you out of the application.
Swapnil Kadam
  • 4,075
  • 5
  • 29
  • 35
1

Here is a complete class that shows how another activity is called when a button in the first activity is pressed.

public class FirstActivity extends Activity implements View.OnClickListener {

    Button goToSecondActivityButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.first_activity);

        ((TextView) findViewById(R.id.textRecommendationMessage)).setText("This is the first activity");

        goToSecondActivityButton= (Button) findViewById(R.id.button_go_to_second_activity);
        goToSecondActivityButton.setOnClickListener(this);
    }

     @Override
     public void onClick(View view) {

         goToSecondActivity();
    }

    private void goToSecondActivity() {

        Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
        startActivity(intent);
        finish();
    }
}
biniam
  • 8,099
  • 9
  • 49
  • 58
1

use onBackPressed() method in DetailedActivity

  override fun onBackPressed(){ //trigger when user press back button
      super.onBackPressed()
      finishAffinity()  //This will close all acitivities
    }
Saurabh Dhage
  • 1,478
  • 5
  • 17
  • 31
0

on your activity

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    onBackPressed();
    return super.onOptionsItemSelected(item);
}

public void onBackPressed(){
    Intent a = new Intent(Qeydiyyat.this,Login.class);
    a.addCategory(Intent.CATEGORY_HOME);
    a.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(a);
0
   public void onBackPressed() {
    moveTaskToBack(true);

}
Ganesan J
  • 539
  • 7
  • 12
0

There might be more ways to achieve this but here are 2 ways that works for me. One way would be to move the task back on the stack.

    override fun onBackPressed() {
        moveTaskToBack(true);
    }

Another way would be this:

    override fun onBackPressed() {
        val activityToMove = Intent(Intent.ACTION_MAIN)
        activityToMove.addCategory(Intent.CATEGORY_HOME) //Indicate the next activity
        activityToMove.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        startActivity(activityToMove)
    }
chinedu
  • 1
  • 1