Saturday, July 9, 2011

Get screen size in DPI

android.util.DisplayMetrics is a structure describing general information about a display, such as its size, density, and font scaling.

Get screen size in DPI

package com.exercise.AndroidDPI;

import android.app.Activity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.widget.TextView;

public class AndroidDPIActivity extends Activity {
   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
      
       DisplayMetrics dm = new DisplayMetrics();
       getWindowManager().getDefaultDisplay().getMetrics(dm);
      
       String strScreenDIP = "";
       strScreenDIP += "The logical density of the display: " + dm.density + "\n";
       strScreenDIP += "The screen density expressed as dots-per-inch: " + dm.densityDpi +"\n";
       strScreenDIP += "The absolute height of the display in pixels: " + dm.heightPixels +"\n";
       strScreenDIP += "The absolute width of the display in pixels: " + dm.widthPixels + "\n";
       strScreenDIP += "A scaling factor for fonts displayed on the display: " + dm.scaledDensity + "\n";
       strScreenDIP += "The exact physical pixels per inch of the screen in the X dimension: " + dm.xdpi + "\n";
       strScreenDIP += "The exact physical pixels per inch of the screen in the Y dimension: " + dm.ydpi + "\n";
      
       TextView textScreenDIP = (TextView)findViewById(R.id.strScreenDIP);
       textScreenDIP.setText(strScreenDIP);
   }
}

Related:
Get display information using DisplayMetrics, in Multi-Window Mode

2 comments:

Anonymous said...

strScreenDIP += "The exact physical pixels per inch of the screen in the X dimension: " + dm.xdpi + "\n";

xdpi is x Dots Per Inch not "exact physical PPI"

Am I right?

Andr.oid Eric said...

Hello,

I'm not sure your question, sorry.

As my understanding, Dots Per Inch is same as ppi (pixel per inch). Are you confused with density? read DisplayMetrics.density. ~ This value does not exactly follow the real screen size...