Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
121 views
in Technique[技术] by (71.8m points)

android - How to detect when the notification/system bar is opened

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...