Sets up the orientation event listener if it does not exist. - Android User Interface

Android examples for User Interface:Screen Orientation

Description

Sets up the orientation event listener if it does not exist.

Demo Code


//package com.java2s;
import android.content.Context;
import android.hardware.Camera;
import android.view.OrientationEventListener;

public class Main {
    private static int mRotation = 0;
    private static int mCameraId = 0;
    private static OrientationEventListener mOrientationEventListener;


    public static void loadOrientationEventListener(Context c) {
        if (mOrientationEventListener != null) {
            mOrientationEventListener.disable();
            return;
        }/*w w  w. j  a  v  a 2s  .c o  m*/
        mOrientationEventListener = new OrientationEventListener(c) {
            @Override
            public void onOrientationChanged(int orientation) {
                if (orientation == ORIENTATION_UNKNOWN)
                    return;

                android.hardware.Camera.CameraInfo info = new android.hardware.Camera.CameraInfo();
                android.hardware.Camera.getCameraInfo(mCameraId, info);

                orientation = (orientation + 45) / 90 * 90;

                if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                    mRotation = (info.orientation - orientation + 360) % 360;
                } else { // back-facing camera
                    mRotation = (info.orientation + orientation) % 360;
                }

            }

        };
    }
}

Related Tutorials