在android中使用最新的facebook sdk获取好友列表

时间:2014-12-26 13:15:40

标签: android facebook-graph-api android-facebook

MainActivity.java

public class MainActivity extends ActionBarActivity {

RequestAsyncTask task = null;
private SharedPreferences preferences;

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

private static final List<String> PERMISSIONSFRD = Arrays
        .asList("user_friends");

private static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization";
private boolean pendingPublishReauthorization = false;

private LoginButton btn_fb_login;
private UiLifecycleHelper uiHelper;
private PendingAction pendingAction = PendingAction.NONE;
private GraphUser user;
private final String PENDING_ACTION_BUNDLE_KEY = "com.facebook.samples.hellofacebook:PendingAction";

private enum PendingAction {
    NONE, POST_PHOTO, POST_STATUS_UPDATE
}

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.e("HelloFacebook", String.format("Error: %s",
        // error.toString()));
    }

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

private Button btn_share_fb;
Button  btn_frds;
private boolean isShareProcess = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    uiHelper = new UiLifecycleHelper(this, callback);
    uiHelper.onCreate(savedInstanceState);

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

    System.out.println("Start");
    Log.e("FB LOGIN--->", "----->Login");

    setContentView(R.layout.activity_main);

    preferences = PreferenceManager
            .getDefaultSharedPreferences(getApplicationContext());

    btn_share_fb = (Button) findViewById(R.id.btn_share_fb);
    btn_frds = (Button)findViewById(R.id.btn_frds);

    btn_frds.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            getFrdList();
        }
    });

    btn_fb_login = (LoginButton) findViewById(R.id.btn_fb_login);

    btn_fb_login.setReadPermissions(Arrays.asList("basic_info", "email",
            "user_birthday", "user_location"));

    btn_fb_login.setUserInfoChangedCallback(new UserInfoChangedCallback() {

        @Override
        public void onUserInfoFetched(GraphUser user) {
            // TODO Auto-generated method stub

            MainActivity.this.user = user;
            try {
                Session session = Session.getActiveSession();
                boolean enableButtons = (session != null && session
                        .isOpened());
                if (enableButtons && user != null) {
                     Log.e("-->", "" + session.getPermissions());
                     Log.e("fb user.getId", "" + user.getId());
                     Log.e("fb user.getFirstName",
                     "" + user.getFirstName());
                     Log.e("fb user.getMiddleName",
                     "" + user.getMiddleName());
                     Log.e("fb user.getLastName",
                     "" + user.getLastName());
                     Log.e("fb user.getUsername",
                     "" + user.getUsername());
                     Log.e("fb user.getBirthday",
                     "" + user.getBirthday());
                     Log.e("fb user.getLocation",
                     "" + user.getLocation());
                     Log.e("fb user.gender",
                     ""
                     + user.asMap().get("gender")
                     .toString());
                     Log.e("fb user email", "Email "
                     + user.asMap().get("email"));

                    AccessToken = session.getAccessToken();

                    Editor PEDIT = preferences.edit();
                    PEDIT.putBoolean(
                            GeneralClass.temp_isFbLoginShare, true);
                    PEDIT.commit();

                    setFbLoginDetails1();

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

                    // btn_fb_login.setVisibility(View.VISIBLE);

                    Log.e("FB--->", "----> NOT LOGIN");

                    Editor PEDIT = preferences.edit();
                    PEDIT.putBoolean(
                            GeneralClass.temp_isFbLoginShare, false);
                    PEDIT.commit();
                }
            } catch (Exception e) {
                e.printStackTrace();
                // Log.e("error get facebook details-->",
                // "error get facebook details");
            }
            handlePendingAction();
        }
    });

    btn_share_fb.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            if(!FbSharing.checkUserFBLogin()){
                if (preferences.getBoolean(
                        GeneralClass.temp_isFbLoginShare, false) == true) {
                    // publishFeedDialog();
                    /**
                     * original method
                     * */
                    Session session = Session.getActiveSession();
                    boolean enableButtons = (session != null && session
                            .isOpened());
                    if (enableButtons) {
                        publishStory();
                        isShareProcess = true;
                    } else {
                        // Log.e("error:",
                        // "please login again in facebook");
                    }
                    // share();

                    // getListofFacebookFriend();
                } else {
                    GeneralClass.showToast("Please login with Facebook",
                            getApplicationContext());
                    btn_fb_login.setVisibility(View.VISIBLE);
                }
            }else if(FbSharing.checkUserFBLogin()){
                try {
                    publishStory();
                } catch (Exception e) {
                    // Log.e("error share facebook user",
                    // "error share facebook user");
                    e.printStackTrace();
                }
            }
        }
    });

    setFbLoginDetails();
}

