gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 20:56:12 25 4
gpt4 key购买 nike

主 Activity .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":[]}

我不知道如何获取好友列表。我已经为此做了研发。但没有得到实际结果。我知道在最新的 sdk 中,不可能得到所有的 friend ,而只能得到那些使用过你的应用程序的人。我还尝试与两个都是 friend 的不同用户一起运行我的应用程序。但仍然没有得到结果。

请帮我解决这个问题。

最佳答案

从 v2.0 开始,不可能再获得所有 friend 的列表。您只会得到那些也授权了您的应用程序的 friend 。这就是“数据”为空的原因。

查看更新日志以获取更多信息:https://developers.facebook.com/docs/apps/changelog

也查看关于完全相同问题的大量其他线程,尤其是这个提供了额外信息的线程:Facebook Graph Api v2.0+ - /me/friends returns empty, or only friends who also use my app

关于android - 在android中使用最新的facebook sdk获取好友列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27657669/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com