What's the difference between getDefaultSharedPreferences() and getPreferences()?

前端 未结 4 1932
挽巷
挽巷 2020-12-09 18:54

I\'m currently taking the \"Developing Android Apps\" Udacity course. In the \"Lesson 3: New Activities and Intents > Use SharedPreferences\" segment, the instructor asked

4条回答
  •  無奈伤痛
    2020-12-09 19:27

    If you take a look inside PreferenceManager:

    public static SharedPreferences getDefaultSharedPreferences(Context context) {
        return context.getSharedPreferences(getDefaultSharedPreferencesName(context),
                getDefaultSharedPreferencesMode());
    }
    
    /**
     * Returns the name used for storing default shared preferences.
     *
     * @see #getDefaultSharedPreferences(Context)
     * @see Context#getSharedPreferencesPath(String)
     */
    public static String getDefaultSharedPreferencesName(Context context) {
        return context.getPackageName() + "_preferences";
    }
    
    private static int getDefaultSharedPreferencesMode() {
        return Context.MODE_PRIVATE;
    }
    

    So getDefaultSharedPreferences() use getSharedPreferences() method with your app package name and mode private, if you use getPreferences() from activity it will use the same getSharedPreferences() method but with getLocalClassName();

提交回复
热议问题