gpt4 book ai didi

java - 如何使用 facebook sdk 版本 3.22.0 从 Facebook 登录获取 emailid

转载 作者:行者123 更新时间:2023-11-30 01:47:15 35 4
gpt4 key购买 nike

我只使用了一个按钮,当我点击按钮时我想获取电子邮件 ID。这是我的代码并获取 ID 和名称,但无法获取 emailid。我正在使用 facebook sdk 版本 3.22.0 请帮助我。

在此输入验证码

包 com.example.testintegration;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;

import org.json.JSONException;
import org.json.JSONObject;

import com.example.testfbintegration.R;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.facebook.model.GraphUser;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

private static String APP_ID = "862722850469774"; // Replace with your App ID

// Instance of Facebook Class
private Facebook facebook = new Facebook(APP_ID);
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;

// Buttons
Button btnFbLogin;
/*Button btnFbGetProfile;
Button btnPostToWall;
Button btnShowAccessTokens;*/


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);


btnFbLogin = (Button) findViewById(R.id.btn_fblogin);
/*btnFbGetProfile = (Button) findViewById(R.id.btn_get_profile);
btnPostToWall = (Button) findViewById(R.id.btn_fb_post_to_wall);
btnShowAccessTokens = (Button) findViewById(R.id.btn_show_access_tokens);*/
mAsyncRunner = new AsyncFacebookRunner(facebook);

/**
* Login button Click event
* */
btnFbLogin.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
Log.d("Image Button", "button Clicked");
//loginToFacebook();
logfacebook();
}
});

/**
* Getting facebook Profile info
* *//*
btnFbGetProfile.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
getProfileInformation();
}
});

*//**
* Posting to Facebook Wall
* *//*
btnPostToWall.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
postToWall();
}
});

*//**
* Showing Access Tokens
* *//*
btnShowAccessTokens.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
showAccessTokens();
}
});*/




}

public void logfacebook()
{
Session.openActiveSession(MainActivity.this, true, new Session.StatusCallback() {

// callback when session changes state
@Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {

// make request to the /me API
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {

// callback after Graph API response with user object
@Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
System.out.println(user.getName());
System.out.println(user.getBirthday());
System.out.println(user.getFirstName());
System.out.println(user.getLastName());
System.out.println(user.getLink());
System.out.println(user.getUsername());
System.out.println(user.getLocation());
System.out.println("facebook user id" + user.getId());
System.out.println(user.asMap().get("email").toString());
// Session.OpenRequest open = new Session.OpenRequest(Login)
}
}
});
}
}
});
}
/**
* Function to login into facebook
* */
public void loginToFacebook() {

mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);

if (access_token != null) {
facebook.setAccessToken(access_token);

btnFbLogin.setVisibility(View.INVISIBLE);

// Making get profile button visible
// btnFbGetProfile.setVisibility(View.VISIBLE);

// Making post to wall visible
//btnPostToWall.setVisibility(View.VISIBLE);

// Making show access tokens button visible
//btnShowAccessTokens.setVisibility(View.VISIBLE);

Log.d("FB Sessions", "" + facebook.isSessionValid());
}

if (expires != 0) {
facebook.setAccessExpires(expires);
}

if (!facebook.isSessionValid()) {
facebook.authorize(this,
new String[] { "email", "publish_actions" },
new DialogListener() {

@Override
public void onCancel() {
// Function to handle cancel event
}

@Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();

// Making Login button invisible
btnFbLogin.setVisibility(View.INVISIBLE);

// Making logout Button visible
// btnFbGetProfile.setVisibility(View.VISIBLE);

// Making post to wall visible
//btnPostToWall.setVisibility(View.VISIBLE);

// Making show access tokens button visible
//btnShowAccessTokens.setVisibility(View.VISIBLE);
}

@Override
public void onError(DialogError error) {
// Function to handle error

}

@Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors

}

});
}
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
}


