spotify / android-sdk

Spotify SDK for Android
https://developer.spotify.com/documentation/android/
Apache License 2.0
474 stars 120 forks source link

Use Activity Result API instead of deprecated methods startActivityForResult & onActivityResult #324

Open chuck-stein opened 2 years ago

chuck-stein commented 2 years ago

The current implementation of AuthorizationClient calls startActivityForResult and expects the user to call onActivityResult, both of which are now deprecated in favor of the Activity Result API.

The SDK should therefore be updated to use the Activity Result API, as should the documentation + sample code, which currently recommend the client uses the deprecated method onActivityResult.

For the SDK to implement the Activity Result API, it could be as simple as a new static function in AuthorizationClient such as the following:

fun createLoginActivityResultContract(contextActivity: Activity) = object : ActivityResultContract<AuthorizationRequest, AuthorizationResponse>() {

    override fun createIntent(context: Context, input: AuthorizationRequest): Intent =
        AuthorizationClient.createLoginActivityIntent(contextActivity, input)

    override fun parseResult(resultCode: Int, intent: Intent?): AuthorizationResponse =
        AuthorizationClient.getResponse(resultCode, intent)
}

(or the Java equivalent).

Then, instead of instructing the client to call the following from their Activity:

AuthorizationClient.openLoginActivity(this, REQUEST_CODE, request)

they should call:

requestSpotifyAuth.launch(request)

where requestSpotifyAuth is a property of the Activity declared as:

private val requestSpotifyAuth = registerForActivityResult(AuthorizationClient.createLoginActivityResultContract(this)) { response: AuthorizationResponse ->
    /* ...handle response... */ 
}

(or the Java equivalent -- although the documentation & sample code should be updated to use Kotlin as it has been Google's preferred language for Android developers to use since 2019).

Something like this would bring the SDK up to date, remove developer confusion at the recommendation to use deprecated methods, and remove the need to use arbitrary result codes. Thanks!

langsmith commented 5 months ago

Yes, this would be great. Kinda' wild that they haven't updated the SDK to use Activity Result API 😕