结合Facebook和Google Auth for Firebase Android [英] Combining Facebook and Google auth for Firebase Android
问题描述
背景
您好,我是Android Firebase的新手,并且我正在尝试首次实现Facebook和Google身份验证/登录.我按照以下两个教程进行了相应的身份验证:
- http://firebase.google.com/docs/auth/android/google-signin
- http://firebase.google.com/docs/auth/android/facebook-login
FacebookSignInActivity
和 GoogleSignInActivity
分别可以正常工作.
问题
问题是我试图在同一活动中使用Google和Facebook身份验证,但无法正常工作.像这样:
我做什么
我试图通过允许他们扩展 MainActivity
并在其中设置布局,来使 FacebookSignInActivity
与 GoogleSignInActivity
分开.>
但是我认为我应该将两者合并为一个.所以我尝试了一下,但是出现了一个奇怪的nullpointer异常:
java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'void com.google.firebase.auth.FirebaseAuth.addAuthStateListener(com.google.firebase.auth.FirebaseAuth $ AuthStateListener)'
我不知道为什么 onCreate
中的对象为null,因为我已经从其他两个有效的活动中复制了相同的代码:
mAuth = FirebaseAuth.getInstance();mAuthListener = new FirebaseAuth.AuthStateListener(){@Override公共无效onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth){FirebaseUser用户= firebaseAuth.getCurrentUser();如果(用户!= null){//用户已登录Log.d(TAG,"onAuthStateChanged:signed_in:" + user.getUid());} 别的 {//用户已注销Log.d(TAG,"onAuthStateChanged:signed_out");}//[START_EXCLUDE]updateUI(用户);//[END_EXCLUDE]}};
我什至不确定我是否应该将两者合并为一项活动.我还检查了以下链接:
但是,这似乎与我正在尝试做的事情不同.如果有人可以帮助我指出正确的方向,将不胜感激.
您可以尝试以下代码:
公共类LoginActivity扩展了AppCompatActivity,它实现了GoogleApiClient.OnConnectionFailedListener,View.OnClickListener {私有静态最终String TAG ="SignInActivity";私有静态最终int RC_SIGN_IN = 9001;私有GoogleApiClient mGoogleApiClient;私有FirebaseAuth mAuth;私有FirebaseAuth.AuthStateListener mAuthListener;私人CallbackManager mCallbackManager;@Override受保护的void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_login);//Facebook登入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公共无效onSuccess(LoginResult loginResult){Log.d(TAG,"facebook:onSuccess:" + loginResult);firebaseAuthWithFacebook(loginResult.getAccessToken());}@Override公共无效onCancel(){Log.d(TAG,"facebook:onCancel");}@Override公共无效onError(FacebookException错误){Log.d(TAG,"facebook:onError",错误);}});//Google登录//分配字段按钮mGoogleSignInButton =(按钮)findViewById(R.id.google_button);//设置点击监听器mGoogleSignInButton.setOnClickListener(this);GoogleSignInOptions gso =新的GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestIdToken(getString(R.string.default_web_client_id)).requestEmail().建造();mGoogleApiClient =新的GoogleApiClient.Builder(this).enableAutoManage(此/* FragmentActivity */,此/* OnConnectionFailedListener */).addApi(Auth.GOOGLE_SIGN_IN_API,gso).建造();//初始化FirebaseAuthmAuth = FirebaseAuth.getInstance();mAuthListener = new FirebaseAuth.AuthStateListener(){@Override公共无效onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth){FirebaseUser用户= firebaseAuth.getCurrentUser();如果(用户!= null){//用户已登录Log.d(TAG,"onAuthStateChanged:signed_in:" + user.getUid());} 别的 {//用户已注销Log.d(TAG,"onAuthStateChanged:signed_out");}}};}@Override公共无效onStart(){super.onStart();mAuth.addAuthStateListener(mAuthListener);}@Override公共无效onStop(){super.onStop();如果(mAuthListener!= null){mAuth.removeAuthStateListener(mAuthListener);}}私人无效firebaseAuthWithGoogle(GoogleSignInAccount acct){Log.d(TAG,"firebaseAuthWithGooogle:" + acct.getId());AuthCredential凭据= GoogleAuthProvider.getCredential(acct.getIdToken(),null);mAuth.signInWithCredential(凭证).addOnCompleteListener(this,new OnCompleteListener< AuthResult>(){@Overridepublic void onComplete(@NonNull Task< AuthResult>任务){Log.d(TAG,"signInWithCredential:onComplete:" + task.isSuccessful());//如果登录失败,则向用户显示一条消息.如果登录成功//将会通知auth状态监听器,并提供逻辑来处理//登录的用户可以在侦听器中处理.如果(!task.isSuccessful()){Log.w(TAG,"signInWithCredential",task.getException());Toast.makeText(LoginActivity.this,身份验证失败.",Toast.LENGTH_SHORT).show();} 别的 {startActivity(new Intent(LoginActivity.this,MainActivity.class));结束();}}});}私人无效firebaseAuthWithFacebook(AccessToken令牌){Log.d(TAG,"handleFacebookAccessToken:" +令牌);最终的AuthCredential凭据= FacebookAuthProvider.getCredential(token.getToken());mAuth.signInWithCredential(凭证).addOnCompleteListener(this,new OnCompleteListener< AuthResult>(){@Overridepublic void onComplete(@NonNull Task< AuthResult>任务){Log.d(TAG,"signInWithCredential:onComplete:" + task.isSuccessful());//如果登录失败,则向用户显示一条消息.如果登录成功//将会通知auth状态监听器,并提供逻辑来处理//登录的用户可以在侦听器中处理.如果(!task.isSuccessful()){Log.w(TAG,"signInWithCredential",task.getException());Toast.makeText(LoginActivity.this,身份验证失败.",Toast.LENGTH_SHORT).show();} 别的 {startActivity(new Intent(LoginActivity.this,MainActivity.class));结束();}}});}@Overridepublic void onClick(View v){开关(v.getId()){大小写R.id.google_button:登入();休息;默认:返回;}}私人无效signIn(){意图signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);startActivityForResult(signInIntent,RC_SIGN_IN);}@Overridepublic void onActivityResult(int requestCode,int resultCode,Intent data){super.onActivityResult(requestCode,resultCode,data);mCallbackManager.onActivityResult(requestCode,resultCode,data);//从GoogleSignInApi.getSignInIntent(...)启动Intent返回的结果;如果(requestCode == RC_SIGN_IN){GoogleSignInResult结果= Auth.GoogleSignInApi.getSignInResultFromIntent(data);如果(result.isSuccess()){//Google登录成功,并通过Firebase进行身份验证GoogleSignInAccount帐户= result.getSignInAccount();firebaseAuthWithGoogle(account);} 别的 {//Google登录失败Log.e(TAG,"Google登录失败.");}}}@Override公共无效onConnectionFailed(@NonNull ConnectionResult connectionResult){//发生无法解决的错误,Google API(包括登录)将不会//能得到的.Log.d(TAG,"onConnectionFailed:" + connectionResult);Toast.makeText(this,"Google Play Services错误.",Toast.LENGTH_SHORT).show();}}
如果您有任何疑问,请告诉我.
Background
Hello, I'm new with Firebase for Android and I'm trying to implement the Facebook and Google auth/login for the first time. I followed these two tutorials for the corresponding authentication:
- http:// firebase.google.com/docs/auth/android/google-signin
- http:// firebase.google.com/docs/auth/android/facebook-login
Separately, the FacebookSignInActivity
and GoogleSignInActivity
are working as they should.
Problem
The problem is that I'm trying to use the Google and Facebook auth in the same activity, but it won't work. Like so:
What I did
I tried to keep the FacebookSignInActivity
separate from the GoogleSignInActivity
by letting them extend a MainActivity
and set the layout in there.
But I think I'm supposed to merge the two into one. So I tried that but I'm getting a weird nullpointer exception:
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
I don't know why the object is null in the onCreate
because I've copied the same code from the other two activities which are working:
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]
}
};
I'm not even sure if I'm even supposed to merge the two into one activity. I've also checked these links:
- https://firebase.google.com/docs/auth/android/account-linking
- How to Link Multiple Auth Providers to an Firebase Account?
But it looks like that is something else from what I'm trying to do. If someone could help point me in the right direction, it would be gladly appreciated.
You can try this code:
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();
}
}
Please let me know if you have any questions.
这篇关于结合Facebook和Google Auth for Firebase Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!