我在android上使用facebook sdk并且我想检查用户ID(在Toast上显示例如userID) 我写了一些代码,可以登录facebook现在我想在用户登录时想要通过吐司显示用户ID
这是我的代码,
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);
Intent in = new Intent(getApplicationContext(),
ChooseLocation.class);
startActivity(in);
Log.d("FB Sessions", "" + facebook.isSessionValid());
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(this,
new String[] { "email", "publish_stream" },
new DialogListener() {
@Override
public void onCancel() {
}
@Override
public void onComplete(Bundle values) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
try {
JSONObject me = new JSONObject(facebook
.request("me"));
String id = me.getString("id");
Toast.makeText(getApplicationContext(), id,
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
// TODO: handle exception
}
Intent in = new Intent(getApplicationContext(),
ChooseLocation.class);
startActivity(in);
}
@Override
public void onError(DialogError error) {
}
@Override
public void onFacebookError(FacebookError fberror) {
}
});
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
}
}
答案 0 :(得分:1)
您可以调用此功能以在用户成功登录时获取用户信息。
public void getProfileInformation() {
mAsyncRunner.request("me", new RequestListener() {
@Override
public void onComplete(String response, Object state) {
Log.d("Profile", response);
String json = response;
try {
JSONObject profile = new JSONObject(json);
// getting id of the user
final String id = profile.getString("id");
// getting name of the user
final String name = profile.getString("name");
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), "Name: " + name + "\nID: " + id, 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) {
}
});
}
请参阅LogCat中的Log.d("Profile", response);
。它返回Json。
我想这会帮助你。