简体   繁体   中英

Android - how to return to different previous activities

I have several activities/pages in my app. From the first activity, I can open a second activity. In this second activity a game is played. Once this game ends, a new activity starts. In that new activity, I have a button that finishes it, using finish() , which returns me to the activity with the game. I also have a button that is to return it to the very first activity. Here is a diagram to clarify:

img

When I use finish() to go back to the Game Activity, the game is in an endstate. I want to reset all variables and widgets, but I do not know how to check if I entered this page via calling finish() in the Final Activity.

Q1: How can I check if I entered an activity as a result of finishing another?

I also have another question- what method can I use in button2 to finish not only the final activity but also all previous activities on the stack (except for the first activity, so in this case it would be Final Activity and Game Activity), in order to return to the first activity? In other answers on stackoverflow, I have found suggestions to use FLAG_ACTIVITY_CLEAR_TOP , but if I were to do that, I could no longer also return to Game Activity with button1.

Q2: How can I return to the first activity, while still allowing me to use finish() to return to other activities?


Code I use to go back to previous activity:

// called from button1's onClick 
public void goBack(View button1){
    finish();
}

And for going back to the first activity:

public void toFirstActivity(View button2){
    Intent previousPage = new Intent();
    previousPage.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    finish();
}

Q1: How can I check if I entered an activity as a result of finishing another?

You can easily use a global boolean flag such as "activityFinished", when you call finish() on Final Activity, you set it to true. and in onResume() of your activities, check if activityFinished == true, if so do your stuff and reset the flag to false.

Q2: How can I return to the first activity, while still allowing me to use finish() to return to other activities?

I don't understand why FLAG_ACTIVITY_CLEAR_TOP is a problem for you. You only set the intent as FLAG_ACTIVITY_CLEAR_TOP to go back to your very first activity after you have pressed button 2, don't you? How does this have something to do with your button 1's action?

Update: try this code

Intent a = new Intent(this,FirstActivity.class);
a.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(a);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM