2012-04-30 21 views
52

Me gustaría conocer la orientación detallada de un dispositivo, preferiblemente uno de SCREEN_ORIENTATION_LANDSCAPE, SCREEN_ORIENTATION_PORTRAIT, SCREEN_ORIENTATION_REVERSE_LANDSCAPE, SCREEN_ORIENTATION_REVERSE_PORTRAIT de ActivityInfo o equivalente.¿Cómo obtengo la orientación CURRENT (ActivityInfo.SCREEN_ORIENTATION_ *) de un dispositivo Android?

Algunas de las respuestas aquí en StackOverflow incluido

getWindowManager().getDefaultDisplay().getRotation() 

pero esto realmente no me dicen si el dispositivo está en modo retrato o paisaje, sólo cómo se ha girado con referencia a su posición natural - que a su a su vez puede ser paisaje o retrato en primer lugar.

getResources().getConfiguration().orientation 

devuelve uno de los tres siguientes: ORIENTATION_LANDSCAPE, ORIENTATION_PORTRAIT, ORIENTATION_SQUARE, que luego realmente no me dicen qué manera se enciende el teléfono (ya sea al revés o cuál de los lados se ha girado a).

Sé que podría usar este último en combinación con DisplayMetrics para conocer la orientación natural del dispositivo, pero ¿realmente no hay mejor manera?

Respuesta

85

Terminé usando la siguiente solución:

private int getScreenOrientation() { 
    int rotation = getWindowManager().getDefaultDisplay().getRotation(); 
    DisplayMetrics dm = new DisplayMetrics(); 
    getWindowManager().getDefaultDisplay().getMetrics(dm); 
    int width = dm.widthPixels; 
    int height = dm.heightPixels; 
    int orientation; 
    // if the device's natural orientation is portrait: 
    if ((rotation == Surface.ROTATION_0 
      || rotation == Surface.ROTATION_180) && height > width || 
     (rotation == Surface.ROTATION_90 
      || rotation == Surface.ROTATION_270) && width > height) { 
     switch(rotation) { 
      case Surface.ROTATION_0: 
       orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT; 
       break; 
      case Surface.ROTATION_90: 
       orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE; 
       break; 
      case Surface.ROTATION_180: 
       orientation = 
        ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT; 
       break; 
      case Surface.ROTATION_270: 
       orientation = 
        ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE; 
       break; 
      default: 
       Log.e(TAG, "Unknown screen orientation. Defaulting to " + 
         "portrait."); 
       orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT; 
       break;    
     } 
    } 
    // if the device's natural orientation is landscape or if the device 
    // is square: 
    else { 
     switch(rotation) { 
      case Surface.ROTATION_0: 
       orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE; 
       break; 
      case Surface.ROTATION_90: 
       orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT; 
       break; 
      case Surface.ROTATION_180: 
       orientation = 
        ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE; 
       break; 
      case Surface.ROTATION_270: 
       orientation = 
        ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT; 
       break; 
      default: 
       Log.e(TAG, "Unknown screen orientation. Defaulting to " + 
         "landscape."); 
       orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE; 
       break;    
     } 
    } 

    return orientation; 
} 

NOTA: Algunos usuarios (Geltrude y holtaf en los comentarios abajo) señaló que esta solución no funciona en todos los dispositivos como el la dirección de rotación desde la orientación natural no está estandarizada.

+1

¡Impresionante! ¡Muchas gracias! – Alexander

+1

¡Funciona genial! –

+3

Esto no funcionará si su actividad tiene una orientación de pantalla fija. getRotation solo informa un valor cuando la orientación de la pantalla no está bloqueada. – AndroidDev

7

getResources().getConfiguration().orientation es la forma estándar de conocer la orientación actual que se está utilizando. Sin embargo, si no satisface sus necesidades, entonces tal vez pueda usar sensores para calcularlo en términos de ángulo. Lea this y this

+0

Sí, soy consciente de eso. Solo quería saber si había un solo método que me devolviera información completa sobre la orientación de la pantalla, incluido el lado al que se dirigió (no solo paisaje o retrato), es decir, al revés, o al lado izquierdo o derecho. –

+0

Sí, entiendo tu punto. Entonces, lo que puedes hacer es crear tu propio método estático usando estos sensores ... – waqaslam

-1

¿Esto resuelve su problema?

public static int getscrOrientation(Activity act) 
{ 
    Display getOrient = act.getWindowManager() 
      .getDefaultDisplay(); 

    int orientation = getOrient.getOrientation(); 

    // Sometimes you may get undefined orientation Value is 0 
    // simple logic solves the problem compare the screen 
    // X,Y Co-ordinates and determine the Orientation in such cases 
    if (orientation == Configuration.ORIENTATION_UNDEFINED) { 

     Configuration config = act.getResources().getConfiguration(); 
     orientation = config.orientation; 

     if (orientation == Configuration.ORIENTATION_UNDEFINED) { 
      // if height and widht of screen are equal then 
      // it is square orientation 
      if (getOrient.getWidth() == getOrient.getHeight()) { 
       orientation = Configuration.ORIENTATION_SQUARE; 
      } else { // if widht is less than height than it is portrait 
       if (getOrient.getWidth() < getOrient.getHeight()) { 
        orientation = Configuration.ORIENTATION_PORTRAIT; 
       } else { // if it is not any of the above it will defineitly 
          // be landscape 
        orientation = Configuration.ORIENTATION_LANDSCAPE; 
       } 
      } 
     } 
    } 
    return orientation; // return value 1 is portrait and 2 is Landscape 
         // Mode 
} 
+1

