如何通过Facebook集成Android获取电子邮件ID

时间:2016-01-02 10:13:53

标签: android facebook facebook-graph-api

我希望在通过Facebook登录后获得用户电子邮件ID。我几乎尝试了所有解决方案。但它总是返回null。

这是我的活动课。

public class MainActivity extends FragmentActivity {
String TAG = "MainActivity";

private final String PENDING_ACTION_BUNDLE_KEY = "pending_action";
 private static final String PERMISSION = "publish_actions";
private Button postStatusUpdateButton;
private LoginButton loginButton;
private ProfilePictureView profilePictureView;
private TextView greeting;
private PendingAction pendingAction = PendingAction.NONE;
private GraphUser user;
private GraphPlace place;
private List<GraphUser> tags;
private boolean canPresentShareDialog;

private enum PendingAction {
    NONE, POST_STATUS_UPDATE
}

private UiLifecycleHelper uiHelper;

private Session.StatusCallback callback = new Session.StatusCallback() {
    @Override
    public void call(Session session, SessionState state,
                     Exception exception) {
        onSessionStateChange(session, state, exception);
    }
};


private FacebookDialog.Callback dialogCallback = new FacebookDialog.Callback() {
    @Override
    public void onError(FacebookDialog.PendingCall pendingCall,
                        Exception error, Bundle data) {
        Log.d(TAG, String.format("Error: %s", error.toString()));
    }

    @Override
    public void onComplete(FacebookDialog.PendingCall pendingCall,
                           Bundle data) {
        Log.d(TAG, "Success!");
    }
};

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    uiHelper = new UiLifecycleHelper(this, callback);
    uiHelper.onCreate(savedInstanceState);
    // Can we present the share dialog for regular links?
    canPresentShareDialog = FacebookDialog.canPresentShareDialog(this, FacebookDialog.ShareDialogFeature.SHARE_DIALOG);

    if (savedInstanceState != null) {
        String name = savedInstanceState.getString(PENDING_ACTION_BUNDLE_KEY);
        pendingAction = PendingAction.valueOf(name);
    }

    setContentView(R.layout.activity_main);

    loginButton = (LoginButton) findViewById(R.id.login_button);
    loginButton.setUserInfoChangedCallback(new LoginButton.UserInfoChangedCallback() {
        @Override
        public void onUserInfoFetched(GraphUser user) {
            MainActivity.this.user = user;
            updateUI();
            // It's possible that we were waiting for this.user to
            // be populated in order to post a status update.
            handlePendingAction();
        }
    });

    profilePictureView = (ProfilePictureView) findViewById(R.id.profilePicture);
    greeting = (TextView) findViewById(R.id.greeting);

    postStatusUpdateButton = (Button) findViewById(R.id.postStatusUpdateButton);
    postStatusUpdateButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            performPublish(PendingAction.POST_STATUS_UPDATE, canPresentShareDialog);
        }
    });
}

//override lifecycle methods so that UiLifecycleHelper know about state of the activity
@Override
protected void onResume() {
    super.onResume();
    uiHelper.onResume();
    updateUI();
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    uiHelper.onSaveInstanceState(outState);
    outState.putString(PENDING_ACTION_BUNDLE_KEY, pendingAction.name());
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    uiHelper.onActivityResult(requestCode, resultCode, data, dialogCallback);
}

@Override
public void onPause() {
    super.onPause();
    uiHelper.onPause();
}

@Override
public void onDestroy() {
    super.onDestroy();
    uiHelper.onDestroy();
}

private void onSessionStateChange(Session session, SessionState state, Exception exception) {
    if (state.isOpened()) {
        Toast.makeText(getApplicationContext(), "User logged in...", Toast.LENGTH_SHORT).show();
    } else if (state.isClosed()) {
        Toast.makeText(getApplicationContext(), "User logged out...", Toast.LENGTH_SHORT).show();
    }
    if (pendingAction != PendingAction.NONE
            && (exception instanceof FacebookOperationCanceledException
            || exception instanceof FacebookAuthorizationException)) {
        new AlertDialog.Builder(MainActivity.this)//if permission is not granted
                .setTitle(R.string.cancelled)
                .setMessage(R.string.permission_not_granted)
                .setPositiveButton(R.string.ok, null).show();
        pendingAction = PendingAction.NONE;
    } else if (state == SessionState.OPENED_TOKEN_UPDATED) {
        handlePendingAction();
    }

    updateUI();


}

