Android 具有共享首选项的Singleton类,每次传入上下文或存储它

Android 具有共享首选项的Singleton类,每次传入上下文或存储它,android,sharedpreferences,Android,Sharedpreferences,我正在创建一个静态的单例类,因为它需要从任何地方访问。此类需要经常写入共享首选项。要创建共享引用对象,我需要上下文 我读到在静态类中存储对上下文的引用是个坏主意,因为上下文不能被垃圾收集,特别是当它是活动时 因此,我创建了一些方法,只要它需要写入以共享首选项,我就在上下文中传递这些方法。这将导致创建共享首选项对象,存储数据,然后删除该对象 这样行吗?为什么 谢谢你你可以 SharedPreferences pref = PreferenceManager. getDefaultSh

我正在创建一个静态的单例类,因为它需要从任何地方访问。此类需要经常写入共享首选项。要创建共享引用对象,我需要上下文

我读到在静态类中存储对上下文的引用是个坏主意,因为上下文不能被垃圾收集,特别是当它是活动时

因此,我创建了一些方法,只要它需要写入以共享首选项,我就在上下文中传递这些方法。这将导致创建共享首选项对象,存储数据,然后删除该对象

这样行吗?为什么

谢谢你

你可以

SharedPreferences pref = PreferenceManager.
       getDefaultSharedPreferences(context.getApplicationContext());
因此,每当
上下文
最终确定时,您都不会在意,因为您可以简单地使用应用程序上下文

SharedPreferences pref = PreferenceManager.
       getDefaultSharedPreferences(context.getApplicationContext());
public ClassSingle{

       private static ClassSingle classSingle = null;

        public ClassSingle(Context context) {
          //default values of variable if any
        }

       synchronized public static ClassSingle getInstance(Context context) {
           if (classSingle == null) {
               String configJson = context.getSharedPreferences(ApplicationConstants.PREF_FILE_CONFIG, Context.MODE_PRIVATE)
                .getString(ApplicationConstants.EXTRA_KEY, null);
              try {
                  classSingle = new Gson().fromJson(configJson, ClassSingle.class);
              } catch (JsonSyntaxException e) {
                  e.getStackTrace();
              }

              if (classSingle == null) {
                 classSingle = new ClassSingle(context);
         }
      }
      return classSingle;
     }
}
所以,每当
context
最终确定时,您都不会在意,因为您使用的是应用程序上下文

public ClassSingle{

       private static ClassSingle classSingle = null;

        public ClassSingle(Context context) {
          //default values of variable if any
        }

       synchronized public static ClassSingle getInstance(Context context) {
           if (classSingle == null) {
               String configJson = context.getSharedPreferences(ApplicationConstants.PREF_FILE_CONFIG, Context.MODE_PRIVATE)
                .getString(ApplicationConstants.EXTRA_KEY, null);
              try {
                  classSingle = new Gson().fromJson(configJson, ClassSingle.class);
              } catch (JsonSyntaxException e) {
                  e.getStackTrace();
              }

              if (classSingle == null) {
                 classSingle = new ClassSingle(context);
         }
      }
      return classSingle;
     }
}
使用这种方法生成singlton类并在任何地方获取实例。。如果它不在那里,它将创建新实例,否则它将返回现有实例


使用这种方法生成singlton类并在任何地方获取实例。。如果不存在,它将创建新实例,否则它将返回现有实例。

那么在静态类中将ApplicationContext作为变量存储是安全的吗?那么在静态类中将ApplicationContext作为变量存储是安全的吗?是的,可以。我一直使用这种方法来避免生物车牌代码是的,没关系。我一直使用这种方法来避免biolerplate代码