2017-09-05 96 views
0

我正在使用此代碼來使用Firebase的sigin。Firebase Google Sigin身份驗證失敗

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) { 
     GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data); 
     if (result.isSuccess()) { 
      // Google Sign In was successful, authenticate with Firebase 
      GoogleSignInAccount account = result.getSignInAccount(); 
      firebaseAuthWithGoogle(account); 
     } else { 
      Toast.makeText(SignIn.this, "Authentication 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(SignIn.this, "Authentication failed.", 
           Toast.LENGTH_SHORT).show(); 
         //updateUI(null); 
        } 

        // ... 
       } 
      }); 

} 

} 但是,當我試圖簽署in.Like驗證失敗,它給錯誤。 我在哪裏做錯了?

我已經包括既爲firebaseAuth的依賴關係裏面我的應用搖籃 compile 'com.google.firebase:firebase-auth:11.0.2' compile 'com.google.android.gms:play-services-auth:11.0.2' 而且也使谷歌在我的火力地堡控制檯登入方法。

在我的logout.class我使用此代碼`button =(Button)findViewById(R.id.logout); mAuth = FirebaseAuth.getInstance();

mAuthlistener = new FirebaseAuth.AuthStateListener() { 
     @Override 
     public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { 
      if (firebaseAuth.getCurrentUser() == null) { 
       startActivity(new Intent(logout.this, SignIn.class)); 
      } 
     } 
    }; 

    button.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      mAuth.signOut(); 
     } 
    }); 
}` 

但是當我點擊那麼這將打開Sigin.class但是當我們再次嘗試SIGIN崩潰。

回答

1

確保您使用添加SHA1證書到您的火力地堡的項目,同時在與火力地堡火力地堡控制檯項目,並嘗試使用我下面的代碼

<?xml version="1.0" encoding="utf-8"?> 
<android.support.constraint.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" 
    android:background="@color/back" 

    tools:context="com.food.sheenishere.stark.MainActivity"> 


    <com.google.android.gms.common.SignInButton 
     android:id="@+id/googlebtn" 
     android:layout_width="286dp" 
     android:layout_height="49dp" 
     android:layout_marginEnd="24dp" 
     android:layout_marginLeft="24dp" 
     android:layout_marginRight="24dp" 
     android:layout_marginStart="24dp" 
     android:layout_marginTop="270dp" 

     app:layout_constraintHorizontal_bias="0.502" 
     app:layout_constraintLeft_toLeftOf="parent" 
     app:layout_constraintRight_toRightOf="parent" 


     app:layout_constraintTop_toTopOf="parent"> 


    </com.google.android.gms.common.SignInButton> 

</android.support.constraint.ConstraintLayout> 


package com.food.sheenishere.stark; 

import android.app.ActionBar; 
import android.app.ProgressDialog; 
import android.content.Intent; 
import android.graphics.Color; 
import android.graphics.drawable.ColorDrawable; 
import android.support.annotation.NonNull; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.MenuItem; 
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; 

public class MainActivity extends AppCompatActivity { 
private SignInButton mGoogleBtn; 

    private static final int RC_SIGN_IN=1; 

    private GoogleApiClient mGoogleApiClient; 
    private FirebaseAuth mAuth; 
    private static final String TAG="MAINACTIVITY"; 
    private FirebaseAuth.AuthStateListener mAuthListener; 
    // A progress dialog to display when the user is connecting in 
    // case there is a delay in any of the dialogs being ready. 
    private ProgressDialog mConnectionProgressDialog; 



    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 




     mAuth=FirebaseAuth.getInstance(); 
     mAuthListener=new FirebaseAuth.AuthStateListener() { 
      @Override 
      public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { 
       if (firebaseAuth.getCurrentUser() !=null){ 
        startActivity(new Intent(MainActivity.this,profilemain.class)); 
       } 
      } 
     }; 
     mGoogleBtn=(SignInButton) findViewById(R.id.googlebtn); 

     // Configure the ProgressDialog that will be shown if there is a 
     // delay in presenting the user with the next sign in step. 
     mConnectionProgressDialog = new ProgressDialog(this,R.style.MyAlertDialogStyle); 
     mConnectionProgressDialog.setMessage("Signing in..."); 
     // Configure Google Sign In 
     GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) 
       .requestIdToken(getString(R.string.default_web_client_id)) 
       .requestEmail() 
       .build(); 

