如何检查用户是否使用 Android 的 FB SDK 4.0 登录?
How to check if user is logged in with FB SDK 4.0 for Android?
几天前我在我的APP上实现了FB登录,今天我发现我实现的大部分东西现在都被弃用了。
之前,我使用 Session
查看用户是否登录。但是,这不适用于新的 SDK。
根据他们的文档,我们可以使用 AccessToken.getCurrentAccessToken()
和 Profile.getCurrentProfile()
来检查用户是否已经登录,但我无法使用它们。
我试过这样的事情:
if(AccessToken.getCurrentAccessToken() == null)
我想知道如果我可以在这个里面使用它是否可行(这也是由 FB 提供的):
LoginManager.getInstance().registerCallback(callbackManager, new LoginManager.Callback() {...});
但是,我得到了 "Cannot resolve symbol 'Callback'"。
编辑!!!!!!
好的,所以我可以使用以下方法检查用户是否已登录:
在创建时:
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
。
如果有人能提供帮助,我将不胜感激。
谢谢!
我明白了!
首先,请确保您已初始化 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);
}
}
这对我有用! =]
您可以使用 Felipe 在他的回答中提到的相同方式,也可以使用其他两种方式。但似乎 AccessTokenTracker 是一种方便的方法,因为它可以帮助您跟踪访问令牌(与 ProfileTracker 一起使用 class)
- 如果您使用自定义按钮登录,请使用 LoginManager 回调
例如
在你的布局中xml
<Button
android:id="@+id/my_facebook_button"
android:background="@drawable/btnfacebook"
android:onClick="facebookLogin"/>
在你的Activity
//Custom Button
Button myFacebookButton = (Button) findViewById(R.id.my_facebook_button);
按钮onclick监听器
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");
}
});
- 如果您使用的是 SDK 中提供的按钮 (com.facebook.login.widget.LoginButton),请使用 LoginButton 回调(这在他们的参考文档中有详细说明 - https://developers.facebook.com/docs/facebook-login/android/v2.3)
例如
在你的布局中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"/>
在你的activity
//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 中调用 callbackManager.onActivityResult(requestCode, resultCode, data);
onActivityResult()
一个更简单的解决方案适用于我的案例(我不知道这是否是更优雅的方法):
public boolean isLoggedIn() {
AccessToken accessToken = AccessToken.getCurrentAccessToken();
return accessToken != null;
}
我使用 AccessToken 和 AccessTokenTracker 来检查登录状态的困境是,当 AccessToken 准备好并且跟踪器的回调函数被调用但配置文件可能尚未准备好时,因此我无法在那个时候获取或显示 Facebooker 的名字。
我的解决方案是检查当前个人资料 != null 并同时使用其跟踪器获取 Facebooker 的姓名:
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());
}
回复晚了,现在在Facebook SDK
的4.25.0
版本中有一个方法:
public void retrieveLoginStatus(Context context,
LoginStatusCallback responseCallback)
其中指出:
Retrieves the login status for the user. This will return an access
token for the app if a user is logged into the Facebook for Android
app on the same device and that user had previously logged into the
app. If an access token was retrieved then a toast will be shown
telling the user that they have been logged in.
并且可以像这样使用:
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();
}
} );
根据 facebook documentation 你可以通过以下方式做到这一点:
AccessToken accessToken = AccessToken.getCurrentAccessToken();
boolean isLoggedIn = accessToken != null && !accessToken.isExpired();
几天前我在我的APP上实现了FB登录,今天我发现我实现的大部分东西现在都被弃用了。
之前,我使用 Session
查看用户是否登录。但是,这不适用于新的 SDK。
根据他们的文档,我们可以使用 AccessToken.getCurrentAccessToken()
和 Profile.getCurrentProfile()
来检查用户是否已经登录,但我无法使用它们。
我试过这样的事情:
if(AccessToken.getCurrentAccessToken() == null)
我想知道如果我可以在这个里面使用它是否可行(这也是由 FB 提供的):
LoginManager.getInstance().registerCallback(callbackManager, new LoginManager.Callback() {...});
但是,我得到了 "Cannot resolve symbol 'Callback'"。
编辑!!!!!!
好的,所以我可以使用以下方法检查用户是否已登录:
在创建时:
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
。
如果有人能提供帮助,我将不胜感激。
谢谢!
我明白了!
首先,请确保您已初始化 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);
}
}
这对我有用! =]
您可以使用 Felipe 在他的回答中提到的相同方式,也可以使用其他两种方式。但似乎 AccessTokenTracker 是一种方便的方法,因为它可以帮助您跟踪访问令牌(与 ProfileTracker 一起使用 class)
- 如果您使用自定义按钮登录,请使用 LoginManager 回调
例如
在你的布局中xml
<Button
android:id="@+id/my_facebook_button"
android:background="@drawable/btnfacebook"
android:onClick="facebookLogin"/>
在你的Activity
//Custom Button
Button myFacebookButton = (Button) findViewById(R.id.my_facebook_button);
按钮onclick监听器
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");
}
});
- 如果您使用的是 SDK 中提供的按钮 (com.facebook.login.widget.LoginButton),请使用 LoginButton 回调(这在他们的参考文档中有详细说明 - https://developers.facebook.com/docs/facebook-login/android/v2.3)
例如
在你的布局中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"/>
在你的activity
//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 中调用 callbackManager.onActivityResult(requestCode, resultCode, data);
onActivityResult()
一个更简单的解决方案适用于我的案例(我不知道这是否是更优雅的方法):
public boolean isLoggedIn() {
AccessToken accessToken = AccessToken.getCurrentAccessToken();
return accessToken != null;
}
我使用 AccessToken 和 AccessTokenTracker 来检查登录状态的困境是,当 AccessToken 准备好并且跟踪器的回调函数被调用但配置文件可能尚未准备好时,因此我无法在那个时候获取或显示 Facebooker 的名字。
我的解决方案是检查当前个人资料 != null 并同时使用其跟踪器获取 Facebooker 的姓名:
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());
}
回复晚了,现在在Facebook SDK
的4.25.0
版本中有一个方法:
public void retrieveLoginStatus(Context context,
LoginStatusCallback responseCallback)
其中指出:
Retrieves the login status for the user. This will return an access token for the app if a user is logged into the Facebook for Android app on the same device and that user had previously logged into the app. If an access token was retrieved then a toast will be shown telling the user that they have been logged in.
并且可以像这样使用:
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();
}
} );
根据 facebook documentation 你可以通过以下方式做到这一点:
AccessToken accessToken = AccessToken.getCurrentAccessToken();
boolean isLoggedIn = accessToken != null && !accessToken.isExpired();