Como dije en mi pregunta. Necesito saber en qué dirección gira la pantalla. Retrato o paisaje es información insuficiente. P.ej. si es un dispositivo alto o vertical, si está en orientación horizontal, necesito saber si está encendido, hacia la izquierda o hacia la derecha, etc. –

7

Creo que su problema es que se puede detectar horizontal y vertical, pero no revertir paisaje y revertir protrait, ya que no son compatibles con versiones anteriores. Para detectar lo que puede hacer es que puede usar tanto mantenimiento como rotación. Te estoy dando una idea de que puede ser útil para ti.

intente esto, creo que puede resolver su problema.

  int orientation = getResources().getConfiguration().orientation; 
      int rotation = getWindowManager().getDefaultDisplay().getRotation(); 
      int actual_orientation = -1; 
      if (orientation == Configuration.ORIENTATION_LANDSCAPE 
      && (rotation == Surface.ROTATION_0 
      || rotation == Surface.ROTATION_90)){ 
       orientation = Configuration.ORIENTATION_LANDSCAPE; 
      } else if (orientation == Configuration.ORIENTATION_PORTRAIT 
        && (rotation == Surface.ROTATION_0 
        || rotation == Surface.ROTATION_90)) { 
       orientation = Configuration.ORIENTATION_PORTRAIT; 
      } else if (orientation == Configuration.ORIENTATION_LANDSCAPE 
        && (rotation == Surface.ROTATION_180 
        || rotation == Surface.ROTATION_270)){ 
       orientation = //any constant for reverse landscape orientation; 
      } else { 
       if (orientation == Configuration.ORIENTATION_PORTRAIT 
         && (rotation == Surface.ROTATION_180 
         || rotation == Surface.ROTATION_270)){ 
         orientation = //any constant for reverse portrait orientation; 
       } 
      } 
+0

Sí, terminé haciendo una solución similar. Lo publiqué como una respuesta. –

15
public static int getScreenOrientation(Activity activity) { 
     int rotation = activity.getWindowManager().getDefaultDisplay().getRotation(); 
     int orientation = activity.getResources().getConfiguration().orientation; 
     if (orientation == Configuration.ORIENTATION_PORTRAIT) { 
      if (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_270) { 
      return ActivityInfo.SCREEN_ORIENTATION_PORTRAIT; 
      } else { 
      return ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT; 
      } 
     } 
     if (orientation == Configuration.ORIENTATION_LANDSCAPE) { 
      if (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_90) { 
      return ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE; 
      } else { 
      return ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE; 
      } 
     } 
     return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED; 
     } 
+0

Como este método depende de la orientación natural del dispositivo, no funcionará como se espera en cada dispositivo. –

2

Terminé usando la respuesta de Zoltán arriba, que funciona muy bien, excepto cuando lo probé en una tableta (una ventaja Samsung Galaxy Tab P6210 7.0). En modo retrato, devolvió SCREEN_ORIENTATION_REVERSE_PORTRAIT. Entonces, en la declaración else (si la orientación natural es el paisaje) cambié las cajas por ROTATION_90 y ROTATION_270, y todo parece funcionar bien. (No tengo la reputación suficiente para publicar esto como un comentario a la respuesta de Zoltán.)

+0

¿Sabes si esto sucede en otras tabletas de paisajes también? ¿Tal vez estos dos casos deberían intercambiarse por todos los dispositivos de paisaje natural? –

+0

Confirmado, sucede también en un Asus Transformer Prime, intercambiando las fundas que lo arreglaron. – Joan

16

enfoque simple sería utilizar

getResources().getConfiguration().orientation 

1 es para Potrait y 2 para el paisaje.

+4

La pregunta solicita información más detallada, es decir, que incluye reverso y reverso, que estas funciones no proporcionan. –

1

Puede hacerlo de una manera muy simple: obtener la pantalla widht y height. ancho de pantalla siempre será mayor cuando el dispositivo está en orientación horizontal.

Display display = getWindowManager().getDefaultDisplay(); 
    int width = display.getWidth(); 
    int height = display.getHeight(); 
    Toast.makeText(getApplicationContext(), "" + width + "," + height, 
      Toast.LENGTH_SHORT).show(); 
    if (width > height) { 
     Toast.makeText(getApplicationContext(), "LandScape", 
       Toast.LENGTH_SHORT).show(); 
    } 
+1

La pregunta es realmente cómo obtener la orientación detallada, es decir, incluyendo la forma en que se gira el dispositivo. El método que está sugiriendo no diferencia entre orientaciones opuestas, p. retrato y retrato boca abajo, etc. –

Cuestiones relacionadas