系列文章目录
鸿蒙开发案例:进京赶考(1)
鸿蒙开发案例:进京赶考(2)
鸿蒙开发案例:进京赶考(3)
案例介绍
“进京赶考”是一款抽卡游戏,玩家在游戏界面中通过随机抽取到不同颜色的卡片,可获得不 同积分;抽卡结束后,根据积分的高低对游戏成绩进行判定(状元、榜眼、探花、进士)。本篇接上篇实现GameAbility的启动。
完成后效果如图所示,注意当进度条走完自动进入下一个页面,由于涉及到Ability之间的跳转需要在模拟器或真机上进行演示,在Previewer中无法展示如下效果
一、Ability是什么?
一个应用可以有一个 Ability,也可以有多个 Ability。在 HarmonyOS 应用的实际开发场景 中,往往需要多个 Ability。细节见https://zhuanlan.zhihu.com/p/668408551
二、使用步骤
1.创建 UIAbility
2.创建 Page 页面
创建完 gameability 后,需要为 Ability 设置 page 页面,选中 pages 目录,单击鼠标右键, 选择 New > Page,在对话框中修改名字后,即可创建相关的 Page 页面。
在GameAbility 文件中的 onWindowStageCreate()方法里,使用 windowStage.loadContent 为指定 Ability 设置相关的 Page 页面。
3.启动UIAbility
首先在 entryability 的 Second.ets 文件中定义跳转到GameAbility的方法,代码如下:
//启动GameAbility
turnToGameAbility(){
//1. 首先获取 AbilityContext 接口
let handler = getContext(this)
//2.获取到 AbilityContext 接口后,调用该接口中的 startAbility()方
this.startGameAbility(handler)
}
//具体的启动方法
startGameAbility(context) {
const want = {
bundleName: 'com.fj.myapplication',
abilityName: 'GameAbility',
parameters: {
name: `${this.name}`
}
};
try {
context.startAbility(want);
} catch (error) {
hilog.error(CommonConstants.LOG_COLOR, CommonConstants.TAG, '%{public}s', error);
}
}
修改aboutToAppear方法,增加方法调用 this.turnToGameAbility(),实现5秒后自动跳转到GameAblity加载的页面
总结
本文创新了新的GameAbility,思考如下问题:
如果不创建GameAbility,仅创建GamePage页面,在Second.ets文件中通过router跳转到该页面,如下所示,也可以达到案例要求的效果,那为何要创建GameAbility呢?
本篇完成后,Second.ets完整代码如下:
import router from '@ohos.router'
import hilog from '@ohos.hilog'
import CommonConstants from '../common/constants/CommonConstants';
@Entry
@Component
struct Second {
//获取首页传递过来的玩家姓名
@State
name: string = router.getParams()['name']
@State
currentvalue:number=20
@State
colorValue:number=20
private timer:number
build() {
Column() {
Text(this.name+'正在进入游戏……')
.fontSize(20)
.fontWeight(FontWeight.Bold)
Progress({
value:this.currentvalue,//当前值
total:100,
type:ProgressType.ScaleRing
})
.color(0x1E90FF)
.value(this.colorValue)
.width(150)
.style({strokeWidth:20,scaleCount:40,scaleWidth:4})
.margin({top:'10%'})
}
.width('100%')
.margin({top:20})
}
aboutToAppear(){
if(this.currentvalue<=100&&this.colorValue<=100){
this.timer=setInterval(()=>{
this.colorValue=this.colorValue+20
this.currentvalue=this.currentvalue+20
},1000)
}
setTimeout(()=>{
clearInterval(this.timer)
this.turnToGameAbility()
},5000)
}
//启动GameAbility
turnToGameAbility(){
//1. 首先获取 AbilityContext 接口
let handler = getContext(this)
//2.获取到 AbilityContext 接口后,调用该接口中的 startAbility()方
this.startGameAbility(handler)
}
//具体的启动方法
startGameAbility(context) {
const want = {
bundleName: 'com.fj.myapplication',
abilityName: 'GameAbility',
parameters: {
name: `${this.name}`
}
};
try {
context.startAbility(want);
} catch (error) {
hilog.error(CommonConstants.LOG_COLOR, CommonConstants.TAG, '%{public}s', error);
}
}
}