android - 成功登录后 Facebook 未在 Android 中打开新 Activity ,重定向到上一个 Activity

标签 android facebook facebook-login android-facebook

我在我的 android 应用程序中使用 Facebook 登录。

成功登录 Facebook 后,我正在获取个人资料信息,一切正常。

但我的问题是它没有打开下一个 Activity 。它将转到我的应用程序中的先前 Activity 。

我还在我的应用程序中使用了 Google Plus 登录,它在同一页面中工作正常。

 public class MainActivity extends FragmentActivity {
    String TAG="MainActivity";
    private static final String PERMISSION = "publish_actions";

    //private static final String PERMISSION = "email";

    private final String PENDING_ACTION_BUNDLE_KEY = "pending_action";

    private Button postStatusUpdateButton;
    private LoginButton loginButton;
    private ProfilePictureView profilePictureView;
    private TextView greeting;
    private PendingAction pendingAction = PendingAction.NONE;
    private GraphUser user;
    private GraphPlace place;
    private List<GraphUser> tags;
    private boolean canPresentShareDialog;

    Button LogoutButton,Pro;

/*  private static final List<String> PERMISSION = Arrays.asList(
            "email","publish_actions");*/


    private enum PendingAction
    {
        NONE, POST_STATUS_UPDATE
    }

    private UiLifecycleHelper uiHelper;

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

    private FacebookDialog.Callback dialogCallback = new FacebookDialog.Callback() {
        @Override
        public void onError(FacebookDialog.PendingCall pendingCall,
                Exception error, Bundle data) {
            Log.d(TAG, String.format("Error: %s", error.toString()));
        }

        @Override
        public void onComplete(FacebookDialog.PendingCall pendingCall,
                Bundle data) {
            Log.d(TAG, "Success!");
        }
    };



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        uiHelper = new UiLifecycleHelper(this, callback);
        uiHelper.onCreate(savedInstanceState);
        // Can we present the share dialog for regular links?
        canPresentShareDialog = FacebookDialog.canPresentShareDialog(this,FacebookDialog.ShareDialogFeature.SHARE_DIALOG);

        if (savedInstanceState != null) {
            String name = savedInstanceState.getString(PENDING_ACTION_BUNDLE_KEY);
            pendingAction = PendingAction.valueOf(name);
        }

        setContentView(R.layout.activity_main);



        loginButton = (LoginButton) findViewById(R.id.login_button);
        loginButton.setUserInfoChangedCallback(new LoginButton.UserInfoChangedCallback() 
        {
                    @Override
                    public void onUserInfoFetched(GraphUser user) 
                    {
                        MainActivity.this.user = user;
                        updateUI();
                        // It's possible that we were waiting for this.user to
                        // be populated in order to post a status update.
                        handlePendingAction();


                    }
                });

        profilePictureView = (ProfilePictureView) findViewById(R.id.profilePicture);
        greeting = (TextView) findViewById(R.id.greeting);

        postStatusUpdateButton = (Button) findViewById(R.id.postStatusUpdateButton);
        postStatusUpdateButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                performPublish(PendingAction.POST_STATUS_UPDATE,canPresentShareDialog);
            }
        });

          LogoutButton=(Button)findViewById(R.id.LogoutButton);
          LogoutButton.setOnClickListener(new View.OnClickListener() 
          {

            @Override
            public void onClick(View v)
            {

                //callFacebookLogout(session);
                Logout();

            }
        });

    }

    //override lifecycle methods so that UiLifecycleHelper know about state of the activity
    @Override
    protected void onResume() {
        super.onResume();
        uiHelper.onResume();
        updateUI();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        uiHelper.onSaveInstanceState(outState);
        outState.putString(PENDING_ACTION_BUNDLE_KEY, pendingAction.name());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        uiHelper.onActivityResult(requestCode, resultCode, data, dialogCallback);
    }

    @Override
    public void onPause() {
        super.onPause();
        uiHelper.onPause();
    }

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

    private void onSessionStateChange(Session session, SessionState state,Exception exception) 
    {
        if (state.isOpened()) {
            Toast.makeText(getApplicationContext(), "User logged in...", Toast.LENGTH_SHORT).show();

            getUserData(session,state);



        } else if (state.isClosed()) {
            Toast.makeText(getApplicationContext(), "User logged out...", Toast.LENGTH_SHORT).show();
        }
        if (pendingAction != PendingAction.NONE
                && (exception instanceof FacebookOperationCanceledException 
                || exception instanceof FacebookAuthorizationException)) {
            new AlertDialog.Builder(MainActivity.this)//if permission is not granted
                    .setTitle(R.string.cancelled)
                    .setMessage(R.string.permission_not_granted)
                    .setPositiveButton(R.string.ok, null).show();
            pendingAction = PendingAction.NONE;
        } else if (state == SessionState.OPENED_TOKEN_UPDATED) {
            handlePendingAction();
        }
        updateUI();
    }

    private void updateUI() 
    {
        Session session = Session.getActiveSession();
        boolean enableButtons = (session != null && session.isOpened());

        postStatusUpdateButton.setEnabled(enableButtons
                || canPresentShareDialog);

        if (enableButtons && user != null) 
        {
            profilePictureView.setProfileId(user.getId());
            greeting.setText(getString(R.string.hello_user, user.getFirstName()));



        } else {
            profilePictureView.setProfileId(null);
            greeting.setText(null);
        }


    }

    @SuppressWarnings("incomplete-switch")
    private void handlePendingAction() {
        PendingAction previouslyPendingAction = pendingAction;
        // These actions may re-set pendingAction if they are still pending, but we assume they
        // will succeed.
        pendingAction = PendingAction.NONE;

        switch (previouslyPendingAction) {
        case POST_STATUS_UPDATE:
            postStatusUpdate();
            break;
        }
    }

    private interface GraphObjectWithId extends GraphObject {
        String getId();
    }

    private void showPublishResult(String message, GraphObject result,
            FacebookRequestError error) {
        String title = null;
        String alertMessage = null;
        if (error == null) {
            title = getString(R.string.success);
            String id = result.cast(GraphObjectWithId.class).getId();
            alertMessage = getString(R.string.successfully_posted_post,
                    message, id);
        } else {
            title = getString(R.string.error);
            alertMessage = error.getErrorMessage();
        }

        new AlertDialog.Builder(this).setTitle(title).setMessage(alertMessage)
                .setPositiveButton(R.string.ok, null).show();
    }

    // create sample post to update on facebook
    private FacebookDialog.ShareDialogBuilder createShareDialogBuilderForLink() {
        return new FacebookDialog.ShareDialogBuilder(this)
                .setName("Hello Facebook")
                .setDescription("this is sample post from androidSRC.net to demonstrate facebook login in your android application")
                .setLink("http://androidsrc.net/");
    }

    private void postStatusUpdate() {
        if (canPresentShareDialog) {
            FacebookDialog shareDialog = createShareDialogBuilderForLink().build();
            uiHelper.trackPendingDialogCall(shareDialog.present());
        } else if (user != null && hasPublishPermission()) {
            final String message = getString(R.string.status_update,
                    user.getFirstName(), (new Date().toString()));
            Request request = Request.newStatusUpdateRequest(
                    Session.getActiveSession(), message, place, tags,
                    new Request.Callback() {
                        @Override
                        public void onCompleted(Response response) {
                            showPublishResult(message,
                                    response.getGraphObject(),
                                    response.getError());
                        }
                    });
            request.executeAsync();
        } else {
            pendingAction = PendingAction.POST_STATUS_UPDATE;
        }
    }

    //check if app has permission to publish on facebook
    private boolean hasPublishPermission() {
        Session session = Session.getActiveSession();
        return session != null && session.getPermissions().contains("publish_actions")&&session.getPermissions().contains("email");
    }

    private void performPublish(PendingAction action, boolean allowNoSession) {
        Session session = Session.getActiveSession();
        if (session != null) {
            pendingAction = action;
            if (hasPublishPermission()) {
                // We can do the action right away.
                handlePendingAction();
                return;
            } else if (session.isOpened()) {
                // We need to get new permissions, then complete the action when
                // we get called back.
                session.requestNewPublishPermissions(new Session.NewPermissionsRequest(
                        this, PERMISSION));
                return;
            }
        }

        if (allowNoSession) {
            pendingAction = action;
            handlePendingAction();
        }
    }

    public void Logout()
    {
        if (Session.getActiveSession() != null) 
        {
            Session.getActiveSession().closeAndClearTokenInformation();
            Toast.makeText(getApplicationContext(), "logged out...", Toast.LENGTH_SHORT).show();
        }

        Session.setActiveSession(null);
    }




    private void getUserData(Session session, SessionState state)
    {
        if (state.isOpened())
        {
            Request.newMeRequest(session, new Request.GraphUserCallback()
            {
                @Override
                public void onCompleted(GraphUser user, Response response)
                {
                    if (response != null)
                    {
                        try
                        {
                            String name = user.getName();
                            // If you asked for email permission
                            String email = (String) user.getProperty("email");
                           // Log.e(LOG_TAG, "Name: " + name + " Email: " + email);

                            Toast.makeText(getApplicationContext(), "Name: " + name + " Email: " + email, Toast.LENGTH_SHORT).show();
                        }
                        catch (Exception e)
                        {
                            e.printStackTrace();
                            //Log.d(LOG_TAG, "Exception e");
                        }

                    }
                }
            }).executeAsync();
        }
    }

