Search code examples
androidgoogle-play-gamesactivity-lifecycleleaderboardstart-activity

Tracking Leaderboard activity lifecyle (Android)


I'm trying to make my app as robust and friendly as possible and test it for all possible occurrences. Now, I am launching a leaderboard in my app like so:

startActivityForResult(Games.Leaderboards.getLeaderboardIntent(getApiClient(), ID), 1);

When the leaderboard activity is displayed (over my main activity) and the user presses the 'Home' key on their device, and leaves it for a while, one of four things (I think), can happen:

  • 1) Nothing happens and the user is free to return to the app (it will pick up from where is was as it's all still in memory)

  • 2) My App's main activity (It only has one activity) is killed by the System along with the Leaderboard activity to free up resources

  • 3) My App's main activity is killed by the System to free up resources (but the Leaderboard activity survives)

  • 4) The leaderboard activity is killed and the main app survives

Now, when re-launching, I have code in place (using a simple int variable) to track if there was a leaderboard showing at the time the app was paused.

Obviously, this int value can only know the state of the leaderboard at the time the home key was pressed.

When relaunching, how can I know the current state of the leaderboard activity? How can I know if it's still alive or if the system killed it? I need to know this so I can handle any scenario. (ie, if its still physically there, then no need to re-launch it).

Edit

To summarise, when returning to the app after it previously went into the background, how can I know if the leaderboard activity still exists / is displayed or not?


Solution

  • I worked out how to do this. I've tested it and it works perfectly.

    I initially declare an Intent as an instance variable:

    private Intent myLeaderboard;
    

    Then in my ShowLeaderboard() method, I do this:

    ShowLeaderBoard(){
    
        //Only create new object if one doesn't currently exist
        if (myLeaderboard==null){    
            myLeaderboard = Games.Leaderboards.getLeaderboardIntent(getApiClient(), ID);
        }
    
        myLeaderboard.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        startActivityForResult(myLeaderboard, 1);
    
    }