美文网首页
2019-10-09 通过传感器监听屏幕方向

2019-10-09 通过传感器监听屏幕方向

作者: 兣甅 | 来源:发表于2019-10-09 15:45 被阅读0次
直接上代码
import android.content.pm.ActivityInfo;
import android.hardware.*;
import android.util.Log;

public class OrientationListener implements SensorEventListener {
  //默认竖屏
  private int mOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
  //监听屏幕方向变化
  private OnOrientationChangeListener mListener;

  //防止检测太快
  private long time = 0;

  @Override
  public void onSensorChanged(SensorEvent event) {
    //没有监听不处理
    if (Sensor.TYPE_ACCELEROMETER != event.sensor.getType() || mListener == null) {
      return;
    }
    if (System.currentTimeMillis() - time < 500) {
      return;
    }
    time = System.currentTimeMillis();
    float[] values = event.values;
    //魅蓝5s测试信息如下:
    float x = values[0];//逆时针横放值为10,竖放值为0,顺时针横放值为-10
    float y = values[1];//正立竖放值为10,手机平放值为0,倒立竖放值为-10
    int newOrientation = -999;
    //防止边缘只抖动,所以只取了范围内的来监听,没有else
    if (x > -5 && x < 5 && y >= 5) {
      newOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;//正立竖放
    } else if (x > 5 && y < 5 && y > -5) {
      newOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;//逆时针横放
    } else if (x < -5 && y < 5 && y > -5) {
      newOrientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;//顺时针横放
    } else if (x > -5 && x < 5 && y < -5) {
      newOrientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;//倒立竖放
    }
    if (mOrientation != newOrientation) {
      if (mListener != null) {
        mListener.orientationChanged(newOrientation);
      }
      mOrientation = newOrientation;
    }
  }

  @Override
  public void onAccuracyChanged(Sensor sensor, int accuracy) {

  }

  public void setListener(OnOrientationChangeListener mListener) {
    this.mListener = mListener;
  }

  public interface OnOrientationChangeListener {
    //回调方向
    void orientationChanged(int newOrientation);
  }
}

相关文章

网友评论

      本文标题:2019-10-09 通过传感器监听屏幕方向

      本文链接:https://www.haomeiwen.com/subject/krsgpctx.html