赞
踩
先自我介绍一下,小编浙江大学毕业,去过华为、字节跳动等大厂,目前阿里P7
深知大多数程序员,想要提升技能,往往是自己摸索成长,但自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!
因此收集整理了一份《2024年最新HarmonyOS鸿蒙全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友。
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上鸿蒙开发知识点,真正体系化!
由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新
如果你需要这些资料,可以添加V获取:vip204888 (备注鸿蒙)
效果示意如下图所示,点击“打开PDF文档”时,会弹出选择框供用户选择。
terminateSelf()
方法实现。import common from ‘@ohos.app.ability.common’;
import hilog from ‘@ohos.hilog’;
const TAG: string = ‘[Page_FromStageModel]’;
const DOMAIN_NUMBER: number = 0xFF00;
@Entry
@Component
struct Page_FromStageModel {
@State message: string = ‘Hello World’
build() {
Button()
.onClick(() => {
let context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext; // UIAbilityContext
// context为需要停止的UIAbility实例的AbilityContext
context.terminateSelf((err) => {
if (err.code) {
hilog.error(DOMAIN_NUMBER, TAG, Failed to terminate self. Code is ${err.code}, message is ${err.message}
);
return;
}
});
})
}
}
当使用隐式Want启动其他应用的UIAbility并希望获取返回结果时,调用方需要使用 startAbilityForResult()
方法启动目标UIAbility。例如主应用中需要启动三方支付并获取支付结果。
{
“module”: {
“abilities”: [
{
…
“skills”: [
{
“entities”: [
…
“entity.system.default”
],
“actions”: [
…
“ohos.want.action.editData”
]
}
]
}
]
}
}
startAbilityForResult()
方法启动支付应用的UIAbility,在调用方want参数中的entities和action需要被包含在待匹配UIAbility的skills标签配置的entities和actions中。异步回调中的data用于后续接收支付UIAbility停止自身后返回给调用方的信息。系统匹配到符合entities和actions参数条件的UIAbility后,会弹出选择框展示匹配到的UIAbility实例列表供用户选择使用。import common from ‘@ohos.app.ability.common’;
import hilog from ‘@ohos.hilog’;
import Want from ‘@ohos.app.ability.Want’;
import { BusinessError } from ‘@ohos.base’;
const TAG: string = ‘[Page_UIAbilityComponentsInteractive]’;
const DOMAIN_NUMBER: number = 0xFF00;
@Entry
@Component
struct Page_UIAbilityComponentsInteractive {
build() {
Button()
.onClick(() => {
let context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext; // UIAbilityContext
let want: Want = {
deviceId: ‘’, // deviceId为空表示本设备
bundleName: ‘com.samples.stagemodelabilitydevelop’,
moduleName: ‘entry’, // moduleName非必选
abilityName: ‘FuncAbilityA’,
parameters: { // 自定义信息
info: ‘来自EntryAbility UIAbilityComponentsInteractive页面’
}
};
context.startAbilityForResult(want).then((data) => {
// …
}).catch((err: BusinessError) => {
hilog.error(DOMAIN_NUMBER, TAG, Failed to start ability for result. Code is ${err.code}, message is ${err.message}
);
});
})
}
}
terminateSelfWithResult()
方法实现停止自身,并将abilityResult参数信息返回给调用方。import common from ‘@ohos.app.ability.common’;
import hilog from ‘@ohos.hilog’;
const TAG: string = ‘[Page_FuncAbilityA]’;
const DOMAIN_NUMBER: number = 0xFF00;
@Entry
@Component
struct Page_FuncAbilityA {
build() {
Button()
.onClick(() => {
let context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext; // UIAbilityContext
const RESULT_CODE: number = 1001;
let abilityResult: common.AbilityResult = {
resultCode: RESULT_CODE,
want: {
bundleName: ‘com.samples.stagemodelabilitydevelop’,
moduleName: ‘entry’, // moduleName非必选
abilityName: ‘FuncAbilityB’,
parameters: {
info: ‘来自FuncAbility Index页面’
},
},
};
context.terminateSelfWithResult(abilityResult, (err) => {
if (err.code) {
hilog.error(DOMAIN_NUMBER, TAG, Failed to terminate self with result. Code is ${err.code}, message is ${err.message}
);
return;
}
});
})
}
}
startAbilityForResult()
方法回调中接收支付应用返回的信息,RESULT_CODE需要与前面 terminateSelfWithResult()
返回的数值保持一致。import common from ‘@ohos.app.ability.common’;
import hilog from ‘@ohos.hilog’;
import Want from ‘@ohos.app.ability.Want’;
import { BusinessError } from ‘@ohos.base’;
import promptAction from ‘@ohos.promptAction’;
const TAG: string = ‘[EntryAbility]’;
const DOMAIN_NUMBER: number = 0xFF00;
@Entry
@Component
struct Page_UIAbilityComponentsInteractive {
build() {
Button()
.onClick(() => {
let context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext; // UIAbilityContext
const RESULT_CODE: number = 1001;
let want: Want = {
deviceId: ‘’, // deviceId为空表示本设备
bundleName: ‘com.samples.stagemodelabilitydevelop’,
moduleName: ‘entry’, // moduleName非必选
abilityName: ‘FuncAbilityA’,
parameters: { // 自定义信息
info: ‘来自EntryAbility UIAbilityComponentsInteractive页面’
}
};
context.startAbilityForResult(want).then((data) => {
if (data?.resultCode === RESULT_CODE) {
// 解析被调用方UIAbility返回的信息
let info = data.want?.parameters?.info;
hilog.info(DOMAIN_NUMBER, TAG, JSON.stringify(info) ?? ‘’);
if (info !== null) {
promptAction.showToast({
message: JSON.stringify(info)
});
}
}
hilog.info(DOMAIN_NUMBER, TAG, JSON.stringify(data.resultCode) ?? ‘’);
}).catch((err: BusinessError) => {
hilog.error(DOMAIN_NUMBER, TAG, Failed to start ability for result. Code is ${err.code}, message is ${err.message}
);
});
})
}
}
当用户打开应用时,应用程序会以不同的窗口模式进行展示,即启动UIAbility的窗口模式。应用程序可以启动为全屏模式,悬浮窗模式或分屏模式。
全屏模式是指应用程序启动后,占据整个屏幕,用户无法同时查看其他窗口或应用程序。全屏模式通常适用于那些要求用户专注于特定任务或界面的应用程序。
悬浮窗模式是指应用程序启动后,以浮动窗口的形式显示在屏幕上,用户可以轻松切换到其他窗口或应用程序。悬浮窗通常适用于需要用户同时处理多个任务的应用程序。
分屏模式允许用户在同一屏幕上同时运行两个应用程序,其中一个应用程序占据屏幕左侧/上侧的一部分,另一个应用程序占据右侧/下侧的一部分。分屏模式主要用于提高用户的多任务处理效率。
使用 startAbility()
方法启动UIAbility时,可以通过在入参中增加 StartOptions 参数的windowMode属性来配置启动UIAbility的窗口模式。
说明:
startAbility()
方法启动UIAbility时,入参中未指定 StartOptions 参数的windowMode属性,那么UIAbility将以系统默认的窗口展示形态启动。以下是具体的操作步骤,以悬浮窗模式为例,假设需要从EntryAbility的页面中启动FuncAbility:
startAbility()
方法时,增加 StartOptions 参数。windowMode
字段为WINDOW_MODE_FLOATING
,表示启动的UIAbility将以悬浮窗的形式展示。windowMode
属性仅适用于系统应用,三方应用可以使用displayId
属性。import AbilityConstant from ‘@ohos.app.ability.AbilityConstant’;
import common from ‘@ohos.app.ability.common’;
import hilog from ‘@ohos.hilog’;
import StartOptions from ‘@ohos.app.ability.StartOptions’;
import Want from ‘@ohos.app.ability.Want’;
import { BusinessError } from ‘@ohos.base’;
const TAG: string = ‘[Page_UIAbilityComponentsInteractive]’;
const DOMAIN_NUMBER: number = 0xFF00;
@Entry
@Component
struct Page_UIAbilityComponentsInteractive {
build() {
Button()
.onClick(() => {
let context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext; // UIAbilityContext
let want: Want = {
deviceId: ‘’, // deviceId为空表示本设备
bundleName: ‘com.samples.stagemodelabilitydevelop’,
moduleName: ‘entry’, // moduleName非必选
abilityName: ‘FuncAbilityB’,
parameters: { // 自定义信息
info: ‘来自EntryAbility Index页面’
}
};
let options: StartOptions = {
windowMode: AbilityConstant.WindowMode.WINDOW_MODE_FLOATING
};
// context为调用方UIAbility的UIAbilityContext
context.startAbility(want, options).then(() => {
hilog.info(DOMAIN_NUMBER, TAG, ‘Succeeded in starting ability.’);
}).catch((err: BusinessError) => {
hilog.error(DOMAIN_NUMBER, TAG, Failed to start ability. Code is ${err.code}, message is ${err.message}
);
});
})
}
}
效果示意如下图所示。
一个UIAbility可以对应多个页面,在不同的场景下启动该UIAbility时需要展示不同的页面,例如从一个UIAbility的页面中跳转到另外一个UIAbility时,希望启动目标UIAbility的指定页面。
UIAbility的启动分为两种情况:UIAbility冷启动和UIAbility热启动。
本文主要讲解 目标UIAbility冷启动 两种启动指定页面的场景,以及在讲解启动指定页面之前会讲解到在调用方如何指定启动页面。
调用方UIAbility启动另外一个UIAbility时,通常需要跳转到指定的页面。例如FuncAbility包含两个页面(Index对应首页,Second对应功能A页面),此时需要在传入的want参数中配置指定的页面路径信息,可以通过want中的parameters参数增加一个自定义参数传递页面跳转信息。
import common from ‘@ohos.app.ability.common’;
import hilog from ‘@ohos.hilog’;
import Want from ‘@ohos.app.ability.Want’;
import { BusinessError } from ‘@ohos.base’;
const TAG: string = ‘[Page_UIAbilityComponentsInteractive]’;
const DOMAIN_NUMBER: number = 0xFF00;
@Entry
@Component
struct Page_UIAbilityComponentsInteractive {
build() {
Button()
.onClick(() => {
let context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext; // UIAbilityContext
let want: Want = {
deviceId: ‘’, // deviceId为空表示本设备
bundleName: ‘com.samples.stagemodelabilityinteraction’,
moduleName: ‘entry’, // moduleName非必选
abilityName: ‘FuncAbility’,
parameters: { // 自定义参数传递页面信息
router: ‘FuncA’
}
};
// context为调用方UIAbility的UIAbilityContext
context.startAbility(want).then(() => {
hilog.info(DOMAIN_NUMBER, TAG, ‘Succeeded in starting ability.’);
}).catch((err: BusinessError) => {
hilog.error(DOMAIN_NUMBER, TAG, Failed to start ability. Code is ${err.code}, message is ${err.message}
);
});
})
}
}
目标UIAbility冷启动时,在目标UIAbility的onCreate()
生命周期回调中,接收调用方传过来的参数。然后在目标UIAbility的onWindowStageCreate()
生命周期回调中,解析EntryAbility传递过来的want参数,获取到需要加载的页面信息url,传入windowStage.loadContent()
方法。
import AbilityConstant from ‘@ohos.app.ability.AbilityConstant’;
import UIAbility from ‘@ohos.app.ability.UIAbility’;
import Want from ‘@ohos.app.ability.Want’;
import window from ‘@ohos.window’;
export default class FuncAbility extends UIAbility {
funcAbilityWant: Want | undefined = undefined;
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
// 接收调用方UIAbility传过来的参数
this.funcAbilityWant = want;
}
onWindowStageCreate(windowStage: window.WindowStage) {
// Main window is created, set main page for this ability
let url = ‘pages/Index’;
if (this.funcAbilityWant?.parameters?.router && this.funcAbilityWant.parameters.router === ‘funcA’) {
url = ‘pages/Page_ColdStartUp’;
}
windowStage.loadContent(url, (err, data) => {
// …
});
}
}
在应用开发中,会遇到目标UIAbility实例之前已经启动过的场景,这时再次启动目标UIAbility时,不会重新走初始化逻辑,只会直接触发onNewWant()
生命周期方法。为了实现跳转到指定页面,需要在onNewWant()
中解析参数进行处理。
例如短信应用和联系人应用配合使用的场景。
onNewWant()
回调,而不会再走onCreate()
和onWindowStageCreate()
等初始化逻辑。图1 目标UIAbility热启动
开发步骤如下所示。
onWindowStageCreate()
生命周期回调中,通过调用 getUIContext()
接口获取UI上下文实例 UIContext
对象。import hilog from ‘@ohos.hilog’;
import UIAbility from ‘@ohos.app.ability.UIAbility’;
import Want from ‘@ohos.app.ability.Want’;
import window from ‘@ohos.window’;
import { UIContext } from ‘@ohos.arkui.UIContext’;
const DOMAIN_NUMBER: number = 0xFF00;
const TAG: string = ‘[EntryAbility]’;
export default class EntryAbility extends UIAbility {
funcAbilityWant: Want | undefined = undefined;
uiContext: UIContext | undefined = undefined;
// …
onWindowStageCreate(windowStage: window.WindowStage): void {
// Main window is created, set main page for this ability
let url = ‘pages/Index’;
if (this.funcAbilityWant?.parameters?.router && this.funcAbilityWant.parameters.router === ‘funcA’) {
url = ‘pages/Page_ColdStartUp’;
}
windowStage.loadContent(url, (err, data) => {
if (err.code) {
return;
}
let windowClass: window.Window;
windowStage.getMainWindow((err, data) => {
if (err.code) {
hilog.error(DOMAIN_NUMBER, TAG, Failed to obtain the main window. Code is ${err.code}, message is ${err.message}
);
return;
}
windowClass = data;
this.uiContext = windowClass.getUIContext();
})
});
}
}
onNewWant()
回调中解析调用方传递过来的want参数,通过调用UIContext中的getRouter()
方法获取 Router
对象,并进行指定页面的跳转。此时再次启动该短信应用的UIAbility实例时,即可跳转到该短信应用的UIAbility实例的指定页面。import AbilityConstant from ‘@ohos.app.ability.AbilityConstant’;
import hilog from ‘@ohos.hilog’;
import UIAbility from ‘@ohos.app.ability.UIAbility’;
import Want from ‘@ohos.app.ability.Want’;
import { BusinessError } from ‘@ohos.base’;
import { Router, UIContext } from ‘@ohos.arkui.UIContext’;
const DOMAIN_NUMBER: number = 0xFF00;
const TAG: string = ‘[EntryAbility]’;
export default class EntryAbility extends UIAbility {
funcAbilityWant: Want | undefined = undefined;
uiContext: UIContext | undefined = undefined;
onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void {
if (want?.parameters?.router && want.parameters.router === ‘funcB’) {
let funcAUrl = ‘pages/Page_HotStartUp’;
if (this.uiContext) {
let router: Router = this.uiContext.getRouter();
router.pushUrl({
url: funcAUrl
}).catch((err: BusinessError) => {
hilog.error(DOMAIN_NUMBER, TAG, Failed to push url. Code is ${err.code}, message is ${err.message}
);
});
}
}
}
// …
}
说明:
当被调用方 UIAbility组件启动模式 设置为multiton启动模式时,每次启动都会创建一个新的实例,那么 onNewWant() 回调就不会被用到。
Call调用是UIAbility能力的扩展,它为UIAbility提供一种能够被外部调用并与外部进行通信的能力。Call调用支持前台与后台两种启动方式,使UIAbility既能被拉起到前台展示UI,也可以在后台被创建并运行。Call调用在调用方与被调用方间建立了IPC通信,因此应用开发者可通过Call调用实现不同UIAbility之间的数据共享。
Call调用的核心接口是startAbilityByCall()
方法,与startAbility()
接口的不同之处在于:
startAbility()
仅支持前台启动。startAbilityByCall()
所返回的Caller对象与被调用方进行通信,而startAbility()
不具备通信能力。Call调用的使用场景主要包括:
表1 Call调用相关名词解释
名词 | 描述 |
---|---|
CallerAbility | 进行Call调用的UIAbility(调用方)。 |
CalleeAbility | 被Call调用的UIAbility(被调用方)。 |
Caller | 实际对象,由startAbilityByCall接口返回,CallerAbility可使用Caller与CalleeAbility进行通信。 |
Callee | 实际对象,被CalleeAbility持有,可与Caller进行通信。 |
Call调用示意图如下所示。
图1 Call调用示意图
说明:
Call功能主要接口如下表所示。具体的API详见 接口文档。
表2 Call功能主要接口
接口名 | 描述 |
---|---|
startAbilityByCall(want: Want): Promise | 启动指定UIAbility并获取其Caller通信接口,默认为后台启动,通过配置want可实现前台启动,详见 接口文档。AbilityContext与ServiceExtensionContext均支持该接口。 |
on(method: string, callback: CalleeCallBack): void | 通用组件Callee注册method对应的callback方法。 |
off(method: string): void | 通用组件Callee解注册method的callback方法。 |
call(method: string, data: rpc.Parcelable): Promise | 向通用组件Callee发送约定序列化数据。 |
callWithResult(method: string, data: rpc.Parcelable): Promise<rpc.MessageSequence> | 向通用组件Callee发送约定序列化数据, 并将Callee返回的约定序列化数据带回。 |
release(): void | 释放通用组件的Caller通信接口。 |
on(type: “release”, callback: OnReleaseCallback): void | 注册通用组件通信断开监听通知。 |
设备内通过Call调用实现UIAbility交互,涉及如下两部分开发:
在Callee被调用端,需要实现指定方法的数据接收回调函数、数据的序列化及反序列化方法。在需要接收数据期间,通过on接口注册监听,无需接收数据时通过off接口解除监听。
例如将CalleeAbility配置为单实例模式singleton
。
import UIAbility from ‘@ohos.app.ability.UIAbility’;
import type rpc from ‘@ohos.rpc’;
class MyParcelable {
num: number = 0;
str: string = ‘’;
constructor(num: number, string: string) {
this.num = num;
this.str = string;
};
mySequenceable(num, string): void {
this.num = num;
this.str = string;
};
marshalling(messageSequence: rpc.MessageSequence): boolean {
messageSequence.writeInt(this.num);
messageSequence.writeString(this.str);
return true;
};
unmarshalling(messageSequence: rpc.MessageSequence): boolean {
this.num = messageSequence.readInt();
this.str = messageSequence.readString();
return true;
};
};
被调用端Callee的监听函数注册时机,取决于应用开发者。注册监听之前的数据不会被处理,取消监听之后的数据不会被处理。如下示例在UIAbility的onCreate注册’MSG_SEND_METHOD’监听,在onDestroy取消监听,收到序列化数据后作相应处理并返回,应用开发者根据实际需要做相应处理。具体示例代码如下:
import type AbilityConstant from ‘@ohos.app.ability.AbilityConstant’;
import UIAbility from ‘@ohos.app.ability.UIAbility’;
import type Want from ‘@ohos.app.ability.Want’;
import hilog from ‘@ohos.hilog’;
import Logger from ‘…/utils/Logger’;
import type rpc from ‘@ohos.rpc’;
import type { Caller } from ‘@ohos.app.ability.UIAbility’;
const MSG_SEND_METHOD: string = ‘CallSendMsg’;
const DOMAIN_NUMBER: number = 0xFF00;
const TAG: string = ‘[CalleeAbility]’;
class MyParcelable {
num: number = 0;
str: string = ‘’;
constructor(num: number, string: string) {
this.num = num;
this.str = string;
}
mySequenceable(num, string): void {
this.num = num;
this.str = string;
}
marshalling(messageSequence: rpc.MessageSequence): boolean {
messageSequence.writeInt(this.num);
messageSequence.writeString(this.str);
return true;
};
unmarshalling(messageSequence: rpc.MessageSequence): boolean {
this.num = messageSequence.readInt();
this.str = messageSequence.readString();
return true;
};
};
function sendMsgCallback(data: rpc.MessageSequence): rpc.Parcelable {
hilog.info(DOMAIN_NUMBER, TAG, ‘%{public}s’, ‘CalleeSortFunc called’);
// 获取Caller发送的序列化数据
let receivedData: MyParcelable = new MyParcelable(0, ‘’);
data.readParcelable(receivedData);
hilog.info(DOMAIN_NUMBER, TAG, ‘%{public}s’, receiveData[${receivedData.num}, ${receivedData.str}]
);
let num: number = receivedData.num;
// 作相应处理
// 返回序列化数据result给Caller
return new MyParcelable(num + 1, send ${receivedData.str} succeed
) as rpc.Parcelable;
}
export default class CalleeAbility extends UIAbility {
caller: Caller | undefined;
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
try {
this.callee.on(MSG_SEND_METHOD, sendMsgCallback);
} catch (error) {
hilog.error(DOMAIN_NUMBER, TAG, ‘%{public}s’, Failed to register. Error is ${error}
);
};
}
releaseCall(): void {
try {
if (this.caller) {
this.caller.release();
this.caller = undefined;
}
Logger.info(‘caller release succeed’);
} catch (error) {
Logger.info(caller release failed with ${error}
);
};
}
onDestroy(): void {
try {
this.callee.off(MSG_SEND_METHOD);
hilog.info(DOMAIN_NUMBER, TAG, ‘%{public}s’, ‘Callee OnDestroy’);
this.releaseCall();
} catch (error) {
hilog.error(DOMAIN_NUMBER, TAG, ‘%{public}s’, Failed to register. Error is ${error}
);
};
}
}
import UIAbility from ‘@ohos.app.ability.UIAbility’;
import { Caller } from ‘@ohos.app.ability.UIAbility’;
import { BusinessError } from ‘@ohos.base’;
import common from ‘@ohos.app.ability.common’;
import promptAction from ‘@ohos.promptAction’;
网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
需要这份系统化的资料的朋友,可以添加V获取:vip204888 (备注鸿蒙)
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!
};
}
}
import UIAbility from ‘@ohos.app.ability.UIAbility’;
import { Caller } from ‘@ohos.app.ability.UIAbility’;
import { BusinessError } from ‘@ohos.base’;
import common from ‘@ohos.app.ability.common’;
import promptAction from ‘@ohos.promptAction’;
网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
需要这份系统化的资料的朋友,可以添加V获取:vip204888 (备注鸿蒙)
[外链图片转存中…(img-xBNElj8J-1713294498424)]
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。