打开时关闭状态栏:Android

por*_*der 2 android statusbar

我试图想出一些方法来禁用状态栏而不完全隐藏它。这是在 3rd 方应用程序中禁用状态栏的介绍尝试。目前,我想在我自己的应用程序中禁用它,然后最终创建一个后台服务,看看我是否可以在其他应用程序中这样做。我正在创建的应用程序是一个面向儿童的操作系统,我正在尝试开发一个封闭的系统。

这是我尝试过的。我最初的想法是监控状态栏何时被访问,然后关闭它。

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    Log.i(TAG, "onWindowFocusChanged()");
    try {
        if (!hasFocus) {
            Log.d(TAG, "close status bar attempt");
            Object service = getSystemService("statusbar");
            Class<?> statusbarManager = Class
                    .forName("android.app.StatusBarManager");
            Method collapse = statusbarManager.getMethod("collapse");
            collapse.setAccessible(true);
            collapse.invoke(service);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我使用的方法。它用于检测何时访问状态栏,但是,一旦获得焦点,它就不会关闭状态栏。我错过了什么?提前致谢。

por*_*der 5

我找到了我的问题的答案。首先,我缺少以下权限

<uses-permission android:name="android.permission.EXPAND_STATUS_BAR" />
Run Code Online (Sandbox Code Playgroud)

有了这个权限,下面的代码现在工作得很好。

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    Log.i(TAG, "onWindowFocusChanged()");
    try {
        if (!hasFocus) {
            Log.d(TAG, "close status bar attempt");
            //option 1
            int currentApiVersion = android.os.Build.VERSION.SDK_INT;
            Object service = getSystemService("statusbar");
            Class<?> statusbarManager = Class
                    .forName("android.app.StatusBarManager");

            if (currentApiVersion <= 16) {
                Method collapse = statusbarManager.getMethod("collapse");
                collapse.setAccessible(true);
                collapse.invoke(service);
            } else {
                Method collapse = statusbarManager.getMethod("collapsePanels");
                collapse.setAccessible(true);
                collapse.invoke(service);
            }
            // option 2
            Intent it = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
            mContext.sendBroadcast(it); 

        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您注意到,还有第二个选项,我发现它运行良好。如果要使用选项 2,可以注释掉选项 1,反之亦然。两者都完成相同的事情,尽管我认为选项 2 更好。

Intent it = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
mContext.sendBroadcast(it); 
Run Code Online (Sandbox Code Playgroud)

我发现唯一的缺点是关闭时它很慢(呃)。但是,这两种方法的崩溃速度都足够快,以至于没有人可以单击状态栏中的任何通知或选项。希望这对其他人有帮助。祝你好运,干杯!