SharedPreferences

简介

  • SharedPreferences是Android平台上一个轻量级数据存储方式,用来保存应用的一些常用配置,比如Activity状态,Activity暂停时,将此activity的状态保到SharedPereferences中;当Activity重载,系统回调方法 onSaveInstanceState时,再从SharedPreferences中将值取出。
  • SharedPreferences提供了java常规的Long、Int、String等类型数据的保存接口。
  • SharedPreferences类似过去Windows系统上的ini配置文件,但是它分为多种权限,可以全局共享访问。
  • 提示最终是以xml方式来保存,整体效率来看不是特别的高,对于常规的轻量级而言比SQLite要好不少,如果真的存储量不大可以考虑自己定义文件格式。xml处理时Dalvik会通过自带底层的本地XML Parser解析,比如XMLpull方式,这样对于内存资源占用比较好。

实现方式

  • SharedPreferences接口主要负责读取应用程序的Preferences数据,它提供了如下常用方法来访问SharedPreferences的key_value键值对

  • SharedPreferences常用的属性和方法

    public abstract boolean contains (String key)

    判断SharedPreferences是否包含特定key的数据

    public abstract SharedPreferences.Editor edit ()

    返回一个Edit对象用于操作SharedPreferences

    public abstract Map

操作模式

SharedPreferences是一个接口,那么我们怎么样来创建SharedPreferences例呢?可以通过Context.getSharedPreferences(Stringname,intmode)来得到一个SharedPreferences实例

name:是指文件名称,不需要加后缀.xml,系统会自动为我们添加上。一般这个文件存储在/data/data/<package name>/shared_prefs

mode:是指定读写方式,其值有四种。分别为

Context.MODE_PRIVATE Context.MODE_APPENDContext.MODE_WORLD_READABLEContext.MODE_WORLD_WRITEABLE  
    ontext.MODE_PRIVATE:为默认操作模式,代表该文件是私有数据,只能应用本身访问,在该模式下,写入的内容会覆盖原文件的内容      Context.MODE_APPEND:模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件.    Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE用来控制其他应用是否有权限读写该文件.    MODE_WORLD_READABLE:表示当前文件可以被其他应用读取.    MODE_WORLD_WRITEABLE:表示当前文件可以被其他应用写入  

用法

SharedPreferences 可以用来进行数据的共享,包括应用程序之间,或者同一个应用程序中的不同组件。比如两个activity除了通过Intent传

递数据之外,也可以通过ShreadPreferences来共享数据。

        Editor sharedata = getSharedPreferences("data", 0).edit();        sharedata.putString("item","hello getSharedPreferences");        sharedata.commit();
        SharedPreferences sharedata = getSharedPreferences("data", 0);        String data = sharedata.getString("item", null);        Log.v("cola","data="+data);  

实例方法

MainActivity.java

        import android.app.Activity;        import android.content.SharedPreferences;        import android.content.SharedPreferences.Editor;        import android.os.Bundle;        import android.view.View;        import android.view.View.OnClickListener;        import android.widget.Button;        import android.widget.EditText;        import android.widget.TextView;        import android.widget.Toast;        public class MainActivity extends Activity {        private TextView tv_read;        private EditText ed_wirte;        private Button wirte, read;        @Override        protected void onCreate(Bundle savedInstanceState) {            super.onCreate(savedInstanceState);            setContentView(R.layout.activity_main);            ed_wirte = (EditText) findViewById(R.id.ed_write);            tv_read = (TextView) findViewById(R.id.tv_read);            wirte = (Button) findViewById(R.id.write);            read = (Button) findViewById(R.id.read);            wirte.setOnClickListener(Write);            read.setOnClickListener(Read);        }        OnClickListener Write = new OnClickListener() {            @Override            public void onClick(View v) {                String name = ed_wirte.getText().toString();                // 实例化SharedPreferences对象(第一步)                SharedPreferences sharedPreferences = getSharedPreferences(                        "sptest", MODE_PRIVATE);                // 实例化SharedPreferences.Editor对象(第二步)                Editor editor = sharedPreferences.edit();                // 用putXX的方法保存数据                editor.putString("name", name);                // 提交当前数据                editor.commit();                // 使用toast信息提示框提示成功写入数据                Toast.makeText(MainActivity.this, "写入成功", Toast.LENGTH_SHORT)                        .show();            }        };        OnClickListener Read = new OnClickListener() {            @Override            public void onClick(View v) {                SharedPreferences sharedPreferences = getSharedPreferences(                        "sptest", MODE_PRIVATE);                String name = sharedPreferences.getString("name", "");                read.setText(name);             }           };        }
  • Activity_main.xml
        <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical">        <EditText  android:id="@+id/ed_write" android:layout_width="match_parent" android:layout_height="wrap_content" />        <Button  android:id="@+id/write" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="write" />        <Button  android:id="@+id/read" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="read" />        <TextView  android:id="@+id/tv_read" android:layout_width="match_parent" android:layout_height="wrap_content" />        </LinearLayout>
  • 图片

  • 关于其他程序访问sharedpreference的问题

OtherSpTest.java    import java.io.File;    import java.io.FileInputStream;    import android.content.Context;    import android.content.SharedPreferences;    import android.test.AndroidTestCase;    import android.util.Log;    public class OtherSpTest extends AndroidTestCase{    private static final String TAG = "AccessSharePreferenceTest";    /** * 访问SharePreference的方式一,注:权限要足够 * @throws Exception */    public void OtherSpTest() throws Exception{        String path = "/data/data/com.vampire.sharedpreferences.activity/shared_prefs/ljq123.xml";        File file = new File(path);        FileInputStream inputStream = new FileInputStream(file);        //获取的是一个xml字符串        String data = new FileService().read(inputStream);        Log.i(TAG, data);    }    /** * 访问SharePreference的方式二,注:权限要足够 * @throws Exception */    public void OtherSpTest2() throws Exception{        Context context = this.getContext().createPackageContext("com.vampire.sharedpreferences.activity",                 Context.CONTEXT_IGNORE_SECURITY);        SharedPreferences sharedPreferences = context.getSharedPreferences("ljq123",                 Context.MODE_WORLD_READABLE+Context.MODE_WORLD_WRITEABLE);        String name = sharedPreferences.getString("name", "");        Log.i(TAG, name);    }    }

如果访问其他应用中的Preference,前提条件是:该preference创建时指定了Context.MODE_WORLD_READABLE或者Context.MODE_WORLD_WRITEABLE权限。

如:有个为com.sp.MainActivity的应用使用下面语句创建了preference。

getSharedPreferences("sptest", Context.MODE_WORLD_READABLE);

其他应用要访问上面应用的preference,首先需要创建上面应用的Context,然后通过Context 访问preference ,访问preference时会在应用所在包下的shared_prefs目录找到preference :

Context otherAppsContext = createPackageContext("com.sp.MainActivity", Context.CONTEXT_IGNORE_SECURITY);
SharedPreferences   sharedPreferences =otherAppsContext.getSharedPreferences("sptest", Context.MODE_WORLD_READABLE); String name = sharedPreferences.getString("name", "");

如果不通过创建Context访问其他应用的preference,也可以以读取xml文件方式直接访问其他应用preference对应的xml文件,如:

File xmlFile = new File("/data/data/<package name>/shared_prefs/itcast.xml");//<package name>应替换成应用的包名

SharedPreferences的注意事项:

  • 编辑完SharedPreferences一定要记得调用Editor的commit()方法,否则不会将数据写入到文件里的。
    回顾总结:

    1、 如何得到SharedPreferences

    SharedPreferences preferences=getPreferences(“test”,MODE_PRIVATE);

    2、 如何编辑SharedPreferences
    得到Editor对象实例

    SharedPreferences.Editor editor=preferences.editor();

    3、 SharedPreferences的存储位置

    /data/data/<package name>/shared_prefs 

更多相关文章

  1. 一句话锁定MySQL数据占用元凶
  2. Android项目开发技术总结 by wellsoho
  3. Android学习笔记——网络技术
  4. Android--SQLite数据库应用技巧分享
  5. Android两种相机的调用方式
  6. Java(Android)数据结构汇总(四)-- Map(上)
  7. Android(安卓)不明确key时遍历JSONObject
  8. android sensor驱动移植
  9. Android(安卓)BaseRecyclerViewAdapterHelper 使用中的一些坑

随机推荐

  1. 贝叶斯之父Judea Pearl推荐:机器学习因果
  2. 日均万亿事件:Netflix怎么做实时流处理?
  3. 最有趣的机器学习可视化图集
  4. 暴力堆数据没用!NLP和语音技术突破难在哪?
  5. DeepMind PotArt多任务深度强化学习获突
  6. 大数据凉了?No,流式计算浪潮才刚刚开始!
  7. 作为普通Ruby开发,我如何从零转型机器学习
  8. 一文看懂Pinterest如何构建时间序列数据
  9. 6大最常用的Java机器学习库一览
  10. 9月份最热门的机器学习开源项目TOP 5