Session.getActiveSession()在启动应用程序时返回null,尽管我已连接

jul*_*jul 8 android facebook-android-sdk

我使用com.facebook.widget.UserSettingsFragment管理我的应用程序中的登录/注销到Facebook:

UserSettingsFragment userSettingsFragment = new UserSettingsFragment();
Session session = Session.getActiveSession();
if(session==null || session.isClosed()){
    userSettingsFragment.setPublishPermissions(Arrays.asList("publish_actions"));
}
fragmentTransaction.replace(R.id.content_container, userSettingsFragment, "userSettingsFragment");
Run Code Online (Sandbox Code Playgroud)

在另一个Fragment(但相同Activity),在Facebook上发布之前,我正在检查我是否正在使用

Session session = Session.getActiveSession();
if (session != null && session.isOpened()){
    publishOnFacebook(intent.getExtras());
}
Run Code Online (Sandbox Code Playgroud)

当我启动我的应用程序并尝试发布时,我总是得到一个,null Session虽然我之前登录过.当我开始时UserSettingsFragment,它告诉我我已经连接了.

怎么能Session.getActiveSession();null,如果我确实有联系吗?

此外,如果II开始Fragment我直接发布的地方UserSettingsFragment,我得到正确的Session,即:

1 start the app
2 call `Session.getActiveSession()` in another `Fragment` returns `null`
3 start `UserSettingsFragment` shows that I'm log
Run Code Online (Sandbox Code Playgroud)

1 start the app
2 start `UserSettingsFragment` shows that I'm log
3 call `Session.getActiveSession()` in another `Fragment` returns a session
Run Code Online (Sandbox Code Playgroud)

有人可以帮忙吗?

jul*_*jul 34

好的,我刚读过openActiveSessionFromCache(不是来自Facebook doc):

Session session = Session.getActiveSession(); 

if(session==null){                      
    // try to restore from cache
    session = Session.openActiveSessionFromCache(getActivity());
}

if(session!=null && session.isOpened()){    
    publishOnFacebook(intent.getExtras());  
}
else{
    login();
}
Run Code Online (Sandbox Code Playgroud)