当前位置: 动力学知识库 > 问答 > 编程问答 >

How to like a facebook post from android app

问题描述:

I have implemented the login authentication in my app, i know how to share, but im getting crazy about the like, because im never getting a positive response. So...how can i like a post from my android app with facebook sdk, by requesting publish permissions?

网友答案:

Its work for me.

private static final List<String> PERMISSIONS = Arrays.asList("publish_actions", "publish_stream");

public void likeThis() {
Session session = Session.getActiveSession();       

if (session != null && session.isOpened()) {
    List<String> permissions = session.getPermissions();
    if (!isSubsetOf(PERMISSIONS, permissions)) {
        pendingPublishReauthorization = true;
        Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(this, PERMISSIONS);

        if (setPermissions(session, newPermissionsRequest))
            return;
    }

    Request.Callback callback = new Request.Callback() {
        public void onCompleted(Response response) {

            if (response != null) {
                FacebookRequestError error = response.getError();

                if (error != null) {
                    //                      error
                } else {
                    //                      success
                }
            } else {
                MessageToast toast =  MessageToast.getInstance(mContext);
                toast.show("Tente novamente mais tarde", MessageToast.ALERT);
            }
        }
    };

    Request request = new Request(session, "1442581505974136/likes", null, HttpMethod.POST, callback);

    RequestAsyncTask task = new RequestAsyncTask(request);
    task.execute();
}else{
//      not logged
}

}

private boolean isSubsetOf(Collection<String> subset, Collection<String> superset) {
    for (String string : subset) {
        if (!superset.contains(string)) {
            return false;
        }
    }
    return true;
}

private boolean setPermissions(final Session session, final NewPermissionsRequest newPermissionsRequest) {

    try {
        Log.i(TAG, "Getting a new permission...");
        session.requestNewPublishPermissions(newPermissionsRequest);

        return true;
    } catch (IllegalStateException e) {
        Log.e("setPermissions","[IllegalStateException] \n" + e.getMessage());


        pendingPublishReauthorization = false;

        return false;
    } catch (UnsupportedOperationException e) {
        Log.e("setPermissions","[UnsupportedOperationException] \n" + e.getMessage());


        pendingPublishReauthorization = false;

        return false;
    }
}

But sometime, I can't like some fb_id. I don't know why, yet..

分享给朋友:
您可能感兴趣的文章:
随机阅读: