七、android的SharedPreferences

淩亂°似流年 2022-10-14 14:48 300阅读 0赞

很多时候我们开发的软件需要向用户提供软件参数设置功能,例如我们常用的QQ,用户可以设置是否允许陌生人添加自己为好友。对于软件配置参数的保存,如果是window软件通常我们会采用ini文件进行保存,如果是j2se应用,我们会采用properties属性文件或者xml进行保存。如果是Android应用,我们最适合采用什么方式保存软件配置参数呢?Android平台给我们提供了一个SharedPreferences类,它是一个轻量级的存储类,特别适合用于保存软件配置参数。使用SharedPreferences保存数据,其背后是用xml文件存放数据,文件存放在/data/data//shared_prefs目录下:

  1. SharedPreferences sharedPreferences = getSharedPreferences("itcast", Context.MODE_PRIVATE);
  2. Editor editor = sharedPreferences.edit();//获取编辑器
  3. editor.putString("name", "名称");
  4. editor.putInt("age", 4);
  5. editor.commit();//提交修改

生成的 itcast.xml 文件内容如下

  1. <?xml version='1.0' encoding='utf-8' standalone='yes' ?>
  2. <map>
  3. <string name="name">名称</string>
  4. <int name="age" value="4" />
  5. </map>

因为SharedPreferences背后是使用xml文件保存数据,getSharedPreferences(name,mode)方法的第一个参数用于指定该文件的名称,名称不用带后

缀,后缀会由Android自动加上。方法的第二个参数指定文件的操作模式,共有四种操作模式,这四种模式前面介绍使用文件方式保存数据时已经讲解

过。如果希望SharedPreferences背后使用的xml文件能被其他应用读和写,可以指

定Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE权限。另外Activity还提供了另一个getPreferences(mode)方法操作SharedPreferences,这个方法默认使用当前类不带包名的类名作为文件

的名称。

访问SharedPreferences中的数据代码如下:

  1. SharedPreferences sharedPreferences = getSharedPreferences("itcast", Context.MODE_PRIVATE);
  2. //getString()第二个参数为缺省值,如果preference中不存在该key,将返回缺省值
  3. String name = sharedPreferences.getString("name", "");
  4. int age = sharedPreferences.getInt("age", 1);

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

者Context.MODE_WORLD_WRITEABLE权限。如:有个为cn.itcast.action的应用使用下面语句创建了preference。

getSharedPreferences(“itcast”,Context.MODE_WORLD_READABLE);

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

  1. Context otherAppsContext = createPackageContext("cn.itcast.action", Context.CONTEXT_IGNORE_SECURITY);
  2. SharedPreferences sharedPreferences = otherAppsContext.getSharedPreferences("itcast", Context.MODE_WORLD_READABLE);
  3. String name = sharedPreferences.getString("name", "");
  4. int age = sharedPreferences.getInt("age", 0);

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

File xmlFile =new File(“/data/data//shared_prefs/itcast.xml”);//应替换成应用的包名

1、工程结构:

SouthEast

界面:SouthEast 1

设置偏好xml生成的格式:SouthEast 2

xml生成的文件目录:SouthEast 3

2、string.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <resources>
  3. <string name="hello">Hello World, PreferencesActivity!</string>
  4. <string name="app_name">Preferences</string>
  5. <string name="name">姓名</string>
  6. <string name="age">年龄</string>
  7. <string name="savepre">保存参数</string>
  8. <string name="success">保存成功</string>
  9. </resources>

3、界面main.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="fill_parent"
  4. android:layout_height="fill_parent"
  5. android:orientation="vertical" >
  6. <TextView
  7. android:layout_width="fill_parent"
  8. android:layout_height="wrap_content"
  9. android:text="@string/name" />
  10. <EditText
  11. android:layout_width="fill_parent"
  12. android:layout_height="wrap_content"
  13. android:id="@+id/name" />
  14. <TextView
  15. android:layout_width="fill_parent"
  16. android:layout_height="wrap_content"
  17. android:text="@string/age" />
  18. <EditText
  19. android:layout_width="fill_parent"
  20. android:layout_height="wrap_content"
  21. android:id="@+id/age"
  22. android:numeric="integer" /><!-- 限制只能输入整型值 -->
  23. <Button
  24. android:layout_width="wrap_content"
  25. android:layout_height="wrap_content"
  26. android:text="@string/savepre"
  27. android:id="@+id/button"
  28. android:onClick="save" />
  29. <!-- 用于指定显示界面所在的Activity中定义save方法 ,这里是PreferencesActivity-->
  30. </LinearLayout>

4、Activity

  1. package cn.huangjie.preferences;
  2. import java.util.Map;
  3. import cn.huangjie.service.PreferencesService;
  4. import android.app.Activity;
  5. import android.os.Bundle;
  6. import android.view.View;
  7. import android.widget.EditText;
  8. import android.widget.Toast;
  9. public class PreferencesActivity extends Activity {
  10. private EditText nameText;
  11. private EditText ageText;
  12. private PreferencesService service;
  13. @Override
  14. public void onCreate(Bundle savedInstanceState) {
  15. super.onCreate(savedInstanceState);
  16. setContentView(R.layout.main);
  17. nameText = (EditText) this.findViewById(R.id.name);
  18. ageText = (EditText) this.findViewById(R.id.age);
  19. service = new PreferencesService(getApplicationContext());
  20. //使显示界面的时候就把原有的值给赋值上
  21. Map<String, String> params = service.getPreferences();
  22. nameText.setText(params.get("name"));
  23. ageText.setText(params.get("age"));
  24. }
  25. public void save(View v){
  26. // 默认的xml文件是该Activity的简单名称PreferencesActivity
  27. // this.getPreferences(MODE_PRIVATE);
  28. String name = nameText.getText().toString();
  29. String age = ageText.getText().toString();
  30. service.save(name, Integer.valueOf(age));
  31. Toast.makeText(getApplicationContext(), R.string.success, Toast.LENGTH_LONG).show();
  32. }
  33. }

5、Service处理类

  1. package cn.huangjie.service;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. import android.content.Context;
  5. import android.content.SharedPreferences;
  6. import android.content.SharedPreferences.Editor;
  7. public class PreferencesService {
  8. private Context context;
  9. public PreferencesService(Context context){
  10. this.context = context;
  11. }
  12. /**
  13. * 保存设置偏好
  14. * @param name
  15. * @param age
  16. */
  17. public void save(String name, Integer age) {
  18. //设置文件是以xml来进行保存的
  19. SharedPreferences preferences = context.getSharedPreferences("user", Context.MODE_PRIVATE);
  20. Editor editor = preferences.edit();
  21. editor.putString("name", name);
  22. editor.putInt("age", age);
  23. editor.commit();
  24. }
  25. /**
  26. * 读取设置偏好
  27. */
  28. public Map<String, String> getPreferences(){
  29. Map<String, String> params = new HashMap<String, String>();
  30. SharedPreferences preferences = context.getSharedPreferences("user", Context.MODE_PRIVATE);
  31. params.put("name", preferences.getString("name", ""));
  32. params.put("age", String.valueOf(preferences.getInt("age", 0)));
  33. return params;
  34. }
  35. }

工程下载路径: http://download.csdn.net/detail/wxwzy738/6272239

发表评论

表情:
评论列表 (有 0 条评论,300人围观)

还没有评论,来说两句吧...

相关阅读

    相关 androidSharedPreferences

    很多时候我们开发的软件需要向用户提供软件参数设置功能,例如我们常用的QQ,用户可以设置是否允许陌生人添加自己为好友。对于软件配置参数的保存,如果是window软件通常我们会采用