Pablo Pautasso
Pablo Pautasso

Reputation: 49

how back to the main activity in android?

I have a MainActivity "A", which have a button that launch activity "B", and activity "B" have another button that launch activity "C". In the activities B and C, both have onBackPressed() method, which appears an AlertDialog asking if the user wants to return to MainActivity. If they press yes, the program should show MainActiviy.

The question is: in activity B, i have not problem, simply call the finish() method, and MainActivity appears, but the problem is in activity C, if i call a finish() method, the program is back to activity B. How back to MainActivity from activity C??

Upvotes: 4

Views: 4655

Answers (3)

Rich
Rich

Reputation: 1055

try this on you onBackPressed:

Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

this clears the activity stack and opens your main activity. No matter which activity you are, you will always go back to the main activity and all other activities are removed from the stack.

Upvotes: 6

KNOX.C
KNOX.C

Reputation: 323

You can try ActivityCompat.finishAffinity and start MainActivity at your Activity C.

Upvotes: 0

Alok
Alok

Reputation: 163

Use the following in your manifest file for the activity B and C:

<activity android:name=".ActivityB"
            android:parentActivityName=".MainActivity"/>
<activity android:name=".ActivityC"
            android:parentActivityName=".MainActivity"/>

Upvotes: 3

Related Questions