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