protected void setFbLoginDetails() {

        if (FbSharing.checkUserFBLogin()) {
            btn_fb_login.setVisibility(View.GONE);
            btn_share_fb.setVisibility(View.VISIBLE);
        } else if (preferences.getBoolean(GeneralClass.temp_isFbLoginShare,
                false) == true) {
            btn_fb_login.setVisibility(View.GONE);
            btn_share_fb.setVisibility(View.VISIBLE);
        } else {
            btn_fb_login.setVisibility(View.GONE);
            btn_share_fb.setVisibility(View.VISIBLE);
    }

}

protected void setFbLoginDetails1() {

        if (FbSharing.checkUserFBLogin()) {
            btn_fb_login.setVisibility(View.GONE);
            btn_share_fb.setVisibility(View.VISIBLE);
        } else if (preferences.getBoolean(GeneralClass.temp_isFbLoginShare,
                false) == true) {
            btn_fb_login.setVisibility(View.VISIBLE);
            btn_share_fb.setVisibility(View.VISIBLE);
        } else {
            btn_fb_login.setVisibility(View.GONE);
            btn_share_fb.setVisibility(View.VISIBLE);
        }

}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);
    uiHelper.onActivityResult(requestCode, resultCode, data, dialogCallback);
}

@Override
protected void onResume() {
    super.onResume();
    uiHelper.onResume();

    // Call the 'activateApp' method to log an app event for use in
    // analytics and advertising reporting. Do so in
    // the onResume methods of the primary Activities that an app may be
    // launched into.
    AppEventsLogger.activateApp(this);

    updateUI("onResume");

}

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

@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 (pendingAction != PendingAction.NONE
            && (exception instanceof FacebookOperationCanceledException || exception instanceof FacebookAuthorizationException)) {
        new AlertDialog.Builder(MainActivity.this)
                .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("onSessionStateChange");
}


@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_PHOTO:
        // postPhoto();
        break;
    case POST_STATUS_UPDATE:
        // postStatusUpdate();
        break;
    }
}


private void updateUI(String fromWhere) {

    // Log.e("fromWhere", "" + fromWhere);

    Session session = Session.getActiveSession();
    boolean enableButtons = (session != null && session.isOpened());



    if (enableButtons && user != null) {


        AccessToken = session.getAccessToken();

        Editor PEDIT = preferences.edit();
        PEDIT.putBoolean(GeneralClass.temp_isFbLoginShare, true);
        PEDIT.commit();
        setFbLoginDetails();
    } else {

        Editor PEDIT = preferences.edit();
        PEDIT.putBoolean(GeneralClass.temp_isFbLoginShare, false);
        PEDIT.commit();
    }
}


public void share() {
    try {
        Session session = Session.getActiveSession();
        boolean enableButtons = (session != null && session.isOpened());
        if (enableButtons) {
            Bundle bundle = new Bundle();
            bundle.putString("caption", "Harlem Shake Launcher for Android");
            bundle.putString("description",
                    "Your android can do the Harlem Shake. Download it from google play");
            bundle.putString("link",
                    "https://play.google.com/store/apps/details?id=mobi.shush.harlemlauncher");
            bundle.putString("name", "Harlem Shake Launcher");
            bundle.putString("picture", "http://shush.mobi/bla.png");
            new WebDialog.FeedDialogBuilder(getApplicationContext(),
                    Session.getActiveSession(), bundle).build().show();
        }
    } catch (Exception e) {
        // Log.e("error share on facebook", "error share on facebook");
        e.printStackTrace();
    }
}


@SuppressWarnings("unused")
private void publishFeedDialog() {

    try {
        Session session = Session.getActiveSession();
        boolean enableButtons = (session != null && session.isOpened());
        if (enableButtons) {
            Bundle params = new Bundle();
            params.putString("name", "Facebook SDK for Android");
            params.putString("caption",
                    "Build great social apps and get more installs.");
            params.putString(
                    "description",
                    "The Facebook SDK for Android makes it easier and faster to develop Facebook integrated Android apps.");
            params.putString("link",
                    "https://developers.facebook.com/android");
            params.putString("picture",
                    "https://raw.github.com/fbsamples/ios-3.x-howtos/master/Images/iossdk_logo.png");

            WebDialog feedDialog = (new WebDialog.FeedDialogBuilder(
                    getApplicationContext(), Session.getActiveSession(),
                    params)).setOnCompleteListener(
                    new OnCompleteListener() {

                        @Override
                        public void onComplete(Bundle values,
                                FacebookException error) {
                            if (error == null) {
                                // When the story is posted, echo the
                                // success
                                // and the post Id.
                                final String postId = values
                                        .getString("post_id");
                                if (postId != null) {
                                    Toast.makeText(getApplicationContext(),
                                            "Posted story, id: " + postId,
                                            Toast.LENGTH_SHORT).show();
                                } else {
                                    // User clicked the Cancel button
                                    Toast.makeText(
                                            getApplicationContext()
                                                    .getApplicationContext(),
                                            "Publish cancelled",
                                            Toast.LENGTH_SHORT).show();
                                }
                            } else if (error instanceof FacebookOperationCanceledException) {
                                // User clicked the "x" button
                                Toast.makeText(
                                        getApplicationContext()
                                                .getApplicationContext(),
                                        "Publish cancelled",
                                        Toast.LENGTH_SHORT).show();
                            } else {
                                // Generic, ex: network error
                                Toast.makeText(
                                        getApplicationContext()
                                                .getApplicationContext(),
                                        "Error posting story",
                                        Toast.LENGTH_SHORT).show();
                            }
                        }

                    }).build();
            feedDialog.show();
        }
    } catch (Exception e) {
        // Log.e("error share on facebook", "error share on facebook");
        e.printStackTrace();
    }
}

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

