How to replace startIntentSenderForResult with ActivityResultContract in Android

Viewed 32

i am investigating Google Identity Services in my current Android project for Sign In With Google.

theres this code in the docs:-

private static final int REQUEST_CODE_GOOGLE_SIGN_IN = 1; /* unique request id */

private void signIn() {
    GetSignInIntentRequest request =
        GetSignInIntentRequest.builder()
            .setServerClientId(getString(R.string.server_client_id))
            .build();

    Identity.getSignInClient(activity)
        .getSignInIntent(request)
        .addOnSuccessListener(
                result -> {
                    try {
                        startIntentSenderForResult(
                                result.getIntentSender(),
                                REQUEST_CODE_GOOGLE_SIGN_IN,
                                /* fillInIntent= */ null,
                                /* flagsMask= */ 0,
                                /* flagsValue= */ 0,
                                /* extraFlags= */ 0,
                                /* options= */ null);
                    } catch (IntentSender.SendIntentException e) {
                        Log.e(TAG, "Google Sign-in failed");
                    }
                })
        .addOnFailureListener(
                e -> {
                    Log.e(TAG, "Google Sign-in failed", e);
                });
}

however startIntentSenderForResult method is marked ad deprecated with the following comment:-

This method has been deprecated in favour of using the Activity Result API which brings increased type 
safety via an ActivityResultContract and the prebuilt contracts for common intents available in 
androidx.activity.result.contract.ActivityResultContracts, provides hooks for testing, and allow 
receiving results in separate, testable classes independent from your activity.
Use registerForActivityResult(ActivityResultContract, ActivityResultCallback) passing
in a StartIntentSenderForResult object for the ActivityResultContract.

i do not understand how to replace startIntentSenderForResult with registerForActivityResult(ActivityResultContract, ActivityResultCallback), when i follow the instructions and pass the StartIntentSenderForResult object for the ActivityResultContract as follows i get a compile error message

heres my code

private fun signIn() {
        val request: GetSignInIntentRequest = GetSignInIntentRequest.builder()
            .setServerClientId(getString(R.string.server_client_id))
            .build()

        Identity.getSignInClient(this@MainActivity)
            .getSignInIntent(request)
            .addOnSuccessListener { 
                
                registerForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) {

                    Log.d(TAG, "signIn() called ${it.data}")
                    Log.d(TAG, "signIn() called ${it.resultCode}")

                }




            }
            .addOnFailureListener { e -> Log.e(TAG, "Google Sign-in failed", e) }
    }
1 Answers

this is what i ended up with:-

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initializeGoogleSignIn()
    }

    private val launcher = registerForActivityResult(ActivityResultContracts.StartIntentSenderForResult(), ::handleSignInResult)

    private fun handleSignInResult(result: ActivityResult) {
        val task: Task<GoogleSignInAccount> = GoogleSignIn.getSignedInAccountFromIntent(result.data)
        try {
            val account = task.getResult(ApiException::class.java)
            Log.d(TAG, "handleSignInResult() called with: result = $account")
        } catch (ex: ApiException) {
            Log.e(TAG, "handleSignInResult: ", ex)
        }
    }

    private fun initializeGoogleSignIn() {
        val request = GetSignInIntentRequest.builder()
            .setServerClientId(getString(R.string.server_client_id))
            .build()

        Identity.getSignInClient(this)
            .getSignInIntent(request)
            .addOnSuccessListener { result ->
                val intentSenderRequest = IntentSenderRequest.Builder(result).build()
                launcher.launch(intentSenderRequest)
            }
            .addOnFailureListener { e ->
                Log.e(TAG, "initializeGoogleSignIn: ",e )
            }
    }
}
Related