1

In my project i move from main activity to activity A and from activity A to activity B. From activity B using home menu on toolbar i jump back to main activity. Now when i press back button application should exit but it opens the activity A again.

4 Answers4

0

Call the finish() method before starting the next activity to have it removed from the activity. Find more details and options here.

Bernard
  • 333
  • 2
  • 8
0

You should make use of the launch flags to manage your activities in the back stack. As far as I understood your scenario, I think you need to use FLAG_ACTIVITY_CLEAR_TOP for starting your main/home activity.

Read more about launch flags: https://developer.android.com/reference/android/content/Intent#FLAG_ACTIVITY_CLEAR_TOP.

Also, take a look this for more details on managing activity back stack on Android: https://developer.android.com/guide/components/activities/tasks-and-back-stack#ManagingTasks

Shubham Naik
  • 410
  • 1
  • 7
  • 18
0

For Kotlin write this in your MainActivity :

override fun onBackPressed() {
    moveTaskToBack(true)
    exitProcess(-1)
}

For Java write this in your MainActivity :

@Override
void onBackPressed() {
    moveTaskToBack(true)
    exitProcess(-1)
}

Hope to it will work for you as good as for me

-1

hey i write some code for you Variables:

boolean backactivity = true;

CODE:

public boolean onOptionsItemSelected(MenuItem item){
        if(backactivity==true)
        {
            finishActivity(1);
            backactivity=false;
        }else
        {
            Intent homeIntent = new Intent(Intent.ACTION_MAIN);
            homeIntent.addCategory( Intent.CATEGORY_HOME );
            homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(homeIntent);
        }
        return true;
    }
MoriX
  • 1
  • 2