本文主要是记录一些零碎的知识点
SharedPreferences 最容易理解的Android存储技术之一,主要是用来实现用户的自动登录,记录当前音乐播放的歌曲、进度等少量信息,可以理解为web里的cookies,但是不是cookies.
演示一下怎么使用SharedPreferences 实现记住用户登录信息,需要一个登录界面,有个用户名输入框,一个密码输入框,一个登录按钮,没东西,代码就不贴了
看具体代码实现:
private SharedPreferences sharedPreferences;
// sharedPreferences = this.getSharedPreferences("userInfo", Context.MODE_PRIVATE);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//读取用户名密码,登录 ,用户点击退出后就不是自动登录
String username = sharedPreferences.getString("userName", "");
String password = sharedPreferences.getString("password", "");
//The name of the preference to retrieve. Value to return if this preference does not exist.
if (sharedPreferences.getBoolean("AUTO_ISCHECK", false)) {
//自动登录,进入主页面
} else {
/*进入初始化登录页面阶段
初始化页面可以自动填入用户名密码的信息
mLoginName.setText(username);(EditText)
mPasswordView.setText(password);
*/
init();
}
//用户点击登录时,收集用户信息,我默认是自动登录,没有做那个checkbox
//保存用户名密码 自动登录
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", loginName);
editor.putString("password", password);
editor.putBoolean("AUTO_ISCHECK", true);
editor.commit();
如何取消自动登录
//取消用户的自动登录,可以在应用里做一个退出按钮,在里面写上下面的就好了,下次就需要输入用户名了
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("AUTO_ISCHECK",false);
editor.commit();
这个TextInputLayout效果特别好嘛,尤其是我们这种不会做美化的
<android.support.design.widget.TextInputLayout android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText android:id="@+id/password" android:layout_width="match_parent"
android:layout_height="wrap_content" android:hint="@string/prompt_password"
android:imeActionId="@+id/login"
android:imeActionLabel="@string/action_sign_in_short"
android:imeOptions="actionUnspecified" android:inputType="textPassword"
android:maxLines="1" android:singleLine="true" />
</android.support.design.widget.TextInputLayout>
需要在build.gradle添加依赖dependencies {
//原先的别删哈,只是添加这一条
compile 'com.android.support:design:23.1.0'
}