GetSize () no es compatible con versiones anteriores de Android OS, getWidth () / getHeight () obsoleto

Entonces, ¿cómo puedo escribir código para acomodar esto? No quiero dejar llamadas de API obsoletas en mi código, pero tampoco quiero perder a los usuarios con (un poco) dispositivos antiguos. ¿Hay algún tipo de configuración de compatibilidad que puedo implementar?

Rel. código

Display display = getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); int screen_width = size.x; int screen_height = size.y; 

Vs el método más antiguo:

 int screen_width = getWindowManager().getDefaultDisplay().getWidth(); int screen_height = getWindowManager().getDefaultDisplay().getHeight(); 

El mejor (y por mejor, me refiero a la opción que funcionaría prácticamente cada vez) opción sería utilizar la reflexión. Echa un vistazo a las pautas de Compatibilidad con versiones anteriores de Android Backwards (actualizadas con la nueva ubicación del artículo en reflexión).

Mientras que la respuesta de tyczj funcionará perfectamente mientras las funciones obsoletas estén todavía en el SDK, tan pronto como se eliminen, no tendrás forma de usarlas o de ejecutar tu aplicación en un dispositivo antiguo si todavía quieres crear contra el SDK más reciente. .

Reflection resuelve este problema detectando dinámicamente la función en tiempo de ejecución, lo que significa que incluso si construye contra ICS, siempre y cuando la minSdkVersion sea correcta, puede hacer que su aplicación se ejecute en un dispositivo con Gingerbread o Froyo por ejemplo.

Tengo dos funciones, enviando el contexto y gettin altura y ancho en píxeles.

 public static int getWidth(Context mContext){ int width=0; WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE); Display display = wm.getDefaultDisplay(); if(Build.VERSION.SDK_INT>Build.VERSION_CODES.HONEYCOMB){ Point size = new Point(); display.getSize(size); width = size.x; } else{ width = display.getWidth(); // deprecated } return width; } 

y

 public static int getHeight(Context mContext){ int height=0; WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE); Display display = wm.getDefaultDisplay(); if(Build.VERSION.SDK_INT>Build.VERSION_CODES.HONEYCOMB){ Point size = new Point(); display.getSize(size); height = size.y; }else{ height = display.getHeight(); // deprecated } return height; } 

Puedes hacer algo como esto

 if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH){ //do stuff pertaining to this version here }else{ //other versions } 

Creo que algo de lo que RivieraKid sugiere, sería algo como esto:

 static Point getDisplaySize(Display d) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { return getDisplaySizeGE11(d); } return getDisplaySizeLT11(d); } @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) static Point getDisplaySizeGE11(Display d) { Point p = new Point(0, 0); d.getSize(p); return p; } static Point getDisplaySizeLT11(Display d) { try { Method getWidth = Display.class.getMethod("getWidth", new Class[] {}); Method getHeight = Display.class.getMethod("getHeight", new Class[] {}); return new Point(((Integer) getWidth.invoke(d, (Object[]) null)).intValue(), ((Integer) getHeight.invoke(d, (Object[]) null)).intValue()); } catch (NoSuchMethodException e2) // None of these exceptions should ever occur. { return new Point(-1, -1); } catch (IllegalArgumentException e2) { return new Point(-2, -2); } catch (IllegalAccessException e2) { return new Point(-3, -3); } catch (InvocationTargetException e2) { return new Point(-4, -4); } } 

Normalmente tengo una super clase es decir. BaseActivity con un método genérico para obtener un punto con el tamaño de pantalla actual. Mantiene todo agradable y limpio en la actividad real.

 /** * Return screen size as a point. * @return */ @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) @SuppressWarnings("deprecation") protected Point getSize() { final Point point = new Point(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { getWindowManager().getDefaultDisplay().getSize(point); } else { final Display display = getWindowManager().getDefaultDisplay(); point.x = display.getWidth(); point.y = display.getHeight(); } return point; } 
  • BackupAgent compatible con versiones anteriores
  • Estrategias para Honeycomb y compatibilidad con versiones anteriores
  • ¿Qué es la compatibilidad hacia atrás en Android Studio?
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.