首页 > 解决方案 > 单例对象的变量随机设置为 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 值。

标签: androidandroid-intentandroid-lifecyclekoin

解决方案


当应用程序在后台时,您的进程被杀死。当用户返回应用程序时,Android 会创建一个新进程,并且它仅实例化堆栈Activity顶部的MainActivitySplashActivitynull

您需要将数据存储在其他地方(永久),或者您需要检测 Android 已终止该进程并在检测到该进程时重新初始化您的内存中数据。

我已经回答了很多关于如何做到这一点的问题。看看这些:

https://stackoverflow.com/a/29802601/769265

https://stackoverflow.com/a/27276077/769265

https://stackoverflow.com/a/11249090/769265


推荐阅读