简体   繁体   中英

Call an Activity after returning to main activity?

I have a main activity which is the main menu for my game - Also a second activity: the game itself. After the player finishes a game session they are then returned to the main menu - I want to call a method when they return to the main menu. How would I implement this?

Code for starting the game:

    Intent intent = new Intent(MainActivity.this, InGame.class);
            finish();
            MainActivity.this.startActivity(intent);

Code for returning to the main menu:

public void returnMainMenu()
{
    Intent intent = new Intent(InGame.this, MainActivity.class);
    InGame.this.startActivity(intentMain);
}

Any help would be greatly appreciated thanks.

Use startActivityForResult() to go the game activity from the main activity. Also, do not finish the main activity, because the idea is to come back to it, and not create a new instance of it when you are coming back.

To return to the main menu, you should simply call finish() to kill the second activity and go back to the main activity. This will invoke onActivityResult() in the main activity.

To start the InGame Activity,

Intent intent = new Intent(MainActivity.this, InGame.class);
MainActivity.this.startActivityForResult(intent, YOUR_REQUEST_CODE);

To return to main menu,

public void returnMainMenu(){
    InGame.this.finish();
}

This invokes

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == YOUR_REQUEST_CODE) {
        // your logic here 
    }
}

Read this Android documentation here for a more detailed explanation.

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