devicePortLandSensor.ets
2.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
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) {}
}
}