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

在Android上使用访问令牌创建Facebook会话对象,android,facebook,facebook-android-sdk,Android,Facebook,Facebook Android Sdk,我正在尝试以下方法: 在一部android手机上,我正在使用Facebook授权我的应用程序,并将访问令牌存储在共享首选项中 将此访问令牌发送到第二个android设备(某些不同的应用程序具有相同的Facebook appKey) 现在,我无法在第二台设备上使用此访问令牌创建会话。第二台设备没有UI,因此我无法使用web/FB本机应用在那里进行授权 问题:我的问题是如何使用此已传递的访问令牌创建访问API的facebook会话。如果有人能指出一个示例,这将更有帮助。不知道如何获取该访问令牌并授权

我正在尝试以下方法:

  • 在一部android手机上,我正在使用Facebook授权我的应用程序,并将访问令牌存储在共享首选项中
  • 将此访问令牌发送到第二个android设备(某些不同的应用程序具有相同的Facebook appKey)
  • 现在,我无法在第二台设备上使用此访问令牌创建会话。第二台设备没有UI,因此我无法使用web/FB本机应用在那里进行授权

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

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

    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课程是:

    公共类会话事件{

    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();
    }
    
    private static LinkedList mAuthListeners=new LinkedList();
    私有静态LinkedList mLogoutListeners=新LinkedList();
    /**
    *将给定侦听器与此Facebook对象关联。侦听器的
    *发生身份验证事件时将调用回调接口。
    * 
    *@param侦听器
    *用于在身份验证时通知应用程序的回调对象
    *事情发生了。
    */
    公共静态无效addAuthListener(AuthListener listener){
    添加(侦听器);
    }
    /**
    *从将被通知的侦听器列表中删除给定的侦听器
    *当身份验证事件发生时。
    * 
    *@param侦听器
    *用于在身份验证时通知应用程序的回调对象
    *事情发生了。
    */
    公共静态void removeAuthListener(AuthListener listener){
    删除(侦听器);
    }
    /**
    *将给定侦听器与此Facebook对象关联。侦听器的
    *注销时将调用回调接口。
    * 
    *@param侦听器
    *用于在注销时通知应用程序的回调对象
    *开始和结束。
    */
    公共静态void addLogoutListener(LogoutListener侦听器){
    添加(监听器);
    }
    /**
    *从将被通知的侦听器列表中删除给定的侦听器
    *当注销发生时。
    * 
    *@param侦听器
    *用于在注销时通知应用程序的回调对象
    *开始和结束。
    */
    公共静态void removeLogoutListener(LogoutListener侦听器){
    删除(侦听器);
    }
    公共静态void onloginsucess(){
    for(AuthListener侦听器:MauthlListeners){
    listener.onAuthSucceed();
    }
    }
    公共静态void onlogin错误(字符串错误){
    for(AuthListener侦听器:MauthlListeners){
    onAuthFail(错误);
    }
    }
    公共静态void onLogoutBegin(){
    for(LogoutListener l:mLogoutListeners){
    l、 onLogoutBegin();
    }
    }
    公共静态void onLogoutFinish(){
    for(LogoutListener l:mLogoutListeners){
    l、 onLogoutFinish();
    }
    }
    /**
    *授权事件的回调接口。
    */
    公共静态接口AuthListener{
    /**
    *当验证流成功完成且OAuth有效时调用
    *已接收令牌。由启动令牌的线程执行
    *认证。现在可以进行API请求。
    */
    成功()的公共无效;
    /**
    *当登录失败并出现错误时调用。
    * 
    *由启动身份验证的线程执行。
    */
    authFail上的公共void(字符串错误);
    }
    /**
    *注销事件的回调接口。
    */
    公共静态接口LogoutListener{
    /**
    *在会话无效之前,在注销开始时调用。最后一次机会
    *进行API调用。由启动
    *注销。
    */
    public void onLogoutBegin();
    /**
    *在清除会话信息时调用。UI应为
    *已更新以反映注销状态。
    * 
    *由启动注销的线程执行。
    */
    public void onLogoutFinish();
    }
    
    }


    可能会对您有所帮助。

    此函数可以通过使用您传入的参数覆盖默认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);
    }
    

    截至facebook sdk for Android 3.0 final,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);
                }
            }
        });
    
    }
    

    您在代码中使用的是Facebook类,根据下面链接中的Facebook类文档,该类已被弃用/不推荐,@SpcFbone:好的。我正在谈论我以前使用的内容,对我帮助很大。可能对您有帮助。[1]在您的代码中,您似乎没有使用存储的访问令牌创建会话?[2]我正在尝试FB最新Android SDK“facebook-Android-SDK-3.0.b”中提供的名为hackbook的示例…此应用程序也使用了类似的概念,但问题是,每次启动应用程序时,它都会要求在FB帐户中登录。因此,您是否也面临类似的问题或任何解决方法?不,我不会面临此类问题。一旦我登录Facebook,在我从Facebook注销或删除应用程序并重新安装。我正在使用相同的东西(facebook的Hackbook)用于登录,效果很好。另外,如果没有有效的会话,那么我将使用上述代码重新生成facebook会话。这并不意味着令牌缓存API在facebook3.0sdk最终版本中发生了更改。此方法不再按原样工作。现在对此方案有明确的支持。您可以使用AccessToken token=AccessToken.createFromE存在accessToken(accessToken、expiresDate、lastRefreshDate、AccessTokenSource、权限);然后是session.open(token、回调);o
    @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);
                }
            }
        });
    
    }