在 androidx.appcompat:appcompat:1.1.0 中找不到 LocalBroadcastManager 但在 1.0.0 中可用

LocalBroadcastManager not found in androidx.appcompat:appcompat:1.1.0 but available in 1.0.0

我刚刚通过 Android Studio 中的 Refactor -> Move to Androidx 选项迁移到了 androidx。 默认情况下,build.gradle 文件使用:

implementation 'androidx.appcompat:appcompat:1.0.0'

我在项目的很多地方都在使用LocalBroadcastManager。我可以完美地将 import androidx.localbroadcastmanager.content.LocalBroadcastManager 与上述 androidx.appcompat 的 v1.0.0 一起使用。但是当我将它更新为 1.1.0 时:

implementation 'androidx.appcompat:appcompat:1.1.0'

导入无效。我收到 Unresolved reference : localbroadcastmanager 错误。

我已经多次尝试清理项目并重建项目,但问题仍然存在。

有什么解决办法吗?谢谢。

AppCompat 1.0.0 对 legacy-support-core-utils 具有传递依赖性(包括 localbroadcastmanager,以便与最新的支持库 28.0.0 版本保持完全兼容。

AppCompat 1.1.0 删除了传递依赖,现在只依赖于它需要的确切库。

因此如果你的应用代码还需要LocalBroadcastManager,你需要手动添加对LocalBroadcastManager的依赖:

implementation "androidx.localbroadcastmanager:localbroadcastmanager:1.0.0"

请注意,根据 LocalBroadcastManager 1.1.0-alpha01 release notes

androidx.localbroadcastmanager is being deprecated in version 1.1.0-alpha01.

Reason

  • LocalBroadcastManager is an application-wide event bus and embraces layer violations in your app; any component may listen to events from any other component.
  • It inherits unnecessary use-case limitations of system BroadcastManager; developers have to use Intent even though objects live in only one process and never leave it. For this same reason, it doesn’t follow feature-wise BroadcastManager.

These add up to a confusing developer experience.

Replacement

You can replace usage of LocalBroadcastManager with other implementations of the observable pattern. Depending on your use case, suitable options may be LiveData or reactive streams.