Getting screen size not from Activity subclass

DisplayMetrics metrics = getBaseContext().getResources().getDisplayMetrics();         
    final int w = metrics.widthPixels;
    final int h = metrics.heightPixels;

Yes there is a way, if you can pass the Context Object to your non activity class,

   int width= context.getResources().getDisplayMetrics().widthPixels;
   int height= context.getResources().getDisplayMetrics().heightPixels;

You don't need the Activity Object itself.


The other answers here won't give you the screen resolution.

Here's how you should do it:

@SuppressLint("ObsoleteSdkInt")
@JvmStatic
fun getScreenResolution(context: Context, naturalResolution: Boolean = false): Point {
    val screenResolution = Point()
    val display = getDisplay(context)!!
    @Suppress("DEPRECATION")
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        display.getRealSize(screenResolution)
    } else display.getSize(screenResolution)
    if (naturalResolution) {
        val screenNaturalOrientation = getScreenNaturalOrientation(context)
        if ((screenNaturalOrientation == Configuration.ORIENTATION_PORTRAIT && screenResolution.x > screenResolution.y)
                || (screenNaturalOrientation == Configuration.ORIENTATION_LANDSCAPE && screenResolution.y > screenResolution.x))
            screenResolution.set(screenResolution.y, screenResolution.x)
    }
    return screenResolution
}

/**
 * returns the natural orientation of the device: Configuration.ORIENTATION_LANDSCAPE or Configuration.ORIENTATION_PORTRAIT .<br></br>
 * The result should be consistent no matter the orientation of the device
 */
fun getScreenNaturalOrientation(context: Context): Int {
    //based on : http://stackoverflow.com/a/9888357/878126
    val config = context.resources.configuration
    val rotation = getDisplay(context)!!.rotation
    return if ((rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180) &&
            config.orientation == Configuration.ORIENTATION_LANDSCAPE
            || (rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270) &&
            config.orientation == Configuration.ORIENTATION_PORTRAIT) Configuration.ORIENTATION_LANDSCAPE else Configuration.ORIENTATION_PORTRAIT
}

To get the display, use:

fun getDisplay(context: Context): Display? {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R)
        try {
            val result = context.display
            if (result != null)
                return result
        } catch (e: Throwable) {
        }
    if (context is Activity) {
        return try {
            @Suppress("DEPRECATION")
            context.windowManager.defaultDisplay
        } catch (e: Throwable) {
            null
        }
    }
    return null
}

docs:

https://developer.android.com/reference/android/view/Display.html#getRealSize(android.graphics.Point)