结合Facebook和谷歌AUTH的火力地堡的Android
背景结合Facebook和谷歌AUTH的火力地堡的Android
你好,我是新与火力地堡Android和我试图实现首次Facebook和谷歌认证/注册。我遵循了相应的认证这两个教程:
- 的http:// firebase.google.com/docs/auth/android/google-signin
- 的http:// firebase.google.com/docs/ auth/android/facebook-login
另外,FacebookSignInActivity
和GoogleSignInActivity
正在运行。
问题
的问题是,我想使用谷歌和Facebook AUTH在同一个活动,但它不会工作。像这样:
我做什么
我试图让他们延长MainActivity
,并在那里设置布局,以保持从GoogleSignInActivity
的FacebookSignInActivity
分开。
但我想我应该将两者合并为一。所以,我想,但我发现了一个奇怪的空指针异常:
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.firebase.auth.FirebaseAuth.addAuthStateListener(com.google.firebase.auth.FirebaseAuth$AuthStateListener)' on a null object reference
我不知道为什么对象是在onCreate
空,因为我已经从这些工作的另外两个活动复制相同的代码:
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
// [START_EXCLUDE]
updateUI(user);
// [END_EXCLUDE]
}
};
我甚至不确定我是否应该将两者合并为一项活动。我还检查了这些链接:
- https://firebase.google.com/docs/auth/android/account-linking
- How to Link Multiple Auth Providers to an Firebase Account?
但它看起来就像是我想要做别的东西。如果有人能帮助我指出正确的方向,我将很高兴地感激。
你可以试试这个代码:
public class LoginActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener,
View.OnClickListener {
private static final String TAG = "SignInActivity";
private static final int RC_SIGN_IN = 9001;
private GoogleApiClient mGoogleApiClient;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private CallbackManager mCallbackManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// Facebook Login
FacebookSdk.sdkInitialize(getApplicationContext());
mCallbackManager = CallbackManager.Factory.create();
LoginButton mFacebookSignInButton = (LoginButton) findViewById(R.id.facebook_button);
mFacebookSignInButton.setReadPermissions("email", "public_profile", "user_birthday", "user_friends");
mFacebookSignInButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
Log.d(TAG, "facebook:onSuccess:" + loginResult);
firebaseAuthWithFacebook(loginResult.getAccessToken());
}
@Override
public void onCancel() {
Log.d(TAG, "facebook:onCancel");
}
@Override
public void onError(FacebookException error) {
Log.d(TAG, "facebook:onError", error);
}
});
// Google Sign-In
// Assign fields
Button mGoogleSignInButton = (Button) findViewById(R.id.google_button);
// Set click listeners
mGoogleSignInButton.setOnClickListener(this);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
// Initialize FirebaseAuth
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
}
};
}
@Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
@Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
Log.d(TAG, "firebaseAuthWithGooogle:" + 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) {
Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Log.w(TAG, "signInWithCredential", task.getException());
Toast.makeText(LoginActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
} else {
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}
}
});
}
private void firebaseAuthWithFacebook(AccessToken token) {
Log.d(TAG, "handleFacebookAccessToken:" + token);
final AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Log.w(TAG, "signInWithCredential", task.getException());
Toast.makeText(LoginActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
} else {
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}
}
});
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.google_button:
signIn();
break;
default:
return;
}
}
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);
mCallbackManager.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 {
// Google Sign In failed
Log.e(TAG, "Google Sign In failed.");
}
}
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
// An unresolvable error has occurred and Google APIs (including Sign-In) will not
// be available.
Log.d(TAG, "onConnectionFailed:" + connectionResult);
Toast.makeText(this, "Google Play Services error.", Toast.LENGTH_SHORT).show();
}
}
请让我知道如果您有任何问题。
也许任何人仍在寻找解决方案:
在Activity(yourLoginActivity。类)
*创建一个恒定的int表示ActivityForResult
的requestCode// You can change to any Value just be unique
private static final int RC_SIGN_IN = 1001;
- >声明GoogleApiClient,FirebaseAuth,AuthStateListener和CallbackManager
private static final String TAG = "LoginActivity";
private static final int RC_SIGN_IN = 1001;
private GoogleApiClient mGoogleApiClient;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private CallbackManager mCallbackManager;
- >初始化上述所声明的变量:
mCallbackManager = CallbackManager.Factory.create(); mAuth = FirebaseAuth.getInstance(); mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
} };
- >请参考Si ngInButton和LoginButton:
LoginButton facebookLoginButton = findViewById(R.id.login_facebook_button);
SignInButton mGoogleSignInButton = findViewById(R.id.sign_in_button);
- >处理的SingInButton和LoginButton:
facebookLoginButton.setReadPermissions("email", "public_profile", "user_birthday");
facebookLoginButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
firebaseAuthWithFacebook(loginResult.getAccessToken());
}
@Override
public void onCancel() {
Toast.makeText(LoginActivity.this, "Succes", Toast.LENGTH_SHORT).show();
}
@Override
public void onError(FacebookException error) {
Toast.makeText(LoginActivity.this, "Succes", Toast.LENGTH_SHORT).show();
}
});
mGoogleSignInButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
signIn();
}
});
- >管理GoogleSingInOptions和GoogleApiClient
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
- >处理Facebook的登录
private void authWithFacebook(AccessToken token) {
Log.d(TAG, "handleFacebookAccessToken:" + token);
final AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
if (mAuth.getCurrentUser() != null) {
mAuth.getCurrentUser().linkWithCredential(credential)
.addOnSuccessListener(new OnSuccessListener<AuthResult>() {
@Override
public void onSuccess(AuthResult authResult) {
Toast.makeText(LoginActivity.this, "Logged IN", Toast.LENGTH_LONG).show();
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
e.printStackTrace();
Log.e(TAG, "onFailure: " + e.getMessage());
mAuth.signInWithCredential(credential).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
@Override
public void onSuccess(AuthResult authResult) {
Toast.makeText(LoginActivity.this, "Logged IN", Toast.LENGTH_LONG).show();
}
});
}
});
} else {
mAuth.signInWithCredential(credential);
}
}
- >处理的谷歌登录:
pprivate void authWithGoogle(final GoogleSignInAccount acct) {
Log.d(TAG, "firebaseAuthWithGooogle:" + acct.getId());
final AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
if (mAuth.getCurrentUser() != null) {
mAuth.getCurrentUser().linkWithCredential(credential).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
@Override
public void onSuccess(AuthResult authResult) {
Toast.makeText(LoginActivity.this, "Logged IN", Toast.LENGTH_LONG).show();
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
e.printStackTrace();
Log.e(TAG, "onFailure: " + e.getMessage());
mAuth.signInWithCredential(credential).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
@Override
public void onSuccess(AuthResult authResult) {
Toast.makeText(LoginActivity.this, "Logged IN", Toast.LENGTH_LONG).show();
}
});
}
});
}else{
mAuth.signInWithCredential(credential);
}
}
- >重写onConnectionFailed():
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
// An unresolvable error has occurred and Google APIs (including Sign-In) will not
// be available.
Log.d(TAG, "onConnectionFailed:" + connectionResult);
Toast.makeText(this, "Google Play Services error.", Toast.LENGTH_SHORT).show();
}
- >歌唱和调用onActivityForResult()
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
- >实施GoogleApiClient.OnConnectionFailedListener
LoginActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener{
....
}
请确保你有ENABLED FACEBOOK SDK从FIREBASE控制台登录并正确设置!
您发布的代码不是抛出异常的代码。当您调用'mAuth.addAuthStateListener(mAuthListener)'和'mAuth'为空时会发生异常。在尝试添加侦听器之前,请确认您已经执行了'mAuth = FirebaseAuth.getInstance()'。 –
就像在firebase教程中,你所指的那一行:'mAuth = FirebaseAuth.getInstance()'在我的代码片段中。它在onCreate中被调用。在onStart中调用'mAuth.addAuthStateListener(mAuthListener);'。 – Tim