如何在重新创建活动后处理 onCreate 中 Dagger 注入所需的未初始化资源?

如何解决如何在重新创建活动后处理 onCreate 中 Dagger 注入所需的未初始化资源?

我正在将 Dagger 添加到我的旧版 Android 应用程序中,并试图弄清楚如何处理依赖于非 Dagger 对象的依赖项,这些对象在正常应用程序初始化期间创建,但在后台 + 不活动后重新启动活动期间不会重新创建。

现有代码

在旧代码中,在身份验证代码路径期间,我们构造了一个“会话”对象,其中包含创建经过身份验证的 Retrofit 对象所需的令牌和其他内容。某些活动依赖于该会话对象的存在,并且用户没有通过身份验证代码路径访问它们的正常方法。但是,如果应用程序处于非活动状态,然后在稍后恢复,则平台将尝试直接重新创建活动而不通过身份验证代码路径,因此会话对象将为空。

为了防止出现这种情况,历史上每个依赖于登录的活动都源自“SessionActivity”,其 onCreate 检查我们是否已登录,如果没有完成活动并启动应用程序的入口点。 (这将触发重新创建“会话”对象;用户将不得不再次导航回该屏幕,但至少没有崩溃)

class SessionActivity {

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);

    if( LegacySingleton.getInstance().session == null ) {
    {
        Intent intent = new Intent(this,LauncherActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        finish();
        return;
    }
}

}

新代码

我现在正在添加 Dagger,并且希望能够注入使用该会话对象构建的 Retrofit 对象。

@Provides
fun provideRetrofit(): Retrofit {
    return LegacySingleton.getInstance().session!!.authenticatedRetrofit
}

然后一个依赖于登录的示例活动将有一个 onCreate 之类的

@Override
protected void onCreate(Bundle savedInstanceState)
{
    ((MyComponentProvider) getApplicationContext()).getComponent().inject(this);
    super.onCreate(savedInstanceState);
}

有一个明显的问题:如果 LegacySingleton.getInstance().session 返回 null(就像在重新创建路径中一样),那么我们就会崩溃。是否有解决此问题的通用模式?

尝试 1:

如果 session 为 null,我的第一个倾向是在 provideRetrofit 中抛出 IllegalStateException,然后依赖登录的活动会说

@Override
protected void onCreate(Bundle savedInstanceState)
{
    try {
       ((MyComponentProvider) getApplicationContext()).getComponent().inject(this);
   } catch (ex: IllegalStateException) {
        Intent intent = new Intent(this,LauncherActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        finish();
        return;
   }        
    super.onCreate(savedInstanceState);
}

(显然这会被考虑到辅助方法中,但为了简单起见,这里写出来)

但是,这行不通,因为 Android 要求所有对 onCreate 的调用都调用到 super.onCreate。

尝试 2:

我可以说

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    try {
       ((MyComponentProvider) getApplicationContext()).getComponent().inject(this);
   } catch (ex: IllegalStateException) {
        Intent intent = new Intent(this,LauncherActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        finish();
        return;
   }        
}

但这打破了在super.onCreate之前注入的dagger原则。 (然后确保依赖项准备就绪,以防 super.onCreate 回调到派生类并需要这些依赖项之一)所以这在某些情况下可能有效,但如果有人开始依赖 super.onCreate 中的这些依赖项,那么我会在运行时命中 NPE。不太好。

尝试 3:

我可以执行注入并跟踪它是否成功,例如

@Override
protected void onCreate(Bundle savedInstanceState)
{
    Val injectionSucceeded = try {
       ((MyComponentProvider) getApplicationContext()).getComponent().inject(this);
       true
   } catch (ex: IllegalStateException) {
       false
   }
    super.onCreate(savedInstanceState);
   If (!injectionSucceeded)
        Intent intent = new Intent(this,LauncherActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        finish();
        return;
   }        
}

但是和尝试2有同样的问题;如果注入失败,那么我无论如何都会调用 super.onCreate 并且并非所有依赖项都已注入。

尝试 4:

我可以改为提供 Nullable 对象

@Provides
fun provideRetrofit(): Retrofit? {
    return LegacySingleton.getInstance().session?.authenticatedRetrofit
}

但是每个客户端都需要在使用依赖项之前检查它们的可空性,这将是一个巨大的痛苦。 (我什至不确定这是否可能)

Codelab 建议:

Google 的 Dagger 代码实验室提到了这个问题:https://developer.android.com/codelabs/android-dagger#12

重要:进行条件字段注入(正如我们所做的那样) 在 MainActivity.kt 中,仅当用户登录时注入)是 非常危险。开发商必须了解条件和 与注入的交互时,您可能会遇到 NullPointerExceptions 领域。为了避免这个问题,我们可以通过创建一个添加一些间接 SplashScreen 路由到注册、登录或主界面 取决于用户的状态。

但这对于现有的应用程序来说似乎不切实际,因为它有十几个 SessionActivity 子类想要向自己注入 Retrofit 对象。

有人有更好的主意吗?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 <select id="xxx"> SELECT di.id, di.name, di.work_type, di.updated... <where> <if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 <property name="dynamic.classpath" value="tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-