Skip to content
This repository was archived by the owner on Nov 27, 2025. It is now read-only.

Commit 0cf21e9

Browse files
wahaha150949liang_tao001
andauthored
fix:修改sensor.on监听接口返回的方向数据错误问题 (#35)
Signed-off-by: liang_tao001 <liangtao50@h-partners.com> Co-authored-by: liang_tao001 <liangtao50@h-partners.com>
1 parent 77e9df4 commit 0cf21e9

File tree

1 file changed

+19
-4
lines changed

1 file changed

+19
-4
lines changed

harmony/orientation_locker/src/main/ets/RNOrientationLockerTurboModule.ts

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ import display from '@ohos.display'
1111
import { BusinessError } from '@kit.BasicServicesKit'
1212
import sensor from '@ohos.sensor';
1313

14+
const ORIENTATION_UNKNOWN = -1;
15+
1416
export class RNOrientationLockerTurboModule extends TurboModule implements TM.OreitationLockerNativeModule.Spec {
1517
private lastDeviceOrientationValue:string = this.getOrientationString(display.getDefaultDisplaySync().orientation);
1618
private lastDeviceSensorOrientationValue:string = "";
@@ -27,11 +29,23 @@ export class RNOrientationLockerTurboModule extends TurboModule implements TM.Or
2729
}
2830
})
2931

30-
sensor.on(sensor.SensorId.ORIENTATION, (data: sensor.OrientationResponse) => {
31-
console.info("orientation change z value:"+data.alpha)
32+
sensor.on(sensor.SensorId.ACCELEROMETER, (data: sensor.AccelerometerResponse) => {
33+
const X = -data.x;
34+
const Y = -data.y;
35+
const Z = -data.z;
36+
const xyMagnitude = X * X + Y * Y;
37+
const zSquared = Z * Z;
38+
let orientation = ORIENTATION_UNKNOWN;
39+
if (xyMagnitude * 4 >= zSquared) {
40+
const angleRad = Math.atan2(-Y, X);
41+
let angleDeg = 90 - (angleRad * 180 / Math.PI);
42+
while (angleDeg >= 360) angleDeg -= 360;
43+
while (angleDeg < 0) angleDeg += 360;
44+
orientation = Math.round(angleDeg);
45+
}
46+
3247
let deviceOrientationValue:string = this.lastDeviceSensorOrientationValue;
33-
let orientation=data.alpha
34-
if (orientation == -1) {
48+
if (orientation === ORIENTATION_UNKNOWN) {
3549
deviceOrientationValue = "UNKNOWN";
3650
} else if (orientation > 355 || orientation < 5) {
3751
deviceOrientationValue = "PORTRAIT";
@@ -169,5 +183,6 @@ export class RNOrientationLockerTurboModule extends TurboModule implements TM.Or
169183
__onDestroy__(): void {
170184
super.__onDestroy__()
171185
display.off('change')
186+
sensor.off(sensor.SensorId.ACCELEROMETER)
172187
}
173188
}

0 commit comments

Comments
 (0)