Checking if an Android application is running in the background

前端 未结 30 2801
无人共我
无人共我 2020-11-21 06:19

By background, I mean none of the application\'s activities are currently visible to the user?

30条回答
  •  盖世英雄少女心
    2020-11-21 06:51

    Starting support library version 26 you can use ProcessLifecycleOwner, just add it to your dependency like described here, for example:

    dependencies {
        def lifecycle_version = "1.1.1"
    
        // ViewModel and LiveData
        implementation "android.arch.lifecycle:extensions:$lifecycle_version"
        // alternatively - Lifecycles only (no ViewModel or LiveData).
        //     Support library depends on this lightweight import
        implementation "android.arch.lifecycle:runtime:$lifecycle_version"
        annotationProcessor "android.arch.lifecycle:compiler:$lifecycle_version" // use kapt for Kotlin
    }
    

    And then just query ProcessLifecycleOwner whenever you want for app state, examples:

    //Check if app is in background
    ProcessLifecycleOwner.get().getLifecycle().getCurrentState() == Lifecycle.State.CREATED;
    
    //Check if app is in foreground
    ProcessLifecycleOwner.get().getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.STARTED);
    

提交回复
热议问题