android.app.Application 无法转换为 LifecycleOwner

Luk*_*der 5 android android-lifecycle androidx

不幸的是,我不能使用 getApplication() 作为 LifecycleOwner,因为 android.app.Application 似乎没有实现它。

为什么 android.app.Application 没有实现 LifecycleOwner?

我尝试使用 getApplication() 作为 LiveData 的 LifecycleOwner 的代码:

result.observe(getApplication(), ....);
Run Code Online (Sandbox Code Playgroud)

摇篮:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "XXXX"
        minSdkVersion 15
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        vectorDrawables.useSupportLibrary = true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility = '1.8'
        targetCompatibility = '1.8'
    }

}

dependencies {
    // GENERAL
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'com.google.android.material:material:1.1.0-alpha07'
    implementation "androidx.room:room-runtime:2.1.0"
    annotationProcessor "androidx.room:room-compiler:2.1.0"
    implementation "androidx.lifecycle:lifecycle-extensions:2.0.0"
    annotationProcessor "androidx.lifecycle:lifecycle-compiler:2.0.0"
    implementation "androidx.navigation:navigation-fragment:2.1.0-alpha05"
    implementation "androidx.navigation:navigation-ui:2.1.0-alpha05"

    // Third party libraries

    // Jetbrains
    implementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.3.31'
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.0.0'

    // Glide
    implementation 'com.github.bumptech.glide:glide:4.9.0'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.9.0'

    // Fotoapparat
    implementation 'io.fotoapparat:fotoapparat:2.7.0'

    // TEST
    testImplementation 'junit:junit:4.12'

    // ANDROID TEST
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    androidTestImplementation "androidx.room:room-testing:2.1.0"
}

Run Code Online (Sandbox Code Playgroud)

错误:

java.lang.ClassCastException: ...
android.app.Application cannot be cast to androidx.lifecycle.LifecycleOwner
Run Code Online (Sandbox Code Playgroud)

Com*_*are 13

为什么 android.app.Application 没有实现 LifecycleOwner?

它没有生命周期。它被创建,然后存在于整个过程的存在中。

我尝试使用 getApplication() 作为 LiveData 的 LifecycleOwner 的代码:

要么使用具有实际生命周期(活动、片段等)的东西,要么使用observeForever().