SharedPreferences application context vs activity context

后端 未结 3 1819
清歌不尽
清歌不尽 2020-12-08 12:56

I am using several SharedPreferences to store data in my app. Some preferences are used in a lot of activites.

I know that the SharedPreferences are internally back

3条回答
  •  無奈伤痛
    2020-12-08 13:26

    It is worth reviewing the sources that show that a Context instance (be it an Activity or an Application instance) share the same static map HashMap.

    So whenever you request an instance of SharedPreferences by the same name via Context.getSharedPreferences(name, mode) you get the same instance since it first checks if the map already contains SharedPreferences instance for a key (which is the passed name). Once SharedPreferences instance is loaded it will not be loaded again, but taken from the map instead.

    So it actually does not matter which way you go, the important thing is to use the same name in order to get the same prefs from different parts of the application. However creating a single "access point" for the prefs could be a plus. So it could be a singleton wrapper over the prefs instantiated in Application.onCreate().

提交回复
热议问题