匕首 2 和 Activity 被杀

Dagger 2 and Activity killed

我有一个使用 Dagger2 的应用程序 在Application的onCreate中实例化组件:

@Override
public void onCreate() {
    super.onCreate();
    mComponent =  DaggerApplicationComponent.builder()
            .applicationModule(new ApplicationModule(this))
            .build();
}

Dagger 正在管理一个 "CacheRepository",这是一个 class 存储用户在整个应用程序中使用的数据。

我遇到的问题是:当应用程序被系统杀死时,应用程序被销毁,组件实例丢失。但是当我再次启动该应用程序时,该应用程序会尝试恢复其先前的状态,其中包括从现在已重新初始化的缓存中获取数据。因此应用程序崩溃,因为数据为空。

我该如何预防?

一个简单的选择是强制应用程序在被系统杀死时从头开始重新启动,但我还没有找到任何解决方案。

另一种解决方案是将缓存存储在 SharedPreferences(或任何类型的存储)中,但我不喜欢这种解决方案,因为缓存中的大部分数据都是临时的,这会使应用程序更加复杂。

您可以使用 Realm、sqllite 等在 IE 本地保存数据。另一种解决方案是为您的匕首 CacheRepository 查看自定义范围。

在 Dagger 2 范围机制中,只要其范围存在,就会保持 class 的单个实例。实际上,这意味着 @ApplicationScope 范围内的实例与 Application 对象一样长。只要 Activity 存在,@ActivityScope 就会保留引用(例如,我们可以在这个 Activity 中托管的所有片段之间共享任何 class 的单个实例)。

来源:Dependency injection with Dagger 2 - Custom scopes

感谢

,我想我找到了解决方案

想法是如果应用程序已被终止,则强制应用程序从头重新启动(例如启动画面)。

in onCreate() of all activities, check if the "app initialization" has been performed by using a public static variable or singleton. If the initialization has not been done, you know that your app's process was killed and recreated and you need to either redirect the user to your root Activity (ie: start the app all over again) or do the initialization immediately in the onCreate() of the Activity.

这可能不是最好的解决方案,但至少非常简单。而且您不会冒损坏数据或存储您只想在应用程序生命周期内保留的内容的风险。