mGoogleApiClient=new GoogleApiClient.Builder(getApplicationContext()) 
     .enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() { 
      @Override 
      public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { 
       Toast.makeText(MainActivity.this,"you got an error", Toast.LENGTH_SHORT).show(); 
      } 
     }) 
     .addApi(Auth.GOOGLE_SIGN_IN_API,gso) 
     .build(); 

     mGoogleBtn.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       signIn(); 
      } 
     }); 
    } 

    @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) { 
      GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data); 
      mConnectionProgressDialog.setMessage("Signing in..."); 
      mConnectionProgressDialog.show(); 
      if (result.isSuccess()) { 
       // Google Sign In was successful, authenticate with Firebase 
       GoogleSignInAccount account = result.getSignInAccount(); 
       firebaseAuthWithGoogle(account); 
      } else { 
       // Google Sign In failed, update UI appropriately 

       Toast.makeText(MainActivity.this, "Something went wrong.", 
         Toast.LENGTH_SHORT).show(); 
       mConnectionProgressDialog.dismiss(); 
       // ... 
      } 
     } 
    } 

    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(); 
          mConnectionProgressDialog.dismiss(); 
          // updateUI(user); 
         } else { 
          // If sign in fails, display a message to the user. 
          Log.w(TAG, "signInWithCredential:failure", task.getException()); 
          Toast.makeText(MainActivity.this, "Authentication failed.", 
            Toast.LENGTH_SHORT).show(); 
          // updateUI(null); 
         } 

         // ... 
        } 
       }); 
    } 
} 

不要讓我知道它是否有效與否。

+0

好吧,我會讓你知道 – DimKUsik

+0

工作當我連接Firebase到Android Studio從工具選項,btw感謝您的幫助。 :) – DimKUsik

+0

我還有一件事是面對註銷按鈕的問題當用戶你可以你建議我一種方法。我在上面添加了我的註銷代碼。請檢查 – DimKUsik

0

對於LOgOUt 您必須按照我在項目中完成的BottomNavigation佈局。下面是xml代碼。

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout 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:id="@+id/container" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" 
    tools:context="com.food.sheenishere.stark.profilemain"> 



    <android.support.design.widget.BottomNavigationView 
     android:id="@+id/navigation" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_gravity="bottom" 
     android:background="?android:attr/windowBackground" 
     app:menu="@menu/navigation" /> 

</LinearLayout> 

這裏是Java代碼。

package com.food.sheenishere.stark; 


import android.app.ProgressDialog; 

import android.content.Intent; 

import android.os.Bundle; 
import android.support.annotation.NonNull; 
import android.support.design.widget.BottomNavigationView; 
import android.support.v7.app.AppCompatActivity; 

import android.view.MenuItem; 


import android.view.View; 
import android.widget.AdapterView; 
import android.widget.ArrayAdapter; 

import android.widget.ListView; 

import android.widget.Toast; 

import com.firebase.client.Firebase; 

import com.google.firebase.auth.FirebaseAuth; 
import com.google.firebase.database.ChildEventListener; 
import com.google.firebase.database.DataSnapshot; 
import com.google.firebase.database.DatabaseError; 
import com.google.firebase.database.DatabaseReference; 
import com.google.firebase.database.FirebaseDatabase; 

import java.util.ArrayList; 

public class profilemain extends AppCompatActivity { 
    private FirebaseAuth mAuth; 
    private FirebaseAuth.AuthStateListener mAuthListener; 





    private BottomNavigationView.OnNavigationItemSelectedListener 
      mOnNavigationItemSelectedListener 
      = new BottomNavigationView.OnNavigationItemSelectedListener() { 

     @Override 
     public boolean onNavigationItemSelected(@NonNull MenuItem item) { 
      switch (item.getItemId()) { 
       case R.id.navigation_home: 

        Toast.makeText(profilemain.this, "hi hello", Toast.LENGTH_SHORT).show(); 
        return true; 
       case R.id.navigation_dashboard: 
        Toast.makeText(profilemain.this, "hi hello", Toast.LENGTH_SHORT).show(); 
        return true; 
       case R.id.navigation_notifications: 
        Toast.makeText(profilemain.this, "hi hello", Toast.LENGTH_SHORT).show(); 
        return true; 
       case R.id.navigation_signout: 

        Toast.makeText(profilemain.this, "You have successfully Signed out", Toast.LENGTH_SHORT).show(); 
        mAuth.signOut(); 
        return true; 
      } 
      return false; 
     } 

    }; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_profilemain); 





     BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation); 
     navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener); 
     mAuth = FirebaseAuth.getInstance(); 


     mAuthListener = new FirebaseAuth.AuthStateListener() { 
      @Override 
      public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { 
       if (firebaseAuth.getCurrentUser() == null) { 
        startActivity(new 
          Intent(profilemain.this, MainActivity.class)); 

       } 
      } 
     }; 


    } 

    @Override 
    protected void onStart() { 
     super.onStart(); 

     mAuth.addAuthStateListener(mAuthListener); 
    } 
}