如何检查用户是否使用FB SDK 4.0 for Android登录?

时间:2015-03-27 05:38:19

标签: android facebook facebook-graph-api login

前几天我实施了FB登录到我的APP,今天我发现我实施的大部分内容现已弃用。

之前,我使用Session来查看用户是否已登录。但是,这不适用于新的SDK。

根据他们的文档,我们可以使用AccessToken.getCurrentAccessToken()Profile.getCurrentProfile()来检查用户是否已经登录,但我无法使用它们。

我试过这样的事情:

if(AccessToken.getCurrentAccessToken() == null)

我想知道如果我可以在其中使用它(这也是由FB提供)是否可行:

LoginManager.getInstance().registerCallback(callbackManager, new LoginManager.Callback() {...});

但是,我得到“无法解析符号'回调'”。

修改!!!!!!

好的,我可以使用以下方法检查用户是否已登录:

on onCreate:

accessTokenTracker = new AccessTokenTracker() {
        @Override
        protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken newAccessToken) {
            updateWithToken(newAccessToken);
        }
    };

然后,调用我的updateWithToken方法:

private void updateWithToken(AccessToken currentAccessToken) {
    if (currentAccessToken != null) {

            LOAD ACTIVITY A!

    } else {

            LOAD ACTIVITY B!
    }
}

现在,问题是:如果用户使用过该应用程序并且之前没有登录,我可以检查一下!但如果这是用户第一次使用该应用,则我的AccessTokenTracker永远不会调用updateWithToken

如果有人可以提供帮助,我真的很感激。

谢谢!

6 个答案:

答案 0 :(得分:134)

一个更简单的解决方案适用于我的情况(我不知道这是否是更优雅的方式):

public boolean isLoggedIn() {
    AccessToken accessToken = AccessToken.getCurrentAccessToken();
    return accessToken != null;
}

答案 1 :(得分:35)

我明白了!

首先,确保已初始化FB SDK。其次,添加以下内容:

accessTokenTracker = new AccessTokenTracker() {
        @Override
        protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken newAccessToken) {
            updateWithToken(newAccessToken);
        }
    };

当当前访问令牌发生变化时,将调用此方法。这意味着,只有在用户已经登录时,这才会对您有所帮助。

接下来,我们将其添加到我们的onCreate()方法:

updateWithToken(AccessToken.getCurrentAccessToken());

当然,我们的updateWithToken()方法:

private void updateWithToken(AccessToken currentAccessToken) {

    if (currentAccessToken != null) {
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                Intent i = new Intent(SplashScreen.this, GeekTrivia.class);
                startActivity(i);

                finish();
            }
        }, SPLASH_TIME_OUT);
    } else {
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                Intent i = new Intent(SplashScreen.this, Login.class);
                startActivity(i);

                finish();
            }
        }, SPLASH_TIME_OUT);
    }
}

这样做对我来说! =]

答案 2 :(得分:9)

使用AccessToken和AccessTokenTracker检查登录状态的困境是,当AccessToken准备好并且跟踪器的回调函数被调用但是配置文件可能还没有准备好时,因此我无法在此时获取或显示Facebooker的名称。

我的解决方案是检查当前个人资料!= null并使用其跟踪器同时拥有Facebook的名称:

    ProfileTracker fbProfileTracker = new ProfileTracker() {
        @Override
        protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) {
            // User logged in or changed profile
        }
    };

检查登录状态,然后获取用户名:

Profile profile = Profile.getCurrentProfile();
if (profile != null) {
    Log.v(TAG, "Logged, user name=" + profile.getFirstName() + " " + profile.getLastName());
}

答案 3 :(得分:3)

