尝试在Android中登录Facebook 3.6时,会话已关闭

时间:2014-01-23 15:53:23

标签: android facebook facebook-android-sdk facebook-access-token facebook-authentication

在Android应用程序中使用Facebook SDK只会让我的日子变得更糟。我似乎不时松开会话,哈希有时似乎不对。当前错误表示hashkey * 与注册的密钥不同。哪个不正确,hashkey在他们的平台上注册了应用程序(该应用程序也是公开的)。

这是我用来连接Facebook的课程。我选择登录后,我得到说明权限的对话框(想看到朋友列表..),然后我选择确定或取消..没有发生任何事情。会议结束。

import java.util.Properties;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.facebook.FacebookOperationCanceledException;
import com.facebook.LoggingBehavior;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.Settings;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;

public class Test extends Activity {

    private GraphUser user = null;
    private static final String URL_PREFIX_FRIENDS = "https://graph.facebook.com/me/friends?access_token=";
    private Session.StatusCallback statusCallback = new SessionStatusCallback();
    private final String TAG = "Login with facebook";
    private Session session;

    // gcm
    public static final String EXTRA_MESSAGE = "message";
    private static final String PROPERTY_APP_VERSION = "appVersion";
    public static final String PROPERTY_REG_ID = "registration_id";

    private Properties properties;

