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 身份验证用户数据库中登录。
对于数据库,您应该检查一次数据库规则的读写权限,它应该可以工作
TA贡献1878条经验 获得超4个赞
在收到来自 Google Signin 的结果后,您没有调用 firebase signin。
在你的内部handleSignInResult你有谷歌登录的结果,你只需要创建 GoogleAuth 凭据并将其用于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();
}
}
});
这将创建/登录 firebase 用户,然后您可以检查数据库以查看用于登录的 google 帐户是否是用于保存用户信息的新帐户。
PS 你也可以优化你的数据库查询。您当前的查询将从数据库中获取所有用户。此外,您不应将电子邮件地址用作数据库中的键。
更高效的数据库结构可以使用 firebase 用户 ID 作为键:
users: {
firebaaseUID1: {},
firebaaseUID2: {},
.
.
}
你SaveToDataBase现在可以:
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) {}
});
}
}
添加回答
举报