Android startActivityForResult Deprecated

Nov 2, 2021
class MainActivity : ComponentActivity() {    private val auth: FirebaseAuth = Firebase.auth    private lateinit var googleSignInClient: GoogleSignInClient    private lateinit var authResultLauncher: ActivityResultLauncher<Intent>    override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)        auth.addAuthStateListener { auth ->            Timber.d("addAuthStateListener: ${auth.currentUser}")        }        val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)            .requestIdToken(getString(R.string.default_web_client_id))            .requestEmail()            .build()        googleSignInClient = GoogleSignIn.getClient(this, gso)        authResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->            // if (result.resultCode == Activity.RESULT_OK) {            // There are no request codes            val data: Intent? = result.data            val task = GoogleSignIn.getSignedInAccountFromIntent(data)            try {                // Google Sign In was successful, authenticate with Firebase                val account = task.getResult(ApiException::class.java)!!                Timber.d("firebaseAuthWithGoogle:" + account.id)                firebaseAuthWithGoogle(account.idToken!!)            } catch (e: ApiException) {                // Google Sign In failed, update UI appropriately                Timber.w(e, "Google sign in failed")            }            // }        }    }    fun signIn() {        val signInIntent = googleSignInClient.signInIntent        // startActivityForResult(signInIntent, RC_SIGN_IN)        authResultLauncher.launch(signInIntent)    }    private fun firebaseAuthWithGoogle(idToken: String) {        val credential = GoogleAuthProvider.getCredential(idToken, null)        auth.signInWithCredential(credential)            .addOnCompleteListener(this) { task ->                if (task.isSuccessful) {                    // Sign in success, update UI with the signed-in user's information                    Timber.d("signInWithCredential:success")                    // val user = auth.currentUser                    // updateUI(user)                } else {                    // If sign in fails, display a message to the user.                    Timber.w(task.exception, "signInWithCredential:failure")                    // updateUI(null)                }            }    }    }

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.