我想使用 Facebook SDK 3.0 for Android 来做一些简单的图形请求。由于我不会使用Fragment
s,因此我无法使用 Facebook 开发人员文档中发布的示例。
我已经设置了一些简单Activity
的 s,但它们不起作用。我在这里和这里提出了赏金问题。但这并没有真正帮助。
与此同时,我阅读了很多关于 Facebook SDK 的帖子并尝试了数十个小时,但没有成功。最后,我在这个博客上找到了一个额外的代码示例。所以我设置了一个完整Activity
的,将所有朋友的家乡打印到LogCat。
但这也不起作用。相反,它只要求基本权限(公共信息+朋友列表)然后退出。我究竟做错了什么?Facebook 应用程序的密钥哈希、包名和类名已设置,LogCat 中没有任何有趣的内容。
package com.my.package;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.Toast;
import com.facebook.*;
public class FBRequest extends Activity {
private static final String PERMISSION_FRIENDS_HOMETOWN = "friends_hometown";
private static final String PREFERENCE_ACCESS_TOKEN = "facebookAccessToken";
private static final String PREFERENCE_EXPIRATION_DATE = "facebookAccessTokenExpires";
private ProgressDialog mProgress;
private SharedPreferences mPrefs;
private void showToast(final String text) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
}
});
}
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
try {
startFacebookRequest();
}
catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session session = Session.getActiveSession();
if (session != null) {
session.onActivityResult(this, requestCode, resultCode, data);
}
}
public interface FacebookConnectHandler {
public void onSuccess();
public void onFailure();
}
public void startFacebookRequest() {
connectToFacebook(new FacebookConnectHandler() {
@Override
public void onSuccess() {
// safety check
if (isFinishing()) { return; }
showProgressDialog("Connecting to Facebook ...");
// check for publish permissions
final List<String> permissions_required = Arrays.asList(PERMISSION_FRIENDS_HOMETOWN);
if (Session.getActiveSession().getPermissions() == null || !Session.getActiveSession().getPermissions().containsAll(permissions_required)) {
// need to make a Session.openActiveSessionFromCache(...) call
// because of a bug in the Facebook sdk
// where a second call to get permissions
// won't result in a session callback when the token is updated
if (Session.openActiveSessionFromCache(FBRequest.this) == null) {
showToast("Could not connect to Facebook! (3)");
return;
}
Session.getActiveSession().addCallback(new Session.StatusCallback() {
@Override
public void call(Session session, SessionState state, Exception exception) {
if (exception != null || state.equals(SessionState.CLOSED) || state.equals(SessionState.CLOSED_LOGIN_FAILED)) {
// didn't get required permissions
session.removeCallback(this);
// safety check
if (!isFinishing()) {
showToast("Could not connect to Facebook! (4)");
}
}
else if (state.equals(SessionState.OPENED_TOKEN_UPDATED) && session.getPermissions().containsAll(permissions_required)) {
// got required permissions
session.removeCallback(this);
// safety check
if (!isFinishing()) {
startFacebookRequest();
}
}
}
});
Session.getActiveSession().requestNewReadPermissions(new Session.NewPermissionsRequest(FBRequest.this, permissions_required));
return;
}
startGraphRequest(Session.getActiveSession());
}
@Override
public void onFailure() {
cancelProgressDialog();
showToast("Could not connect to Facebook! (1)");
}
});
}
private void startGraphRequest(Session session) {
Request.executeGraphPathRequestAsync(session, "me/friends/?access_token="+session.getAccessToken()+"&fields=id,name,hometown&limit=500", new Request.Callback() {
@Override
public void onCompleted(Response response) {
if (response != null) {
try {
JSONArray jarr = response.getGraphObject().getInnerJSONObject().getJSONArray("data");
JSONObject entry;
StringBuilder backupStr = new StringBuilder();
int nExistingEntries = existingEntries.length;
for (int i = 0; i < jarr.length(); i++) {
entry = jarr.getJSONObject(i);
if (!entry.isNull("id") && !entry.isNull("name") && !entry.isNull("hometown")) {
System.out.println(entry.getString("hometown"));
}
}
}
catch (Exception e) {
e.printStackTrace();
showToast("Unexpected error!");
}
}
}
});
}
private void connectToFacebook(final FacebookConnectHandler handler) {
// check whether the user already has an active session
// and try opening it if we do
// (note: making a Session.openActiveSessionFromCache(...) call
// instead of simply checking whether the active session is opened
// because of a bug in the Facebook sdk
// where successive calls to update a token
// (requesting additional permissions etc)
// don't result in a session callback)
if (Session.getActiveSession() != null && Session.openActiveSessionFromCache(this) != null) {
handler.onSuccess();
return;
}
// initialise the session status callback
Session.StatusCallback callback = new Session.StatusCallback() {
@Override
public void call(Session session, SessionState state, Exception exception) {
if (isFinishing()) { return; }
// check session state
if (state.equals(SessionState.CLOSED) || state.equals(SessionState.CLOSED_LOGIN_FAILED)) {
clearFacebookSharedPreferences();
// specific action for when the session is closed
// because an open-session request failed
if (state.equals(SessionState.CLOSED_LOGIN_FAILED)) {
cancelProgressDialog();
handler.onFailure();
}
}
else if (state.equals(SessionState.OPENED)) {
cancelProgressDialog();
saveFacebookSharedPreferences(session.getAccessToken(), session.getExpirationDate().getTime());
showToast("Succeeded connecting to Facebook");
handler.onSuccess();
}
}
};
// make the call to open the session
showProgressDialog("Connecting to Facebook...");
if (Session.getActiveSession() == null && mPrefs.contains(PREFERENCE_ACCESS_TOKEN) && mPrefs.contains(PREFERENCE_EXPIRATION_DATE)) {
// open a session from the access token info
// saved in the app's shared preferences
String accessTokenString = mPrefs.getString(PREFERENCE_ACCESS_TOKEN, "");
Date accessTokenExpires = new Date(mPrefs.getLong(PREFERENCE_EXPIRATION_DATE, 0));
AccessToken accessToken = AccessToken.createFromExistingAccessToken(accessTokenString, accessTokenExpires, null, null, null);
Session.openActiveSessionWithAccessToken(this, accessToken, callback);
}
else {
// open a new session, logging in if necessary
Session.openActiveSession(this, true, callback);
}
}
private void saveFacebookSharedPreferences(final String token, final long expiration) {
if (mPrefs != null) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString(PREFERENCE_ACCESS_TOKEN, token);
editor.putLong(PREFERENCE_EXPIRATION_DATE, expiration);
editor.commit();
}
}
private void clearFacebookSharedPreferences() {
if (mPrefs != null) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.remove(PREFERENCE_ACCESS_TOKEN);
editor.remove(PREFERENCE_EXPIRATION_DATE);
editor.commit();
}
}
private void showProgressDialog(final String text) {
mProgress = ProgressDialog.show(getApplicationContext(), "Facebook", text, true, false);
}
private void cancelProgressDialog() {
if (mProgress != null) {
if (mProgress.isShowing()) {
mProgress.dismiss();
}
mProgress = null;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
cancelProgressDialog();
}
}
提前致谢!
编辑:代码确实有效,但我没有调用setContentView()
,并且在一个错误情况下调用了Activity
's 。finish()
这就是为什么无法看到第二个(扩展)权限请求的原因。