我的注销方法

public void Logout()
        {
            if (Session.getActiveSession() != null) 
            {
                Session.getActiveSession().closeAndClearTokenInformation();
                Toast.makeText(getApplicationContext(), "logged out...", Toast.LENGTH_SHORT).show();
            }

            Session.setActiveSession(null);
        }

但是在我的代码中,登录、注销、个人资料信息都可以正常工作。

我认为我在 Onactivtyresult 中犯了错误,因为 Google plus 登录和 Facebook 登录都使用相同的 Onactivityresult 。

将我的 onActivityResult 从(旧)更改为仅 facebook 登录

 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        uiHelper.onActivityResult(requestCode, resultCode, data, dialogCallback);
    }

//在ActivityResult上点赞(新)-Google plusFacebook登录

@Override
    protected void onActivityResult(int requestCode, int resultCode,Intent data)
    {
        //For Google Plus
        if (requestCode == RC_SIGN_IN) 
        {
            if (resultCode != RESULT_OK) {
                mSignInClicked = false;
            }

            mIntentInProgress = false;

            if (!mGoogleApiClient.isConnecting()) {
                mGoogleApiClient.connect();
            }
        }


        //For FACEBOOK LOGIN
        uiHelper.onActivityResult(requestCode, resultCode, data, dialogCallback);
        }

