易得天气
第三方库:
"@hzw/zrouter": "^1.3.3",
"@pura/harmony-utils": "1.2.8",
"@ohos/axios": "^2.2.4"
初始页面(加载闪屏页):
@Entry
@Component
struct Index {
build() {
Navigation(ZRouter.getNavStack())
.mode(NavigationMode.Auto)
.hideTitleBar(true)
.height('100%')
.width('100%')
.onAppear(() => {
ZRouter.getInstance()
.setAnimate(false)
.push(RouterConstants.SPLASH_PAGE)
})
}
}
闪屏页(设置定时器延迟2s加载首页):
@Route({ name: RouterConstants.SPLASH_PAGE })
@ComponentV2
export struct SplashPage {
build() {
NavDestination() {
Column() {
Image($r('app.media.splash'))
.width('100%')
.height('100%')
.objectFit(ImageFit.Cover)
}
}
.hideTitleBar(true)
.height('100%')
.width('100%')
.onAppear(() => {
console.log('SplashPage aboutToAppear');
setTimeout(() => {
console.log("push")
ZRouter.getInstance().replace(RouterConstants.WEATHER_MAIN_PAGE)
}, 2000)
})
.onBackPressed(() => {
console.log('onBackPressed');
return true
})
}
}
在module.json5文件配置网络权限
{
"name": "ohos.permission.INTERNET",
"reason": '$string:reason_internet_permission'
}
首页面(网络请求天气数据):
const axiosInstance: AxiosInstance = axios.create({
// 设置超时时间
timeout: 100000,
headers: {
'Content-Type': 'application/json;charset=utf-8',
'Content-Language': 'zh_CN'
},
});
@Route({ name: RouterConstants.WEATHER_MAIN_PAGE })
@ComponentV2
export struct WeatherMainPage {
@Local data: string = '主页面'
aboutToAppear(): void {
console.log('WeatherMainPage aboutToAppear')
axiosInstance.get<string, AxiosResponse<string>, null>(Api.WEATHER_API, {
params: {
'citykey': 101210113
}
}).then((response: AxiosResponse<string>) => {
this.data = JSON.stringify(response)
LogUtil.error('data = ' + this.data)
}).catch((error: AxiosError) => {
this.data = JSON.stringify(error)
LogUtil.error('error = ' + this.data)
}).then(() => {
// 总是会执行
LogUtil.error('finished')
});
}
build() {
NavDestination() {
Column() {
Text(this.data)
.fontColor(Color.Black)
.fontSize(14)
.height('100%')
}
.width('100%')
.height('100%')
}
.hideTitleBar(true)
.height('100%')
.width('100%')
.onBackPressed(() => {
console.log('WeatherMainPage onBackPressed');
let context = getContext(this) as common.UIAbilityContext
context.terminateSelf()
return true
})
}
}
入口EntryAbility文件的onBackPressed()函数:
onBackPressed(): boolean {
// 当targetSdkVersion<12时,默认返回值为false,会销毁UIAbility。
// 当targetSdkVersion>=12时,默认返回值为true,会将UIAbility移动到后台不销毁。
// 这里希望返回桌面时销毁
return false
}
最后贴张效果图: