I wish to have one application that runs in the background, which knows when any of the built-in applications (messaging, contacts, etc) is running.
So my questions
For cases when we need to check from our own service/background-thread whether our app is in foreground or not. This is how I implemented it, and it works fine for me:
public class TestApplication extends Application implements Application.ActivityLifecycleCallbacks {
public static WeakReference foregroundActivityRef = null;
@Override
public void onActivityStarted(Activity activity) {
foregroundActivityRef = new WeakReference<>(activity);
}
@Override
public void onActivityStopped(Activity activity) {
if (foregroundActivityRef != null && foregroundActivityRef.get() == activity) {
foregroundActivityRef = null;
}
}
// IMPLEMENT OTHER CALLBACK METHODS
}
Now to check from other classes, whether app is in foreground or not, simply call:
if(TestApplication.foregroundActivityRef!=null){
// APP IS IN FOREGROUND!
// We can also get the activity that is currently visible!
}
Update (as pointed out by SHS):
Do not forget to register for the callbacks in your Application class's onCreate
method.
@Override
public void onCreate() {
...
registerActivityLifecycleCallbacks(this);
}