简体   繁体   English

只有公共静态成员的公共类

[英]Public class with only public static members

I have a public class that only contains public static members. 我有一个仅包含公共静态成员的公共类。

I know this is not the best thing to do but I was just wondering why on my Android, if I pause the application, open a few others and come back to mine, all variables seems to be (null). 我知道这不是最好的事情,但是我只是想知道为什么在我的Android上,如果我暂停应用程序,打开其他几个并返回我的列表,那么所有变量似乎都是(null)。

Questions: 问题:

  1. Is it because of some kind of a memory release made by Android? 是因为Android发行了某种内存版本吗?
  2. What then could be a better way to keep such variables? 那么,什么是保留此类变量的更好方法呢?
  3. Is a class that extends Application a good option? 扩展Application的类是一个不错的选择吗?

Here is my code: 这是我的代码:

public class Session {

public static String ID = null;
public static String UNIQID = null;
public static String TOKEN = null;
public static String SESSIONID = null;
}

As your application process might get destroyed any time, those static instances might get garbage collected indeed. 由于您的应用程序进程随时可能被破坏,因此那些静态实例实际上可能会被垃圾回收。

If you put these static variables in a custom Application object, same will apply, unless you initialise them in the application's onCreate function each time the application gets (re-)created. 如果将这些静态变量放在自定义的Application对象中,则除非将它们在每次(重新)创建应用程序时在应用程序的onCreate函数中进行初始化,否则它们将适用。

You should keep track of persistent data using either SharedPreferences or a SQLite database. 您应该使用SharedPreferences或SQLite数据库来跟踪持久性数据。

If these variables are too complex to be stored like that then you might want to consider using a singleton (subclassing Application is not as recommended as it used to be). 如果这些变量太复杂而无法像这样存储,那么您可能要考虑使用单例(不像以前那样建议使用子类化Application)。

public class MySingleton {

  public static MySingleton getInstance(Context context) {
    if (instance==null) {
      // Make sure you don't leak an activity by always using the application
      // context for singletons
      instance = new MySingleton(context.getApplicationContext());
    }
    return instance;
  }

  private static MySingleton instance = null;

  private MySingleton(Context context) {
    // init your stuff here...
  }

  private String id = null;
  private String uniqueId= null;
  private String token = null;
  private String sessionId = null;
}
  1. Yes, android may collect memory when required 是的,Android可能会在需要时收集内存

  2. May be something like SharedPreferences 可能类似于SharedPreferences

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM