android detect Samsung Galaxy S8 navigation bar hide or show programmatically

4.2k views Asked by At

On some devices such as Samsung S8, navigation bar can be hide or show, that's a question in some condition. Samsung S8's navigation bar can be hide or show by click left bottom button

I didn't find straight way to determine even if in the Android sources code.

And I google some issues, such as A good solution to check for navigation bar , but it doesn't help.

Any help is very appreciated.

2

There are 2 answers

4
Haomin On

First, credit the original author: https://www.jianshu.com/p/ddfbabd614b6

For the Samsung phones (i.e, S8, S9, etc) you can detect if the navigation bar is showing via listening to a Samsung event.

private static final String SAMSUNG_NAVIGATION_EVENT = "navigationbar_hide_bar_enabled";

Then just listen to this event, and do your thing:

private void checkNavigationBar() {
    if (isSamsungVersionNougat()) { // check if Samsung phones
        // detect navigation bar
        try {
            // there are navigation bar
            if (Settings.Global.getInt(activity.getContentResolver(), SAMSUNG_NAVIGATION_EVENT) == 0) {
                // Your code
                // example: galleryViewModel.navigationBarHeight.set(getNavigationBarHeight());
            } else { // there are no navigation bar
                // Your code
                // example: galleryViewModel.navigationBarHeight.set(0);
            }
        } catch (Exception ignored) {
        }
        barHideEnableObserver = new BarHideEnableObserver(new Handler());
        activity.getContentResolver().registerContentObserver(
                Settings.Global.getUriFor(SAMSUNG_NAVIGATION_EVENT),
                true, barHideEnableObserver);
    } else {
        galleryViewModel.navigationBarHeight.set(getNavigationBarHeight());
    }
}
1
Thomas Jansen On

Use this method, worked for me. Make sure the view has been rendered first to make sure that getHeight() doesn't return 0. Also make sure that the rootView you are using is meant to take up the whole screen.

public static boolean hasNavBar (Activity activity, View rootView) {
    if (activity == null || rootView == null)
        return true;

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1)
        return true;

    Display d = activity.getWindowManager().getDefaultDisplay();
    DisplayMetrics realDisplayMetrics = new DisplayMetrics();
    d.getRealMetrics(realDisplayMetrics);

    int viewHeight = rootView.getHeight();
    if (viewHeight == 0)
        return true;

    int realHeight = realDisplayMetrics.heightPixels;
    return realHeight != viewHeight;
}