Cómo puedo obtener el ScreenSize mediante programación en android

Android define los tamaños de pantalla como Normal Large XLarge, etc.

Selecciona automáticamente entre recursos estáticos en carpetas apropiadas. Necesito estos datos sobre el dispositivo actual en mi código java. DisplayMetrics sólo proporciona información sobre la densidad del dispositivo actual. No hay nada disponible con respecto al tamaño de la pantalla.

Encontré el enum de ScreenSize en código de grep aquí Sin embargo esto no parece disponible para mí para SDK 4.0. ¿Hay alguna forma de obtener esta información?

Copie y pegue este código en su Activity y cuando se ejecute, se brindará la categoría de tamaño de pantalla del dispositivo.

 int screenSize = getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK; String toastMsg; switch(screenSize) { case Configuration.SCREENLAYOUT_SIZE_LARGE: toastMsg = "Large screen"; break; case Configuration.SCREENLAYOUT_SIZE_NORMAL: toastMsg = "Normal screen"; break; case Configuration.SCREENLAYOUT_SIZE_SMALL: toastMsg = "Small screen"; break; default: toastMsg = "Screen size is neither large, normal or small"; } Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show(); 
 private static String getScreenResolution(Context context) { WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); Display display = wm.getDefaultDisplay(); DisplayMetrics metrics = new DisplayMetrics(); display.getMetrics(metrics); int width = metrics.widthPixels; int height = metrics.heightPixels; return "{" + width + "," + height + "}"; } 

Determine el tamaño de la pantalla:

 int screenSize = getResources().getConfiguration().screenLayout &Configuration.SCREENLAYOUT_SIZE_MASK; switch(screenSize) { case Configuration.SCREENLAYOUT_SIZE_LARGE: Toast.makeText(this, "Large screen",Toast.LENGTH_LONG).show(); break; case Configuration.SCREENLAYOUT_SIZE_NORMAL: Toast.makeText(this, "Normal screen",Toast.LENGTH_LONG).show(); break; case Configuration.SCREENLAYOUT_SIZE_SMALL: Toast.makeText(this, "Small screen",Toast.LENGTH_LONG).show(); break; default: Toast.makeText(this, "Screen size is neither large, normal or small" , Toast.LENGTH_LONG).show(); } 

Determine la densidad:

 int density= getResources().getDisplayMetrics().densityDpi; switch(density) { case DisplayMetrics.DENSITY_LOW: Toast.makeText(context, "LDPI", Toast.LENGTH_SHORT).show(); break; case DisplayMetrics.DENSITY_MEDIUM: Toast.makeText(context, "MDPI", Toast.LENGTH_SHORT).show(); break; case DisplayMetrics.DENSITY_HIGH: Toast.makeText(context, "HDPI", Toast.LENGTH_SHORT).show(); break; case DisplayMetrics.DENSITY_XHIGH: Toast.makeText(context, "XHDPI", Toast.LENGTH_SHORT).show(); break; } 

Para Ref: http://devl-android.blogspot.in/2013/10/wifi-connectivity-and-hotspot-in-android.html

Puede obtener el tamaño de la pantalla en píxeles utilizando este código.

 Display display = getWindowManager().getDefaultDisplay(); SizeUtils.SCREEN_WIDTH = display.getWidth(); SizeUtils.SCREEN_HEIGHT = display.getHeight(); 

Usted puede intentar esto, él está trabajando Ejemplo

 DisplayMetrics displaymetrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); int ht = displaymetrics.heightPixels; int wt = displaymetrics.widthPixels; if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE) { Toast.makeText(this, "Large screen", Toast.LENGTH_LONG).show();} else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_NORMAL) { Toast.makeText(this, "Normal sized screen", Toast.LENGTH_LONG) .show(); } else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_SMALL) { Toast.makeText(this, "Small sized screen", Toast.LENGTH_LONG) .show(); } else { Toast.makeText(this, "Screen size is neither large, normal or small", Toast.LENGTH_LONG).show(); } // Determine density DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); int density = metrics.densityDpi; if (density == DisplayMetrics.DENSITY_HIGH) { Toast.makeText(this, "DENSITY_HIGH... Density is " + String.valueOf(density), Toast.LENGTH_LONG).show(); } else if (density == DisplayMetrics.DENSITY_MEDIUM) { Toast.makeText(this, "DENSITY_MEDIUM... Density is " + String.valueOf(density), Toast.LENGTH_LONG).show(); } else if (density == DisplayMetrics.DENSITY_LOW) { Toast.makeText(this, "DENSITY_LOW... Density is " + String.valueOf(density), Toast.LENGTH_LONG).show(); } else { Toast.makeText( this, "Density is neither HIGH, MEDIUM OR LOW. Density is " + String.valueOf(density), Toast.LENGTH_LONG) .show(); } // These are deprecated Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)) .getDefaultDisplay(); int width = display.getWidth(); int height = display.getHeight(); 

Simon-

