SharedPreferences介绍:
SharedPreferences是Android平台上一个轻量级的存储类,主要是保存一些常用的配置参数,一般在Activity中 重载窗口状态onSaveInstanceState保存一般使用SharedPreferences完成,它提供了Android平台常规的Long长 整形、Int整形、String字符串型的保存,它是什么样的处理方式呢?SharedPreferences类似过去Windows系统上的ini配置文件,但是它分为多种权限,可以全局共享访问,android123提示最 终是以xml方式来保存,整体效率来看不是特别的高,对于常规的轻量级而言比SQLite要好不少,如果真的存储量不大可以考虑自己定义文件格式。xml 处理时Dalvik会通过自带底层的本地XML Parser解析,比如XMLpull方式,这样对于内存资源占用比较好。
这种方式应该是用起来最简单的Android读写外部数据的方法了。他的用法基本上和 J2SE(java.util.prefs.Preferences)中的用法一样,以一种简单、 透明的方式来保存一些用户个性化设置的字体、颜色、位置等参数信息。一般的应用程序都会提供“设置”或者“首选项”的这样的界面,那么这些设置最后就可以 通过Preferences来保存,而程序员不需要知道它到底以什么形式保存的,保存在了什么地方。当然,如果你愿意保存其他的东西,也没有什么限制。只 是在性能上不知道会有什么问题。
它是采用xml文件存放数据的,文件存放在"/data/data/<package name>/shared_prefs"目录下。
SharedPreferences的用法:
由于SharedPreferences是一个接口,而且在这个接口里没有提供写入数据和读取数据的能力。但它是通过其Editor接口中的一些方法来操作SharedPreference的,用法见下面代码:
Context.getSharedPreferences(String name,int mode)来得到一个SharedPreferences实例
name:是指文件名称,不需要加后缀.xml,系统会自动为我们添加上。
mode:是指定读写方式,其值有三种,分别为:Context.MODE_PRIVATE:指定该SharedPreferences数据只能被本应用程序读、写
Context.MODE_WORLD_READABLE:指定该SharedPreferences数据能被其他应用程序读,但不能写
Context.MODE_WORLD_WRITEABLE:指定该SharedPreferences数据能被其他应用程序读写。
实例分享
下面是个登陆记住密码和自动登陆的小例子,还不错,分享给大家。
结果截图:
废话不多说,直接上代码
Java代码
LoginActivity.java
package com.example.a002034.autologindemo;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
/**
* @author 002034
*/
public class LoginActivity extends AppCompatActivity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {
private static final String TAG = "LoginActivity";
private EditText mUserName, mPassword;
private CheckBox mCbPwd, mCbAutoLogin;
private Button mBtnLogin;
private ImageButton mBtnQuit;
private String mUserNameValue, mPasswordValue;
private SharedPreferences sp;
@SuppressLint("WorldReadableFiles")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//去除标题
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_login);
//获得实例对象
sp = this.getSharedPreferences("userInfo", Context.MODE_WORLD_READABLE);
mUserName = findViewById(R.id.et_zh);
mPassword = findViewById(R.id.et_mima);
mCbPwd = findViewById(R.id.cb_mima);
mCbAutoLogin = findViewById(R.id.cb_auto);
mCbPwd.setOnCheckedChangeListener(this);
mCbAutoLogin.setOnCheckedChangeListener(this);
mBtnLogin = findViewById(R.id.btn_login);
mBtnQuit = findViewById(R.id.img_btn);
mBtnLogin.setOnClickListener(this);
mBtnQuit.setOnClickListener(this);
//检查初始状态
checkInitStatus(sp);
}
/**
* 检查记住密码.
*/
private void checkRemPwd() {
if (mCbPwd.isChecked()) {
Log.i(TAG, "checkRemPwd:记住密码已选中 ");
sp.edit().putBoolean("ISCHECK", true).apply();
} else {
Log.i(TAG, "checkRemPwd: 记住密码没有选中");
sp.edit().putBoolean("ISCHECK", false).apply();
}
}
/**
* 初始检查记住密码状态以及是否设置自动登录.
*/
private void checkInitStatus(SharedPreferences sp) {
if (sp.getBoolean("ISCHECK", false)) {
//设置默认是记录密码状态
mCbPwd.setChecked(true);
mUserName.setText(sp.getString("USER_NAME", ""));
mPassword.setText(sp.getString("PASSWORD", ""));
//判断自动登陆多选框状态
if (sp.getBoolean("AUTO_ISCHECK", false)) {
//设置默认是自动登录状态
mCbAutoLogin.setChecked(true);
//跳转界面
Intent intent = new Intent(LoginActivity.this, LogoActivity.class);
LoginActivity.this.startActivity(intent);
}
}
}
/**
* 登录.
*/
private void login() {
mUserNameValue = mUserName.getText().toString();
mPasswordValue = mPassword.getText().toString();
if ("xzy".equals(mUserNameValue) && "123".equals(mPasswordValue)) {
Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
//登录成功和记住密码框为选中状态才保存用户信息
if (mCbPwd.isChecked()) {
//记住用户名、密码、
SharedPreferences.Editor editor = sp.edit();
editor.putString("USER_NAME", mUserNameValue);
editor.putString("PASSWORD", mPasswordValue);
editor.apply();
}
//跳转界面
Intent intent = new Intent(LoginActivity.this, LogoActivity.class);
LoginActivity.this.startActivity(intent);
} else {
Toast.makeText(LoginActivity.this, "用户名或密码错误,请重新登录", Toast.LENGTH_LONG).show();
}
}
/**
* 检查自动登录.
*/
private void checkAutoLogin() {
if (mCbAutoLogin.isChecked()) {
System.out.println("自动登录已选中");
sp.edit().putBoolean("AUTO_ISCHECK", true).apply();
} else {
System.out.println("自动登录没有选中");
sp.edit().putBoolean("AUTO_ISCHECK", false).apply();
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.img_btn:
finish();
break;
// 登录监听事件 现在默认为用户名为:xzy 密码:123
case R.id.btn_login:
login();
break;
default:
break;
}
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
switch (buttonView.getId()) {
//监听自动登录多选框事件
case R.id.cb_auto:
checkAutoLogin();
break;
//监听记住密码
case R.id.cb_mima:
checkRemPwd();
break;
default:
break;
}
}
}
LogoActivity.java
package com.example.a002034.autologindemo;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ProgressBar;
/**
* @author 002034
*/
public class LogoActivity extends AppCompatActivity {
private ProgressBar progressBar;
private Button backButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_logo);
progressBar = findViewById(R.id.pgBar);
backButton = findViewById(R.id.btn_back);
progressBar.setMax(3000);
Intent intent = new Intent(this, WelcomeActivity.class);
LogoActivity.this.startActivity(intent);
backButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
}
登录成功后会跳转到WelcomeActivity.java页面,代码很简单,就不贴出来了,主要逻辑都在LoginActivity里面,文末也会贴出源码链接。
布局文件:
activity_login.xml文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@mipmap/logo_bg"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<ImageButton
android:id="@+id/img_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:background="@mipmap/quit"/>
<TextView
android:id="@+id/tv_zh"
android:layout_width="wrap_content"
android:layout_height="35dip"
android:layout_marginLeft="12dip"
android:layout_marginTop="10dip"
android:gravity="bottom"
android:text="帐号:"
android:textColor="#000000"
android:textSize="18sp" />
<EditText
android:id="@+id/et_zh"
android:layout_width="fill_parent"
android:layout_height="40dip"
android:layout_below="@id/tv_zh"
android:layout_marginLeft="12dip"
android:layout_marginRight="10dip" />
<TextView
android:id="@+id/tv_mima"
android:layout_width="wrap_content"
android:layout_height="35dip"
android:layout_below="@id/et_zh"
android:layout_marginLeft="12dip"
android:layout_marginTop="10dip"
android:gravity="bottom"
android:text="密码:"
android:textColor="#000000"
android:textSize="18sp" />
<EditText
android:id="@+id/et_mima"
android:layout_width="fill_parent"
android:layout_height="40dip"
android:layout_below="@id/tv_mima"
android:layout_marginLeft="12dip"
android:layout_marginRight="10dip"
android:maxLines="200"
android:password="true"
android:scrollHorizontally="true" />
<CheckBox
android:id="@+id/cb_mima"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/et_mima"
android:layout_marginLeft="12dip"
android:text="记住密码"
android:textColor="#000000" />
<CheckBox
android:id="@+id/cb_auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/cb_mima"
android:layout_marginLeft="12dip"
android:text="自动登录"
android:textColor="#000000" />
<Button
android:id="@+id/btn_login"
android:layout_width="80dip"
android:layout_height="40dip"
android:layout_below="@id/et_mima"
android:layout_alignParentRight="true"
android:layout_alignTop="@id/cb_auto"
android:layout_marginRight="10dip"
android:gravity="center"
android:text="登录"
android:textColor="#000000"
android:textSize="18sp"/>
</RelativeLayout>
</LinearLayout>
activity_logo.xml文件<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@mipmap/logo_bg"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="3">
<ProgressBar
android:id="@+id/pgBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
<TextView
android:id="@+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/pgBar"
android:layout_centerHorizontal="true"
android:text="正在登录..."
android:textColor="#000000"
android:textSize="18sp" />
</RelativeLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:orientation="vertical" >
<Button
android:id="@+id/btn_back"
android:layout_width="70dip"
android:layout_height="35dip"
android:text="取消"
android:textColor="#000000"
android:textSize="12sp" />
</LinearLayout>
</LinearLayout>
感谢
感谢此文 http://blog.csdn.net/liuyiming_/article/details/7704923
源码地址
源码免费下载地址:https://download.csdn.net/download/jdfkldjlkjdl/10403828