Search code examples
androidbuttonkotlinsoftkeys

Invisible soft navigation bar on some devices


I want to know if a device has a soft navigation bar. I use the following code for this purpose:

        val hasNavBar = resources.getIdentifier("config_showNavigationBar", "bool", "android")
        if(hasNavBar > 0 && resources.getBoolean(hasNavBar)){

            val resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android")
            if (resourceId > 0) {
                ApiHelper.navHeight = resources.getDimensionPixelSize(resourceId)
            }
        }

But on some devices that have no soft navigation bar, resources.getDimensionPixelSize(resourceId) gives some height and hasNavBar is true.

The device with this problem is a Redmi Note 4 Pro. I don't know if other devices have the same problem.

enter image description here


Solution

  • I found the answer.

    There are some functions in stackOverflow that doesn't work, but this worked.

    How to tell whether an android device has hard keys

    fun hasSoftKeys(windowManager: WindowManager): Boolean {
            var hasSoftwareKeys = true
    
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                val d = context.getWindowManager().getDefaultDisplay()
    
                val realDisplayMetrics = DisplayMetrics()
                d.getRealMetrics(realDisplayMetrics)
    
                val realHeight = realDisplayMetrics.heightPixels
                val realWidth = realDisplayMetrics.widthPixels
    
                val displayMetrics = DisplayMetrics()
                d.getMetrics(displayMetrics)
    
                val displayHeight = displayMetrics.heightPixels
                val displayWidth = displayMetrics.widthPixels
    
                hasSoftwareKeys = realWidth - displayWidth > 0 || realHeight - displayHeight > 0x<
            } else {
                val hasMenuKey = ViewConfiguration.get(context).hasPermanentMenuKey()
                val hasBackKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK)
                hasSoftwareKeys = !hasMenuKey && !hasBackKey
            }
            return hasSoftwareKeys
        }