Los diferentes tamaños de pantalla tienen diferentes densidades de píxeles. Una pantalla de 4 pulgadas en el teléfono podría tener más o menos píxeles y luego decir un televisor de 26 pulgadas. Si estoy entendiendo correctamente quiere detectar cuál de los grupos de tamaño de la pantalla actual es, pequeño, normal, grande y extra grande. Lo único que puedo pensar es detectar la densidad de píxeles y usarlo para determinar el tamaño real de la pantalla.

Necesito esto para un par de mis aplicaciones y el código siguiente fue mi solución al problema. Sólo mostrando el código dentro de creer. Se trata de una aplicación independiente que se ejecuta en cualquier dispositivo para devolver la información de la pantalla.

 setContentView(R.layout.activity_main); txSize = (TextView) findViewById(R.id.tvSize); density = (TextView) findViewById(R.id.density); densityDpi = (TextView) findViewById(R.id.densityDpi); widthPixels = (TextView) findViewById(R.id.widthPixels); xdpi = (TextView) findViewById(R.id.xdpi); ydpi = (TextView) findViewById(R.id.ydpi); Configuration config = getResources().getConfiguration(); if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE) { Toast.makeText(this, "Large screen", Toast.LENGTH_LONG).show(); txSize.setText("Large screen"); } else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_NORMAL) { Toast.makeText(this, "Normal sized screen", Toast.LENGTH_LONG) .show(); txSize.setText("Normal sized screen"); } else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_SMALL) { Toast.makeText(this, "Small sized screen", Toast.LENGTH_LONG) .show(); txSize.setText("Small sized screen"); } else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE) { Toast.makeText(this, "xLarge sized screen", Toast.LENGTH_LONG) .show(); txSize.setText("Small sized screen"); } else { Toast.makeText(this, "Screen size is neither large, normal or small", Toast.LENGTH_LONG).show(); txSize.setText("Screen size is neither large, normal or small"); } Display display = getWindowManager().getDefaultDisplay(); DisplayMetrics metrics = new DisplayMetrics(); display.getMetrics(metrics); Log.i(TAG, "density :" + metrics.density); density.setText("density :" + metrics.density); Log.i(TAG, "D density :" + metrics.densityDpi); densityDpi.setText("densityDpi :" + metrics.densityDpi); Log.i(TAG, "width pix :" + metrics.widthPixels); widthPixels.setText("widthPixels :" + metrics.widthPixels); Log.i(TAG, "xdpi :" + metrics.xdpi); xdpi.setText("xdpi :" + metrics.xdpi); Log.i(TAG, "ydpi :" + metrics.ydpi); ydpi.setText("ydpi :" + metrics.ydpi); 

Y un simple archivo XML

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity" > <TextView android:id="@+id/tvSize" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/density" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/densityDpi" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/widthPixels" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/xdpi" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/ydpi" android:layout_width="wrap_content" android:layout_height="wrap_content" /> 

Creo que es una simple pieza simple de código!

 public Map<String, Integer> deriveMetrics(Activity activity) { try { DisplayMetrics metrics = new DisplayMetrics(); if (activity != null) { activity.getWindowManager().getDefaultDisplay().getMetrics(metrics); } Map<String, Integer> map = new HashMap<String, Integer>(); map.put("screenWidth", Integer.valueOf(metrics.widthPixels)); map.put("screenHeight", Integer.valueOf(metrics.heightPixels)); map.put("screenDensity", Integer.valueOf(metrics.densityDpi)); return map; } catch (Exception err) { ; // just use zero values return null; } } 

Este método ahora se puede utilizar en cualquier lugar independientemente. Donde quiera que desee obtener información sobre la pantalla del dispositivo, hágalo de la siguiente manera:

  Map<String, Integer> map = deriveMetrics2(this); map.get("screenWidth"); map.get("screenHeight"); map.get("screenDensity"); 

Espero que esto pueda ser útil para alguien por ahí y puede ser más fácil de usar. Si necesito corregir o mejorar por favor no dude en hacérmelo saber! Todos los derechos reservados

¡¡¡Aclamaciones!!!

Debo estar perdiendo algo. DisplayMetrics.widthPixels, DisplayMetrics.heightPixels?

http://developer.android.com/reference/android/util/DisplayMetrics.html#heightPixels

[EDITAR]

Ah, me falta algo. ¡Un cerebro! +1 para Alex.

 DisplayMetrics displayMetrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); int width = displayMetrics.widthPixels; int height = displayMetrics.heightPixels; 
  • Convertir todo el contenido en un ScrollView a un mapa de bits?
  • Mantener la pantalla activada en Actividad - no funciona con FLAG_KEEP_SCREEN_ON
  • ¿Cómo atenuar / desenfoque sólo parte de la pantalla?
  • Android - Google Play filtrando xxhdpi
  • Android: el acceso directo a la aplicación tiene que ser recreado después de la actualización
  • Cómo arreglar la pantalla en blanco en la aplicación Inicio?
  • Actividad con una altura específica frente a la lockscreen
  • ¿Cómo crear dos vistas en Android que usan 50% de altura cada una, a menos que sea menor?
  • Android obtener el tamaño de la pantalla de la orientación de la pantalla de otros
  • La orientación de la pantalla de Android difiere entre los dispositivos
  • Nueva actividad en Android "entrar desde el lado"
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.