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.

31 comments:

  1. This comment has been removed by the author.

    ReplyDelete
    Replies
    1. Great Article android based projects

      Java Training in Chennai

      Project Center in Chennai

      Java Training in Chennai

      projects for cse

      The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training

      Delete
  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
  10. This is a very good tip especially to those fresh to the blogosphere.
    Simple but very precise info… Thanks for sharing this one.
    Android App Development Company in USA

    ReplyDelete
  11. The blog gave me idea about components of Python.They explained in effective manner.Thanks for sharing it. Keep sharing more blogs.

    Python Training in Chennai

    ReplyDelete
  12. 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
  13. Good post.Thank you for sharing your valuable information.moviebox for mac

    ReplyDelete
  14. This is a really fascinating attempt! which is very well explained and articulated particularly favorable circumstances to the accommodation industry. It's music to my ears.
    Thank you and yours!

    DedicatedHosting4u.com

    ReplyDelete
  15. 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
  16. This is the first & best article to make me satisfied by presenting good content. I feel so happy and delighted. Thank you so much for this article.
    internship for web development | internship in electrical engineering | mini project topics for it 3rd year | online internship with certificate | final year project for cse

    ReplyDelete
  17. 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