Friday 17 October 2014

This blog useful when we have to update status on user's fan page/friend page instead of user's wall using Facebook sdk.

This kind of functionality implemented in Instagram.
After a lots of search I  have find some useful things which is useful to me.
I would like to share this thing with you. This might be useful to u also.

Parameter list Used in Request:
  • name
  • caption
  • description
  • picture
  • link
  • to
  • message
This is parameter required when we want to post on user's fan page. You can add or remove more parameter as per requirement.

We have to pass bundle in parameter so bundle created for parameter.
Bundle requestParams =new Bundle (); 

requestParams.putString(

                        "picture", filePath);

requestParams.putString("name",

                         TheApplication.getInstance().getString(R.string.app_name));

requestParams.putString("link",
                           "http://url");
Permission:
  <string-array name="fb_advance_permissions">

        <item>manage_pages</item>

   </string-array> 

1.) Retrieve login user's page list

This method retrieve page list created by login user. manage_page permission required to fetch user's page list.
/**

     * retrieve facebook user page list and ask for permission

     * 

     * @param pageListener

     *            - call success, error

     */

    public static void getUserPageList(

            final IFacebookCommonListener<String> pageListener) {

        Session session = Session.getActiveSession();

        sFBRedirectionState = FbRedirectionState.GET_PAGE_LIST;

        getPagesCallback = pageListener;



        if (getPagesCallback == null) {

            return;

        }

        if (session != null) {

            // if (!session.isOpened()) {

            // openSession();

            // }



            if (!session.isOpened()) {

                Logs.d(DEBUG_FACEBOOK_PUBLISH,

                        "Page error: !session.isOpened()");

                closeSession();

                openSession();

              

                return;

            }



            if (!canRetrievePages() && !isPagePermissionCalled) {

                getPagesPermissions(mStatusCallback);

                isPagePermissionCalled = true;

                return;

            }



            if (!canRetrievePages() && isPagePermissionCalled) {

                if (pageListener != null) {

                    pageListener.onError("Facebook can't retrieve pages");

                }

                session.removeCallback(statusCallback);

                sFBRedirectionState = FbRedirectionState.NONE;

                isPagePermissionCalled = false;

                return;

            }



            try {

                /* make the API call */

                Request request = new Request(session, "/me/accounts", null,

                        HttpMethod.GET, new Request.Callback() {

                            public void onCompleted(Response response) {

                                /* handle the result */

                                Logs.e(TAG, "Response:" + response);

                                if (response.getError() == null) {

                                    Logs.d("Pages",

                                            "Page success"

                                                    + response.getRawResponse());

                                    if (pageListener != null) {

                                        

                                        pageListener.onSuccess(response

                                                .getRawResponse());

                                    }

                                } else {

                                    Logs.d("Pages", "Page error: "

                                            + response.getError()

                                                    .getErrorMessage());

                                    if (pageListener != null) {

                                        pageListener

                                                .onError("Facebook can't retrieve pages");

                                    }

                                }

                            }

                        });



                Bundle requestParams = request.getParameters();

                requestParams.putString("access_token",

                        session.getAccessToken());

                request.setParameters(requestParams);

                request.executeAsync();

            } catch (Exception e) {

                // TODO: handle exception

                if (pageListener != null)

                    pageListener.onError("Facebook can't retrieve pages");

            }

            sFBRedirectionState = FbRedirectionState.NONE;

            getPagesCallback = null;

            isPagePermissionCalled = false;

        } else {

            startLogin();

        }

    }

2.) This method check for permission.
Check user has authorize permission or not.
/**

     * check for user's has taken manage_pages permission

     * 

     * @return

     */

    private static boolean canRetrievePages() {

        Session session = FacebookHelper.getSession();

        if (session != null) {

            try {

                if (!session.isOpened()) {

                    openSession();

                } else {

                    List<String> grantedPermissions = session.getPermissions();

                    String[] publishPermissions = mActivity.getResources()

                            .getStringArray(R.array.fb_advance_permissions);

                    return grantedPermissions.containsAll(Arrays

                            .asList(publishPermissions));

                }

            } catch (FacebookException e) {

                Logs.d(TAG, e);

            } catch (Exception e) {

                Logs.d(TAG, e);

            }

        }

        return false;

    }

3.) Ask user for permission
If user has not authorize permission. we have to authorize user for manage_page permission. We can use below method to ask for permission from user.
    /**

     * ask user for page permission.

     * 

     * @param callback

     */

    public static synchronized void getPagesPermissions(StatusCallback callback) {

        Session session = FacebookHelper.getSession();

        if (session != null) {

            try {

                if (!session.isOpened()) {

                    openSession();

                }

                List<String> grantedPermissions = session.getPermissions();

                List<String> neededPermissions = new ArrayList<String>();

                String[] publishPermissions = mActivity.getResources()

                        .getStringArray(R.array.fb_advance_permissions);

                for (String p : publishPermissions) {

                    if (!grantedPermissions.contains(p)) {

                        neededPermissions.add(p);

                    }

                }

                if (!neededPermissions.isEmpty()) {

                    if (callback != null) {

                        session.removeCallback(callback);

                        session.addCallback(callback);

                    }

                    Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(

                            mActivity, neededPermissions);

                    session.requestNewPublishPermissions(newPermissionsRequest);

                }

            } catch (FacebookException e) {

                Logs.e(TAG, e);

            } catch (Exception e) {

                Logs.e(TAG, e);

            }

        }

    }
