【每日学点HarmonyOS Next知识】页面级弹窗、返回桌面接口、横竖屏切换繁琐、设置状态栏颜色、设置屏幕常亮
#### 1、HarmonyOS uiContext.getPromptAction().openCustomDialog 能实现打开一个页面级的弹窗吗?
uiContext.getPromptAction().openCustomDialog 能实现打开一个页面级的弹窗?或者有什么方式可以实现在页面内打开一个页面级别的弹窗吗?场景是在A页面内打开一个弹窗,弹窗中点击按钮打开新的B页面,在新的B页面中没有弹窗,但是进行返回到A页面时,已经打开的弹窗还在
目前没有组件能直接实现这种效果,可以模拟弹窗效果来实现:参考demo如下:
```
import router from '@ohos.router';
@Entry
@Component
struct Index {
@State textValue: string = 'Hello World'
@State visible: Visibility = Visibility.None
build() {
Stack() {
Row() {
Column() {
Text('Hello World')
.fontSize(50)
.fontWeight(FontWeight.Bold)
Button('click')
.onClick(() => {
console.log("hit me!")
if (this.visible == Visibility.Visible) {
this.visible = Visibility.None
} else {
this.visible = Visibility.Visible
}
})
.backgroundColor(0x777474)
.fontColor(0x000000)
}
.width('100%')
}
.height('100%')
.backgroundColor("#36D")
Column() {
GridRow({
columns:{xs:1 ,sm: 4, md: 8, lg: 12},
breakpoints: { value: ["400vp", "600vp", "800vp"],
reference: BreakpointsReference.WindowSize },
})
{
GridCol({
span:{xs:1 ,sm: 2, md: 4, lg: 8},
offset:{xs:0 ,sm: 1, md: 2, lg: 2}
})
}
}
```
#### 2、HarmonyOS 退回桌面api?
退回桌面api,将应用挂在后台。
可以尝试通过windowStage获取主窗口对象,然后用minimize完成主窗口的最小化。 参考文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-window
#### 3、HarmonyOS 横竖屏切换实现过于繁琐?
当前体验不好,需要在每个页面(Entry)的 onPageShow中写下转屏函数;
目前可以自定义一个工具类来统一管理所有页面的展示方式,参考下这个demo呢:
Index7gongju.ets
```
import Stack from '@ohos.util.Stack';
import { uiObserver, window } from '@kit.ArkUI';
import { common, UIAbility } from '@kit.AbilityKit';
class MyPage {
id?: string
name?: ResourceStr
path?: string
type?: string
lifeCricle?: number
}
interface pageTracking {
page: MyPage
//onshown时刻
starttime: number
//停留时间
statetime: number
}
//窗口做区分 string
let mypagestack: Record<string, Stack<pageTracking>> = {};
let windows: Record<string, window.Window> = {};
let pageOrientations: Record<string, window.Orientation> = {
"Index": window.Orientation.UNSPECIFIED,
"Logon": window.Orientation.PORTRAIT,
"Detail": window.Orientation.LANDSCAPE,
"Page2": window.Orientation.PORTRAIT_INVERTED,
"Page3": window.Orientation.LANDSCAPE_INVERTED,
}
//要求mainWindow传参
//每个窗口的页面路径一定是一条链 不传默认主窗
export function observerAll(curWindow: window.Window, windowName ?: string) {
//判断是否为空 mainWindow
if (!windowName || windowName == 'mainWindow') {
windowName = 'mainWindow'
}
let name = windowName as string
windows[name] = curWindow;
let myObserve = curWindow.getUIContext().getUIObserver();
mypagestack[name] = new Stack<pageTracking>();
// mypagestack.push <windowName, Stack<pageTracking>>
//监听navDestination组件生命周期变化
myObserve.on('navDestinationUpdate', (info) => {
//映射成mypage
let mypage = new MyPage
mypage.id = info.navDestinationId
mypage.name = info.name
mypage.path = info.param?.toString()
mypage.type = 'NavDestination'
mypage.lifeCricle = info.state
//
tracking(mypage, name)
})
//监听page生命周期变化
myObserve.on('routerPageUpdate', (info) => {
// enterPageLoaded = true;
let mypage = new MyPage
mypage.id = String(info.index)
// router的name字段额外返回了path,去最后一个名称即可
mypage.name = info.name.split('/').pop()
mypage.path = info.path
mypage.type = 'page'
mypage.lifeCricle = navState(info.state)
tracking(mypage, name)
})
}
//使用mypage埋点 存生命周期信息
function tracking(mypage: MyPage, windowname: string) {
let stack: Stack<pageTracking> = mypagestack[windowname]
let pagetracking: pageTracking;
// 1.存页面信息(abouttoappear),同时打印当前所有路径 打印当前栈的顺序
// 如果当前栈元素为一个且当前元素为navd页面,仅修改对应页面的类型
// 不入栈 ,而是将对应的栈顶元素的page类型改为navPage
if (mypage.lifeCricle == 2) {
let firstPage = stack.peek()
if (stack.length == 1 && firstPage.page.type == 'NavDestination') {
firstPage = stack.pop()
firstPage.page.type = 'navPage'
stack.push(firstPage)
} else {
stack.push({
page: mypage,
starttime: Date.now(),
statetime: 0,
})
let pagesPath = windowname + ':'
stack.forEach((pagetraking) => {
pagesPath += '->' + pagetraking.page.name?.toString()
})
console.log(pagesPath)
}
}
// 2.更新页面信息 :onshown(刷新开始时间)
else if (mypage.lifeCricle == 0) {
pagetracking = stack.pop();
pagetracking.starttime = Date.now()
stack.push(pagetracking)
// 改变方向:
let defaultOrientation = window.Orientation.PORTRAIT
if (!!pageOrientations[mypage.name as string]) {
defaultOrientation = pageOrientations[mypage.name as string];
}
windows[windowname].setPreferredOrientation(defaultOrientation)
}
// 3.更新页面信息 :onhidden(累计值 刷新停留时间)
else if (mypage.lifeCricle == 1) {
pagetracking = stack.pop();
pagetracking.statetime = Date.now() - pagetracking.starttime
stack.push(pagetracking)
}
// 4.输出页面信息 abouttodistoappear 删除页面信息
else if (mypage.lifeCricle == 3) {
let pagesPath = windowname + ':'
//
// let time=Date.now()-stack.pop().starttime
// console.log('zyf'+)
//展示当前页面展示时间
// stack.forEach((pagetraking) => {
// // let time=Date.now()-pagetraking.starttime
// // console.log('zyf'+pagetraking.page.name?.toString() + time + 'ms');
// console.log('zyf'+pagetraking.page.name?.toString() + pagetraking.statetime + 'ms');
// })
let popPage = stack.pop()
console.log(popPage.page.name?.toString() + ' statetime ' + popPage.statetime + 'ms')
console.log('popPage :' + popPage.page.name)
stack.forEach((pagetraking) => {
pagesPath += '->' + pagetraking.page.name?.toString()
})
console.log(pagesPath);
}
}
//NavDestination与page生命周期统一
function navState(state: number): number {
if (state == 0) {
return 2
} else if (state == 1) {
return 3
} else if (state == 2) {
return 0
} else if (state == 3) {
return 1
} else if (state == 4) {
return 100
} else {
return 4
}
}
```
然后在Aililty中引用这个工具类,在onWindowStageCreate中调用,参考下面代码
```
import { observerAll } from '../pages/Index7gongju';
onWindowStageCreate(windowStage: window.WindowStage): void {
// Main window is created, set main page for this ability
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
windowStage.loadContent('pages/Logon', (err) => {
if (err.code) {
hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
return;
}
try {
let mainWindow = windowStage.getMainWindowSync()
observerAll(mainWindow)
} catch (error) {
console.error(error, " zzzzzz")
}
hilog.info(0x0000, 'testTag', 'Succeeded in loading the content.');
});
}
```
#### 4、HarmonyOS 如何设置状态栏为背景图片或颜色?
参考如下代码:
```
import { BusinessError } from '@ohos.base';
import { window } from '@kit.ArkUI';
@Entry
@Component
struct chuangkou{
build() {
Button("窗口设置").width(100).height(100)
.onClick(()=>{
let SystemBarProperties: window.SystemBarProperties = {
statusBarColor: '#ffee5610',
};
let windowClass: window.Window | undefined = undefined;
try {
let promise = window.getLastWindow(getContext());
promise.then((data) => {
windowClass = data;
windowClass.setWindowSystemBarProperties(SystemBarProperties)
console.info('Succeeded in obtaining the top window. Data: '+ JSON.stringify(data));
}).catch((err: BusinessError) => {
console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(err));
});
} catch (exception) {
console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(exception));
}
})
}
}
```
参考链接:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-window-V5#setwindowsystembarproperties9
#### 5、HarmonyOS 如何设置屏幕常亮并设置屏幕亮度最高?
请参考以下代码,通过点击事件设置屏幕常亮,也可以根据业务需求通过其他方式设置:
```
import { BusinessError } from '@ohos.base';
import { window } from '@kit.ArkUI';
import common from '@ohos.app.ability.common';
@Entry
@Component
struct WebPage {
private context = getContext(this) as common.UIAbilityContext;
controller: webView.WebviewController = new webView.WebviewController();
build() {
Column() {
Button('keeplight')
.onClick(() => {
// 1.获取应用主窗口。
let windowClass: window.Window | undefined = undefined;
try {
window.getLastWindow(this.context, (err: BusinessError, data) => {
const errCode: number = err.code;
if (errCode) {
console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(err));
return;
}
windowClass = data;
console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(data));
try {
windowClass.setWindowKeepScreenOn(true, (err: BusinessError) => {
const errCode: number = err.code;
if (errCode) {
console.error('Failed to set the screen to be always on. Cause: ' + JSON.stringify(err));
return;
}
console.info('Succeeded in setting the screen to be always on.');
});
} catch (exception) {
console.error('Failed to set the screen to be always on. Cause: ' + JSON.stringify(exception));
}
});
} catch (exception) {
console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(exception));
}
})
}
}
}
```
点击按钮控制台输出
```
05-15 14:48:04.050 12178-12178 A03d00/JSAPP com.examp...lication I Succeeded in obtaining the top window. Data: {}
05-15 14:48:04.059 12178-12178 A03d00/JSAPP com.examp...lication I Succeeded in setting the screen to be always on.
```
更多推荐
所有评论(0)