Search code examples
androidgoogle-play-gamesstartactivityforresult

The official document about Leaderboards of Play Games Services uses deprecated startActivityForResult


Below code is from Google's official document about Leaderboards of Play Games Services (converted into Kotlin):

private fun showLeaderboard() {
    PlayGames.getLeaderboardsClient(this).allLeaderboardsIntent
        .addOnSuccessListener { intent ->
            startActivityForResult(intent, 0)
        }
}

Android Studio says:

'startActivityForResult(Intent!, Int): Unit' is deprecated. Deprecated in Java

How can I fix this?


Solution

  • You can use ActivityResultContracts instead of deprecated startActivityForResult.

    private val leaderboardsResultLauncher = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { /* do nothing */ }
    
    private fun showLeaderboard() {
        PlayGames.getLeaderboardsClient(this).allLeaderboardsIntent
            .addOnSuccessListener { intent ->
                leaderboardsResultLauncher.launch(intent)
            }
    }
    

    The Leaderboards document says:

    Notice that even though no result is returned, we have to use startActivityForResult so that the API can obtain the identity of the calling package.

    So, in this situation (as for Leaderboards), you have nothing to do with the result in your ActivityResultContracts.