帮我解决

最佳答案

获取用户数据后可以调用NextActivity-

private void getUserData(Session session, SessionState state)
    {
        if (state.isOpened())
        {
            Request.newMeRequest(session, new Request.GraphUserCallback()
            {
                @Override
                public void onCompleted(GraphUser user, Response response)
                {
                    if (response != null)
                    {
                        try
                        {
                            String name = user.getName();
                            // If you asked for email permission
                            String email = (String) user.getProperty("email");
                            // Log.e(LOG_TAG, "Name: " + name + " Email: " + email);

                            Toast.makeText(getApplicationContext(), "Name: " + name + " Email: " + email, Toast.LENGTH_SHORT).show();
                            Intent _int = new Intent(CurrentActivity.this,NextActivity.class);
                            startActivity(_int);

                        }
                        catch (Exception e)
                        {
                            e.printStackTrace();
                            //Log.d(LOG_TAG, "Exception e");
                        }

                    }
                }
            }).executeAsync();
        }

    }

关于android - 成功登录后 Facebook 未在 Android 中打开新 Activity ,重定向到上一个 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30995179/

相关文章:

python - 在 Python 中处理 Facebook 取消授权回调

android - 如何在 android 上获取失败的 shell 命令的错误消息

android - 获取歌曲的流派

facebook - Facebook 是否公开裁剪用户个人资料缩略图的较大版本的偏移定位?

ios - 为什么 FBLogin 在模拟器中不工作? - 它留在 Safari 中?

ios - 当我将我的应用程序连接到 Facebook 时,无法显示用户名?

java - 将项目添加到 Java 构建路径

android - XML 布局到 Java 代码生成器

c# - Facebook,构建手动登录流程 - C# SDK

swift - 使用 swift 登录 Facebook - 导入问题