How to detect when the notification/system bar is

2019-01-07 01:27发布

问题:

I needed to know when the system/notification bar gets opened in my app, and I couldn't find any real solutions, so I hacked something together which seems to work pretty well.

回答1:

Before I big with the implementation, I will give a brief explanation of my (very hacky) logic. When an Activity is no longer visible to the user for any reason, onWindowFocusChanged(..) gets invoked. However, onStop() only gets invoked when the Activity is no longer visible to the user by going to the background. I noticed that when switching Activities, onStop() is always invoked after onWindowFocusChanged(..), so I added a check in onWindowFocusChanged(..) to see if onStop() had already been invoked (with a 1 second delay), and I did this using the static member. Now for the how-to...

You will need a parent Activity that all the Activities in your app extend. In this parent Activity, add this static member:

private static boolean wasOnStopCalledAfterOnWindowFocusChanged;

Then in your onStop() method, add this line, make sure you invoke it BEFORE super.onStop()

@Override
protected void onStop() {
    wasOnStopCalledAfterOnWindowFocusChanged = true;
    super.onStop();
}

Finally, you need to override onWindowFocusChanged(..) in this parent Activity, and add in the below logic.

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    if (!hasFocus) {
        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
                if (!wasOnStopCalledAfterOnWindowFocusChanged) {

                    // NOTIFICATION BAR IS DOWN...DO STUFF

                }
                wasOnStopCalledAfterOnWindowFocusChanged = false;
            }
        }, 1000);
    }
}