private void updateUI() {
    Session session = Session.getActiveSession();
    boolean enableButtons = (session != null && session.isOpened());

    postStatusUpdateButton.setEnabled(enableButtons
            || canPresentShareDialog);

    if (enableButtons && user != null) {
        profilePictureView.setProfileId(user.getId());
        greeting.setText(getString(R.string.hello_user, user.getName()));
        try {
            List<String> permissions = new ArrayList<String>();
            permissions.add("email");

            String fbemail = user.getProperty("email").toString();
            Toast.makeText(MainActivity.this, ".....emai...."+ fbemail, Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

    } else {
        profilePictureView.setProfileId(null);
        greeting.setText(null);
    }
}

@SuppressWarnings("incomplete-switch")
private void handlePendingAction() {
    PendingAction previouslyPendingAction = pendingAction;
    // These actions may re-set pendingAction if they are still pending, but we assume they
    // will succeed.
    pendingAction = PendingAction.NONE;

    switch (previouslyPendingAction) {
        case POST_STATUS_UPDATE:
            postStatusUpdate();
            break;
    }
}

private interface GraphObjectWithId extends GraphObject {
    String getId();
}

private void showPublishResult(String message, GraphObject result,
                               FacebookRequestError error) {
    String title = null;
    String alertMessage = null;
    if (error == null) {
        title = getString(R.string.success);
        String id = result.cast(GraphObjectWithId.class).getId();
        alertMessage = getString(R.string.successfully_posted_post,
                message, id);
    } else {
        title = getString(R.string.error);
        alertMessage = error.getErrorMessage();
    }

    new AlertDialog.Builder(this).setTitle(title).setMessage(alertMessage)
            .setPositiveButton(R.string.ok, null).show();
}

// create sample post to update on facebook
private FacebookDialog.ShareDialogBuilder createShareDialogBuilderForLink() {
    return new FacebookDialog.ShareDialogBuilder(this)
            .setName("Hello Facebook")
            .setDescription("this is sample post from androidSRC.net to demonstrate facebook login in your android application")
            .setLink("http://androidsrc.net/");
}

private void postStatusUpdate() {
    if (canPresentShareDialog) {
        FacebookDialog shareDialog = createShareDialogBuilderForLink().build();
        uiHelper.trackPendingDialogCall(shareDialog.present());
    } else if (user != null && hasPublishPermission()) {
        final String message = getString(R.string.status_update,
                user.getFirstName(), (new Date().toString()));
        Request request = Request.newStatusUpdateRequest(
                Session.getActiveSession(), message, place, tags,
                new Request.Callback() {
                    @Override
                    public void onCompleted(Response response) {
                        showPublishResult(message,
                                response.getGraphObject(),
                                response.getError());
                    }
                });
        request.executeAsync();
    } else {
        pendingAction = PendingAction.POST_STATUS_UPDATE;
    }
}

//check if app has permission to publish on facebook
private boolean hasPublishPermission() {
    Session session = Session.getActiveSession();
    return session != null && session.getPermissions().contains("publish_actions");
}

private void performPublish(PendingAction action, boolean allowNoSession) {
    Session session = Session.getActiveSession();
    if (session != null) {
        pendingAction = action;
        if (hasPublishPermission()) {
            // We can do the action right away.
            handlePendingAction();
            return;
        } else if (session.isOpened()) {
            // We need to get new permissions, then complete the action when
            // we get called back.
            session.requestNewPublishPermissions(new Session.NewPermissionsRequest(
                    this, PERMISSION));
            return;
        }
    }

    if (allowNoSession) {
        pendingAction = action;
        handlePendingAction();
    }
}
}
在logcat中

它会出错:

01-02 15:22:13.673 24567-24587/com.example.facebook W/EGL_emulation: eglSurfaceAttrib not implemented
01-02 15:22:13.673 24567-24587/com.example.facebook W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xa143ec80, error=EGL_SUCCESS
01-02 15:22:14.779 24567-24567/com.example.facebook W/System.err:        java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
01-02 15:22:14.780 24567-24567/com.example.facebook W/System.err:     at   com.example.facebook.MainActivity.updateUI(MainActivity.java:198)
01-02 15:22:14.780 24567-24567/com.example.facebook W/System.err:     at com.example.facebook.MainActivity.access$200(MainActivity.java:24)
01-02 15:22:14.780 24567-24567/com.example.facebook W/System.err:     at com.example.facebook.MainActivity$3.onUserInfoFetched(MainActivity.java:90)
01-02 15:22:14.781 24567-24567/com.example.facebook W/System.err:     at com.facebook.widget.LoginButton$1.onCompleted(LoginButton.java:630)
01-02 15:22:14.781 24567-24567/com.example.facebook W/System.err:     at com.facebook.Request$1.onCompleted(Request.java:269)
01-02 15:22:14.781 24567-24567/com.example.facebook W/System.err:     at com.facebook.Request$4.run(Request.java:1669)
01-02 15:22:14.781 24567-24567/com.example.facebook W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
01-02 15:22:14.781 24567-24567/com.example.facebook W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
01-02 15:22:14.782 24567-24567/com.example.facebook W/System.err:     at android.os.Looper.loop(Looper.java:148) 
01-02 15:22:14.782 24567-24567/com.example.facebook W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5417)
01-02 15:22:14.782 24567-24567/com.example.facebook W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
01-02 15:22:14.782 24567-24567/com.example.facebook W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
01-02 15:22:14.783 24567-24567/com.example.facebook W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
01-02 15:22:14.887 24567-24573/com.example.facebook W/art: Suspending all threads took: 31.994ms

如果有人有解决方案,请回复。

1 个答案:

答案 0 :(得分:1)

如果您没有收到电子邮件,则只有3个理由: