打開一個新的窗口
我們首先來實現如何在一個應用中打開一個新窗口,使用的模型是 Stage 模型
- 在項目文件里,新建一個
newWindow.ets
新文件
src/main/ets/pages/newWindow.ets
newWindow.ets
文件里面隨便寫點什么都行,這里是第一步創建的文件
新建的文件可以在 src/main/resources/base/profile/main_pages.json
查看
- 新建一個
Ability
src/main/ets
文件=>鼠標右鍵=>新建=>Ability
=>寫好新的Ability
名字比如這里我寫newWindow
ets
文件夾下會出現一個新的newWindow
文件夾,里面有個新的newWindow.ets
文件,打開它并修改下面的生命周期函數確保啟動文件為第一步新建的文件newWindow.ets
onWindowStageCreate(windowStage: window.WindowStage): void {windowStage.loadContent('pages/newWindow')}
- 回到入口文件
src/main/ets/pages/Index.ets
,加入一個可以跳到新窗口的按鈕
import { common } from '@kit.AbilityKit'@Entry
@Component
struct Index {build() {Button('在新窗口打開').onClick(_ => {//getContext() 得到UIAbilityContext對象//得到頁面所在UIAbility對應的UIAbilityContext// 強行逆轉父類 aslet ctx = getContext() as common.UIAbilityContext//啟動一個新的UIAbilityctx.startAbility({bundleName: 'com.example.myapplication', //必需!要啟動哪個應用下的UIAbilityabilityName: 'newWindow', //必需!要啟動的UIAbility名(參考moduels.json5中的名字)// moduleName: 'entry', //可選的!如果目標Ability在同一個模塊下,此屬性可以省略})})}
}
// AppScope/app.json5 查看 bundleName
這樣就可以打開一個新的窗口了
使用 Want
顯式 Want
// 我這里又新建了一個項目,所以有些名字和上面的例子不同
import { common ,Want } from '@kit.AbilityKit'@Entry
@Component
struct Index {build() {Button('在新窗口打開').onClick(_ => {let ctx = getContext() as common.UIAbilityContextlet wantInfo: Want = {bundleName: 'com.example.quanguokefei',abilityName: 'Page1',moduleName: 'entry',}//啟動一個新的UIAbilityctx.startAbility(wantInfo)})}
}
隱式 Want
- 跳到自定義窗口
隱式 Want 使用 skills 標簽來定義需要使用的能力
- 先去目錄
src/main/module.json5
修改需要跳轉的窗口 - 比如我要跳轉的窗口是
Page1
,加入actions: ["iampage1"]
,名字自由取,可以多個
{name: "Page1",srcEntry: "./ets/page1/Page1.ets",description: "$string:Page1_desc",icon: "$media:layered_image",label: "$string:Page1_label",startWindowIcon: "$media:startIcon",startWindowBackground: "$color:start_window_background",skills: [{actions: ["iampage1", "other_name"],},],
}
處理 Want
import { common ,Want } from '@kit.AbilityKit'@Entry
@Component
struct Index {build() {Button('在新窗口打開').onClick(_ => {let ctx = getContext() as common.UIAbilityContext// 在這里只需要action就行let wantInfo: Want = {action:'iampage1'}ctx.startAbility(wantInfo)})}
}
窗口啟動模式
singleton
啟動模式為單實例模式,也是默認情況下的啟動模式
multiton
啟動模式為多實例模式
specified
啟動模式為指定實例模式,針對一些特殊場景使用(例如文檔應用中每次新建文檔希望都能新建一個文檔實例,重復打開一個已保存的文檔希望打開的都是同一個文檔實例)
在 src/main/module.json5
文件中修改
{"module": {"abilities": [{"name": "Page1Ability","launchType": "singleton | multiton | specified"}]}
}
UIAbility 生命周期
執行順序:
首次啟動 onCreate → onWindowStageCreate → onForeground
切換到后臺 onBackground
從后臺重新打開 onForeground
正常退出應用 onBackground → onWindowStageDestroy → onDestroy
窗口已經存在的情況下,從主程序進入,不是窗口視圖 onNewWant → onForeground