共享preferences应用程序上下文VS活动背景 [英] SharedPreferences application context vs activity context

查看:151
本文介绍了共享preferences应用程序上下文VS活动背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用几个共享preferences将数据存储在我的应用程序。 一些preferences被用在很多activites的。

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

我知道,共享preferences内部背靠地图快速读取访问和写入SD卡时设置被更改。

I know that the SharedPreferences are internally backed by a map for fast read-access and written to sdcard when settings are changed.

我不知道哪种方式更好,如果共享preference是由很多activies的访问:

I wonder which way is better if a sharedpreference is accessed by a lot of activies:

  1. 使用活动场景实例化它的每一项活动。
  2. 实例化它的每一次活动,但使用的应用程序上下文。
  3. 把它放在如应用类实例化它只有一次出现,类似于一个单例。

如果我用1解决方案是有一个共享的preference的每个活动的对象?而将当活动被破坏的共享preference内部的地图被摧毁?

If I use 1. solution is there a sharedpreference object for every activity? And will the sharedpreference's internal map get destroyed when the activity is destroyed?

如果我用2的解决方案,虽然我叫getShared preferences在每一个活动都会有只有一个实例?而将在内部映射在内存中,只要应用程序是活?

If I use 2. solution will there be only one instance although I call getSharedPreferences in every activity? And will the internal map be in memory as long as the application is alive?

希望有人知道Android的内部如何处理它。

Hopefully someone knows how Android handles it internally.

推荐答案

这是值得检讨的<一个href="http://grep$c$c.com/file_/repository.grep$c$c.com/java/ext/com.google.android/android/2.3.7_r1/android/app/ContextImpl.java/?v=source">sources这表明,一个上下文实例(无论是活动应用程序实例)共享同一个静态地图的HashMap&LT;字符串,共享preferencesImpl&GT;

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<String, SharedPreferencesImpl>.

所以每当您请求的共享preferences 经由 Context.getShared preferences相同的姓名(名称,模式的情况下)你会得到相同的实例,因为它首先检查是否在地图中已包含共享preferences 实例一键(也就是通过名称)。一旦共享preferences 实例加载它不会再次加载,但是从图采取替代。

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.

所以它实际上不要紧,你走哪条路,重要的是要使用相同的名称,以便您可以通过应用程序的不同部分相同的preFS。但是建立一个单一的接入点为preFS可能是一个加号。因此,它可能是一个单封装了实例化 Application.onCreate的preFS()

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().

这篇关于共享preferences应用程序上下文VS活动背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