简体   繁体   English

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

[英]When to request permissions with Facebook's new Android SDK 3.0?

With Facebook's new Android SDK 3.0 (that was released a few days ago), the process of authentication has changed. 随着Facebook的新Android SDK 3.0(几天前发布),身份验证过程发生了变化。

So how do you request a read permission such as "friends_hometown"? 那么你如何申请阅读权限,例如“friends_hometown”?

The following code is how I am trying to do it - but I'm quite sure it's not the way you should do this: 以下代码是我试图这样做的 - 但我很确定这不是你应该这样做的方式:

Version 1: 版本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() {
                    ...
                });
            }
        }
    });
}

Version 2: 版本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);
        }
    }
}

What I'm doing is to request the permission as soon as the session is open - but at this point the code is already starting a Graph API request, thus the permission request comes to late ... 我正在做的是在会话打开后立即请求权限 - 但此时代码已经启动了一个Graph API请求,因此权限请求来得很晚......

Can't you request a permission at the same time you initialize the session? 您无法在初始化会话的同时申请权限吗?

I was able to get it to work. 我能够让它发挥作用。 It's a modification of your Version 2 sample. 它是对第2版示例的修改。 The link Jesse provided also helped a ton. Jesse提供的链接也有所帮助。

Here is the code I run through when authenticating a user: 以下是我在验证用户时运行的代码:

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());
              }
            });
    }
}

For testing I ran it through the below code after returning from Facebooks authentication: 为了测试我从Facebooks身份验证返回后通过以下代码运行它:

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());
          }
        });
    }
}

I solved the same problem by implementing my own Session.openActiveSession() method: 我通过实现自己的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;
}

I recommend that you read our login tutorial here specifically in step 3. Using the login button that we provide is the most convenient method, (see authButton.setReadPermissions() ) 我建议您阅读我们的登录教程这里具体步骤3.使用登录按钮,我们提供的是最方便的方法,(见authButton.setReadPermissions()

EDIT: 编辑:

To set permissions without using the loginbutton is trickier since you will have to do all the session management by hand. 在不使用loginbutton的情况下设置权限比较棘手,因为您必须手动完成所有会话管理。 Digging into the source code for the login button, this line of code is probably what you need. 深入研究登录按钮的源代码,这行代码可能就是您所需要的。 It looks like you will need to create your own Session.OpenRequest and set it's attributes such as permissions, audience, and login behavior, then get the current session and call openForRead() on your Session.OpenRequest . 看起来您需要创建自己的Session.OpenRequest并设置其属性(如权限,受众和登录行为),然后获取当前会话并在Session.OpenRequest上调用openForRead()

Although the first question was asked few months ago and there is accepted answers, there is another more elegant solution for requesting more permissions from user while authentication. 虽然几个月前就提出了第一个问题,并且已经接受了答案,但还有另一个更优雅的解决方案,用于在身份验证时向用户请求更多权限。 In addition, Facebook SDK 3.5 was released recently and it would be good to refresh this thread :) 此外,最近发布了Facebook SDK 3.5 ,刷新这个帖子会很好:)

So, the elegant solution comes with this open source library: android-simple-facebook 因此,优雅的解决方案来自这个开源库: android-simple-facebook

Setup 建立

Just add next lines in your Activity class: 只需在Activity类中添加下一行:

  1. Define and select permissions you need, like friends_hometown : 定义并选择所需的权限 ,例如friends_hometown

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

    The great thing here with the permissions, is that you don't need to seperate READ and PUBLISH permissions. 这里有权限的好处是你不需要分开READ和PUBLISH权限。 You just mention what you need and library will take care for the rest. 你只需要提到你需要的东西,图书馆就会照顾好其余部分。

  2. Build and define the configuration by putting app_id , namespace and permissions : 通过放置app_idnamespacepermissions构建和定义配置:

     SimpleFacebookConfiguration configuration = new SimpleFacebookConfiguration.Builder() .setAppId("625994234086470") .setNamespace("sromkuapp") .setPermissions(permissions) .build(); 
  3. And, create SimpleFacebook instance and set this configuration: 并且,创建SimpleFacebook实例并设置此配置:

     SimpleFacebook simpleFacebook = SimpleFacebook.getInstance(Activity); simpleFacebook.setConfiguration(configuration); 

Now, you can run the methods like: login , publish feed/story , invite ,… 现在,您可以运行以下方法: 登录发布Feed / story邀请 ,...

Login 登录

mSimpleFacebook.login(OnLoginListener);

Logout 登出

mSimpleFacebook.logout(OnLogoutListener);

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM