getSharedPreferences()与getDefaultSharedPreferences()的区别

本文深入解析了getDefaultSharedPreferences()方法的工作原理,包括如何通过上下文获取默认的SharedPreferences实例,以及其默认配置为包名_preferences和私有模式。


其实,getDefaultSharedPreference()方法中调用了getSharedPreferences()方法,而名称默认为 包名+_preferences,并且默认为私有模式

[java]  view plain copy
  1. /** 
  2.     * Gets a SharedPreferences instance that points to the default file that is 
  3.     * used by the preference framework in the given context. 
  4.     *  
  5.     * @param context The context of the preferences whose values are wanted. 
  6.     * @return A SharedPreferences instance that can be used to retrieve and 
  7.     *         listen to values of the preferences. 
  8.     */  
  9.    public static SharedPreferences getDefaultSharedPreferences(Context context) {  
  10.        return context.getSharedPreferences(getDefaultSharedPreferencesName(context),  
  11.                getDefaultSharedPreferencesMode());  
  12.    }  
  13.   
  14.    private static String getDefaultSharedPreferencesName(Context context) {  
  15.        return context.getPackageName() + "_preferences";  
  16.    }  
  17.   
  18.    private static int getDefaultSharedPreferencesMode() {  
  19.        return Context.MODE_PRIVATE;  
  20.    }  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值