/**
* Get Profile information by making request to Facebook Graph API
* */
public void getProfileInformation() {
mAsyncRunner.request("me", new RequestListener() {
@Override
public void onComplete(String response, Object state) {
Log.d("Profile", response);
String json = response;
try {
// Facebook Profile JSON data
JSONObject profile = new JSONObject(json);

// getting name of the user
final String name = profile.getString("name");

// getting email of the user
final String email = profile.getString("email");

runOnUiThread(new Runnable() {

@Override
public void run() {
Toast.makeText(getApplicationContext(), "Name: " + name + "\nEmail: " + email, Toast.LENGTH_LONG).show();
}

});


} catch (JSONException e) {
e.printStackTrace();
}
}

@Override
public void onIOException(IOException e, Object state) {
}

@Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
}

@Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
}

@Override
public void onFacebookError(FacebookError e, Object state) {
}
});
}

/**
* Function to post to facebook wall
* */
public void postToWall() {
// post on user's wall.
facebook.dialog(this, "feed", new DialogListener() {

@Override
public void onFacebookError(FacebookError e) {
}

@Override
public void onError(DialogError e) {
}

@Override
public void onComplete(Bundle values) {
}

@Override
public void onCancel() {
}
});

}

/**
* Function to show Access Tokens
* */
public void showAccessTokens() {
String access_token = facebook.getAccessToken();

Toast.makeText(getApplicationContext(),
"Access Token: " + access_token, Toast.LENGTH_LONG).show();
}

/**
* Function to Logout user from Facebook
* */
public void logoutFromFacebook() {
mAsyncRunner.logout(this, new RequestListener() {
@Override
public void onComplete(String response, Object state) {
Log.d("Logout from Facebook", response);
if (Boolean.parseBoolean(response) == true) {
runOnUiThread(new Runnable() {

@Override
public void run() {
// make Login button visible
btnFbLogin.setVisibility(View.VISIBLE);

// making all remaining buttons invisible
/*btnFbGetProfile.setVisibility(View.INVISIBLE);
btnPostToWall.setVisibility(View.INVISIBLE);
btnShowAccessTokens.setVisibility(View.INVISIBLE);*/
}

});

}
}

@Override
public void onIOException(IOException e, Object state) {
}

@Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
}

@Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
}

@Override
public void onFacebookError(FacebookError e, Object state) {
}
});
}

}

最佳答案

使用此代码。

LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback() {

        @Override
public void onSuccess(LoginResult result) {
new GraphRequest();
// SocialSdkPrefrences.getInstance().setAccessToken(result.getAccessToken().getToken());
GraphRequest request = GraphRequest.newMeRequest(result.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {

@Override
public void onCompleted(JSONObject object, GraphResponse response) {
Profile profile = Profile.getCurrentProfile();
FacebookGraphUser fbGraphUser = (FacebookGraphUser) JsonUtil.toModel(response.getRawResponse(), FacebookGraphUser.class);
if (fbGraphUser != null) {
String image_url = "http://graph.facebook.com/" + fbGraphUser.getId() + "/picture?type=large";

// UniversalImageLoaderUtil.loadImageWithDefaultImage(image_url, (ImageView) findViewById(R.id.user_image), null, R.drawable.place_holder_album);
User user=new User(fbGraphUser.getEmail(),image_url,profile.getName(),Long.parseLong(fbGraphUser.getId()));
Gson gson = new Gson();
Log.d("social", gson.toJson(user));
if (fbGraphUser.getEmail() != null) {
if (Util.isValidEmail(fbGraphUser.getEmail())) {
new SocialLogInAsyncTask(LoginActivity.this, user).execute();
} else {
Toast.showShortToast(LoginActivity.this, "You have not valid email,cant login");
}
} else {
Toast.showShortToast(LoginActivity.this, "You have not email,cant login");
}
} else {
Toast.showErrorToast(LoginActivity.this, R.string.error_signup);
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender,birthday,picture.width(300)");
request.setParameters(parameters);
request.executeAsync();

}

@Override
public void onCancel() {
Log.d("tag", "cancel facebook login");
}

@Override
public void onError(FacebookException error) {
Log.d("tag", "error in login" + error.getMessage());
}
});

关于java - 如何使用 facebook sdk 版本 3.22.0 从 Facebook 登录获取 emailid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33543929/

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