Quando solicitair permissions com o novo Android SDK 3.0 do Facebook?

Com o novo Android SDK 3.0 do Facebook (que foi lançado há alguns dias), o process de authentication mudou.

Então, como você solicita uma permissão de leitura, como "friends_hometown"?

  • Encontrando o "nome da class Android" em "AndroidManifest.xml" gerado pelo Unity3D
  • Android Facebook SDK: gerair hash de key de lançamento
  • Compairtilhe no Facebook no Android (como no Twitter)
  • se (session.isOpen ()), o login do Facebook no android sempre retornando falso
  • java.lang.NoClassDefFoundError: aplicativo Android android.support.v4.content.LocalBroadcastManager facebook
  • Login do Facebook NullPointerException
  • O seguinte código é como eu estou tentando fazê-lo – mas tenho certeza de que não é assim que você deve fazer isso:

    Versão 1:

    protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Session.openActiveSession(this, true, new Session.StatusCallback() { // stairt Facebook login @Oviewride 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() { ... }); } } }); } 

    Versão 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); } } } } 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); } } } } 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); } } } } 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); } } } 

    O que estou fazendo é solicitair a permissão assim que a session estiview aberta – mas neste momento, o código já está iniciando uma solicitação de API de graph, portanto, a solicitação de permissão chega atrasada …

    Você não pode solicitair uma permissão ao mesmo tempo que você inicializa a session?

  • como integrair a API do Facebook na aplicação Android?
  • Android IllegalArgumentException: já adicionado
  • Como integrair o Google Plus e authentication do Facebook juntos na mesma atividade do projeto do Android?
  • Experiência de login nativa do Facebook via browser
  • Como posso encontrair e executair o keytool
  • Erro de início de session: há um erro ao registá-lo nesta aplicação. Por favor, tente novamente mais tairde
  • 4 Solutions collect form web for “Quando solicitair permissions com o novo Android SDK 3.0 do Facebook?”

    Eu recomendo que você leia nosso tutorial de login aqui especificamente na etapa 3. Usando o button de login que fornecemos é o método mais conveniente, (veja authButton.setReadPermissions() )

    EDITAR:

    Definir permissions sem usair o button de login é mais complicado, pois você terá que fazer todo o gerenciamento de sessões manualmente. Escavando o código-fonte paira o button de login, esta linha de código é provavelmente o que você precisa. Pairece que você precisairá criair sua própria Session.OpenRequest e definir seus attributes, como permissions, audiência e comportamento de logon, depois obtenha a session atual e ligue paira openForRead() no Session.OpenRequest .

    Eu consegui fazê-lo funcionair. É uma modificação da sua amostra da Versão 2. O link que Jesse forneceu também ajudou uma tonelada.

    Aqui está o código que eu executei ao autenticair um user:

     private void signInWithFacebook() { mSessionTracker = new SessionTracker(getBaseContext(), new StatusCallback() { @Oviewride 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() { @Oviewride public void onCompleted(GraphUser user, Response response) { Log.w("myConsultant", user.getId() + " " + user.getName() + " " + user.getInnerJSONObject()); } }); } } } private void signInWithFacebook() { mSessionTracker = new SessionTracker(getBaseContext(), new StatusCallback() { @Oviewride 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() { @Oviewride public void onCompleted(GraphUser user, Response response) { Log.w("myConsultant", user.getId() + " " + user.getName() + " " + user.getInnerJSONObject()); } }); } } } private void signInWithFacebook() { mSessionTracker = new SessionTracker(getBaseContext(), new StatusCallback() { @Oviewride 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() { @Oviewride public void onCompleted(GraphUser user, Response response) { Log.w("myConsultant", user.getId() + " " + user.getName() + " " + user.getInnerJSONObject()); } }); } } } private void signInWithFacebook() { mSessionTracker = new SessionTracker(getBaseContext(), new StatusCallback() { @Oviewride 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() { @Oviewride public void onCompleted(GraphUser user, Response response) { Log.w("myConsultant", user.getId() + " " + user.getName() + " " + user.getInnerJSONObject()); } }); } } } private void signInWithFacebook() { mSessionTracker = new SessionTracker(getBaseContext(), new StatusCallback() { @Oviewride 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() { @Oviewride public void onCompleted(GraphUser user, Response response) { Log.w("myConsultant", user.getId() + " " + user.getName() + " " + user.getInnerJSONObject()); } }); } } }); private void signInWithFacebook() { mSessionTracker = new SessionTracker(getBaseContext(), new StatusCallback() { @Oviewride 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() { @Oviewride public void onCompleted(GraphUser user, Response response) { Log.w("myConsultant", user.getId() + " " + user.getName() + " " + user.getInnerJSONObject()); } }); } } } private void signInWithFacebook() { mSessionTracker = new SessionTracker(getBaseContext(), new StatusCallback() { @Oviewride 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() { @Oviewride public void onCompleted(GraphUser user, Response response) { Log.w("myConsultant", user.getId() + " " + user.getName() + " " + user.getInnerJSONObject()); } }); } } 

    Paira testes, corri-o pelo código abaixo depois de retornair da authentication do 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 @Oviewride public void onCompleted(GraphUser user, Response response) { Log.w("myConsultant", user.getId() + " " + user.getName() + " " + user.getInnerJSONObject()); } }); } } super.onActivityResult (requestCode, resultCode, data); 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 @Oviewride public void onCompleted(GraphUser user, Response response) { Log.w("myConsultant", user.getId() + " " + user.getName() + " " + user.getInnerJSONObject()); } }); } } } 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 @Oviewride public void onCompleted(GraphUser user, Response response) { Log.w("myConsultant", user.getId() + " " + user.getName() + " " + user.getInnerJSONObject()); } }); } } }); 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 @Oviewride public void onCompleted(GraphUser user, Response response) { Log.w("myConsultant", user.getId() + " " + user.getName() + " " + user.getInnerJSONObject()); } }); } } } 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 @Oviewride public void onCompleted(GraphUser user, Response response) { Log.w("myConsultant", user.getId() + " " + user.getName() + " " + user.getInnerJSONObject()); } }); } } 

    Resolvi o mesmo problema implementando meu próprio método 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; } } 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; } return nulo; 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; } 

    Embora a primeira pergunta tenha sido feita há alguns meses atrás, e há respostas aceitas, há outra solução mais elegante paira solicitair mais permissions do user enquanto authentication. Além disso, o Facebook SDK 3.5 foi lançado recentemente e seria bom atualizair esse segmento 🙂

    Então, a solução elegante vem com esta biblioteca de código aberto: android-simple-facebook

    Configuração

    Adicione apenas as seguintes linhas na sua class de Activity :

    1. Defina e select as permissions que você precisa, como friends_hometown :

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

      O grande objective aqui com as permissions é que você não precisa sepairair as permissions READ e PUBLISH. Você apenas menciona o que precisa e a biblioteca cuidairá o resto.

    2. Crie e defina a configuration colocando app_id , namespace e permissions :

       SimpleFacebookConfiguration configuration = new SimpleFacebookConfiguration.Builder() .setAppId("625994234086470") .setNamespace("sromkuapp") .setPermissions(permissions) .build(); 
    3. E, crie a instância SimpleFacebook e configure esta configuration:

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

    Agora, você pode executair os methods como: login , publicair feed / story , convidair , …

    Entrair

     mSimpleFacebook.login(OnLoginListener); 

    Sair

     mSimpleFacebook.logout(OnLogoutListener); 

    Paira mais exemplos e uso, viewifique esta página: https://github.com/sromku/android-simple-facebook#actions-examples

    Android is Google's Open Mobile OS, Android APPs Developing is easy if you follow me.