使用新Firebase进行Android Facebook登录:即使在允许

时间:2016-06-20 15:21:51

标签: android firebase facebook-login firebase-authentication facebook-authentication

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

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

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

这是代码

的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>

LoginActivity.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>

1 个答案:

答案 0 :(得分:2)

试试这段代码。

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();
    }
}