Checking if an Android application is running in the background

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

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

30条回答
  •  旧时难觅i
    2020-11-21 07:10

    GOOGLE SOLUTION - not a hack, like previous solutions. Use ProcessLifecycleOwner

    Kotlin:

    class ArchLifecycleApp : Application(), LifecycleObserver {
    
        override fun onCreate() {
            super.onCreate()
            ProcessLifecycleOwner.get().lifecycle.addObserver(this)
        }
    
        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        fun onAppBackgrounded() {
            //App in background
        }
    
        @OnLifecycleEvent(Lifecycle.Event.ON_START)
        fun onAppForegrounded() {
            // App in foreground
        }
    
    }
    


    Java:

    public class ArchLifecycleApp extends Application implements LifecycleObserver {
    
        @Override
        public void onCreate() {
            super.onCreate();
            ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
        }
    
        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        public void onAppBackgrounded() {
            //App in background
        }
    
        @OnLifecycleEvent(Lifecycle.Event.ON_START)
        public void onAppForegrounded() {
            // App in foreground
        }
    }
    

    in app.gradle

    dependencies {
        ...
        implementation "android.arch.lifecycle:extensions:1.1.0"
    
        //New Android X dependency is this - 
        implementation "androidx.lifecycle:lifecycle-extensions:2.0.0"
    
    }
    
    allprojects {
        repositories {
            ...
            google()
            jcenter()
            maven { url 'https://maven.google.com' }
        }
    }
    

    You can read more about Lifecycle related architecture components here - https://developer.android.com/topic/libraries/architecture/lifecycle

提交回复
热议问题