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.

11 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Embedded system training: Wiztech Automation Provides Excellent training in embedded system training in Chennai - IEEE Projects - Mechanical projects in Chennai Wiztech provide 100% practical training, Individual focus, Free Accommodation, Placement for top companies. The study also includes standard microcontrollers such as Intel 8051, PIC, AVR, ARM, ARMCotex, Arduino etc.

    Embedded system training in chennai
    Embedded Course training in chennai
    Matlab training in chennai
    Android training in chennai
    LabVIEW training in chennai
    Arduino training in chennai
    Robotics training in chennai
    Oracle training in chennai
    Final year projects in chennai
    Mechanical projects in chennai
    ece projects in chennai

    ReplyDelete
  3. WIZTECH Automation, Anna Nagar, Chennai, has earned reputation offering the best automation training in Chennai in the field of industrial automation. Flexible timings, hands-on-experience, 100% practical. The candidates are given enhanced job oriented practical training in all major brands of PLCs (AB, Keyence, ABB, GE-FANUC, OMRON, DELTA, SIEMENS, MITSUBISHI, SCHNEIDER, and MESSUNG)

    PLC training in chennai
    Automation training in chennai
    Best plc training in chennai
    PLC SCADA training in chennai
    Process automation training in chennai
    Final year eee projects in chennai
    VLSI training in chennai

    ReplyDelete
  4. Wiztech Automation is the Leading Best IEEE Final year project Centre in Chennai and the final year students are provided complete guidance and support in their final year projects. The IEEE projects in Chennai that Wiztech Automation offers guidance and support for include complete range of system domains – such as PLC projects, embedded projects, VLSI projects, software projects, IT projects, Civil projects. Students looking for specific projects pertaining to departments of ECE, EEE, E&I, Mechanical, Mechatronics, bio-medical, IT, Computer, Civil projects in B.E, M.E, B.Tech, M.Tech, B.SC., and M.Sc Electronics, could also get turnkey solutions at Wiztech Automation Solutions to turn out successful project outcomes and models. Since the students at Wiztech Automation gain thorough theoretical and practical knowledge and skills as they pursue their final year projects and develop 2015 and 2016 Latest IEEE Projects portraying them well.

    Final year projects in chennai
    Mechanical projects in chennai
    ece projects in chennai
    Final year eee projects in chennai
    VLSI project center in chennai
    Industrial projects in chennai
    Fianl year CSE projects in chennai

    ReplyDelete

  5. 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
  6. 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
  7. Such a great info provided in this post. Keep providing useful post in this blog .I appreciate author for this specific valuable post. Culinary Schools in Dubai , International Centre for Culinary Arts

    ReplyDelete
  8. The blog is absolutely truly incredible. Lots of large information and inspiration, both of which we all need.
    Bangalore Web Designing Company, UI Designing Company Bangalore

    ReplyDelete
  9. I absolutely admired every bit of it and i additionally accept you book apparent to analysis out fresh things in your site.
    UI Design Company Bangalore, Web Application Development Services in Bangalore

    ReplyDelete