4.) Post on Fan page in background.
We require page token which is we got from page list data. we get this token from page related data. This token used for publish status on user's page. Page id required on which we want to post data.
/**

     *  This method publish status on fan page

     * @param requestParams - requested param

     * @param uploadListener - for success, failure callback

     */

    public static void postOnFanPage(Bundle requestParams,

            final IFacebookCommonListener<Void> uploadListener) {



        requestParams.putString("access_token",

                Preferences.getFaceBookPageToken());



        Request request = new Request(Session.getActiveSession(),

                Preferences.getFacebookPageId() + "/feed", requestParams,

                HttpMethod.POST, new Request.Callback() {

                    public void onCompleted(Response response) {

                        /* handle the result */

                        if (response != null) {

                            Logs.d(TAG,

                                    "Page: publish reponse:"

                                            + response.toString());



                            FacebookRequestError error = response.getError();

                            if (error != null) {

                                Logs.d(TAG,

                                        "Page: publish Errror:"

                                                + error.getErrorMessage());



                                if (uploadListener != null) {

                                    uploadListener

                                            .onError("Facebook can't publish your content");

                                }



                            } else {



                                if (uploadListener != null) {

                                    uploadListener.onSuccess(null);

                                }



                            }

                        }



                    }

                });

        requestParams.remove("message");

        request.setParameters(requestParams);

        request.executeAsync();

    }
5.) Post on Fan page using feed dialog.
 Some time we need to post on user's fan page using feed dialog. for that we can use below method.

requestParams.putString("access_token",

                             Preferences.getFaceBookPageToken()); 


private static void publishPageFeedDialog(Bundle params) {

        WebDialog feedDialog = (new WebDialog.FeedDialogBuilder(mActivity,

                Session.getActiveSession(), params)).setOnCompleteListener(

                new WebDialog.OnCompleteListener() {

                    @Override

                    public void onComplete(Bundle values,

                            FacebookException error) {

                        if (error != null) {

                            if (!(error instanceof FacebookOperationCanceledException)) {

                                mActivity.informUser(mActivity

                                        .getString(R.string.bback_shared_facebook_failed));

                            }

                            Logs.e("FACEBOOK_ANDROID", "error", error);

                        } else if (values != null

                                && values.containsKey("post_id")) {

                            mActivity.informUser(mActivity

                                    .getString(R.string.bback_shared_facebook_success));

                        }

                    }

                }).setFrom(String.valueOf(Preferences.getFacebookPageId())).build();

        feedDialog.show();

    }

I have put method here from project. So might be some reference class or not there.   
You can get basic idea how we can integrate.


Screen with FanPage list.




References:

https://developers.facebook.com/docs/graph-api/reference/v2.1/page
https://developers.facebook.com/docs/facebook-login/access-tokens#pagetokens https://developers.facebook.com/docs/graph-api/reference/v2.0/user/accounts https://developers.facebook.com/docs/sharing/reference/feed-dialog/v2.1
Please share in comment if you are facing any problem.

10 comments:

  1. This comment has been removed by the author.

    ReplyDelete

  2. All are saying the same thing repeatedly, but in your blog I had a chance to get some useful and unique information, I love your writing style very much, I would like to suggest your blog in my dude circle, so keep on updates.



    SAP training in Chennai
    SAP ABAP training in Chennai
    SAP FICO training in Chennai
    SAP MM training in Chennai
    SAP SD training in Chennai
    SAP HR training in Cheennai

    ReplyDelete
  3. It was a great information about Status and fans page.the author presented his programming skill very well. Thanks for sharing such an amazing article.
    Marine Colleges in Chennai, Nautical Science Colleges In Chennai

    ReplyDelete
  4. Good work…unique site and interesting too… keep it up…looking forward for more updates.Good luck to all of you and thanks so much for your hard-work.

    Language Interpretation Services, Voiceover Bangalore


    ReplyDelete
  5. Good post.Thank you for sharing your valuable information.moviebox for mac

    ReplyDelete
  6. Look at the way my colleague Wesley Virgin's adventure begins in this SHOCKING and controversial video.

    Wesley was in the army-and soon after leaving-he discovered hidden, "SELF MIND CONTROL" secrets that the government and others used to get everything they want.

    As it turns out, these are the exact same SECRETS tons of celebrities (especially those who "come out of nothing") and the greatest business people used to become rich and famous.

    You've heard that you only use 10% of your brain.

    That's because most of your BRAINPOWER is UNCONSCIOUS.

    Maybe that conversation has even taken place INSIDE OF YOUR very own brain... as it did in my good friend Wesley Virgin's brain about 7 years ago, while riding an unregistered, garbage bucket of a car without a license and $3 in his bank account.

    "I'm absolutely frustrated with going through life paycheck to paycheck! Why can't I become successful?"

    You've taken part in those questions, ain't it right?

    Your success story is waiting to be written. All you have to do is in YOURSELF.

    Watch Wesley Virgin's Video Now!

    ReplyDelete
  7. Jio tv apk is getting everyone’s nerve as a most diverse live tv streaming platform. Specifically designed for the people in India having Jio SIM in their mobile phones.

    https://apkmodule.com/jio-tv-mod-apk/

    ReplyDelete