Calculating android screen size?

2020-07-18 07:31发布

问题:

Is it possible to calculate the android screen diagonal dimension in inches.

I have tried below two approaches both is not suitable for my case.

Approach 1:

DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int absoluteHeightInPx = displayMetrics.heightPixels;
int absoluteWidthInPx = displayMetrics.widthPixels;     
double diagonalPixels = Math.sqrt((absoluteHeightInPx * absoluteHeightInPx) + (absoluteWidthInPx * absoluteWidthInPx));
double diagonalInInches = diagonalPixels / displayMetrics.densityDpi;

Approach 2:

float actualHeight = absoluteHeightInPx * deviceDensity;
float actualWidth = absoluteWidthInPx * deviceDensity;
float deviceDensity = displayMetrics.density;
float physicalPixelPerInchX = displayMetrics.xdpi;
float physicalPixelPerInchY = displayMetrics.ydpi;
float heightInInches = actualHeight / physicalPixelPerInchY;
float widhtInInches = actualWidth / physicalPixelPerInchX;
double diagonalInInches = Math.sqrt((heightInInches * heightInInches) + (widhtInInches * widhtInInches));

Could you correct if i am wrong.

Thanks, Easwar

回答1:

I use the code below, and it works on my Moto Dey.

 DisplayMetrics metrics=new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);

    float height=metrics.heightPixels/metrics.xdpi;
    float width=metrics.widthPixels/metrics.ydpi;

    TextView tv=(TextView) findViewById(R.id.textview);
    tv.setText("The screen size is:"+FloatMath.sqrt(height*height+width*width));

The real diagonal length is 3.7" and the code gives out 3.6979072, precise enough. According to the descriptions in SDK, I think my method should work on other devices.



回答2:

I have tested both of my approach in 8 android devices. The second is almost accurate.

But for few devices this is not giving proper answer. So I concluded following the second approach.