Difference between getDefaultSharedPreferences and getSharedPreferences

前端 未结 6 579
臣服心动
臣服心动 2020-11-22 13:13

What is the difference between getDefaultSharedPreferences and getSharedPreferences in Android? Can anyone please explain?

6条回答
  •  长发绾君心
    2020-11-22 13:29

    getDefaultSharedPreferences will use a default name like "com.example.something_preferences", but getSharedPreferences will require a name.

    getDefaultSharedPreferences in fact uses Context.getSharedPreferences (below is directly from the Android source):

    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;
    }
    

提交回复
热议问题