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