Determining the current foreground application from a background task or service

后端 未结 13 1437
我寻月下人不归
我寻月下人不归 2020-11-22 02:29

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

13条回答
  •  无人及你
    2020-11-22 02:58

    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);
    }
    

提交回复
热议问题