How to get screen dimensions as pixels in Android?

 

You can get the screen dimensions in pixels in Android by using the DisplayMetrics class. Here's an example of how to do this:

java
import android.content.Context; import android.util.DisplayMetrics; import android.view.WindowManager; // Get the screen dimensions in pixels public static void getScreenDimensions(Context context) { WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); DisplayMetrics displayMetrics = new DisplayMetrics(); if (windowManager != null) { windowManager.getDefaultDisplay().getMetrics(displayMetrics); int screenWidthPixels = displayMetrics.widthPixels; int screenHeightPixels = displayMetrics.heightPixels; // Print or use the screen dimensions System.out.println("Screen Width (Pixels): " + screenWidthPixels); System.out.println("Screen Height (Pixels): " + screenHeightPixels); } }

In this example:

  1. We obtain a reference to the WindowManager service using context.getSystemService(Context.WINDOW_SERVICE).

  2. We create a DisplayMetrics object to store the display metrics, including screen dimensions.

  3. We use windowManager.getDefaultDisplay().getMetrics(displayMetrics) to get the display metrics and populate the displayMetrics object.

  4. We extract the screen width and height in pixels from the displayMetrics object.

  5. You can print or use these screen dimensions in your Android application as needed.

Make sure you have the appropriate permissions set in your AndroidManifest.xml file to access the WINDOW_SERVICE. Additionally, this code assumes that you're running it within an Android component, such as an Activity or Fragment, where you have access to the Context. If you're running it in a non-Android context, you'll need to ensure you have a valid Context reference.

Comments