1. 程式人生 > >Android6.0 原始碼修改之遮蔽導航欄虛擬按鍵(Home和RecentAPP)/動態顯示和隱藏NavigationBar

Android6.0 原始碼修改之遮蔽導航欄虛擬按鍵(Home和RecentAPP)/動態顯示和隱藏NavigationBar

轉載請註明出處:https://blog.csdn.net/u012932409/article/details/83063075

場景分析,
為了完全實現沉浸式效果,在進入特定的app後可以將導航欄移除,當退出app後再次將導航欄恢復。(下面將採用傳送廣播的方式來移除和恢復導航欄)

ps:不修改原始碼的情況下,簡單的沉浸式效果實現程式碼如下,在ACitivy中新增即可(此種做法的缺點是當介面彈出對話方塊時或者點選的螢幕的頂部或底部邊緣,會再次出現導航欄和狀態列)

    @Override
    public void onWindowFocusChanged(boolean
hasFocus) {//new add super.onWindowFocusChanged(hasFocus); if (hasFocus && Build.VERSION.SDK_INT >= 19) { View decorView = getWindow().getDecorView(); decorView.setSystemUiVisibility( //hide title&navigation View.
SYSTEM_UI_FLAG_FULLSCREEN |View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY |View.SYSTEM_UI_FLAG_HIDE_NAVIGATION); } }

一、遮蔽導航欄虛擬按鍵(Home和RecentAPP)

我們先來分析下底部導航欄所處的控制元件,
所見即所得,既然是虛擬按鍵,必定有相對應的View,要麼是xml的佈局檔案,要麼是自定義View,基於此思路,開啟AS中的Tools選單下Android–>Android Device Monitor–>Hierarchy View ,不會用的童鞋可以自己參考這篇

Hierarchy View,這裡就不再寫了。

我們發現Home按鍵對應的id為 @+id/home, 有了id我們就已經成功的揪出它了,接下來通過搜尋命令

grep -nr 命令

通過搜尋,我們發現了Home按鍵的 原始碼位置

frameworks\base\packages\SystemUI\res\layout-sw600dp\navigation_bar.xml
frameworks\base\packages\SystemUI\res\layout\navigation_bar.xml

         <!--2018-10-13 cczheng set home KeyButton  visibility  invisible-->
            <com.android.systemui.statusbar.policy.KeyButtonView android:id="@+id/home"
                android:layout_width="162dp" android:paddingStart="42dp" android:paddingEnd="42dp"
                android:layout_height="match_parent"
                android:src="@drawable/ic_sysbar_home"
                android:scaleType="centerInside"
                systemui:keyCode="3"
                systemui:keyRepeat="true"
                android:layout_weight="0"
                android:contentDescription="@string/accessibility_home"
                android:visibility="invisible"
                />
          <!--2018-10-13 cczheng set recent KeyButton  visibility  invisible-->
            <com.android.systemui.statusbar.policy.KeyButtonView android:id="@+id/recent_apps"
                android:layout_width="162dp" android:paddingStart="42dp" android:paddingEnd="42dp"
                android:layout_height="match_parent"
                android:src="@drawable/ic_sysbar_recent"
                android:scaleType="centerInside"
                android:layout_weight="0"
                android:contentDescription="@string/accessibility_recent"
                android:visibility="invisible"
                />

此處說下為什麼用invisible,而不用gone, 如果使用gone,剩下的按鍵將自動居中,這並不是我們想要的效果,當你以為按照上面的程式碼遮蔽後就可以安心的交差了,那你真是too young too simple了。

繼續搜尋 R.id.home,我們接下來查詢在java程式碼中的引用,找到位置

frameworks/base/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarView.java

    public View getBackButton() {
        ImageView view = (ImageView) mCurrentView.findViewById(R.id.back);
        view.setImageDrawable(mNavBarPlugin.getBackImage(view.getDrawable()));
        return view;
    }

很明顯通過getBackButton()方法能獲取到該View,就能對View進行操作,繼續檢視呼叫getBackButton()的地方

找到當前類中

    public void setDisabledFlags(int disabledFlags, boolean force) {
        if (!force && mDisabledFlags == disabledFlags) return;

        mDisabledFlags = disabledFlags;
		...

		getBackButton().setVisibility(disableBack ? View.INVISIBLE : View.VISIBLE);
        getHomeButton().setVisibility(disableHome ? View.INVISIBLE : View.VISIBLE);
        getRecentsButton().setVisibility(disableRecent ? View.INVISIBLE : View.VISIBLE);

        //2018-10-13 cczheng add recent KeyButton  visibility  invisible
        getHomeButton().setVisibility(View.INVISIBLE);  
        getRecentsButton().setVisibility(View.INVISIBLE);
        //2018-10-13 cczheng add recent KeyButton  visibility  invisible

     	 ...
    }

另外一處位於
frameworks\base\packages\SystemUI\src\com\android\systemui\statusbar\phone\PhoneStatusBar.java

    private void prepareNavigationBarView() {
        mNavigationBarView.reorient();

        mNavigationBarView.getRecentsButton().setOnClickListener(mRecentsClickListener);
        mNavigationBarView.getRecentsButton().setOnTouchListener(mRecentsPreloadOnTouchListener);
        mNavigationBarView.getRecentsButton().setLongClickable(true);
        mNavigationBarView.getRecentsButton().setOnLongClickListener(mLongPressBackRecentsListener);
        mNavigationBarView.getBackButton().setLongClickable(true);
        mNavigationBarView.getBackButton().setOnLongClickListener(mLongPressBackRecentsListener);
        mNavigationBarView.getHomeButton().setOnTouchListener(mHomeActionListener);
        mNavigationBarView.getHomeButton().setOnLongClickListener(mLongPressHomeListener);
        mAssistManager.onConfigurationChanged();

        //2018-10-13 cczheng set recent KeyButton  visibility  invisible
        mNavigationBarView.getHomeButton().setVisibility(View.INVISIBLE);  
        mNavigationBarView.getRecentsButton().setVisibility(View.INVISIBLE);
        //2018-10-13 cczheng set recent KeyButton  visibility  invisible

		....
     }

ok,大功告成,重新mm,編譯替換SystemUI.apk重啟檢視效果。

二、動態顯示和隱藏NavigationBar

文章開頭提到將以廣播的方式來實現動態顯示和隱藏NavigationBar這一功能,那麼我們改從哪裡入手呢?細心的你可能已經發現了上面的一個方法,prepareNavigationBarView()在PhoneStatusBar.java中,從方法名字就能猜到它和NavigationBar的載入有關。查詢prepareNavigationBarView()引用

    // For small-screen devices (read: phones) that lack hardware navigation buttons
    private void addNavigationBar() {
        if (DEBUG) Log.v(TAG, "addNavigationBar: about to add " + mNavigationBarView);
        if (mNavigationBarView == null) return;

        prepareNavigationBarView();

        mWindowManager.addView(mNavigationBarView, getNavigationBarLayoutParams());
    }

    private void repositionNavigationBar() {
        if (mNavigationBarView == null || !mNavigationBarView.isAttachedToWindow()) return;

        prepareNavigationBarView();

        mWindowManager.updateViewLayout(mNavigationBarView, getNavigationBarLayoutParams());
    }

共有兩處引用,很明顯找對地方了,在addNavigationBar()中,核心方法是通過mWindowManager.addView()新增的。看到這你應該明白了,導航欄其實就是一個在window最底部新增的View,既然有addView,對應就有removeView,查詢原始碼中並未發現提供了removeView方法。看來需要我們自己來實現這個方法。

PS:如果想實現遮蔽整個NavigationBar的效果,可直接將addNavigationBar()方法註釋

    @Override
    public void start() {
        mDisplay = ((WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE))
                .getDefaultDisplay();
        updateDisplaySize();
        mScrimSrcModeEnabled = mContext.getResources().getBoolean(
                R.bool.config_status_bar_scrim_behind_use_src);

        super.start(); // calls createAndAddWindows()

        mMediaSessionManager
                = (MediaSessionManager) mContext.getSystemService(Context.MEDIA_SESSION_SERVICE);
        // TODO: use MediaSessionManager.SessionListener to hook us up to future updates
        // in session state

        //"anotation this can hide navigationbar" 註釋此處的addNavigationBar即可
        addNavigationBar();

        // Lastly, call to the icon policy to install/update all the icons.
        mIconPolicy = new PhoneStatusBarPolicy(mContext, mCastController, mHotspotController,
                mUserInfoController, mBluetoothController);
        mIconPolicy.setCurrentUserSetup(mUserSetup);
        mSettingsObserver.onChange(false); // set up
	}

