下面列出了怎么用android.view.OrientationEventListener的API类实例代码及写法,或者点击链接到github查看源代码。
private void identifyOrientationEvents() {
OrientationEventListener myOrientationEventListener = new OrientationEventListener(context, SensorManager.SENSOR_DELAY_NORMAL) {
@Override
public void onOrientationChanged(int iAngle) {
final int[] iLookup = {0, 0, 0, 90, 90, 90, 90, 90, 90, 180, 180, 180, 180, 180, 180, 270, 270, 270, 270, 270, 270, 0, 0, 0}; // 15-degree increments
if (iAngle != ORIENTATION_UNKNOWN) {
int iNewOrientation = iLookup[iAngle / 15];
if (iOrientation != iNewOrientation) {
iOrientation = iNewOrientation;
}
mPhotoAngle = normalize(iAngle);
}
}
};
if (myOrientationEventListener.canDetectOrientation()) {
myOrientationEventListener.enable();
}
}
public DisplayOrientationDetector(Context context) {
mOrientationEventListener = new OrientationEventListener(context) {
/** This is either Surface.Rotation_0, _90, _180, _270, or -1 (invalid). */
private int mLastKnownRotation = -1;
@Override
public void onOrientationChanged(int orientation) {
if (orientation == OrientationEventListener.ORIENTATION_UNKNOWN ||
mDisplay == null) {
return;
}
final int rotation = mDisplay.getRotation();
if (mLastKnownRotation != rotation) {
mLastKnownRotation = rotation;
dispatchOnDisplayOrientationChanged(DISPLAY_ORIENTATIONS.get(rotation));
}
}
};
}
public DisplayOrientationDetector(Context context) {
mOrientationEventListener = new OrientationEventListener(context) {
/** This is either Surface.Rotation_0, _90, _180, _270, or -1 (invalid). */
private int mLastKnownRotation = -1;
@Override
public void onOrientationChanged(int orientation) {
if (orientation == OrientationEventListener.ORIENTATION_UNKNOWN ||
mDisplay == null) {
return;
}
final int rotation = mDisplay.getRotation();
if (mLastKnownRotation != rotation) {
mLastKnownRotation = rotation;
dispatchOnDisplayOrientationChanged(DISPLAY_ORIENTATIONS.get(rotation));
}
}
};
}
public DisplayOrientationDetector(Context context) {
mOrientationEventListener = new OrientationEventListener(context) {
/** This is either Surface.Rotation_0, _90, _180, _270, or -1 (invalid). */
private int mLastKnownRotation = -1;
@Override
public void onOrientationChanged(int orientation) {
if (orientation == OrientationEventListener.ORIENTATION_UNKNOWN ||
mDisplay == null) {
return;
}
final int rotation = mDisplay.getRotation();
if (mLastKnownRotation != rotation) {
mLastKnownRotation = rotation;
dispatchOnDisplayOrientationChanged(DISPLAY_ORIENTATIONS.get(rotation));
}
}
};
}
private void initOrientationListener() {
mOrientationListener = new OrientationEventListener(this) {
public void onOrientationChanged(int rotation) {
// 设置竖屏
if (rotation >= 0 && rotation <= 45 || rotation >= 315 || rotation >= 135 && rotation <= 225) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else if (rotation > 45 && rotation < 135 || rotation > 225 && rotation < 315) {
// 设置横屏
if (rotation > 225 && rotation < 315) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
}
}
}
};
}
public RCTCameraView(Context context) {
super(context);
this._context = context;
RCTCamera.createInstance(getDeviceOrientation(context));
_orientationListener = new OrientationEventListener(context, SensorManager.SENSOR_DELAY_NORMAL) {
@Override
public void onOrientationChanged(int orientation) {
if (setActualDeviceOrientation(_context)) {
layoutViewFinder();
}
}
};
if (_orientationListener.canDetectOrientation()) {
_orientationListener.enable();
} else {
_orientationListener.disable();
}
}
public CompassView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initSensors();
int colorAccent = ContextCompat.getColor(getContext(), R.color.colorAccent);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CompassView);
mPrimaryColor = a.getColor(R.styleable.CompassView_primaryColor, colorAccent);
mSecondaryColor = a.getColor(R.styleable.CompassView_secondaryColor, Color.WHITE);
a.recycle();
mOrientationEventListener = new OrientationEventListener(getContext()) {
@Override
public void onOrientationChanged(int i) {
configureOrientation();
}
};
}
public DisplayOrientationDetector(Context context) {
mOrientationEventListener = new OrientationEventListener(context) {
/** This is either Surface.Rotation_0, _90, _180, _270, or -1 (invalid). */
private int mLastKnownRotation = -1;
@Override
public void onOrientationChanged(int orientation) {
if (orientation == OrientationEventListener.ORIENTATION_UNKNOWN ||
mDisplay == null) {
return;
}
final int rotation = mDisplay.getRotation();
if (mLastKnownRotation != rotation) {
mLastKnownRotation = rotation;
dispatchOnDisplayOrientationChanged(DISPLAY_ORIENTATIONS.get(rotation));
}
}
};
}
public DisplayOrientationDetector(Context context) {
mOrientationEventListener = new OrientationEventListener(context) {
/** This is either Surface.Rotation_0, _90, _180, _270, or -1 (invalid). */
private int mLastKnownRotation = -1;
@Override
public void onOrientationChanged(int orientation) {
if (orientation == OrientationEventListener.ORIENTATION_UNKNOWN ||
mDisplay == null) {
return;
}
final int rotation = mDisplay.getRotation();
if (mLastKnownRotation != rotation) {
mLastKnownRotation = rotation;
dispatchOnDisplayOrientationChanged(DISPLAY_ORIENTATIONS.get(rotation));
}
}
};
}
@Override
public void onOrientationChanged(int orientation) {
if (orientation == OrientationEventListener.ORIENTATION_UNKNOWN) {
return;
}
//只检测是否有四个角度的改变
if (orientation < 45 || orientation > 315) { //0度
mCurrentOrientation = 0;
} else if (orientation > 45 && orientation < 135) { //90度
mCurrentOrientation = 90;
} else if (orientation > 135 && orientation < 225) { //180度
mCurrentOrientation = 180;
} else if (orientation > 225 && orientation < 315) { //270度
mCurrentOrientation = 270;
}
}
/**
* Translates from the device orientation given by the Android sensor APIs to the
* orientation for a JPEG image.
*/
private int getJpegOrientation(CameraCharacteristics c, int deviceOrientation) {
Log.d(TAG, "getJpegOrientation: ");
if (deviceOrientation == android.view.OrientationEventListener.ORIENTATION_UNKNOWN)
return 0;
int sensorOrientation = c.get(CameraCharacteristics.SENSOR_ORIENTATION);
// Round device orientation to a multiple of 90
deviceOrientation = (deviceOrientation + 45) / 90 * 90;
// Reverse device orientation for front-facing cameras
boolean facingFront = c.get(CameraCharacteristics.LENS_FACING) ==
CameraCharacteristics.LENS_FACING_FRONT;
if (facingFront) deviceOrientation = -deviceOrientation;
// Calculate desired JPEG orientation relative to camera orientation to make
// the image upright relative to the device orientation
int jpegOrientation = (sensorOrientation + deviceOrientation + 360) % 360;
return jpegOrientation;
}
/**
* Translates from the device orientation given by the Android sensor APIs to the
* orientation for a JPEG image.
*/
private int getJpegOrientation(CameraCharacteristics c, int deviceOrientation) {
Log.d(TAG, "getJpegOrientation: ");
if (deviceOrientation == android.view.OrientationEventListener.ORIENTATION_UNKNOWN)
return 0;
int sensorOrientation = c.get(CameraCharacteristics.SENSOR_ORIENTATION);
// Round device orientation to a multiple of 90
deviceOrientation = (deviceOrientation + 45) / 90 * 90;
// Reverse device orientation for front-facing cameras
boolean facingFront = c.get(CameraCharacteristics.LENS_FACING) ==
CameraCharacteristics.LENS_FACING_FRONT;
if (facingFront) deviceOrientation = -deviceOrientation;
// Calculate desired JPEG orientation relative to camera orientation to make
// the image upright relative to the device orientation
int jpegOrientation = (sensorOrientation + deviceOrientation + 360) % 360;
return jpegOrientation;
}
@Override
public void onViewCreated(final View view, Bundle savedInstanceState) {
view.findViewById(R.id.picture).setOnClickListener(this);
view.findViewById(R.id.info).setOnClickListener(this);
mTextureView = (AutoFitTextureView) view.findViewById(R.id.texture);
// Setup a new OrientationEventListener. This is used to handle rotation events like a
// 180 degree rotation that do not normally trigger a call to onCreate to do view re-layout
// or otherwise cause the preview TextureView's size to change.
mOrientationListener = new OrientationEventListener(getActivity(),
SensorManager.SENSOR_DELAY_NORMAL) {
@Override
public void onOrientationChanged(int orientation) {
if (mTextureView != null && mTextureView.isAvailable()) {
configureTransform(mTextureView.getWidth(), mTextureView.getHeight());
}
}
};
}
public VideoCaptureAndroid(int id, long native_capturer) {
this.id = id;
this.native_capturer = native_capturer;
this.info = new Camera.CameraInfo();
Camera.getCameraInfo(id, info);
// Must be the last thing in the ctor since we pass a reference to |this|!
final VideoCaptureAndroid self = this;
orientationListener = new OrientationEventListener(GetContext()) {
@Override public void onOrientationChanged(int degrees) {
if (degrees == OrientationEventListener.ORIENTATION_UNKNOWN) {
return;
}
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
degrees = (info.orientation - degrees + 360) % 360;
} else { // back-facing
degrees = (info.orientation + degrees) % 360;
}
self.OnOrientationChanged(self.native_capturer, degrees);
}
};
// Don't add any code here; see the comment above |self| above!
}
public static int roundOrientation(final int orientationInput) {
// landscape mode
int orientation = orientationInput;
if (orientation == OrientationEventListener.ORIENTATION_UNKNOWN) {
orientation = 0;
}
orientation = orientation % 360;
int retVal;
if (orientation < ((0 * 90) + 45)) {
retVal = 0;
} else if (orientation < ((1 * 90) + 45)) {
retVal = 90;
} else if (orientation < ((2 * 90) + 45)) {
retVal = 180;
} else if (orientation < ((3 * 90) + 45)) {
retVal = 270;
} else {
retVal = 0;
}
return retVal;
}
public OrientationHelper(@NonNull Context context, @NonNull Callback callback) {
mCallback = callback;
mListener = new OrientationEventListener(context.getApplicationContext(), SensorManager.SENSOR_DELAY_NORMAL) {
@SuppressWarnings("ConstantConditions")
@Override
public void onOrientationChanged(int orientation) {
int or = 0;
if (orientation == OrientationEventListener.ORIENTATION_UNKNOWN) {
or = mDeviceOrientation != -1 ? mDeviceOrientation : 0;
} else if (orientation >= 315 || orientation < 45) {
or = 0;
} else if (orientation >= 45 && orientation < 135) {
or = 90;
} else if (orientation >= 135 && orientation < 225) {
or = 180;
} else if (orientation >= 225 && orientation < 315) {
or = 270;
}
if (or != mDeviceOrientation) {
mDeviceOrientation = or;
mCallback.onDeviceOrientationChanged(mDeviceOrientation);
}
}
};
}
@TargetApi(Build.VERSION_CODES.M)
public Camera2Proxy(Activity activity) {
mActivity = activity;
mCameraManager = (CameraManager) mActivity.getSystemService(Context.CAMERA_SERVICE);
mOrientationEventListener = new OrientationEventListener(mActivity) {
@Override
public void onOrientationChanged(int orientation) {
mDeviceOrientation = orientation;
}
};
}
public static void register(MainActivity activity) {
current = new OrientationEventListener(activity, SensorManager.SENSOR_DELAY_NORMAL) {
int oldOrientation = -1;
@Override
public void onOrientationChanged(int angle) {
int iosOrientation = -1;
if (getInt(activity.getContentResolver(), ACCELEROMETER_ROTATION, 0) == 0) {
} else if (angle < 0) {
} else if (angle < DELTA || angle > (360 - DELTA))
iosOrientation = UIDeviceOrientation.Portrait;
else if (angle > (90 - DELTA) && angle < (90 + DELTA))
iosOrientation = UIDeviceOrientation.LandscapeLeft;
else if (angle > (180 - DELTA) && angle < (180 + DELTA))
iosOrientation = UIDeviceOrientation.PortraitUpsideDown;
else if (angle > (270 - DELTA) && angle < (270 + DELTA))
iosOrientation = UIDeviceOrientation.LandscapeRight;
if (iosOrientation < 0 || !GraphicsBridgeConstants.shouldAcceptOrientation(iosOrientation)) {
} else if (oldOrientation != iosOrientation) {
oldOrientation = iosOrientation;
Native.graphics().setOrientation(iosOrientation);
activity.onOrientationChanged(iosOrientation);
}
}
};
activity.getStateListener().register(new ActivityLifecycleListener() {
@Override
public void onPause() {
current.disable();
}
@Override
public void onResume() {
if (current.canDetectOrientation())
current.enable();
}
});
}
public CameraSession(CameraInfo info, Size preview, Size picture, int format) {
previewSize = preview;
pictureSize = picture;
pictureFormat = format;
cameraInfo = info;
SharedPreferences sharedPreferences = ApplicationLoader.applicationContext.getSharedPreferences("camera", Activity.MODE_PRIVATE);
currentFlashMode = sharedPreferences.getString(cameraInfo.frontCamera != 0 ? "flashMode_front" : "flashMode", Camera.Parameters.FLASH_MODE_OFF);
orientationEventListener = new OrientationEventListener(ApplicationLoader.applicationContext) {
@Override
public void onOrientationChanged(int orientation) {
if (orientationEventListener == null || !initied || orientation == ORIENTATION_UNKNOWN) {
return;
}
jpegOrientation = roundOrientation(orientation, jpegOrientation);
WindowManager mgr = (WindowManager) ApplicationLoader.applicationContext.getSystemService(Context.WINDOW_SERVICE);
int rotation = mgr.getDefaultDisplay().getRotation();
if (lastOrientation != jpegOrientation || rotation != lastDisplayOrientation) {
if (!isVideo) {
configurePhotoCamera();
}
lastDisplayOrientation = rotation;
lastOrientation = jpegOrientation;
}
}
};
if (orientationEventListener.canDetectOrientation()) {
orientationEventListener.enable();
} else {
orientationEventListener.disable();
orientationEventListener = null;
}
}
private int roundOrientation(int orientation, int orientationHistory) {
boolean changeOrientation;
if (orientationHistory == OrientationEventListener.ORIENTATION_UNKNOWN) {
changeOrientation = true;
} else {
int dist = Math.abs(orientation - orientationHistory);
dist = Math.min(dist, 360 - dist);
changeOrientation = (dist >= 45 + ORIENTATION_HYSTERESIS);
}
if (changeOrientation) {
return ((orientation + 45) / 90 * 90) % 360;
}
return orientationHistory;
}
protected void configureRecorder(int quality, MediaRecorder recorder) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(cameraInfo.cameraId, info);
int displayOrientation = getDisplayOrientation(info, false);
int outputOrientation = 0;
if (jpegOrientation != OrientationEventListener.ORIENTATION_UNKNOWN) {
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
outputOrientation = (info.orientation - jpegOrientation + 360) % 360;
} else {
outputOrientation = (info.orientation + jpegOrientation) % 360;
}
}
recorder.setOrientationHint(outputOrientation);
int highProfile = getHigh();
boolean canGoHigh = CamcorderProfile.hasProfile(cameraInfo.cameraId, highProfile);
boolean canGoLow = CamcorderProfile.hasProfile(cameraInfo.cameraId, CamcorderProfile.QUALITY_LOW);
if (canGoHigh && (quality == 1 || !canGoLow)) {
recorder.setProfile(CamcorderProfile.get(cameraInfo.cameraId, highProfile));
} else if (canGoLow) {
recorder.setProfile(CamcorderProfile.get(cameraInfo.cameraId, CamcorderProfile.QUALITY_LOW));
} else {
throw new IllegalStateException("cannot find valid CamcorderProfile");
}
isVideo = true;
}
/**
* Given the device orientation and Camera2 characteristics, this returns
* the required JPEG rotation for this camera.
*
* @param deviceOrientationDegrees the clockwise angle of the device orientation from its
* natural orientation in degrees.
* @return The angle to rotate image clockwise in degrees. It should be 0, 90, 180, or 270.
*/
public static int getJpegRotation(int deviceOrientationDegrees,
CameraCharacteristics characteristics)
{
if (deviceOrientationDegrees == OrientationEventListener.ORIENTATION_UNKNOWN)
{
return 0;
}
boolean isFrontCamera = characteristics.get(CameraCharacteristics.LENS_FACING) ==
CameraMetadata.LENS_FACING_FRONT;
int sensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
return getImageRotation(sensorOrientation, deviceOrientationDegrees, isFrontCamera);
}
public CameraSession(CameraInfo info, Size preview, Size picture, int format) {
previewSize = preview;
pictureSize = picture;
pictureFormat = format;
cameraInfo = info;
SharedPreferences sharedPreferences = ApplicationLoader.applicationContext.getSharedPreferences("camera", Activity.MODE_PRIVATE);
currentFlashMode = sharedPreferences.getString(cameraInfo.frontCamera != 0 ? "flashMode_front" : "flashMode", Camera.Parameters.FLASH_MODE_OFF);
orientationEventListener = new OrientationEventListener(ApplicationLoader.applicationContext) {
@Override
public void onOrientationChanged(int orientation) {
if (orientationEventListener == null || !initied || orientation == ORIENTATION_UNKNOWN) {
return;
}
jpegOrientation = roundOrientation(orientation, jpegOrientation);
WindowManager mgr = (WindowManager) ApplicationLoader.applicationContext.getSystemService(Context.WINDOW_SERVICE);
int rotation = mgr.getDefaultDisplay().getRotation();
if (lastOrientation != jpegOrientation || rotation != lastDisplayOrientation) {
if (!isVideo) {
configurePhotoCamera();
}
lastDisplayOrientation = rotation;
lastOrientation = jpegOrientation;
}
}
};
if (orientationEventListener.canDetectOrientation()) {
orientationEventListener.enable();
} else {
orientationEventListener.disable();
orientationEventListener = null;
}
}
private int roundOrientation(int orientation, int orientationHistory) {
boolean changeOrientation;
if (orientationHistory == OrientationEventListener.ORIENTATION_UNKNOWN) {
changeOrientation = true;
} else {
int dist = Math.abs(orientation - orientationHistory);
dist = Math.min(dist, 360 - dist);
changeOrientation = (dist >= 45 + ORIENTATION_HYSTERESIS);
}
if (changeOrientation) {
return ((orientation + 45) / 90 * 90) % 360;
}
return orientationHistory;
}
protected void configureRecorder(int quality, MediaRecorder recorder) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(cameraInfo.cameraId, info);
int displayOrientation = getDisplayOrientation(info, false);
int outputOrientation = 0;
if (jpegOrientation != OrientationEventListener.ORIENTATION_UNKNOWN) {
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
outputOrientation = (info.orientation - jpegOrientation + 360) % 360;
} else {
outputOrientation = (info.orientation + jpegOrientation) % 360;
}
}
recorder.setOrientationHint(outputOrientation);
int highProfile = getHigh();
boolean canGoHigh = CamcorderProfile.hasProfile(cameraInfo.cameraId, highProfile);
boolean canGoLow = CamcorderProfile.hasProfile(cameraInfo.cameraId, CamcorderProfile.QUALITY_LOW);
if (canGoHigh && (quality == 1 || !canGoLow)) {
recorder.setProfile(CamcorderProfile.get(cameraInfo.cameraId, highProfile));
} else if (canGoLow) {
recorder.setProfile(CamcorderProfile.get(cameraInfo.cameraId, CamcorderProfile.QUALITY_LOW));
} else {
throw new IllegalStateException("cannot find valid CamcorderProfile");
}
isVideo = true;
}
private void initViewBefore(Context context) {
if (!(context instanceof AppCompatActivity)) {
throw new IllegalArgumentException("Context must be AppCompatActivity");
}
//是否使用surface view
isUseSurfaceView = SPUtils.getInstance().getBoolean("surface_renders", true);
//获取绑定的Activity实例
mAttachActivity = (AppCompatActivity) context;
//加载布局
View.inflate(context, R.layout.layout_exo_player_view, this);
//获取播放器实例,ffmpeg扩展不支持TextureView
exoPlayer = isUseSurfaceView
? new ExoFFmpegPlayer(mAttachActivity, trackSelector)
: ExoPlayerFactory.newSimpleInstance(mAttachActivity, trackSelector);
//屏幕翻转控制
mOrientationListener = new OrientationEventListener(mAttachActivity) {
@Override
public void onOrientationChanged(int orientation) {
if (mIsNeverPlay) {
return;
}
// 根据角度进行横屏切换
if (orientation >= 60 && orientation <= 120) {
mAttachActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
} else if (orientation >= 240 && orientation <= 300) {
mAttachActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
}
};
//声音管理器
mAudioManager = (AudioManager) mAttachActivity.getSystemService(Context.AUDIO_SERVICE);
if (mAudioManager != null)
mMaxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
}
public CameraProxy(Activity activity) {
mActivity = activity;
mOrientationEventListener = new OrientationEventListener(mActivity) {
@Override
public void onOrientationChanged(int orientation) {
setPictureRotate(orientation);
}
};
}
private void setPictureRotate(int orientation) {
if (orientation == OrientationEventListener.ORIENTATION_UNKNOWN) return;
orientation = (orientation + 45) / 90 * 90;
int rotation;
if (mCameraInfo.facing == CameraInfo.CAMERA_FACING_FRONT) {
rotation = (mCameraInfo.orientation - orientation + 360) % 360;
} else { // back-facing camera
rotation = (mCameraInfo.orientation + orientation) % 360;
}
mLatestRotation = rotation;
}
@TargetApi(Build.VERSION_CODES.M)
public Camera2Proxy(Activity activity) {
mActivity = activity;
mCameraManager = (CameraManager) mActivity.getSystemService(Context.CAMERA_SERVICE);
mOrientationEventListener = new OrientationEventListener(mActivity) {
@Override
public void onOrientationChanged(int orientation) {
mDeviceOrientation = orientation;
}
};
}
private int getJpegOrientation(int deviceOrientation) {
if (deviceOrientation == android.view.OrientationEventListener.ORIENTATION_UNKNOWN) return 0;
int sensorOrientation = mCameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
// Round device orientation to a multiple of 90
deviceOrientation = (deviceOrientation + 45) / 90 * 90;
// Reverse device orientation for front-facing cameras
boolean facingFront = mCameraCharacteristics.get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics
.LENS_FACING_FRONT;
if (facingFront) deviceOrientation = -deviceOrientation;
// Calculate desired JPEG orientation relative to camera orientation to make
// the image upright relative to the device orientation
int jpegOrientation = (sensorOrientation + deviceOrientation + 360) % 360;
Log.d(TAG, "jpegOrientation: " + jpegOrientation);
return jpegOrientation;
}