android - LifecycleObserver 使用较新 API 的方法产生异常

标签 android kotlin android-lifecycle fragment-lifecycle

我的 ViewModel 类实现了 LifecycleObserver。 当我调用 fragment.lifecycle.addObserver(this) 时,它会产生异常。

Caused by: java.lang.IllegalArgumentException: The observer class has some methods that use newer APIs which are not available in the current OS version. Lifecycles cannot access even other methods so you should make sure that your observer classes only access framework classes that are available in your min API level OR use lifecycle:compiler annotation processor.

奇怪,本来还好好的,前不久就出现了这个异常。我发现,audioFocusRequest 是导致此错误的原因。

private val audioFocusRequest by lazy {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
        .setOnAudioFocusChangeListener(this)
        .build() else throw RuntimeException("Can't be done for Android API lower than 26")
}

有人知道怎么解决吗?

UPD

尝试使用 annotationProcessor "androidx.lifecycle:lifecycle-compiler:$lifecycle_version",但出现编译错误: enter image description here (决定粘贴截图,因为整个日志很大)

UPD 2
最后,我决定删除 audioFocusRequest 字段并使用旧的弃用方法 - requestAudioFocus(OnAudioFocusChangeListener l, int streamType, int durationHint) 而不是推荐的 requestAudioFocus (@NonNull AudioFocusRequest focusRequest)

它帮助我使代码再次工作,所以它可以成为解决方案。但我没有找到答案——为什么会出现这个问题。这很奇怪,因为以前的代码可以正常工作。

所以问题已经解决,但问题仍然没有答案

最佳答案

尝试使用kapt "androidx.lifecycle:lifecycle-compiler:2.0.0"

关于android - LifecycleObserver 使用较新 API 的方法产生异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54555764/

相关文章:

带有 RecyclerView 的 Android BottomSheet

android - 如何使用jetpack compose删除卡片 View 的边框

android - CursorAdapter changeCursor bolck ui thread in android

android - 我在kotlin类中的代码会自动替换为Android Studio中的一些XML代码

android 保存以编程方式创建的 View

java - AndroidViewModel 没有零参数构造函数

android - Proguard Gradle 重复的 jar

Android资源编译失败(values.xml :200: error: invalid color)

android - 使用流作为 API 调用的返回类型

android - 如何通过深度链接在不丢失 Activity 堆栈(或应用程序状态)的情况下恢复 Android 应用程序?