我遵循了documentation,并尝试将代码用于Firebase的Google SignIn。 我已经在Firebase上正确添加了SHA-1指纹,并且还为Android和基于Google Cloud Platform的Web创建了两个OAuth 2.0客户端ID。但是,它仍然无法登录Google。当前有两个活动-1. MainActivity和2. Profile。以下是代码:
build.gradle
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
allprojects {
repositories {
google()
mavenCentral()
maven {
url "https://repository-achartengine.forge.cloudbees.com/snapshot/"
}
}
}
android {
compileSdkVersion 30
buildToolsVersion "30.0.2"
defaultConfig {
applicationId "com.example.grocery"
minSdkVersion 16
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.1'
implementation 'com.google.firebase:firebase-auth:16.0.5'
implementation 'com.google.android.gms:play-services-auth:18.1.0'
implementation 'com.google.android.material:material:1.2.1'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}
activity_main.xml
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.google.android.gms.common.SignInButton
android:id="@+id/google_signIn"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_alignParentTop="true"
android:layout_margin="10dp"
android:padding="10dp"
android:text="Text"
android:textSize="18sp"
tools:layout_editor_absoluteX="3dp"
tools:layout_editor_absoluteY="286dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
package com.example.grocery;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.snackbar.Snackbar;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
public class MainActivity extends AppCompatActivity {
private GoogleSignInClient mGoogleSignInClient;
private final static int RC_SIGN_IN = 123;
private FirebaseAuth mAuth;
@Override
protected void onStart() {
super.onStart();
FirebaseUser user = mAuth.getCurrentUser();
if(user != null) {
startActivity(new Intent(getApplicationContext(), Profile.class));
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
createRequest();
findViewById(R.id.google_signIn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
signIn();
}
});
}
private void createRequest() {
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = task.getResult(ApiException.class);
firebaseAuthWithGoogle(account.getIdToken());
} catch (ApiException e) {
// Google Sign In failed, update UI appropriately
Toast.makeText(this, "Sign In Failed!", Toast.LENGTH_SHORT).show();
}
}
}
private void firebaseAuthWithGoogle(String idToken) {
AuthCredential credential = GoogleAuthProvider.getCredential(idToken, 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
FirebaseUser user = mAuth.getCurrentUser();
startActivity(new Intent(getApplicationContext(), Profile.class));
} else {
// If sign in fails, display a message to the user.
Toast.makeText(MainActivity.this, "Authentication Failed!", Toast.LENGTH_SHORT).show();
}
// ...
}
});
}
}
activity_profile.xml
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Profile">
<Button
android:id="@+id/logout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Logout"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
tools:layout_editor_absoluteX="43dp"
tools:layout_editor_absoluteY="74dp" />
<TextView
android:id="@+id/mail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
tools:layout_editor_absoluteX="47dp"
tools:layout_editor_absoluteY="131dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
Profile.java
package com.example.grocery;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.firebase.auth.FirebaseAuth;
public class Profile extends AppCompatActivity {
TextView name, mail;
Button logout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
logout = findViewById(R.id.logout);
name = findViewById(R.id.name);
mail = findViewById(R.id.mail);
GoogleSignInAccount signInAccount = GoogleSignIn.getLastSignedInAccount(this);
if (signInAccount != null) {
name.setText(signInAccount.getDisplayName());
mail.setText(signInAccount.getEmail());
}
logout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
});
}
}
该构建可以正确运行,但是无法在模拟器上通过Google进行身份验证。我已经在Firebase(以及电子邮件)上启用了Google登录。请帮忙,我也查看了StackOverflow和Google上的其他解决方案,但找不到。