何时使用Facebook的新Android SDK 3.0请求权限?

时间:2012-12-15 23:15:08

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

使用Facebook的新Android SDK 3.0(几天前发布),身份验证过程发生了变化。

那么你如何申请阅读权限,例如“friends_hometown”?

以下代码是我尝试的方式 - 但我很确定这不是你应该这样做的方式:

版本1:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Session.openActiveSession(this, true, new Session.StatusCallback() { // start Facebook login
        @Override
        public void call(Session session, SessionState state, Exception exception) { // callback for session state changes
            if (session.isOpened()) {
                List<String> permissions = new ArrayList<String>();
                permissions.add("friends_hometown");
                session.requestNewReadPermissions(new Session.NewPermissionsRequest(FBImport.this, permissions));
                Request.executeGraphPathRequestAsync(session, "me/friends/?access_token="+session.getAccessToken()+"&fields=id,name,hometown", new Request.Callback() {
                    ...
                });
            }
        }
    });
}

版本2:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Session currentSession = Session.getActiveSession();
    if (currentSession == null || currentSession.getState().isClosed()) {
        Session session = Session.openActiveSession(this, true, fbStatusCallback); // PROBLEM: NO PERMISSIONS YET BUT CALLBACK IS EXECUTED ON OPEN
        currentSession = session;
    }
    if (currentSession != null && !currentSession.isOpened()) {
        OpenRequest openRequest = new OpenRequest(this).setCallback(fbStatusCallback); // HERE IT IS OKAY TO EXECUTE THE CALLBACK BECAUSE WE'VE GOT THE PERMISSIONS
        if (openRequest != null) {
            openRequest.setDefaultAudience(SessionDefaultAudience.FRIENDS);
            openRequest.setPermissions(Arrays.asList("friends_hometown"));
            openRequest.setLoginBehavior(SessionLoginBehavior.SSO_WITH_FALLBACK);
            currentSession.openForRead(openRequest);
        }
    }
}

我正在做的是在会话打开后立即请求权限 - 但此时代码已经启动了一个Graph API请求,因此权限请求来得很晚......

您无法在初始化会话的同时申请权限吗?

4 个答案:

答案 0 :(得分:67)

我能够让它发挥作用。它是对第2版示例的修改。 link杰西提供的帮助也很大。

以下是我在验证用户时遇到的代码:

private void signInWithFacebook() {

    mSessionTracker = new SessionTracker(getBaseContext(), new StatusCallback() {

        @Override
        public void call(Session session, SessionState state, Exception exception) {
        }
    }, null, false);

    String applicationId = Utility.getMetadataApplicationId(getBaseContext());
    mCurrentSession = mSessionTracker.getSession();

    if (mCurrentSession == null || mCurrentSession.getState().isClosed()) {
        mSessionTracker.setSession(null);
        Session session = new Session.Builder(getBaseContext()).setApplicationId(applicationId).build();
        Session.setActiveSession(session);
        mCurrentSession = session;
    }

    if (!mCurrentSession.isOpened()) {
        Session.OpenRequest openRequest = null;
        openRequest = new Session.OpenRequest(SignUpChoices.this);

        if (openRequest != null) {
            openRequest.setDefaultAudience(SessionDefaultAudience.FRIENDS);
            openRequest.setPermissions(Arrays.asList("user_birthday", "email", "user_location"));
            openRequest.setLoginBehavior(SessionLoginBehavior.SSO_WITH_FALLBACK);

            mCurrentSession.openForRead(openRequest);
        }
    }else {
        Request.executeMeRequestAsync(mCurrentSession, new Request.GraphUserCallback() {
              @Override
              public void onCompleted(GraphUser user, Response response) {
                  Log.w("myConsultant", user.getId() + " " + user.getName() + " " + user.getInnerJSONObject());
              }
            });
    }
}

为了测试我从Facebook认证返回后通过以下代码运行:

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

  if (mCurrentSession.isOpened()) {
    Request.executeMeRequestAsync(mCurrentSession, new Request.GraphUserCallback() {

          // callback after Graph API response with user object
          @Override
          public void onCompleted(GraphUser user, Response response) {
              Log.w("myConsultant", user.getId() + " " + user.getName() + " " + user.getInnerJSONObject());
          }
        });
    }
}

答案 1 :(得分:55)

我通过实现自己的Session.openActiveSession()方法解决了同样的问题:

private static Session openActiveSession(Activity activity, boolean allowLoginUI, StatusCallback callback, List<String> permissions) {
    OpenRequest openRequest = new OpenRequest(activity).setPermissions(permissions).setCallback(callback);
    Session session = new Builder(activity).build();
    if (SessionState.CREATED_TOKEN_LOADED.equals(session.getState()) || allowLoginUI) {
        Session.setActiveSession(session);
        session.openForRead(openRequest);
        return session;
    }
    return null;
}

答案 2 :(得分:16)

我建议您在步骤3中专门阅读我们的登录教程here。使用我们提供的登录按钮是最方便的方法,(参见authButton.setReadPermissions()

编辑:

在不使用loginbutton的情况下设置权限比较棘手,因为您必须手动完成所有会话管理。深入研究登录按钮的源代码,这line of code可能就是您所需要的。看起来您需要创建自己的Session.OpenRequest并设置权限,受众群体和登录行为等属性,然后获取当前会话并在openForRead()上调用Session.OpenRequest。< / p>

答案 3 :(得分:4)

尽管几个月前第一个问题被问到并且有可接受的答案,但还有另一个更优雅的解决方案,用于在身份验证时请求用户获得更多权限。 另外,最近发布了Facebook SDK 3.5,刷新这个帖子会很好:)

因此,这个开源库提供了优雅的解决方案:android-simple-facebook

设置

只需在Activity课程中添加下一行:

  1. 定义并选择您需要的权限,例如friends_hometown

    Permissions[] permissions = new Permissions[]
    {
        Permissions.FRIENDS_HOMETOWN,
        Permissions.FRIENDS_PHOTOS,
        Permissions.PUBLISH_ACTION
    };
    

    这里有权限的好处是你不需要分开READ和PUBLISH权限。你只需要提到你需要的东西,图书馆就会照顾好其余部分。

  2. 通过app_idnamespacepermissions来构建和定义配置:

    SimpleFacebookConfiguration configuration = new SimpleFacebookConfiguration.Builder()
            .setAppId("625994234086470")
            .setNamespace("sromkuapp")
            .setPermissions(permissions)
            .build();
    
  3. 并创建SimpleFacebook实例并设置此配置:

    SimpleFacebook simpleFacebook = SimpleFacebook.getInstance(Activity);
    simpleFacebook.setConfiguration(configuration);
    
  4. 现在,您可以运行以下方法:登录发布Feed /故事邀请,...

    登录

    mSimpleFacebook.login(OnLoginListener);
    

    <强>注销

    mSimpleFacebook.logout(OnLogoutListener);
    

    有关更多示例和用法,请查看此页面:https://github.com/sromku/android-simple-facebook#actions-examples