android - 单例对象的变量随机设置为 NULL
问题描述
有时我注意到当我将应用程序从后台带到前台时,单例对象的值设置为 NULL,我相信这与我的启动模式设置有关
<application
android:name="FooApplication"
android:allowBackup="false">
<activity
android:name="SplashActivity"
android:launchMode="singleTask">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="MainActivity"
android:launchMode="singleTop" />
</application>
这是流 Splash -> Main。这就是我从 SplashActivity 启动 Main Activity 的方式。
val nextIntent = Intent(context, MainActivity::class.java);
nextIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
startActivity(intent)
finish()
我使用 Koin 从应用程序类中注入一些单例对象。
class ProductManager() {
internal var productsMap: MutableMap<String, String> = ConcurrentSkipListMap(String.CASE_INSENSITIVE_ORDER)
//This is being populated by some method call from SplashActivity
}
现在,当我在 MainActivity 上将应用程序从后台带到前台时,90% 的时间我都可以看到值存在。但是,有时 ProductManager.productsMap 为 NULL,尽管 ProductManager 本身不为 NULL。
我假设 MainActivity 被进程杀死并且数据丢失。如果数据丢失,为什么注入 MainActivity 的 ProductManager 对象不为 NULL,但它的属性为 NULL。这不应该发生,因为 Activity 已被杀死,但该进程仍然存在,因为当我启动它时,它仍然会转到 MainActivity,它是当前的顶部,不会再次重新启动应用程序。
我不想存储来自 Bundle 或 SharedPreference 的数据。我能否重新启动应用程序,该应用程序将自动引导数据,而不是从 Singleton 获取 NULL 值。
解决方案
当应用程序在后台时,您的进程被杀死。当用户返回应用程序时,Android 会创建一个新进程,并且它仅实例化堆栈Activity
顶部的MainActivity
SplashActivity
null
您需要将数据存储在其他地方(永久),或者您需要检测 Android 已终止该进程并在检测到该进程时重新初始化您的内存中数据。
我已经回答了很多关于如何做到这一点的问题。看看这些:
https://stackoverflow.com/a/29802601/769265
推荐阅读
- java - 如何制作上升(三角形)搜索栏Android
- image - 为什么我们要在 CNN 之前对图像进行归一化?
- python - Python - 启动分离的进程,等待标准输出中的特定输出,然后继续
- typescript - 使用类型将自定义对象属性初始化为未定义?
- java - Jackson 将 POJO 转换为 Map 时将 Set 转换为 List
- c# - Blazor 中的数据表:Dispose() 不起作用
- .net - SSRS集成.Net MVC,我的reportviewer webcontrol总是链接到jquery.min.js 3.1.1版本
- mysql - 在sql中创建一个动态时间范围
- android - Firebase 跟踪的 in_app_purchase 事件是 Play 控制台中实际购买的一半
- python - 如何在 django 中向 3rd 方应用程序发送发布请求?