Getting current display orientation of android device


Watch this on YouTube

In some situations we need to to know what is the current display orientation of the device. In this post i explain how to get the current orientation of an android device. In order to get the display orientation of the android device you need to first get the display information of the device. 
                                                                     For getting the current display info you need to get an object of WindowManager class using the  method  getWindowManager(). After getting it you need to obtain an object of Display class using the WindowManager object and getDefaultDisplay() method.
                          WindowManager manager = getWindowManager();
          Display disp = manager.getDefaultDisplay();

MainActivity.java

  1. package com.orientationdemo;
  2. import android.os.Bundle;
  3. import android.app.Activity;
  4. import android.view.Display;
  5. import android.view.Menu;
  6. import android.view.WindowManager;
  7. import android.widget.Toast;
  8. public class MainActivity extends Activity {
  9. @Override
  10. protected void onCreate(Bundle savedInstanceState) {
  11. super.onCreate(savedInstanceState);
  12. setContentView(R.layout.activity_main);
  13. WindowManager manager = getWindowManager();
  14. Display disp = manager.getDefaultDisplay();
  15. if(disp.getWidth() > disp.getHeight())
  16. {
  17. Toast.makeText(getBaseContext(),"Orientation:LANDSCAPE", Toast.LENGTH_LONG).show();
  18. }
  19. else
  20. {
  21. Toast.makeText(getBaseContext(),"Orientation:PORTRAIT", Toast.LENGTH_LONG).show();
  22. }
  23. }
  24. @Override
  25. public boolean onCreateOptionsMenu(Menu menu) {
  26. // Inflate the menu; this adds items to the action bar if it is present.
  27. getMenuInflater().inflate(R.menu.main, menu);
  28. return true;
  29. }
  30. }
You can change the orientation of AVD using the short key ctrl + f11