how to detect orientation of android device?

I think the safest and easiest way is to add a tag for some element of your activity in XML. For example, set the viewpager's tag to "portrait" in the portrait layout and set it to "landscape" in in landscape. Then in your oncreate check for that tag like so:

if(mViewpager.getTag().equals("portrait"))
  // is in portrait
else
  // is in landscape

You can also use:

getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE

Use the getRotation method:

Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int rotation = display.getRotation();

From the documentation:

Returns the rotation of the screen from its "natural" orientation. The returned value may be Surface.ROTATION_0 (no rotation), Surface.ROTATION_90, Surface.ROTATION_180, or Surface.ROTATION_270. For example, if a device has a naturally tall screen, and the user has turned it on its side to go into a landscape orientation, the value returned here may be either Surface.ROTATION_90 or Surface.ROTATION_270 depending on the direction it was turned. The angle is the rotation of the drawn graphics on the screen, which is the opposite direction of the physical rotation of the device. For example, if the device is rotated 90 degrees counter-clockwise, to compensate rendering will be rotated by 90 degrees clockwise and thus the returned value here will be Surface.ROTATION_90.

Keep in mind that getRotation was introduced from Android 2.2. Use getOrientation if your target are older devices.