【问题标题】:Android Firebase Oauth Facebook not working in fragmentAndroid Firebase Oauth Facebook 无法在片段中工作
【发布时间】:2017-06-04 08:46:44
【问题描述】:

使用 Firebase Facebook 进行身份验证不起作用,这是我的片段代码:

public class LoginFragment extends Fragment {

private View mView;

private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private CallbackManager mCallbackManager;

public LoginFragment() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    mView = inflater.inflate(R.layout.fragment_login, container, false);
    loginFacebook();
    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");
            }
            // ...
        }
    };

    return mView;
}


private void loginFacebook() {
    // Initialize Facebook Login button
    mCallbackManager = CallbackManager.Factory.create();
    LoginButton loginButton = (LoginButton) mView.findViewById(R.id.login_button);
    loginButton.setReadPermissions("email", "public_profile");
    loginButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            //Log.d(TAG, "facebook:onSuccess:" + loginResult);
            handleFacebookAccessToken(loginResult.getAccessToken());
        }

        @Override
        public void onCancel() {
            //Log.d(TAG, "facebook:onCancel");
            // ...
        }

        @Override
        public void onError(FacebookException error) {
            //Log.d(TAG, "facebook:onError", error);
            // ...
        }
    });
}


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

    // Pass the activity result back to the Facebook SDK
    mCallbackManager.onActivityResult(requestCode, resultCode, data);
}

@Override
public void onStart() {
    super.onStart();
    mAuth.addAuthStateListener(mAuthListener);
}

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

private void handleFacebookAccessToken(AccessToken token) {
    //Log.d(TAG, "handleFacebookAccessToken:" + token);

    AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener((MainActivity)getActivity(), 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((MainActivity)getActivity(), "Authentication failed.",
                                Toast.LENGTH_SHORT).show();
                    }


                }
            });
}
}

在 Facebook 弹出窗口出现并输入我的用户名和密码后,在调试模式下代码中没有任何内容。

Firebase 用户始终为 null。我究竟做错了什么 ? 登录后记录 Log.d("LOGGER", "onAuthStateChanged:signed_out");

PS:完全相同的代码在插入 MainActivity

时会起作用

【问题讨论】:

  • 是否触发过 onComplete 监听器?您能否更详细地说明您的尝试以及结果如何?看起来您已经注释掉了相关日志。您如何验证它实际上是在尝试进行身份验证?见how to askcreating an mcve
  • 它进入 AuthStateListener,并给我 Log.d("LOGGER", "onAuthStateChanged:signed_out");
  • 它最初会做什么,直到你真正登录。那么,你是如何验证 onComplete 曾经被调用过的?

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


【解决方案1】:

您可以尝试将片段链接到登录按钮。

loginButton.setFragment(this);

【讨论】:

    【解决方案2】:

    所以经过一些研究,我现在知道我应该使用 Activity 进行登录操作,而不是片段。

    但是我在让代码在 MainActivity 中工作时遇到了问题,实际上一切都“工作”了。我登录了,但我的 FirebaseAuth.AuthStateListener 没有从 firebaseAuth.getCurrentUser() 返回任何用户。

    所以经过几个小时的测试后,我发现在登录方法中启用电子邮件/密码可以让它工作。奇怪……

    至少我认为这是问题所在,但我确实创建了一个新的 Android 项目。并使用:Tools -> firebase 生成一个 firebase 项目。但我记得这并没有解决问题,至少没有立即解决。

    也可能是模拟器的原因。

    【讨论】:

      【解决方案3】:

      我只是从我的自定义按钮中调用 facebook 默认按钮,并将每一行代码都保留为记录并成功运行。

      public class SignInFragment extends Fragment implements
      > FragmentChangeListener{
      >     private Button facebook;
      
      private FirebaseAuth firebaseAuth;
      private CallbackManager mCallBackManager;
      private LoginButton loginButton;
      
      
      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container,
                               Bundle savedInstanceState) {
      
          // Inflate the layout for this fragment
          View view =  inflater.inflate(R.layout.fragment_sign_in, container, false);
      
          facebook = view.findViewById(R.id.facebookButton);
          loginButton = view.findViewById(R.id.facebookBtn);
      
          firebaseAuth = FirebaseAuth.getInstance();
      
          facebook.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                  loginButton.callOnClick();
              }
          });
      
          loginButton.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                  mCallBackManager = CallbackManager.Factory.create();
                  loginButton.setFragment(SignInFragment.this);
                  loginButton.setPermissions("email","public_profile");
                  loginButton.registerCallback(mCallBackManager, new FacebookCallback<LoginResult>() {
                      @Override
                      public void onSuccess(LoginResult loginResult) {
                          handleFacebookAccessToken(loginResult.getAccessToken());
                      }
      
                      @Override
                      public void onCancel() {
                          Toast.makeText(getContext(),"Is Cancelled",Toast.LENGTH_LONG).show();
                      }
      
                      @Override
                      public void onError(FacebookException error) {
                          Toast.makeText(getContext(),error.getMessage(),Toast.LENGTH_LONG).show();
                      }
                  });
              }
          });
      
          return view;
      }
      
      
      @Override
      public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
          super.onActivityResult(requestCode, resultCode, data);
      
          mCallBackManager.onActivityResult(requestCode, resultCode, data);
      
      }
      
      private void handleFacebookAccessToken(AccessToken token) {
          AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
          firebaseAuth.signInWithCredential(credential)
                  .addOnCompleteListener(getActivity(), 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
                              FirebaseUser user = firebaseAuth.getCurrentUser();
                              startActivity(new Intent(getContext(),MainActivity.class));
                          } else {
                              // If sign in fails, display a message to the user.
                              Toast.makeText(getContext(), task.getException().getMessage(),
                                      Toast.LENGTH_SHORT).show();
                          }
      
                      }
                  });
      }
      

      }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-07-09
        • 2015-05-14
        • 2021-07-14
        • 1970-01-01
        • 2015-12-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多