我正在尝试开发可以发布到 Facebook 的应用程序。
所以 SDK 设置好了,我可以像 hackbook 示例一样使用 FB 按钮登录。我真的不喜欢它的样子。我正在开发一个应用程序,然后在它上面浮动 webview 弹出窗口?
也许我弄错了,但我很想在我的设置活动中以某种方式获取 Facebook 登录名/密码,然后将令牌保存到共享首选项。
有没有办法做到这一点?
Saving the access tokens in SharedPrefs can be done by using the following code when you are setting up a valid session.
Utility.fb.authorize(MainActivity.this,Utility.fbPermissions , new DialogListener() {
@Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
Toast.makeText(context, "Facebook Error", Toast.LENGTH_LONG).show();
}
@Override
public void onError(DialogError e) {
// TODO Auto-generated method stub
Toast.makeText(context, "Dialog Error", Toast.LENGTH_LONG).show();
}
@Override
public void onComplete(Bundle values) {
// TODO Auto-generated method stub
Toast.makeText(context, "User Logged In", Toast.LENGTH_LONG).show();
Utility.editor = Utility.prefs.edit();
Utility.editor.putString("access_token", Utility.fb.getAccessToken());
Utility.editor.putLong("access_expires", Utility.fb.getAccessExpires());
Utility.editor.commit();
Intent intent = new Intent(context, UpdateStatus.class);
startActivity(intent);
}
@Override
public void onCancel() {
// TODO Auto-generated method stub
Toast.makeText(context, "Cancelled by user", Toast.LENGTH_LONG).show();
}
});
And later you can just check for the validity of the access token and log in the user directly, without asking for his username or password.
Utility.prefs = getSharedPreferences(Utility.PREF_UTILITY_FILE_NAME, MODE_PRIVATE);
Utility.access_token = Utility.prefs.getString("access_token", null);
Utility.expires = Utility.prefs.getLong("access_expires", 0);
if(Utility.access_token != null)
{
Utility.fb.setAccessToken(Utility.access_token);
}
if(Utility.expires !=0)
{
Utility.fb.setAccessExpires(Utility.expires);
}
if(Utility.fb.isSessionValid())
{
//user is already logged in
}
EDIT : Ever since Facebook API removed the offline access permission, you can increase the validity of the access tokens by putting the following code in the activity where you are doing the authentication to authorize the user login.
public void onResume() {
super.onResume();
Utility.fb.extendAccessTokenIfNeeded(this, null);
}