先明确需求:应用全局是竖屏的,个别页面要支持横屏,且这个横屏是受控制中心的手机方向锁定限制。
因为是要锁定应用竖屏,所以module.json5中要设置:
"orientation": "portrait", // 固定屏幕方向
由于要在支持横屏的页面中用到mainwindow
let windowStage: window.WindowStage = AppStorage.get('windowStage') as window.WindowStage;
所以需要在你的 EntryAbility.ets文件中,先保存一个全局的windowStage:
onWindowStageCreate(windowStage: window.WindowStage): void {
// Main window is created, set main page for this ability
AppStorage.setOrCreate("windowStage",windowStage) //保存windowStage
}
然后在需要要支持横屏的页面里实现如下方法:
aboutToAppear(): void {
this.changeScreenOrientation(window.Orientation.AUTO_ROTATION_RESTRICTED);
}
aboutToDisappear(): void {
this.changeScreenOrientation(window.Orientation.PORTRAIT);
}
changeScreenOrientation(orientation: window.Orientation) {
let windowStage: window.WindowStage = AppStorage.get('windowStage') as window.WindowStage;
let windowClass: window.Window;
windowStage.getMainWindow((err, data) => {
const errCode: number = err.code;
if (errCode) {
console.error(`Failed to obtain the main window. Cause code: ${err.code}, message: ${err.message}`);
return;
}
windowClass = data;
try {
windowClass.setPreferredOrientation(orientation, (err) => {
const errCode: number = err.code;
if (errCode) {
console.error(`Failed to set window orientation. Cause code: ${err.code}, message: ${err.message}`);
return;
}
console.info('Succeeded in setting window orientation.');
});
} catch (exception) {
console.error(`Failed to set window orientation. Cause code: ${exception.code}, message: ${exception.message}`);
}
});
}
解释一下Orientation(https://developer.huawei.com/consumer/cn/doc/harmonyos-references/arkts-apis-window-e#orientation9)中几个枚举值的区别:

image.png
因此我们这里选择了AUTO_ROTATION_RESTRICTED。如果设置AUTO_ROTATION,那么就会忽略手机控制中心里的手机方向锁定键,页面始终与手机物理方向保持一致。