devicePortLandSensor.ets 2.49 KB
import sensor from '@ohos.sensor';
import window from '@ohos.window';
import { WindowModel } from 'wdKit';

export class devicePLSensorManager {
  public static devicePLSensorOn(targetOrientation: number) {
    try {
      sensor.off(sensor.SensorId.ACCELEROMETER);
    } catch (e) {
    }
    let requestOrientation = -1; // sensor旋转的角度
    let num = -1;
    try {
      // 订阅加速度传感器数据
      sensor.on(sensor.SensorId.ACCELEROMETER, (response: sensor.AccelerometerResponse) => {
        if (num < 5) {
          num++;
          return;
        } else {
          num = -1;
        }
        let orientation = -1;
        let X = -response.x;
        let Y = -response.y;
        let Z = -response.z;
        let magnitude = X * X + Y * Y;
        if (magnitude * 4 >= Z * Z) {
          let OneEightyOverPi = 57.29577957855;
          let angle = Math.atan2(-Y, X) * OneEightyOverPi;
          orientation = 90 - Math.round(angle);
          while (orientation >= 360) {
            orientation -= 360;
          }
          while (orientation < 0) {
            orientation += 360;
          }
        }
        if (orientation == -1) return; // 水平方向不处理
        if (orientation > 315 || orientation < 45) {
          requestOrientation = window.Orientation.PORTRAIT;
        }
        else if (orientation > 45 && orientation < 135) {
          requestOrientation = window.Orientation.LANDSCAPE;
        }
        else if (orientation > 225 && orientation < 315) {
          requestOrientation = window.Orientation.LANDSCAPE_INVERTED;
        }
        if (targetOrientation == window.Orientation.PORTRAIT && requestOrientation == window.Orientation.PORTRAIT) {
          WindowModel.shared.setPreferredOrientation(window.Orientation.AUTO_ROTATION_RESTRICTED);
          sensor.off(sensor.SensorId.ACCELEROMETER);
        }
        if (targetOrientation == window.Orientation.LANDSCAPE && (requestOrientation == window.Orientation.LANDSCAPE || requestOrientation == window.Orientation.LANDSCAPE_INVERTED)) {
          WindowModel.shared.setPreferredOrientation(window.Orientation.AUTO_ROTATION_RESTRICTED);
          sensor.off(sensor.SensorId.ACCELEROMETER);
        }
      }, { interval: 2000000000 })
    } catch (e) {
      console.error(`屏幕状态报错:${e}`);
      try {
        sensor.off(sensor.SensorId.ACCELEROMETER);
      } catch (e) {

      }
    }
  }

  public static devicePLSensorOff() {
    try {
      sensor.off(sensor.SensorId.ACCELEROMETER);
    } catch (e) {
    }
  }
}