迁移以使用主模块中的 Kotlin 扩展 (KTX) API

Firebase 正在加大对 Kotlin 的投入,并且我们正在努力实现 Android 生态系统的现代化改造,使 Kotlin 在 Firebase 中更易于访问和使用。

为实现这一现代化改造,我们对 Firebase Android SDK 进行了一些更改。本页面介绍了有关此更改的重要信息,包括:


了解如何迁移应用

有哪些变化?

Kotlin 扩展 (KTX) API 已添加到其各自的主模块中。例如,firebase-perf-ktx 中的所有 API 均已添加到 com.google.firebase.perf 包下的 firebase-perf 中。

这项更改意味着,Kotlin 开发者现在可以依赖于主模块,而不是 KTX 模块(使用 Firebase BoM v32.5.0+ 或 BoM v32.5.0+ 中列出的主模块版本时)。

作为此更改的一部分,每个 KTX 模块中的 Kotlin 扩展 (KTX) API 现已弃用。最早从 2024 年 4 月开始,我们将不再发布 KTX 模块,届时我们还将从 Firebase Android BoM 中移除 KTX 库。

为什么要进行此变更?

Firebase 致力于为 Android 开发者打造 Kotlin-first 的生态系统。这种封装现代化改造具有以下优势:

  • 简化了依赖项管理:现在您只需依赖于单个模块,而无需在主模块和 Kotlin 扩展之间切换,也无需同时依赖于两者。

  • 增强了 Kotlin 支持:所有 Firebase Android SDK 现在都可以为 Kotlin 提供更好的支持。我们将直接在主模块中添加所有适用于 Kotlin 的新功能。

此更改的重要日期

2023 年 10 月

Kotlin 扩展程序 (KTX) API 已添加到其各自的主模块,这意味着,在使用 Firebase BoM v32.5.0+ 或 BoM v32.5.0+ 中列出的主模块版本时,您现在可以直接从主模块使用 KTX API。

同时,KTX 模块中的 Kotlin 扩展程序 (KTX) API 已弃用(请参阅说明这项变更的版本说明)。弃用阶段,KTX 模块中弃用的 API 将继续正常运行和维护。

最早 2024 年 4 月

我们将停止发布 KTX 模块的新版本,并从 Firebase BoM 中移除 KTX 模块。

之前发布的任何 KTX 模块或 BoM 版本都将继续正常运行,但将进入维护终止阶段。这意味着我们将停止向 KTX 模块添加问题修复、向后兼容的更改和新功能。针对 Android 上的 Firebase 的所有未来开发都将在主模块(对于 Java 和 Kotlin)中完成。

如何迁移以使用主模块中的 KTX API

如果您使用 Kotlin 扩展程序 (KTX) API,请在您的应用中进行以下更新,以便开始使用主模块(而不是 KTX 模块)中的 API。

  1. 修改 Gradle 依赖项,以依赖于主模块,而不是 KTX 模块。例如,如果您使用 Firebase Android BoM(推荐)

    之前

    dependencies {
      // ...
    
      // Import the Firebase BoM
      implementation(platform("com.google.firebase:firebase-bom:32.7.4"))
    
      // Using KTX libraries for Authentication and Cloud Firestore
      implementation("com.google.firebase:firebase-auth-ktx")
      implementation("com.google.firebase:firebase-firestore-ktx")
    }
    

    升级后

    dependencies {
      // ...
    
      // Import the Firebase BoM as usual
      // Make sure to use Firebase BoM v32.5.0 or higher
      implementation(platform("com.google.firebase:firebase-bom:32.7.4"))
    
      // No need to use the KTX libraries, everything is now in the main module
      implementation("com.google.firebase:firebase-auth")
      implementation("com.google.firebase:firebase-firestore")
    }
    


  2. 更新您的代码,将出现的所有 KTX API 替换为 com.google.firebase 包下的主模块中重新定位的 API。

    之前

    import com.google.firebase.auth.ktx.auth
    import com.google.firebase.firestore.ktx.firestore
    import com.google.firebase.firestore.ktx.toObject
    import com.google.firebase.ktx.Firebase
    

    升级后

    import com.google.firebase.auth.auth
    import com.google.firebase.firestore.firestore
    import com.google.firebase.firestore.toObject
    import com.google.firebase.Firebase