How to detect when an Android app goes to the background and come back to the foreground

后端 未结 30 1354
独厮守ぢ
独厮守ぢ 2020-11-22 00:56

I am trying to write an app that does something specific when it is brought back to the foreground after some amount of time. Is there a way to detect when an app is sent to

30条回答
  •  -上瘾入骨i
    2020-11-22 01:14

    The android.arch.lifecycle package provides classes and interfaces that let you build lifecycle-aware components

    Your application should implement the LifecycleObserver interface:

    public class MyApplication extends Application implements LifecycleObserver {
    
        @Override
        public void onCreate() {
            super.onCreate();
            ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
        }
    
        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        private void onAppBackgrounded() {
            Log.d("MyApp", "App in background");
        }
    
        @OnLifecycleEvent(Lifecycle.Event.ON_START)
        private void onAppForegrounded() {
            Log.d("MyApp", "App in foreground");
        }
    }
    

    To do that, you need to add this dependency to your build.gradle file:

    dependencies {
        implementation "android.arch.lifecycle:extensions:1.1.1"
    }
    

    As recommended by Google, you should minimize the code executed in the lifecycle methods of activities:

    A common pattern is to implement the actions of the dependent components in the lifecycle methods of activities and fragments. However, this pattern leads to a poor organization of the code and to the proliferation of errors. By using lifecycle-aware components, you can move the code of dependent components out of the lifecycle methods and into the components themselves.

    You can read more here: https://developer.android.com/topic/libraries/architecture/lifecycle

提交回复
热议问题