source
stringlengths
14
113
code
stringlengths
10
21.3k
application-dev\application-models\stop-pageability.md
import featureAbility from '@ohos.ability.featureAbility'; import hilog from '@ohos.hilog'; const TAG: string = 'PagePageAbilityFirst'; const domain: number = 0xFF00;
application-dev\application-models\stop-pageability.md
//... (async (): Promise<void> => { try { hilog.info(domain, TAG, 'Begin to terminateSelf'); await featureAbility.terminateSelf(); hilog.info(domain, TAG, 'terminateSelf succeed'); } catch (error) { hilog.error(domain, TAG, 'terminateSelf failed with ' + error); } })() //...
application-dev\application-models\subscribe-system-environment-variable-changes.md
import { common, EnvironmentCallback, Configuration } from '@kit.AbilityKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; import { BusinessError } from '@kit.BasicServicesKit'; const TAG: string = '[CollaborateAbility]'; const DOMAIN_NUMBER: number = 0xFF00; @Entry @Component struct Index { private context = this.getUIContext().getHostContext() as common.UIAbilityContext; private callbackId: number = 0; // ID of the subscription for system environment variable changes. subscribeConfigurationUpdate(): void { let systemLanguage: string | undefined = this.context.config.language; // Obtain the system language in use. // 1. Obtain an ApplicationContext object. let applicationContext = this.context.getApplicationContext(); // 2. Subscribe to system environment variable changes through ApplicationContext. let environmentCallback: EnvironmentCallback = { onConfigurationUpdated(newConfig: Configuration) { hilog.info(DOMAIN_NUMBER, TAG, `onConfigurationUpdated systemLanguage is ${systemLanguage}, newConfig: ${JSON.stringify(newConfig)}`); if (systemLanguage !== newConfig.language) { hilog.info(DOMAIN_NUMBER, TAG, `systemLanguage from ${systemLanguage} changed to ${newConfig.language}`); systemLanguage = newConfig.language; // Save the new system language as the system language in use, which will be used for comparison. } }, onMemoryLevel(level) { hilog.info(DOMAIN_NUMBER, TAG, `onMemoryLevel level: ${level}`); } } try { this.callbackId = applicationContext.on('environment', environmentCallback); } catch (err) { let code = (err as BusinessError).code; let message = (err as BusinessError).message; hilog.error(DOMAIN_NUMBER, TAG, `Failed to register applicationContext. Code is ${code}, message is ${message}`); } } // Page display. build() { //... } }
application-dev\application-models\subscribe-system-environment-variable-changes.md
import { common } from '@kit.AbilityKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; import { BusinessError } from '@kit.BasicServicesKit'; const TAG: string = '[CollaborateAbility]'; const DOMAIN_NUMBER: number = 0xFF00; @Entry @Component struct Index { private context = this.getUIContext().getHostContext() as common.UIAbilityContext; private callbackId: number = 0; // ID of the subscription for system environment variable changes. unsubscribeConfigurationUpdate() { let applicationContext = this.context.getApplicationContext(); try { applicationContext.off('environment', this.callbackId); } catch (err) { let code = (err as BusinessError).code; let message = (err as BusinessError).message; hilog.error(DOMAIN_NUMBER, TAG, `Failed to unregister applicationContext. Code is ${code}, message is ${message}`); } } // Page display. build() { //... } }
application-dev\application-models\subscribe-system-environment-variable-changes.md
import { AbilityStage, Configuration } from '@kit.AbilityKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; const TAG: string = '[MyAbilityStage]'; const DOMAIN_NUMBER: number = 0xFF00; let systemLanguage: string | undefined; // System language in use. export default class MyAbilityStage extends AbilityStage { onCreate(): void { systemLanguage = this.context.config.language; // Obtain the system language in use when the module is loaded for the first time. hilog.info(DOMAIN_NUMBER, TAG, `systemLanguage is ${systemLanguage}`); //... } onConfigurationUpdate(newConfig: Configuration): void { hilog.info(DOMAIN_NUMBER, TAG, `onConfigurationUpdate, language: ${newConfig.language}`); hilog.info(DOMAIN_NUMBER, TAG, `onConfigurationUpdated systemLanguage is ${systemLanguage}, newConfig: ${JSON.stringify(newConfig)}`); if (systemLanguage !== newConfig.language) { hilog.info(DOMAIN_NUMBER, TAG, `systemLanguage from ${systemLanguage} changed to ${newConfig.language}`); systemLanguage = newConfig.language; // Save the new system language as the system language in use, which will be used for comparison. } } }
application-dev\application-models\subscribe-system-environment-variable-changes.md
import { AbilityConstant, Configuration, UIAbility, Want } from '@kit.AbilityKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; const TAG: string = '[EntryAbility]'; const DOMAIN_NUMBER: number = 0xFF00; let systemLanguage: string | undefined; // System language in use. export default class EntryAbility extends UIAbility { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { systemLanguage = this.context.config.language; // Obtain the system language in use when the UIAbility instance is loaded for the first time. hilog.info(DOMAIN_NUMBER, TAG, `systemLanguage is ${systemLanguage}`); } onConfigurationUpdate(newConfig: Configuration): void { hilog.info(DOMAIN_NUMBER, TAG, `onConfigurationUpdated systemLanguage is ${systemLanguage}, newConfig: ${JSON.stringify(newConfig)}`); if (systemLanguage !== newConfig.language) { hilog.info(DOMAIN_NUMBER, TAG, `systemLanguage from ${systemLanguage} changed to ${newConfig.language}`); systemLanguage = newConfig.language; // Save the new system language as the system language in use, which will be used for comparison. } } // ... }
application-dev\application-models\subscribe-system-environment-variable-changes.md
import { FormExtensionAbility } from '@kit.FormKit'; import { Configuration } from '@kit.AbilityKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; const TAG: string = '[EntryAbility]'; const DOMAIN_NUMBER: number = 0xFF00; export default class EntryFormAbility extends FormExtensionAbility { onConfigurationUpdate(config: Configuration) { hilog.info(DOMAIN_NUMBER, TAG, '[EntryFormAbility] onConfigurationUpdate:' + JSON.stringify(config)); } // ... }
application-dev\application-models\uiability-data-sync-with-ui.md
import { hilog } from '@kit.PerformanceAnalysisKit'; import { UIAbility, Context, Want, AbilityConstant } from '@kit.AbilityKit'; const DOMAIN_NUMBER: number = 0xFF00; const TAG: string = '[EventAbility]'; export default class EntryAbility extends UIAbility { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { // Obtain an eventHub object. let eventhub = this.context.eventHub; // Subscribe to the event. eventhub.on('event1', this.eventFunc); eventhub.on('event1', (data: string) => { // Trigger the event to complete the service operation. }); hilog.info(DOMAIN_NUMBER, TAG, '%{public}s', 'Ability onCreate'); } // ... eventFunc(argOne: Context, argTwo: Context): void { hilog.info(DOMAIN_NUMBER, TAG, '1. ' + `${argOne}, ${argTwo}`); return; } }
application-dev\application-models\uiability-data-sync-with-ui.md
import { common } from '@kit.AbilityKit'; @Entry @Component struct Page_EventHub { private context = this.getUIContext().getHostContext() as common.UIAbilityContext; eventHubFunc(): void { // Trigger the event without parameters. this.context.eventHub.emit('event1'); // Trigger the event with one parameter. this.context.eventHub.emit('event1', 1); // Trigger the event with two parameters. this.context.eventHub.emit('event1', 2, 'test'); // You can design the parameters based on your service requirements. } build() { Column() { // ... List({ initialIndex: 0 }) { ListItem() { Row() { // ... } .onClick(() => { this.eventHubFunc(); this.getUIContext().getPromptAction().showToast({ message: 'EventHubFuncA' }); }) } // ... ListItem() { Row() { // ... } .onClick(() => { this.context.eventHub.off('event1'); this.getUIContext().getPromptAction().showToast({ message: 'EventHubFuncB' }); }) } // ... } // ... } // ... } }
application-dev\application-models\uiability-data-sync-with-ui.md
import { UIAbility } from '@kit.AbilityKit'; export default class EntryAbility extends UIAbility { // ... onDestroy(): void { this.context.eventHub.off('event1'); } }
application-dev\application-models\uiability-intra-device-interaction.md
import { common, Want } from '@kit.AbilityKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; import { BusinessError } from '@kit.BasicServicesKit'; const TAG: string = '[Page_UIAbilityComponentsInteractive]'; const DOMAIN_NUMBER: number = 0xFF00; @Entry @Component struct Page_UIAbilityComponentsInteractive { private context = this.getUIContext().getHostContext() as common.UIAbilityContext; build() { Column() { //... List({ initialIndex: 0 }) { ListItem() { Row() { //... } .onClick(() => { // Context is a member of the ability object and is required for invoking inside a non-ability object. // Pass in the Context object. let wantInfo: Want = { deviceId: '', // An empty deviceId indicates the local device. bundleName: 'com.samples.stagemodelabilitydevelop', moduleName: 'entry', // moduleName is optional. abilityName: 'FuncAbilityA', parameters: { // Custom information. info: 'From Page_UIAbilityComponentsInteractive of EntryAbility', }, }; // context is the UIAbilityContext of the initiator UIAbility. this.context.startAbility(wantInfo).then(() => { hilog.info(DOMAIN_NUMBER, TAG, 'startAbility success.'); }).catch((error: BusinessError) => { hilog.error(DOMAIN_NUMBER, TAG, 'startAbility failed.'); }); }) } //... } //... } //... } }
application-dev\application-models\uiability-intra-device-interaction.md
import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; export default class FuncAbilityA extends UIAbility { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { // Receive the parameters passed by the initiator UIAbility. let funcAbilityWant = want; let info = funcAbilityWant?.parameters?.info; } //... }
application-dev\application-models\uiability-intra-device-interaction.md
import { common } from '@kit.AbilityKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; const TAG: string = '[Page_FromStageModel]'; const DOMAIN_NUMBER: number = 0xFF00; @Entry @Component struct Page_FromStageModel { build() { Column() { //... Button('FuncAbilityB') .onClick(() => { let context = this.getUIContext().getHostContext() as common.UIAbilityContext; // UIAbilityContext // context is the UIAbilityContext of the UIAbility instance to stop. context.terminateSelf((err) => { if (err.code) { hilog.error(DOMAIN_NUMBER, TAG, `Failed to terminate self. Code is ${err.code}, message is ${err.message}`); return; } }); }) } //... } }
application-dev\application-models\uiability-intra-device-interaction.md
import { common, Want } from '@kit.AbilityKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; import { BusinessError } from '@kit.BasicServicesKit'; const TAG: string = '[Page_UIAbilityComponentsInteractive]'; const DOMAIN_NUMBER: number = 0xFF00; @Entry @Component struct Page_UIAbilityComponentsInteractive { build() { Column() { //... List({ initialIndex: 0 }) { ListItem() { Row() { //... } .onClick(() => { let context = this.getUIContext().getHostContext() as common.UIAbilityContext; // UIAbilityContext const RESULT_CODE: number = 1001; let want: Want = { deviceId: '', // An empty deviceId indicates the local device. bundleName: 'com.samples.stagemodelabilitydevelop', moduleName: 'entry', // moduleName is optional. abilityName: 'FuncAbilityA', parameters: { // Custom information. info: 'From UIAbilityComponentsInteractive of EntryAbility', } }; context.startAbilityForResult(want).then((data) => { if (data?.resultCode === RESULT_CODE) { // Parse the information returned by the target UIAbility. let info = data.want?.parameters?.info; hilog.info(DOMAIN_NUMBER, TAG, JSON.stringify(info) ?? ''); if (info !== null) { this.getUIContext().getPromptAction().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}`); }); }) } //... } //... } //... } }
application-dev\application-models\uiability-intra-device-interaction.md
import { common } from '@kit.AbilityKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; const TAG: string = '[Page_FuncAbilityA]'; const DOMAIN_NUMBER: number = 0xFF00; @Entry @Component struct Page_FuncAbilityA { build() { Column() { //... List({ initialIndex: 0 }) { ListItem() { Row() { //... } .onClick(() => { let context = this.getUIContext().getHostContext() as common.UIAbilityContext; // UIAbilityContext const RESULT_CODE: number = 1001; let abilityResult: common.AbilityResult = { resultCode: RESULT_CODE, want: { bundleName: 'com.samples.stagemodelabilitydevelop', moduleName: 'entry', // moduleName is optional. abilityName: 'FuncAbilityB', parameters: { info: 'From the Index page of FuncAbility', }, }, }; 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; } }); }) } //... } //... } //... } }
application-dev\application-models\uiability-intra-device-interaction.md
import { common, Want } from '@kit.AbilityKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; import { BusinessError } from '@kit.BasicServicesKit'; const TAG: string = '[Page_UIAbilityComponentsInteractive]'; const DOMAIN_NUMBER: number = 0xFF00; @Entry @Component struct Page_UIAbilityComponentsInteractive { build() { Column() { //... List({ initialIndex: 0 }) { ListItem() { Row() { //... } .onClick(() => { let context = this.getUIContext().getHostContext() as common.UIAbilityContext; // UIAbilityContext const RESULT_CODE: number = 1001; let want: Want = { deviceId: '', // An empty deviceId indicates the local device. bundleName: 'com.samples.stagemodelabilitydevelop', moduleName: 'entry', // moduleName is optional. abilityName: 'FuncAbilityA', parameters: { // Custom information. info: 'From UIAbilityComponentsInteractive of EntryAbility', } }; context.startAbilityForResult(want).then((data) => { if (data?.resultCode === RESULT_CODE) { // Parse the information returned by the target UIAbility. let info = data.want?.parameters?.info; hilog.info(DOMAIN_NUMBER, TAG, JSON.stringify(info) ?? ''); if (info !== null) { this.getUIContext().getPromptAction().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}`); }); }) } //... } //... } //... } }
application-dev\application-models\uiability-intra-device-interaction.md
import { common, Want } from '@kit.AbilityKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; import { BusinessError } from '@kit.BasicServicesKit'; const TAG: string = '[Page_UIAbilityComponentsInteractive]'; const DOMAIN_NUMBER: number = 0xFF00; @Entry @Component struct Page_UIAbilityComponentsInteractive { build() { Column() { //... List({ initialIndex: 0 }) { ListItem() { Row() { //... } .onClick(() => { let context = this.getUIContext().getHostContext() as common.UIAbilityContext; // UIAbilityContext let want: Want = { deviceId: '', // An empty deviceId indicates the local device. bundleName: 'com.samples.stagemodelabilityinteraction', moduleName: 'entry', // moduleName is optional. abilityName: 'FuncAbility', parameters: { // Custom parameter used to pass the page information. router: 'funcA' } }; // context is the UIAbilityContext of the initiator UIAbility. 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}`); }); }) } //... } //... } //... } }
application-dev\application-models\uiability-intra-device-interaction.md
import { AbilityConstant, Want, UIAbility } from '@kit.AbilityKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; import { window, UIContext } from '@kit.ArkUI'; const DOMAIN_NUMBER: number = 0xFF00; const TAG: string = '[EntryAbility]'; export default class EntryAbility extends UIAbility { funcAbilityWant: Want | undefined = undefined; uiContext: UIContext | undefined = undefined; onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { // Receive the parameters passed by the initiator UIAbility. this.funcAbilityWant = want; } onWindowStageCreate(windowStage: window.WindowStage): void { // Main window is created. Set a main page for this UIAbility. hilog.info(DOMAIN_NUMBER, TAG, '%{public}s', 'Ability onWindowStageCreate'); // Main window is created. Set a main page for this UIAbility. let url = 'pages/Index'; if (this.funcAbilityWant?.parameters?.router && this.funcAbilityWant.parameters.router === 'funcA') { url = 'pages/Page_ColdStartUp'; } windowStage.loadContent(url, (err, data) => { // ... }); } }
application-dev\application-models\uiability-intra-device-interaction.md
import { hilog } from '@kit.PerformanceAnalysisKit'; import { Want, UIAbility } from '@kit.AbilityKit'; import { window, UIContext } from '@kit.ArkUI'; 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 a main page for this UIAbility. hilog.info(DOMAIN_NUMBER, TAG, '%{public}s', 'Ability onWindowStageCreate'); 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(); }); hilog.info(DOMAIN_NUMBER, TAG, 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? ''); }); } }
application-dev\application-models\uiability-intra-device-interaction.md
import { AbilityConstant, Want, UIAbility } from '@kit.AbilityKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; import type { Router, UIContext } from '@kit.ArkUI'; import type { BusinessError } from '@kit.BasicServicesKit'; 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 === 'funcA') { 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}`); }); } } } }
application-dev\application-models\uiability-intra-device-interaction.md
import { AbilityConstant, common, Want, StartOptions } from '@kit.AbilityKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; import { BusinessError } from '@kit.BasicServicesKit'; const TAG: string = '[Page_UIAbilityComponentsInteractive]'; const DOMAIN_NUMBER: number = 0xFF00; @Entry @Component struct Page_UIAbilityComponentsInteractive { build() { Column() { //... List({ initialIndex: 0 }) { ListItem() { Row() { //... } .onClick(() => { let context = this.getUIContext().getHostContext() as common.UIAbilityContext; // UIAbilityContext let want: Want = { deviceId: '', // An empty deviceId indicates the local device. bundleName: 'com.samples.stagemodelabilitydevelop', moduleName: 'entry', // moduleName is optional. abilityName: 'FuncAbilityB', parameters: { // Custom information. info: 'From the Index page of EntryAbility', } }; let options: StartOptions = { windowMode: AbilityConstant.WindowMode.WINDOW_MODE_FLOATING }; // context is the UIAbilityContext of the initiator UIAbility. 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}`); }); }) } //... } //... } //... } }
application-dev\application-models\uiability-intra-device-interaction.md
import { UIAbility } from '@kit.AbilityKit';
application-dev\application-models\uiability-intra-device-interaction.md
import { rpc } from '@kit.IPCKit'; class MyParcelable { num: number = 0; str: string = ''; constructor(num: number, string: string) { this.num = num; this.str = string; } mySequenceable(num: number, string: 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; } }
application-dev\application-models\uiability-intra-device-interaction.md
import { AbilityConstant, UIAbility, Want, Caller } from '@kit.AbilityKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; import { rpc } from '@kit.IPCKit'; 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: number, string: 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'); // Obtain the parcelable data sent by the CallerAbility. 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; // Process the data. // Return the parcelable data result to the CallerAbility. 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; } hilog.info(DOMAIN_NUMBER, TAG, '%{public}s', 'caller release succeed'); } catch (error) { hilog.info(DOMAIN_NUMBER, TAG, '%{public}s', `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}`); } } }
application-dev\application-models\uiability-intra-device-interaction.md
import { UIAbility } from '@kit.AbilityKit';
application-dev\application-models\uiability-intra-device-interaction.md
import { common, Want, Caller } from '@kit.AbilityKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; import { BusinessError } from '@kit.BasicServicesKit'; const TAG: string = '[Page_UIAbilityComponentsInteractive]'; const DOMAIN_NUMBER: number = 0xFF00; @Entry @Component struct Page_UIAbilityComponentsInteractive { caller: Caller | undefined = undefined; // Register the onRelease() listener of the CallerAbility. private regOnRelease(caller: Caller): void { hilog.info(DOMAIN_NUMBER, TAG, `caller is ${caller}`); try { caller.on('release', (msg: string) => { hilog.info(DOMAIN_NUMBER, TAG, `caller onRelease is called ${msg}`); }) hilog.info(DOMAIN_NUMBER, TAG, 'succeeded in registering on release.'); } catch (err) { let code = (err as BusinessError).code; let message = (err as BusinessError).message; hilog.error(DOMAIN_NUMBER, TAG, `Failed to caller register on release. Code is ${code}, message is ${message}`); } }; build() { Column() { // ... List({ initialIndex: 0 }) { // ... ListItem() { Row() { // ... } .onClick(() => { let context = this.getUIContext().getHostContext() as common.UIAbilityContext; // UIAbilityContext let want: Want = { bundleName: 'com.samples.stagemodelabilityinteraction', abilityName: 'CalleeAbility', parameters: { // Custom information. info: 'CallSendMsg' } }; context.startAbilityByCall(want).then((caller: Caller) => { hilog.info(DOMAIN_NUMBER, TAG, `Succeeded in starting ability.Code is ${caller}`); if (caller === undefined) { hilog.info(DOMAIN_NUMBER, TAG, 'get caller failed'); return; } else { hilog.info(DOMAIN_NUMBER, TAG, 'get caller success'); this.regOnRelease(caller); this.getUIContext().getPromptAction().showToast({ message: 'CallerSuccess' }); try { caller.release(); } catch (releaseErr) { console.log('Caller.release catch error, error.code: ' + JSON.stringify(releaseErr.code) + ' error.message: ' + JSON.stringify(releaseErr.message)); } } }).catch((err: BusinessError) => { hilog.error(DOMAIN_NUMBER, TAG, `Failed to start ability. Code is ${err.code}, message is ${err.message}`); }); }) } // ... } // ... } // ... } }
application-dev\application-models\uiability-launch-type.md
// Configure a unique key for each UIAbility instance. // For example, in the document usage scenario, use the document path as the key. import { common, Want } from '@kit.AbilityKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; import { BusinessError } from '@kit.BasicServicesKit'; const TAG: string = '[Page_StartModel]'; const DOMAIN_NUMBER: number = 0xFF00; function getInstance(): string { return 'KEY'; } @Entry @Component struct Page_StartModel { private KEY_NEW = 'KEY'; build() { Row() { Column() { // ... Button() .onClick(() => { let context: common.UIAbilityContext = this.getUIContext().getHostContext() as common.UIAbilityContext; // context is the UIAbilityContext of the initiator UIAbility. let want: Want = { deviceId: '', // An empty deviceId indicates the local device. bundleName: 'com.samples.stagemodelabilitydevelop', abilityName: 'SpecifiedFirstAbility', moduleName: 'entry', // moduleName is optional. parameters: { // Custom information. instanceKey: this.KEY_NEW } }; context.startAbility(want).then(() => { hilog.info(DOMAIN_NUMBER, TAG, 'Succeeded in starting SpecifiedAbility.'); }).catch((err: BusinessError) => { hilog.error(DOMAIN_NUMBER, TAG, `Failed to start SpecifiedAbility. Code is ${err.code}, message is ${err.message}`); }) this.KEY_NEW = this.KEY_NEW + 'a'; }) // ... Button() .onClick(() => { let context: common.UIAbilityContext = this.getUIContext().getHostContext() as common.UIAbilityContext; // context is the UIAbilityContext of the initiator UIAbility. let want: Want = { deviceId: '', // An empty deviceId indicates the local device. bundleName: 'com.samples.stagemodelabilitydevelop', abilityName: 'SpecifiedSecondAbility', moduleName: 'entry', // moduleName is optional. parameters: { // Custom information. instanceKey: getInstance() } }; context.startAbility(want).then(() => { hilog.info(DOMAIN_NUMBER, TAG, 'Succeeded in starting SpecifiedAbility.'); }).catch((err: BusinessError) => { hilog.error(DOMAIN_NUMBER, TAG, `Failed to start SpecifiedAbility. Code is ${err.code}, message is ${err.message}`); }) this.KEY_NEW = this.KEY_NEW + 'a'; }) // ... } .width('100%') } .height('100%') } }
application-dev\application-models\uiability-launch-type.md
import { AbilityStage, Want } from '@kit.AbilityKit'; export default class MyAbilityStage extends AbilityStage { onAcceptWant(want: Want): string { // In the AbilityStage instance of the callee, a key string corresponding to a UIAbility instance is returned for UIAbility whose launch type is specified. // In this example, SpecifiedAbility of module1 is returned. if (want.abilityName === 'SpecifiedFirstAbility' || want.abilityName === 'SpecifiedSecondAbility') { // The returned KEY string is a custom string. if (want.parameters) { return `SpecifiedAbilityInstance_${want.parameters.instanceKey}`; } } // ... return 'MyAbilityStage'; } }
application-dev\application-models\uiability-lifecycle.md
import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; export default class EntryAbility extends UIAbility { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { // Initialize the page. } // ... }
application-dev\application-models\uiability-lifecycle.md
import { UIAbility } from '@kit.AbilityKit'; import { window } from '@kit.ArkUI'; import { hilog } from '@kit.PerformanceAnalysisKit'; const TAG: string = '[EntryAbility]'; const DOMAIN_NUMBER: number = 0xFF00; export default class EntryAbility extends UIAbility { // ... onWindowStageCreate(windowStage: window.WindowStage): void { // Subscribe to the WindowStage events (having or losing focus, switching to the foreground or background, or becoming interactive or non-interactive in the foreground). try { windowStage.on('windowStageEvent', (data) => { let stageEventType: window.WindowStageEventType = data; switch (stageEventType) { case window.WindowStageEventType.SHOWN: // Switch to the foreground. hilog.info(DOMAIN_NUMBER, TAG, `windowStage foreground.`); break; case window.WindowStageEventType.ACTIVE: // Gain focus. hilog.info(DOMAIN_NUMBER, TAG, `windowStage active.`); break; case window.WindowStageEventType.INACTIVE: // Lose focus. hilog.info(DOMAIN_NUMBER, TAG, `windowStage inactive.`); break; case window.WindowStageEventType.HIDDEN: // Switch to the background. hilog.info(DOMAIN_NUMBER, TAG, `windowStage background.`); break; case window.WindowStageEventType.RESUMED: // Interactive in the foreground. hilog.info(DOMAIN_NUMBER, TAG, `windowStage resumed.`); break; case window.WindowStageEventType.PAUSED: // Non-interactive in the foreground. hilog.info(DOMAIN_NUMBER, TAG, `windowStage paused.`); break; default: break; } }); } catch (exception) { hilog.error(DOMAIN_NUMBER, TAG, `Failed to enable the listener for window stage event changes. Cause: ${JSON.stringify(exception)}`); } hilog.info(DOMAIN_NUMBER, TAG, `%{public}s`, `Ability onWindowStageCreate`); // Set the page to be loaded. windowStage.loadContent('pages/Index', (err, data) => { // ... }); } }
application-dev\application-models\uiability-lifecycle.md
import { UIAbility } from '@kit.AbilityKit'; import { window } from '@kit.ArkUI'; export default class EntryAbility extends UIAbility { windowStage: window.WindowStage | undefined = undefined; // ... onWindowStageCreate(windowStage: window.WindowStage): void { this.windowStage = windowStage; // ... } onWindowStageDestroy() { // Release UI resources. } }
application-dev\application-models\uiability-lifecycle.md
import { UIAbility } from '@kit.AbilityKit'; import { window } from '@kit.ArkUI'; import { BusinessError } from '@kit.BasicServicesKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; const TAG: string = '[EntryAbility]'; const DOMAIN_NUMBER: number = 0xFF00; export default class EntryAbility extends UIAbility { windowStage: window.WindowStage | undefined = undefined; // ... onWindowStageCreate(windowStage: window.WindowStage): void { this.windowStage = windowStage; // ... } onWindowStageWillDestroy(windowStage: window.WindowStage) { // Release the resources obtained through the windowStage object. // Unsubscribe from the WindowStage events (having or losing focus, switching to the foreground or background, or becoming interactive or non-interactive in the foreground) in the onWindowStageWillDestroy() callback. try { if (this.windowStage) { this.windowStage.off('windowStageEvent'); } } catch (err) { let code = (err as BusinessError).code; let message = (err as BusinessError).message; hilog.error(DOMAIN_NUMBER, TAG, `Failed to disable the listener for windowStageEvent. Code is ${code}, message is ${message}`); } } onWindowStageDestroy() { // Release UI resources. } }
application-dev\application-models\uiability-lifecycle.md
import { UIAbility } from '@kit.AbilityKit'; export default class EntryAbility extends UIAbility { // ... onForeground(): void { // Apply for the resources required by the system or re-apply for the resources released in onBackground(). } onBackground(): void { // Release unused resources when the UI is invisible, or perform time-consuming operations in this callback, // for example, saving the status. } }
application-dev\application-models\uiability-lifecycle.md
import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; export default class EntryAbility extends UIAbility { // ... onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam) { // Update resources and data. } }
application-dev\application-models\uiability-lifecycle.md
import { UIAbility } from '@kit.AbilityKit'; export default class EntryAbility extends UIAbility { // ... onDestroy() { // Release system resources and save data. } }
application-dev\application-models\uiability-startup-adjust.md
import { common, OpenLinkOptions } from '@kit.AbilityKit'; import { BusinessError } from '@kit.BasicServicesKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; const TAG: string = '[UIAbilityComponentsOpenLink]'; const DOMAIN_NUMBER: number = 0xFF00; @Entry @Component struct Index { build() { Button('start link', { type: ButtonType.Capsule, stateEffect: true }) .width('87%') .height('5%') .margin({ bottom: '12vp' }) .onClick(() => { let context = this.getUIContext().getHostContext() as common.UIAbilityContext; // When using startAbility to explicitly start other UIAbilities, the openLink API is recommended. // let want: Want = { // bundleName: "com.test.example", // moduleName: "entry", // abilityName: "EntryAbility" // }; // try { // context.startAbility(want) // .then(() => { // hilog.info(DOMAIN_NUMBER, TAG, 'startAbility success.'); // }).catch((err: BusinessError) => { // hilog.error(DOMAIN_NUMBER, TAG, `startAbility failed. Code is ${err.code}, message is ${err.message}`); // }) // } catch (paramError) { // hilog.error(DOMAIN_NUMBER, TAG, `Failed to startAbility. Code is ${paramError.code}, message is ${paramError.message}`); // } let link: string = "https://www.example.com"; let openLinkOptions: OpenLinkOptions = { // Specify whether the matched abilities options must pass App Linking domain name verification. appLinkingOnly: true, // Same as parameter in want, which is used to transfer parameters. parameters: {demo_key: "demo_value"} }; try { context.openLink(link, openLinkOptions) .then(() => { hilog.info(DOMAIN_NUMBER, TAG, 'open link success.'); }).catch((err: BusinessError) => { hilog.error(DOMAIN_NUMBER, TAG, `open link failed. Code is ${err.code}, message is ${err.message}`); }) } catch (paramError) { hilog.error(DOMAIN_NUMBER, TAG, `Failed to start link. Code is ${paramError.code}, message is ${paramError.message}`); } }) } }
application-dev\application-models\uiability-startup-adjust.md
import { common, OpenLinkOptions } from '@kit.AbilityKit'; import { BusinessError } from '@kit.BasicServicesKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; const TAG: string = '[UIAbilityComponentsOpenLink]'; const DOMAIN_NUMBER: number = 0xFF00; @Entry @Component struct Index { build() { Button('start link', { type: ButtonType.Capsule, stateEffect: true }) .width('87%') .height('5%') .margin({ bottom: '12vp' }) .onClick(() => { let context = this.getUIContext().getHostContext() as common.UIAbilityContext; // When using startAbility to explicitly start other UIAbilities, the openLink API is recommended. // let want: Want = { // bundleName: "com.test.example", // moduleName: "entry", // abilityName: "EntryAbility" // }; // try { // context.startAbilityForResult(want) // .then((data) => { // hilog.info(DOMAIN_NUMBER, TAG, 'startAbility success. data:' + JSON.stringify(data)); // }).catch((err: BusinessError) => { // hilog.error(DOMAIN_NUMBER, TAG, `startAbility failed. Code is ${err.code}, message is ${err.message}`); // }) // } catch (paramError) { // hilog.error(DOMAIN_NUMBER, TAG, `Failed to startAbility. Code is ${paramError.code}, message is ${paramError.message}`); // } let link: string = "https://www.example.com"; let openLinkOptions: OpenLinkOptions = { // Specify whether the matched abilities options must pass App Linking domain name verification. appLinkingOnly: true, // Same as parameter in want, which is used to transfer parameters. parameters: {demo_key: "demo_value"} }; try { context.openLink(link, openLinkOptions, (err, data) => { // AbilityResult callback, which is triggered only when the started ability is terminated. hilog.info(DOMAIN_NUMBER, TAG, 'open link success. Callback result:' + JSON.stringify(data)); }).then(() => { hilog.info(DOMAIN_NUMBER, TAG, 'open link success.'); }).catch((err: BusinessError) => { hilog.error(DOMAIN_NUMBER, TAG, `open link failed. Code is ${err.code}, message is ${err.message}`); }) } catch (paramError) { hilog.error(DOMAIN_NUMBER, TAG, `Failed to start link. Code is ${paramError.code}, message is ${paramError.message}`); } }) } }
application-dev\application-models\uiability-usage.md
import { UIAbility } from '@kit.AbilityKit'; import { window } from '@kit.ArkUI'; export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage: window.WindowStage): void { // Main window is created. Set a main page for this ability. windowStage.loadContent('pages/Index', (err, data) => { // ... }); } // ... }
application-dev\application-models\uiability-usage.md
import { UIAbility, AbilityConstant, Want } from '@kit.AbilityKit'; export default class EntryAbility extends UIAbility { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { // Obtain the context of the UIAbility instance. let context = this.context; // ... } }
application-dev\application-models\uiability-usage.md
import { common, Want } from '@kit.AbilityKit'; @Entry @Component struct Page_EventHub { private context = this.getUIContext().getHostContext() as common.UIAbilityContext; startAbilityTest(): void { let want: Want = { // Want parameter information. }; this.context.startAbility(want); } // Page display. build() { // ... } }
application-dev\application-models\uiability-usage.md
import { common, Want } from '@kit.AbilityKit'; @Entry @Component struct Page_UIAbilityComponentsBasicUsage { startAbilityTest(): void { let context = this.getUIContext().getHostContext() as common.UIAbilityContext; let want: Want = { // Want parameter information. }; context.startAbility(want); } // Page display. build() { // ... } }
application-dev\application-models\uiability-usage.md
import { common } from '@kit.AbilityKit'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct Page_UIAbilityComponentsBasicUsage { // Page display. build() { Column() { //... Button('FuncAbilityB') .onClick(() => { let context = this.getUIContext().getHostContext() as common.UIAbilityContext; try { context.terminateSelf((err: BusinessError) => { if (err.code) { // Process service logic errors. console.error(`terminateSelf failed, code is ${err.code}, message is ${err.message}.`); return; } // Carry out normal service processing. console.info(`terminateSelf succeed.`); }); } catch (err) { // Capture the synchronization parameter error. let code = (err as BusinessError).code; let message = (err as BusinessError).message; console.error(`terminateSelf failed, code is ${code}, message is ${message}.`); } }) } } }
application-dev\application-models\uiability-usage.md
import { common, Want } from '@kit.AbilityKit'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct Index { @State message: string = 'Hello World'; @State context: common.UIAbilityContext = this.getUIContext().getHostContext() as common.UIAbilityContext; build() { Scroll() { Column() { Text(this.message) .id('HelloWorld') .fontSize(50) .fontWeight(FontWeight.Bold) .alignRules({ center: { anchor: '__container__', align: VerticalAlign.Center }, middle: { anchor: '__container__', align: HorizontalAlign.Center } }) .onClick(() => { this.message = 'Welcome'; }) Button('terminateSelf').onClick(() => { this.context.terminateSelf() }) Button('Start UIAbilityB').onClick((event: ClickEvent) => { let want: Want = { bundleName: this.context.abilityInfo.bundleName, abilityName: 'UIAbilityB', } this.context.startAbility(want, (err: BusinessError) => { if (err.code) { console.error(`Failed to startAbility. Code: ${err.code}, message: ${err.message}.`); } }); }) } } } }
application-dev\application-models\uiability-usage.md
import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; import { window } from '@kit.ArkUI'; export default class UIAbilityB extends UIAbility { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { // The caller does not need to manually pass parameters. The system automatically passes the caller's information to the Want object. console.log(`onCreate, callerPid: ${want.parameters?.['ohos.aafwk.param.callerPid']}.`); console.log(`onCreate, callerBundleName: ${want.parameters?.['ohos.aafwk.param.callerBundleName']}.`); console.log(`onCreate, callerAbilityName: ${want.parameters?.['ohos.aafwk.param.callerAbilityName']}.`); } onDestroy(): void { console.log(`UIAbilityB onDestroy.`); } onWindowStageCreate(windowStage: window.WindowStage): void { console.log(`Ability onWindowStageCreate.`); windowStage.loadContent('pages/Index', (err) => { if (err.code) { console.error(`Failed to load the content, error code: ${err.code}, error msg: ${err.message}.`); return; } console.log(`Succeeded in loading the content.`); }); } }
application-dev\application-models\uiextensionability.md
import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct Index { @State message: string = 'UIExtension UserA'; private myProxy: UIExtensionProxy | undefined = undefined; build() { Row() { Column() { Text(this.message) .fontSize(30) .size({ width: '100%', height: '50' }) .fontWeight(FontWeight.Bold) .textAlign(TextAlign.Center) UIExtensionComponent( { bundleName: 'com.samples.uiextensionability', abilityName: 'UIExtensionProvider', moduleName: 'entry', parameters: { 'ability.want.params.uiExtensionType': 'sys/commonUI', } }) .onRemoteReady((proxy) => { this.myProxy = proxy; }) .onReceive((data) => { this.message = JSON.stringify(data); }) .onTerminated((terminateInfo: TerminationInfo) => { // This callback is triggered when the started UIExtensionAbility is terminated by calling terminateSelfWithResult or terminateSelf. // It returns the result of the UIExtensionAbility's normal exit, including the result code and Want data. this.message = `terminate code: ${terminateInfo.code}, want: ${terminateInfo.want}`; }) .onError((error: BusinessError) => { // This callback is invoked when an error occurs during the running of the started UIExtensionAbility. // It returns the error code and error message when the UIExtensionAbility encounters an exception. this.message = `error code: ${error.code}, error msg: ${error.message}`; }) .offset({ x: 0, y: 10 }) .size({ width: 300, height: 300 }) .border({ width: 5, color: 0x317AF7, radius: 10, style: BorderStyle.Dotted }) UIExtensionComponent( { bundleName: 'com.samples.uiextension2', abilityName: 'UIExtensionProviderB', moduleName: 'entry', parameters: { 'ability.want.params.uiExtensionType': 'sys/commonUI', } }) .onRemoteReady((proxy) => { this.myProxy = proxy; }) .onReceive((data) => { this.message = JSON.stringify(data); }) .onTerminated((terminateInfo: TerminationInfo) => { // This callback is triggered when the started UIExtensionAbility is terminated by calling terminateSelfWithResult or terminateSelf. // It returns the result of the UIExtensionAbility's normal exit, including the result code and Want data. this.message = `terminate code: ${terminateInfo.code}, want: ${terminateInfo.want}`; }) .onError((error: BusinessError) => { // This callback is invoked when an error occurs during the running of the started UIExtensionAbility. // It returns the error code and error message when the UIExtensionAbility encounters an exception. this.message = `error code: ${error.code}, error msg: ${error.message}`; }) .offset({ x: 0, y: 50 }) .size({ width: 300, height: 300 }) .border({ width: 5, color: 0x317AF7, radius: 10, style: BorderStyle.Dotted }) } .width('100%') } .height('100%') } }
application-dev\application-models\uiextensionability.md
import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct Index { @State message: string = 'UIExtension User'; private myProxy: UIExtensionProxy | undefined = undefined; build() { Row() { Column() { Text(this.message) .fontSize(30) .size({ width: '100%', height: '50' }) .fontWeight(FontWeight.Bold) .textAlign(TextAlign.Center) UIExtensionComponent( { bundleName: 'com.samples.uiextensionability', abilityName: 'UIExtensionProviderA', moduleName: 'entry', parameters: { 'ability.want.params.uiExtensionType': 'sys/commonUI', } }) .onRemoteReady((proxy) => { this.myProxy = proxy; }) .onReceive((data) => { this.message = JSON.stringify(data); }) .onTerminated((terminateInfo: TerminationInfo) => { // This callback is triggered when the started UIExtensionAbility is terminated by calling terminateSelfWithResult or terminateSelf. // It returns the result of the UIExtensionAbility's normal exit, including the result code and Want data. this.message = `terminate code: ${terminateInfo.code}, want: ${terminateInfo.want}`; }) .onError((error: BusinessError) => { // This callback is invoked when an error occurs during the running of the started UIExtensionAbility. // It returns the error code and error message when the UIExtensionAbility encounters an exception. this.message = `error code: ${error.code}, error msg: ${error.message}`; }) .offset({ x: 0, y: 10 }) .size({ width: 300, height: 300 }) .border({ width: 5, color: 0x317AF7, radius: 10, style: BorderStyle.Dotted }) UIExtensionComponent( { bundleName: 'com.samples.uiextensionability', abilityName: 'UIExtensionProviderB', moduleName: 'entry', parameters: { 'ability.want.params.uiExtensionType': 'sys/commonUI', } }) .onRemoteReady((proxy) => { this.myProxy = proxy; }) .onReceive((data) => { this.message = JSON.stringify(data); }) .onTerminated((terminateInfo: TerminationInfo) => { // This callback is triggered when the started UIExtensionAbility is terminated by calling terminateSelfWithResult or terminateSelf. // It returns the result of the UIExtensionAbility's normal exit, including the result code and Want data. this.message = `terminate code: ${terminateInfo.code}, want: ${terminateInfo.want}`; }) .onError((error: BusinessError) => { // This callback is invoked when an error occurs during the running of the started UIExtensionAbility. // It returns the error code and error message when the UIExtensionAbility encounters an exception. this.message = `error code: ${error.code}, error msg: ${error.message}`; }) .offset({ x: 0, y: 50 }) .size({ width: 300, height: 300 }) .border({ width: 5, color: 0x317AF7, radius: 10, style: BorderStyle.Dotted }) } .width('100%') } .height('100%') } }
application-dev\application-models\uiextensionability.md
import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct Index { @State message: string = 'UIExtension User' private myProxy: UIExtensionProxy | undefined = undefined; build() { Row() { Column() { Text(this.message) .fontSize(30) .size({ width: '100%', height: '50' }) .fontWeight(FontWeight.Bold) .textAlign(TextAlign.Center) UIExtensionComponent( { bundleName: 'com.samples.uiextensionability', abilityName: 'UIExtensionProvider', moduleName: 'entry', parameters: { 'ability.want.params.uiExtensionType': 'sys/commonUI', } }) .onRemoteReady((proxy) => { this.myProxy = proxy; }) .onReceive((data) => { this.message = JSON.stringify(data); }) .onTerminated((terminateInfo: TerminationInfo) => { // This callback is triggered when the started UIExtensionAbility is terminated by calling terminateSelfWithResult or terminateSelf. // It returns the result of the UIExtensionAbility's normal exit, including the result code and Want data. this.message = `terminate code: ${terminateInfo.code}, want: ${terminateInfo.want}`; }) .onError((error: BusinessError) => { // This callback is invoked when an error occurs during the running of the started UIExtensionAbility. // It returns the error code and error message when the UIExtensionAbility encounters an exception. this.message = `error code: ${error.code}, error msg: ${error.message}`; }) .offset({ x: 0, y: 10 }) .size({ width: 300, height: 300 }) .border({ width: 5, color: 0x317AF7, radius: 10, style: BorderStyle.Dotted }) UIExtensionComponent( { bundleName: 'com.samples.uiextensionability', abilityName: 'UIExtensionProvider', moduleName: 'entry', parameters: { 'ability.want.params.uiExtensionType': 'sys/commonUI', } }) .onRemoteReady((proxy) => { this.myProxy = proxy; }) .onReceive((data) => { this.message = JSON.stringify(data); }) .onTerminated((terminateInfo: TerminationInfo) => { // This callback is triggered when the started UIExtensionAbility is terminated by calling terminateSelfWithResult or terminateSelf. // It returns the result of the UIExtensionAbility's normal exit, including the result code and Want data. this.message = `terminate code: ${terminateInfo.code}, want: ${terminateInfo.want}`; }) .onError((error: BusinessError) => { // This callback is invoked when an error occurs during the running of the started UIExtensionAbility. // It returns the error code and error message when the UIExtensionAbility encounters an exception. this.message = `error code: ${error.code}, error msg: ${error.message}`; }) .offset({ x: 0, y: 50 }) .size({ width: 300, height: 300 }) .border({ width: 5, color: 0x317AF7, radius: 10, style: BorderStyle.Dotted }) } .width('100%') } .height('100%') } }
application-dev\application-models\uiextensionability.md
import { Want, UIExtensionAbility, UIExtensionContentSession } from '@kit.AbilityKit'; const TAG: string = '[testTag] UIExtAbility'; export default class UIExtAbility extends UIExtensionAbility { onCreate() { console.log(TAG, `onCreate`); } onForeground() { console.log(TAG, `onForeground`); } onBackground() { console.log(TAG, `onBackground`); } onDestroy() { console.log(TAG, `onDestroy`); } onSessionCreate(want: Want, session: UIExtensionContentSession) { console.log(TAG, `onSessionCreate, want: ${JSON.stringify(want)}}`); let storage: LocalStorage = new LocalStorage(); storage.setOrCreate('session', session); session.loadContent('pages/Extension', storage); } onSessionDestroy(session: UIExtensionContentSession) { console.log(TAG, `onSessionDestroy`); } }
application-dev\application-models\uiextensionability.md
import { UIExtensionContentSession } from '@kit.AbilityKit'; const TAG: string = `[testTag] ExtensionPage`; @Entry() @Component struct Extension { @State message: string = `UIExtension provider`; localStorage: LocalStorage | undefined = this.getUIContext().getSharedLocalStorage(); private session: UIExtensionContentSession | undefined = this.localStorage?.get<UIExtensionContentSession>('session'); onPageShow() { console.info(TAG, 'show'); } build() { Row() { Column() { Text(this.message) .fontSize(30) .fontWeight(FontWeight.Bold) .textAlign(TextAlign.Center) Button("send data") .width('80%') .type(ButtonType.Capsule) .margin({ top: 20 }) .onClick(() => { this.session?.sendData({ "data": 543321 }); }) Button("terminate self") .width('80%') .type(ButtonType.Capsule) .margin({ top: 20 }) .onClick(() => { this.session?.terminateSelf(); this.localStorage?.clear(); }) Button("terminate self with result") .width('80%') .type(ButtonType.Capsule) .margin({ top: 20 }) .onClick(() => { this.session?.terminateSelfWithResult({ resultCode: 0, want: { bundleName: "com.example.uiextensiondemo", parameters: { "result": 123456 } } }) }) } } .height('100%') } }
application-dev\application-models\uiextensionability.md
import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct Index { @State message: string = 'UIExtension User'; private myProxy: UIExtensionProxy | undefined = undefined; build() { Row() { Column() { Text(this.message) .fontSize(30) .size({ width: '100%', height: '50' }) .fontWeight(FontWeight.Bold) .textAlign(TextAlign.Center) UIExtensionComponent( { bundleName: 'com.example.uiextensiondemo', abilityName: 'UIExtensionProvider', moduleName: 'entry', parameters: { 'ability.want.params.uiExtensionType': 'sys/commonUI', } }) .onRemoteReady((proxy) => { this.myProxy = proxy; }) .onReceive((data) => { this.message = JSON.stringify(data); }) .onTerminated((terminateInfo: TerminationInfo) => { // This callback is triggered when the started UIExtensionAbility is terminated by calling terminateSelfWithResult or terminateSelf. // It returns the result of the UIExtensionAbility's normal exit, including the result code and Want data. this.message = `terminate code: ${terminateInfo.code}, want: ${terminateInfo.want}`; }) .onError((error: BusinessError) => { // This callback is invoked when an error occurs during the running of the started UIExtensionAbility. // It returns the error code and error message when the UIExtensionAbility encounters an exception. this.message = `error code: ${error.code}, error msg: ${error.message}`; }) .offset({ x: 0, y: 30 }) .size({ width: 300, height: 300 }) .border({ width: 5, color: 0x317AF7, radius: 10, style: BorderStyle.Dotted }) Button("sendData") .type(ButtonType.Capsule) .offset({ x: 0, y: 60 }) .width('80%') .type(ButtonType.Capsule) .margin({ top: 20 }) .onClick(() => { this.myProxy?.send({ "data": 123456, "message": "data from component" }) }) } .width('100%') } .height('100%') } }
application-dev\application-models\uiserviceextension-sys.md
import { common, UIServiceExtensionAbility, Want } from '@kit.AbilityKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; import { window } from '@kit.ArkUI'; export default class UIServiceExtAbility extends UIServiceExtensionAbility { // Create a UIServiceExtensionAbility. onCreate(want: Want) { hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate'); } // Callback for request processing. onRequest(want: Want, startId: number) { hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onRequest'); } // Callback invoked when a connection is set up. onConnect(want: Want, proxy: common.UIServiceHostProxy) { hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onConnect'); } // Callback invoked when a connection is interrupted. onDisconnect(want: Want, proxy: common.UIServiceHostProxy) { hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDisconnect'); } // Callback invoked when a window is about to create. onWindowWillCreate(config: window.ExtensionWindowConfig): void { hilog.info(0x0000, TestTag, '%{public}s', 'Ability onWindowWillCreate'); let rect: window.Rect = { left: 100, top: 100, width: 500, height: 500 }; config.windowRect = rect; // Create a subwindow. config.windowName = 'sub_window' config.windowAttribute = window.ExtensionWindowAttribute.SUB_WINDOW; config.windowRect = rect; config.subWindowOptions = { title: 'sub_window_title', decorEnabled: true, // Whether the window is a modal window. isModal: false } hilog.info(0x0000, TestTag, '%{public}s', 'Ability onWindowWillCreate end'); } // Callback invoked when a window is created. onWindowDidCreate(window: window.Window) { hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowDidCreate'); window.setUIContent('uiservice/page/WindowPage') window.showWindow() } // Callback invoked to receive data. onData(proxy: common.UIServiceHostProxy, data: Record<string, Object>) { hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onData'); } // Callback invoked to destroy the instance. onDestroy() { hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy'); } }
application-dev\application-models\uiserviceextension-sys.md
import { common, Want } from '@kit.AbilityKit'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct Index { build() { Column() { Row() { // Create a Start button. Button('start ability') .enabled(true) .onClick(() => { let context = this.getUIContext().getHostContext() as common.UIAbilityContext; let startWant: Want = { bundleName: 'com.acts.uiserviceextensionability', abilityName: 'UiServiceExtAbility', }; try { // Start the UIServiceExtensionAbility. context.startUIServiceExtensionAbility(startWant).then(() => { console.log('startUIServiceExtensionAbility success'); }).catch((error: BusinessError) => { console.log('startUIServiceExtensionAbility error', JSON.stringify(error)); }) } catch (err) { console.log('startUIServiceExtensionAbility failed', JSON.stringify(err)); } }) } } } }
application-dev\application-models\uiserviceextension-sys.md
import { common, Want } from '@kit.AbilityKit'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct Page_UIServiceExtensionAbility { @State uiServiceProxy: common.UIServiceProxy | null = null; build() { Column() { //... Row() { //... }.onClick(() => { const context = this.getUIContext().getHostContext() as common.UIAbilityContext; const want: Want = { deviceId: '', bundleName: 'com.example.myapplication', abilityName: '' }; // Define a callback. const callback: common.UIServiceExtensionConnectCallback = { onData: (data: Record<string, Object>): void => { console.log('onData:', JSON.stringify(data)); }, onDisconnect: (): void => { console.log('onDisconnect'); } }; // Connect to the UIServiceExtensionAbility. context.connectUIServiceExtensionAbility(want, callback).then((uiServiceProxy: common.UIServiceProxy) => { this.uiServiceProxy = uiServiceProxy; console.log('connectUIServiceExtensionAbility success'); }).catch((error: BusinessError) => { console.log('connectUIServiceExtensionAbility failed', JSON.stringify(error)); }) }) } } }
application-dev\application-models\uiserviceextension-sys.md
import { common } from '@kit.AbilityKit'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct Page_UIServiceExtensionAbility { @State uiServiceProxy: common.UIServiceProxy | null = null; build() { Column() { //... Row() { //... }.onClick(() => { const context = this.getUIContext().getHostContext() as common.UIAbilityContext; // this.uiServiceProxy is the proxy object saved during connection. context.disconnectUIServiceExtensionAbility(this.uiServiceProxy).then(() => { console.log('disconnectUIServiceExtensionAbility success'); }).catch((error: BusinessError) => { console.log('disconnectUIServiceExtensionAbility failed', JSON.stringify(error)); }) }) } } }
application-dev\application-models\uiserviceextension-sys.md
import { common, Want} from '@kit.AbilityKit'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct Index { comProxy: common.UIServiceProxy | null = null; connectCallback : common.UIServiceExtensionConnectCallback = { onData:(data: Record<string, Object>) => { console.log("received data", JSON.stringify(data)); }, onDisconnect:() => { console.log("onDisconnect"); } } build() { Column() { Row() { // Create a Connect button. Button("connect ability") .enabled(true) .onClick(() => { let context = this.getUIContext().getHostContext() as common.UIAbilityContext; let startWant:Want = { bundleName: 'com.acts.uiserviceextensionability', abilityName: 'UiServiceExtAbility', }; try { // Connect to the UIServiceExtensionAbility. context.connectUIServiceExtensionAbility(startWant, this.connectCallback).then((proxy: common.UIServiceProxy) => { this.comProxy = proxy; let formData: Record<string, string> = { 'test': 'test' }; try { this.comProxy.sendData(formData); } catch (err) { console.log('sendData failed', JSON.stringify(err)); }; }).catch((err: BusinessError) => { console.log("connectUIServiceExtensionAbility failed", JSON.stringify(err)); }); } catch(err) { console.log("connectUIServiceExtensionAbility failed", JSON.stringify(err)); } }) } } } }
application-dev\application-models\uiserviceextension-sys.md
import { common, Want, UIServiceExtensionAbility} from '@kit.AbilityKit'; import { window } from '@kit.ArkUI'; export default class MyServiceExtAbility extends UIServiceExtensionAbility { comProxy : common.UIServiceHostProxy | null = null; // Callback invoked when a UIServiceExtensionAbility is created. onCreate(want: Want) { console.log('UIServiceExtensionAbility onCreate'); } // Callback for request processing. onRequest(want: Want, startId: number) { console.log('UIServiceExtensionAbility onRequest'); } // Callback invoked when a connection is set up. onConnect(want: Want, proxy: common.UIServiceHostProxy) { console.log('UIServiceExtensionAbility onConnect'); this.comProxy = proxy; } // Callback invoked when a connection is interrupted. onDisconnect(want: Want, proxy: common.UIServiceHostProxy) { console.log('UIServiceExtensionAbility onDisconnect'); this.comProxy = null; } // Callback invoked to receive data. onData(proxy: common.UIServiceHostProxy, data: Record<string, Object>) { console.log('UIServiceExtensionAbility onData'); try { let formData: Record<string, string> = { 'Data' : 'reply message' }; proxy.sendData(formData); } catch (err) { console.log('sendData failed',JSON.stringify(err)); }; } onWindowWillCreate(extensionWindowConfig: window.ExtensionWindowConfig) { console.log('UIServiceExtensionAbility onWindowWillCreate'); } onWindowDidCreate(window: window.Window) { console.log('UIServiceExtensionAbility onWindowDidCreate'); } onDestroy() { console.log('UIServiceExtensionAbility onDestroy'); } }
application-dev\application-models\uiserviceextension.md
import { common, Want } from '@kit.AbilityKit'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct Index { build() { Column() { Row() { // Create a Start button. Button('start ability') .enabled(true) .onClick(() => { let context = this.getUIContext().getHostContext() as common.UIAbilityContext; let startWant: Want = { bundleName: 'com.acts.uiserviceextensionability', abilityName: 'UiServiceExtAbility', }; try { // Start the UIServiceExtensionAbility. context.startUIServiceExtensionAbility(startWant).then(() => { console.log('startUIServiceExtensionAbility success'); }).catch((error: BusinessError) => { console.log('startUIServiceExtensionAbility error', JSON.stringify(error)); }) } catch (err) { console.log('startUIServiceExtensionAbility failed', JSON.stringify(err)); } }) } } } }
application-dev\application-models\uiserviceextension.md
import { common, Want } from '@kit.AbilityKit'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct Index { comProxy: common.UIServiceProxy | null = null; connectCallback : common.UIServiceExtensionConnectCallback = { onData:(data: Record<string, Object>) => { console.log("received data", JSON.stringify(data)); }, onDisconnect:() => { console.log("onDisconnect "); } } build() { Column() { Row() { // Create a Connect button. Button("connect ability") .enabled(true) .onClick(() => { let context = this.getUIContext().getHostContext() as common.UIAbilityContext; let startWant:Want = { bundleName: 'com.acts.uiserviceextensionability', abilityName: 'UiServiceExtAbility', }; try { // Connect to the UIServiceExtensionAbility. context.connectUIServiceExtensionAbility(startWant, this.connectCallback).then((proxy: common.UIServiceProxy) => { this.comProxy = proxy; let formData: Record<string, string> = { 'test': 'test' }; try { this.comProxy.sendData(formData); } catch (err) { console.log('sendData failed', JSON.stringify(err)); }; }).catch((err: BusinessError) => { console.log("connectUIServiceExtensionAbility failed", JSON.stringify(err)); }); } catch(err) { console.log("connectUIServiceExtensionAbility failed", JSON.stringify(err)); }; }) } } } }
application-dev\application-models\want-overview.md
import { Want } from '@kit.AbilityKit'; let wantInfo: Want = { deviceId: '', // An empty deviceId indicates the local device. bundleName: 'com.example.myapplication', abilityName: 'FuncAbility', }
application-dev\application-models\want-overview.md
import { Want } from '@kit.AbilityKit'; let wantInfo: Want = { // Uncomment the line below if you want to implicitly query data only in the specific bundle. // bundleName: 'com.example.myapplication', action: 'ohos.want.action.search', // entities can be omitted. entities: [ 'entity.system.browsable' ], uri: 'https://www.test.com:8080/query/student', type: 'text/plain', };
application-dev\application-test\arkxtest-guidelines.md
import { describe, it, expect } from '@ohos/hypium'; import { abilityDelegatorRegistry } from '@kit.TestKit'; import { UIAbility, Want } from '@kit.AbilityKit'; const delegator = abilityDelegatorRegistry.getAbilityDelegator() const bundleName = abilityDelegatorRegistry.getArguments().bundleName; function sleep(time: number) { return new Promise<void>((resolve: Function) => setTimeout(resolve, time)); } export default function abilityTest() { describe('ActsAbilityTest', () =>{ it('testUiExample',0, async (done: Function) => { console.info("uitest: TestUiExample begin"); //start tested ability const want: Want = { bundleName: bundleName, abilityName: 'EntryAbility' } await delegator.startAbility(want); await sleep(1000); // Check the top display ability. const ability: UIAbility = await delegator.getCurrentTopAbility(); console.info("get top ability"); expect(ability.context.abilityInfo.name).assertEqual('EntryAbility'); done(); }) }) }
application-dev\application-test\arkxtest-guidelines.md
@Entry @Component struct Index { @State message: string = 'Hello World' build() { Row() { Column() { Text(this.message) .fontSize(50) .fontWeight(FontWeight.Bold) Text("Next") .fontSize(50) .margin({top:20}) .fontWeight(FontWeight.Bold) Text("after click") .fontSize(50) .margin({top:20}) .fontWeight(FontWeight.Bold) } .width('100%') } .height('100%') } }
application-dev\application-test\arkxtest-guidelines.md
import { describe, it, expect } from '@ohos/hypium'; // Import the test dependencies. import { abilityDelegatorRegistry, Driver, ON } from '@kit.TestKit'; import { UIAbility, Want } from '@kit.AbilityKit'; const delegator: abilityDelegatorRegistry.AbilityDelegator = abilityDelegatorRegistry.getAbilityDelegator() const bundleName = abilityDelegatorRegistry.getArguments().bundleName; function sleep(time: number) { return new Promise<void>((resolve: Function) => setTimeout(resolve, time)); } export default function abilityTest() { describe('ActsAbilityTest', () => { it('testUiExample',0, async (done: Function) => { console.info("uitest: TestUiExample begin"); //start tested ability const want: Want = { bundleName: bundleName, abilityName: 'EntryAbility' } await delegator.startAbility(want); await sleep(1000); // Check the top display ability. const ability: UIAbility = await delegator.getCurrentTopAbility(); console.info("get top ability"); expect(ability.context.abilityInfo.name).assertEqual('EntryAbility'); // UI test code // Initialize the driver. const driver = Driver.create(); await driver.delayMs(1000); // Find the button on text 'Next'. const button = await driver.findComponent(ON.text('Next')); // Click the button. await button.click(); await driver.delayMs(1000); // Check text. await driver.assertComponentExist(ON.text('after click')); await driver.pressBack(); done(); }) }) }
application-dev\arkts-utils\arkts-async-lock-introduction.md
import { ArkTSUtils, taskpool } from '@kit.ArkTS'; @Sendable export class A { private count_: number = 0; lock_: ArkTSUtils.locks.AsyncLock = new ArkTSUtils.locks.AsyncLock(); public async getCount(): Promise<number> { // Add an asynchronous lock to protect the data. return this.lock_.lockAsync(() => { return this.count_; }) } public async increaseCount() { // Add an asynchronous lock to protect the data. await this.lock_.lockAsync(() => { this.count_++; }) } } @Concurrent async function printCount(a: A) { console.info("InputModule: count is:" + await a.getCount()); } @Entry @Component struct Index { @State message: string = 'Hello World'; build() { RelativeContainer() { Text(this.message) .id('HelloWorld') .fontSize(50) .fontWeight(FontWeight.Bold) .alignRules({ center: { anchor: '__container__', align: VerticalAlign.Center }, middle: { anchor: '__container__', align: HorizontalAlign.Center } }) .onClick(async () => { // Create the Sendable object a. let a: A = new A(); // Pass object a to a child thread. await taskpool.execute(printCount, a); }) } .height('100%') .width('100%') } }
application-dev\arkts-utils\arkts-bytecode-function-name.md
##prefix#original_function_name
application-dev\arkts-utils\arkts-bytecode-function-name.md
<Scope tag 1><Scope name 1>[<Renaming index>]<Scope tag 2><Scope name 2><[Renaming index]>...<Scope tag n><Scope name n>[<Renaming index >]<Scope tag n+1>
application-dev\arkts-utils\arkts-bytecode-function-name.md
function longFuncName() { // The function name of longFuncName is "#*#longFuncName", where "longFuncName" is the original function name and will not be converted to an index. function A() { } // The function name of A is "#*@0*#A", where "@0" indicates the string whose index is 0 in the corresponding LiteralArray. In this case, the string is "longFuncName", which means that the original name of this function is "#*longFuncName*#A". function B() { } // The function name of B is "#*@0*#B". }
application-dev\arkts-utils\arkts-bytecode-function-name.md
namespace A { function bar() { } // The function name of bar is "#&A*#bar". } namespace A { function foo() { } // The function name of foo is "#&A^1*#foo", where "^1" indicates the renaming index. }
application-dev\arkts-utils\arkts-bytecode-function-name.md
function foo() {} // The original function name is "foo". () => { } // The original function name is "". () => { } // The original function name is "^1".
application-dev\arkts-utils\arkts-bytecode-function-name.md
let a = () => {} // The original function name is "a".
application-dev\arkts-utils\arkts-bytecode-function-name.md
let B = { b : () => {} // The original function name is "b". }
application-dev\arkts-utils\arkts-bytecode-function-name.md
let a = { "a.b#c^2": () => {} // The original function name is "". "x\\y#": () => {} // The original function name is "^1". }
application-dev\arkts-utils\arkts-bytecode-function-name.md
namespace A { // The function name of the namespace in bytecode is "#&#A". class B { // The function name of the constructor in bytecode is "#&A~B=#B". m() { // The function name of the function m in bytecode is "#&A~B>#m". return () => {} // The function name of the anonymous function in bytecode is "#&A~B>m*#". } static s() {} // The function name of the static function s in bytecode is "#&A~B<#s". } enum E { // The function name of the enum in bytecode is "#&A %#E". } }
application-dev\arkts-utils\arkts-bytecode-function-name.md
namespace LongNamespaceName { // The function name of the namespace in bytecode is "#&#LongNamespaceName". class LongClassName { // The function name of the constructor function in bytecode is "#&@1~@0=#LongClassName". longFunctionName() { // The function name of the instance function in bytecode is "#&@1~@0>#longFunctionName". } longFunctionName() { // The function name of the function in bytecode is "#&@1~@0>#longFunctionName^1". function inSecondFunction() {} // The function name of the function in bytecode is "#&@1~@0>@2^1*#inSecondFunction". } } }
application-dev\arkts-utils\arkts-bytecode-fundamentals.md
function foo(): number { return 1; }
application-dev\arkts-utils\arkts-bytecode-fundamentals.md
function foo(): void { a += 2; b = 5; }
application-dev\arkts-utils\arkts-bytecode-fundamentals.md
import { a, b } from "./module_foo" import * as c from "./module_bar" export let d: number = 3; a + b + d;
application-dev\arkts-utils\arkts-bytecode-fundamentals.md
function foo(): void { let a: number = 1; function bar(): number { return a; } }
application-dev\arkts-utils\arkts-bytecode-fundamentals.md
function bar(): void {} // Add a statement and compile the patch. function foo(): void { bar(); // Add a statement and compile the patch. }
application-dev\arkts-utils\arkts-bytecode-fundamentals.md
function foo(a: number, b: number): void {}
application-dev\arkts-utils\arkts-collections-introduction.md
import { ArkTSUtils, collections, taskpool } from '@kit.ArkTS'; @Concurrent async function add(arr: collections.Array<number>, lock: ArkTSUtils.locks.AsyncLock) { await lock.lockAsync(() => { // Without the asynchronous lock, the task will fail due to data race conflicts. arr[0]++; }) } @Entry @Component struct Index { @State message: string = 'Hello World'; build() { RelativeContainer() { Text(this.message) .id('HelloWorld') .fontSize(50) .fontWeight(FontWeight.Bold) .alignRules({ center: { anchor: '__container__', align: VerticalAlign.Center }, middle: { anchor: '__container__', align: HorizontalAlign.Center } }) .onClick(() => { let taskGroup = new taskpool.TaskGroup(); let lock = new ArkTSUtils.locks.AsyncLock(); let arr = collections.Array.create<number>(1, 0); let count = 1000; while (count--) { taskGroup.addTask(add, arr, lock); } taskpool.execute(taskGroup).then(() => { console.info(`Return success: ${arr[0]} === ${count}`); }).catch((e: Error) => { console.error("Return error."); }) }) } .height('100%') .width('100%') } }
application-dev\arkts-utils\arkts-condition-variable-introduction.md
import { ArkTSUtils, taskpool } from '@kit.ArkTS'; @Concurrent function notifyAll(conditionVariable: ArkTSUtils.locks.ConditionVariable) { conditionVariable.notifyAll(); } @Concurrent function notifyOne(conditionVariable: ArkTSUtils.locks.ConditionVariable) { conditionVariable.notifyOne(); } @Concurrent async function wait(conditionVariable: ArkTSUtils.locks.ConditionVariable) { await conditionVariable.wait().then(() => { console.log(`TaskPool Thread Wait: success`); }); } @Concurrent async function waitFor(conditionVariable: ArkTSUtils.locks.ConditionVariable) { await conditionVariable.waitFor(3000).then(() => { console.log(`TaskPool Thread WaitFor: success`); }); } @Entry @Component struct Index { @State message: string = 'Hello World'; build() { Row() { Column() { Text(this.message) .fontSize(50) .fontWeight(FontWeight.Bold) .onClick(() => { // Create a conditionVariable object. const conditionVariable: ArkTSUtils.locks.ConditionVariable = new ArkTSUtils.locks.ConditionVariable(); // Pass the conditionVariable object to the wait thread. taskpool.execute(wait, conditionVariable); // Pass the conditionVariable object to the notify thread to wake up the wait thread. The log information "TaskPool Thread Wait: success" is displayed. taskpool.execute(notifyAll, conditionVariable); // Pass the conditionVariable object to the waitFor thread. taskpool.execute(waitFor, conditionVariable); // Pass the conditionVariable object to the notifyOne thread to wake up the waitFor thread. The log information "TaskPool Thread WaitFor: success" is displayed. taskpool.execute(notifyOne, conditionVariable); // Create a conditionVariable object with a name. const conditionVariableRequest: ArkTSUtils.locks.ConditionVariable = ArkTSUtils.locks.ConditionVariable.request("Request1"); // Pass the conditionVariableRequest object to the wait thread. taskpool.execute(wait, conditionVariableRequest); // Pass the conditionVariableRequest object to the notify thread to wake up the wait thread. The log information "TaskPool Thread Wait: success" is displayed. taskpool.execute(notifyAll, conditionVariableRequest); // Pass the conditionVariableRequest object to the waitFor thread. taskpool.execute(waitFor, conditionVariableRequest); // Pass the conditionVariableRequest object to the notifyOne thread to wake up the waitFor thread. The log information "TaskPool Thread WaitFor: success" is displayed. taskpool.execute(notifyOne, conditionVariableRequest); }) } .width('100%') } .height('100%') } }
application-dev\arkts-utils\arkts-import-native-module.md
// index.d.ts corresponding to libentry.so export const add: (a: number, b: number) => number;
application-dev\arkts-utils\arkts-import-native-module.md
// test.ets import { add } from 'libentry.so' add(2, 3);
application-dev\arkts-utils\arkts-import-native-module.md
// index.d.ts corresponding to libentry.so export const add: (a: number, b: number) => number;
application-dev\arkts-utils\arkts-import-native-module.md
// test.ets import entry from 'libentry.so' entry.add(2, 3);
application-dev\arkts-utils\arkts-import-native-module.md
// index.d.ts corresponding to libentry.so export const add: (a: number, b: number) => number;
application-dev\arkts-utils\arkts-import-native-module.md
// test.ets import * as add from 'libentry.so' add.add(2, 3);
application-dev\arkts-utils\arkts-import-native-module.md
// test1.ets import hilog from '@ohos.hilog' export { hilog }
application-dev\arkts-utils\arkts-import-native-module.md
// test2.ets import { hilog } from './test1' hilog.info(0x000, 'testTag', '%{public}s', 'test');
application-dev\arkts-utils\arkts-import-native-module.md
// index.d.ts corresponding to libentry.so export const add: (a: number, b: number) => number;
application-dev\arkts-utils\arkts-import-native-module.md
// test1.ets export * from 'libentry.so'
application-dev\arkts-utils\arkts-import-native-module.md
// test2.ets import { add } from './test1' add(2, 3);
application-dev\arkts-utils\arkts-import-native-module.md
// test1.ets export * from 'libentry.so'
application-dev\arkts-utils\arkts-import-native-module.md
// test2.ets import * as add from './test1' // The add object cannot be obtained.
application-dev\arkts-utils\arkts-import-native-module.md
// index.d.ts corresponding to libentry.so export const add: (a: number, b: number) => number;
application-dev\arkts-utils\arkts-import-native-module.md
// test.ets import('libentry.so').then((ns:ESObject) => { ns.default.add(2, 3); })
application-dev\arkts-utils\arkts-import-native-module.md
// test1.ets import add from 'libentry.so' export { add } // test2.ets import('./test1').then((ns:ESObject) => { ns.add.add(2, 3); })
application-dev\arkts-utils\arkts-import-native-module.md
// test1.ets export * from 'libentry.so'
application-dev\arkts-utils\arkts-import-native-module.md
// test2.ets import('./test1').then((ns:ESObject) => { // The ns object cannot be obtained. })