小编Nik*_*ola的帖子

应用程序恢复后,Singleton对象变为null

对于我的Android项目,我需要全局单例Cache对象来通过应用程序访问有关用户的数据.

当应用程序进入后台并且在使用其他应用程序一段时间后我尝试在Cache对象中打开应用程序变量时出现问题.当我杀死应用程序并再次打开它时,一切都很好.我正在使用依赖注入来访问Cache对象.如果发生这种情况,为什么app不会再次启动?是否有一些注释可以在低内存条件下保持缓存变量?

这是我的Cache类

class Cache {
    var categories : Array<BaseResponse.Category>? = null
    var user : BaseResponse.User? = null
    var options : BaseResponse.OptionsMap? = null
    var order: MenuOrderDataModel? = null
}
Run Code Online (Sandbox Code Playgroud)

这是DI的存储模块

@Module class StorageModule {

    @Singleton @Provides fun getSharedPrefs(context: Context): SharedPreferences {
        return PreferenceManager.getDefaultSharedPreferences(context)
    }


    @Singleton @Provides fun getCache() : Cache = Cache()
}
Run Code Online (Sandbox Code Playgroud)

我注入对象@Inject lateinit var cache: Cache,然后在启动画面中填充用户数据.

编辑 - 从应用程序和启动活动添加的代码片段

class MyApp : Application() {
    val component: ApplicationComponent by lazy {
        DaggerApplicationComponent
                .builder()
                .appModule(AppModule(this))
                .build()
    } …
Run Code Online (Sandbox Code Playgroud)

android caching dependency-injection kotlin dagger-2

5
推荐指数
1
解决办法
3205
查看次数