    // Facebook
    private UiLifecycleHelper uiHelper;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity);

        Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);

        uiHelper = new UiLifecycleHelper(this, callback);
        uiHelper.onCreate(savedInstanceState);

        Session session = Session.getActiveSession();
        if (session == null) {
            if (savedInstanceState != null) {
                session = Session.restoreSession(this, null, statusCallback,
                        savedInstanceState);
            }
            if (session == null) {
                session = new Session(this);
            }
            Session.setActiveSession(session);
            if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
                session.openForRead(new Session.OpenRequest(this)
                        .setCallback(statusCallback));
            }
            Log.d(TAG, "Session state: " + session.getState());
        }

        if (session.isOpened()) {
            Log.d(TAG, "Access token: " + session.isOpened());
            System.out.println(session.getAccessToken());
        } else {
            onClickLogin();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Session.getActiveSession().onActivityResult(this, requestCode,
                resultCode, data);

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Session session = Session.getActiveSession();
        Session.saveSession(session, outState);
    }

    private void onClickLogin() {
        Session session = Session.getActiveSession();
        if (!session.isOpened() && !session.isClosed()) {
            session.openForRead(new Session.OpenRequest(this)
                    .setCallback(statusCallback));
        } else {
            Session.openActiveSession(this, true, statusCallback);
        }
    }

    private class SessionStatusCallback implements Session.StatusCallback {
        @Override
        public void call(Session session, SessionState state,
                Exception exception) {

            onSessionStateChange(session, state, exception);

        }
    }

    private void onSessionStateChange(final Session session,
            SessionState state, Exception exception) {
        if (session != null && session.isOpened()) {
            if (!state.equals(SessionState.OPENED_TOKEN_UPDATED)) {
                makeMeRequest(session);
            }
        }
        if (exception instanceof FacebookOperationCanceledException) {
            // Cancelled by user, show alert
            new AlertDialog.Builder(Test.this)
                    .setTitle(getString(R.string.hello))
                    .setMessage(getString(R.string.back_in_facebook_login))
                    .setPositiveButton(R.string.got_it, new OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            startActivity(new Intent(
                                    Test.this,
                                    LaunchingActivity.class));
                            finish();
                        }
                    }).show();
        }
    }

    private void makeMeRequest(final Session session) {
        // Make an API call to get user data and define a
        // new callback to handle the response.
        Request request = Request.newMeRequest(session,
                new Request.GraphUserCallback() {
                    @Override
                    public void onCompleted(GraphUser user, Response response) {
                        // If the response is successful
                        if (session == Session.getActiveSession()) {
                            if (user != null) {

                                if (session.isOpened()) {
                                    // yey. you have a valid session
                                }
                            }
                        }
                        if (response.getError() != null) {
                            // Handle errors, will do so later.
                        }
                    }
                });
        request.executeAsync();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    public void show(final String message) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(Test.this, message,
                        Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onStop() {
        super.onStop();
        Session.getActiveSession().removeCallback(statusCallback);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Session.getActiveSession().addCallback(statusCallback);
    }

    public interface SkipLoginCallback {
        void onSkipLoginPressed();
    }

    public void setSkipLoginCallback(SkipLoginCallback skipLoginCallback2) {
        // skipLoginCallback = skipLoginCallback2;
    }

    private Session.StatusCallback callback = new Session.StatusCallback() {
        @Override
        public void call(Session session, SessionState state,
                Exception exception) {
        }
    };
}

在manifest.xml中:

<!-- Facebook -->
        <activity
            android:name="com.facebook.LoginActivity"
            android:label="@string/app_name"
            android:theme="@android:style/Theme.Translucent.NoTitleBar" />


        <meta-data
            android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/fb_app_id" />
        <!-- end -->

在布局中:

<com.facebook.widget.LoginButton
            android:id="@+id/fbLoginBtn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal" />

错误日志:

W/fb4a(:<default>):BlueServiceQueue(11190): Exception during service
W/fb4a(:<default>):BlueServiceQueue(11190): com.facebook.http.protocol.ApiException: Key hash ****************** does not match any
 stored key hashes.
W/fb4a(:<default>):BlueServiceQueue(11190):     at com.facebook.http.protocol.ApiResponseChecker.b(ApiResponseChecker.java:83)
W/fb4a(:<default>):BlueServiceQueue(11190):     at com.facebook.http.protocol.ApiResponseChecker.a(ApiResponseChecker.java:162)
W/fb4a(:<default>):BlueServiceQueue(11190):     at com.facebook.http.protocol.ApiResponse.g(ApiResponse.java:186)
W/fb4a(:<default>):BlueServiceQueue(11190):     at com.facebook.platform.server.protocol.AuthorizeAppMethod.a(AuthorizeAppMethod.java:274)
W/fb4a(:<default>):BlueServiceQueue(11190):     at com.facebook.platform.server.protocol.AuthorizeAppMethod.a(AuthorizeAppMethod.java:30)
W/fb4a(:<default>):BlueServiceQueue(11190):     at com.facebook.http.protocol.ApiResponseHandler.a(ApiResponseHandler.java:56)
W/fb4a(:<default>):BlueServiceQueue(11190):     at com.facebook.http.protocol.ApiResponseHandler.handleResponse(ApiResponseHandler.java:29)
W/fb4a(:<default>):BlueServiceQueue(11190):     at com.facebook.http.common.FbHttpRequestProcessor.a(FbHttpRequestProcessor.java:318)
W/fb4a(:<default>):BlueServiceQueue(11190):     at com.facebook.http.common.FbHttpRequestProcessor.a(FbHttpRequestProcessor.java:147)
W/fb4a(:<default>):BlueServiceQueue(11190):     at com.facebook.http.common.FbHttpRequestProcessor.b(FbHttpRequestProcessor.java:104)
W/fb4a(:<default>):BlueServiceQueue(11190):     at com.facebook.http.common.FbHttpRequestProcessor.a(FbHttpRequestProcessor.java:234)
W/fb4a(:<default>):BlueServiceQueue(11190):     at com.facebook.http.protocol.SingleMethodRunnerImpl.a(SingleMethodRunnerImpl.java:380)
W/fb4a(:<default>):BlueServiceQueue(11190):     at com.facebook.http.protocol.SingleMethodRunnerImpl.a(SingleMethodRunnerImpl.java:161)
W/fb4a(:<default>):BlueServiceQueue(11190):     at com.facebook.http.protocol.AbstractSingleMethodRunner.a(AbstractSingleMethodRunner.java:1
8)
W/fb4a(:<default>):BlueServiceQueue(11190):     at com.facebook.platform.server.common.SimplePlatformOperation.a(SimplePlatformOperation.jav
a:40)
W/fb4a(:<default>):BlueServiceQueue(11190):     at com.facebook.platform.server.handler.PlatformOperationHandler.a(PlatformOperationHandler.
java:61)
W/fb4a(:<default>):BlueServiceQueue(11190):     at com.facebook.fbservice.service.BlueServiceQueue.e(BlueServiceQueue.java:300)
W/fb4a(:<default>):BlueServiceQueue(11190):     at com.facebook.fbservice.service.BlueServiceQueue.d(BlueServiceQueue.java:53)
W/fb4a(:<default>):BlueServiceQueue(11190):     at com.facebook.fbservice.service.BlueServiceQueue$3.run(BlueServiceQueue.java:230)
W/fb4a(:<default>):BlueServiceQueue(11190):     at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422)
W/fb4a(:<default>):BlueServiceQueue(11190):     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
W/fb4a(:<default>):BlueServiceQueue(11190):     at com.facebook.common.executors.ListenableScheduledFutureImpl.run(ListenableScheduledFuture
Impl.java:59)
W/fb4a(:<default>):BlueServiceQueue(11190):     at android.os.Handler.handleCallback(Handler.java:733)
W/fb4a(:<default>):BlueServiceQueue(11190):     at android.os.Handler.dispatchMessage(Handler.java:95)
W/fb4a(:<default>):BlueServiceQueue(11190):     at android.os.Looper.loop(Looper.java:136)
W/fb4a(:<default>):BlueServiceQueue(11190):     at android.os.HandlerThread.run(HandlerThread.java:61)
W/fb4a(:<default>):GDPDialog(11190): Failed to send
W/fb4a(:<default>):GDPDialog(11190): com.facebook.fbservice.service.ServiceException: API_ERROR: API_ERROR
W/fb4a(:<default>):GDPDialog(11190):    at com.facebook.fbservice.ops.BlueServiceOperation.c(BlueServiceOperation.java:640)
W/fb4a(:<default>):GDPDialog(11190):    at com.facebook.fbservice.ops.BlueServiceOperation.c(BlueServiceOperation.java:48)
W/fb4a(:<default>):GDPDialog(11190):    at com.facebook.fbservice.ops.BlueServiceOperation$2.run(BlueServiceOperation.java:605)
W/fb4a(:<default>):GDPDialog(11190):    at android.os.Handler.handleCallback(Handler.java:733)
W/fb4a(:<default>):GDPDialog(11190):    at android.os.Handler.dispatchMessage(Handler.java:95)
W/fb4a(:<default>):GDPDialog(11190):    at android.os.Looper.loop(Looper.java:136)
W/fb4a(:<default>):GDPDialog(11190):    at android.app.ActivityThread.main(ActivityThread.java:5017)
W/fb4a(:<default>):GDPDialog(11190):    at java.lang.reflect.Method.invokeNative(Native Method)
W/fb4a(:<default>):GDPDialog(11190):    at java.lang.reflect.Method.invoke(Method.java:515)
W/fb4a(:<default>):GDPDialog(11190):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
W/fb4a(:<default>):GDPDialog(11190):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
W/fb4a(:<default>):GDPDialog(11190):    at dalvik.system.NativeStart.main(Native Method)

希望有人注意到我的错误,因为我现在不明白这一点。感谢

1 个答案:

答案 0 :(得分:1)

尝试调用Session.getActiveSession而不将其指定给Session对象。这应该会触发回调。然后在onSessionStateChange(...)方法中,执行条件检查会话是否已打开。

onCreate(...)进行所有会话检查,如果将其移至onSessionStateChange(...),可以更好地工作,前提是您可以触发回调。

编辑:尝试手动将回调设置为LoginButton。我认为.setCallback(...)有一个LoginButton方法。我不太可能在不久前从按钮触发回调。