您可以使用Felipe在答案中提到的相同方式,也可以使用其他两种方式。但似乎AccessTokenTracker似乎是方便的方式,因为它可以帮助您跟踪访问令牌(与ProfileTracker类一起使用)

  1. 如果您使用自定义按钮登录,请使用LoginManager回拨
  2. 例如

    在你的布局xml中

        <Button
            android:id="@+id/my_facebook_button"
            android:background="@drawable/btnfacebook"
            android:onClick="facebookLogin"/>
    

    在您的活动中

        //Custom Button
        Button myFacebookButton = (Button) findViewById(R.id.my_facebook_button);
    

    按钮onclick Listener

    public void facebookLogin(View view) {
            LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile", "user_friends"));
        }
    

    最后是LoginManager回调

     //Create callback manager to handle login response
            CallbackManager callbackManager = CallbackManager.Factory.create();
    
           LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
               @Override
               public void onSuccess(LoginResult loginResult) {
                   Log.i(TAG, "LoginManager FacebookCallback onSuccess");
                   if(loginResult.getAccessToken() != null) {
                       Log.i(TAG, "Access Token:: " + loginResult.getAccessToken());
                       facebookSuccess();
                   }
               }
    
               @Override
               public void onCancel() {
                   Log.i(TAG, "LoginManager FacebookCallback onCancel");
               }
    
               @Override
               public void onError(FacebookException e) {
                   Log.i(TAG, "LoginManager FacebookCallback onError");
               }
           });
    
    1. 如果您使用SDK中提供的按钮(com.facebook.login.widget.LoginButton),请使用LoginButton回调(这在其参考文档中详细说明了 - https://developers.facebook.com/docs/facebook-login/android/v2.3
    2. 例如

      在你的布局xml中

      <com.facebook.login.widget.LoginButton
                      android:id="@+id/login_button"
                      android:layout_width="wrap_content"
                      android:layout_height="wrap_content"
                      android:layout_gravity="center_horizontal"/>
      

      在您的活动中

          //Facebook SDK provided LoginButton
          LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
          loginButton.setReadPermissions("user_friends");
          //Callback registration
          loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
              @Override
              public void onSuccess(LoginResult loginResult) {
                  // App code
                  Log.i(TAG, "LoginButton FacebookCallback onSuccess");
                  if(loginResult.getAccessToken() != null){
                      Log.i(TAG, "Access Token:: "+loginResult.getAccessToken());
                      facebookSuccess();
                  }
      
              }
      
              @Override
              public void onCancel() {
                  // App code
                  Log.i(TAG, "LoginButton FacebookCallback onCancel");
              }
      
              @Override
              public void onError(FacebookException exception) {
                  // App code
                  Log.i(TAG, "LoginButton FacebookCallback onError:: "+exception.getMessage());
                  Log.i(TAG,"Exception:: "+exception.getStackTrace());
              }
          });
      

      别忘了在Activity onActivityResult()

      中调用callbackManager.onActivityResult(requestCode, resultCode, data);

答案 4 :(得分:3)

根据facebook documentation,您可以通过以下方式进行操作:

AccessToken accessToken = AccessToken.getCurrentAccessToken();
boolean isLoggedIn = accessToken != null && !accessToken.isExpired();

答案 5 :(得分:1)

回复较晚,但现在4.25.0的版本 Facebook SDK 有一种方法:

public void retrieveLoginStatus(Context context,
                                LoginStatusCallback responseCallback)

哪个州:

  

检索用户的登录状态。这将返回访问权限   用户登录Facebook for Android时的应用令牌   同一设备上的应用程序和该用户以前登录过的   应用程序。如果检索到访问令牌,则会显示Toast   告诉用户他们已经登录。

可以像:

一样使用
LoginManager.getInstance().retrieveLoginStatus( this, new LoginStatusCallback()
{
    @Override
    public void onCompleted( AccessToken accessToken )
    {
        GraphRequest request = GraphRequest.newMeRequest( accessToken, new GraphRequest.GraphJSONObjectCallback()
        {
            @Override
            public void onCompleted( JSONObject object, GraphResponse response )
            {
                Log.e( TAG, object.toString() );
                Log.e( TAG, response.toString() );

                try
                {
                    userId = object.getString( "id" );
                    profilePicture = new URL( "https://graph.facebook.com/" + userId + "/picture?width=500&height=500" );
                    Log.d( "PROFILE_URL", "url: " + profilePicture.toString() );
                    if ( object.has( "first_name" ) )
                    {
                        firstName = object.getString( "first_name" );
                    }
                    if ( object.has( "last_name" ) )
                    {
                        lastName = object.getString( "last_name" );
                    }
                    if ( object.has( "email" ) )
                    {
                        email = object.getString( "email" );
                    }
                    if ( object.has( "birthday" ) )
                    {
                        birthday = object.getString( "birthday" );
                    }
                    if ( object.has( "gender" ) )
                    {
                        gender = object.getString( "gender" );
                    }

                    Intent main = new Intent( LoginActivity.this, MainActivity.class );
                    main.putExtra( "name", firstName );
                    main.putExtra( "surname", lastName );
                    main.putExtra( "imageUrl", profilePicture.toString() );
                    startActivity( main );
                    finish();
                }
                catch ( JSONException e )
                {
                    e.printStackTrace();
                }
                catch ( MalformedURLException e )
                {
                    e.printStackTrace();
                }

            }
        } );
        //Here we put the requested fields to be returned from the JSONObject
        Bundle parameters = new Bundle();
        parameters.putString( "fields", "id, first_name, last_name, email, birthday, gender" );
        request.setParameters( parameters );
        request.executeAsync();
    }

    @Override
    public void onFailure()
    {
        Toast.makeText( LoginActivity.this, "Could not log in.", Toast.LENGTH_SHORT ).show();
    }

    @Override
    public void onError( Exception exception )
    {
        Toast.makeText( LoginActivity.this, "Could not log in.", Toast.LENGTH_SHORT ).show();
    }
} );
相关问题