private void publishStory() {
    Session session = Session.getActiveSession();

    if (session != null) {

        GeneralClass.showToast("Wait while we share in facebook",
                getApplicationContext());

        // Check for publish permissions
        List<String> permissions = session.getPermissions();
        if (!isSubsetOf(PERMISSIONS, permissions)) {
            pendingPublishReauthorization = true;
            Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(
                    this, PERMISSIONS);
            session.requestNewPublishPermissions(newPermissionsRequest);
            return;
        }

        Bundle postParams = new Bundle();
        postParams.putString("name", "Lolipop for Android");
        postParams.putString("caption",
                "Get better experience!");
        postParams.putString("description",
                "Get better experience!");
        postParams.putString("link",
                "https://developers.facebook.com/android");
        postParams
                .putString("picture",
                        "https://raw.github.com/fbsamples/ios-3.x-howtos/master/Images/iossdk_logo.png");

        Request.Callback callback = new Request.Callback() {
            public void onCompleted(Response response) {
                JSONObject graphResponse = response.getGraphObject()
                        .getInnerJSONObject();
                String postId = null;
                try {
                    postId = graphResponse.getString("id");
                } catch (JSONException e) {
                    Log.i("-->", "JSON error " + e.getMessage());
                }
                FacebookRequestError error = response.getError();
                if (error != null) {
                    Toast.makeText(getApplicationContext(),
                            error.getErrorMessage(), Toast.LENGTH_SHORT)
                            .show();
                    isShareProcess = false;
                } else {
                    Toast.makeText(
                            getApplicationContext(),
                            "Successfully Shared on Facebook, postid - "
                                    + postId, Toast.LENGTH_LONG).show();
                    isShareProcess = false;

                    new GetLists().execute();
                }

                task = null;
            }
        };

        Request request = new Request(session, "me/feed", postParams,
                HttpMethod.POST, callback);

        task = new RequestAsyncTask(request);
        task.execute();
    }

}

private void getFrdList() {
    Session session = Session.getActiveSession();

    if (session != null) {

        GeneralClass.showToast("Wait while we get List",
                getApplicationContext());

        // Check for publish permissions
        List<String> permissions = session.getPermissions();
        if (!isSubsetOf(PERMISSIONSFRD, permissions)) {
            pendingPublishReauthorization = true;
            Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(
                    this, PERMISSIONSFRD);
            session.requestNewPublishPermissions(newPermissionsRequest);
            return;
        }

        new Request(
                session,
                "/me/friends",
                null,
                HttpMethod.GET,
                new Request.Callback() {
                    public void onCompleted(Response response) {
                        /* handle the result */
                        JSONObject graphResponse = response.getGraphObject()
                                .getInnerJSONObject();
                        Log.e("JSON RESPONSE---->", "FRIEND LIST--->"+ graphResponse.toString());
                    }
                }).executeAsync();


    }

}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

@Override
public void onBackPressed() {
    // TODO Auto-generated method stub
    if (isShareProcess == false) {
        if (task != null) {
            // Log.e("back press", "wait for share");
        } else {
            task = null;
            // Log.e("back press", "no wait for share");
            super.onBackPressed();
        }
    }
}
}

上面的代码在点击朋友按钮时显示以下输出:

FRIEND LIST--->{"summary":{"total_count":10},"data":[]}

我不知道如何获取朋友列表。我已经为此做过R&amp; D.但没有得到实际的结果。我知道在最新的sdk中,它不可能得到所有的朋友,只有那些使用你的应用程序的人。我还尝试与两个不同的朋友一起运行我的应用程序。但仍然没有得到结果。

请帮助我解决这个问题。

1 个答案:

答案 0 :(得分:2)

从v2.0开始,无法获得所有朋友的列表。您只会获得授权您的应用程序的朋友。这就是为什么&#34;数据&#34;是空的。

有关详细信息,请参阅更改日志:https://developers.facebook.com/docs/apps/changelog

查看大量关于同一问题的其他主题,尤其是这一主题提供了更多信息:Facebook Graph Api v2.0+ - /me/friends returns empty, or only friends who also use my app