如何在 Android 中使用 Firebase 通过 GitHub 签名后更新用户的个人资料?
在本文中,我们将学习更新通过 GitHub 登录应用程序的用户个人资料。个人资料将通过用户的 GitHub 信息更新,如 GitHub Id、姓名、关注者、关注者等。让我们开始吧!
第 1 步:首先设置您的应用程序,以便用户可以通过 GitHub 登录。因此,您需要在 firebase 的帮助下使用 GitHub 对用户进行身份验证。为此,请按照文章中的所有步骤操作:在 android 中使用 Github 验证用户。
第 2 步:更新个人资料
为此,在 signInWithGithubProvider() 方法的 else 部分声明一个类型为 map
private fun signInWithGithubProvider(){
. . .
if{
. . . }
else {
. . .
val user: Map
. . .
}
}
使用 additionalUserInfo,所有必需的信息将从 MainActivity 发送到 HomePageActivity(使用 Intent),其中包含用户的个人资料信息。所有代码都与本文相同,找出不同之处并添加更新用户配置文件所需的代码行。下面是MainActivity.kt文件的代码。代码中添加了注释以更详细地理解代码。
Kotlin
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.android.gms.tasks.OnFailureListener
import com.google.android.gms.tasks.OnSuccessListener
import com.google.android.gms.tasks.Task
import com.google.firebase.auth.AuthResult
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.auth.OAuthProvider
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
class MainActivity : AppCompatActivity() {
private lateinit var firebaseUser: FirebaseUser
private lateinit var loginBtn: Button
private lateinit var githubEdit: EditText
// firebaseAuth variable to be initialized later
private lateinit var auth: FirebaseAuth
// an instance of an OAuthProvider using its
// Builder with the provider ID github.com
private var provider = OAuthProvider.newBuilder("github.com")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Initialize Firebase Auth
auth = Firebase.auth
loginBtn = findViewById(R.id.github_login_btn)
githubEdit = findViewById(R.id.githubId)
// Target specific email with login hint.
provider.addCustomParameter("login", githubEdit.text.toString())
// Request read access to a user's email addresses.
// This must be preconfigured in the app's API permissions.
val scopes: ArrayList = object : ArrayList() {
init {
add("user:email")
}
}
provider.scopes = scopes
// call signInWithGithubProvider() method
// after clicking login Button
loginBtn.setOnClickListener {
if (TextUtils.isEmpty(githubEdit.text.toString())) {
Toast.makeText(this, "Enter email associated to github", Toast.LENGTH_LONG).show()
} else {
signInWithGithubProvider()
}
}
}
// To check if there is a pending
// result, call pendingAuthResult
private fun signInWithGithubProvider() {
// There's something already here! Finish the sign-in for your user.
val pendingResultTask: Task? = auth.pendingAuthResult
if (pendingResultTask != null) {
pendingResultTask
.addOnSuccessListener {
// User is signed in.
Toast.makeText(this, "User exist", Toast.LENGTH_LONG).show()
}
.addOnFailureListener {
// Handle failure.
Toast.makeText(this, "Error1 : $it", Toast.LENGTH_LONG).show()
}
} else {
auth.startActivityForSignInWithProvider(this, provider.build())
.addOnSuccessListener(
OnSuccessListener {
// User is signed in.
// retrieve the current user
firebaseUser = auth.currentUser!!
val user: Map =
// contains additional user information as
// a result of a successful sign-in
it.additionalUserInfo!!.profile as Map //
// navigate to HomePageActivity after successful login
val intent = Intent(this, HomePageActivity::class.java)
// send github user name from MainActivity to HomePageActivity
intent.putExtra("githubUserName", firebaseUser.displayName)
intent.putExtra("twitterHandle", user["twitter_username"].toString())
intent.putExtra("githubBio", user["bio"].toString())
intent.putExtra("linkedInLink", user["blog"].toString())
intent.putExtra("id", user["login"].toString())
intent.putExtra("follower", user["followers"].toString())
intent.putExtra("following", user["following"].toString())
intent.putExtra("publicRepos", user["public_repos"].toString())
intent.putExtra("location", user["location"].toString())
intent.putExtra("profilePic", user["avatar_url"].toString())
this.startActivity(intent)
Toast.makeText(this, "Login Successfully", Toast.LENGTH_LONG).show()
})
.addOnFailureListener(
OnFailureListener {
// Handle failure.
Toast.makeText(this, "Error2 : $it", Toast.LENGTH_LONG).show()
})
}
}
}
XML
Kotlin
package com.anju.kumari.usergithubauth
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.bumptech.glide.Glide
class HomePageActivity : AppCompatActivity() {
// declare variables to contain
// user's sent information
// initialize them too
private var userName = ""
private var twitterHandle = " "
private var bio = " "
private var linkedIn = " "
private var githubId = " "
private var follower = " "
private var following = " "
private var repos = " "
private var picUrl = " "
private lateinit var githubUserName: TextView
private lateinit var logoutBtn: Button
private lateinit var handle: TextView
private lateinit var githubBio: TextView
private lateinit var linkedInLink: TextView
private lateinit var userId: TextView
private lateinit var totalFollower: TextView
private lateinit var totalFollowing: TextView
private lateinit var totalRepos: TextView
private lateinit var userPic: ImageView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home_page)
githubUserName = findViewById(R.id.id)
logoutBtn = findViewById(R.id.logOut)
handle = findViewById(R.id.twitterUserName)
githubBio = findViewById(R.id.bio)
linkedInLink = findViewById(R.id.linkedInLink)
userId = findViewById(R.id.githubId)
totalFollower = findViewById(R.id.follower)
totalFollowing = findViewById(R.id.following)
totalRepos = findViewById(R.id.repos)
userPic = findViewById(R.id.profilePic)
// catching all data sent from MainActivity using Intent
userName = intent.getStringExtra("githubUserName")!!
twitterHandle = intent.getStringExtra("twitterHandle")!!
bio = intent.getStringExtra("githubBio")!!
linkedIn = intent.getStringExtra("linkedInLink")!!
githubId = intent.getStringExtra("id")!!
follower = intent.getStringExtra("follower")!!
following = intent.getStringExtra("following")!!
repos = intent.getStringExtra("publicRepos")!!
picUrl = intent.getStringExtra("profilePic")!!
// set all information to the widgets
// to display them on the screen
githubUserName.text = userName
handle.text = twitterHandle
githubBio.text = bio
linkedInLink.text = linkedIn
userId.text = githubId
totalFollower.text = follower
totalFollowing.text = following
totalRepos.text = repos
// use glide to download the user's
// pic using url of the image
Glide.with(this)
.load(picUrl)
.into(userPic)
// logout button to signOut from the app
logoutBtn.setOnClickListener {
val intent = Intent(this, MainActivity::class.java)
this.startActivity(intent)
}
}
}
第 3 步:创建一个新的空活动
参考这篇文章如何在 Android Studio 中创建新的 Activity 并创建一个新的 Activity。将活动命名为HomePageActivity。导航到app > res > layout > activity_home_page.xml并将以下代码添加到该文件中。下面是activity_home_page.xml文件的代码。
XML
转到HomePageActivity.kt文件并参考以下代码。下面是HomePageActivity.kt文件的代码。代码中添加了注释以更详细地理解代码。
科特林
package com.anju.kumari.usergithubauth
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.bumptech.glide.Glide
class HomePageActivity : AppCompatActivity() {
// declare variables to contain
// user's sent information
// initialize them too
private var userName = ""
private var twitterHandle = " "
private var bio = " "
private var linkedIn = " "
private var githubId = " "
private var follower = " "
private var following = " "
private var repos = " "
private var picUrl = " "
private lateinit var githubUserName: TextView
private lateinit var logoutBtn: Button
private lateinit var handle: TextView
private lateinit var githubBio: TextView
private lateinit var linkedInLink: TextView
private lateinit var userId: TextView
private lateinit var totalFollower: TextView
private lateinit var totalFollowing: TextView
private lateinit var totalRepos: TextView
private lateinit var userPic: ImageView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home_page)
githubUserName = findViewById(R.id.id)
logoutBtn = findViewById(R.id.logOut)
handle = findViewById(R.id.twitterUserName)
githubBio = findViewById(R.id.bio)
linkedInLink = findViewById(R.id.linkedInLink)
userId = findViewById(R.id.githubId)
totalFollower = findViewById(R.id.follower)
totalFollowing = findViewById(R.id.following)
totalRepos = findViewById(R.id.repos)
userPic = findViewById(R.id.profilePic)
// catching all data sent from MainActivity using Intent
userName = intent.getStringExtra("githubUserName")!!
twitterHandle = intent.getStringExtra("twitterHandle")!!
bio = intent.getStringExtra("githubBio")!!
linkedIn = intent.getStringExtra("linkedInLink")!!
githubId = intent.getStringExtra("id")!!
follower = intent.getStringExtra("follower")!!
following = intent.getStringExtra("following")!!
repos = intent.getStringExtra("publicRepos")!!
picUrl = intent.getStringExtra("profilePic")!!
// set all information to the widgets
// to display them on the screen
githubUserName.text = userName
handle.text = twitterHandle
githubBio.text = bio
linkedInLink.text = linkedIn
userId.text = githubId
totalFollower.text = follower
totalFollowing.text = following
totalRepos.text = repos
// use glide to download the user's
// pic using url of the image
Glide.with(this)
.load(picUrl)
.into(userPic)
// logout button to signOut from the app
logoutBtn.setOnClickListener {
val intent = Intent(this, MainActivity::class.java)
this.startActivity(intent)
}
}
}
注意:确保添加使用 Glide 加载用户图片的依赖项。
dependencies{
. . .
implementation ‘com.github.bumptech.glide:glide:4.11.0’
annotationProcessor ‘com.github.bumptech.glide:compiler:4.11.0’
. . .
}
这是输出。
输出:
GitHub 上的源代码: https://github.com/Anju1415/Github-Auth