Difference between getDefaultSharedPreferences and getSharedPreferences

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

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

6条回答
  •  一生所求
    2020-11-22 13:28

    Let's review the basic points of difference:

    1. getDefaultSharedPreferences() uses a default preference-file name. This default is set per application, so all activities in the same app context can access it easily as in the following example:

      SharedPreferences spref = PreferenceManager.getDefaultSharedPreferences(this);
      if (spref.contains("email")) {
           String sEmailAddr = spref.getString("email", "");
      }
      

      The preferences are usually stored at /data/data/com.package.name/shared_prefs/com.package.name_preferences.xml.

    2. The alternative method - getSharedPreferences(name,mode) requires to indicate a specific preference (file) name and an operation mode (e.g. private, world_readable, etc.)

    As mentioned by copolii, the result is the same, but the first option is simpler and lacks the flexibility to split to multiple preference files, that is offered by the second option of getSharedPreferences(). Sharing the preferences between apps using a MODE_WORLD_READABLE operation indicator is also something possible using getSharedPreferences(), but is rarely used.

    IMHO, getDefaultSharedPreferences() can be safely used without going into the confusion of multiple preference file names that are prone to typos and confusion, unless you want that different modules in your app will use different preference files. Normally this is not needed. If an app needs to save a lot of parameters, probably using external database will be better as it offers also better data protection.

    If someone knows of a good reason to regularly use getSharedPreferences() and not getDefaultSharedPreferences(), please let me know by commenting here.

提交回复
热议问题