UIAbilityContext provides the context environment for a UIAbility. It inherits from Context. For details about the relationships and differences between various types of contexts, see Context.
When a UIAbility component is instantiated, the system automatically creates the corresponding UIAbilityContext. You can use the APIs provided by UIAbilityContext to obtain the ability information (AbilityInfo), application information (ApplicationInfo), and other information, start another UIAbility, connect to system services, and destroy a UIAbility.
System capability: SystemCapability.Ability.AbilityRuntime.Core
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| abilityInfo | AbilityInfo | No | No | UIAbility information. Atomic service API: This API can be used in atomic services since API version 11. |
| currentHapModuleInfo | HapModuleInfo | No | No | Information about the HAP to which the UIAbility belongs. Atomic service API: This API can be used in atomic services since API version 11. |
| config | Configuration | No | No | Environment variables for the application runtime, such as language and color mode. Atomic service API: This API can be used in atomic services since API version 11. |
| windowStage12+ | window.WindowStage | No | No | WindowStage object. It can be called only on the main thread. Atomic service API: This API can be used in atomic services since API version 12. |
startAbility(want: Want, callback: AsyncCallback<void>): void
Starts a UIAbility. This API uses an asynchronous callback to return the result. It can be called only on the main thread.
For details about the startup rules for the components in the stage model, see Component Startup Rules (Stage Model).
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Ability.AbilityRuntime.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| want | Want | Yes | Mandatory information for starting the UIAbility. |
| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the API call is successful, code in err is 0 and message is an empty string. Otherwise, err contains the corresponding error code and error information. |
Error codes
For details about the error codes, see Universal Error Codes and Ability Error Codes.
| ID | Error Message |
|---|---|
| 201 | The application does not have permission to call the interface. Applicable version: 10+ |
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
| 16000001 | The specified ability does not exist. |
| 16000002 | Incorrect ability type. |
| 16000004 | Cannot start an invisible component. |
| 16000005 | The specified process does not have the permission. |
| 16000006 | Cross-user operations are not allowed. |
| 16000008 | The crowdtesting application expires. |
| 16000009 | An ability cannot be started or stopped in Wukong mode. |
| 16000010 | The call with the continuation and prepare continuation flag is forbidden. |
| 16000011 | The context does not exist. |
| 16000012 | The application is controlled. Applicable version: 10+ |
| 16000013 | The application is controlled by EDM. Applicable version: 10+ |
| 16000018 | Redirection to a third-party application is not allowed in API version greater than 11. Applicable version: 12+ |
| 16000019 | No matching ability is found. Applicable version: 12+ |
| 16000050 | Internal error. |
| 16000053 | The ability is not on the top of the UI. |
| 16000055 | Installation-free timed out. |
| 16000071 | App clone is not supported. Applicable Version: 14+ |
| 16000072 | App clone or multi-instance is not supported. Applicable Version: 14+ |
| 16000073 | The app clone index is invalid. Applicable version: 12+ |
| 16000076 | The app instance key is invalid. Applicable Version: 14+ |
| 16000077 | The number of app instances reaches the limit. Applicable Version: 14+ |
| 16000078 | The multi-instance is not supported. Applicable Version: 14+ |
| 16000079 | The APP_INSTANCE_KEY cannot be specified. Applicable Version: 14+ |
| 16000080 | Creating a new instance is not supported. Applicable Version: 14+ |
| 16200001 | The caller has been released. |
Example
import { UIAbility, Want } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
export default class EntryAbility extends UIAbility {
onForeground() {
let want: Want = {
bundleName: 'com.example.myapplication',
abilityName: 'EntryAbility'
};
try {
this.context.startAbility(want, (err: BusinessError) => {
if (err.code) {
// Process service logic errors.
console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`);
return;
}
// Carry out normal service processing.
console.info('startAbility succeed');
});
} catch (err) {
// Process input parameter errors.
let code = (err as BusinessError).code;
let message = (err as BusinessError).message;
console.error(`startAbility failed, code is ${code}, message is ${message}`);
}
}
} startAbility(want: Want, options: StartOptions, callback: AsyncCallback<void>): void
Starts a UIAbility. This API uses an asynchronous callback to return the result. It can be called only on the main thread.
For details about the startup rules for the components in the stage model, see Component Startup Rules (Stage Model).
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Ability.AbilityRuntime.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| want | Want | Yes | Mandatory information for starting the UIAbility. |
| options | StartOptions | Yes | Parameters used for starting the UIAbility. |
| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the API call is successful, code in err is 0 and message is an empty string. Otherwise, err contains the corresponding error code and error information. |
Error codes
For details about the error codes, see Universal Error Codes and Ability Error Codes.
| ID | Error Message |
|---|---|
| 201 | The application does not have permission to call the interface. Applicable version: 10+ |
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
| 801 | Capability not support. Applicable version: 12+ |
| 16000001 | The specified ability does not exist. |
| 16000002 | Incorrect ability type. Applicable version: 9 |
| 16000004 | Cannot start an invisible component. |
| 16000005 | The specified process does not have the permission. |
| 16000006 | Cross-user operations are not allowed. |
| 16000008 | The crowdtesting application expires. |
| 16000009 | An ability cannot be started or stopped in Wukong mode. |
| 16000010 | The call with the continuation and prepare continuation flag is forbidden. Applicable version: 9 |
| 16000011 | The context does not exist. |
| 16000012 | The application is controlled. Applicable version: 10+ |
| 16000013 | The application is controlled by EDM. Applicable version: 10+ |
| 16000018 | Redirection to a third-party application is not allowed in API version greater than 11. Applicable version: 12+ |
| 16000019 | No matching ability is found. Applicable version: 12+ |
| 16000050 | Internal error. |
| 16000053 | The ability is not on the top of the UI. |
| 16000055 | Installation-free timed out. |
| 16000067 | The StartOptions check failed. Applicable version: 12+ |
| 16000068 | The ability is already running. Applicable version: 12+ |
| 16300003 | The target application is not the current application. Applicable version: 12+ |
| 16000071 | App clone is not supported. Applicable Version: 14+ |
| 16000072 | App clone or multi-instance is not supported. Applicable Version: 14+ |
| 16000073 | The app clone index is invalid. Applicable version: 12+ |
| 16000076 | The app instance key is invalid. Applicable Version: 14+ |
| 16000077 | The number of app instances reaches the limit. Applicable Version: 14+ |
| 16000078 | The multi-instance is not supported. Applicable Version: 14+ |
| 16000079 | The APP_INSTANCE_KEY cannot be specified. Applicable Version: 14+ |
| 16000080 | Creating a new instance is not supported. Applicable Version: 14+ |
| 16200001 | The caller has been released. |
Example
import { UIAbility, Want, StartOptions } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
export default class EntryAbility extends UIAbility {
onForeground() {
let want: Want = {
deviceId: '',
bundleName: 'com.example.myapplication',
abilityName: 'EntryAbility'
};
let options: StartOptions = {
displayId: 0
};
try {
this.context.startAbility(want, options, (err: BusinessError) => {
if (err.code) {
// Process service logic errors.
console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`);
return;
}
// Carry out normal service processing.
console.info('startAbility succeed');
});
} catch (err) {
// Process input parameter errors.
let code = (err as BusinessError).code;
let message = (err as BusinessError).message;
console.error(`startAbility failed, code is ${code}, message is ${message}`);
}
}
} startAbility(want: Want, options?: StartOptions): Promise<void>
Starts a UIAbility. This API uses a promise to return the result. It can be called only on the main thread.
For details about the startup rules for the components in the stage model, see Component Startup Rules (Stage Model).
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Ability.AbilityRuntime.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| want | Want | Yes | Mandatory information for starting the UIAbility. |
| options | StartOptions | No | Parameters used for starting the UIAbility. |
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 |
|---|---|
| 201 | The application does not have permission to call the interface. Applicable version: 10+ |
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
| 801 | Capability not support. Applicable version: 12+ |
| 16000001 | The specified ability does not exist. |
| 16000002 | Incorrect ability type. |
| 16000004 | Cannot start an invisible component. |
| 16000005 | The specified process does not have the permission. |
| 16000006 | Cross-user operations are not allowed. |
| 16000008 | The crowdtesting application expires. |
| 16000009 | An ability cannot be started or stopped in Wukong mode. |
| 16000010 | The call with the continuation and prepare continuation flag is forbidden. |
| 16000011 | The context does not exist. |
| 16000012 | The application is controlled. Applicable version: 10+ |
| 16000013 | The application is controlled by EDM. Applicable version: 10+ |
| 16000018 | Redirection to a third-party application is not allowed in API version greater than 11. Applicable version: 12+ |
| 16000019 | No matching ability is found. Applicable version: 12+ |
| 16000050 | Internal error. |
| 16000053 | The ability is not on the top of the UI. |
| 16000055 | Installation-free timed out. |
| 16000067 | The StartOptions check failed. Applicable version: 12+ |
| 16000068 | The ability is already running. Applicable version: 12+ |
| 16300003 | The target application is not the current application. Applicable version: 12+ |
| 16000071 | App clone is not supported. Applicable Version: 14+ |
| 16000072 | App clone or multi-instance is not supported. Applicable Version: 14+ |
| 16000073 | The app clone index is invalid. Applicable version: 12+ |
| 16000076 | The app instance key is invalid. Applicable Version: 14+ |
| 16000077 | The number of app instances reaches the limit. Applicable Version: 14+ |
| 16000078 | The multi-instance is not supported. Applicable Version: 14+ |
| 16000079 | The APP_INSTANCE_KEY cannot be specified. Applicable Version: 14+ |
| 16000080 | Creating a new instance is not supported. Applicable Version: 14+ |
| 16200001 | The caller has been released. |
Example
import { UIAbility, Want, StartOptions } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
export default class EntryAbility extends UIAbility {
onForeground() {
let want: Want = {
bundleName: 'com.example.myapplication',
abilityName: 'EntryAbility'
};
let options: StartOptions = {
displayId: 0
};
try {
this.context.startAbility(want, options)
.then(() => {
// Carry out normal service processing.
console.info('startAbility succeed');
})
.catch((err: BusinessError) => {
// Process service logic errors.
console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`);
});
} catch (err) {
// Process input parameter errors.
let code = (err as BusinessError).code;
let message = (err as BusinessError).message;
console.error(`startAbility failed, code is ${code}, message is ${message}`);
}
}
} startAbilityForResult(want: Want, callback: AsyncCallback<AbilityResult>): void
Starts a UIAbility and returns the exit result of the launched UIAbility via a callback. This API uses an asynchronous callback to return the result. It can be called only on the main thread.
The following situations may be possible for a started UIAbility:
For details about the startup rules for the components in the stage model, see Component Startup Rules (Stage Model).
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Ability.AbilityRuntime.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| want | Want | Yes | Mandatory information for starting the UIAbility. |
| callback | AsyncCallback<AbilityResult> | Yes | Callback used to return the result. If the API call is successful, code in err is 0 and data is the result code and data when the UIAbility exits. Otherwise, err contains the corresponding error code and error information. |
Error codes
For details about the error codes, see Universal Error Codes and Ability Error Codes.
| ID | Error Message |
|---|---|
| 201 | The application does not have permission to call the interface. Applicable version: 10+ |
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
| 16000001 | The specified ability does not exist. |
| 16000002 | Incorrect ability type. |
| 16000004 | Cannot start an invisible component. |
| 16000005 | The specified process does not have the permission. |
| 16000006 | Cross-user operations are not allowed. |
| 16000008 | The crowdtesting application expires. |
| 16000009 | An ability cannot be started or stopped in Wukong mode. |
| 16000010 | The call with the continuation and prepare continuation flag is forbidden. |
| 16000011 | The context does not exist. |
| 16000012 | The application is controlled. Applicable version: 10+ |
| 16000013 | The application is controlled by EDM. Applicable version: 10+ |
| 16000018 | Redirection to a third-party application is not allowed in API version greater than 11. Applicable version: 12+ |
| 16000019 | No matching ability is found. Applicable version: 12+ |
| 16000050 | Internal error. |
| 16000053 | The ability is not on the top of the UI. |
| 16000055 | Installation-free timed out. |
| 16000071 | App clone is not supported. Applicable Version: 14+ |
| 16000072 | App clone or multi-instance is not supported. Applicable Version: 14+ |
| 16000073 | The app clone index is invalid. Applicable version: 12+ |
| 16000076 | The app instance key is invalid. Applicable Version: 14+ |
| 16000077 | The number of app instances reaches the limit. Applicable Version: 14+ |
| 16000078 | The multi-instance is not supported. Applicable Version: 14+ |
| 16000079 | The APP_INSTANCE_KEY cannot be specified. Applicable Version: 14+ |
| 16000080 | Creating a new instance is not supported. Applicable Version: 14+ |
| 16200001 | The caller has been released. |
Example
import { UIAbility, Want, common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
export default class EntryAbility extends UIAbility {
onForeground() {
let want: Want = {
deviceId: '',
bundleName: 'com.example.myapplication',
abilityName: 'EntryAbility'
};
try {
this.context.startAbilityForResult(want, (err: BusinessError, result: common.AbilityResult) => {
if (err.code) {
// Process service logic errors.
console.error(`startAbilityForResult failed, code is ${err.code}, message is ${err.message}`);
return;
}
// Carry out normal service processing.
console.info('startAbilityForResult succeed');
});
} catch (err) {
// Process input parameter errors.
let code = (err as BusinessError).code;
let message = (err as BusinessError).message;
console.error(`startAbilityForResult failed, code is ${code}, message is ${message}`);
}
}
} startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback<AbilityResult>): void
Starts a UIAbility and returns the exit result of the launched UIAbility via a callback. This API uses an asynchronous callback to return the result. It can be called only on the main thread.
The following situations may be possible for a started UIAbility:
For details about the startup rules for the components in the stage model, see Component Startup Rules (Stage Model).
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Ability.AbilityRuntime.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| want | Want | Yes | Mandatory information for starting the UIAbility. |
| options | StartOptions | Yes | Parameters used for starting the UIAbility. |
| callback | AsyncCallback<AbilityResult> | Yes | Callback used to return the result. If the API call is successful, code in err is 0 and data is the result code and data when the UIAbility exits. Otherwise, err contains the corresponding error code and error information. |
Error codes
For details about the error codes, see Universal Error Codes and Ability Error Codes.
| ID | Error Message |
|---|---|
| 201 | The application does not have permission to call the interface. Applicable version: 10+ |
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
| 16000001 | The specified ability does not exist. |
| 16000002 | Incorrect ability type. Applicable version: 9 |
| 16000004 | Cannot start an invisible component. |
| 16000005 | The specified process does not have the permission. |
| 16000006 | Cross-user operations are not allowed. |
| 16000008 | The crowdtesting application expires. |
| 16000009 | An ability cannot be started or stopped in Wukong mode. |
| 16000010 | The call with the continuation and prepare continuation flag is forbidden. Applicable version: 9 |
| 16000011 | The context does not exist. |
| 16000012 | The application is controlled. Applicable version: 10+ |
| 16000013 | The application is controlled by EDM. Applicable version: 10+ |
| 16000018 | Redirection to a third-party application is not allowed in API version greater than 11. Applicable version: 12+ |
| 16000019 | No matching ability is found. Applicable version: 12+ |
| 16000050 | Internal error. |
| 16000053 | The ability is not on the top of the UI. |
| 16000055 | Installation-free timed out. |
| 16000071 | App clone is not supported. Applicable Version: 14+ |
| 16000072 | App clone or multi-instance is not supported. Applicable Version: 14+ |
| 16000073 | The app clone index is invalid. Applicable version: 12+ |
| 16000076 | The app instance key is invalid. Applicable Version: 14+ |
| 16000077 | The number of app instances reaches the limit. Applicable Version: 14+ |
| 16000078 | The multi-instance is not supported. Applicable Version: 14+ |
| 16000079 | The APP_INSTANCE_KEY cannot be specified. Applicable Version: 14+ |
| 16000080 | Creating a new instance is not supported. Applicable Version: 14+ |
| 16200001 | The caller has been released. |
Example
import { UIAbility, Want, common, StartOptions } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
export default class EntryAbility extends UIAbility {
onForeground() {
let want: Want = {
deviceId: '',
bundleName: 'com.example.myapplication',
abilityName: 'EntryAbility'
};
let options: StartOptions = {
displayId: 0
};
try {
this.context.startAbilityForResult(want, options, (err: BusinessError, result: common.AbilityResult) => {
if (err.code) {
// Process service logic errors.
console.error(`startAbilityForResult failed, code is ${err.code}, message is ${err.message}`);
return;
}
// Carry out normal service processing.
console.info('startAbilityForResult succeed');
});
} catch (err) {
// Process input parameter errors.
let code = (err as BusinessError).code;
let message = (err as BusinessError).message;
console.error(`startAbilityForResult failed, code is ${code}, message is ${message}`);
}
}
} startAbilityForResult(want: Want, options?: StartOptions): Promise<AbilityResult>
Starts a UIAbility and returns the exit result of the launched UIAbility via a callback. This API uses a promise to return the result. It can be called only on the main thread.
The following situations may be possible for a started UIAbility:
For details about the startup rules for the components in the stage model, see Component Startup Rules (Stage Model).
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Ability.AbilityRuntime.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| want | Want | Yes | Mandatory information for starting the UIAbility. |
| options | StartOptions | No | Parameters used for starting the UIAbility. |
Return value
| Type | Description |
|---|---|
| Promise<AbilityResult> | Promise used to return the result. |
Error codes
For details about the error codes, see Universal Error Codes and Ability Error Codes.
| ID | Error Message |
|---|---|
| 201 | The application does not have permission to call the interface. Applicable version: 10+ |
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
| 16000001 | The specified ability does not exist. |
| 16000002 | Incorrect ability type. |
| 16000004 | Cannot start an invisible component. |
| 16000005 | The specified process does not have the permission. |
| 16000006 | Cross-user operations are not allowed. |
| 16000008 | The crowdtesting application expires. |
| 16000009 | An ability cannot be started or stopped in Wukong mode. |
| 16000010 | The call with the continuation and prepare continuation flag is forbidden. |
| 16000011 | The context does not exist. |
| 16000012 | The application is controlled. Applicable version: 10+ |
| 16000013 | The application is controlled by EDM. Applicable version: 10+ |
| 16000018 | Redirection to a third-party application is not allowed in API version greater than 11. Applicable version: 12+ |
| 16000019 | No matching ability is found. Applicable version: 12+ |
| 16000050 | Internal error. |
| 16000053 | The ability is not on the top of the UI. |
| 16000055 | Installation-free timed out. |
| 16000071 | App clone is not supported. Applicable Version: 14+ |
| 16000072 | App clone or multi-instance is not supported. Applicable Version: 14+ |
| 16000073 | The app clone index is invalid. Applicable version: 12+ |
| 16000076 | The app instance key is invalid. Applicable Version: 14+ |
| 16000077 | The number of app instances reaches the limit. Applicable Version: 14+ |
| 16000078 | The multi-instance is not supported. Applicable Version: 14+ |
| 16000079 | The APP_INSTANCE_KEY cannot be specified. Applicable Version: 14+ |
| 16000080 | Creating a new instance is not supported. Applicable Version: 14+ |
| 16200001 | The caller has been released. |
Example
import { UIAbility, Want, common, StartOptions } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
export default class EntryAbility extends UIAbility {
onForeground() {
let want: Want = {
bundleName: 'com.example.myapplication',
abilityName: 'EntryAbility'
};
let options: StartOptions = {
displayId: 0
};
try {
this.context.startAbilityForResult(want, options)
.then((result: common.AbilityResult) => {
// Carry out normal service processing.
console.info('startAbilityForResult succeed');
})
.catch((err: BusinessError) => {
// Process service logic errors.
console.error(`startAbilityForResult failed, code is ${err.code}, message is ${err.message}`);
});
} catch (err) {
// Process input parameter errors.
let code = (err as BusinessError).code;
let message = (err as BusinessError).message;
console.error(`startAbilityForResult failed, code is ${code}, message is ${message}`);
}
}
} terminateSelf(callback: AsyncCallback<void>): void
Terminates this UIAbility. This API uses an asynchronous callback to return the result. It can be called only on the main thread.
After this API is called, missions in the task center are not cleared by default. To clear missions, set removeMissionAfterTerminate to true.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Ability.AbilityRuntime.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the API call is successful, code in err is 0. Otherwise, err contains the corresponding error code and error information. |
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. |
| 16000005 | The specified process does not have the permission. Applicable version: 9 |
| 16000004 | Cannot start an invisible component. Applicable version: 9 |
| 16000001 | The specified ability does not exist. Applicable version: 9 |
| 16000009 | An ability cannot be started or stopped in Wukong mode. |
| 16000011 | The context does not exist. |
| 16000050 | Internal error. |
Example
The following is an example of calling terminateSelf to terminate a UIAbility. By default, the application retains the snapshot in the recent tasks list.
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
export default class EntryAbility extends UIAbility {
onForeground() {
try {
this.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}`);
}
}
} (Optional) To remove the mission from the task center (that is, not to retain the snapshot in the recent tasks list) when terminating the UIAbility, set the removeMissionAfterTerminate field to true in the module.json5 file.
{
"module": {
// ...
"abilities": [
{
// ...
"removeMissionAfterTerminate": true
}
]
}
} terminateSelf(): Promise<void>
Terminates this UIAbility. This API uses a promise to return the result. It can be called only on the main thread.
After this API is called, missions in the task center are not cleared by default. To clear missions, set removeMissionAfterTerminate to true.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Ability.AbilityRuntime.Core
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Error codes
For details about the error codes, see Ability Error Codes.
| ID | Error Message |
|---|---|
| 16000005 | The specified process does not have the permission. Applicable version: 9 |
| 16000004 | Cannot start an invisible component. Applicable version: 9 |
| 16000001 | The specified ability does not exist. Applicable version: 9 |
| 16000009 | An ability cannot be started or stopped in Wukong mode. |
| 16000011 | The context does not exist. |
| 16000050 | Internal error. |
Example
The following is an example of calling terminateSelf to terminate a UIAbility. By default, the application retains the snapshot in the recent tasks list.
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
export default class EntryAbility extends UIAbility {
onForeground() {
try {
this.context.terminateSelf()
.then(() => {
// Carry out normal service processing.
console.info('terminateSelf succeed');
})
.catch((err: BusinessError) => {
// Process service logic errors.
console.error(`terminateSelf failed, code is ${err.code}, message is ${err.message}`);
});
} 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}`);
}
}
} (Optional) To remove the mission from the task center (that is, not to retain the snapshot in the recent tasks list) when terminating the UIAbility, set the removeMissionAfterTerminate field to true in the module.json5 file.
{
"module": {
// ...
"abilities": [
{
// ...
"removeMissionAfterTerminate": true
}
]
}
} terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback<void>): void
Terminates this UIAbility. This API uses an asynchronous callback to return the result. It can be called only on the main thread.
The result is returned to the caller when terminateSelfWithResult is called to terminate the UIAbility that is started by calling startAbilityForResult.
After this API is called, missions in the task center are not cleared by default. To clear missions, set removeMissionAfterTerminate to true.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Ability.AbilityRuntime.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| parameter | AbilityResult | Yes | Information returned to the caller. |
| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the API call is successful, code in err is 0. Otherwise, err contains the corresponding error code and error information. |
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. |
| 16000005 | The specified process does not have the permission. Applicable version: 9 |
| 16000004 | Cannot start an invisible component. Applicable version: 9 |
| 16000001 | The specified ability does not exist. Applicable version: 9 |
| 16000009 | An ability cannot be started or stopped in Wukong mode. |
| 16000011 | The context does not exist. |
| 16000050 | Internal error. |
Example
import { UIAbility, Want, common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
export default class EntryAbility extends UIAbility {
onForeground() {
let want: Want = {
bundleName: 'com.example.myapplication',
abilityName: 'EntryAbility'
};
let resultCode = 100;
// AbilityResult information returned to the caller.
let abilityResult: common.AbilityResult = {
want,
resultCode
};
try {
this.context.terminateSelfWithResult(abilityResult, (err: BusinessError) => {
if (err.code) {
// Process service logic errors.
console.error(`terminateSelfWithResult failed, code is ${err.code}, message is ${err.message}`);
return;
}
// Carry out normal service processing.
console.info('terminateSelfWithResult succeed');
});
} catch (err) {
// Process input parameter errors.
let code = (err as BusinessError).code;
let message = (err as BusinessError).message;
console.error(`terminateSelfWithResult failed, code is ${code}, message is ${message}`);
}
}
} terminateSelfWithResult(parameter: AbilityResult): Promise<void>
Terminates this UIAbility. This API uses a promise to return the result. It can be called only on the main thread.
The result is returned to the caller when terminateSelfWithResult is called to terminate the UIAbility that is started by calling startAbilityForResult.
After this API is called, missions in the task center are not cleared by default. To clear missions, set removeMissionAfterTerminate to true.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Ability.AbilityRuntime.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| parameter | AbilityResult | Yes | Information returned to the caller. |
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. |
| 16000005 | The specified process does not have the permission. Applicable version: 9 |
| 16000004 | Cannot start an invisible component. Applicable version: 9 |
| 16000001 | The specified ability does not exist. Applicable version: 9 |
| 16000009 | An ability cannot be started or stopped in Wukong mode. |
| 16000011 | The context does not exist. |
| 16000050 | Internal error. |
Example
import { UIAbility, Want, common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
export default class EntryAbility extends UIAbility {
onForeground() {
let want: Want = {
bundleName: 'com.example.myapplication',
abilityName: 'EntryAbility'
};
let resultCode = 100;
// AbilityResult information returned to the caller.
let abilityResult: common.AbilityResult = {
want,
resultCode
};
try {
this.context.terminateSelfWithResult(abilityResult)
.then(() => {
// Carry out normal service processing.
console.info('terminateSelfWithResult succeed');
})
.catch((err: BusinessError) => {
// Process service logic errors.
console.error(`terminateSelfWithResult failed, code is ${err.code}, message is ${err.message}`);
});
} catch (err) {
// Process input parameter errors.
let code = (err as BusinessError).code;
let message = (err as BusinessError).message;
console.error(`terminateSelfWithResult failed, code is ${code}, message is ${message}`);
}
}
} connectServiceExtensionAbility(want: Want, options: ConnectOptions): number
Connects this UIAbility to a ServiceExtensionAbility. It enables communication with the ServiceExtensionAbility via a proxy, allowing access to the capabilities exposed by the ServiceExtensionAbility. It can be called only on the main thread.
For details about the startup rules for the components in the stage model, see Component Startup Rules (Stage Model).
System capability: SystemCapability.Ability.AbilityRuntime.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| want | Want | Yes | Want information for connecting to the ServiceExtensionAbility. |
| options | ConnectOptions | Yes | Callback used to return the information indicating that the connection is successful, failed, or interrupted. |
Return value
| Type | Description |
|---|---|
| number | Connection ID. A caller can call disconnectServiceExtensionAbility with this ID for disconnection. |
Error codes
For details about the error codes, see Universal Error Codes and Ability Error Codes.
| ID | Error Message |
|---|---|
| 201 | The application does not have permission to call the interface. |
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
| 16000001 | The specified ability does not exist. |
| 16000002 | Incorrect ability type. Applicable version: 10+ |
| 16000004 | Cannot start an invisible component. Applicable version: 10+ |
| 16000005 | The specified process does not have the permission. |
| 16000006 | Cross-user operations are not allowed. Applicable version: 10+ |
| 16000008 | The crowdtesting application expires. Applicable version: 10+ |
| 16000011 | The context does not exist. |
| 16000012 | The application is controlled. Applicable version: 10+ |
| 16000013 | The application is controlled by EDM. Applicable version: 10+ |
| 16000050 | Internal error. |
| 16000053 | The ability is not on the top of the UI. Applicable version: 10+ |
| 16000055 | Installation-free timed out. Applicable version: 10+ |
Example
import { UIAbility, Want, common } from '@kit.AbilityKit';
import { rpc } from '@kit.IPCKit';
import { BusinessError } from '@kit.BasicServicesKit';
export default class EntryAbility extends UIAbility {
onForeground() {
let want: Want = {
deviceId: '',
bundleName: 'com.example.myapplication',
abilityName: 'ServiceExtensionAbility'
};
let commRemote: rpc.IRemoteObject;
let options: common.ConnectOptions = {
onConnect(elementName, remote) {
commRemote = remote;
console.info('onConnect...');
},
onDisconnect(elementName) {
console.info('onDisconnect...');
},
onFailed(code) {
console.info('onFailed...');
}
};
let connection: number;
try {
connection = this.context.connectServiceExtensionAbility(want, options);
} catch (err) {
// Process input parameter errors.
let code = (err as BusinessError).code;
let message = (err as BusinessError).message;
console.error(`connectServiceExtensionAbility failed, code is ${code}, message is ${message}`);
}
}
} disconnectServiceExtensionAbility(connection: number): Promise<void>
Disconnects from a ServiceExtensionAbility. Once the connection is terminated, set the remote object, which is returned when the connection is established, to null. This API uses a promise to return the result. It can be called only on the main thread.
System capability: SystemCapability.Ability.AbilityRuntime.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| connection | number | Yes | ID of the connected ServiceExtensionAbility, that is, connectionId returned by connectServiceExtensionAbility. |
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. |
| 16000011 | The context does not exist. |
| 16000050 | Internal error. |
Example
import { UIAbility } from '@kit.AbilityKit';
import { rpc } from '@kit.IPCKit';
import { BusinessError } from '@kit.BasicServicesKit';
export default class EntryAbility extends UIAbility {
onForeground() {
// connection is the return value of connectServiceExtensionAbility.
let connection = 1;
let commRemote: rpc.IRemoteObject | null;
try {
this.context.disconnectServiceExtensionAbility(connection).then(() => {
commRemote = null;
// Carry out normal service processing.
console.info('disconnectServiceExtensionAbility succeed');
}).catch((err: BusinessError) => {
// Process service logic errors.
console.error(`disconnectServiceExtensionAbility failed, code is ${err.code}, message is ${err.message}`);
});
} catch (err) {
commRemote = null;
// Process input parameter errors.
let code = (err as BusinessError).code;
let message = (err as BusinessError).message;
console.error(`disconnectServiceExtensionAbility failed, code is ${code}, message is ${message}`);
}
}
} disconnectServiceExtensionAbility(connection: number, callback: AsyncCallback<void>): void
Disconnects from a ServiceExtensionAbility. Once the connection is terminated, set the remote object, which is returned when the connection is established, to null. This API uses an asynchronous callback to return the result. It can be called only on the main thread.
System capability: SystemCapability.Ability.AbilityRuntime.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| connection | number | Yes | ID of the connected ServiceExtensionAbility, that is, connectionId returned by connectServiceExtensionAbility. |
| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the API call is successful, err is undefined. Otherwise, err is an error object. |
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. |
| 16000011 | The context does not exist. |
| 16000050 | Internal error. |
Example
import { UIAbility } from '@kit.AbilityKit';
import { rpc } from '@kit.IPCKit';
import { BusinessError } from '@kit.BasicServicesKit';
export default class EntryAbility extends UIAbility {
onForeground() {
// connection is the return value of connectServiceExtensionAbility.
let connection = 1;
let commRemote: rpc.IRemoteObject | null;
try {
this.context.disconnectServiceExtensionAbility(connection, (err: BusinessError) => {
commRemote = null;
if (err.code) {
// Process service logic errors.
console.error(`disconnectServiceExtensionAbility failed, code is ${err.code}, message is ${err.message}`);
return;
}
// Carry out normal service processing.
console.info('disconnectServiceExtensionAbility succeed');
});
} catch (err) {
commRemote = null;
// Process input parameter errors.
let code = (err as BusinessError).code;
let message = (err as BusinessError).message;
console.error(`disconnectServiceExtensionAbility failed, code is ${code}, message is ${message}`);
}
}
} startAbilityByCall(want: Want): Promise<Caller>
Obtains a Caller object for communicating with a Callee object. If the specified UIAbility is not started, the UIAbility will be started in the foreground or background. This API uses a promise to return the result. It can be called only on the main thread.
This API cannot be used to start the UIAbility with the launch type set to specified.
In cross-device scenarios, the caller and the callee must belong to the same application.
In same-device scenarios, the caller and the callee must belong to different applications, and the caller must have the ohos.permission.ABILITY_BACKGROUND_COMMUNICATION permission (available only for system applications).
In addition, if the application needs to call this API in the background, the ohos.permission.START_ABILITIES_FROM_BACKGROUND permission is required (available only for system applications). For details about the startup rules for the components in the stage model, see Component Startup Rules (Stage Model).
Required permissions: ohos.permission.DISTRIBUTED_DATASYNC
For API version 10 and earlier, the permission ohos.permission.ABILITY_BACKGROUND_COMMUNICATION is required. This permission is available only to system applications.
For API version 11 and later, only the permission ohos.permission.DISTRIBUTED_DATASYNC is required. This permission is verified by the DSoftBus subsystem only when the link between applications is established. No verification is conducted during the application launch phase.
System capability: SystemCapability.Ability.AbilityRuntime.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| want | Want | Yes | Information about the UIAbility to start, including the ability name, module name, bundle name, device ID, and parameters (optional). If 'ohos.aafwk.param.callAbilityToForeground' in parameters is set to true, the UIAbility is brought to the foreground. Otherwise, the UIAbility is brought to the background. |
Return value
| Type | Description |
|---|---|
| Promise<Caller> | Promise used to return the Caller object. |
Error codes
For details about the error codes, see Universal Error Codes and Ability Error Codes.
| ID | Error Message |
|---|---|
| 201 | The application does not have permission to call the interface. |
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
| 16000001 | The specified ability does not exist. |
| 16000002 | Incorrect ability type. |
| 16000004 | Cannot start an invisible component. |
| 16000005 | The specified process does not have the permission. Applicable version: 9 |
| 16000006 | Cross-user operations are not allowed. |
| 16000008 | The crowdtesting application expires. |
| 16000011 | The context does not exist. |
| 16000012 | The application is controlled. Applicable version: 10+ |
| 16000013 | The application is controlled by EDM. Applicable version: 10+ |
| 16000018 | Redirection to a third-party application is not allowed in API version greater than 11. Applicable version: 12+ |
| 16000050 | Internal error. Possible causes: 1.Connect to system service failed. 2.Sending restart message to system service failed. 3.System service failed to communicate with dependency module. 4.Non-system applications are only allowed to call this interface across devices, not on the current device. |
| 16000071 | App clone is not supported. Applicable Version: 14+ |
| 16000072 | App clone or multi-instance is not supported. Applicable Version: 14+ |
| 16000073 | The app clone index is invalid. Applicable version: 12+ |
| 16000076 | The app instance key is invalid. Applicable Version: 14+ |
| 16000077 | The number of app instances reaches the limit. Applicable Version: 14+ |
| 16000078 | The multi-instance is not supported. Applicable Version: 14+ |
| 16000079 | The APP_INSTANCE_KEY cannot be specified. Applicable Version: 14+ |
| 16200001 | The caller has been released. Applicable version: 9 |
| 16000080 | Creating a new instance is not supported. Applicable Version: 14+ |
Example
The following code demonstrates that the caller launches the callee to the background, sends a message to the callee after successfully obtaining the Caller object, and then releases the Caller object.
import { Caller, UIAbility, Want } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { rpc } from '@kit.IPCKit';
const DOMAIN = 0x0000;
const LOG_TAG = 'TEST_TAG';
class TestParcelable implements rpc.Parcelable {
age: number = 0;
name: string = '';
marshalling(dataOut: rpc.MessageSequence): boolean {
dataOut.writeInt(this.age);
dataOut.writeString(this.name);
return true;
}
unmarshalling(dataIn: rpc.MessageSequence): boolean {
this.age = dataIn.readInt();
this.name = dataIn.readString();
return true;
}
}
export default class EntryAbility extends UIAbility {
async onForeground() {
let caller: Caller;
// Start the ability in the background.
let wantBackground: Want = {
bundleName: 'com.example.myapplication',
abilityName: 'EntryAbility',
};
try {
caller = await this.context.startAbilityByCall(wantBackground);
await caller.call('TEST_CALL', new TestParcelable());
caller.release();
} catch (err) {
// Process input parameter errors.
hilog.error(DOMAIN, LOG_TAG, `startAbilityByCall failed ${err}`);
}
}
} The following code demonstrates that the callee registers a listener after being launched and unregisters the listener when destroyed.
import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { rpc } from '@kit.IPCKit';
const DOMAIN = 0x0000;
const LOG_TAG = 'TEST_TAG';
class TestParcelable implements rpc.Parcelable {
age: number = 0;
name: string = '';
marshalling(dataOut: rpc.MessageSequence): boolean {
dataOut.writeInt(this.age);
dataOut.writeString(this.name);
return true;
}
unmarshalling(dataIn: rpc.MessageSequence): boolean {
this.age = dataIn.readInt();
this.name = dataIn.readString();
return true;
}
}
export default class EntryAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
hilog.info(DOMAIN, LOG_TAG, '%{public}s', 'Ability onCreate');
// Register a listener.
this.callee.on('TEST_CALL', (data: rpc.MessageSequence) => {
let recv = new TestParcelable();
data.readParcelable(recv);
recv.age++;
return recv;
});
}
onDestroy(): void {
hilog.info(DOMAIN, LOG_TAG, '%{public}s', 'Ability onDestroy');
// Unregisters the listener.
this.callee.off('TEST_CALL');
}
} The following code demonstrates the scenario where the caller launches the callee to the foreground.
import { Caller, UIAbility, Want } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
const DOMAIN = 0x0000;
const LOG_TAG = 'TEST_TAG';
export default class EntryAbility extends UIAbility {
async onForeground() {
let caller: Caller;
// Launch the UIAbility to the foreground and set 'ohos.aafwk.param.callAbilityToForeground' in parameters to true.
let wantForeground: Want = {
bundleName: 'com.example.myapplication',
abilityName: 'EntryAbility',
parameters: {
'ohos.aafwk.param.callAbilityToForeground': true
}
};
try {
caller = await this.context.startAbilityByCall(wantForeground);
caller.release();
} catch (err) {
// Process input parameter errors.
hilog.error(DOMAIN, LOG_TAG, `startAbilityByCall failed ${err}`);
}
}
} setMissionLabel(label: string, callback: AsyncCallback<void>): void
Sets a mission label for this UIAbility on the multitasking screen. This API uses an asynchronous callback to return the result.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Ability.AbilityRuntime.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| label | string | Yes | Mission label. |
| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the API call is successful, code in err is 0. Otherwise, err contains the corresponding error code and error information. |
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. |
| 16000011 | The context does not exist. |
| 16000050 | Internal error. |
Example
import { UIAbility, AbilityConstant, Want } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
export default class EntryAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
this.context.setMissionLabel('test', (result: BusinessError) => {
console.info(`setMissionLabel: ${JSON.stringify(result)}`);
});
}
} setMissionLabel(label: string): Promise<void>
Sets a mission label for this UIAbility on the multitasking screen. This API 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.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| label | string | Yes | Mission label. |
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. |
| 16000011 | The context does not exist. |
| 16000050 | Internal error. |
Example
import { UIAbility, AbilityConstant, Want } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
export default class EntryAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
this.context.setMissionLabel('test').then(() => {
console.info('success');
}).catch((err: BusinessError) => {
let code = (err as BusinessError).code;
let message = (err as BusinessError).message;
console.error(`setMissionLabel failed, code is ${code}, message is ${message}`);
});
}
} setMissionContinueState(state: AbilityConstant.ContinueState, callback: AsyncCallback<void>): void
Sets the mission continuation state of this UIAbility. This API uses an asynchronous callback to return the result.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Ability.AbilityRuntime.Core
Device behavior difference: This API does not take effect when called on a Wearable device that does not support distributed services.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| state | AbilityConstant.ContinueState | Yes | Mission continuation state. |
| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the API call is successful, code in err is 0. Otherwise, err contains the corresponding error code and error information. |
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. |
| 16000011 | The context does not exist. |
| 16000050 | Internal error. |
Example
import { UIAbility, AbilityConstant } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
export default class EntryAbility extends UIAbility {
onForeground() {
this.context.setMissionContinueState(AbilityConstant.ContinueState.INACTIVE, (result: BusinessError) => {
console.info(`setMissionContinueState: ${JSON.stringify(result)}`);
});
}
} setMissionContinueState(state: AbilityConstant.ContinueState): Promise<void>
Sets the mission continuation state of this UIAbility. This API 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.Core
Device behavior difference: This API does not take effect when called on a Wearable device that does not support distributed services.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| state | AbilityConstant.ContinueState | Yes | Mission continuation state. |
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. |
| 16000011 | The context does not exist. |
| 16000050 | Internal error. |
Example
import { UIAbility, AbilityConstant } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
export default class EntryAbility extends UIAbility {
onForeground() {
this.context.setMissionContinueState(AbilityConstant.ContinueState.INACTIVE).then(() => {
console.info('success');
}).catch((err: BusinessError) => {
console.error(`setMissionContinueState failed, code is ${err.code}, message is ${err.message}`);
});
}
} restoreWindowStage(localStorage: LocalStorage): void
Restores the WindowStage data in the UIAbility. It can be called only on the main thread.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Ability.AbilityRuntime.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| localStorage | LocalStorage | Yes | Storage data used to restore the window stage. |
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. |
| 16000011 | The context does not exist. |
| 16000050 | Internal error. |
Example
import { UIAbility } from '@kit.AbilityKit';
export default class EntryAbility extends UIAbility {
onForeground() {
let storage = new LocalStorage();
this.context.restoreWindowStage(storage);
}
} isTerminating(): boolean
Checks whether this UIAbility is in the terminating state.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Ability.AbilityRuntime.Core
Return value
| Type | Description |
|---|---|
| boolean | Check result for whether the UIAbility is in the terminating state. true if in the terminating state, false otherwise. |
Error codes
For details about the error codes, see Ability Error Codes.
| ID | Error Message |
|---|---|
| 16000011 | The context does not exist. |
Example
import { UIAbility } from '@kit.AbilityKit';
export default class EntryAbility extends UIAbility {
onForeground() {
let isTerminating: boolean = this.context.isTerminating();
console.info(`ability state is ${isTerminating}`);
}
} requestDialogService(want: Want, result: AsyncCallback<dialogRequest.RequestResult>): void
Starts a ServiceExtensionAbility that supports modal dialog boxes. After the ServiceExtensionAbility is started, the application displays a modal dialog box. You can call setRequestResult to obtain the result. This API uses an asynchronous callback to return the result. It can be called only on the main thread.
For details about the startup rules for the components in the stage model, see Component Startup Rules (Stage Model).
System capability: SystemCapability.Ability.AbilityRuntime.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| want | Want | Yes | Want information for starting the ServiceExtensionAbility. |
| result | AsyncCallback<dialogRequest.RequestResult> | Yes | Callback used to return the result. If the API call is successful, code in err is 0 and data the result of the request for a modal dialog box. Otherwise, err contains the corresponding error code and error information. |
Error codes
For details about the error codes, see Universal Error Codes and Ability Error Codes.
| ID | Error Message |
|---|---|
| 201 | The application does not have permission to call the interface. Applicable version: 10+ |
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
| 16000001 | The specified ability does not exist. |
| 16000002 | Incorrect ability type. |
| 16000004 | Cannot start an invisible component. |
| 16000005 | The specified process does not have the permission. |
| 16000006 | Cross-user operations are not allowed. |
| 16000008 | The crowdtesting application expires. |
| 16000009 | An ability cannot be started or stopped in Wukong mode. |
| 16000010 | The call with the continuation and prepare continuation flag is forbidden. |
| 16000011 | The context does not exist. |
| 16000012 | The application is controlled. Applicable version: 10+ |
| 16000013 | The application is controlled by EDM. Applicable version: 10+ |
| 16000050 | Internal error. |
| 16000053 | The ability is not on the top of the UI. |
| 16000055 | Installation-free timed out. |
| 16200001 | The caller has been released. |
Example
import { UIAbility, Want, dialogRequest } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
export default class EntryAbility extends UIAbility {
onForeground() {
let want: Want = {
deviceId: '',
bundleName: 'com.example.myapplication',
abilityName: 'AuthAccountServiceExtension'
};
try {
this.context.requestDialogService(want, (err: BusinessError, result: dialogRequest.RequestResult) => {
if (err.code) {
// Process service logic errors.
console.error(`requestDialogService failed, code is ${err.code}, message is ${err.message}`);
return;
}
// Carry out normal service processing.
console.info(`requestDialogService succeed, result = ${JSON.stringify(result)}`);
});
} catch (err) {
// Process input parameter errors.
let code = (err as BusinessError).code;
let message = (err as BusinessError).message;
console.error(`requestDialogService failed, code is ${code}, message is ${message}`);
}
}
} requestDialogService(want: Want): Promise<dialogRequest.RequestResult>
Starts a ServiceExtensionAbility that supports modal dialog boxes. After the ServiceExtensionAbility is started, the application displays a modal dialog box. You can call setRequestResult to obtain the result. This API uses a promise to return the result. It can be called only on the main thread.
For details about the startup rules for the components in the stage model, see Component Startup Rules (Stage Model).
System capability: SystemCapability.Ability.AbilityRuntime.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| want | Want | Yes | Want information for starting the ServiceExtensionAbility. |
Return value
| Type | Description |
|---|---|
| Promise<dialogRequest.RequestResult> | Promise that returns no value. |
Error codes
For details about the error codes, see Universal Error Codes and Ability Error Codes.
| ID | Error Message |
|---|---|
| 201 | The application does not have permission to call the interface. Applicable version: 10+ |
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
| 16000001 | The specified ability does not exist. |
| 16000002 | Incorrect ability type. |
| 16000004 | Cannot start an invisible component. |
| 16000005 | The specified process does not have the permission. |
| 16000006 | Cross-user operations are not allowed. |
| 16000008 | The crowdtesting application expires. |
| 16000009 | An ability cannot be started or stopped in Wukong mode. |
| 16000010 | The call with the continuation and prepare continuation flag is forbidden. |
| 16000011 | The context does not exist. |
| 16000012 | The application is controlled. Applicable version: 10+ |
| 16000013 | The application is controlled by EDM. Applicable version: 10+ |
| 16000050 | Internal error. |
| 16000053 | The ability is not on the top of the UI. |
| 16000055 | Installation-free timed out. |
| 16200001 | The caller has been released. |
Example
import { UIAbility, Want, dialogRequest } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
export default class EntryAbility extends UIAbility {
onForeground() {
let want: Want = {
bundleName: 'com.example.myapplication',
abilityName: 'AuthAccountServiceExtension'
};
try {
this.context.requestDialogService(want)
.then((result: dialogRequest.RequestResult) => {
// Carry out normal service processing.
console.info(`requestDialogService succeed, result = ${JSON.stringify(result)}`);
})
.catch((err: BusinessError) => {
// Process service logic errors.
console.error(`requestDialogService failed, code is ${err.code}, message is ${err.message}`);
});
} catch (err) {
// Process input parameter errors.
let code = (err as BusinessError).code;
let message = (err as BusinessError).message;
console.error(`requestDialogService failed, code is ${code}, message is ${message}`);
}
}
} reportDrawnCompleted(callback: AsyncCallback<void>): void
Called when the window content associated with the UIAbility finishes drawing. This API uses an asynchronous callback to return the result.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Ability.AbilityRuntime.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the API call is successful, code in err is 0. Otherwise, err contains the corresponding error code and error information. |
Error codes
For details about the error codes, see Ability Error Codes.
| ID | Error Message |
|---|---|
| 16000011 | The context does not exist. |
| 16000050 | Internal error. |
Example
import { UIAbility } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';
export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage: window.WindowStage) {
windowStage.loadContent('pages/Index', (err, data) => {
if (err.code) {
return;
}
try {
this.context.reportDrawnCompleted((err) => {
if (err.code) {
// Process service logic errors.
console.error(`reportDrawnCompleted failed, code is ${err.code}, message is ${err.message}`);
return;
}
// Carry out normal service processing.
console.info('reportDrawnCompleted succeed');
});
} catch (err) {
// Capture the synchronization parameter error.
let code = (err as BusinessError).code;
let message = (err as BusinessError).message;
console.error(`reportDrawnCompleted failed, code is ${code}, message is ${message}`);
}
});
console.info("MainAbility onWindowStageCreate");
}
}; startAbilityByType(type: string, wantParam: Record<string, Object>, abilityStartCallback: AbilityStartCallback, callback: AsyncCallback<void>) : void
Implicitly starts a given type of UIExtensionAbility. This API uses an asynchronous callback to return the result. It can be called only in the main thread and by applications running in the foreground.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Ability.AbilityRuntime.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| type | string | Yes | Type of the UIExtensionAbility to start. For details, see Starting an Application of the Specified Type. |
| wantParam | Record<string, Object> | Yes | Extended parameter. |
| abilityStartCallback | AbilityStartCallback | Yes | Callback used to return the detailed error information if the startup fails. |
| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the API call is successful, err is undefined. Otherwise, err is an error object. |
Error codes
For details about the error codes, see Universal Error Codes and Ability Error Codes.
| ID | Error Message |
|---|---|
| 201 | The application does not have permission to call the interface. Applicable version: 11 |
| 16000004 | Cannot start an invisible component. Applicable version: 11 |
| 16200001 | The caller has been released. Applicable version: 11 |
| 16000002 | Incorrect ability type. Applicable version: 11 |
| 16000001 | The specified ability does not exist. Applicable version: 11 |
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
| 16000050 | Internal error. |
Example
import { UIAbility, common } from '@kit.AbilityKit';
export default class EntryAbility extends UIAbility {
onForeground() {
let wantParam: Record<string, Object> = {
'time': '2023-10-23 20:45'
};
let abilityStartCallback: common.AbilityStartCallback = {
onError: (code: number, name: string, message: string) => {
console.error(`code:` + code + `name:` + name + `message:` + message);
},
onResult: (abilityResult: common.AbilityResult) => {
console.info(`resultCode:` + abilityResult.resultCode + `bundleName:` + abilityResult.want?.bundleName);
}
};
this.context.startAbilityByType("photoEditor", wantParam, abilityStartCallback, (err) => {
if (err) {
console.error(`startAbilityByType fail, err: ${JSON.stringify(err)}`);
} else {
console.info(`success`);
}
});
}
} startAbilityByType(type: string, wantParam: Record<string, Object>, abilityStartCallback: AbilityStartCallback) : Promise<void>
Implicitly starts a given type of UIExtensionAbility. This API uses a promise to return the result. It can be called only in the main thread and by applications running in the foreground.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Ability.AbilityRuntime.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| type | string | Yes | Type of the UIExtensionAbility to start. For details, see Starting an Application of the Specified Type. |
| wantParam | Record<string, Object> | Yes | Extended parameter. |
| abilityStartCallback | AbilityStartCallback | Yes | Callback used to return the detailed error information if the startup fails. |
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 |
|---|---|
| 201 | The application does not have permission to call the interface. Applicable version: 11 |
| 16000004 | Cannot start an invisible component. Applicable version: 11 |
| 16200001 | The caller has been released. Applicable version: 11 |
| 16000002 | Incorrect ability type. Applicable version: 11 |
| 16000001 | The specified ability does not exist. Applicable version: 11 |
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
| 16000050 | Internal error. |
Example
import { UIAbility, common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
export default class EntryAbility extends UIAbility {
onForeground() {
let wantParam: Record<string, Object> = {
'time': '2023-10-23 20:45'
};
let abilityStartCallback: common.AbilityStartCallback = {
onError: (code: number, name: string, message: string) => {
console.error(`code:` + code + `name:` + name + `message:` + message);
},
onResult: (abilityResult: common.AbilityResult) => {
console.info(`resultCode:` + abilityResult.resultCode + `bundleName:` + abilityResult.want?.bundleName);
}
};
this.context.startAbilityByType("photoEditor", wantParam, abilityStartCallback).then(() => {
console.info(`startAbilityByType success`);
}).catch((err: BusinessError) => {
console.error(`startAbilityByType fail, err: ${JSON.stringify(err)}`);
});
}
} showAbility(): Promise<void>
Shows this UIAbility. This API uses a promise to return the result. It can be called only on the main thread.
Before calling this API, ensure that the application has been added to the status bar.
System capability: SystemCapability.Ability.AbilityRuntime.Core
Device behavior differences: This API can be properly called only on PC/2-in-1 devices and tablets. On other devices, it returns the error code 801.
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 |
|---|---|
| 801 | Capability not support. |
| 16000050 | Internal error. |
| 16000067 | The StartOptions check failed. |
Example
// Index.ets
import { common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct Index {
@State showAbility: string = 'showAbility'
build() {
Row() {
Column() {
Text(this.showAbility)
.fontSize(30)
.fontWeight(FontWeight.Bold)
.onClick(() => {
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
context.showAbility().then(() => {
console.info(`showAbility success`);
}).catch((err: BusinessError) => {
console.error(`showAbility fail, err: ${JSON.stringify(err)}`);
});
});
}
.width('100%')
}
.height('100%')
}
} // EntryAbility.ts
import { UIAbility, Want, StartOptions, contextConstant } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
export default class EntryAbility extends UIAbility {
onForeground() {
let want: Want = {
deviceId: '',
bundleName: 'com.example.myapplication',
abilityName: 'EntryAbility'
};
let options: StartOptions = {
displayId: 0,
processMode: contextConstant.ProcessMode.NEW_PROCESS_ATTACH_TO_STATUS_BAR_ITEM,
startupVisibility: contextConstant.StartupVisibility.STARTUP_SHOW
};
try {
this.context.startAbility(want, options, (err: BusinessError) => {
if (err.code) {
// Process service logic errors.
console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`);
return;
}
// Carry out normal service processing.
console.info('startAbility succeed');
});
} catch (err) {
// Process input parameter errors.
let code = (err as BusinessError).code;
let message = (err as BusinessError).message;
console.error(`startAbility failed, code is ${code}, message is ${message}`);
}
}
} hideAbility(): Promise<void>
Hides this UIAbility. This API uses a promise to return the result. It can be called only on the main thread.
Before calling this API, ensure that the application has been added to the status bar.
System capability: SystemCapability.Ability.AbilityRuntime.Core
Device behavior differences: This API can be properly called only on PC/2-in-1 devices and tablets. On other devices, it returns the error code 801.
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 |
|---|---|
| 801 | Capability not support. |
| 16000050 | Internal error. |
| 16000067 | The StartOptions check failed. |
Example
// Index.ets
import { common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct Index {
@State hideAbility: string = 'hideAbility'
build() {
Row() {
Column() {
Text(this.hideAbility)
.fontSize(30)
.fontWeight(FontWeight.Bold)
.onClick(() => {
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
context.hideAbility().then(() => {
console.info(`hideAbility success`);
}).catch((err: BusinessError) => {
console.error(`hideAbility fail, err: ${JSON.stringify(err)}`);
});
});
}
.width('100%')
}
.height('100%')
}
} // EntryAbility.ts
import { UIAbility, Want, StartOptions, contextConstant } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
export default class EntryAbility extends UIAbility {
onForeground() {
let want: Want = {
deviceId: '',
bundleName: 'com.example.myapplication',
abilityName: 'EntryAbility'
};
let options: StartOptions = {
displayId: 0,
processMode: contextConstant.ProcessMode.NEW_PROCESS_ATTACH_TO_STATUS_BAR_ITEM,
startupVisibility: contextConstant.StartupVisibility.STARTUP_HIDE
};
try {
this.context.startAbility(want, options, (err: BusinessError) => {
if (err.code) {
// Process service logic errors.
console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`);
return;
}
// Carry out normal service processing.
console.info('startAbility succeed');
});
} catch (err) {
// Process input parameter errors.
let code = (err as BusinessError).code;
let message = (err as BusinessError).message;
console.error(`startAbility failed, code is ${code}, message is ${message}`);
}
}
} moveAbilityToBackground(): Promise<void>
Moves this UIAbility from the foreground to the background. This API uses a promise to return the result. It can be called only on the main thread.
This API can be used only on phones.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Ability.AbilityRuntime.Core
Device behavior differences
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Error codes
For details about the error codes, see Ability Error Codes.
| ID | Error Message |
|---|---|
| 16000011 | The context does not exist. |
| 16000050 | Internal error. |
| 16000061 | Operation not supported. |
| 16000065 | The API can be called only when the ability is running in the foreground. |
| 16000066 | An ability cannot switch to the foreground or background in Wukong mode. |
Example
import { common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct Index {
@State moveAbilityToBackground: string = 'Move To Background'
build() {
Row() {
Column() {
Text(this.moveAbilityToBackground)
.fontSize(30)
.fontWeight(FontWeight.Bold)
.onClick(() => {
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
context.moveAbilityToBackground().then(() => {
console.info(`moveAbilityToBackground success.`);
}).catch((err: BusinessError) => {
console.error(`moveAbilityToBackground error: ${JSON.stringify(err)}.`);
});
});
}
.width('100%')
}
.height('100%')
}
} openAtomicService(appId: string, options?: AtomicServiceOptions): Promise<AbilityResult>
Opens an atomic service in an independent window. This API uses a promise to return the result. It can be called only on the main thread.
After an atomic service is started, the following situations may occur:
For details about the startup rules for the components in the stage model, see Component Startup Rules (Stage Model).
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Ability.AbilityRuntime.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| appId | string | Yes | Unique ID of the application, which is allocated by the cloud. |
| options | AtomicServiceOptions | No | Parameter carried in the request for starting the atomic service. |
Return value
| Type | Description |
|---|---|
| Promise<AbilityResult> | Promise 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. |
| 16000002 | Incorrect ability type. |
| 16000003 | The specified ID does not exist. |
| 16000004 | Cannot start an invisible component. |
| 16000011 | The context does not exist. |
| 16000012 | The application is controlled. |
| 16000050 | Internal error. |
| 16000053 | The ability is not on the top of the UI. |
| 16000055 | Installation-free timed out. |
| 16200001 | The caller has been released. |
Example
import { UIAbility, common, AtomicServiceOptions } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
export default class EntryAbility extends UIAbility {
onForeground() {
let appId: string = '6918661953712445909';
let options: AtomicServiceOptions = {
displayId: 0
};
try {
this.context.openAtomicService(appId, options)
.then((result: common.AbilityResult) => {
// Carry out normal service processing.
console.info('openAtomicService succeed');
})
.catch((err: BusinessError) => {
// Process service logic errors.
console.error(`openAtomicService failed, code is ${err.code}, message is ${err.message}`);
});
} catch (err) {
// Process input parameter errors.
let code = (err as BusinessError).code;
let message = (err as BusinessError).message;
console.error(`openAtomicService failed, code is ${code}, message is ${message}`);
}
}
} openLink(link: string, options?: OpenLinkOptions, callback?: AsyncCallback<AbilityResult>): Promise<void>
Starts a UIAbility by using App Linking or Deep Linking, and returns the exit result of the launched UIAbility via a callback. This API uses a promise to return the result. It can be called only on the main thread.
A URL in the standard format is passed in to the link field to start the target UIAbility based on the implicit Want matching rules. The target UIAbility must have the following filter characteristics to process links of App Linking:
If you want to obtain the result after the started UIAbility is terminated, set the callback parameter. For details about how to use this parameter, see startAbilityForResult.
If an input parameter is invalid, for example, a mandatory parameter is not set or the URL set in link is not in the standard format, an exception is thrown. If the parameter verification is successful but an error occurs when starting the target UIAbility, the error information is returned through promise.
For details about the startup rules for the components in the stage model, see Component Startup Rules (Stage Model).
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Ability.AbilityRuntime.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| link | string | Yes | URL to open, which must be in the standard format. |
| options | OpenLinkOptions | No | Options of the URL. |
| callback | AsyncCallback<AbilityResult> | No | Callback used to return the result. |
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 |
|---|---|
| 201 | The application does not have permission to call the interface. |
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
| 16000001 | The specified ability does not exist. |
| 16000002 | Incorrect ability type. |
| 16000004 | Cannot start an invisible component. |
| 16000005 | The specified process does not have the permission. |
| 16000006 | Cross-user operations are not allowed. |
| 16000008 | The crowdtesting application expires. |
| 16000009 | An ability cannot be started or stopped in Wukong mode. |
| 16000010 | The call with the continuation and prepare continuation flag is forbidden. |
| 16000011 | The context does not exist. |
| 16000012 | The application is controlled. |
| 16000013 | The application is controlled by EDM. |
| 16000019 | No matching ability is found. |
| 16200001 | The caller has been released. |
| 16000053 | The ability is not on the top of the UI. |
| 16000136 | The UIAbility is prohibited from launching itself via App Linking. Applicable version: 23+ |
Example
import { common, OpenLinkOptions } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';
const DOMAIN = 0xeeee;
const TAG: string = '[openLinkDemo]';
@Entry
@Component
struct Index {
build() {
RelativeContainer() {
Button("Call StartAbilityForResult")
.onClick(() => {
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
let link: string = 'https://www.example.com';
let openLinkOptions: OpenLinkOptions = {
appLinkingOnly: true,
parameters: { demo_key: 'demo_value' }
};
try {
context.openLink(
link,
openLinkOptions,
(err, result) => {
hilog.error(DOMAIN, TAG, `openLink callback error.code: ${JSON.stringify(err)}`);
hilog.info(DOMAIN, TAG, `openLink callback result: ${JSON.stringify(result.resultCode)}`);
hilog.info(DOMAIN, TAG, `openLink callback result data: ${JSON.stringify(result.want)}`);
}
).then(() => {
hilog.info(DOMAIN, TAG, `open link success.`);
}).catch((err: BusinessError) => {
hilog.error(DOMAIN, TAG, `open link failed, errCode ${JSON.stringify(err.code)}`);
});
}
catch (e) {
hilog.error(DOMAIN, TAG, `exception occurred, errCode ${JSON.stringify(e.code)}`);
}
})
}
.height('100%')
.width('100%')
}
} backToCallerAbilityWithResult(abilityResult: AbilityResult, requestCode: string): Promise<void>
Returns the startup result to the caller of startAbilityForResult or openLink. Different from terminateSelfWithResult, this API does not destroy the current UIAbility when it returns the result. This API uses a promise to return the result.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Ability.AbilityRuntime.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| abilityResult | AbilityResult | Yes | Result returned to the caller. |
| requestCode | string | Yes | requestCode generated by the system to identify this call when the target ability is started through startAbilityForResult or openLink and needs to return a result. This value can be obtained through the CALLER_REQUEST_CODE field in wantConstant. |
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 |
|---|---|
| 201 | The application does not have permission to call the interface. |
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
| 16000009 | An ability cannot be started or stopped in Wukong mode. |
| 16000011 | The context does not exist. |
| 16000050 | Internal error. |
| 16000074 | The caller does not exist. |
| 16000075 | BackToCaller is not supported. |
Example
The caller starts the target through the startAbilityForResult API, and the target then calls the backToCallerAbilityWithResult API to return to the caller.
// Caller
// index.ets
import { common, Want } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
@Entry
@Component
struct Index {
@State message: string = 'Hello World';
build() {
Row() {
Column() {
Text(this.message)
.fontSize(30)
.fontWeight(FontWeight.Bold)
Button("Call StartAbilityForResult")
.onClick(() => {
let context: common.UIAbilityContext = this.getUIContext().getHostContext() as common.UIAbilityContext;
let want: Want = {
bundleName: 'com.example.demo2',
abilityName: 'EntryAbility'
};
try {
// Use startAbilityForResult to start the target UIAbility.
context.startAbilityForResult(want, (err: BusinessError, result: common.AbilityResult) => {
if (err.code) {
// Process service logic errors.
hilog.error(0x0000, 'testTag', `startAbilityForResult failed, code is ${err.code}, message is ${err.message}`);
this.message = `startAbilityForResult failed: code is ${err.code}, message is ${err.message}`
return;
}
// Carry out normal service processing.
hilog.info(0x0000, 'testTag', `startAbilityForResult succeed`);
hilog.info(0x0000, 'testTag', `AbilityResult is ${JSON.stringify(result)}`);
this.message = `AbilityResult.resultCode: ${JSON.stringify(result.resultCode)}`
});
} catch (err) {
// Process input parameter errors.
let code = (err as BusinessError).code;
let message = (err as BusinessError).message;
hilog.error(0x0000, 'testTag', `startAbilityForResult failed, code is ${code}, message is ${message}`);
this.message = `startAbilityForResult failed, code is ${code}, message is ${message}`;
}
})
}
.width('100%')
}
.height('100%')
}
} // Target UIAbility
// EntryAbility.ets
import { AbilityConstant, common, UIAbility, Want, wantConstant } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';
export default class EntryAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
// Obtain the CALLER_REQUEST_CODE of the caller from want and save it.
let callerRequestCode: string = want?.parameters?.[wantConstant.Params.CALLER_REQUEST_CODE] as string;
AppStorage.setOrCreate<string>("callerRequestCode", callerRequestCode)
}
onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void {
let callerRequestCode: string = want?.parameters?.[wantConstant.Params.CALLER_REQUEST_CODE] as string;
AppStorage.setOrCreate<string>("callerRequestCode", callerRequestCode)
}
onForeground(): void {
// Obtain the saved CALLER_REQUEST_CODE.
let callerRequestCode: string = AppStorage.get<string>("callerRequestCode") as string;
hilog.info(0x0000, 'testTag', `callerRequestCode is ${callerRequestCode}`);
let want: Want = {};
let resultCode = 100;
let abilityResult: common.AbilityResult = {
want,
resultCode
};
try {
// Return the result to the caller.
this.context.backToCallerAbilityWithResult(abilityResult, callerRequestCode)
.then(() => {
// Carry out normal service processing.
hilog.info(0x0000, 'testTag', 'backToCallerAbilityWithResult succeed');
})
.catch((err: BusinessError) => {
// Process service logic errors.
hilog.error(0x0000, 'testTag', `backToCallerAbilityWithResult failed, code is ${err.code}, message is ${err.message}`);
});
} catch (err) {
// Capture the synchronization parameter error.
let code = (err as BusinessError).code;
let message = (err as BusinessError).message;
hilog.error(0x0000, 'testTag', `backToCallerAbilityWithResult failed, code is ${code}, message is ${message}`);
}
}
} setRestoreEnabled(enabled: boolean): void
Sets whether to enable backup and restore for this UIAbility.
If the application sets removeMissionAfterTerminate to true, the backup and restore function does not take effect.
Atomic service API: This API can be used in atomic services since API version 14.
System capability: SystemCapability.Ability.AbilityRuntime.Core
Device behavior differences: The UIAbility backup and restore function takes effect only on Phone, Tablet, Wearable, and TV devices. PC/2in1 devices do not support the backup and restore function. On Tablet devices, the backup and restore function does not take effect after free multi-window is enabled.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| enabled | boolean | Yes | Whether to enable backup and restore. true to enable, false otherwise. |
Error codes
For details about the error codes, see Universal Error Codes and Ability Error Codes.
| ID | Error Message |
|---|---|
| 401 | If the input parameter is not valid parameter. |
| 16000011 | The context does not exist. |
Example
import { UIAbility, AbilityConstant, Want } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
export default class EntryAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
let enabled = true;
try {
this.context.setRestoreEnabled(enabled);
} catch (paramError) {
let code = (paramError as BusinessError).code;
let message = (paramError as BusinessError).message;
console.error(`setRestoreEnabled failed, err code: ${code}, err msg: ${message}`);
}
}
} startUIServiceExtensionAbility(want: Want): Promise<void>
Starts a UIServiceExtensionAbility. This API uses a promise to return the result.
For details about the startup rules for the components in the stage model, see Component Startup Rules (Stage Model).
Atomic service API: This API can be used in atomic services since API version 14.
System capability: SystemCapability.Ability.AbilityRuntime.Core
Device behavior differences: This API can be properly called only on PCs/2-in-1 devices. If it is called on other device types, error code 801 is returned.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| want | Want | Yes | Mandatory information for starting the UIServiceExtensionAbility. |
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 |
|---|---|
| 201 | The application does not have permission to call the interface. |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
| 801 | Capability not supported. |
| 16000001 | The specified ability does not exist. |
| 16000002 | Incorrect ability type. |
| 16000004 | Cannot start an invisible component. |
| 16000005 | The specified process does not have the permission. |
| 16000008 | The crowdtesting application expires. |
| 16000011 | The context does not exist. |
| 16000012 | The application is controlled. |
| 16000013 | The application is controlled by EDM. |
| 16000019 | No matching ability is found. |
| 16000050 | Internal error. |
| 16200001 | The caller has been released. |
Example
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.info('startUIServiceExtensionAbility success');
}).catch((error: BusinessError) => {
console.error('startUIServiceExtensionAbility error', JSON.stringify(error));
})
} catch (err) {
console.error('startUIServiceExtensionAbility failed', JSON.stringify(err));
}
})
}
}
}
} connectUIServiceExtensionAbility(want: Want, callback: UIServiceExtensionConnectCallback) : Promise<UIServiceProxy>
Connects to a UIServiceExtensionAbility. This API uses a promise to return the result.
For details about the startup rules for the components in the stage model, see Component Startup Rules (Stage Model).
Atomic service API: This API can be used in atomic services since API version 14.
System capability: SystemCapability.Ability.AbilityRuntime.Core
Device behavior differences: This API can be properly called only on PCs/2-in-1 devices. If it is called on other device types, error code 801 is returned.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| want | Want | Yes | Mandatory information for connecting to the UIServiceExtensionAbility. |
| callback | UIServiceExtensionConnectCallback | Yes | Callback for connecting to the UIServiceExtensionAbility. |
Return value
| Type | Description |
|---|---|
| Promise<UIServiceProxy> | Promise used to return the result, which is a UIServiceProxy object. |
Error codes
For details about the error codes, see Universal Error Codes and Ability Error Codes.
| ID | Error Message |
|---|---|
| 201 | The application does not have permission to call the interface. |
| 801 | Capability not supported. |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
| 16000001 | The specified ability does not exist. |
| 16000002 | Incorrect ability type. |
| 16000004 | Cannot start an invisible component. |
| 16000005 | The specified process does not have the permission. |
| 16000008 | The crowdtesting application expires. |
| 16000011 | The context does not exist. |
| 16000013 | The application is controlled by EDM. |
| 16000050 | Internal error. |
| 16000055 | Installation-free timed out. |
Example
import { common, Want } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
const TAG: string = '[Extension] ';
@Entry
@Component
struct UIServiceExtensionAbility {
dataCallBack : common.UIServiceExtensionConnectCallback = {
// Receive data
onData: (data: Record<string, Object>) => {
console.info(`dataCallBack received data`, JSON.stringify(data));
},
// Disconnect from the UIServiceExtensionAbility.
onDisconnect: () => {
console.info(`dataCallBack onDisconnect`);
}
}
async myConnect() {
// Obtain the context.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
let startWant: Want = {
deviceId: '',
bundleName: 'com.example.myapplication',
abilityName: 'UiServiceExtAbility'
};
try {
// Connect to the UIServiceExtensionAbility.
context.connectUIServiceExtensionAbility(startWant, this.dataCallBack)
.then((proxy: common.UIServiceProxy) => {
console.info(TAG + `try to connectUIServiceExtensionAbility`, JSON.stringify(proxy));
}).catch((err: Error) => {
let code = (err as BusinessError).code;
let message = (err as BusinessError).message;
console.error(TAG + `connectUIServiceExtensionAbility failed, code is ${code}, message is ${message}`);
});
} catch (err) {
let code = (err as BusinessError).code;
let message = (err as BusinessError).message;
console.error(TAG + `connectUIServiceExtensionAbility failed, code is ${code}, message is ${message}`);
};
}
build() {
RelativeContainer() {
// Create a Connect button.
Button('connectServiceExtensionAbility', { type: ButtonType.Capsule, stateEffect: true })
.alignRules({
center: { anchor: '__container__', align: VerticalAlign.Center },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
})
.onClick(() => {
this.myConnect()
});
}
.height('100%')
.width('100%')
}
} disconnectUIServiceExtensionAbility(proxy: UIServiceProxy): Promise<void>
Disconnects from a UIServiceExtensionAbility. This API uses a promise to return the result.
For details about the startup rules for the components in the stage model, see Component Startup Rules (Stage Model).
Atomic service API: This API can be used in atomic services since API version 14.
System capability: SystemCapability.Ability.AbilityRuntime.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| proxy | UIServiceProxy | Yes | Proxy returned after connectUIServiceExtensionAbility is called. |
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; 3. Parameter verification failed. |
| 16000011 | The context does not exist. |
| 16000050 | Internal error. |
Example
import { common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
const TAG: string = '[Extension] ';
@Entry
@Component
struct UIServiceExtensionAbility {
comProxy: common.UIServiceProxy | null = null;
build() {
Scroll() {
Column() {
// Create a Disconnect button.
Button('disconnectUIServiceExtensionAbility', { type: ButtonType.Capsule, stateEffect: true })
.margin({
top: 5,
left: 10,
right: 10,
bottom: 5
})
.alignRules({
center: { anchor: '__container__', align: VerticalAlign.Center },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
})
.onClick(() => {
this.myDisconnectUIServiceExtensionAbility()
});
}
.width('100%')
}
.height('100%')
}
myDisconnectUIServiceExtensionAbility() {
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
try {
// Disconnect from the UIServiceExtensionAbility.
context.disconnectUIServiceExtensionAbility(this.comProxy)
.then(() => {
console.info(TAG + `disconnectUIServiceExtensionAbility succeed ${this.comProxy}`);
}).catch((err: Error) => {
let code = (err as BusinessError).code;
let message = (err as BusinessError).message;
console.error(TAG + `disconnectUIServiceExtensionAbility failed, code is ${code}, message is ${message}`);
});
} catch (err) {
let code = (err as BusinessError).code;
let message = (err as BusinessError).message;
console.error(TAG + `disconnectUIServiceExtensionAbility failed, code is ${code}, message is ${message}`);
}
}
} setAbilityInstanceInfo(label: string, icon: image.PixelMap): Promise<void>
Sets the icon and label for this UIAbility. The icon and label can be displayed in the task center and the shortcut bar. This API uses a promise to return the result.
Required permissions: ohos.permission.SET_ABILITY_INSTANCE_INFO
System capability: SystemCapability.Ability.AbilityRuntime.Core
Device behavior differences: This API can be properly called only on PCs/2-in-1 devices. If it is called on other device types, error code 801 is returned.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| label | string | Yes | New icon label. The label cannot be an empty string, and can contain a maximum of 1024 bytes. |
| icon | image.PixelMap | Yes | Icon. The recommended icon size is 512 px * 512 px. |
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 |
|---|---|
| 201 | The application does not have permission to call the interface. |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
| 801 | Capability not supported. |
| 16000011 | The context does not exist. |
| 16000050 | Internal error. |
Example
import { UIAbility } from '@kit.AbilityKit';
import { image } from '@kit.ImageKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { window } from '@kit.ArkUI';
export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage: window.WindowStage): void {
windowStage.loadContent('pages/Index', async (err, data) => {
if (err.code) {
console.error(`loadContent failed, code is ${err.code}`);
return;
}
let newLabel: string = 'instance label';
let color = new ArrayBuffer(512 * 512 * 4); // Create an ArrayBuffer object to store image pixels. The size of the object is (height * width * 4) bytes.
let bufferArr = new Uint8Array(color);
for (let i = 0; i < bufferArr.length; i += 4) {
bufferArr[i] = 255;
bufferArr[i+1] = 0;
bufferArr[i+2] = 122;
bufferArr[i+3] = 255;
}
let opts: image.InitializationOptions = {
editable: true, pixelFormat: image.PixelMapFormat.RGBA_8888, size: { height: 512, width: 512 }
};
let imagePixelMap: image.PixelMap = await image.createPixelMap(color, opts);
// Set the icon and label information of the UIAbility instance.
try {
this.context.setAbilityInstanceInfo(newLabel, imagePixelMap)
.then(() => {
console.info('setAbilityInstanceInfo success');
}).catch((err: BusinessError) => {
console.error(`setAbilityInstanceInfo failed, code is ${err.code}, message is ${err.message}`);
});
} catch (paramError) {
let code = (paramError as BusinessError).code;
let message = (paramError as BusinessError).message;
console.error(`setAbilityInstanceInfo failed, code is ${code}, message is ${message}`);
}
});
}
} revokeDelegator(): Promise<void>
When the first UIAbility launched under a module needs to redirect to another UIAbility, the target UIAbility is known as the DelegatorAbility. For details about how to set up the DelegatorAbility, see step 1 in the example provided for this API.
Once the DelegatorAbility has completed its specific operations, you can use this API to revert to the first UIAbility. This API uses a promise to return the result.
System capability: SystemCapability.Ability.AbilityRuntime.Core
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 |
|---|---|
| 801 | Capability not support. |
| 16000011 | The context does not exist. |
| 16000050 | Internal error. |
| 16000065 | The API can be called only when the ability is running in the foreground. |
| 16000084 | Only DelegatorAbility is allowed to call this API, and only once. |
| 16000085 | An error occurred during the interaction between the ability and window. |
Example
Set a DelegatorAbility.
Configure abilitySrcEntryDelegator and abilityStageSrcEntryDelegator in the module.json5 file. When the first UIAbility of the module is cold started, the system preferentially starts the UIAbility specified by abilitySrcEntryDelegator.
{
"module": {
// ...
"abilityStageSrcEntryDelegator": "xxxModuleName",
"abilitySrcEntryDelegator": "xxxAbilityName",
// ...
}
} Revoke the DelegatorAbility.
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
export default class DelegatorAbility extends UIAbility {
onForeground() {
// After the DelegatorAbility completes the specific operation, call revokeDelegator to revert to the first UIAbility.
this.context.revokeDelegator().then(() => {
console.info('revokeDelegator success');
}).catch((err: BusinessError) => {
console.error(`revokeDelegator failed, code is ${err.code}, message is ${err.message}`);
});
}
} setColorMode(colorMode: ConfigurationConstant.ColorMode): void
Sets the dark/light color mode for this UIAbility. Before calling this API, ensure that the page corresponding to the UIAbility has been loaded. This API can be called only on the main thread.
Atomic service API: This API can be used in atomic services since API version 18.
System capability: SystemCapability.Ability.AbilityRuntime.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| colorMode | ConfigurationConstant.ColorMode | Yes | Color mode to set, which can be any of the following: - COLOR_MODE_DARK: dark mode - COLOR_MODE_LIGHT: light mode - COLOR_MODE_NOT_SET: not set (follows the system or application) |
Error codes
For details about the error codes, see Ability Error Codes.
| ID | Error Message |
|---|---|
| 16000011 | The context does not exist. |
Example
import { UIAbility, ConfigurationConstant } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { window } from '@kit.ArkUI';
export default class MyAbility extends UIAbility {
onWindowStageCreate(windowStage: window.WindowStage) {
windowStage.loadContent('pages/Index', (err, data) => {
if (err.code) {
hilog.error(0x0000, 'testTag', 'Failed to load the content.');
return;
}
let uiAbilityContext = this.context;
uiAbilityContext.setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_DARK);
});
}
} startAppServiceExtensionAbility(want: Want): Promise<void>
Starts an AppServiceExtensionAbility instance. This API uses a promise to return the result.
The caller of this API must be the application to which the AppServiceExtensionAbility instance belongs or an application in the application list supported by the AppServiceExtensionAbility instance (configured in the appIdentifierAllowList property of extensionAbilities).
System capability: SystemCapability.Ability.AbilityRuntime.Core
Device behavior differences: This API can be properly called only on PCs/2-in-1 devices. If it is called on other device types, error code 801 is returned.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| want | Want | Yes | Want information for starting the AppServiceExtensionAbility. |
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 |
|---|---|
| 801 | Capability not supported. |
| 16000001 | The specified ability does not exist. |
| 16000002 | Incorrect ability type. |
| 16000004 | Cannot start an invisible component. |
| 16000005 | The specified process does not have the permission. |
| 16000006 | Cross-user operations are not allowed. |
| 16000008 | The crowdtesting application expires. |
| 16000011 | The context does not exist. |
| 16000012 | The application is controlled. |
| 16000013 | The application is controlled by EDM. |
| 16000019 | No matching ability is found. |
| 16000050 | Internal error. |
| 16000200 | The caller is not in the appIdentifierAllowList of the target application. |
Example
import { UIAbility, Want } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
export default class EntryAbility extends UIAbility {
onForeground() {
let want: Want = {
deviceId: '',
bundleName: 'com.example.myapplication',
abilityName: 'AppServiceExtensionAbility'
};
try {
this.context.startAppServiceExtensionAbility(want)
.then(() => {
// Carry out normal service processing.
console.info('startAppServiceExtensionAbility succeed');
})
.catch((err: BusinessError) => {
// Process service logic errors.
console.error(`startAppServiceExtensionAbility failed, code is ${err.code}, message is ${err.message}`);
});
} catch (err) {
// Process input parameter errors.
let code = (err as BusinessError).code;
let message = (err as BusinessError).message;
console.error(`startAppServiceExtensionAbility failed, code is ${code}, message is ${message}`);
}
}
} stopAppServiceExtensionAbility(want: Want): Promise<void>
Stops an AppServiceExtensionAbility instance. This API uses a promise to return the result.
The caller of this API must be the application to which the AppServiceExtensionAbility instance belongs or an application in the application list supported by the AppServiceExtensionAbility instance (configured in the appIdentifierAllowList property of extensionAbilities).
System capability: SystemCapability.Ability.AbilityRuntime.Core
Device behavior differences: This API can be properly called only on PCs/2-in-1 devices. If it is called on other device types, error code 801 is returned.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| want | Want | Yes | Want information for stoping the AppServiceExtensionAbility. |
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 |
|---|---|
| 801 | Capability not supported. |
| 16000001 | The specified ability does not exist. |
| 16000002 | Incorrect ability type. |
| 16000004 | Cannot start an invisible component. |
| 16000005 | The specified process does not have the permission. |
| 16000006 | Cross-user operations are not allowed. |
| 16000011 | The context does not exist. |
| 16000050 | Internal error. |
| 16000200 | The caller is not in the appIdentifierAllowList of the target application. |
Example
import { UIAbility, Want } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
export default class EntryAbility extends UIAbility {
onForeground() {
let want: Want = {
deviceId: '',
bundleName: 'com.example.myapplication',
abilityName: 'AppServiceExtensionAbility'
};
try {
this.context.stopAppServiceExtensionAbility(want)
.then(() => {
// Carry out normal service processing.
console.info('stopAppServiceExtensionAbility succeed');
})
.catch((err: BusinessError) => {
// Process service logic errors.
console.error(`stopAppServiceExtensionAbility failed, code is ${err.code}, message is ${err.message}`);
});
} catch (err) {
// Process input parameter errors.
let code = (err as BusinessError).code;
let message = (err as BusinessError).message;
console.error(`stopAppServiceExtensionAbility failed, code is ${code}, message is ${message}`);
}
}
} connectAppServiceExtensionAbility(want: Want, callback: ConnectOptions): number
Connects this UIAbility to an AppServiceExtensionAbility. It enables communication with the AppServiceExtensionAbility via a proxy, allowing access to the capabilities exposed by the AppServiceExtensionAbility. It can be called only on the main thread.
If the AppServiceExtensionAbility instance is not started, the caller of this API must be the application to which the AppServiceExtensionAbility instance belongs or an application in the application list supported by the AppServiceExtensionAbility instance (configured in the appIdentifierAllowList property of extensionAbilities).
System capability: SystemCapability.Ability.AbilityRuntime.Core
Device behavior differences: This API can be properly called only on PCs/2-in-1 devices. If it is called on other device types, error code 801 is returned.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| want | Want | Yes | Want information for connecting to the AppServiceExtensionAbility. |
| callback | ConnectOptions | Yes | Callback used to return the information indicating that the connection is successful, failed, or interrupted. |
Return value
| Type | Description |
|---|---|
| number | Connection ID. A caller can call disconnectAppServiceExtensionAbility with this ID for disconnection. |
Error codes
For details about the error codes, see Universal Error Codes and Ability Error Codes.
| ID | Error Message |
|---|---|
| 801 | Capability not supported. |
| 16000001 | The specified ability does not exist. |
| 16000002 | Incorrect ability type. |
| 16000004 | Cannot start an invisible component. |
| 16000005 | The specified process does not have the permission. |
| 16000006 | Cross-user operations are not allowed. |
| 16000008 | The crowdtesting application expires. |
| 16000011 | The context does not exist. |
| 16000050 | Internal error. |
| 16000201 | The target service has not been started yet. |
Example
import { UIAbility, Want, common } from '@kit.AbilityKit';
import { rpc } from '@kit.IPCKit';
import { BusinessError } from '@kit.BasicServicesKit';
export default class EntryAbility extends UIAbility {
onForeground() {
let want: Want = {
deviceId: '',
bundleName: 'com.example.myapplication',
abilityName: 'AppServiceExtensionAbility'
};
let commRemote: rpc.IRemoteObject;
let callback: common.ConnectOptions = {
onConnect(elementName, remote) {
commRemote = remote;
console.info('onConnect...');
},
onDisconnect(elementName) {
console.info('onDisconnect...');
},
onFailed(code) {
console.info('onFailed...');
}
};
let connection: number;
try {
connection = this.context.connectAppServiceExtensionAbility(want, callback);
} catch (err) {
// Process input parameter errors.
let code = (err as BusinessError).code;
let message = (err as BusinessError).message;
console.error(`connectAppServiceExtensionAbility failed, code is ${code}, message is ${message}`);
}
}
} disconnectAppServiceExtensionAbility(connection: number): Promise<void>
Disconnects from an AppServiceExtensionAbility. It can be called only on the main thread. This API uses a promise to return the result.
Once the connection is terminated, you are advised to set the remote object returned when the connection is established to null, so as to prevent communication using the remote object that may become invalid.
System capability: SystemCapability.Ability.AbilityRuntime.Core
Device behavior differences: This API can be properly called only on PCs/2-in-1 devices. If it is called on other device types, error code 801 is returned.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| connection | number | Yes | Connection ID returned by connectAppServiceExtensionAbility. |
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 |
|---|---|
| 801 | Capability not supported. |
| 16000011 | The context does not exist. |
| 16000050 | Internal error. |
Example
import { UIAbility } from '@kit.AbilityKit';
import { rpc } from '@kit.IPCKit';
import { BusinessError } from '@kit.BasicServicesKit';
export default class EntryAbility extends UIAbility {
onForeground() {
// connection is the return value of connectAppServiceExtensionAbility.
let connection = 1;
let commRemote: rpc.IRemoteObject | null;
try {
this.context.disconnectAppServiceExtensionAbility(connection).then(() => {
commRemote = null;
// Carry out normal service processing.
console.info('disconnectAppServiceExtensionAbility succeed');
}).catch((err: BusinessError) => {
// Process service logic errors.
console.error(`disconnectAppServiceExtensionAbility failed, code is ${err.code}, message is ${err.message}`);
});
} catch (err) {
commRemote = null;
// Process input parameter errors.
let code = (err as BusinessError).code;
let message = (err as BusinessError).message;
console.error(`disconnectAppServiceExtensionAbility failed, code is ${code}, message is ${message}`);
}
}
} setOnNewWantSkipScenarios(scenarios: number): Promise<void>
Sets whether to trigger the onNewWant lifecycle callback when a UIAbility is started in a specific scenario. It can be called only on the main thread. This API uses a promise to return the result.
Atomic service API: This API can be used in atomic services since API version 20.
System capability: SystemCapability.Ability.AbilityRuntime.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| scenarios | number | Yes | Scenarios. For details about the available options, see Scenarios. |
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 |
|---|---|
| 16000050 | Internal error. Possible causes: Connection to service failed. |
Example
import { AbilityConstant, contextConstant, UIAbility, Want } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
export default class EntryAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
let scenarios: number = contextConstant.Scenarios.SCENARIO_MOVE_MISSION_TO_FRONT |
contextConstant.Scenarios.SCENARIO_SHOW_ABILITY |
contextConstant.Scenarios.SCENARIO_BACK_TO_CALLER_ABILITY_WITH_RESULT;
try {
this.context.setOnNewWantSkipScenarios(scenarios).then(() => {
// Carry out normal service processing.
console.info('setOnNewWantSkipScenarios succeed');
}).catch((err: BusinessError) => {
// Process service logic errors.
console.error(`setOnNewWantSkipScenarios failed, code is ${err.code}, message is ${err.message}`);
});
} catch (err) {
// Process input parameter errors.
let code = (err as BusinessError).code;
let message = (err as BusinessError).message;
console.error(`setOnNewWantSkipScenarios failed, code is ${code}, message is ${message}`);
}
}
} startSelfUIAbilityInCurrentProcess(want: Want, specifiedFlag: string, options?: StartOptions): Promise<void>
Starts the application's own UIAbility within the current process.
System capability: SystemCapability.Ability.AbilityRuntime.Core
Device behavior differences
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| want | Want | Yes | Mandatory information for starting the UIAbility. Only explicit startup is supported. Implicit startup is not supported. |
| specifiedFlag | string | Yes | ID of the UIAbility. This ID must not duplicate that of any already running UIAbility instance; otherwise, an error is returned. NOTE When this API is used to start a UIAbility instance in specified mode, the onAcceptWant callback is not triggered. |
| options | StartOptions | No | Parameters used for starting the UIAbility. |
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 |
|---|---|
| 801 | Capability not supported. |
| 16000001 | The specified ability does not exist. |
| 16000008 | The crowdtesting application expires. |
| 16000009 | An ability cannot be started or stopped in Wukong mode. |
| 16000011 | The context does not exist. |
| 16000050 | Internal error. Connect to system service failed. |
| 16000053 | The ability is not on the top of the UI. |
| 16000122 | The target component is blocked by the system module and does not support startup. |
| 16000123 | Implicit startup is not supported. |
| 16000124 | Starting a remote UIAbility is not supported. |
| 16000130 | The UIAbility not belong to caller. |
| 16000131 | The UIAbility is already exist, can not start again. |
Example
import { UIAbility, StartOptions, Want } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
export default class EntryAbility extends UIAbility {
onForeground() {
let want: Want = {
deviceId: '',
bundleName: 'com.example.myapplication',
abilityName: 'EntryAbility'
};
let accountId = 100;
let options: StartOptions = {
displayId: 0
};
let instanceFlag = 'instance1';
try {
this.context.startSelfUIAbilityInCurrentProcess(want, instanceFlag, options);
} catch (err) {
// Process input parameter errors.
let code = (err as BusinessError).code;
let message = (err as BusinessError).message;
console.error(`startSelfUIAbilityInCurrentProcess failed, code is ${code}, message is ${message}`);
}
}
} restartApp(want: Want): Promise<void>
Called by a focused UIAbility to restart its own process and launch a specified UIAbility within the same application. This API can be called only on the main thread. This API uses a promise to return the result.
If the target UIAbility is the current one, this action resets the window to its initial state. If it is a different UIAbility, the system navigates to and open a new window for that UIAbility.
When this API is called to restart the process, the onDestroy lifecycle callback of the UIAbility in the process is not triggered.
If an atomic service calls this API, restartSelfAtomicService(), or ApplicationContext.restartApp() within 3 seconds after a successful call to this API, the system returns error code 16000064.
If an application calls this API or ApplicationContext.restartApp() within 3 seconds after a successful call to this API, the system returns error code 16000064.
Atomic service API: This API can be used in atomic services since API version 22.
System capability: SystemCapability.Ability.AbilityRuntime.Core
Device behavior differences: This API can be properly called only on phones. If it is called on other device types, error code 801 is returned.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| want | Want | Yes | Want information about the UIAbility to start. The bundle name and ability name are verified. |
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 |
|---|---|
| 801 | Capability not supported. |
| 16000011 | The context does not exist. |
| 16000050 | Connect to system server error. |
| 16000063 | The target to restart does not belong to the caller or is not a UIAbility. |
| 16000064 | Restart too frequently. |
| 16000065 | The API can be called only when the ability is focused. |
Example
import { hilog } from '@kit.PerformanceAnalysisKit';
import { common, Want } from '@kit.AbilityKit';
@Entry
@Component
struct Index {
@State message: string = 'restartApp with window';
build() {
RelativeContainer() {
Text(this.message)
.id('HelloWorld')
.fontSize($r('app.float.page_text_font_size'))
.fontWeight(FontWeight.Bold)
.alignRules({
center: { anchor: '__container__', align: VerticalAlign.Center },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
})
.onClick(async () => {
let want: Want = {
bundleName: 'com.example.myapplication',
abilityName: 'EntryAbility'
};
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
try {
await context.restartApp(want);
} catch (err) {
hilog.error(0x0000, 'testTag', `restart failed: ${err.code}, ${err.message}`);
}
})
}
.height('100%')
.width('100%')
}
} setMissionWindowIcon(windowIcon: image.PixelMap): Promise<void>
Sets the icon for this UIAbility, which is displayed in the application window, application card in the mission center, and window snapshot in the shortcut bar. This API uses a promise to return the result.
There is no priority relationship among the setMissionWindowIcon and setAbilityInstanceInfo. The icon set by the last called API takes effect. If these APIs are called sequentially, the icon set by the last call takes precedence and overwrites any previous settings.
System capability: SystemCapability.Ability.AbilityRuntime.Core
Device behavior differences: This API can be properly called only on PCs/2-in-1 devices. If it is called on other device types, error code 801 is returned.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| windowIcon | image.PixelMap | Yes | Icon of the UIAbility displayed in the application window, application card in the mission center, and window snapshot in the shortcut bar. The icon must be a square and its size must not exceed 128 MB. Otherwise, error code 401 is returned. |
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 |
|---|---|
| 801 | Capability not supported. |
| 16000050 | Internal error. 1. Connect to system service failed; 2.System service failed to communicate with dependency module. |
| 16000135 | The main window of this ability not exist. |
Example
import { UIAbility } from '@kit.AbilityKit';
import { image } from '@kit.ImageKit';
import { BusinessError } from '@kit.BasicServicesKit';
export default class EntryAbility extends UIAbility {
onForeground() {
let imagePixelMap: image.PixelMap;
let color = new ArrayBuffer(1024 * 1024 * 4); // Create an ArrayBuffer object to store image pixels. The size of the object is (height * width * 4) bytes.
let bufferArr = new Uint8Array(color);
for (let i = 0; i < bufferArr.length; i += 4) {
bufferArr[i] = 255;
bufferArr[i+1] = 0;
bufferArr[i+2] = 122;
bufferArr[i+3] = 255;
}
image.createPixelMap(color, {
editable: true, pixelFormat: image.PixelMapFormat.RGBA_8888, size: { height: 1024, width: 1024 }
}).then((data) => {
imagePixelMap = data;
this.context.setMissionWindowIcon(imagePixelMap)
.then(() => {
console.info('setMissionWindowIcon succeed');
})
.catch((err: BusinessError) => {
console.error(`setMissionWindowIcon failed, code is ${err.code}, message is ${err.message}`);
});
}).catch((err: BusinessError) => {
console.error(`createPixelMap failed, code is ${err.code}, message is ${err.message}`);
});
}
} startSelf(): Promise<void>
Starts the current UIAbility instance and switches it to the foreground. This API is used to bring a native UIAbility that stays in an intermediate phase to the foreground. This API uses a promise to return the result.
For a UIAbility configured with a native module, its startup may stay in a specific phase due to the startupPhase configuration: PRE_WINDOW or PRE_FOREGROUND.
If the UIAbility is not configured with a native module, calling this API returns error code 801.
Since: 26.0.0
System capability: SystemCapability.Ability.AbilityRuntime.Core
Device behavior differences: This API can be properly called only on PCs/2-in-1 devices. If it is called on other device types, error code 801 is returned.
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 |
|---|---|
| 801 | Capability not supported, because starting self to foreground from background is not supported in current device or current UIAbility is a non-native UIAbility. |
| 16000011 | The context does not exist. |
| 16000050 | Internal error. Connect to system service failed. |
| 16000082 | The UIAbility is being started. The UIAbility has not completed onCreate or onWindowStageCreate. |
Example
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
export default class EntryAbility extends UIAbility {
onCreate() {
try {
setTimeout((): void => {
this.context.startSelf()
.then((): void => {
console.info('startSelf succeed');
})
.catch((err: BusinessError): void => {
console.error(`startSelf failed, code is ${err.code}, message is ${err.message}`);
});
}, 100);
} catch (err) {
let code = (err as BusinessError).code;
let message = (err as BusinessError).message;
console.error(`startSelf failed, code is ${code}, message is ${message}`);
}
}
} startSelfUIAbilityInChildProcess(want: Want, specifiedFlag: string): Promise<void>
Starts the UIAbility of the current application in a child process. The UIAbility in the child process supports loading native modules. This API uses a promise to return the result.
The lifecycle of the child process follows that of the parent process. When the parent process exits, the child process exits automatically.
Since: 26.0.0
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Ability.AbilityRuntime.Core
Device behavior differences: This API can be properly called only on PCs/2-in-1 devices. If it is called on other device types, error code 801 is returned.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| want | Want | Yes | Necessary information for starting the ability. Only explicit start is supported, and implicit start is not supported. |
| specifiedFlag | string | Yes | Custom UIAbility identifier defined by the developer. This identifier must be different from the identifiers of the UIAbilities that have been started. Otherwise, an error is returned. NOTE When this API is used to start a UIAbility whose launch type is specified, the onAcceptWant callback will not be triggered. |
| 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 |
|---|---|
| 801 | Capability not supported. |
| 16000001 | The specified ability does not exist. |
| 16000008 | The crowdtesting application expires. |
| 16000009 | An ability cannot be started or stopped in Wukong mode. |
| 16000011 | The context does not exist. |
| 16000050 | Internal error. Connect to system service failed. |
| 16000053 | The ability is not on the top of the UI. |
| 16000122 | The target component is blocked by the system module and does not support startup. |
| 16000123 | Implicit startup is not supported. |
| 16000124 | Starting a remote UIAbility is not supported. |
| 16000130 | The UIAbility not belong to caller. |
| 16000131 | The UIAbility is already exist, can not start again. |
Example
import { UIAbility, Want } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
export default class EntryAbility extends UIAbility {
onForeground() {
let want: Want = {
bundleName: 'com.example.myapplication',
abilityName: 'ChildProcessAbility'
};
let instanceFlag = 'instance1';
try {
this.context.startSelfUIAbilityInChildProcess(want, instanceFlag)
.then(() => {
console.info('startSelfUIAbilityInChildProcess succeed');
})
.catch((err: BusinessError) => {
console.error(`startSelfUIAbilityInChildProcess failed, code is ${err.code}, message is ${err.message}`);
});
} catch (err) {
let code = (err as BusinessError).code;
let message = (err as BusinessError).message;
console.error(`startSelfUIAbilityInChildProcess failed, code is ${code}, message is ${message}`);
}
}
}