How to detect when the notification/system bar is opened

瘦欲@ 提交于 2019-11-27 02:18:01

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);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!