简体   繁体   中英

How do I resume screen activity for more than one activity?

So I have these two screens, Messages screen and Game screen. What I want to do is when the user switches back from either screen, it resumes from the previous activity.

This is a bit of code in my Game screen that allows the user to go to the Messages screen:

public void onMessagesButtonClick() {
    Intent intent = new Intent(this, Messages.class);
    startActivity(intent);
    overridePendingTransition(0, 0);
}

And this is a bit of code that allows the user to go from the Messages screen back to the Game screen.

public void onGameButtonClick() {
    Intent intent = new Intent(getApplicationContext(), Game.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    startActivity(intent);
    finish();
    overridePendingTransition(0, 0);
}

So far I am able to go from the Game screen to the Messages screen, then go from the Messages screen and resume activity in the Game screen.

The problem I now have is I can't resume activity from the Messages screen, only the Game screen. If I were to update the onMessagesButtonClick() to:

public void onMessagesButtonClick() {
    Intent intent = new Intent(getApplicationContext(), Messages.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    startActivity(intent);
    finish();
    overridePendingTransition(0, 0);
}

I will no longer be able to resume activity from the Game screen. It will be as if I am entering the screen for the first time, starting the screen fresh.

What can I do to be able to resume previous activity from both screens when going back and forth between screens?

try this one

public void onGameButtonClick() {
    Intent intent = new Intent();
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    setResult(RESULT_OK, intent);
    finish();
    overridePendingTransition(0, 0);
}

on your game class

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if(resultCode == RESULT_OK) {
             //If you are going to fetch data from former activity
            }
    }
}

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