本文共 2678 字,大约阅读时间需要 8 分钟。
SharedPreferences是Android平台上一个轻量级的存储类,提供了Android平台常规的Long、Int、String等等类型的保存,可以设置权限来限定使用起来很简单。存储的数据会以XML文件的形式保存在/data/data/工程名/shared_prefs/ 目录下。
Application是用来保存全局变量的,并且是在应用程序创建的时候就跟着创建了。所以当我们需要创建全局变量的时候,不需要再像 j2se那样需要创建public权限的static变量,而直接在application中去存储相应的全局变量。只需要调用Context的 getApplicationContext或者Activity的getApplication方法来获得一个application对象,然后再得到相应的成员变量便可。
同时android.app.Application的onCreate()方法是整个Android程序的入口点,所以整个应用程序的初始化工作可以在这里完成,他的继承关系如下:
+android.content.ContextWrapper
下面的例子同时使用了sharedpreference和Application,实现整个应用程序的初始化和数据的写入、读取。
- /**
- * TestSharePreferences.java
- * com.androidtest.sharedpreferences
- *
- * Function: TODO
- *
- * ver date author
- * ──────────────────────────────────
- * 2011-6-15 Leon
- *
- * Copyright (c) 2011, TNT All Rights Reserved.
- */
-
- package com.androidtest.sharedpreferences;
-
- import android.app.Application;
- import android.content.Context;
- import android.content.SharedPreferences;
- import android.content.SharedPreferences.Editor;
- import android.content.res.Configuration;
- import android.util.Log;
-
- /**
- * ClassName:TestSharePreferences Function: TODO ADD FUNCTION Reason: TODO ADD
- * REASON
- *
- * @author Leon
- * @version
- * @since Ver 1.1
- * @Date 2011-6-15
- */
- public class TestSharePreferences extends Application {
- private static final String TAG = TestSharePreferences.class
- .getSimpleName();
- private Integer sharedInteger ;
-
- public Integer getSharedInteger() {
- return sharedInteger;
- }
-
- public void setSharedInteger(Integer sharedInteger) {
- this.sharedInteger = sharedInteger;
- }
-
- @Override
- public void onCreate() {
-
- // TODO Auto-generated method stub
- super.onCreate();
- // 写入 第二个参数是设置此preferences的权限s
-
- SharedPreferences preferences = this.getSharedPreferences(
- "MusicCurrentPosition", Context.MODE_PRIVATE);
- if (!preferences.contains("key")) {
- Editor editor = preferences.edit();
- editor.putInt("key", 10000);
- editor.commit();
- Log.v(TAG , "写入数据 成功");
- }
-
- //读出
- //第二个参数是指如果没有这个Key值,则返回的默认值
- sharedInteger = preferences.getInt("key", 20000);
- Integer myInt2 = preferences.getInt("myKey", 30000);
- Log.v(TAG, "sharedInteger : " + sharedInteger.toString() + " myInt2 :" + myInt2);
-
- }
-
- @Override
- public void onConfigurationChanged(Configuration newConfig) {
-
- // TODO Auto-generated method stub
- super.onConfigurationChanged(newConfig);
-
- }
-
- @Override
- public void onLowMemory() {
-
- // TODO Auto-generated method stub
- super.onLowMemory();
-
- }
-
- @Override
- public void onTerminate() {
-
- // TODO Auto-generated method stub
- super.onTerminate();
-
- }
-
- }
记得要配置AndroidManifest
- <application android:icon="@drawable/icon" android:label="@string/app_name"
- android:name=".sharedpreferences.TestSharePreferences">
-
转载地址:http://hupjm.baihongyu.com/