我正在使用 Facebook 登录构建一个 Android 应用程序,但我坚持将会话持续到内部存储器。这是我实例化它的方式:
private static Session openActiveSession(Activity activity, boolean allowLoginUI, StatusCallback callback, List<String> permissions) {
OpenRequest openRequest = new OpenRequest(activity).setPermissions(permissions).setCallback(callback);
Session session = getSession(activity);
if (SessionState.CREATED_TOKEN_LOADED.equals(session.getState()) || allowLoginUI) {
Session.setActiveSession(session);
session.openForRead(openRequest);
return session;
}
return null;
}
private static Session getSession(Activity activity) {
return new Builder(activity).setTokenCachingStrategy(new SharedPreferencesTokenCachingStrategy(activity)).build();
}
问题是这个检查会话是否可以恢复的代码永远不会触发,因为 isOpened() 将始终返回 false
if((facebookSession = getSession(this)) != null && facebookSession.isOpened()) {
waitDialog = ProgressDialog.show(this, getResources().getString(R.string.pleaseWait), getResources().getString(R.string.loadingData));
onPostLogin();
return;
}
我试图用这两个函数来解决这个问题:
private void saveFacebookSession() {
Bundle facebookCache = new Bundle();
Parcel parceledCache = Parcel.obtain();
Session.saveSession(facebookSession, facebookCache);
parceledCache.writeBundle(facebookCache);
try {
FileOutputStream output = openFileOutput(FACEBOOK_SESSION_FILE, MODE_PRIVATE);
byte[] marshalledParcel = parceledCache.marshall();
Editor prefsEditor = preferences.edit();
prefsEditor.putInt(RESTORE_BYTE_COUNT, marshalledParcel.length);
prefsEditor.commit();
output.write(marshalledParcel);
output.flush();
output.close();
} catch (Exception e) {
Log.e(getClass().getName(), "Could not save the facebook session to storage");
}
}
private boolean restoreFacebookSession() {
try {
FileInputStream input = openFileInput(FACEBOOK_SESSION_FILE);
int arraySize = preferences.getInt(RESTORE_BYTE_COUNT, -1);
if(arraySize == -1) {
Log.e(getClass().getName(), "Could not read the facebook restore size");
return false;
}
byte[] sessionData = new byte[arraySize];
input.read(sessionData);
Parcel readParcel = Parcel.obtain();
readParcel.unmarshall(sessionData, 0, arraySize);
Bundle sessionBundle = readParcel.readBundle();
facebookSession = Session.restoreSession(getApplicationContext(), null, (StatusCallback)this, sessionBundle);
return true;
} catch (Exception e) {
Log.e(getClass().getName(), "Could not restore the session");
return false;
}
}
第二种方法不起作用,因为在读取捆绑包时会引发有关幻数的异常。
有任何想法吗?