完整的通過廣播動態顯示和隱藏NavigationBar的程式碼如下所示:

    ////2018-10-13 cczheng hide or show navigationbat by broadcast 
    private NotifyChangeNavigationBarBroadcast mNotifyChangeNavigationBarBroadcast;
    private static final String SHOW_NAVIGATION = "cc.intent.systemui.shownavigation";
    private static final String HIDE_NAVIGATION = "cc.intent.systemui.hidenavigation";


	@Override
    public void start() {
        mDisplay = ((WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE))
                .getDefaultDisplay();
        updateDisplaySize();
        mScrimSrcModeEnabled = mContext.getResources().getBoolean(
                R.bool.config_status_bar_scrim_behind_use_src);

		....

		//2018-10-13 cczheng hide or show navigationbat by broadcast 
        mNotifyChangeNavigationBarBroadcast = new NotifyChangeNavigationBarBroadcast();
        IntentFilter mfilter = new IntentFilter();
        mfilter.addAction(HIDE_NAVIGATION);
        mfilter.addAction(SHOW_NAVIGATION);
        mContext.registerReceiver(mNotifyChangeNavigationBarBroadcast, mfilter);

	}


	private void prepareNavigationBarView() {
        mNavigationBarView.reorient();

        mNavigationBarView.getRecentsButton().setOnClickListener(mRecentsClickListener);
        mNavigationBarView.getRecentsButton().setOnTouchListener(mRecentsPreloadOnTouchListener);
        mNavigationBarView.getRecentsButton().setLongClickable(true);
        mNavigationBarView.getRecentsButton().setOnLongClickListener(mLongPressBackRecentsListener);
        mNavigationBarView.getBackButton().setLongClickable(true);
		.....
		//2018-10-13 cczheng hide or show navigationbat by broadcast start
        if (!isNavigationShow) {
            int newVal = mSystemUiVisibility;
            mSystemUiVisibility = View.SYSTEM_UI_FLAG_VISIBLE;
            setSystemUiVisibility(newVal, /*SYSTEM_UI_VISIBILITY_MASK*/Color.TRANSPARENT);
            int hints = mNavigationIconHints;
            mNavigationIconHints = 0;
            setNavigationIconHints(hints);
            topAppWindowChanged(mShowMenu);
        }
        //2018-10-13 cczheng hide or show navigationbat by broadcast end

	}

	//2018-10-13 cczheng hide or show navigationbat by broadcast start
    private static boolean isNavigationShow = true ;
    class NotifyChangeNavigationBarBroadcast extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.i(TAG, "NotifyChangeNavigationBarBroadcast: action =" + action); 
            if (HIDE_NAVIGATION.equals(action)) {
                isNavigationShow = false;
                hideNavigationBar();
            }else if (SHOW_NAVIGATION.equals(action)) {
                if (isNavigationShow) return;

                showNavigationBar();
            }
        }
    };

    private void showNavigationBar() {
        mNavigationBarView =(NavigationBarView) View.inflate(mContext, R.layout.navigation_bar, null);
        mNavigationBarView.setBar(this);
        
        addNavigationBar();
        isNavigationShow = true;

        // mNavigationBarView.setBackgroundColor(Color.TRANSPARENT);
    }

    private void hideNavigationBar() {
        Log.d(TAG, "hideNavigationBar: about to remove"  + mNavigationBarView);
        if (mNavigationBarView == null) return;

        mWindowManager.removeView(mNavigationBarView);
        mNavigationBarView = null;
    }
    //2018-10-13 cczheng hide or show navigationbat by broadcast end

ok, 動態顯示和隱藏NavigationBar的功能也搞定了。

三、總結

Hierarchy View是一個非常好用的利器,不僅是對原始碼分析查詢,當你要檢視借鑑別人的app時也會是一個非常好用的扳手。So,多研究研究吧。

下一篇將介紹在不修改原始碼的情況下,通過兩種方式實現載入loading對話方塊的功能(不退出沉浸式效果)