harmony 鸿蒙@ohos.app.ability.UIAbility (UIAbility)
@ohos.app.ability.UIAbility (UIAbility)
UIAbility is an application component that has the UI. The UIAbility module, inherited from Ability, provides lifecycle callbacks such as component creation, destruction, and foreground/background switching. It also provides the following capabilities related to component collaboration:
- Caller: an object returned by startAbilityByCall. The CallerAbility (caller) uses this object to communicate with the CalleeAbility (callee).
- Callee: an internal object of UIAbility. The CalleeAbility (callee) uses this object to communicate with the CallerAbility (caller).
For details about the inheritance relationship of each ability, see Inheritance Relationship.
NOTE
The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
The APIs of this module can be used only in the stage model.
Modules to Import
import { UIAbility } from '@kit.AbilityKit';
Properties
System capability: SystemCapability.Ability.AbilityRuntime.AbilityCore
Name | Type | Read-only | Optional | Description |
---|---|---|---|---|
context | UIAbilityContext | No | No | Context of the UIAbility. Atomic service API: This API can be used in atomic services since API version 11. |
launchWant | Want | No | No | Parameters for starting the UIAbility. Atomic service API: This API can be used in atomic services since API version 11. |
lastRequestWant | Want | No | No | Latest Want received through onCreate or onNewWant when the UIAbility is started for multiple times. Atomic service API: This API can be used in atomic services since API version 11. |
callee | Callee | No | No | Object that invokes the stub service. |
UIAbility.onCreate
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void
Called to initialize the service logic when a UIAbility instance in the completely closed state is created. In other words, a UIAbility instance enters this lifecycle callback from a cold start. This API returns the result synchronously and does not support asynchronous callback.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Ability.AbilityRuntime.AbilityCore
Parameters
Name | Type | Mandatory | Description |
---|---|---|---|
want | Want | Yes | Want information, including the ability name and bundle name. |
launchParam | AbilityConstant.LaunchParam | Yes | Parameters for starting the UIAbility, and the reason for the last abnormal exit. |
Example
import { UIAbility, AbilityConstant, Want } from '@kit.AbilityKit';
class MyUIAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
console.log(`onCreate, want: ${want.abilityName}`);
}
}
UIAbility.onWindowStageCreate
onWindowStageCreate(windowStage: window.WindowStage): void
Called when a WindowStage is created for this UIAbility.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Ability.AbilityRuntime.AbilityCore
Parameters
Name | Type | Mandatory | Description |
---|---|---|---|
windowStage | window.WindowStage | Yes | WindowStage information. |
Example
import { UIAbility } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';
class MyUIAbility extends UIAbility {
onWindowStageCreate(windowStage: window.WindowStage) {
console.log('onWindowStageCreate');
}
}
UIAbility.onWindowStageWillDestroy12+
onWindowStageWillDestroy(windowStage: window.WindowStage): void
Called when the WindowStage is about to be destroyed.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Ability.AbilityRuntime.AbilityCore
Parameters
Name | Type | Mandatory | Description |
---|---|---|---|
windowStage | window.WindowStage | Yes | WindowStage information. |
Example
import { UIAbility } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';
class MyUIAbility extends UIAbility {
onWindowStageWillDestroy(windowStage: window.WindowStage) {
console.log('onWindowStageWillDestroy');
}
}
UIAbility.onWindowStageDestroy
onWindowStageDestroy(): void
Called when the WindowStage is destroyed for this UIAbility.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Ability.AbilityRuntime.AbilityCore
Example
import { UIAbility } from '@kit.AbilityKit';
class MyUIAbility extends UIAbility {
onWindowStageDestroy() {
console.log('onWindowStageDestroy');
}
}
UIAbility.onWindowStageRestore
onWindowStageRestore(windowStage: window.WindowStage): void
Called when the WindowStage is restored during the migration of this UIAbility, which is a multi-instance ability.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Ability.AbilityRuntime.AbilityCore
Parameters
Name | Type | Mandatory | Description |
---|---|---|---|
windowStage | window.WindowStage | Yes | WindowStage information. |
Example
import { UIAbility } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';
class MyUIAbility extends UIAbility {
onWindowStageRestore(windowStage: window.WindowStage) {
console.log('onWindowStageRestore');
}
}
UIAbility.onDestroy
onDestroy(): void|Promise<void>
Called to clear resources when this UIAbility is destroyed. This API returns the result synchronously or uses a promise to return the result.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Ability.AbilityRuntime.AbilityCore
Return value
Type | Description |
---|---|
void | Promise<void> | No return value or a Promise object that returns no result. |
Example
import { UIAbility } from '@kit.AbilityKit';
class MyUIAbility extends UIAbility {
onDestroy() {
console.log('onDestroy');
}
}
After the onDestroy() lifecycle callback is executed, the application may exit. Consequently, the asynchronous function (for example, asynchronously writing data to the database) in onDestroy() may fail to be executed. You can use the asynchronous lifecycle to ensure that the subsequent lifecycle continues only after the asynchronous function in onDestroy() finishes the execution.
import { UIAbility } from '@kit.AbilityKit';
class MyUIAbility extends UIAbility {
async onDestroy() {
console.log('onDestroy');
// Call the asynchronous function.
}
}
UIAbility.onWillForeground20+
onWillForeground(): void
Triggered just before the application transitions to the foreground. It is called before onForeground. It can be used to capture the moment when the application starts to transition to the foreground. When paired with onDidForeground, it can also measure the duration from the application’s initial foreground entry to its full transition into the foreground state.
This API returns the result synchronously and does not support asynchronous callback.
Atomic service API: This API can be used in atomic services since API version 20.
System capability: SystemCapability.Ability.AbilityRuntime.AbilityCore
Example
import { UIAbility } from '@kit.AbilityKit';
import { hiAppEvent, hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';
export default class EntryAbility extends UIAbility {
// ...
onWillForeground(): void {
// Start to log the event that the application starts moving to the foreground.
let eventParams: Record<string, number> = { 'xxxx': 100 };
let eventInfo: hiAppEvent.AppEventInfo = {
// Define the event domain.
domain: "lifecycle",
// Define the event name.
name: "onwillforeground",
// Define the event type.
eventType: hiAppEvent.EventType.BEHAVIOR,
// Define the event parameters.
params: eventParams,
};
hiAppEvent.write(eventInfo).then(() => {
hilog.info(0x0000, 'testTag', `HiAppEvent success to write event`);
}).catch((err: BusinessError) => {
hilog.error(0x0000, 'testTag', `HiAppEvent err.code: ${err.code}, err.message: ${err.message}`);
});
}
// ...
onDidForeground(): void {
// Start to log the event that the application fully transitions to the foreground.
let eventParams: Record<string, number> = { 'xxxx': 100 };
let eventInfo: hiAppEvent.AppEventInfo = {
// Define the event domain.
domain: "lifecycle",
// Define the event name.
name: "ondidforeground",
// Define the event type.
eventType: hiAppEvent.EventType.BEHAVIOR,
// Define the event parameters.
params: eventParams,
};
hiAppEvent.write(eventInfo).then(() => {
hilog.info(0x0000, 'testTag', `HiAppEvent success to write event`);
}).catch((err: BusinessError) => {
hilog.error(0x0000, 'testTag', `HiAppEvent err.code: ${err.code}, err.message: ${err.message}`);
});
}
}
UIAbility.onForeground
onForeground(): void
Triggered when the application transitions from the background to the foreground. It is called between onWillForeground and onDidForeground. It can be used to request system resources required, for example, requesting location services when the application transitions to the foreground.
This API returns the result synchronously and does not support asynchronous callback.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Ability.AbilityRuntime.AbilityCore
Example
import { UIAbility } from '@kit.AbilityKit';
class MyUIAbility extends UIAbility {
onForeground() {
console.log('onForeground');
}
}
UIAbility.onDidForeground20+
onDidForeground(): void
Triggered after the application has transitioned to the foreground. It is called after onForeground. It can be used to capture the moment when the application fully transitions to the foreground. When paired with onWillForeground, it can also measure the duration from the application’s initial foreground entry to its full transition into the foreground state.
This API returns the result synchronously and does not support asynchronous callback.
Atomic service API: This API can be used in atomic services since API version 20.
System capability: SystemCapability.Ability.AbilityRuntime.AbilityCore
Example
For details, see onWillForeground.
UIAbility.onWillBackground20+
onWillBackground(): void
Triggered just when the application transitions to the background. It is called before onBackground. It can be used to log various types of data, such as faults, statistics, security information, and user behavior that occur during application running.
This API returns the result synchronously and does not support asynchronous callback.
Atomic service API: This API can be used in atomic services since API version 20.
System capability: SystemCapability.Ability.AbilityRuntime.AbilityCore
Example
import { UIAbility } from '@kit.AbilityKit';
import { hiAppEvent, hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';
class MyUIAbility extends UIAbility {
onWillBackground(): void {
let eventParams: Record<string, number|string> = {
"int_data": 100,
"str_data": "strValue",
};
// Record the application fault information.
hiAppEvent.write({
domain: "test_domain",
name: "test_event",
eventType: hiAppEvent.EventType.FAULT,
params: eventParams,
}, (err: BusinessError) => {
if (err) {
hilog.error(0x0000, 'hiAppEvent', `code: ${err.code}, message: ${err.message}`);
return;
}
hilog.info(0x0000, 'hiAppEvent', `success to write event`);
});
}
}
UIAbility.onBackground
onBackground(): void
Triggered when the application transitions from the foreground to the background. It is called between onWillBackground and onDidBackground. It can be used to release resources when the UI is no longer visible, for example, stopping location services.
This API returns the result synchronously and does not support asynchronous callback.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Ability.AbilityRuntime.AbilityCore
Example
import { UIAbility } from '@kit.AbilityKit';
class MyUIAbility extends UIAbility {
onBackground() {
console.log('onBackground');
}
}
UIAbility.onDidBackground20+
onDidBackground(): void
Triggered after the application has transitioned to the background. It is called after onBackground. It can be used to release resources after the application has entered the background, for example, stopping audio playback.
This API returns the result synchronously and does not support asynchronous callback.
Atomic service API: This API can be used in atomic services since API version 20.
System capability: SystemCapability.Ability.AbilityRuntime.AbilityCore
Example
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { audio } from '@kit.AudioKit';
class MyUIAbility extends UIAbility {
static audioRenderer: audio.AudioRenderer;
// ...
onForeground(): void {
let audioStreamInfo: audio.AudioStreamInfo = {
samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000, // Sampling rate.
channels: audio.AudioChannel.CHANNEL_2, // Channel.
sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, // Sampling format.
encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW // Encoding format.
};
let audioRendererInfo: audio.AudioRendererInfo = {
usage: audio.StreamUsage.STREAM_USAGE_MUSIC, // Audio stream usage type: music. Set this parameter based on the service scenario.
rendererFlags: 0 // AudioRenderer flag.
};
let audioRendererOptions: audio.AudioRendererOptions = {
streamInfo: audioStreamInfo,
rendererInfo: audioRendererInfo
};
// Request an AudioRenderer in the foreground to play Pulse Code Modulation (PCM) audio data.
audio.createAudioRenderer(audioRendererOptions).then((data) => {
MyUIAbility.audioRenderer = data;
console.info(`AudioRenderer Created : Success : Stream Type: SUCCESS.`);
}).catch((err: BusinessError) => {
console.error(`AudioRenderer Created : F : ${JSON.stringify(err)}.`);
});
}
onDidBackground() {
// Release the AudioRenderer after transitioning to the background.
MyUIAbility.audioRenderer.release((err: BusinessError) => {
if (err) {
console.error(`AudioRenderer release failed, error: ${JSON.stringify(err)}.`);
} else {
console.info(`AudioRenderer released.`);
}
});
}
}
UIAbility.onContinue
onContinue(wantParam: Record<string, Object>): AbilityConstant.OnContinueResult|Promise<AbilityConstant.OnContinueResult>
Called to save data during the UIAbility migration preparation process.
NOTE
Since API version 12, UIAbility.onContinue supports the return value in the form of Promise<AbilityConstant.OnContinueResult>.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Ability.AbilityRuntime.AbilityCore
Parameters
Name | Type | Mandatory | Description |
---|---|---|---|
wantParam | Record<string, Object> | Yes | want parameter. |
Return value
Type | Description |
---|---|
AbilityConstant.OnContinueResult | Promise<AbilityConstant.OnContinueResult> | Continuation result or Promise used to return the continuation result. |
Example
import { UIAbility, AbilityConstant } from '@kit.AbilityKit';
class MyUIAbility extends UIAbility {
onContinue(wantParams: Record<string, Object>) {
console.log('onContinue');
wantParams['myData'] = 'my1234567';
return AbilityConstant.OnContinueResult.AGREE;
}
}
An asynchronous API can be used to save data during ability continuation.
import { UIAbility, AbilityConstant } from '@kit.AbilityKit';
class MyUIAbility extends UIAbility {
async setWant(wantParams: Record<string, Object>) {
console.log('setWant start');
for (let time = 0; time < 1000; ++time) {
wantParams[time] = time;
}
console.log('setWant end');
}
async onContinue(wantParams: Record<string, Object>) {
console.log('onContinue');
return this.setWant(wantParams).then(()=>{
return AbilityConstant.OnContinueResult.AGREE;
});
}
}
UIAbility.onNewWant
onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void
Called when a UIAbility instance that has undergone the following states is started again: started in the foreground, running in the foreground, and switched to the background. In other words, a UIAbility instance enters this lifecycle callback from a hot start.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Ability.AbilityRuntime.AbilityCore
Parameters
Name | Type | Mandatory | Description |
---|---|---|---|
want | Want | Yes | Want information, such as the ability name and bundle name. |
launchParam | AbilityConstant.LaunchParam | Yes | Reason for the UIAbility startup and the last abnormal exit. |
Example
import { UIAbility, AbilityConstant, Want } from '@kit.AbilityKit';
class MyUIAbility extends UIAbility {
onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam) {
console.log(`onNewWant, want: ${want.abilityName}`);
console.log(`onNewWant, launchParam: ${JSON.stringify(launchParam)}`);
}
}
UIAbility.onDump
onDump(params: Array<string>): Array<string>
Called to dump the client information. This API can be used to dump non-sensitive information.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Ability.AbilityRuntime.AbilityCore
Parameters
Name | Type | Mandatory | Description |
---|---|---|---|
params | Array<string> | Yes | Parameters in the form of a command. |
Return value
Type | Description |
---|---|
Array<string> | Dumped information array. |
Example
import { UIAbility } from '@kit.AbilityKit';
class MyUIAbility extends UIAbility {
onDump(params: Array<string>) {
console.log(`dump, params: ${JSON.stringify(params)}`);
return ['params'];
}
}
UIAbility.onSaveState
onSaveState(reason: AbilityConstant.StateType, wantParam: Record<string, Object>): AbilityConstant.OnSaveResult
Called when the framework automatically saves the UIAbility state in the case of an application fault. This API is used together with appRecovery. When an application is faulty, the framework calls onSaveState to save the status of the UIAbility if auto-save is enabled.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Ability.AbilityRuntime.AbilityCore
Parameters
Name | Type | Mandatory | Description |
---|---|---|---|
reason | AbilityConstant.StateType | Yes | Reason for triggering the callback to save the UIAbility state. |
wantParam | Record<string, Object> | Yes | want parameter. |
Return value
Type | Description |
---|---|
AbilityConstant.OnSaveResult | Whether the UIAbility state is saved. |
Example
import { UIAbility, AbilityConstant } from '@kit.AbilityKit';
class MyUIAbility extends UIAbility {
onSaveState(reason: AbilityConstant.StateType, wantParam: Record<string, Object>) {
console.log('onSaveState');
wantParam['myData'] = 'my1234567';
return AbilityConstant.OnSaveResult.RECOVERY_AGREE;
}
}
UIAbility.onShare10+
onShare(wantParam: Record<string, Object>): void
Called by this UIAbility to set data to share in the cross-device sharing scenario.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Ability.AbilityRuntime.AbilityCore
Parameters
Name | Type | Mandatory | Description |
---|---|---|---|
wantParam | Record<string, Object> | Yes | Data to share. |
Example
import { UIAbility } from '@kit.AbilityKit';
class MyUIAbility extends UIAbility {
onShare(wantParams: Record<string, Object>) {
console.log('onShare');
wantParams['ohos.extra.param.key.shareUrl'] = 'example.com';
}
}
UIAbility.onPrepareToTerminate10+
onPrepareToTerminate(): boolean
Called when this UIAbility is about to terminate. It allows for additional actions to be performed before the UIAbility is officially terminated. For example, you can prompt the user to confirm whether they want to terminate the UIAbility. If the user confirms, you can call terminateSelf to terminate it.
Currently, this API takes effect only on 2-in-1 devices.
NOTE
Since API version 15, this callback is not executed when UIAbility.onPrepareToTerminateAsync is implemented. When AbilityStage.onPrepareTerminationAsync or AbilityStage.onPrepareTermination is implemented, this callback is not executed if the user right-clicks the dock bar or system tray to close the UIAbility.
Required permissions: ohos.permission.PREPARE_APP_TERMINATE
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Ability.AbilityRuntime.AbilityCore
Return value
|Type|Description| |–|–| |boolean|Whether to terminate the UIAbility. The value true means that the termination process is canceled. The value false means to continue terminating the UIAbility.|
Example
import { UIAbility, Want } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
export default class EntryAbility extends UIAbility {
onPrepareToTerminate() {
// Define a pre-termination operation,
// for example, starting another UIAbility and performing asynchronous termination based on the startup result.
let want: Want = {
bundleName: "com.example.myapplication",
moduleName: "entry",
abilityName: "SecondAbility"
}
this.context.startAbilityForResult(want)
.then((result)=>{
// Obtain the startup result and terminate the current UIAbility when resultCode in the return value is 0.
console.log('startAbilityForResult success, resultCode is ' + result.resultCode);
if (result.resultCode === 0) {
this.context.terminateSelf();
}
}).catch((err: BusinessError)=>{
// Exception handling.
console.error('startAbilityForResult failed, err:' + JSON.stringify(err));
this.context.terminateSelf();
})
return true; // The pre-termination operation is defined. The value true means that the UIAbility termination process is canceled.
}
}
UIAbility.onPrepareToTerminateAsync15+
onPrepareToTerminateAsync(): Promise<boolean>
Called when this UIAbility is about to terminate. It allows for additional actions to be performed before the UIAbility is officially terminated. This API uses a promise to return the result. For example, you can prompt the user to confirm whether they want to terminate the UIAbility. If the user confirms, you can call terminateSelf to terminate it.
Currently, this API takes effect only on 2-in-1 devices.
NOTE
When AbilityStage.onPrepareTerminationAsync or AbilityStage.onPrepareTermination is implemented, this callback is not executed if the user right-clicks the dock bar or system tray to close the UIAbility.
If an asynchronous callback crashes, it will be handled as a timeout. If the UIAbility does not respond within 10 seconds, it will be terminated forcibly.
Required permissions: ohos.permission.PREPARE_APP_TERMINATE
Atomic service API: This API can be used in atomic services since API version 15.
System capability: SystemCapability.Ability.AbilityRuntime.AbilityCore
Return value
|Type|Description| |–|–| |Promise<boolean>|Promise used to return the result. The value true means that the termination process is canceled. The value false means to continue terminating the UIAbility.|
Example
import { UIAbility } from '@kit.AbilityKit';
export default class EntryAbility extends UIAbility {
async onPrepareToTerminateAsync(): Promise<boolean> {
await new Promise<boolean>((res, rej) => {
setTimeout (res, 2000); // Execute the operation 2 seconds later.
});
return true; // The pre-termination operation is defined. The value true means that the UIAbility termination process is canceled.
}
}
UIAbility.onBackPressed10+
onBackPressed(): boolean
Called when an operation of going back to the previous page is triggered on this UIAbility. The return value determines whether to destroy the UIAbility instance.
- When the target SDK version is earlier than 12, the default return value is false, indicating that the UIAbility will be destroyed.
- When the target SDK version is 12 or later, the default return value is true, indicating that the UIAbility will be moved to the background and will not be destroyed.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Ability.AbilityRuntime.AbilityCore
Return value
|Type|Description| |–|–| |boolean|The value true means that the UIAbility instance will be moved to the background and will not be destroyed, and false means that the UIAbility instance will be destroyed.|
Example
import { UIAbility } from '@kit.AbilityKit';
export default class EntryAbility extends UIAbility {
onBackPressed() {
return true;
}
}
UIAbility.onCollaborate18+
onCollaborate(wantParam: Record<string, Object>): AbilityConstant.CollaborateResult
Callback invoked to return the collaboration result in multi-device collaboration scenarios.
NOTE - This callback does not support ability launch in specified mode. - When you use methods such as startAbility() to start an application, you must include FLAG_ABILITY_ON_COLLABORATE in Flags in the Want object. - During a cold start, this callback must be invoked before onForeground or after onBackground. During a hot start, this callback must be invoked before onNewWant.
System capability: SystemCapability.Ability.AbilityRuntime.AbilityCore
Parameters
Name | Type | Mandatory | Description |
---|---|---|---|
wantParam | Record<string, Object> | Yes | Want parameter, which supports only the key “ohos.extra.param.key.supportCollaborateIndex”. The key can be used to obtain the data passed by the caller and perform corresponding processing. |
Return value
Name | Value | Description |
---|---|---|
AbilityConstant.CollaborateResult | Collaborator result, that is, whether the target application accepts the collaboration request. |
Example
import { UIAbility, AbilityConstant } from '@kit.AbilityKit';
class MyAbility extends UIAbility {
onCollaborate(wantParam: Record<string, Object>) {
return AbilityConstant.CollaborateResult.ACCEPT;
}
}
Caller
Implements sending of parcelable data to the target UIAbility when the CallerAbility invokes the target UIAbility (CalleeAbility).
Caller.call
call(method: string, data: rpc.Parcelable): Promise<void>
Sends parcelable data to the target UIAbility. This API uses a promise to return the result.
System capability: SystemCapability.Ability.AbilityRuntime.AbilityCore
Parameters
Name | Type | Mandatory | Description |
---|---|---|---|
method | string | Yes | Notification message string negotiated between the two UIAbilities. The message is used to instruct the callee to register a function to receive the parcelable data. |
data | rpc.Parcelable | Yes | Parcelable data. You need to customize the data. |
Return value
Type | Description |
---|---|
Promise<void> | Promise that returns no value. |
Error codes
For details about the error codes, see Universal Error Codes and Ability Error Codes.
ID | Error Message |
---|---|
401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
16200001 | Caller released. The caller has been released. |
16200002 | The callee does not exist. |
16000050 | Internal error. |
Example
import { UIAbility, Caller } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';
import { rpc } from '@kit.IPCKit';
import { BusinessError } from '@kit.BasicServicesKit';
class MyMessageAble implements rpc.Parcelable { // Custom parcelable data structure.
name: string
str: string
num: number = 1
constructor(name: string, str: string) {
this.name = name;
this.str = str;
}
marshalling(messageSequence: rpc.MessageSequence) {
messageSequence.writeInt(this.num);
messageSequence.writeString(this.str);
console.log(`MyMessageAble marshalling num[${this.num}] str[${this.str}]`);
return true;
}
unmarshalling(messageSequence: rpc.MessageSequence) {
this.num = messageSequence.readInt();
this.str = messageSequence.readString();
console.log(`MyMessageAble unmarshalling num[${this.num}] str[${this.str}]`);
return true;
}
};
let method = 'call_Function'; // Notification message string negotiated by the two UIAbilities.
let caller: Caller;
export default class MainUIAbility extends UIAbility {
onWindowStageCreate(windowStage: window.WindowStage) {
this.context.startAbilityByCall({
bundleName: 'com.example.myservice',
abilityName: 'MainUIAbility',
deviceId: ''
}).then((obj) => {
caller = obj;
let msg = new MyMessageAble('msg', 'world'); // See the definition of Parcelable.
caller.call(method, msg)
.then(() => {
console.log('Caller call() called');
})
.catch((callErr: BusinessError) => {
console.error(`Caller.call catch error, error.code: ${callErr.code}, error.message: ${callErr.message}`);
});
}).catch((err: BusinessError) => {
console.error(`Caller GetCaller error, error.code: ${err.code}, error.message: ${err.message}`);
});
}
}
Caller.callWithResult
callWithResult(method: string, data: rpc.Parcelable): Promise<rpc.MessageSequence>
Sends parcelable data to the target UIAbility and obtains the parcelable data returned by the target UIAbility. This API uses a promise to return the result.
System capability: SystemCapability.Ability.AbilityRuntime.AbilityCore
Parameters
Name | Type | Mandatory | Description |
---|---|---|---|
method | string | Yes | Notification message string negotiated between the two UIAbilities. The message is used to instruct the callee to register a function to receive the parcelable data. |
data | rpc.Parcelable | Yes | Parcelable data. You need to customize the data. |
Return value
Type | Description |
---|---|
Promise<rpc.MessageSequence> | Promise used to return the parcelable data from the target UIAbility. |
Error codes
For details about the error codes, see Universal Error Codes and Ability Error Codes.
ID | Error Message |
---|---|
401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
16200001 | Caller released. The caller has been released. |
16200002 | The callee does not exist. |
16000050 | Internal error. |
Example
import { UIAbility, Caller } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';
import { rpc } from '@kit.IPCKit';
import { BusinessError } from '@kit.BasicServicesKit';
class MyMessageAble implements rpc.Parcelable {
name: string
str: string
num: number = 1
constructor(name: string, str: string) {
this.name = name;
this.str = str;
}
marshalling(messageSequence: rpc.MessageSequence) {
messageSequence.writeInt(this.num);
messageSequence.writeString(this.str);
console.log(`MyMessageAble marshalling num[${this.num}] str[${this.str}]`);
return true;
}
unmarshalling(messageSequence: rpc.MessageSequence) {
this.num = messageSequence.readInt();
this.str = messageSequence.readString();
console.log(`MyMessageAble unmarshalling num[${this.num}] str[${this.str}]`);
return true;
}
};
let method = 'call_Function';
let caller: Caller;
export default class MainUIAbility extends UIAbility {
onWindowStageCreate(windowStage: window.WindowStage) {
this.context.startAbilityByCall({
bundleName: 'com.example.myservice',
abilityName: 'MainUIAbility',
deviceId: ''
}).then((obj) => {
caller = obj;
let msg = new MyMessageAble('msg', 'world');
caller.callWithResult(method, msg)
.then((data) => {
console.log('Caller callWithResult() called');
let retmsg = new MyMessageAble('msg', 'world');
data.readParcelable(retmsg);
})
.catch((callErr: BusinessError) => {
console.error(`Caller.callWithResult catch error, error.code: ${callErr.code}, error.message: ${callErr.message}`);
});
}).catch((err: BusinessError) => {
console.error(`Caller GetCaller error, error.code: ${err.code}, error.message: ${err.message}`);
});
}
}
Caller.release
release(): void
Releases the caller interface of the target UIAbility.
System capability: SystemCapability.Ability.AbilityRuntime.AbilityCore
Error codes
For details about the error codes, see Ability Error Codes.
ID | Error Message |
---|---|
16200001 | Caller released. The caller has been released. |
16200002 | The callee does not exist. |
Example
import { UIAbility, Caller } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';
let caller: Caller;
export default class MainUIAbility extends UIAbility {
onWindowStageCreate(windowStage: window.WindowStage) {
this.context.startAbilityByCall({
bundleName: 'com.example.myservice',
abilityName: 'MainUIAbility',
deviceId: ''
}).then((obj) => {
caller = obj;
try {
caller.release();
} catch (releaseErr) {
console.error(`Caller.release catch error, error.code: ${releaseErr.code}, error.message: ${releaseErr.message}`);
}
}).catch((err: BusinessError) => {
console.error(`Caller GetCaller error, error.code: ${err.code}, error.message: ${err.message}`);
});
}
}
Caller.onRelease
onRelease(callback: OnReleaseCallback): void
Called when the stub on the target UIAbility is disconnected. This API uses an asynchronous callback to return the result.
System capability: SystemCapability.Ability.AbilityRuntime.AbilityCore
Parameters
Name | Type | Mandatory | Description |
---|---|---|---|
callback | OnReleaseCallback | Yes | Callback used to return the result. |
Error codes
For details about the error codes, see Universal Error Codes and Ability Error Codes.
ID | Error Message |
---|---|
401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
16200001 | Caller released. The caller has been released. |
Example
import { UIAbility, Caller } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';
let caller: Caller;
export default class MainUIAbility extends UIAbility {
onWindowStageCreate(windowStage: window.WindowStage) {
this.context.startAbilityByCall({
bundleName: 'com.example.myservice',
abilityName: 'MainUIAbility',
deviceId: ''
}).then((obj) => {
caller = obj;
try {
caller.onRelease((str) => {
console.log(`Caller OnRelease CallBack is called ${str}`);
});
} catch (error) {
console.error(`Caller.onRelease catch error, error.code: $error.code}, error.message: ${error.message}`);
}
}).catch((err: BusinessError) => {
console.error(`Caller GetCaller error, error.code: ${err.code}, error.message: ${err.message}`);
});
}
}
Caller.onRemoteStateChange10+
onRemoteStateChange(callback: OnRemoteStateChangeCallback): void
Called when the remote UIAbility state changes in the collaboration scenario. This API uses an asynchronous callback to return the result.
System capability: SystemCapability.Ability.AbilityRuntime.AbilityCore
Parameters
Name | Type | Mandatory | Description |
---|---|---|---|
callback | OnRemoteStateChangeCallback | Yes | Callback used to return the result. |
Error codes
For details about the error codes, see Universal Error Codes and Ability Error Codes.
ID | Error Message |
---|---|
401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
16200001 | Caller released. The caller has been released. |
Example
import { UIAbility, Caller } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';
let caller: Caller;
let dstDeviceId: string;
export default class MainAbility extends UIAbility {
onWindowStageCreate(windowStage: window.WindowStage) {
this.context.startAbilityByCall({
bundleName: 'com.example.myservice',
abilityName: 'MainUIAbility',
deviceId: dstDeviceId
}).then((obj) => {
caller = obj;
try {
caller.onRemoteStateChange((str) => {
console.log('Remote state changed ' + str);
});
} catch (error) {
console.error(`Caller.onRemoteStateChange catch error, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}`);
}
}).catch((err: BusinessError) => {
console.error(`Caller GetCaller error, error.code: ${JSON.stringify(err.code)}, error.message: ${JSON.stringify(err.message)}`);
})
}
}
Caller.on(‘release’)
on(type: ‘release’, callback: OnReleaseCallback): void
Called when the stub on the target UIAbility is disconnected. This API uses an asynchronous callback to return the result.
System capability: SystemCapability.Ability.AbilityRuntime.AbilityCore
Parameters
Name | Type | Mandatory | Description |
---|---|---|---|
type | string | Yes | Event type. The value is fixed at ‘release’. |
callback | OnReleaseCallback | Yes | Callback used to return the result. |
Error codes
For details about the error codes, see Universal Error Codes and Ability Error Codes.
ID | Error Message |
---|---|
401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
16200001 | Caller released. The caller has been released. |
Example
import { UIAbility, Caller } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';
let caller: Caller;
export default class MainUIAbility extends UIAbility {
onWindowStageCreate(windowStage: window.WindowStage) {
this.context.startAbilityByCall({
bundleName: 'com.example.myservice',
abilityName: 'MainUIAbility',
deviceId: ''
}).then((obj) => {
caller = obj;
try {
caller.on('release', (str) => {
console.log(`Caller OnRelease CallBack is called ${str}`);
});
} catch (error) {
console.error(`Caller.on catch error, error.code: ${error.code}, error.message: ${error.message}`);
}
}).catch((err: BusinessError) => {
console.error(`Caller GetCaller error, error.code: ${err.code}, error.message: ${err.message}`);
});
}
}
Caller.off(‘release’)
off(type: ‘release’, callback: OnReleaseCallback): void
Unregisters a callback that is invoked when the stub on the target UIAbility is disconnected. This capability is reserved. This API uses an asynchronous callback to return the result.
System capability: SystemCapability.Ability.AbilityRuntime.AbilityCore
Parameters
Name | Type | Mandatory | Description |
---|---|---|---|
type | string | Yes | Event type. The value is fixed at ‘release’. |
callback | OnReleaseCallback | Yes | Callback used to return the result. |
Error codes
For details about the error codes, see Universal Error Codes.
ID | Error Message |
---|---|
401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
Example
import { UIAbility, Caller, OnReleaseCallback } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';
let caller: Caller;
export default class MainUIAbility extends UIAbility {
onWindowStageCreate(windowStage: window.WindowStage) {
this.context.startAbilityByCall({
bundleName: 'com.example.myservice',
abilityName: 'MainUIAbility',
deviceId: ''
}).then((obj) => {
caller = obj;
try {
let onReleaseCallBack: OnReleaseCallback = (str) => {
console.log(`Caller OnRelease CallBack is called ${str}`);
};
caller.on('release', onReleaseCallBack);
caller.off('release', onReleaseCallBack);
} catch (error) {
console.error(`Caller.on or Caller.off catch error, error.code: ${error.code}, error.message: ${error.message}`);
}
}).catch((err: BusinessError) => {
console.error(`Caller GetCaller error, error.code: ${err.code}, error.message: ${err.message}`);
});
}
}
Caller.off(‘release’)
off(type: ‘release’): void
Unregisters a callback that is invoked when the stub on the target UIAbility is disconnected. This capability is reserved.
System capability: SystemCapability.Ability.AbilityRuntime.AbilityCore
Parameters
Name | Type | Mandatory | Description |
---|---|---|---|
type | string | Yes | Event type. The value is fixed at ‘release’. |
Error codes
For details about the error codes, see Universal Error Codes.
ID | Error Message |
---|---|
401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
Example
import { UIAbility, Caller, OnReleaseCallback } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';
let caller: Caller;
export default class MainUIAbility extends UIAbility {
onWindowStageCreate(windowStage: window.WindowStage) {
this.context.startAbilityByCall({
bundleName: 'com.example.myservice',
abilityName: 'MainUIAbility',
deviceId: ''
}).then((obj) => {
caller = obj;
try {
let onReleaseCallBack: OnReleaseCallback = (str) => {
console.log(`Caller OnRelease CallBack is called ${str}`);
};
caller.on('release', onReleaseCallBack);
caller.off('release');
} catch (error) {
console.error(`Caller.on or Caller.off catch error, error.code: ${error.code}, error.message: ${error.message}`);
}
}).catch((err: BusinessError) => {
console.error(`Caller GetCaller error, error.code: ${err.code}, error.message: ${err.message}`);
});
}
}
Callee
Implements callbacks for caller notification registration and deregistration.
Callee.on
on(method: string, callback: CalleeCallback): void
Registers a caller notification callback, which is invoked when the target UIAbility registers a function.
System capability: SystemCapability.Ability.AbilityRuntime.AbilityCore
Parameters
Name | Type | Mandatory | Description |
---|---|---|---|
method | string | Yes | Notification message string negotiated between the two UIAbilities. |
callback | CalleeCallback | Yes | JS notification synchronization callback of the rpc.MessageSequence type. The callback must return at least one empty rpc.Parcelable object. Otherwise, the function execution fails. |
Error codes
For details about the error codes, see Universal Error Codes and Ability Error Codes.
ID | Error Message |
---|---|
401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
16200004 | The method has been registered. |
16000050 | Internal error. |
Example
import { UIAbility, AbilityConstant, Want } from '@kit.AbilityKit';
import { rpc } from '@kit.IPCKit';
class MyMessageAble implements rpc.Parcelable {
name: string
str: string
num: number = 1
constructor(name: string, str: string) {
this.name = name;
this.str = str;
}
marshalling(messageSequence: rpc.MessageSequence) {
messageSequence.writeInt(this.num);
messageSequence.writeString(this.str);
console.log(`MyMessageAble marshalling num[${this.num}] str[${this.str}]`);
return true;
}
unmarshalling(messageSequence: rpc.MessageSequence) {
this.num = messageSequence.readInt();
this.str = messageSequence.readString();
console.log(`MyMessageAble unmarshalling num[${this.num}] str[${this.str}]`);
return true;
}
};
let method = 'call_Function';
function funcCallBack(pdata: rpc.MessageSequence) {
console.log(`Callee funcCallBack is called ${pdata}`);
let msg = new MyMessageAble('test', '');
pdata.readParcelable(msg);
return new MyMessageAble('test1', 'Callee test');
}
export default class MainUIAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
console.log('Callee onCreate is called');
try {
this.callee.on(method, funcCallBack);
} catch (error) {
console.error(`Callee.on catch error, error.code: ${error.code}, error.message: ${error.message}`);
}
}
}
Callee.off
off(method: string): void
Unregisters a caller notification callback, which is invoked when the target UIAbility registers a function.
System capability: SystemCapability.Ability.AbilityRuntime.AbilityCore
Parameters
Name | Type | Mandatory | Description |
---|---|---|---|
method | string | Yes | Registered notification message string. |
Error codes
For details about the error codes, see Universal Error Codes and Ability Error Codes.
ID | Error Message |
---|---|
401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
16200005 | The method has not been registered. |
16000050 | Internal error. |
Example
import { UIAbility, AbilityConstant, Want } from '@kit.AbilityKit';
let method = 'call_Function';
export default class MainUIAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
console.log('Callee onCreate is called');
try {
this.callee.off(method);
} catch (error) {
console.error(`Callee.off catch error, error.code: ${error.code}, error.message: ${error.message}`);
}
}
}
OnReleaseCallback
(msg: string)
(msg: string): void
Defines the callback that is invoked when the stub on the target UIAbility is disconnected.
System capability: SystemCapability.Ability.AbilityRuntime.AbilityCore
Parameters
Name | Type | Mandatory | Description |
---|---|---|---|
msg | string | Yes | Message used for disconnection. |
OnRemoteStateChangeCallback10+
(msg: string)
(msg: string): void
Defines the callback that is invoked when the remote UIAbility state changes in the collaboration scenario.
System capability: SystemCapability.Ability.AbilityRuntime.AbilityCore
Parameters
Name | Type | Mandatory | Description |
---|---|---|---|
msg | string | Yes | Message used for disconnection. |
CalleeCallback
(indata: rpc.MessageSequence)
(indata: rpc.MessageSequence): rpc.Parcelable
Defines the callback of the registration message notification of the UIAbility.
System capability: SystemCapability.Ability.AbilityRuntime.AbilityCore
Parameters
Name | Type | Mandatory | Description |
---|---|---|---|
indata | rpc.MessageSequence | Yes | Data to be transferred. |
Return value
Type | Description |
---|---|
rpc.Parcelable | Returned data object. |
你可能感兴趣的鸿蒙文章
harmony 鸿蒙AbilityAccessControl
harmony 鸿蒙OH_NativeBundle_ApplicationInfo
harmony 鸿蒙OH_NativeBundle_ElementName
- 所属分类: 后端技术
- 本文标签:
热门推荐
-
2、 - 优质文章
-
3、 gate.io
-
8、 golang
-
9、 openharmony
-
10、 Vue中input框自动聚焦