如何检测通知/系统栏何时打开 [英] How to detect when the notification/system bar is opened

查看:85
本文介绍了如何检测通知/系统栏何时打开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要知道何时在我的应用程序中打开系统/通知栏,并且找不到任何真正的解决方案,所以我一起破解了一些看起来不错的东西.

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.

推荐答案

在开始实施之前,我将简要介绍一下我的(非常hacky)逻辑.如果由于某种原因用户不再可见活动",则会调用onWindowFocusChanged(..).但是,仅当活动不再对用户可见时才通过调用后台调用onStop().我注意到在切换活动时,总是在onWindowFocusChanged(..)之后调用onStop(),因此我在onWindowFocusChanged(..)中添加了一个检查,以查看是否已经调用过onStop()(延迟了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;

然后在onStop()方法中添加此行,并确保在super.onStop()之前调用它.

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

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

最后,您需要在此父活动中重写onWindowFocusChanged(..),并添加以下逻辑.

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

这篇关于如何检测通知/系统栏何时打开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