Facebook SDK for Android - set Application ID programmatically

邮差的信 提交于 2019-11-30 05:21:30
Hardy

Hello all i know above answer is right for older sdk version, but in facebook sdk 4 there is no Session class

You can simply do it by using this single line code:

FacebookSdk.setApplicationId(APP_ID);

Thanks!

Here what i used to set the application id programatcally

    private Session.StatusCallback statusCallback = new SessionStatusCallback();

protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    String s=""+R.string.app_id;

    Session session = new Session.Builder(getBaseContext()).setApplicationId(s).build();

    Session.setActiveSession(session);

    if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
        session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
    }
}

private class SessionStatusCallback implements Session.StatusCallback {
    @Override
    public void call(Session session, SessionState state, Exception exception) {
        // TODO Auto-generated method stub
        if(session.isOpened()){
            //Do your task
        }
    }
}

I decided to fork the facebook-android-sdk project on GitHub and make the necessary changes. I have submitted a pull request with my changes if anyone is interested, https://github.com/facebook/facebook-android-sdk/pull/294.

Yes, you can set it programmatically. Use the Sessions$Builder class which allows you to build a session without needing to use one of the private constructors.

Session session = new Session.Builder(context).setApplicationId(applicationId).build();

I think there is a simpler way to do this, just call the static method setApplicationId com.facebook.Settings.setApplicationId(facebookID);

And you're good to go. No need to create a session manually with the Builder and set it as the active session!

Details of the Flaw:

The facebookID you set in the settings class will be used by getMetadataApplicationId method of com.facebook.internal.Utility

public static String getMetadataApplicationId(Context context) {
        Validate.notNull(context, "context");

        Settings.loadDefaultsFromMetadata(context);

        return Settings.getApplicationId();
    }

Which in turn will be used by all the calls to create a Session:

Session(Context context, String applicationId, TokenCachingStrategy tokenCachingStrategy,
            boolean loadTokenFromCache) {
        // if the application ID passed in is null, try to get it from the
        // meta-data in the manifest.
        if ((context != null) && (applicationId == null)) {
            applicationId = Utility.getMetadataApplicationId(context);
        }

        Validate.notNull(applicationId, "applicationId");
.
.
.
}

Cheers.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!