Home » Android » How to finish Activity when starting other activity in Android?

How to finish Activity when starting other activity in Android?

Posted by: admin April 23, 2020 Leave a comment

Questions:

I have problems to finish the activity before. I want to start another activity and finish the current activity. When I used finish it didn’t exit the current activity.

How can I exit the activity before?

How to&Answers:

You need to intent your current context to another activity first with startActivity. After that you can finish your current activity from where you redirect.

 Intent intent = new Intent(this, FirstActivity.class);// New activity
 intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
 startActivity(intent);
 finish(); // Call once you redirect to another activity

intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) – Clears the activity stack. If you don’t want to clear the activity stack. PLease don’t use that flag then.

Answer:

Intent i = new Intent(this,Here is your first activity.Class);
    i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(i);
    finish();

Answer:

  1. Make your activity A in manifest file: launchMode = "singleInstance"
  2. When the user clicks new, do FirstActivity.fa.finish(); and call the new Intent.
  3. When the user clicks modify, call the new Intent or simply finish activity B.

Answer:

startActivity(new Intent(context, ListofProducts.class)
    .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
    .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK));

Answer:

For eg: you are using two activity, if you want to switch over from Activity A to Activity B

Simply give like this.

          Intent intent = new Intent(A.this, B.class);
         startActivity(intent);
         finish();