android - 应用程序进入后台后,Android 不会保持静态字段处于活动状态
问题描述
我正在构建一个安卓应用程序。
我创建了一个“BaseActivity”类,它与我的用户一起保存一个静态字段,所有其他活动都扩展了“BaseActivity”。
在Application onCreate()
我做期间:
BaseActivity.initializeUser();
它基本上为应用程序实例化了用户,这样之后我的所有活动都可以访问用户。
我绝对保证,代码中的任何地方用户都设置为 NULL
问题是:有时,当人们正常使用应用程序(生产)时,有时他们会在一段时间后得到nullpointerexception
,因为活动试图访问用户中的某些字段并且它为空
根据 crashlytics,这总是在某些活动中发生oncreate
(没有具体的,可以是任何)
为什么???
android 是否会丢弃我的单例对象以节省内存?如果是这样,为什么许多其他库(如 Firebase、Admob 和其他库)都有类似的初始化方法,在 Application onCreate() 期间调用但之后无论如何它们都可以在应用程序中正常运行?
====== 更新 =========
initializeUser
就像:
private static void initializeUser(){
currentUser = new User();
//then i do update the user's fields
currentUser.setLocation(something);
currentUser.setRef(something);
currentUser.setVersion(something);
//these values are read from various places but all methods are SYNCHRONOUS and run on main thread
}
currentUser is `private` and `static` and this method is the UNIQUE line of code that does an attribution to this field.
然而,用户在从该实体调用某些方法时得到 nullpointerexception...
解决方案
推荐阅读
- activemq - Hawtio 2.10.0 正在复制 jolokia 的 URL
- linux - 如何在 ubuntu 18.04 中安装我的 netfilter 模块
- flutter - 如何将烧瓶 scoketIO 连接到我的颤振聊天应用程序
- python - 在 MyPy 中定义可选容器类型参数类型的正确方法
- android - 如何从 android_alarm_manager 创建的隔离中调用 MethodChannel?
- java - Javafx 中的 ListView:单元工厂
- python - 从python中的字符串中提取n个第一个连续数字
- asp.net - 来自viewmodel的复选框asp.net mvc selectlistitem
- regex - 正则表达式 - 匹配直到可能出现或不出现的组
- docker - docker fluentd 这个命令行是什么意思?