谷歌signin api不工作android工作室使用firebase



我试图使用firebase从谷歌登录,但它不起作用,GoogleSignInResult结果没有给出任何错误。请检查代码并告诉我我的代码发生了什么。

package com.tube.ui;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
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;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.InstanceIdResult;
import com.tube.R;
public class SignInActivity extends AppCompatActivity {
private GoogleApiClient mGoogleApiClient;
private SignInButton mGoogleBtn;
private static final int RC_SIGN_IN = 2;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private static final String TAG = "SignInActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
mGoogleBtn = findViewById(R.id.sign_in_button);
mGoogleBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
signIn();
}
});
mAuth = FirebaseAuth.getInstance(); //HMM...
mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() != null) {
startActivity(new Intent(SignInActivity.this, MainActivity.class)); //Switch activities
}
}
};

// Configure Google Sign In
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestProfile()
.requestEmail()
.build();
// Build a GoogleSignInClient with the options specified by gso.
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, new GoogleApiClient.OnConnectionFailedListener() {
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Toast.makeText(SignInActivity.this,"Something went wrong",Toast.LENGTH_SHORT).show();
}
})
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
}
@Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
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) {
Toast.makeText(SignInActivity.this,"It's working here...",Toast.LENGTH_SHORT).show();
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = result.getSignInAccount();
firebaseAuthWithGoogle(account);
Toast.makeText(SignInActivity.this,"Sign In Successful...",Toast.LENGTH_SHORT).show();
fetchToken();
}
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
Auth.GoogleSignInApi.signOut(mGoogleApiClient);
}
else {
Toast.makeText(SignInActivity.this,"Auth went wrong",Toast.LENGTH_SHORT).show();
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount account) {
AuthCredential credential = GoogleAuthProvider.getCredential(account.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();
//updateUI(user);
} else {
// If sign in fails, display a message to the user.
Log.w("TAG", "signInWithCredential:failure", task.getException());
Toast.makeText(SignInActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
//updateUI(null);
}
// ...
}
});
}
/**
* Fetches firebase token for single device testing
*/
private void fetchToken(){
// Get token
FirebaseInstanceId.getInstance().getInstanceId()
.addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
@Override
public void onComplete(@NonNull Task<InstanceIdResult> task) {
if (!task.isSuccessful()) {
Log.w(TAG, "getInstanceId failed", task.getException());
return;
}
// Get new Instance ID token
String token = task.getResult().getToken();
// Log and toast
String msg = getString(R.string.msg_token_fmt, token);
Log.d(TAG, msg);
}
});
}
}

我已经启用了googleapi并尝试了所有方法,但无法发现错误,因为在安卓工作室中没有显示运行时的错误消息。

首先请确保您已在Firebase控制台中启用Google SignIn身份验证。(验证-->选项卡"登录方法"(然后检查您的"Web客户端ID"。这是否适合Android项目中"googleservices.json"中的设置?

我在我的项目中的build.gradle中使用"implementation'com.firebaseui:firebase-ui-auth:4.4.1'"来为firebase身份验证提供一个预先默认的ui。

以下代码适用于我实现登录mehtod:

private static final int RC_SIGN_IN = 123;
private FirebaseAuth auth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
auth = FirebaseAuth.getInstance()
if (auth.getCurrentUser() != null) {
Log.i(TAG, "-------------------------------------------");
Log.i(TAG, auth.getCurrentUser().toString());
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
IdpResponse response = IdpResponse.fromResultIntent(data);
if (resultCode == RESULT_OK) {
// Successfully signed in
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
Log.i(TAG, "logged in");
if (user != null) {
// Name, email address, and profile photo Url
String name = user.getDisplayName();
String email = user.getEmail();
Uri photoUrl = user.getPhotoUrl();
// The user's ID, unique to the Firebase project. Do NOT use this value to
// authenticate with your backend server, if you have one. Use
// FirebaseUser.getIdToken() instead.
String uid = user.getUid();
}

}
if (resultCode != RESULT_OK && shouldStartSignIn()) {
// Sign in failed. If response is null the user canceled the
// sign-in flow using the back button. Otherwise check
// response.getError().getErrorCode() and handle the error.
String err = Integer.toString(response.getError().getErrorCode());
Log.i(TAG, "no login");
Log.i(TAG, err);
startSignIn();
}
}
}
/**
* Check if a FirebaseUser is logged in
* @return
*/
private boolean shouldStartSignIn() {
return (!mainActivityViewModel.getIsSignedIn() && FirebaseAuth.getInstance().getCurrentUser() == null);
}
/**
* Show Login module with Firebase UI
*/
private void startSignIn() {
// Firebase Authentication Providers
List<AuthUI.IdpConfig> providers = Arrays.asList(
new AuthUI.IdpConfig.EmailBuilder().build(),
new AuthUI.IdpConfig.GoogleBuilder().build());
// Create and launch sign-in intent for Firebase Authentication
Intent intent = AuthUI.getInstance()
.createSignInIntentBuilder()
.setAvailableProviders(providers)
.setTheme(R.style.AppTheme_NoActionBar)
.setIsSmartLockEnabled(false)
.build();
startActivityForResult(intent, RC_SIGN_IN);
mainActivityViewModel.setIsSignedIn(true);
}

相关内容

  • 没有找到相关文章

最新更新