How to tell whether an android device has hard keys

后端 未结 3 865
轮回少年
轮回少年 2020-12-08 22:30

How can I tell whether an android device has physical keys or the software navigation bar? I need to change the layout dependant on whether the software navigation is drawn

相关标签:
3条回答
  • 2020-12-08 22:54

    Here you go.. this should do what you want.

    @SuppressLint("NewApi")
    private static boolean hasSoftNavigation(Context context)
    {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH){
            return !ViewConfiguration.get(context).hasPermanentMenuKey();
        }
        return false;
    }
    
    0 讨论(0)
  • 2020-12-08 23:01

    private boolean isHardwareKeyboardAvailable() { return getResources().getConfiguration().keyboard != Configuration.KEYBOARD_NOKEYS; }

    In addition, here is more info. http://developer.android.com/reference/android/content/res/Configuration.html#keyboard

    EDIT - To check for physical keyboard

    private boolean isPhysicalKeyboardAvailable() { return getResources().getConfiguration().keyboard == Configuration.KEYBOARD_QWERTY; }

    For more information on the different Configurations view http://developer.android.com/reference/android/content/res/Configuration.html#keyboard

    I am sure one of those works.

    2nd EDIT -

    Check. Already asked.

    Android: Programmatically detect if device has hardware menu button

    0 讨论(0)
  • 2020-12-08 23:11

    Solved by doing this the first time the app is launched and saving to preferences:

    public static boolean hasSoftKeys(WindowManager windowManager){
        boolean hasSoftwareKeys = true;
        //c = context; use getContext(); in fragments, and in activities you can 
        //directly access the windowManager();
    
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.JELLY_BEAN_MR1){
            Display d = c.getWindowManager().getDefaultDisplay();
    
            DisplayMetrics realDisplayMetrics = new DisplayMetrics();
            d.getRealMetrics(realDisplayMetrics);
    
            int realHeight = realDisplayMetrics.heightPixels;
            int realWidth = realDisplayMetrics.widthPixels;
    
            DisplayMetrics displayMetrics = new DisplayMetrics();
            d.getMetrics(displayMetrics);
    
            int displayHeight = displayMetrics.heightPixels;
            int displayWidth = displayMetrics.widthPixels;
    
            hasSoftwareKeys =  (realWidth - displayWidth) > 0 ||
                               (realHeight - displayHeight) > 0;
        } else {
            boolean hasMenuKey = ViewConfiguration.get(c).hasPermanentMenuKey();
            boolean hasBackKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK);
            hasSoftwareKeys = !hasMenuKey && !hasBackKey;
        }
        return hasSoftwareKeys;
    }
    
    0 讨论(0)
提交回复
热议问题