| 6 |
| 7 | public class OrientationHelper { |
| 8 |
| 9 | private static final int ORIENTATION_HYSTERESIS = 5; |
| 10 | private OrientationEventListener orientationEventListener; |
| 11 | private int rotation; |
| 12 |
| 13 | public static volatile boolean cameraRotationDisabled; |
| 14 | public static volatile int cameraRotation; |
| 15 | public static volatile int cameraOrientation; |
| 16 |
| 17 | private int roundOrientation(int orientation, int orientationHistory) { |
| 18 | boolean changeOrientation; |
| 19 | if (orientationHistory == OrientationEventListener.ORIENTATION_UNKNOWN) { |
| 20 | changeOrientation = true; |
| 21 | } else { |
| 22 | int dist = Math.abs(orientation - orientationHistory); |
| 23 | dist = Math.min(dist, 360 - dist); |
| 24 | changeOrientation = (dist >= 45 + ORIENTATION_HYSTERESIS); |
| 25 | } |
| 26 | if (changeOrientation) { |
| 27 | return ((orientation + 45) / 90 * 90) % 360; |
| 28 | } |
| 29 | return orientationHistory; |
| 30 | } |
| 31 |
| 32 | public OrientationHelper() { |
| 33 | orientationEventListener = new OrientationEventListener(ApplicationLoader.applicationContext) { |
| 34 | @Override |
| 35 | public void onOrientationChanged(int orientation) { |
| 36 | if (orientationEventListener == null || orientation == ORIENTATION_UNKNOWN) { |
| 37 | return; |
| 38 | } |
| 39 | int newOrietation = roundOrientation(orientation, rotation); |
| 40 | if (newOrietation != rotation) { |
| 41 | onOrientationUpdate(rotation = newOrietation); |
| 42 | } |
| 43 | } |
| 44 | }; |
| 45 | } |
| 46 |
| 47 | protected void onOrientationUpdate(int orientation) { |
| 48 |
| 49 | } |
| 50 |
| 51 | public void start() { |
| 52 | if (orientationEventListener.canDetectOrientation()) { |
| 53 | orientationEventListener.enable(); |
| 54 | } else { |
| 55 | orientationEventListener.disable(); |
| 56 | orientationEventListener = null; |
| 57 | } |
| 58 | } |
| 59 |
| 60 | public void stop() { |
| 61 | if (orientationEventListener != null) { |
| 62 | orientationEventListener.disable(); |
| 63 | orientationEventListener = null; |
| 64 | } |
| 65 | } |
| 66 |
| 67 | public int getOrientation() { |
| 68 | if (cameraRotationDisabled) { |
| 69 | return 0; |
| 70 | } |
| 71 | return rotation; |
| 72 | } |
| 73 | } |
| 74 |