mrhands
mrhands

Reputation: 1533

How to finish Activity when starting other activity in Android?

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?

Upvotes: 39

Views: 127591

Answers (7)

Robi Kumar Tomar
Robi Kumar Tomar

Reputation: 3404

Intent i = new Intent(this,NewLaunchingActivity.Class);
    i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // Call Only, if you wants to clears the activity stack else ignore it. 
    startActivity(i);
    finish();

Add Intent Flag Intent.FLAG_ACTIVITY_CLEAR_TOP if you want to clear the activity stack else ignore it. Read more about this here.

Upvotes: 9

Aman Sharma
Aman Sharma

Reputation: 39

simple example of this can be (Kotlin)

val intent = intent(this,exampleSecondActivity::class.java)
startActivity(intent)
finsih() //this will do all the work for you

It works of me when i navigate to home screen from splash activity

Upvotes: 1

Rautermann
Rautermann

Reputation: 350

The best - and simplest - solution might be this:

Intent intent = new Intent(this, OtherActivity.class);
startActivity(intent);
finishAndRemoveTask();

Documentation for finishAndRemoveTask():

Call this when your activity is done and should be closed and the task should be completely removed as a part of finishing the root activity of the task.

Is that what you're looking for?

Upvotes: 9

Vikalp Patel
Vikalp Patel

Reputation: 10887

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.

Upvotes: 124

Amit Patel
Amit Patel

Reputation: 1825

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

Upvotes: 1

Jasmine John
Jasmine John

Reputation: 11

  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.

Upvotes: 1

Shadow
Shadow

Reputation: 6899

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();

Upvotes: -1

Related Questions