Android Example Get real display size in inch

Hello,

Maybe this can be useful for others.
You can get the exact screen diagonal size (in inch) using the following simple routine.

B4X:
Sub GetDevicePhysicalSize As Double
#If JAVA
import android.graphics.*;
import android.util.DisplayMetrics;
public double getScreenSizeOfDevice() {
    Point point = new Point();
    getWindowManager().getDefaultDisplay().getRealSize(point);
    DisplayMetrics dm = getResources().getDisplayMetrics();
    double x = Math.pow(point.x/ dm.xdpi, 2);
    double y = Math.pow(point.y / dm.ydpi, 2);
    double screenInches = Math.sqrt(x + y);
    return screenInches;
}
#End If
    Return NativeMe.RunMethod("getScreenSizeOfDevice", Null)
End Sub

Tested on Android 4.4 (LG GPad 8.3), 5.1 (Xperia ZL), 11 (Lenovo Yoga Tab 13) and 12 (Pixel 3a) with perfect results.
 
Last edited:

swChef

Active Member
Licensed User
Longtime User
Thank you.
In B4A, define NativeMe as
B4X:
Dim NativeMe As JavaObject
NativeMe.InitializeContext
 

Star-Dust

Expert
Licensed User
Longtime User
B4X:
Sub GetRealHeight As Int
   Dim p As Phone
   If p.SdkVersion >= 17 Then
     Dim jo As JavaObject
     jo = jo.InitializeContext.RunMethodJO("getWindowManager", Null).RunMethod("getDefaultDisplay", Null)
     Dim metrics As JavaObject
     metrics.InitializeNewInstance("android.util.DisplayMetrics", Null)
     jo.RunMethod("getRealMetrics", Array(metrics))
     Return metrics.GetField("heightPixels")
   Else
     Return GetDeviceLayoutValues.Height
   End If
End Sub

Or
B4X:
    Dim r As Reflector
    r.Target = r.GetContext
    r.Target = r.RunMethod("getResources")
    r.Target = r.RunMethod("getDisplayMetrics")
    Log(r.GetField("xdpi"))
    Log(r.GetField("ydpi"))
    
    Log(GetDeviceLayoutValues.Width/r.GetField("xdpi"))
    Log(GetDeviceLayoutValues.Height/r.GetField("ydpi"))
 

Pendrush

Well-Known Member
Licensed User
Longtime User
You should be careful.

getter for defaultDisplay: Display!' is deprecated. Deprecated in Java (Api 31)
Java:
android.view.WindowManager @Deprecated
public abstract android.view.Display getDefaultDisplay()

 
Last edited:
Cookies are required to use this site. You must accept them to continue using the site. Learn more…