我有一个Activity,我正在尝试实现一种自动登录。在我的登录活动中,我有这个:
sharedPref = context.getSharedPreferences("data", Context.MODE_PRIVATE);
User.setUid(sharedPref.getInt("UID", 1));
Boolean al = sharedPref.getBoolean("AUTOLOGIN", false);
...
if (al) {
Log.i("AUTOLOGIN", "Go!");
Gui.createAlert(context, context.getString(R.string.loading));
Intent i = new Intent(context, CityActivity.class);
context.startActivity(i);
}
...
loginBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
...
Ajax.AjaxListener callback = new Ajax.AjaxListener() {
int uid = Integer.parseInt(userInfo.optString("user_id", "1"));
String sid = user.optString("sid", "");
String k = json.optString("k", "");
Boolean al = autoLogin.isChecked();
SharedPreferences.Editor e = sharedPref.edit();
e.putInt("UID", uid).putBoolean("AUTOLOGIN", al).putString("SID", sid).apply();
Gui.createAlert(context, context.getString(R.string.loading));
Intent i = new Intent(context, CityActivity.class);
};
});
我只能在模拟器上测试这个,我似乎无法在Android设备监视器中显示SharedPreferences
文件内容,但每次加载应用程序时,它都会自动登录常规。即使我完全关闭模拟器并重新启动所有内容,自动登录标志似乎仍然存在。我对Java / Android编程很陌生,但是从PHP和JavaScript背景来看,它并不难获得。我很遗憾为什么AUTOLOGIN
SharedPreference
密钥在检查时似乎总是返回true
。是否有使用SharedPreferences
实现自动登录的示例?
我应该注意到我最初尝试使用数据库,但由于使用困难和现在所需的最少数据而废弃了这个想法。
答案 0 :(得分:-2)
试试这个希望这会帮助你。 MainActivity.java
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void login(View v){
SharedPreferences spf=getSharedPreferences("myprfs",Context.MODE_PRIVATE);
String name=spf.getString("uname", "no value");
String pass=spf.getString("pass", "no value");
EditText et1=(EditText)findViewById(R.id.editText1);
EditText et2=(EditText)findViewById(R.id.editText2);
if(et1.getText().toString().equalsIgnoreCase(name) && et2.getText().toString().equalsIgnoreCase(pass))
{
Intent i=new Intent();
i.setComponent(new ComponentName(getApplicationContext(), WelcomeActivity.class));
startActivity(i);
}
}
public void register(View v){
Intent i=new Intent();
i.setComponent(new ComponentName(getApplicationContext(), RegistrationActivity.class));
startActivity(i);
}
}
RegistrationActivity.java
public class RegistrationActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
}
public void register(View v){
EditText et1=(EditText)findViewById(R.id.editText1);
EditText et2=(EditText)findViewById(R.id.editText2);
EditText et3=(EditText)findViewById(R.id.editText3);
SharedPreferences spf=getSharedPreferences("myprfs", Context.MODE_PRIVATE);
SharedPreferences.Editor spe=spf.edit();
spe.putString("uname", et1.getText().toString());
spe.putString("pass", et2.getText().toString());
spe.putString("dob", et3.getText().toString());
spe.commit();
finish();
}
}