Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
91 lines (74 sloc) 2.49 KB

核心工具类:

package net.imknown.device;

import android.app.Activity;
import android.support.annotation.IntDef;
import android.view.Surface;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

/**
 * Deal with real-time rotate orientation of device, <br/>
 * <font color=red>** NOT **</font> for `Screen Configuration Orientation`.
 *
 * @author imknown on 2016/5/31.
 */
public class OrientationUtils {

    /**
     * imknown: copied from {@link Surface}'s Rotation
     */
    @IntDef({Surface.ROTATION_0, Surface.ROTATION_90, Surface.ROTATION_180, Surface.ROTATION_270})
    @Retention(RetentionPolicy.SOURCE)
    public @interface SurfaceRotation {
    }

    @SurfaceRotation
    public static int getCurrentOrientationByDegree(int orientation) {
        int currentOrientation = Surface.ROTATION_0;

        if (orientation >= 315 || orientation < 45) {
            currentOrientation = Surface.ROTATION_90;
        } else if (orientation >= 45 && orientation < 135) {
            currentOrientation = Surface.ROTATION_180;
        } else if (orientation >= 135 && orientation < 225) {
            currentOrientation = Surface.ROTATION_270;
        } else if (orientation >= 225 && orientation < 315) {
            currentOrientation = Surface.ROTATION_0;
        }

        return currentOrientation;
    }

    /**
     * 设备 当前旋转的 物理方向
     */
    @SurfaceRotation
    public static int getRotation(Activity activity) {
        return activity.getWindowManager().getDefaultDisplay().getRotation();
    }
}

调用

/**
 * 当前实时的方向
 */
@OrientationUtils.SurfaceRotation
private int currentOrientation;
/**
 * 用来记录上次的方向
 */
@OrientationUtils.SurfaceRotation
private int lastCurrentOrientation;

private OrientationEventListener myOrientationEventListener;

private void initOrientation() {
    lastCurrentOrientation = OrientationUtils.getRotation(this);

    myOrientationEventListener = new OrientationEventListener(this, SensorManager.SENSOR_DELAY_NORMAL) {
        public void onOrientationChanged(int orientation) {
            currentOrientation = OrientationUtils.getCurrentOrientationByDegree(orientation);

            if (lastCurrentOrientation != currentOrientation) {
                lastCurrentOrientation = currentOrientation;

                // TODO ...
            }
        }
    };

    if (myOrientationEventListener.canDetectOrientation()) {
        myOrientationEventListener.enable();
    }
}