Android DisplayMetrics returns incorrect screen size in pixels on ICS

前端 未结 6 1104
花落未央
花落未央 2020-11-27 03:24

I\'ve tried this....

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int fullscreenheight = metric         


        
6条回答
  •  北荒
    北荒 (楼主)
    2020-11-27 03:52

    You can use getRealSize to get the screen resolution. It's officially supported in API 17 and higher, but it actually existed in the SDK since API 14. If you use the SDK platform for API 17 or higher, you can access the method normally and just bypass the warning about it only being available in API 17.

    /**
     * Gets the device's native screen resolution rotated
     * based on the device's current screen orientation.
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) //To remove warning about using
                                                   //getRealSize prior to API 17
    private Point screenResolution() {
        WindowManager windowManager =
            (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = windowManager.getDefaultDisplay();
        Point screenResolution = new Point();
    
        if (Build.VERSION.SDK_INT < 14)
            throw new RuntimeException("Unsupported Android version.");
        display.getRealSize(screenResolution);
    
        return screenResolution;    
    }
    

    I've tested this in a real Android 5.0.2 device and an emulator running 4.1.1 (and possibly others).

    Thanks to benc for pointing this out in the comments.

提交回复
热议问题