Facebook Profile.getCurrentProfile() is al

2019-07-16 15:47发布

For the first time when I login into the app through Facebook, I'm getting profile from Profile.getCurrentProfile();

Where as when I exit the app and launch again, It was already logged in. So I can call directly Profile.getCurrentProfile(); is returning null.

Code

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FacebookSdk.sdkInitialize(getApplicationContext());
    setContentView(R.layout.activity_page);
    Profile profile = Profile.getCurrentProfile();
    // For the first launch the profile will be null
    displayProfileName(profile);
    LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
    loginButton.setReadPermissions("public_profile");
    callbackManager = CallbackManager.Factory.create();
    loginButton.registerCallback(callbackManager,
            new FacebookCallback<LoginResult>() {
                @Override
                public void onSuccess(final LoginResult loginResult) {
                    profileTracker = new ProfileTracker() {

                        @Override
                        protected void onCurrentProfileChanged(
                                Profile oldProfile, Profile currentProfile) {
                            profileTracker.stopTracking();
                            Profile.setCurrentProfile(currentProfile);
                            Profile profile = Profile.getCurrentProfile();
                            displayProfileName(profile);
                        }
                    };
                    profileTracker.startTracking();
                }

                @Override
                public void onCancel() {
                }

                @Override
                public void onError(FacebookException exception) {
                }
            });
}

@Override
protected void onDestroy() {
    super.onDestroy();
    if (profileTracker != null) {
        profileTracker.stopTracking();
    }
}

@Override
protected void onPause() {
    super.onPause();
    // Logs 'app deactivate' App Event.
    AppEventsLogger.deactivateApp(this);
}

@Override
protected void onRestart() {
    super.onRestart();
    AppEventsLogger.activateApp(this);
}
/**
*
* Method to display the Profile Name 
*/
private void displayProfileName(Profile profile) {
    if (profile != null) {
        Toast.makeText(MainActivity.this, profile.getName(),
                Toast.LENGTH_LONG).show();
    } else {
        Toast.makeText(MainActivity.this, "No Profile", Toast.LENGTH_LONG)
                .show();
    }
}


@Override
protected void onActivityResult(int arg0, int arg1, Intent arg2) {
    super.onActivityResult(arg0, arg1, arg2);
    callbackManager.onActivityResult(arg0, arg1, arg2);
}

3条回答
【Aperson】
2楼-- · 2019-07-16 16:15

There are two cases in this:

  1. For first login, follow my other answer.
  2. For second login, you will need to refresh your AccessToken and then fetch the profile. Refreshing token code can be found in this answer but the code below has it (for simplification).

The code is taken from FB's dreadful documentation).

You can put this code straight into your app, where the comment says "case 1", just invoke your normal FB login.

private AccessTokenTracker mAccessTokenTracker;

private void loginToMyFbApp() {
    FacebookSdk.sdkInitialize(this);
    if (AccessToken.getCurrentAccessToken() != null) {
        mAccessTokenTracker = new AccessTokenTracker() {
            @Override
            protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {
                mAccessTokenTracker.stopTracking();
                if(currentAccessToken == null) {
                    //(the user has revoked your permissions -
                    //by going to his settings and deleted your app)
                    //do the simple login to FaceBook
                    //case 1
                }
                else {
                    //you've got the new access token now.
                    //AccessToken.getToken() could be same for both
                    //parameters but you should only use "currentAccessToken"
                    //case 2
                    fetchProfile();
                }
            }
        };
        mAccessTokenTracker.startTracking();
        AccessToken.refreshCurrentAccessTokenAsync();
    }
    else {
        //do the simple login to FaceBook
        //case 1
    }
}

private void fetchProfile() {
    GraphRequest request = GraphRequest.newMeRequest(
            AccessToken.getCurrentAccessToken(),
            new GraphRequest.GraphJSONObjectCallback() {
                @Override
                public void onCompleted(JSONObject object, GraphResponse response) {
                    // this is where you should have the profile
                    Log.v("fetched info", object.toString());
                }
            });
    Bundle parameters = new Bundle();
    parameters.putString("fields", "id,name,link"); //write the fields you need
    request.setParameters(parameters);
    request.executeAsync();
}
查看更多
虎瘦雄心在
3楼-- · 2019-07-16 16:36

Call LoginManager.getInstance().logOut(); once you get the profile details.

查看更多
来,给爷笑一个
4楼-- · 2019-07-16 16:37

Instead of accessing Profile.getCurrentProfile()

use access token and make graph request in onSuccess()

( It worked for me)

here snippet of code :

FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
    @Override
    public void onSuccess(LoginResult loginResult) {

        Log.v("profile track", (DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT).format(loginResult.getAccessToken().getExpires())));
        GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(),
                new GraphRequest.GraphJSONObjectCallback() {
                    @Override
                    public void onCompleted(JSONObject object, GraphResponse response) {
                        try {

                            String name = object.getString("name");
                            String email = object.getString("email");
                            String id = object.getString("id");
                            Toast.makeText(Login.this, name + " " + " " + email + " " + id, Toast.LENGTH_SHORT).show();

                    /*write  your code  that is to be executed after successful login*/


                        } catch (JSONException ex) {
                            ex.printStackTrace();
                        }
                    }
                });
        Bundle parameters = new Bundle();
        parameters.putString("fields", "id,name,email,gender, birthday");
        request.setParameters(parameters);
        request.executeAsync();
    }

    @Override
    public void onCancel() {
    }

    @Override
    public void onError(FacebookException e) {
    }
};
查看更多
登录 后发表回答