getSharedPreferences()与getSharedPreferences(String name, int mode)与getDefaultSharedPreferences

本文详细解析了Android中SharedPreferences的三种获取方式,包括Context中的getSharedPreferences方法、PreferenceManager中的getSharedPreferences方法及getDefaultSharedPreferences静态方法,并介绍了SharedPreferences的基本概念及其在Android开发中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一直迷惑于这三个方法的关系,最近忙完项目,好好的分析一下。

如果你熟悉Context那么你可能知道Context当中有这样一个方法:(关于Context的说明)

一、getSharedPreferences(String name, int mode)

<nobr>abstract<a href="http://developer.android.com/reference/android/content/SharedPreferences.html" style="color:rgb(0,102,153); text-decoration:none">SharedPreferences</a></nobr> <nobr><span class="sympad" style="margin-right:2px"><a href="http://developer.android.com/reference/android/content/Context.html#getSharedPreferences(java.lang.String,%20int)" style="color:rgb(0,102,153); text-decoration:none">getSharedPreferences</a></span>(<a href="http://developer.android.com/reference/java/lang/String.html" style="color:rgb(0,102,153); text-decoration:none">String</a>name, int mode)</nobr>

Retrieve and hold the contents of the preferences file 'name', returning a SharedPreferences through which you can retrieve and modify its values. Only one instance of the SharedPreferences object is returned to any callers for the same name, meaning they will see each other's edits as soon as they are made.


得到名为‘name’的偏好文件。同时你可以更改和返回他的值。任何调用者在调用同样名字的偏好文件时只有一个实例返回,这就意味着这些调用者都可以看到其他调用者做出的更改。


这个函数的参数如下:

Parameters
name:
Desired preferences file. If a preferences file by this name does not exist, it will be created when you retrieve an editor (SharedPreferences.edit()) and then commit changes (Editor.commit()).

mode:
Operating mode. Use 0 orMODE_PRIVATEfor the default operation,MODE_WORLD_READABLEandMODE_WORLD_WRITEABLEto control permissions. The bitMODE_MULTI_PROCESScan also be used if multiple processes are mutating the same SharedPreferences file.MODE_MULTI_PROCESSis always on in apps targetting Gingerbread (Android 2.3) and below, and off by default in later versions.

name为本组件的配置文件名( 自己定义,也就是一个文件名),当这个文件不存在时,直接创建,如果已经存在,则直接使用,


mode为操作模式,默认的模式为0或MODE_PRIVATE,还可以使用MODE_WORLD_READABLE和MODE_WORLD_WRITEABLE
mode指定为MODE_PRIVATE,则该配置文件只能被自己的应用程序访问。
mode指定为MODE_WORLD_READABLE,则该配置文件除了自己访问外还可以被其它应该程序读取。
mode指定为MODE_WORLD_WRITEABLE,则该配置文件除了自己访问外还可以被其它应该程序读取和写入

二、PreferenceManager的方法getSharedPreferences()

这个方法我们可以通过查看其源码:

 /**
     * Gets a SharedPreferences instance that preferences managed by this will
     * use.
     * 
     * @return A SharedPreferences instance pointing to the file that contains
     *         the values of preferences that are managed by this.
     */
    public SharedPreferences getSharedPreferences() {
        if (mSharedPreferences == null) {
            mSharedPreferences = mContext.getSharedPreferences(mSharedPreferencesName,
                    mSharedPreferencesMode);
        }
        
        return mSharedPreferences;
    }

这个方法是一个普通的方法,必须有PreferenceManager的实例调用才行,因此我们再按图索骥找找其构造方法。

 /**
     * This constructor should ONLY be used when getting default values from
     * an XML preference hierarchy.
     * <p>
     * The {@link PreferenceManager#PreferenceManager(Activity)}
     * should be used ANY time a preference will be displayed, since some preference
     * types need an Activity for managed queries.
     */
    private PreferenceManager(Context context) {
        init(context);
    }

    private void init(Context context) {
        mContext = context;
        
        setSharedPreferencesName(getDefaultSharedPreferencesName(context));
    }

/**
     * Sets the name of the SharedPreferences file that preferences managed by this
     * will use.
     * 
     * @param sharedPreferencesName The name of the SharedPreferences file.
     * @see Context#getSharedPreferences(String, int)
     */
    public void setSharedPreferencesName(String sharedPreferencesName) {
        mSharedPreferencesName = sharedPreferencesName;
        mSharedPreferences = null;
    }

 private static String getDefaultSharedPreferencesName(Context context) {
        return context.getPackageName() + "_preferences";
    }

由以上方法,我们可以知道,最终我们调用getSharedPreferences()方法得到的是一个名为”yourpackageName_preferences“的偏好。同时其mode为默认私有。

三、getDefaultSharedPreferences方法

 /**
     * Gets a SharedPreferences instance that points to the default file that is
     * used by the preference framework in the given context.
     * 
     * @param context The context of the preferences whose values are wanted.
     * @return A SharedPreferences instance that can be used to retrieve and
     *         listen to values of the preferences.
     */
    public static SharedPreferences getDefaultSharedPreferences(Context context) {
        return context.getSharedPreferences(getDefaultSharedPreferencesName(context),
                getDefaultSharedPreferencesMode());
    }

    private static String getDefaultSharedPreferencesName(Context context) {
        return context.getPackageName() + "_preferences";
    }

    private static int getDefaultSharedPreferencesMode() {
        return Context.MODE_PRIVATE;
    }

这个方法是静态的,因此可以直接调用,同时它与我们调用getSharedPreferences()方法得到的返回值是一样的,只是调用的方式不同罢了。

四、SharedPreferences到底是什么

它是一个轻量级的存储类,特别适合用于保存软件配置参数。使用SharedPreferences保存数据,其背后是用xml文件存放数据,文件存放在/data/data/<package name>/shared_prefs目录下:

SharedPreferences sharedPreferences = getSharedPreferences("TEST", Context.MODE_PRIVATE);
Editor editor = sharedPreferences.edit();//获取编辑器
editor.putString("name", "Yang");
editor.putInt("sex", "boy");
editor.commit();//提交修改
生成的TEST.xml文件内容如下:
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="name">Yang</string>
<int name="sex">boy</string>
</map>

因为SharedPreferences背后是使用xml文件保存数据,getSharedPreferences(name,mode)方法的第一个参数用于指定该文件的名称,名称不用带后缀,后缀会由Android自动加上。方法的第二个参数指定文件的操作模式,共有四种操作模式,这四种模式前面介绍使用文件方式保存数据时已经讲解过。如果希望SharedPreferences背后使用的xml文件能被其他应用读和写,可以指定Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE权限。
另外Activity还提供了另一个getPreferences(mode)方法操作SharedPreferences,这个方法默认使用当前类不带包名的类名作为文件的名称。

如果访问其他应用中的Preference,前提条件是:该preference创建时指定了Context.MODE_WORLD_READABLE或者Context.MODE_WORLD_WRITEABLE权限。如:有个<package name>为cn.yang.action的应用使用下面语句创建了preference。
getSharedPreferences("TEST", Context.MODE_WORLD_READABLE);
其他应用要访问上面应用的preference,首先需要创建上面应用的Context,然后通过Context 访问preference ,访问preference时会在应用所在包下的shared_prefs目录找到preference :
Context otherAppsContext = createPackageContext("cn.yang.action", Context.CONTEXT_IGNORE_SECURITY);
SharedPreferences sharedPreferences = otherAppsContext.getSharedPreferences("TEST", Context.MODE_WORLD_READABLE);
String name = sharedPreferences.getString("name", "");
int age = sharedPreferences.getInt("sex", "");


