[2020/04/21 Google アカウントを利用して Firebase にサインインする No6]
class MainActivity : AppCompatActivity() {
private val coroutineScope = CoroutineScope(Dispatchers.IO)
private val googleAuthController: GoogleAuthController by lazy {
GoogleAuthController(this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val userIdTextView = findViewById<TextView>(R.id.user_id_text_view)
val signInButton = findViewById<Button>(R.id.sign_in_button)
signInButton.setOnClickListener {
googleAuthController.startSignIn {
coroutineScope.launch {
val token = Tasks.await(it.getIdToken(true)).token
withContext(Dispatchers.Main) {
userIdTextView.text = token
}
}
}
}
val signOutButton = findViewById<Button>(R.id.sign_out_button)
signOutButton.setOnClickListener {
googleAuthController.startSignOut()
userIdTextView.text = ""
}
coroutineScope.launch {
val currentUser = googleAuthController.currentUser
if (currentUser != null) {
val token = Tasks.await(currentUser.getIdToken(true)).token
withContext(Dispatchers.Main) {
userIdTextView.text = token
}
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
googleAuthController.onActivityResult(requestCode, resultCode, data)
}
}
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/user_id_text_view"
android:layout_width="0dp"
android:layout_height="0dp"a
android:gravity="center"
android:textSize="16sp"
app:layout_constraintBottom_toTopOf="@id/sign_in_button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/sign_in_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Sign In"
app:layout_constraintTop_toBottomOf="@id/user_id_text_view"
app:layout_constraintBottom_toTopOf="@id/sign_out_button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="@+id/sign_out_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Sign Out"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@id/sign_in_button"
app:layout_constraintBottom_toBottomOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>