一.Preferences简介
1.Preferences是一种轻量级的数据存储机制,可存储一些简单的数据,例如:boolean,int,float,long,string等数据。以键值对的形式存储在应用程序的Preferences目录中,该目录位于(data\data\包名\shared_prefs\)中。
2.游戏中的得分,应用程序记录的上次登录时间等,都可使用Preferences。
二.实现一个显示应用程序上次登录时间的例子
1.main.xml文件
<span style="font-size:18px;"><?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:orientation="vertical" >
<TextView
android:id="@+id/TextView01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="25dip" />
</LinearLayout>
</span>
2.MainActivity.java类
<span style="font-size:18px;">package com.example.preferences;
import java.util.Date;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 返回一个SharedPreferences实例,第一个参数是SharedPreferences的名字,第二个参数是使用默认的操作
SharedPreferences sp = this.getSharedPreferences("sharPre",
Context.MODE_PRIVATE);
String lastLogin = sp.getString("ll", null); // 从SharedPreferences中读取上次访问时间
if (lastLogin == null) {
lastLogin = "欢迎您,您是第一次访问本Preferences";
} else {
lastLogin = "欢迎回来,您上次于" + lastLogin + "登录";
}
SharedPreferences.Editor editor = sp.edit(); // 向SharedPreferences中写本次访问时间
editor.putString("ll", new Date().toLocaleString()); // 向editor中放入现在的时间
editor.commit(); // 提交 editor
tv = (TextView) this.findViewById(R.id.TextView01);
tv.setText(lastLogin);
}
}
</span>
显示效果:
1.程序首次运行效果
2.程序非首次运行效果