android虚拟按键NavigationBar的判断

下面方法可判断手机是否有虚拟按键功能:

  public boolean hasNavigationBarFun(Activity activity) {
        Resources rs = activity.getResources();
        int id = rs.getIdentifier("config_showNavigationBar", "bool", "android");
        boolean hasNavBarFun = false;
        if (id > 0) {
            hasNavBarFun = rs.getBoolean(id);
        }
        try {
            Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
            Method m = systemPropertiesClass.getMethod("get", String.class);
            String navBarOverride = (String)m.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
            if ("1".equals(navBarOverride)) {
                hasNavBarFun = false;
            } else if ("0".equals(navBarOverride)) {
                hasNavBarFun = true;
            }
        } catch (Exception e) {
            hasNavBarFun = false;
        }
        return hasNavBarFun;
    }

检查在有虚拟按键的设备上面,虚拟按键是否展示出来(收起或展示)

public boolean isNavigationBarShow(Activity activity){
        DisplayMetrics dm = new DisplayMetrics();
        Display display = activity.getWindowManager().getDefaultDisplay();
        display.getMetrics(dm);
        int screenHeight = dm.heightPixels;

        DisplayMetrics realDisplayMetrics = new DisplayMetrics();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            display.getRealMetrics(realDisplayMetrics);
        } else {
            Class c;
            try {
                c = Class.forName("android.view.Display");
                Method method = c.getMethod("getRealMetrics", DisplayMetrics.class);
                method.invoke(display, realDisplayMetrics);
            } catch (Exception e) {
                realDisplayMetrics.setToDefaults();
                e.printStackTrace();
            }
        }

        int screenRealHeight = realDisplayMetrics.heightPixels;
        return (screenRealHeight - screenHeight) > 0;
 }

而要监听虚拟按键的展示收起和展示,可以在需要监听的页面为最外面的View在onResume()时添加mContainer.getViewTreeObserver().addOnGlobalLayoutListener(this);
在onPause()时 移除mContainer.getViewTreeObserver().removeGlobalOnLayoutListener(this);
在onGlobalLayout() 中调用checkDeviceHasNavigationBar来检查从而进行判断。

你可能感兴趣的:(android)