如何阻擋android原生的statusBar


Posted by Limon on 2021-07-30

因為公司要做自己的Launcher,花了非~~~~長多的時間研究怎麼樣可以阻擋原生的statusBar(就是手機的狀態欄,下拉會有notification與setting開關),查到的方法大部分都是去修改android原生系統的程式碼,但公司的機種會隨著android系統升級,這就代表如果去改原生地程式碼,未來升級時要花更多的心力去更新,因此只能另尋他法。

我最後採用的方法是"使用浮動視窗去遮蓋status bar"
優點:

  • 方便,不影響原生的程式碼

缺點:

  • 因為我們開發的是Launcher,如果客戶有自己的需求,需要去開發全螢幕的app,會導致原本是status bar的地方被遮住不能click。

首先,要開啟浮動視窗權限,這裡就不教怎麼開了,隨便google就很多答案,根據你的android版本選最佳答案即可。

再來,建立一個View後addView到現在的畫面上,isForeground是用來控制是否覆蓋住statusBar的boolean

WindowManager.LayoutParams localLayoutParams = new WindowManager.LayoutParams();
        localLayoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ERROR;
        localLayoutParams.gravity = Gravity.TOP;
        localLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
                WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;

        localLayoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
        if (isForeground) {
            localLayoutParams.height = getStatusBarHeight();
        } else {
            localLayoutParams.height = getStatusBarHeight() + 100;
        }
        Log.d(TAG, String.format("Set StatusBarBlocker as %d", localLayoutParams.height));
        localLayoutParams.format = PixelFormat.TRANSPARENT;

        /*這一行新增自己要的View,我自己新增了一個class叫CustomViewGroup.java*/
        CustomViewGroup tmp = new CustomViewGroup(this, manager, adminModeConfig, this,notiListAdapter);

        manager.addView(tmp, localLayoutParams);

CustomViewGroup是用來控制下拉後的View,你可以新增自己想要的View

如何拿到原生statusBar的Height:

private int getStatusBarHeight() {

        int result = 0;
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

補充一下:
不知道為什麼每次重新做onResume的時候都需要重新跑一次浮動視窗的程式碼(我也不知道為什麼...,有人研究出來的話可以告訴我嗎T_T),建議設成函數比較好重複使用,因為總是有需要設成false的時候嘛XD


#Android #Launcher







Related Posts

[ 筆記 ] DOM - 事件傳遞機制:捕獲與冒泡、事件代理

[ 筆記 ] DOM - 事件傳遞機制:捕獲與冒泡、事件代理

後端系統架構圖

後端系統架構圖

AWS Solutions Architect - Associate (SAA) 學習計畫與備考心得: Module 7

AWS Solutions Architect - Associate (SAA) 學習計畫與備考心得: Module 7


Comments