如果不通过创建Context访问其他应用的preference,也可以以读取xml文件方式直接访问其他应用preference对应的xml文件,如:
File xmlFile = new File(“/data/data/<package name>/shared_prefs/itcast.xml”);//<package name>应替换成应用的包名。


1.【单选题】 (1分) 下列选项中,不属于getSharedPreferences()方法中的文件操作模式参数的是( )。 A. Context.MODE_PRIVATE B. Context.MODE_PUBLIC C. Context.MODE_WORLD_READABLE D. Context.MODE_WORLD_WRITEABLE 2.【单选题】 (1分) 下列关于初始化SharedPreferences类的代码正确的是( )。 A. SharedPreferences sp = new SharedPreferences(); B. SharedPreferences sp = SharedPreferences.getDefault(); C. SharedPreferences sp = SharedPreferences.Factory(); D. SharedPreferences sp = getSharedPreferences(); 3.【单选题】 (1分) 下列方法中,用于获取SharedPreferences类中的编辑器的方法是( )。 A. getEdit() B. edit() C. setEdit() D. getAll() 4.【单选题】 (1分) 关于 SQLite 事务(Transaction)的作用,以下描述错误的是?()‌ A. 保证操作的原子性 B. 提升批量操作的性能 C. 允许多线程同时写入数据 D. 支持数据回滚‌ 5.【单选题】 (1分) 下列关于SQLite数据库的描述中,错误的是( )。 A. SqliteOpenHelper类有创建数据库和更新数据库版本的功能 B. SqliteDatabase类是用来操作数据库的 C. 每次调用SqliteDatabase的getWritableDatabase()方法时,都会执行SqliteOpenHelper类的onCreate()方法 D. 当数据库版本发生变化时,会调用SqliteOpenHelper类的onUpgrade()方法更新数据库 6.【单选题】 (1分) ‌以下哪种场景适合使用文件存储?( )‌ A. 保存用户登录 Token B. 缓存图片或音视频文件 C. 存储复杂的关系型数据 D. 跨应用共享数据 7.【单选题】 (1分) 下列关于SharedPreferences存取文件的描述错误的是( ) 。 A. 属于移动存储解决方式 B. SharedPreferences处理的就是key-value对 C. 读取xml的路径是/sdcard/shared_prefs D. 文本的保存格式是xml 8.【单选题】 (1分) 下列选项中,可以对Android数据库中的表进行查询操作的方法是( )。 A. insert() B. execSQL() C. query() D. update() 9.【判断题】 (1分) SQLite是Android自带的一个轻量级的数据库,支持基本SQL语法。( ) 10.【判断题】 (1分) 使用openFileOutput()方式打开应用程序的输出流时,只需要指定文件名。( ) 11.【判断题】 (1分) SQLite数据库的事务操作满足原子性、一致性、隔离性和持续性。( ) 12.【判断题】 (1分) SQLiteDatabase类的update()方法用于删除数据表中的数据。( ) 13.【填空题】 (4分) 通过张三王五取钱和存钱的例子,使用SQLite的事务模拟银行转账功能,补全代码 PersonSQLiteOpenHelper helper = new PersonsQLiteOpenHelper (getApplication()); SQLiteDatabase db = helper.getWritableDatabase(); db.________; //开启数据库事务 try{ db.execSQL("update person set account = account-1000 where name =?", new Object[] { "张k" }); db.execsQL("update information set account = account +1000 where name =?", new Object! {"王五”}); db.setTransactionSuccessful(); }catch (Exception e){ Logi("事务处理失败",e.toString()); }finally { db.endTransaction(): __________//关闭数据库 } 14.【填空题】 (4分) 使用SharedPreferences类存储数据,补全代码 SharedPreferences sp = getSharedPreferences(“data”,MODE_PRIVATE) SharedPreferences.Editor editoreditorputString("name","张三”); editor.putlnt("age", 8); editor._______;
03-25
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值