Josh Beckwith Josh Beckwith - 1 month ago 18
Android Question

Android: Listening for activty results in one activty

In Android, I am making a simple game. This game is basically comprised of minigames. Each minigame, I have created as an activity. Let's call them ActivityA ActivityB and ActivityC.

I would like to "broadcast" (I use that term very loosely) on completion of any of these activities. When the user beats the minigame, a 1 is "broadcasted", and when they lose, maybe a -1.

I need something to listen for these "broadcasts" and keep track of the score so I know when to end the game.

What's the best way of keeping track of these, where should I start?
Personally, I was hoping there would be an invisible activity (or maybe a service) between the main menu, and the game screen, that would do all of the controlling (counting score, telling the app which activities to start, etc).

Thank you!

Answer

You might want to read a little about startActivityForResult.

Quick overview
You can also start another activity and receive a result back.Then your MainActivity receives it in the onActivityResult() callback.

In your "MainActivity" you would have something like this:
You set the intent for the new class and then call startActivityForResult with a unique code to identify the activity that was started)

private void startActivityA() {
    Intent intent = new Intent(this, ActivityA.class);
    startActivityForResult(intent, ACTIVITY_A_CODE);
}

private void startActivityB() {
    Intent intent = new Intent(this, ActivityB.class);
    startActivityForResult(intent, ACTIVITY_B_CODE);
}

private void startActivityC() {
    Intent intent = new Intent(this, ActivityC.class);
    startActivityForResult(intent, ACTIVITY_C_CODE);
}

Then in your MainActivity implement the onActivityResult method, something similar like below in which you will check for what activity was started (*_CODE) and then check whether the result was OK or not.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // Check which request we're responding to
    if (requestCode == ACTIVITY_A_CODE) {
        // if the result of the activity was good, then:
        if (resultCode == RESULT_OK) {
           // score++;
        } else {
           // score--;
        }
    }
    else if (requestCode == ACTIVITY_B_CODE) {
        // ....
    }

}


In your new activities you must set the result, based on your criterias, with setResult()


Please read in more detail about startActivityForResult from the Android Documentation.