使用Android上的访问令牌创建Facebook会话对象



我正在尝试以下操作:

  1. 在一个Android手机上,我正在使用Facebook授权我的应用程序,并将访问令牌存储在共享的偏好中。
  2. 将此访问令牌发送到第二个Android设备(一些不同的应用程序具有同一Appkey的Facebook。
  3. 现在,我无法在第二个设备上使用此访问令牌创建会话。第二个设备没有UI,因此我无法使用Web/FB本机应用程序授权。

问题:我的问题是如何使用此传递的访问令牌创建一个Facebook会话来访问API。如果有人可以指出一个示例,将会更有帮助。

在facebook SDK最终的Facebook SDK上,API已更改,@RightParen建议的答案将无效。在新的API中,关键是使用 Session.openActiveSessionWithAccessToken() 静态方法。该方法设计用于从FB SDK 2.X到3.x的迁移。

以下代码对我有用。

@SuppressWarnings("deprecation")
public static void migrateFbTokenToSession() {
    Facebook facebook = Utils.getFacebookObject();
    AccessToken accessToken = AccessToken.createFromExistingAccessToken(facebook.getAccessToken(), new Date(facebook.getAccessExpires()),
            new Date(facebook.getLastAccessUpdate()), AccessTokenSource.FACEBOOK_APPLICATION_NATIVE, Arrays.asList(Constants.FB_APP_PERMISSIONS));
    Session.openActiveSessionWithAccessToken(ICheezApplication.getContext(), accessToken , new Session.StatusCallback() {
        @Override
        public void call(Session session, SessionState state, Exception exception) {
            sLogger.debug("fbshare Migration to newer icheez state has been successful");
            if(session != null && session.isOpened()) {
                Session.setActiveSession(session);
            }
        }
    });
}

此功能可以通过覆盖默认的sdk缓存令状状态来迁移您现有的令牌状态,并带有您传递的参数:

private final void migrateToken(String accessToken, long expiresMilliseconds,
                                List<String> permissions, boolean isSSO,
                                long lastRefreshMilliseconds) {
    Bundle bundle = new Bundle();
    TokenCache.putToken(bundle, accessToken);
    TokenCache.putExpirationMilliseconds(bundle, expiresMilliseconds);
    TokenCache.putPermissions(bundle, permissions);
    TokenCache.putLastRefreshMilliseconds(bundle, lastRefreshMilliseconds);
    TokenCache.putIsSSO(bundle, isSSO);
    SharedPreferencesTokenCache cache = new SharedPreferencesTokenCache(this);
    cache.save(bundle);
}

如果您没有保存的权限,则应通过在获得令牌或空阵列时要求的权限列表,如果您不要求或不知道。

ISSSO参数指定您使用Facebook登录/SSO(true)或登录WebView(false)使用Facebook登录/SSO获得令牌。可以扩展通过Facebook登录获得的令牌,此布尔人控制SDK是否应自动尝试扩展令牌。

此功能覆盖会话构造函数读取的状态。因此,如果您调用该函数,则需要构建会话以使用它。逻辑可能看起来像:

    Session session = Session.openActiveSession(this);
    if ((session == null) && hasOldTokenState()) {
        migrateToken(...);
        session = Session.openActiveSession(this);
    }
    // if session is still null, user will have to log in...

不知道如何获取该访问令牌并授权用户,但是我正在使用以下代码来创建会话,如果会话无效。

private SessionListener mSessionListener = new SessionListener();
Utility.mFacebook = new Facebook(APP_ID);
Utility.mAsyncRunner = new AsyncFacebookRunner(Utility.mFacebook);
SessionStore.restore(Utility.mFacebook, getApplicationContext());
SessionEvents.addAuthListener(mSessionListener);
SessionEvents.addLogoutListener(mSessionListener);

我的SessionEvent类是:

公共类SessionEvents {

private static LinkedList<AuthListener> mAuthListeners = new LinkedList<AuthListener>();
private static LinkedList<LogoutListener> mLogoutListeners = new LinkedList<LogoutListener>();
/**
 * Associate the given listener with this Facebook object. The listener's
 * callback interface will be invoked when authentication events occur.
 * 
 * @param listener
 *            The callback object for notifying the application when auth
 *            events happen.
 */
public static void addAuthListener(AuthListener listener) {
    mAuthListeners.add(listener);
}
/**
 * Remove the given listener from the list of those that will be notified
 * when authentication events occur.
 * 
 * @param listener
 *            The callback object for notifying the application when auth
 *            events happen.
 */
public static void removeAuthListener(AuthListener listener) {
    mAuthListeners.remove(listener);
}
/**
 * Associate the given listener with this Facebook object. The listener's
 * callback interface will be invoked when logout occurs.
 * 
 * @param listener
 *            The callback object for notifying the application when log out
 *            starts and finishes.
 */
public static void addLogoutListener(LogoutListener listener) {
    mLogoutListeners.add(listener);
}
/**
 * Remove the given listener from the list of those that will be notified
 * when logout occurs.
 * 
 * @param listener
 *            The callback object for notifying the application when log out
 *            starts and finishes.
 */
public static void removeLogoutListener(LogoutListener listener) {
    mLogoutListeners.remove(listener);
}
public static void onLoginSuccess() {
    for (AuthListener listener : mAuthListeners) {
        listener.onAuthSucceed();
    }
}
public static void onLoginError(String error) {
    for (AuthListener listener : mAuthListeners) {
        listener.onAuthFail(error);
    }
}
public static void onLogoutBegin() {
    for (LogoutListener l : mLogoutListeners) {
        l.onLogoutBegin();
    }
}
public static void onLogoutFinish() {
    for (LogoutListener l : mLogoutListeners) {
        l.onLogoutFinish();
    }
}
/**
 * Callback interface for authorization events.
 */
public static interface AuthListener {
    /**
     * Called when a auth flow completes successfully and a valid OAuth
     * Token was received. Executed by the thread that initiated the
     * authentication. API requests can now be made.
     */
    public void onAuthSucceed();
    /**
     * Called when a login completes unsuccessfully with an error.
     * 
     * Executed by the thread that initiated the authentication.
     */
    public void onAuthFail(String error);
}
/**
 * Callback interface for logout events.
 */
public static interface LogoutListener {
    /**
     * Called when logout begins, before session is invalidated. Last chance
     * to make an API call. Executed by the thread that initiated the
     * logout.
     */
    public void onLogoutBegin();
    /**
     * Called when the session information has been cleared. UI should be
     * updated to reflect logged-out state.
     * 
     * Executed by the thread that initiated the logout.
     */
    public void onLogoutFinish();
}

}

可能会帮助您。

最新更新