Preferences是一种轻量级的数据存储机制,它将一些简单数据类型的数据,包括boolean类型、int类型、float类型、long类型以及String类型的数据,以键值对的形式存储在应用程序的私有Preferences目录(/data/data/<包名>/shared_prefs/中。这种Preferences机制广泛应用于存储应用 程序中的配置信息。

       在Adndroid平台上,只需要用一个Context的对象调用getSharedPreferences(String name,int mode)方法传入Preferences文件名和打开模式,就可以获得一个SharedPreferences的对象。若该Preferences文件不存在,在提交数据后会创建该Preferences文件。利用SharedPreferences对象可以调用一些getter方法,传入相应的键来读取数据。要对Preferences文件的数据进行修改,首先利用SharedPreferences对象调用edit方法获得一个内部类Editor的对象,然后用这个Editor对象就可以对Preferences文件进行编辑了。注意,编辑完毕后一定要调用commit()方法,这样才会把所做的修改提交到Preferences文件当中去。下面是一个利用Preferences机制来保存Editor中所输入的字符串的示例。

就用一个简单的例子来完成Preferences功能。

创建一个界面,只显示一个EditText换件。


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
	<EditText
		android:id="@+id/edit"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"
		/>
</LinearLayout>


 然后在代码中实现程序功能。在onCreate()方法的实现中,将EditText的内容设置为上一次退出时保存在Preferences文件中字符串。而在onDestroy()方法中,则实现了将当前EditText中的字符串存储到Preferences文件。下面是详细的实现代码。

package com.action;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.EditText;

public class Tab extends Activity {
    EditText edit;
    SharedPreferences sp;
    final static String NAME = "my_sp";
    final static String EDIT_KEY = "edit";
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        edit = (EditText) findViewById(R.id.edit);
        sp = getSharedPreferences(NAME, 0);
        String str = sp.getString(EDIT_KEY, null);
        if(str != null){
        	edit.setText(str);
        }
    }
    @Override
    protected void onDestroy() {
    	super.onDestroy();
    	SharedPreferences.Editor editor = sp.edit();
    	editor.putString(EDIT_KEY, String.valueOf(edit.getText()));
    	editor.commit();
    	
    }
}

 最后,此应用程序在每次启动时会将上次退出时EditText中的内容恢复

SharedPreference数据以XML格式存放的。我们可以在 File Explorer中找到,目录为:data/data/包路径/shared_prefs

我们还可以在另一个应用程序里,来调用这个XML文件里面的数据,因为他们是由包路径来找。在另一个程序里调用时,我匀首先要得到你要调用程序的Activity,也就是Context对像,然后由这个对象来获得数据。代码如下:

try {
			Context context = this.getApplication().createPackageContext(
					"com.hilary", Context.CONTEXT_IGNORE_SECURITY);
			preference = context.getSharedPreferences("user",
					Context.MODE_WORLD_READABLE);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}

 其它用法和上面那个程序一样。只是要注意,createPackageContexst("包名",Context.CONTEXT_IGNORE_SECURITY);这里面的两个参数