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
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