gpt4 book ai didi

Android Facebook 登录使用新的 Firebase : App gets redirected to the login screen even after allowing permission

转载 作者:搜寻专家 更新时间:2023-11-01 09:46:18 25 4
gpt4 key购买 nike

我正在尝试使用 firebase 实现 facebook 登录。我创建了一个新的 Facebook 应用程序并获取了 app id 和 app secret ,在 firebase 控制台中输入了 app id 和 app secret 并启用了 facebook 登录。

在 android studio 中,将应用程序 ID 保存在 strings.xml 中。之后添加了 facebook sdk 依赖。然后我在 AndroidManifest 文件和 LoginActivity.java 中编写了所需的代码。我在 activity_login.xml 中添加了一个按钮。

当我运行应用程序并单击“使用 Facebook 登录”按钮时,它会打开 Facebook View ,询问我是否允许访问电子邮件、个人资料等。在我单击接受后,应用程序重定向到登录屏幕没有任何反应。我真的很沮丧,请帮忙。提前致谢。

这是代码

AndroidManifest.xml

    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androidmate.anuj.trynew">

<uses-permission android:name="android.permission.INTERNET" />

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">

<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/fb_app_id"/>

<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".HomeActivity"
android:windowSoftInputMode="adjustPan"
/>
<activity android:name=".login.LoginActivity"></activity>
<activity android:name="com.facebook.FacebookActivity"
android:configChanges=
"keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:theme="@android:style/Theme.Translucent.NoTitleBar"
android:label="@string/app_name" />
</application>

</manifest>

登录 Activity .java

public class LoginActivity extends AppCompatActivity implements View.OnClickListener, GoogleApiClient.OnConnectionFailedListener {

SignInButton btLoginWhithGoogle;
Button btLoginWithFacebook;
FirebaseAuth mAuth;
FirebaseUser mUser;
CallbackManager callbackManager;

private static final int RC_SIGN_IN = 9000;
private GoogleApiClient mGoogleApiClient;
private static final String TAG = "LoginActivity";
private FirebaseAuth.AuthStateListener mAuthListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);

mAuth= FirebaseAuth.getInstance();
//Facebook Login
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());
startActivity(new Intent(LoginActivity.this,HomeActivity.class));
finish();
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
}
};

mAuth.addAuthStateListener(mAuthListener);

FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
saveFacebookLoginData("facebook", loginResult.getAccessToken());
}

@Override
public void onCancel() {

}

@Override
public void onError(FacebookException error) {
Toast.makeText(getApplicationContext(), "" + error.getMessage(), Toast.LENGTH_LONG).show();
}
});

btLoginWithFacebook = (Button) findViewById(R.id.btLoginWithFacebook);
btLoginWhithGoogle = (SignInButton) findViewById(R.id.btLoginWithGoogle);
btLoginWhithGoogle.setOnClickListener(this);
btLoginWithFacebook.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();
}

private void saveFacebookLoginData(String facebook, AccessToken accessToken) {
String token = accessToken.getToken();
AuthCredential credential = FacebookAuthProvider.getCredential(token);
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, HomeActivity.class));
}

// ...
}
});
}

@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btLoginWithGoogle:

Intent sighniIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(sighniIntent,RC_SIGN_IN);
break;
case R.id.btLoginWithFacebook:
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile", "user_friends", "email"));

break;

}
}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if(requestCode == RC_SIGN_IN){
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if(result.isSuccess()){
GoogleSignInAccount account = result.getSignInAccount();
firebaseAuthWithGoogle(account);
}else{

}
}

}

private void firebaseAuthWithGoogle(GoogleSignInAccount account) {

AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(),null);

mAuth.signInWithCredential(credential).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(!task.isSuccessful()){
String error = String.valueOf(task.getException());
Toast.makeText(LoginActivity.this,"Login Failed :"+ error,Toast.LENGTH_SHORT).show();
}else {

startActivity(new Intent(LoginActivity.this, HomeActivity.class));
finish();

}
}
});

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Log.d(TAG, "onConnectionFailed:" + connectionResult);
Toast.makeText(this, "Google Play Services error.", Toast.LENGTH_SHORT).show();
}


}

activity_login.xml

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@mipmap/login_back"
android:orientation="vertical"
tools:context="com.androidmate.anuj.trynew.login.LoginActivity">

<ImageView
android:layout_width="200dp"
android:layout_height="100dp"
android:src="@mipmap/img_toolbar_logo"
android:layout_gravity="center"
android:layout_marginTop="30dp"
/>


<com.google.android.gms.common.SignInButton
android:id="@+id/btLoginWithGoogle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/btLogin"
android:layout_marginTop="280dp"
android:padding="20dp"

/>

<Button
android:id="@+id/btLoginWithFacebook"
style="?android:textAppearanceSmall"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/com_facebook_button_background_color"

android:padding="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:text="Login with Facebook"
android:textStyle="bold"
android:textColor="#fff"/>

</LinearLayout>

最佳答案

试试这段代码。

LoginManager mLoginManager;

//Firebase Variables
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;

private CallbackManager mCallbackManager;

//Inside onCreate()
FacebookSdk.sdkInitialize(getApplicationContext());

mAuth = FirebaseAuth.getInstance();

mAuthStateListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
updateUI(user);
}
};

mCallbackManager = CallbackManager.Factory.create();
btnFacebookSignIn = (LoginButton) findViewById(R.id.button_facebook_signin);
btnFacebookSignIn.setReadPermissions("email","public_profile");
btnFacebookSignIn.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
Toast.makeText(LoginActivity.this, Constants.LOGINSUCCESSFUL, Toast.LENGTH_SHORT).show();
SharedPreferences sharedPref = getSharedPreferences(Constants.SHAREDPREFERENCE_USER_PROFILE,MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(Constants.USERLOGINTYPE,"facebook");
editor.apply();
handleFacebookAccessToken(loginResult.getAccessToken());
}

@Override
public void onCancel() {
Toast.makeText(LoginActivity.this, Constants.LOGINFAILED, Toast.LENGTH_SHORT).show();
}

@Override
public void onError(FacebookException error) {
Toast.makeText(LoginActivity.this, error.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
});

@Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthStateListener);
}


@Override
protected void onStop() {
super.onStop();
if(mAuthStateListener != null) {
mAuth.removeAuthStateListener(mAuthStateListener);
}
}


// [START onactivityresult]
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mCallbackManager.onActivityResult(requestCode, resultCode, data);
}
// [END onactivityresult]

private void handleFacebookAccessToken(AccessToken token) {
// ...
AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {

// 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()) {
Toast.makeText(LoginActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}

// ...
}
});
}
// [END auth_with_facebook]

private void updateUI(FirebaseUser user) {
if (user != null) {
//Code here for what you want to do after login
}
}


private void FacebookSignOut() {
if (AccessToken.getCurrentAccessToken() == null) {
return; // already logged out
}else {
new GraphRequest(AccessToken.getCurrentAccessToken(), "/me/permissions/", null, HttpMethod.DELETE, new GraphRequest
.Callback() {
@Override
public void onCompleted(GraphResponse graphResponse) {

LoginManager.getInstance().logOut();

}
}).executeAsync();
}
}

关于Android Facebook 登录使用新的 Firebase : App gets redirected to the login screen even after allowing permission,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37926183/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com