3 回答

TA貢獻1712條經驗 獲得超3個贊
我正在考慮您是否已經將 firebase 添加到您的項目中,如果沒有,請點擊此鏈接https://firebase.google.com/docs/auth/android/google-signin
然后,您必須通過從左側面板中選擇身份驗證在 Firebase 中啟用谷歌登錄,然后選擇登錄提供商選項卡并啟用谷歌登錄。
你的項目級構建腳本應該是這樣的
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.4.1'
classpath 'com.google.gms:google-services:4.2.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
應用程序級別的 build.gradle 文件應該具有這些依賴項
//firebasecore
implementation 'com.google.firebase:firebase-core:17.0.0'
//firebase auth
implementation 'com.google.firebase:firebase-auth:18.0.0'
//google auth
implementation 'com.google.android.gms:play-services-auth:17.0.0'
并且登錄應該有這樣的代碼
public class Login_Activity extends AppCompatActivity {
ImageView gLogin;
private static final int RC_SIGN_IN=1;
private FirebaseAuth mAuth;
GoogleSignInClient mGoogleSignInClient;
Firebase user;
@Override
protected void onStart() {
super.onStart();
user = mAuth.getCurrentUser();
if(user!=null)
{
startActivity(new Intent(Login_Activity.this,MainActivity.class));
Login_Activity.this.finish();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_);
gLogin=findViewById(R.id.gLogin);
// ...
// Initialize Firebase Auth
mAuth = FirebaseAuth.getInstance();
// Configure sign-in to request the user's ID, email address, and basic
// profile. ID and basic profile are included in DEFAULT_SIGN_IN.
GoogleSignInOptions gso = new
GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
// Build a GoogleSignInClient with the options specified by gso.
mGoogleSignInClient= GoogleSignIn.getClient(this, gso);
gLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
signIn();
}
});
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
Toast.makeText(this, "starting activity", Toast.LENGTH_SHORT).show();
}
@Override
public void onActivityResult(int requestCode, int resultCode,Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from
GoogleSignInClient.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
// The Task returned from this call is always completed, no need to
//attach
// a listener.
Task<GoogleSignInAccount> task =
GoogleSignIn.getSignedInAccountFromIntent(data);
Toast.makeText(this, "inside on Activity result",
Toast.LENGTH_SHORT).show();
try {
Toast.makeText(this, "authenticating", Toast.LENGTH_SHORT).show();
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = task.getResult(ApiException.class);
firebaseAuthWithGoogle(account);
} catch (ApiException e) {
// Google Sign In failed, update UI appropriately
Log.w("firebase exception", "Google sign in failed", e);
// ...
}
//handleSignInResult(task);
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
Log.d("authenticate", "firebaseAuthWithGoogle:" + acct.getId());
AuthCredential credential =
GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>()
{
@Override
public void onComplete(@NonNull Task<AuthResult> task)
{
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d("message","signInWithCredential:success");
user = mAuth.getCurrentUser();
Log.d("user id", user.getUid());
startActivity(new
Intent(Login_Activity.this,MainActivity.class));
Login_Activity.this.finish();
} else {
// If sign in fails, display a message to the user.
Log.w("message","signInWithCredential:failure", task.getException());
}
}
});
}
您需要使用 google 登錄選項請求 ID 令牌,您可以使用此代碼,它將使用 google 登錄記錄您,并在 firebase 身份驗證用戶數(shù)據(jù)庫中登錄。
對于數(shù)據(jù)庫,您應該檢查一次數(shù)據(jù)庫規(guī)則的讀寫權限,它應該可以工作

TA貢獻1878條經驗 獲得超4個贊
在收到來自 Google Signin 的結果后,您沒有調用 firebase signin。
在你的內部handleSignInResult你有谷歌登錄的結果,你只需要創(chuàng)建 GoogleAuth 憑據(jù)并將其用于signInwithCredentials.
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
FirebaseUser user = mAuth.getCurrentUser();
saveUpdateUserProfile(user);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Snackbar.make(findViewById(R.id.main_layout), "Authentication Failed.", Snackbar.LENGTH_SHORT).show();
}
}
});
這將創(chuàng)建/登錄 firebase 用戶,然后您可以檢查數(shù)據(jù)庫以查看用于登錄的 google 帳戶是否是用于保存用戶信息的新帳戶。
PS 你也可以優(yōu)化你的數(shù)據(jù)庫查詢。您當前的查詢將從數(shù)據(jù)庫中獲取所有用戶。此外,您不應將電子郵件地址用作數(shù)據(jù)庫中的鍵。
更高效的數(shù)據(jù)庫結構可以使用 firebase 用戶 ID 作為鍵:
users: {
firebaaseUID1: {},
firebaaseUID2: {},
.
.
}
你SaveToDataBase現(xiàn)在可以:
void SaveToDataBase(FirebaseUser 用戶,布爾值 isGoogleSignIn){
database.getReference().child("Users").child(user.getUid())
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
// firebase user data is present in db, do appropiate action or take user to home screen
}
else {
LoadingBar.setMessage("Please wait while we load the credentialls in");
LoadingBar.setTitle("Register");
LoadingBar.setCanceledOnTouchOutside(false);
LoadingBar.show();
HashMap<String, Object> Userdatamap = new HashMap<>();
Userdatamap.put("Email", user.getEmail());
// Userdatamap
// .put("phoneNumber", "Google intigrated sign in does not allow phone number requesting... This will be fixed in later patches");
Userdatamap.put("Name", user.getDisplayName());
if (isGoogleSignIn)
Userdatamap.put("Created with", "Intigrated Google sign in");
database
.child("Users")
.child(user.getUid())
.updateChildren(Userdatamap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
LoadingBar.dismiss();
Toast.makeText(LoginOrSignupActivity.this, "Database save successful", Toast.LENGTH_SHORT).show();
Log.e("SignUpError :", task
.getException()
.getMessage());
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(LoginOrSignupActivity.this, "Registration failed", Toast.LENGTH_SHORT).show();
Log.e(Tag, "error: ");
}
});
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {}
});
}
}
添加回答
舉報