记录登录状态,我认为可以在用户登录成功后,与服务器约定一个 token 凭据,保存这个 token 凭据,而不是直接保存用户名、密码。

当然,保存 token 与保存设置数据是一样的,本文只讲解如何保存、读取。protected void save(View v)

{

SharedPreferences sp = getSharedPreferences("config", Context.MODE_PRIVATE);

SharedPreferences.Editor editor = sp.edit();

editor.putString("username", ((EditText)findViewById(R.id.username)).getText().toString());

editor.putString("password", ((EditText)findViewById(R.id.password)).getText().toString());

// editor.putBoolean()、editor.putInt()、editor.putFloat()……

editor.commit();

}

protected void load(View v)

{

SharedPreferences sp = getSharedPreferences("config", Context.MODE_PRIVATE);

String username = sp.getString("username", ""); // 第二个参数为默认值

String password = sp.getString("password", ""); // 第二个参数为默认值

// sp.getBoolean()、sp.getInt()、sp.getFloat()……

((EditText)findViewById(R.id.username)).setText(username);

((EditText)findViewById(R.id.password)).setText(password);

}

config 为本配置文件的名称,Context.MODE_PRIVATE 表示只能被本应用读写,Activity.MODE_WORLD_READABLE 表示可被其他应用读,Activity.MODE_WORLD_WRITEABLE 表示可被其他应用写。

读是直接调用的 SharedPreferences 方法,写是调用的 SharedPreferences.Editor 方法。

相关阅读

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