From 68a9bc915415e4cb2d3fdb3f39358019107daf04 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=83=A1=E8=8A=B7=E7=8F=8A?= Date: Wed, 25 Jun 2025 21:31:39 +0800 Subject: [PATCH] update docs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 胡芷珊 --- .../basic-services/account/Readme-EN.md | 8 +- .../account/auth-domain-account.md | 6 +- .../control-os-account-by-constraints.md | 11 +- .../account/manage-application-account.md | 29 +- .../account/manage-distributed-account.md | 12 +- .../account/manage-domain-account.md | 25 +- .../account/manage-domain-plugin.md | 8 +- .../account/manage-os-account.md | 6 +- .../basic-services-kit-overview.md | 6 +- .../native-common-event-unsubscription.md | 2 +- .../common-event/native-use-pasteboard.md | 141 ++ .../compress/deflate-and-inflate.md | 185 ++- .../basic-services/request/Readme-EN.md | 2 +- .../request/app-file-upload-download.md | 650 ++++++-- .../basic-services/usb/Readme-EN.md | 2 - .../basic-services/usb/usb-glossary.md | 2 +- .../basic-services/usb/usb-guidelines.md | 18 +- .../usb/usbManager/usbhost/bulkTransfer.md | 28 +- .../usb/usbManager/usbhost/controlTransfer.md | 15 +- .../usb/usbManager/usbhost/deviceManager.md | 9 +- .../usbManager/usbhost/interruptTransfer.md | 24 +- .../usbManager/usbhost/isochronousTransfer.md | 24 +- .../usb/usbserial/usbSerial-communication.md | 36 +- .../usb/usbserial/usbSerial-configuration.md | 28 +- .../usb/usbserial/usbSerial-overview.md | 8 +- .../apis-basic-services-kit/Readme-EN.md | 21 +- .../apis-basic-services-kit/_o_h___print.md | 980 ++++++------ .../_print___margin.md | 15 +- .../_print___page_size.md | 7 +- .../_print___print_attributes.md | 11 + .../_print___print_doc_callback.md | 3 + .../apis-basic-services-kit/_print___range.md | 3 + .../apis-basic-services-kit/_time_service.md | 38 +- .../apis-basic-services-kit/c-apis-scan.md | 142 +- .../capi-oh-pasteboard-err-code-h.md | 50 + .../capi-oh-pasteboard-h.md | 763 ++++++++++ .../capi-os-account-common-h.md | 43 + .../capi-os-account-h.md | 53 + .../apis-basic-services-kit/capi-osaccount.md | 14 + .../capi-pasteboard-getdataparams.md | 11 + .../capi-pasteboard-oh-pasteboard.md | 11 + .../capi-pasteboard-oh-pasteboardobserver.md | 11 + .../capi-pasteboard-progressinfo.md | 11 + .../capi-pasteboard.md | 14 + .../common_event/commonEvent-definitions.md | 400 ++--- .../commonEventManager-definitions-sys.md | 218 ++- .../commonEventManager-definitions.md | 359 +++-- .../errorcode-CommonEventService.md | 56 +- .../errorcode-account.md | 58 +- .../errorcode-battery-info.md | 4 +- .../errorcode-pasteboard.md | 6 +- .../errorcode-request.md | 26 +- .../apis-basic-services-kit/errorcode-time.md | 14 +- .../apis-basic-services-kit/errorcode-usb.md | 117 +- .../apis-basic-services-kit/errorcode-zlib.md | 26 +- ...s-app-ability-PrintExtensionAbility-sys.md | 16 +- ...-apis-app-ability-PrintExtensionAbility.md | 12 +- .../js-apis-appAccount.md | 771 ++++++---- ...on-StaticSubscriberExtensionContext-sys.md | 8 +- .../js-apis-battery-info-sys.md | 16 +- .../js-apis-battery-info.md | 8 +- .../js-apis-batteryStatistics-sys.md | 14 +- .../js-apis-brightness-sys.md | 8 +- .../js-apis-commonEventManager-sys.md | 4 +- .../js-apis-commonEventManager.md | 93 +- .../js-apis-configPolicy-sys.md | 100 +- .../js-apis-date-time.md | 60 +- .../js-apis-device-info.md | 219 ++- .../js-apis-deviceAttest-sys.md | 46 +- .../js-apis-distributed-account-sys.md | 66 +- .../js-apis-distributed-account.md | 102 +- .../js-apis-emitter.md | 29 +- ...-apis-inner-commonEvent-commonEventData.md | 4 +- ...nner-commonEvent-commonEventPublishData.md | 4 +- .../js-apis-intelligentVoice-sys.md | 12 +- .../js-apis-osAccount-sys.md | 756 ++++------ .../js-apis-osAccount.md | 378 ++--- .../js-apis-pasteboard.md | 122 +- .../js-apis-power-sys.md | 28 +- .../apis-basic-services-kit/js-apis-power.md | 61 +- .../js-apis-print-sys.md | 441 ++++-- .../apis-basic-services-kit/js-apis-print.md | 551 +++++-- .../js-apis-request-cacheDownload.md | 5 +- .../js-apis-request-sys.md | 16 +- .../js-apis-request.md | 1330 +++++++++++------ .../js-apis-resourceschedule-systemload.md | 7 +- .../js-apis-runninglock.md | 45 +- .../js-apis-screen-lock-sys.md | 8 +- .../js-apis-serialManager-sys.md | 6 +- .../js-apis-serialManager.md | 147 +- .../js-apis-settings.md | 481 +++--- .../js-apis-system-battery.md | 2 +- .../js-apis-system-brightness.md | 6 +- .../js-apis-system-capability-sys.md | 8 +- .../js-apis-system-date-time-sys.md | 2 +- .../js-apis-system-device.md | 2 +- .../js-apis-system-parameterEnhance-sys.md | 29 +- .../js-apis-system-time.md | 10 +- .../js-apis-system-timer-sys.md | 52 +- .../js-apis-thermal.md | 42 +- .../js-apis-update-sys.md | 36 +- .../js-apis-usbManager-sys.md | 196 +-- .../js-apis-usbManager.md | 307 ++-- .../js-apis-wallpaper-sys.md | 14 +- .../js-apis-wallpaper.md | 4 +- .../apis-basic-services-kit/js-apis-zlib.md | 530 ++++--- .../oh__batteryinfo.md | 2 +- .../ohbattery__info_8h.md | 2 +- .../time__service_8h.md | 4 +- 109 files changed, 7486 insertions(+), 4506 deletions(-) create mode 100644 en/application-dev/basic-services/common-event/native-use-pasteboard.md create mode 100644 en/application-dev/reference/apis-basic-services-kit/capi-oh-pasteboard-err-code-h.md create mode 100644 en/application-dev/reference/apis-basic-services-kit/capi-oh-pasteboard-h.md create mode 100644 en/application-dev/reference/apis-basic-services-kit/capi-os-account-common-h.md create mode 100644 en/application-dev/reference/apis-basic-services-kit/capi-os-account-h.md create mode 100644 en/application-dev/reference/apis-basic-services-kit/capi-osaccount.md create mode 100644 en/application-dev/reference/apis-basic-services-kit/capi-pasteboard-getdataparams.md create mode 100644 en/application-dev/reference/apis-basic-services-kit/capi-pasteboard-oh-pasteboard.md create mode 100644 en/application-dev/reference/apis-basic-services-kit/capi-pasteboard-oh-pasteboardobserver.md create mode 100644 en/application-dev/reference/apis-basic-services-kit/capi-pasteboard-progressinfo.md create mode 100644 en/application-dev/reference/apis-basic-services-kit/capi-pasteboard.md diff --git a/en/application-dev/basic-services/account/Readme-EN.md b/en/application-dev/basic-services/account/Readme-EN.md index 60c24594bc3..a410132e79e 100644 --- a/en/application-dev/basic-services/account/Readme-EN.md +++ b/en/application-dev/basic-services/account/Readme-EN.md @@ -1,16 +1,16 @@ # Account Management - [Account Management Overview](account-overview.md) -- System Accounts (for System Applications Only) +- System Accounts (for System Applications Only) - [Managing System Accounts](manage-os-account.md) - [Applying Constraints for System Accounts](control-os-account-by-constraints.md) - [Managing System Account Credentials](manage-os-account-credential.md) -- Domain Accounts (for System Applications Only) +- Domain Accounts (for System Applications Only) - [Managing Domain Accounts](manage-domain-account.md) - [Authenticating Domain Accounts](auth-domain-account.md) - [Managing Domain Account Plugins](manage-domain-plugin.md) -- Distributed Accounts (for System Applications Only) +- Distributed Accounts (for System Applications Only) - [Managing Distributed Accounts](manage-distributed-account.md) -- Application Accounts +- Application Accounts - [Managing Application Accounts](manage-application-account.md) diff --git a/en/application-dev/basic-services/account/auth-domain-account.md b/en/application-dev/basic-services/account/auth-domain-account.md index 8a2e5a42122..ce488509580 100644 --- a/en/application-dev/basic-services/account/auth-domain-account.md +++ b/en/application-dev/basic-services/account/auth-domain-account.md @@ -16,7 +16,7 @@ The domain account can be authenticated by password. You can use [auth](../../re **Procedure** -1. Request the ohos.permission.ACCESS_USER_AUTH_INTERNAL permission. For details, see [Requesting Permissions for system_basic Applications](../../security/AccessToken/determine-application-mode.md#requesting-permissions-for-system_basic-applications). +1. Request the ohos.permission.ACCESS_USER_AUTH_INTERNAL permission. For details about how to request the permission, see [Requesting Permissions for system_basic Applications](../../security/AccessToken/determine-application-mode.md#requesting-permissions-for-system_basic-applications). 2. Obtain user input information, including the domain account and its password. @@ -45,7 +45,7 @@ The domain account can be authenticated by password. You can use [auth](../../re try { osAccount.DomainAccountManager.auth(domainAccountInfo, credential, callback); } catch (err) { - console.log('auth exception = ' + JSON.stringify(err)); + console.error('auth exception = ' + JSON.stringify(err)); } ``` @@ -72,6 +72,6 @@ If the domain account password is unavailable, display a dialog box to authentic try { osAccount.DomainAccountManager.authWithPopup(callback) } catch (err) { - console.log('authWithPopup exception = ' + JSON.stringify(err)); + console.error('authWithPopup exception = ' + JSON.stringify(err)); } ``` diff --git a/en/application-dev/basic-services/account/control-os-account-by-constraints.md b/en/application-dev/basic-services/account/control-os-account-by-constraints.md index 66c1b335895..b7ba67f4597 100644 --- a/en/application-dev/basic-services/account/control-os-account-by-constraints.md +++ b/en/application-dev/basic-services/account/control-os-account-by-constraints.md @@ -42,7 +42,7 @@ The user can set constraints to restrict the system account behaviors. For examp accountManager.setOsAccountConstraints(localId, constraint, true); console.log('setOsAccountConstraints successfully'); } catch (err) { - console.log('setOsAccountConstraints failed, error: ' + JSON.stringify(err)); + console.error('setOsAccountConstraints failed, error: ' + JSON.stringify(err)); } ``` @@ -62,8 +62,9 @@ Before a constraint is enabled for a system account, the application needs to ch 2. Use [isOsAccountConstraintEnabled](../../reference/apis-basic-services-kit/js-apis-osAccount-sys.md#isosaccountconstraintenabled11) to check whether the constraint can be enabled for the system account. ```ts - let isEnabled: boolean = await accountManager.isOsAccountConstraintEnabled(localId, constraint); - if (isEnabled) { - // Your business logic - } + accountManager.isOsAccountConstraintEnabled(localId, constraint).then((isEnabled: boolean) => { + if (isEnabled) { + // Your business logic + } + }); ``` diff --git a/en/application-dev/basic-services/account/manage-application-account.md b/en/application-dev/basic-services/account/manage-application-account.md index cf42f7e4682..01772d79c4f 100644 --- a/en/application-dev/basic-services/account/manage-application-account.md +++ b/en/application-dev/basic-services/account/manage-application-account.md @@ -38,12 +38,11 @@ Create an application account for an application user. 2. Use [createAccount](../../reference/apis-basic-services-kit/js-apis-appAccount.md#createaccount9) to create an application account based on the specified parameters. ```ts - try { - await appAccountManager.createAccount(name, options); - console.log('createAccount successfully'); - } catch (err) { - console.log('createAccount failed, error: ' + JSON.stringify(err)); - } + appAccountManager.createAccount(name, options).then(()=>{ + console.log('createAccount successfully'); + }).catch((err: BusinessError)=>{ + console.error('createAccount failed, error: ' + JSON.stringify(err)); + }); ``` ## Obtaining Application Account List @@ -55,9 +54,9 @@ Use [getAllAccounts](../../reference/apis-basic-services-kit/js-apis-appAccount. ```ts appAccountManager.getAllAccounts().then((data: appAccount.AppAccountInfo[]) => { - console.debug('getAllAccounts successfully, data: ' + JSON.stringify(data)); + console.log('getAllAccounts successfully, data: ' + JSON.stringify(data)); }).catch((err: BusinessError) => { - console.debug('getAllAccounts failed, error: ' + JSON.stringify(err)); + console.error('getAllAccounts failed, error: ' + JSON.stringify(err)); }); ``` @@ -79,7 +78,7 @@ Use [getAllAccounts](../../reference/apis-basic-services-kit/js-apis-appAccount. appAccountManager.getCredential(name, credentialType).then((data: string) => { console.log('getCredential successfully, data: ' + data); }).catch((err: BusinessError) => { - console.log('getCredential failed, error: ' + JSON.stringify(err)); + console.error('getCredential failed, error: ' + JSON.stringify(err)); }); ``` @@ -89,7 +88,7 @@ Use [getAllAccounts](../../reference/apis-basic-services-kit/js-apis-appAccount. appAccountManager.setCredential(name, credentialType, credential).then(() => { console.log('setCredential successfully'); }).catch((err: BusinessError) => { - console.log('setCredential failed: ' + JSON.stringify(err)); + console.error('setCredential failed: ' + JSON.stringify(err)); }); ``` @@ -111,7 +110,7 @@ Use [getAllAccounts](../../reference/apis-basic-services-kit/js-apis-appAccount. appAccountManager.setCustomData(name, key, value).then(() => { console.log('setCustomData successfully'); }).catch((err: BusinessError) => { - console.log('setCustomData failed: ' + JSON.stringify(err)); + console.error('setCustomData failed: ' + JSON.stringify(err)); }); ``` @@ -121,7 +120,7 @@ Use [getAllAccounts](../../reference/apis-basic-services-kit/js-apis-appAccount. appAccountManager.getCustomData(name, key).then((data: string) => { console.log('getCustomData successfully, data: ' + data); }).catch((err: BusinessError) => { - console.log('getCustomData failed, error: ' + JSON.stringify(err)); + console.error('getCustomData failed, error: ' + JSON.stringify(err)); }); ``` @@ -144,7 +143,7 @@ Use [getAllAccounts](../../reference/apis-basic-services-kit/js-apis-appAccount. appAccountManager.setAuthToken(name, authType, token).then(() => { console.log('setAuthToken successfully'); }).catch((err: BusinessError) => { - console.log('setAuthToken failed: ' + JSON.stringify(err)); + console.error('setAuthToken failed: ' + JSON.stringify(err)); }); ``` @@ -154,7 +153,7 @@ Use [getAllAccounts](../../reference/apis-basic-services-kit/js-apis-appAccount. appAccountManager.getAuthToken(name, owner, authType).then((data: string) => { console.log('getAuthToken successfully, data: ' + data); }).catch((err: BusinessError) => { - console.log('getAuthToken failed, error: ' + JSON.stringify(err)); + console.error('getAuthToken failed, error: ' + JSON.stringify(err)); }); ``` @@ -171,7 +170,7 @@ Use [removeAccount](../../reference/apis-basic-services-kit/js-apis-appAccount.m appAccountManager.removeAccount(name).then(() => { console.log('removeAccount successfully'); }).catch((err: BusinessError) => { - console.log('removeAccount failed, error: ' + JSON.stringify(err)); + console.error('removeAccount failed, error: ' + JSON.stringify(err)); }); ``` diff --git a/en/application-dev/basic-services/account/manage-distributed-account.md b/en/application-dev/basic-services/account/manage-distributed-account.md index 611e312899e..483003564c4 100644 --- a/en/application-dev/basic-services/account/manage-distributed-account.md +++ b/en/application-dev/basic-services/account/manage-distributed-account.md @@ -38,7 +38,7 @@ You can use the [distributed account SDK](../../reference/apis-basic-services-ki distributedAccountAbility.setOsAccountDistributedInfo(distributedInfo).then(() => { console.log('setOsAccountDistributedInfo successfully'); }).catch((err: BusinessError) => { - console.log('setOsAccountDistributedInfo exception: ' + JSON.stringify(err)); + console.error('setOsAccountDistributedInfo exception: ' + JSON.stringify(err)); }); ``` @@ -48,7 +48,7 @@ You can use the [distributed account SDK](../../reference/apis-basic-services-ki distributedAccountAbility.getOsAccountDistributedInfo().then((data: distributedAccount.DistributedInfo) => { console.log('distributed information: ' + JSON.stringify(data)); }).catch((err: BusinessError) => { - console.log('getOsAccountDistributedInfo exception: ' + JSON.stringify(err)); + console.error('getOsAccountDistributedInfo exception: ' + JSON.stringify(err)); }); ``` @@ -72,7 +72,7 @@ You can use the [distributed account SDK](../../reference/apis-basic-services-ki distributedAccountAbility.setOsAccountDistributedInfo(distributedInfo).then(() => { console.log('setOsAccountDistributedInfo successfully'); }).catch((err: BusinessError) => { - console.log('setOsAccountDistributedInfo exception: ' + JSON.stringify(err)); + console.error('setOsAccountDistributedInfo exception: ' + JSON.stringify(err)); }); ``` @@ -97,7 +97,7 @@ You can use the [distributed account SDK](../../reference/apis-basic-services-ki distributedAccountAbility.setOsAccountDistributedInfoByLocalId(localId, distributedInfo).then(() => { console.log('setOsAccountDistributedInfoByLocalId successfully'); }).catch((err: BusinessError) => { - console.log('setOsAccountDistributedInfoByLocalId exception: ' + JSON.stringify(err)); + console.error('setOsAccountDistributedInfoByLocalId exception: ' + JSON.stringify(err)); }); ``` @@ -107,7 +107,7 @@ You can use the [distributed account SDK](../../reference/apis-basic-services-ki distributedAccountAbility.getOsAccountDistributedInfoByLocalId(localId).then((data: distributedAccount.DistributedInfo) => { console.log('distributed information: ' + JSON.stringify(data)); }).catch((err: BusinessError) => { - console.log('getOsAccountDistributedInfoByLocalId exception: ' + JSON.stringify(err)); + console.error('getOsAccountDistributedInfoByLocalId exception: ' + JSON.stringify(err)); }); ``` @@ -132,6 +132,6 @@ You can use the [distributed account SDK](../../reference/apis-basic-services-ki distributedAccountAbility.setOsAccountDistributedInfoByLocalId(localId, distributedInfo).then(() => { console.log('setOsAccountDistributedInfoByLocalId successfully'); }).catch((err: BusinessError) => { - console.log('setOsAccountDistributedInfoByLocalId exception: ' + JSON.stringify(err)); + console.error('setOsAccountDistributedInfoByLocalId exception: ' + JSON.stringify(err)); }); ``` diff --git a/en/application-dev/basic-services/account/manage-domain-account.md b/en/application-dev/basic-services/account/manage-domain-account.md index 9a681309983..60d0950f20e 100644 --- a/en/application-dev/basic-services/account/manage-domain-account.md +++ b/en/application-dev/basic-services/account/manage-domain-account.md @@ -38,7 +38,11 @@ Before adding a domain account, the user may need to check whether the domain ac 2. Use [hasAccount](../../reference/apis-basic-services-kit/js-apis-osAccount-sys.md#hasaccount10) to check whether the domain account exists. ```ts - let isAccountExisted: boolean = await osAccount.DomainAccountManager.hasAccount(domainAccountInfo); + osAccount.DomainAccountManager.hasAccount(domainAccountInfo).then((isAccountExisted: boolean)=>{ + console.log('execute hasAccount successfully, isAccountExisted:' + JSON.stringify(isAccountExisted)); + }).catch((err: BusinessError)=>{ + console.error('execute hasAccount err:' + JSON.stringify(err)); + }); ``` ## Adding a Domain Account @@ -62,11 +66,14 @@ The user can add a domain account in **Settings** to allow the domain account us try { osAccountMgr.createOsAccountForDomain(osAccount.OsAccountType.NORMAL, domainInfo, (err: BusinessError, osAccountInfo: osAccount.OsAccountInfo)=>{ - console.log('createOsAccountForDomain err:' + JSON.stringify(err)); - console.log('createOsAccountForDomain osAccountInfo:' + JSON.stringify(osAccountInfo)); + if (err) { + console.error('createOsAccountForDomain exception:' + JSON.stringify(err)); + } else { + console.log('createOsAccountForDomain osAccountInfo:' + JSON.stringify(osAccountInfo)); + } }); } catch (e) { - console.log('createOsAccountForDomain exception: ' + JSON.stringify(e)); + console.error('createOsAccountForDomain exception: ' + JSON.stringify(e)); } ``` @@ -88,7 +95,7 @@ The user can remove the domain account that is not required. Since a domain acco try { localId = await osAccountMgr.getOsAccountLocalIdForDomain(domainInfo); } catch (err) { - console.log('getOsAccountLocalIdForDomain exception: ' + JSON.stringify(err)); + console.error('getOsAccountLocalIdForDomain exception: ' + JSON.stringify(err)); } ``` @@ -98,13 +105,13 @@ The user can remove the domain account that is not required. Since a domain acco try { osAccountMgr.removeOsAccount(localId, (err: BusinessError)=>{ if (err) { - console.log('removeOsAccount failed, error: ' + JSON.stringify(err)); + console.error('removeOsAccount failed, error: ' + JSON.stringify(err)); } else { console.log('removeOsAccount successfully'); } }); } catch (err) { - console.log('removeOsAccount exception: ' + JSON.stringify(err)); + console.error('removeOsAccount exception: ' + JSON.stringify(err)); } ``` @@ -130,12 +137,12 @@ After passing the authentication, the user can query their own or others' domain osAccount.DomainAccountManager.getAccountInfo(options, (err: BusinessError, result: osAccount.DomainAccountInfo) => { if (err) { - console.log('call getAccountInfo failed, error: ' + JSON.stringify(err)); + console.error('call getAccountInfo failed, error: ' + JSON.stringify(err)); } else { console.log('getAccountInfo result: ' + result); } }); } catch (err) { - console.log('getAccountInfo exception = ' + JSON.stringify(err)); + console.error('getAccountInfo exception = ' + JSON.stringify(err)); } ``` diff --git a/en/application-dev/basic-services/account/manage-domain-plugin.md b/en/application-dev/basic-services/account/manage-domain-plugin.md index e77c33296ba..e1617a820b3 100644 --- a/en/application-dev/basic-services/account/manage-domain-plugin.md +++ b/en/application-dev/basic-services/account/manage-domain-plugin.md @@ -14,7 +14,7 @@ The system provides APIs for registering and unregistering a domain account plug import { osAccount, AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; ``` -3. Obtains an **AccountManager** instance. +3. Obtain an **AccountManager** instance. ```ts let accountMgr = osAccount.getAccountManager() @@ -155,7 +155,7 @@ The domain account plugin prototype is [DomainPlugin](../../reference/apis-basic osAccount.DomainAccountManager.registerPlugin(plugin) console.info("registerPlugin success") } catch (err) { - console.info("registerPlugin err: " + JSON.stringify(err)); + console.error("registerPlugin err: " + JSON.stringify(err)); } ``` @@ -163,13 +163,13 @@ The domain account plugin prototype is [DomainPlugin](../../reference/apis-basic Use [unregisterPlugin](../../reference/apis-basic-services-kit/js-apis-osAccount-sys.md#unregisterplugin9) to unregister a domain account plugin that is not required. -**Example** +**Procedure** ```ts try { osAccount.DomainAccountManager.unregisterPlugin(); console.log('unregisterPlugin success.'); } catch(err) { - console.log('unregisterPlugin err:' + JSON.stringify(err)); + console.error('unregisterPlugin err:' + JSON.stringify(err)); } ``` diff --git a/en/application-dev/basic-services/account/manage-os-account.md b/en/application-dev/basic-services/account/manage-os-account.md index d6a7b56b5c9..64f59d1deca 100644 --- a/en/application-dev/basic-services/account/manage-os-account.md +++ b/en/application-dev/basic-services/account/manage-os-account.md @@ -12,7 +12,7 @@ Currently, only the following types of system accounts can be created: | ADMIN | 0 | Administrator account.| | NORMAL | 1 | Normal account. | | GUEST | 2 | Guest account. | -| PRIVATE12+ | 1024 | Private account. | +| PRIVATE12+ | 1024 | Private account. | ### Account Information @@ -110,7 +110,7 @@ Change the profile photo and nickname of a system account as required. let newName: string = 'Tom'; accountManager.setOsAccountName(localId, newName, (err: BusinessError) => { if (err) { - console.log('setOsAccountName failed, error: ' + JSON.stringify(err)); + console.error('setOsAccountName failed, error: ' + JSON.stringify(err)); } else { console.log('setOsAccountName successfully'); } @@ -148,7 +148,7 @@ Use [removeOsAccount](../../reference/apis-basic-services-kit/js-apis-osAccount- let localId: number = 101; accountManager.removeOsAccount(localId, (err: BusinessError)=>{ if (err) { - console.log('removeOsAccount failed, error: ' + JSON.stringify(err)); + console.error('removeOsAccount failed, error: ' + JSON.stringify(err)); } else { console.log('removeOsAccount successfully'); } diff --git a/en/application-dev/basic-services/basic-services-kit-overview.md b/en/application-dev/basic-services/basic-services-kit-overview.md index 95201066ac5..a2020ebb732 100644 --- a/en/application-dev/basic-services/basic-services-kit-overview.md +++ b/en/application-dev/basic-services/basic-services-kit-overview.md @@ -4,8 +4,8 @@ Basic Services Kit provides basic capabilities for application developers, from ## When to Use -Basic Services Kit is typically used in the following scenarios: - +Basic Services Kit is typically used in the following: + - Pasteboard read/write - Intra-device copy and paste: For example, copy a piece of text in application A and paste it to another application. @@ -43,7 +43,7 @@ Depending on different use cases, this kit provides the following capabilities: - [USB management](../reference/apis-basic-services-kit/js-apis-usbManager.md): provides USB device management capabilities, including USB device list query, bulk data transfer, control transfer, and permission control. For details about the development guide, see [USB Service Development Overview](usb/usbManager/usbHost-overview.md). - Others: - - [App account management](../reference/apis-basic-services-kit/js-apis-appAccount.md): provides application account management and data management capabilities. For details, see [Managing App Accounts](account/manage-application-account.md). + - [Application account management](../reference/apis-basic-services-kit/js-apis-appAccount.md): provides application account management and data management capabilities. For details, see [Managing Application Accounts](account/manage-application-account.md). - [Public callback information](../reference/apis-basic-services-kit/js-apis-base.md): defines the public callback types of ArkTS APIs, including the common and error callbacks. - [Time and time zone](../reference/apis-basic-services-kit/js-apis-date-time.md): provides APIs for obtaining the system time and time zone. diff --git a/en/application-dev/basic-services/common-event/native-common-event-unsubscription.md b/en/application-dev/basic-services/common-event/native-common-event-unsubscription.md index 00dfec282f9..457415b34f3 100644 --- a/en/application-dev/basic-services/common-event/native-common-event-unsubscription.md +++ b/en/application-dev/basic-services/common-event/native-common-event-unsubscription.md @@ -11,7 +11,7 @@ For details about the APIs, see [CommonEvent](../../reference/apis-basic-service | API | Description | | ------------------------------------ | ---------------------------------------------------------------- | -|[CommonEvent_ErrCode OH_CommonEvent_UnSubscribe(const CommonEvent_Subscriber* subscriber)](../../reference/apis-basic-services-kit/capi-common-event.md#oh_commonevent_unsubscribe)|Creates the subscriber information.| +|[CommonEvent_ErrCode OH_CommonEvent_UnSubscribe(const CommonEvent_Subscriber* subscriber)](../../reference/apis-basic-services-kit/capi-common-event.md#oh_commonevent_unsubscribe)|Unsubscribe from a common event.| ## How to Develop diff --git a/en/application-dev/basic-services/common-event/native-use-pasteboard.md b/en/application-dev/basic-services/common-event/native-use-pasteboard.md new file mode 100644 index 00000000000..4ed5a1e623f --- /dev/null +++ b/en/application-dev/basic-services/common-event/native-use-pasteboard.md @@ -0,0 +1,141 @@ +# Using the Pasteboard to Copy and Paste (C/C++) + +## When to Use + +The pasteboard allows you to copy and paste data of the plain text, hypertext, and URI. + +## Basic Concepts + +- **OH_PasteboardObserver**: pasteboard observer object, which is used to listen for data changes on the pasteboard. +- **OH_Pasteboard**: pasteboard object, which is used to query and write. +- [**OH_UdmfData**](../../reference/apis-arkdata/capi-oh-udmfdata.md#oh_udmfdata): unified data object. + +## Constraints + +- The pasteboard content, including system service metadata and application settings, has a maximum size of 128 MB by default. For PCs/2-in-1 devices, the maximum size can be changed through system settings, with a valid range from 128 MB to 2 GB. +- To ensure the accuracy of the pasteboard data, only one copy can be performed at a time. +- Currently, supported data types include **OH_UdsPlainText** (plain text), **OH_UdsHtml** (hypertext markup language), **OH_UdsFileUri** (file URI). **OH_UdsPixelMap** (pixel map), **OH_UdsHyperlink** (hyperlink), **OH_UdsAppItem** (application icon), and custom type. The data types supported by JS APIs are different from those supported by NDK APIs. You need to match the data types with the corresponding APIs during usage. For details, see [Using the Pasteboard to Copy and Paste](../pasteboard/use_pasteboard_to_copy_and_paste.md). +- When you copy and paste data of a custom type, the specified type name cannot be the same as an existing one. +- Since API version 12, [permission control](get-pastedata-permission-guidelines.md) is added to the pasteboard reading API to enhance user privacy protection. +- The copy and paste APIs, [setUnifiedData](../../reference/apis-basic-services-kit/js-apis-pasteboard.md#setunifieddata12) and [getUnifiedData](../../reference/apis-basic-services-kit/js-apis-pasteboard.md#getunifieddata12), added in API version 12 are independent of the **OH_Pasteboard_SetData** and **OH_Pasteboard_GetData** APIs mentioned in this topic. Use the corresponding APIs when writing and reading data. + +## Available APIs + +For details about more APIs and their usage, see [Pasteboard](../../reference/apis-basic-services-kit/capi-pasteboard.md). + +| API | Description | +| ------------------------------------------------------------ | ------------------------------------------------------- | +| OH_PasteboardObserver* OH_PasteboardObserver_Create() | Creates a pasteboard observer object. | +| OH_PasteboardObserver_Destroy(OH_PasteboardObserver* observer) | Destroys the pasteboard observer object. | +| int OH_PasteboardObserver_SetData(OH_PasteboardObserver* observer, void* context, const Pasteboard_Notify callback, const Pasteboard_Finalize finalize) | Sets the callback used to return data changes to the pasteboard observer object. | +| OH_Pasteboard* OH_Pasteboard_Create() | Creates a pasteboard instance. | +| void OH_Pasteboard_Destroy(OH_Pasteboard* pasteboard) | Destroys the pasteboard instance. | +| int OH_Pasteboard_Subscribe(OH_Pasteboard* pasteboard, int type, const OH_PasteboardObserver* observer) | Subscribes to the pasteboard observer. | +| int OH_Pasteboard_Unsubscribe(OH_Pasteboard* pasteboard, int type, const OH_PasteboardObserver* observer) | Unsubscribes from the pasteboard observer. | +| bool OH_Pasteboard_IsRemoteData(OH_Pasteboard* pasteboard) | Checks whether the pasteboard data comes from remote devices. | +| int OH_Pasteboard_GetDataSource(OH_Pasteboard* pasteboard, char* source, unsigned int len) | Obtains the pasteboard data source. | +| bool OH_Pasteboard_HasType(OH_Pasteboard* pasteboard, const char* type) | Checks whether the pasteboard contains data of the specified type. | +| bool OH_Pasteboard_HasData(OH_Pasteboard* pasteboard) | Checks whether the pasteboard contains data. | +| OH_UdmfData* OH_Pasteboard_GetData(OH_Pasteboard* pasteboard, int* status) | Obtains data from the pasteboard. | +| int OH_Pasteboard_SetData(OH_Pasteboard* pasteboard, OH_UdmfData* data) | Writes data to the pasteboard. | +| int OH_Pasteboard_ClearData(OH_Pasteboard* pasteboard) | Clears data from the pasteboard. | +| void (\*Pasteboard_Notify)(void\* context, Pasteboard_NotifyType type) | Notifies data changes in the pasteboard. | +| void (\*Pasteboard_Finalize)(void\* context) | Releases context resources when the pasteboard observer object is destroyed.| + +## How to Develop + +1. Add dynamic link libraries. + + ```CMake + # Add the following libraries to **CMakeLists.txt**. + libudmf.so + libpasteboard.so + ``` + +2. Include header files. + + ```c + #include + #include + #include + #include + ``` + +3. Define the callback for listening for pasteboard data changes. + + ```c + // Define the callback for notifying data changes in the pasteboard. + static void Pasteboard_Notify_impl2(void* context, Pasteboard_NotifyType type) + { + printf("Pasteboard_NotifyType, type: %d", type); + } + // Define the callback for notifying when the pasteboard observer object is destroyed. + static void Pasteboard_Finalize_impl2(void* context) + { + printf("callback: Pasteboard_Finalize"); + } + ``` + +4. Subscribe to the pasteboard observer. + + ```c + // 1. Create a pasteboard instance. + OH_Pasteboard* pasteboard = OH_Pasteboard_Create(); + // 2. Create a pasteboard observer instance. + OH_PasteboardObserver* observer = OH_PasteboardObserver_Create(); + // 3. Set two callbacks to the pasteboard observer instance. + OH_PasteboardObserver_SetData(observer, (void* )pasteboard, Pasteboard_Notify_impl2, Pasteboard_Finalize_impl2); + // 4. Subscribe to local data changes on the pasteboard. + OH_Pasteboard_Subscribe(pasteboard, NOTIFY_LOCAL_DATA_CHANGE, observer); + ``` + +5. Write data to the pasteboard. + + ```c + // 1. Create a pasteboard instance. + OH_Pasteboard* pasteboard = OH_Pasteboard_Create(); + + // 2. Create an OH_UdmfRecord object and add text data to it. + OH_UdsPlainText* plainText = OH_UdsPlainText_Create(); + OH_UdsPlainText_SetContent(plainText, "Hello world!"); + OH_UdmfRecord* record = OH_UdmfRecord_Create(); + OH_UdmfRecord_AddPlainText(record, plainText); + + // 3. Create an OH_UdmfData object and add OH_UdmfRecord to it. + OH_UdmfData* data = OH_UdmfData_Create(); + OH_UdmfData_AddRecord(data, record); + + // 4. Write data to the pasteboard. + OH_Pasteboard_SetData(pasteboard, data); + + // 5. Destroy the pointer when the object is no longer required. + OH_UdsPlainText_Destroy(plainText); + OH_UdmfRecord_Destroy(record); + OH_UdmfData_Destroy(data); + OH_Pasteboard_Destroy(pasteboard); + ``` + +6. Read data from the pasteboard. + + ```c + // 1. Create a pasteboard instance. + OH_Pasteboard* pasteboard = OH_Pasteboard_Create(); + // 2. Check whether the pasteboard contains text data. + bool hasPlainTextData = OH_Pasteboard_HasType(pasteboard, "text/plain"); + if (hasPlainTextData) { + // 3. Obtain the unified data OH_UdmfData from the pasteboard. + int ret = 0; + OH_UdmfData* udmfData = OH_Pasteboard_GetData(pasteboard, &ret); + // 4. Obtain the first data record from OH_UdmfData. + OH_UdmfRecord* record = OH_UdmfData_GetRecord(udmfData, 0); + // 5. Obtain the text data from the data record. + OH_UdsPlainText* plainText = OH_UdsPlainText_Create(); + OH_UdmfRecord_GetPlainText(record, plainText); + const char* content = OH_UdsPlainText_GetContent(plainText); + printf("Get plain text success. content: %s", content); + // 5. Destroy the pointer when the object is no longer required. + OH_UdsPlainText_Destroy(plainText); + OH_UdmfData_Destroy(udmfData); + } + OH_Pasteboard_Destroy(pasteboard); + ``` diff --git a/en/application-dev/basic-services/compress/deflate-and-inflate.md b/en/application-dev/basic-services/compress/deflate-and-inflate.md index 98b54ad12db..d16dad667b9 100644 --- a/en/application-dev/basic-services/compress/deflate-and-inflate.md +++ b/en/application-dev/basic-services/compress/deflate-and-inflate.md @@ -23,8 +23,8 @@ For details about more APIs and their usage, see [Zip](../../reference/apis-basi Create a test file **data.txt** in the application sandbox directory and write data for testing. The sample code is as follows: ```ts - import { fileIo as fs} from '@kit.CoreFileKit' - import { BusinessError, zlib } from '@kit.BasicServicesKit' + import { fileIo as fs} from '@kit.CoreFileKit'; + import { BusinessError, zlib } from '@kit.BasicServicesKit'; @Entry @Component @@ -36,7 +36,7 @@ Create a test file **data.txt** in the application sandbox directory and write d Column() { // Create the data.txt file and write test data. Button('Create a test file data.txt').onClick(() => { - let path = getContext(this).filesDir; + let path = this.getUIContext()?.getHostContext()?.filesDir; // Create the data.txt file. let inFile = fs.openSync(path + '/data.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); // Write test data. @@ -63,8 +63,8 @@ Create a test file **data.txt** in the application sandbox directory and write d Use [zlib.compressFile()](../../reference/apis-basic-services-kit/js-apis-zlib.md#zlibcompressfile9-1) to compress the **data.txt** into to the **data.zip** file, and use [zlib.decompressFile()](../../reference/apis-basic-services-kit/js-apis-zlib.md#zlibdecompressfile9-1) to decompress the .zip file to the application sandbox directory. The sample code is as follows: ```ts - import { fileIo as fs} from '@kit.CoreFileKit' - import { BusinessError, zlib } from '@kit.BasicServicesKit' + import { fileIo as fs} from '@kit.CoreFileKit'; + import { BusinessError, zlib } from '@kit.BasicServicesKit'; @Entry @Component @@ -73,7 +73,7 @@ Use [zlib.compressFile()](../../reference/apis-basic-services-kit/js-apis-zlib.m Row() { // Example 1: Compress the data.txt file into the data.zip file. Button('compressFile').onClick(() => { - let path = getContext(this).filesDir; + let path = this.getUIContext()?.getHostContext()?.filesDir; let inFile = path + '/data.txt'; let outFile = path + '/data.zip'; let options: zlib.Options = {}; @@ -86,7 +86,7 @@ Use [zlib.compressFile()](../../reference/apis-basic-services-kit/js-apis-zlib.m // Example 2: Decompress the data.zip file to the application sandbox directory. Button('decompressFile').onClick(() => { - let path = getContext(this).filesDir; + let path = this.getUIContext()?.getHostContext()?.filesDir; let inFile = path + '/data.zip'; let outFile = path; let options: zlib.Options = {}; @@ -108,8 +108,8 @@ Use [zlib.compressFile()](../../reference/apis-basic-services-kit/js-apis-zlib.m For data in a buffer with a known size, use [compress()](../../reference/apis-basic-services-kit/js-apis-zlib.md#compress12) to compress the data into a destination buffer, [compressBound()](../../reference/apis-basic-services-kit/js-apis-zlib.md#compressbound12) to calculate the upper limit of the compression size of the destination buffer, and [uncompress()](../../reference/apis-basic-services-kit/js-apis-zlib.md#uncompress12) to decompress the buffer that stores the compressed data. To check the size of the destination buffer after decompression, obtain and save the original data size before compression. The sample code is as follows: ```ts - import { fileIo as fs} from '@kit.CoreFileKit' - import { BusinessError, zlib } from '@kit.BasicServicesKit' + import { fileIo as fs} from '@kit.CoreFileKit'; + import { BusinessError, zlib } from '@kit.BasicServicesKit'; @Entry @Component @@ -120,7 +120,7 @@ For data in a buffer with a known size, use [compress()](../../reference/apis-ba Row() { // Example 1: Read the data.txt file and save it to a buffer. Call the compress API to compress the data in the source buffer to the destination buffer and write the content in the destination buffer to the data.bin file. Button('compress buffer').onClick(() => { - let path = getContext(this).filesDir; + let path = this.getUIContext()?.getHostContext()?.filesDir; let inFile = fs.openSync(path + '/data.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); let outFile = fs.openSync(path + '/data.bin', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); // Read the content of the data.txt file and save the content to the buffer inBuf. @@ -156,7 +156,7 @@ For data in a buffer with a known size, use [compress()](../../reference/apis-ba // Example 2: Read the compressed data in the data.bin file and save it to a buffer. Call the uncompress API to decompress the data in the source buffer to the destination buffer and write the content in the destination buffer to the data.txt file. Button('uncompress buffer').onClick(() => { - let path = getContext(this).filesDir; + let path = this.getUIContext()?.getHostContext()?.filesDir; let inFile = fs.openSync(path + '/data.bin', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); let outFile = fs.openSync(path + '/data.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); // Read the compressed data in the data.bin file and save the data to the buffer inBuf. @@ -189,13 +189,13 @@ For data in a buffer with a known size, use [compress()](../../reference/apis-ba } ``` -### Compressing and Decompressing Buffers of Unknown Sizes +### Compressing and Decompressing Buffers of Unknown Sizes (.zlib Format) For data in a buffer with an unknown size, use [deflate()](../../reference/apis-basic-services-kit/js-apis-zlib.md#deflate12) to compress the data read from an original input stream and [inflate()](../../reference/apis-basic-services-kit/js-apis-zlib.md#inflate12) to decompress the data read from a compressed input stream. The sample code is as follows: ```ts - import { fileIo as fs} from '@kit.CoreFileKit' - import { BusinessError, zlib } from '@kit.BasicServicesKit' + import { fileIo as fs} from '@kit.CoreFileKit'; + import { BusinessError, zlib } from '@kit.BasicServicesKit'; @Entry @Component @@ -204,7 +204,7 @@ For data in a buffer with an unknown size, use [deflate()](../../reference/apis- Row() { // Example 1: Continuously read data from a file for compression. Button('deflateFile').onClick(() => { - let path = getContext(this).filesDir; + let path = this.getUIContext()?.getHostContext()?.filesDir; let inFile = fs.openSync(path + '/data.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); let outFile = fs.openSync(path + '/data.bin', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); deflateFile(inFile, outFile).then(() => { @@ -216,7 +216,7 @@ For data in a buffer with an unknown size, use [deflate()](../../reference/apis- // Example 2: Continuously read compressed data from the file for decompression. Button('inflateFile').onClick(() => { - let path = getContext(this).filesDir; + let path = this.getUIContext()?.getHostContext()?.filesDir; let inFile = fs.openSync(path + '/data.bin', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); let outFile = fs.openSync(path + '/data.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); inflateFile(inFile, outFile).then(() => { @@ -338,6 +338,159 @@ For data in a buffer with an unknown size, use [deflate()](../../reference/apis- } ``` +### Compressing and Decompressing Buffers of Unknown Sizes (.gzip Format) + +For data in a buffer with an unknown size, use [deflate()](../../reference/apis-basic-services-kit/js-apis-zlib.md#deflate12) to compress the data read from an original input stream and [inflate()](../../reference/apis-basic-services-kit/js-apis-zlib.md#inflate12) to decompress the data read from a compressed input stream. The sample code is as follows: + + ```ts + import { fileIo as fs} from '@kit.CoreFileKit'; + import { BusinessError, zlib } from '@kit.BasicServicesKit'; + + @Entry + @Component + struct Index { + build() { + Row() { + // Example 1: Continuously read data from a file for compression. + Button('deflateGzipFile').onClick(() => { + let path = this.getUIContext()?.getHostContext()?.filesDir; + let inFile = fs.openSync(path + '/data.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); + let outFile = fs.openSync(path + '/data.gz', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); + deflateGzipFile(inFile, outFile).then(() => { + console.info('deflateGzipFile success'); + fs.closeSync(inFile.fd); + fs.closeSync(outFile.fd); + }) + }) + + // Example 2: Continuously read compressed data from the file for decompression. + Button('inflateGzipFile').onClick(() => { + let path = this.getUIContext()?.getHostContext()?.filesDir; + let inFile = fs.openSync(path + '/data.gz', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); + let outFile = fs.openSync(path + '/data.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); + inflateGzipFile(inFile, outFile).then(() => { + console.info('deflateGzipFile success'); + fs.closeSync(inFile.fd); + fs.closeSync(outFile.fd); + }) + }) + } + .height('100%') + .width('100%') + } + } + + // Continuously read data from a file, compress the data, and write the data to another file. + async function deflateGzipFile(src: fs.File, dest: fs.File) { + let flush = zlib.CompressFlushMode.NO_FLUSH; + let strm: zlib.ZStream = {}; // Initialize a compression stream. + const BUFLEN = 4096; + let inBuf = new ArrayBuffer(BUFLEN); // Initialize an input buffer. + let outBuf = new ArrayBuffer(BUFLEN); // Initialize an output buffer. + // Create a compressed object instance. + let zip = zlib.createZipSync(); + // Initialize the stream status. If windowBits is greater than 15, the .gzip format is used. + let windowBits = 15 + 16; + let initStatus = zip.deflateInit2(strm, zlib.CompressLevel.COMPRESS_LEVEL_BEST_SPEED, + zlib.CompressMethod.DEFLATED, windowBits, zlib.MemLevel.MEM_LEVEL_DEFAULT, + zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY); + console.info('deflateInit2 ret: ' + (await initStatus).valueOf()); + do { + // Read data from a file to a buffer. + let readLen = fs.readSync(src.fd, inBuf); + console.info("readSync readLen: " + readLen); + flush = readLen == 0 ? zlib.CompressFlushMode.FINISH : zlib.CompressFlushMode.NO_FLUSH; + // Set the input buffer. + strm.availableIn = readLen; + strm.nextIn = inBuf; + do { + // Set the output buffer. + strm.availableOut = BUFLEN; + strm.nextOut = outBuf; + try { + // Compress the data in the input buffer to the output buffer. + let deflateStatus = zip.deflate(strm, flush); + console.info('deflate ret: ' + (await deflateStatus).valueOf()); + // Update the stream status. + let innerStrm = zip.getZStream(); + strm.availableIn = (await innerStrm).availableIn; + strm.nextIn = (await innerStrm).nextIn; + strm.availableOut = (await innerStrm).availableOut; + strm.nextOut = (await innerStrm).nextOut; + strm.totalIn = (await innerStrm).totalIn; + strm.totalOut = (await innerStrm).totalOut; + + if (strm.availableOut != undefined) { + // Write the compressed data to the output file. + let have = BUFLEN - strm.availableOut; + let writeLen = fs.writeSync(dest.fd, outBuf, { length: have }); + console.info(`writeSync writeLen: ${writeLen}`); + } + } catch (err) { + console.error('deflate err: ' + JSON.stringify(err)); + } + } while (strm.availableOut == 0); // Compress the remaining data in the input buffer cyclically until all data is compressed. + } while (flush != zlib.CompressFlushMode.FINISH); // Read data from the file cyclically until all data is read. + // Release resources. + zip.deflateEnd(strm); + } + + // Continuously read compressed data from a file, decompress the data, and write the data to another file. + async function inflateGzipFile(src: fs.File, dest: fs.File) { + let status: zlib.ReturnStatus = zlib.ReturnStatus.OK; + let strm: zlib.ZStream = {}; // Initialize a compression stream. + const BUFLEN = 4096; + let inBuf = new ArrayBuffer(BUFLEN); // Initialize an input buffer. + let outBuf = new ArrayBuffer(BUFLEN); // Initialize an output buffer. + // Create a compressed object instance. + let zip = zlib.createZipSync(); + // Initialize the stream status. If windowBits is greater than 15, the .gzip format is used. + let windowBits = 15 + 16; + let initStatus = zip.inflateInit2(strm, windowBits); + console.info('inflateInit2 ret: ' + (await initStatus).valueOf()); + do { + // Read the compressed data from the file to the buffer. + let readLen = fs.readSync(src.fd, inBuf); + console.info("readSync readLen: " + readLen); + if (readLen == 0) { + break; + } + // Set the input buffer. + strm.availableIn = readLen; + strm.nextIn = inBuf; + do { + // Set the output buffer. + strm.availableOut = BUFLEN; + strm.nextOut = outBuf; + try { + // Decompress the data in the input buffer to the output buffer. + let inflateStatus = zip.inflate(strm, zlib.CompressFlushMode.NO_FLUSH); + console.info('inflate ret: ' + (await inflateStatus).valueOf()); + // Update the stream status. + let innerStrm = zip.getZStream(); + strm.availableIn = (await innerStrm).availableIn; + strm.nextIn = (await innerStrm).nextIn; + strm.availableOut = (await innerStrm).availableOut; + strm.nextOut = (await innerStrm).nextOut; + strm.totalIn = (await innerStrm).totalIn; + strm.totalOut = (await innerStrm).totalOut; + + if (strm.availableOut != undefined) { + // Write the decompressed data to the output file. + let have = BUFLEN - strm.availableOut; + let writeLen = fs.writeSync(dest.fd, outBuf, { length: have }); + console.info(`writeSync writeLen: ${writeLen}`); + } + } catch (err) { + console.error('inflate err: ' + JSON.stringify(err)); + } + } while (strm.availableOut == 0) // Decompress the remaining data in the input buffer cyclically until all data is decompressed. + } while (status != zlib.ReturnStatus.STREAM_END.valueOf()) // Read data from the file cyclically until all data is read. + // Release resources. + zip.inflateEnd(strm); + } + ``` + ## FAQs 1. 17800005 Incorrect Input Data diff --git a/en/application-dev/basic-services/request/Readme-EN.md b/en/application-dev/basic-services/request/Readme-EN.md index 4a97d96e689..458e98d1608 100644 --- a/en/application-dev/basic-services/request/Readme-EN.md +++ b/en/application-dev/basic-services/request/Readme-EN.md @@ -1,3 +1,3 @@ # Upload and Download -- [Uploading and Downloading Application Files](app-file-upload-download.md) \ No newline at end of file +- [Uploading and Downloading Application Files](app-file-upload-download.md) diff --git a/en/application-dev/basic-services/request/app-file-upload-download.md b/en/application-dev/basic-services/request/app-file-upload-download.md index 1758d0ade14..b4b081c65ec 100644 --- a/en/application-dev/basic-services/request/app-file-upload-download.md +++ b/en/application-dev/basic-services/request/app-file-upload-download.md @@ -2,127 +2,155 @@ This topic describes how to upload an application file to a network server and download a network resource file from a network server to a local application file directory. -## Uploading an Application File +## Uploading Application Files You can use **uploadFile()** in [ohos.request](../../reference/apis-basic-services-kit/js-apis-request.md) to upload local files. The system service agent uploads the files. In API version 12, you can set the address of the agent in **request.agent.create()**. > **NOTE** > -> Currently, only the files in the **cache/** directory (specified by **cacheDir**) can be uploaded. +> Currently, only files in the **cacheDir** directory can be uploaded using **request.uploadFile**; user public files and files in the **cacheDir** directory can be uploaded together using **request.agent**. > > To use **uploadFile()** in **ohos.request**, you need to [declare permissions](../../security/AccessToken/declare-permissions.md): ohos.permission.INTERNET. -The following code demonstrates how to upload files from a cache directory of an application to a network server in two ways: +The following code demonstrates how to upload files from a cache directory of an application to a network server in two approaches: ```ts -// Way 1: Use request.uploadFile. +// Approach 1: Use request.uploadFile. // pages/xxx.ets import { common } from '@kit.AbilityKit'; import fs from '@ohos.file.fs'; import { BusinessError, request } from '@kit.BasicServicesKit'; -// Obtain the application file path. -let context = getContext(this) as common.UIAbilityContext; -let cacheDir = context.cacheDir; - -// Create an application file locally. -let file = fs.openSync(cacheDir + '/test.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); -fs.writeSync(file.fd, 'upload file test'); -fs.closeSync(file); - -// Configure the upload task. -let files: Array = [ -// "internal://cache" in uri corresponds to the cacheDir directory. - { filename: 'test.txt', name: 'test', uri: 'internal://cache/test.txt', type: 'txt' } -] -let data: Array = [{ name: 'name', value: 'value' }]; -let uploadConfig: request.UploadConfig = { - url: 'https://xxx', - header: { - 'key1':'value1', - 'key2':'value2' - }, - method: 'POST', - files: files, - data: data -} +@Entry +@Component +struct Index { + build() { + Row() { + Column() { + Button("Upload").onClick(() => { + // Obtain the application file path. + // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + let cacheDir = context.cacheDir; -// Upload the created application file to the network server. -try { - request.uploadFile(context, uploadConfig) - .then((uploadTask: request.UploadTask) => { - uploadTask.on('complete', (taskStates: Array) => { - for (let i = 0; i < taskStates.length; i++) { - console.info(`upload complete taskState: ${JSON.stringify(taskStates[i])}`); - } - }); - }) - .catch((err: BusinessError) => { - console.error(`Invoke uploadFile failed, code is ${err.code}, message is ${err.message}`); - }) -} catch (error) { - let err: BusinessError = error as BusinessError; - console.error(`Invoke uploadFile failed, code is ${err.code}, message is ${err.message}`); + // Create an application file locally. + let file = fs.openSync(cacheDir + '/test.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); + fs.writeSync(file.fd, 'upload file test'); + fs.closeSync(file); + + // Configure the upload task. + let files: Array = [ + // "internal://cache" in uri corresponds to the cacheDir directory. + { filename: 'test.txt', name: 'test', uri: 'internal://cache/test.txt', type: 'txt' } + ] + let data: Array = [{ name: 'name', value: 'value' }]; + let uploadConfig: request.UploadConfig = { + url: 'https://xxx', + header: { + 'key1':'value1', + 'key2':'value2' + }, + method: 'POST', + files: files, + data: data + } + + // Upload the created application file to the network server. + try { + request.uploadFile(context, uploadConfig) + .then((uploadTask: request.UploadTask) => { + uploadTask.on('complete', (taskStates: Array) => { + for (let i = 0; i < taskStates.length; i++) { + console.info(`upload complete taskState: ${JSON.stringify(taskStates[i])}`); + } + }); + }) + .catch((err: BusinessError) => { + console.error(`Invoke uploadFile failed, code is ${err.code}, message is ${err.message}`); + }) + } catch (error) { + let err: BusinessError = error as BusinessError; + console.error(`Invoke uploadFile failed, code is ${err.code}, message is ${err.message}`); + } + }) + } + } + } } ``` ```ts -// Way 2: Use request.agent. +// Approach 2: Use request.agent. // pages/xxx.ets import { common } from '@kit.AbilityKit'; import fs from '@ohos.file.fs'; import { BusinessError, request } from '@kit.BasicServicesKit'; -// Obtain the application file path. -let context = getContext(this) as common.UIAbilityContext; -let cacheDir = context.cacheDir; - -// Create an application file locally. -let file = fs.openSync(cacheDir + '/test.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); -fs.writeSync(file.fd, 'upload file test'); -fs.closeSync(file); -let attachments: Array = [{ - name: "test", - value: [ - { - filename: "test.txt", - path: "./test.txt", - }, - ] -}]; -let config: request.agent.Config = { - action: request.agent.Action.UPLOAD, - url: 'http://xxx', - mode: request.agent.Mode.FOREGROUND, - overwrite: true, - method: "POST", - headers: { - 'key1':'value1', - 'key2':'value2' - }, - data: attachments, - saveas: "./" -}; -request.agent.create(getContext(), config).then((task: request.agent.Task) => { - task.start((err: BusinessError) => { - if (err) { - console.error(`Failed to start the upload task, Code: ${err.code} message: ${err.message}`); - return; + +@Entry +@Component +struct Index { + build() { + Row() { + Column() { + Button("Upload").onClick(() => { + // Obtain the application file path. + // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + let cacheDir = context.cacheDir; + + // Create an application file locally. + let file = fs.openSync(cacheDir + '/test.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); + fs.writeSync(file.fd, 'upload file test'); + fs.closeSync(file); + let attachments: Array = [{ + name: "test", + value: [ + { + filename: "test.txt", + path: "./test.txt", + }, + ] + }]; + let config: request.agent.Config = { + action: request.agent.Action.UPLOAD, + url: 'http://xxx', + mode: request.agent.Mode.FOREGROUND, + overwrite: true, + method: "POST", + headers: { + 'key1':'value1', + 'key2':'value2' + }, + data: attachments, + saveas: "./" + }; + request.agent.create(context, config).then((task: request.agent.Task) => { + task.start((err: BusinessError) => { + if (err) { + console.error(`Failed to start the upload task, Code: ${err.code} message: ${err.message}`); + return; + } + }); + task.on('progress', async(progress) => { + console.warn(`/Request upload status ${progress.state}, uploaded ${progress.processed}`); + }) + task.on('completed', async() => { + console.warn(`/Request upload completed`); + // This method requires the user to manage the task lifecycle. After the task is complete, call the remove method to release the task object. + request.agent.remove(task.tid); + }) + }).catch((err: BusinessError) => { + console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); + }); + }) + } } - }); - task.on('progress', async(progress) => { - console.warn(`/Request upload status ${progress.state}, uploaded ${progress.processed}`); - }) - task.on('completed', async() => { - console.warn(`/Request upload completed`); - // This method requires the user to manage the task lifecycle. After the task is complete, call the remove method to release the task object. - request.agent.remove(task.tid); - }) -}).catch((err: BusinessError) => { - console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); -}); + } +} + ``` -## Downloading a Network Resource File to an Application Directory +## Downloading Network Resource Files to an Application Directory You can use **downloadFile()** in [ohos.request](../../reference/apis-basic-services-kit/js-apis-request.md) to download network resource files to a local application directory. You can use the [ohos.file.fs](../../reference/apis-core-file-kit/js-apis-file-fs.md) APIs to access the downloaded files. For details, see [Accessing Application Files](../../file-management/app-file-access.md). The system service agent downloads the files. In API version 12, you can set the address of the agent in **request.agent.create()**. @@ -132,10 +160,10 @@ You can use **downloadFile()** in [ohos.request](../../reference/apis-basic-serv > > To use **uploadFile()** in **ohos.request**, you need to [declare permissions](../../security/AccessToken/declare-permissions.md): ohos.permission.INTERNET. -The following code demonstrates how to download files from a network server to an application directory in two ways: +The following code demonstrates how to download files from a network server to an application directory in two approaches: ```ts -// Way 1: Use request.downloadFile. +// Approach 1: Use request.downloadFile. // pages/xxx.ets // Download the network resource file to the local application file directory, and read data from the file. import { common } from '@kit.AbilityKit'; @@ -143,34 +171,47 @@ import fs from '@ohos.file.fs'; import { BusinessError, request } from '@kit.BasicServicesKit'; import { buffer } from '@kit.ArkTS'; -// Obtain the application file path. -let context = getContext(this) as common.UIAbilityContext; -let filesDir = context.filesDir; - -try { - request.downloadFile(context, { - url: 'https://xxxx/xxxx.txt', - filePath: filesDir + '/xxxx.txt' - }).then((downloadTask: request.DownloadTask) => { - downloadTask.on('complete', () => { - console.info('download complete'); - let file = fs.openSync(filesDir + '/xxxx.txt', fs.OpenMode.READ_WRITE); - let arrayBuffer = new ArrayBuffer(1024); - let readLen = fs.readSync(file.fd, arrayBuffer); - let buf = buffer.from(arrayBuffer, 0, readLen); - console.info(`The content of file: ${buf.toString()}`); - fs.closeSync(file); - }) - }).catch((err: BusinessError) => { - console.error(`Invoke downloadTask failed, code is ${err.code}, message is ${err.message}`); - }); -} catch (error) { - let err: BusinessError = error as BusinessError; - console.error(`Invoke downloadFile failed, code is ${err.code}, message is ${err.message}`); +@Entry +@Component +struct Index { + build() { + Row() { + Column() { + Button("Download").onClick(() => { + // Obtain the application file path. + // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + let filesDir = context.filesDir; + + try { + request.downloadFile(context, { + url: 'https://xxxx/xxxx.txt', + filePath: filesDir + '/xxxx.txt' + }).then((downloadTask: request.DownloadTask) => { + downloadTask.on('complete', () => { + console.info('download complete'); + let file = fs.openSync(filesDir + '/xxxx.txt', fs.OpenMode.READ_WRITE); + let arrayBuffer = new ArrayBuffer(1024); + let readLen = fs.readSync(file.fd, arrayBuffer); + let buf = buffer.from(arrayBuffer, 0, readLen); + console.info(`The content of file: ${buf.toString()}`); + fs.closeSync(file); + }) + }).catch((err: BusinessError) => { + console.error(`Invoke downloadTask failed, code is ${err.code}, message is ${err.message}`); + }); + } catch (error) { + let err: BusinessError = error as BusinessError; + console.error(`Invoke downloadFile failed, code is ${err.code}, message is ${err.message}`); + } + }) + } + } + } } ``` ```ts -// Way 2: Use request.agent. +// Approach 2: Use request.agent. // pages/xxx.ets // Download the network resource file to the local application file directory, and read data from the file. import { common } from '@kit.AbilityKit'; @@ -178,49 +219,335 @@ import fs from '@ohos.file.fs'; import { BusinessError, request } from '@kit.BasicServicesKit'; import { buffer } from '@kit.ArkTS'; -// Obtain the application file path. -let context = getContext(this) as common.UIAbilityContext; -let filesDir = context.filesDir; - -let config: request.agent.Config = { - action: request.agent.Action.DOWNLOAD, - url: 'https://xxxx/test.txt', - saveas: 'xxxx.txt', - gauge: true, - overwrite: true, - network: request.agent.Network.WIFI, -}; -request.agent.create(context, config).then((task: request.agent.Task) => { - task.start((err: BusinessError) => { - if (err) { - console.error(`Failed to start the download task, Code: ${err.code} message: ${err.message}`); - return; +@Entry +@Component +struct Index { + build() { + Row() { + Column() { + Button("Download").onClick(() => { + // Obtain the application file path. + // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + let filesDir = context.filesDir; + + let config: request.agent.Config = { + action: request.agent.Action.DOWNLOAD, + url: 'https://xxxx/test.txt', + saveas: 'xxxx.txt', + gauge: true, + overwrite: true, + network: request.agent.Network.WIFI, + }; + request.agent.create(context, config).then((task: request.agent.Task) => { + task.start((err: BusinessError) => { + if (err) { + console.error(`Failed to start the download task, Code: ${err.code} message: ${err.message}`); + return; + } + }); + task.on('progress', async (progress) => { + console.warn(`/Request download status ${progress.state}, downloaded ${progress.processed}`); + }) + task.on('completed', async () => { + console.warn(`/Request download completed`); + let file = fs.openSync(filesDir + '/xxxx.txt', fs.OpenMode.READ_WRITE); + let arrayBuffer = new ArrayBuffer(1024); + let readLen = fs.readSync(file.fd, arrayBuffer); + let buf = buffer.from(arrayBuffer, 0, readLen); + console.info(`The content of file: ${buf.toString()}`); + fs.closeSync(file); + // This method requires the user to manage the task lifecycle. After the task is complete, call the remove method to release the task object. + request.agent.remove(task.tid); + }) + }).catch((err: BusinessError) => { + console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); + }); + }) + } } - }); - task.on('progress', async(progress) => { - console.warn(`/Request download status ${progress.state}, downloaded ${progress.processed}`); - }) - task.on('completed', async() => { - console.warn(`/Request download completed`); - let file = fs.openSync(filesDir + '/xxxx.txt', fs.OpenMode.READ_WRITE); - let arrayBuffer = new ArrayBuffer(1024); - let readLen = fs.readSync(file.fd, arrayBuffer); - let buf = buffer.from(arrayBuffer, 0, readLen); - console.info(`The content of file: ${buf.toString()}`); - fs.closeSync(file); - // This method requires the user to manage the task lifecycle. After the task is complete, call the remove method to release the task object. - request.agent.remove(task.tid); - }) -}).catch((err: BusinessError) => { - console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); -}); + } +} + +``` + +## Downloading Network Resource Files to the User File +You can use the [request.agent](../../reference/apis-basic-services-kit/js-apis-request.md#requestagentcreate10) API of the upload and download module ([ohos.request](../../reference/apis-basic-services-kit/js-apis-request.md)) to download network resource files to the user file. + +### Downloading Documents + +Call the [save()](../../reference/apis-core-file-kit/js-apis-file-picker.md#save) API of [DocumentViewPicker](../../reference/apis-core-file-kit/js-apis-file-picker.md#documentviewpicker) to save a document and obtain the URI of the user file. Use this URI as the value of the **saveas** field of [Config](../../reference/apis-basic-services-kit/js-apis-request.md#config10) to download the document. + +```ts +import { BusinessError, request } from '@kit.BasicServicesKit'; +import { picker } from '@kit.CoreFileKit'; +import { common } from '@kit.AbilityKit'; + +@Entry +@Component +struct Index { + build() { + Row() { + Column() { + Button("Download Document").width("50%").margin({ top: 20 }).height(40).onClick(async () => { + // Create a documentSaveOptions instance. + const documentSaveOptions = new picker.DocumentSaveOptions(); + // (Optional) Name of the file to save. The default value is empty. + documentSaveOptions.newFileNames = ["xxxx.txt"]; + // (Optional) Type of the document to save. The value is in ['Description|File name extensions'] format. To save all files, use 'All files (*.*)|.*'. If there are multiple file name extensions (a maximum of 100 extensions can be filtered), the first one is used by default. If this parameter is not specified, no extension is filtered by default. + documentSaveOptions.fileSuffixChoices = ['Document|.txt', '.pdf']; + + let uri: string = ''; + // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + const documentViewPicker = new picker.DocumentViewPicker(context); + await documentViewPicker.save(documentSaveOptions).then((documentSaveResult: Array) => { + uri = documentSaveResult[0]; + console.info('DocumentViewPicker.save to file succeed and uri is:' + uri); + }).catch((err: BusinessError) => { + console.error(`Invoke documentViewPicker.save failed, code is ${err.code}, message is ${err.message}`); + }) + if (uri != '') { + let config: request.agent.Config = { + action: request.agent.Action.DOWNLOAD, + url: 'https://xxxx/xxxx.txt', + // The saveas field specifies the URI of the file saved by DocumentViewPicker. + saveas: uri, + gauge: true, + // The overwrite field must be set to true. + overwrite: true, + network: request.agent.Network.WIFI, + // The mode field must be set to request.agent.Mode.FOREGROUND. + mode: request.agent.Mode.FOREGROUND, + }; + try { + request.agent.create(context, config).then((task: request.agent.Task) => { + task.start((err: BusinessError) => { + if (err) { + console.error(`Failed to start the download task, Code: ${err.code} message: ${err.message}`); + return; + } + }); + task.on('progress', async (progress) => { + console.warn(`Request download status ${progress.state}, downloaded ${progress.processed}`); + }) + task.on('completed', async (progress) => { + console.warn('Request download completed, ' + JSON.stringify(progress)); + // This method requires the user to manage the task lifecycle. After the task is complete, call the remove method to release the task object. + request.agent.remove(task.tid); + }) + }).catch((err: BusinessError) => { + console.error(`Failed to operate a download task, Code: ${err.code}, message: ${err.message}`); + }); + } catch (err) { + console.error(`Failed to create a download task, err: ${err}`); + } + } + }) + } + } + } +} +``` + +### Downloading Audios + +Call the [save()](../../reference/apis-core-file-kit/js-apis-file-picker.md#save-3) API of [AudioViewPicker](../../reference/apis-core-file-kit/js-apis-file-picker.md#audioviewpicker) to save an audio and obtain the URI of the user file. Use this URI as the value of the **saveas** field of [Config](../../reference/apis-basic-services-kit/js-apis-request.md#config10) to download the audio. + +```ts +import { BusinessError, request } from '@kit.BasicServicesKit'; +import { picker } from '@kit.CoreFileKit'; +import { common } from '@kit.AbilityKit'; + +@Entry +@Component +struct Index { + build() { + Row() { + Column() { + Button("Download Audio").width("50%").margin({ top: 20 }).height(40).onClick(async () => { + // Create a documentSaveOptions instance. + const audioSaveOptions = new picker.AudioSaveOptions(); + // (Optional) Name of the file to save. The default value is empty. + audioSaveOptions.newFileNames = ['xxxx.mp3']; + + let uri: string = ''; + // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + const audioViewPicker = new picker.AudioViewPicker(context); + await audioViewPicker.save(audioSaveOptions).then((audioSelectResult: Array) => { + uri = audioSelectResult[0]; + console.info('AudioViewPicker.save to file succeed and uri is:' + uri); + }).catch((err: BusinessError) => { + console.error(`Invoke audioViewPicker.save failed, code is ${err.code}, message is ${err.message}`); + }) + if (uri != '') { + let config: request.agent.Config = { + action: request.agent.Action.DOWNLOAD, + url: 'https://xxxx/xxxx.mp3', + // The saveas field specifies the URI of the file saved by AudioViewPicker. + saveas: uri, + gauge: true, + // The overwrite field must be set to true. + overwrite: true, + network: request.agent.Network.WIFI, + // The mode field must be set to request.agent.Mode.FOREGROUND. + mode: request.agent.Mode.FOREGROUND, + }; + try { + request.agent.create(context, config).then((task: request.agent.Task) => { + task.start((err: BusinessError) => { + if (err) { + console.error(`Failed to start the download task, Code: ${err.code} message: ${err.message}`); + return; + } + }); + task.on('progress', async (progress) => { + console.warn(`Request download status ${progress.state}, downloaded ${progress.processed}`); + }) + task.on('completed', async (progress) => { + console.warn('Request download completed, ' + JSON.stringify(progress)); + // This method requires the user to manage the task lifecycle. After the task is complete, call the remove method to release the task object. + request.agent.remove(task.tid); + }) + }).catch((err: BusinessError) => { + console.error(`Failed to operate a download task, Code: ${err.code}, message: ${err.message}`); + }); + } catch (err) { + console.error(`Failed to create a download task, err: ${err}`); + } + } + }) + } + } + } +} +``` + +### Downloading Images or Videos + +Call the [createAsset()](../../reference/apis-media-library-kit/js-apis-photoAccessHelper.md#createasset-2) API of [PhotoAccessHelper](../../reference/apis-media-library-kit/js-apis-photoAccessHelper.md) to create a media file and obtain the URI of the user file. Use this URI as the value of the **saveas** field of [Config](../../reference/apis-basic-services-kit/js-apis-request.md#config10) to download the media file. + +Permission required: [ohos.permission.WRITE_IMAGEVIDEO](../../security/AccessToken/permissions-for-all-user.md#ohospermissionwrite_media) + +[ohos.permission.WRITE_IMAGEVIDEO](../../security/AccessToken/permissions-for-all-user.md#ohospermissionwrite_media) is a [restricted permission](../../security/AccessToken/restricted-permissions.md) of the [system_basic](../../security/AccessToken/app-permission-mgmt-overview.md#basic-concepts-in-the-permission-mechanism) level. If the normal-level application needs to request this permission, its APL level must be declared as system_basic or higher. In addition, you should [request the user_grant permission from users](../../security/AccessToken/request-user-authorization.md). + +```ts +import { BusinessError, request } from '@kit.BasicServicesKit'; +import { photoAccessHelper } from '@kit.MediaLibraryKit'; + +import { bundleManager } from '@kit.AbilityKit'; +import { abilityAccessCtrl, Context, PermissionRequestResult, common } from '@kit.AbilityKit'; + +@Entry +@Component +struct Index { + build() { + Row() { + Column() { + Button("Download Image").width("50%").margin({ top: 20 }).height(40).onClick(async () => { + let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION | + bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_METADATA; + // Obtain accessTokenID of the application. + let tokenID = -1; + try { + await bundleManager.getBundleInfoForSelf(bundleFlags).then((data) => { + console.info(`/Request getBundleInfoForSelf successfully. Data: ${JSON.stringify(data)}`); + tokenID = data.appInfo.accessTokenId; + }).catch((err: BusinessError) => { + console.error(`GetBundleInfoForSelf failed. Cause: ${err.message}`); + }); + } catch (err) { + let message = (err as BusinessError).message; + console.error('GetBundleInfoForSelf failed: %{public}s', message); + } + let context: Context = this.getUIContext().getHostContext() as common.UIAbilityContext; + + let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); + let grant = true; + // Check whether the application has the required permission. This API uses a promise to return the result. + await atManager.checkAccessToken(tokenID, 'ohos.permission.WRITE_IMAGEVIDEO') + .then((data: abilityAccessCtrl.GrantStatus) => { + console.log(`/Request checkAccessToken success, data->${JSON.stringify(data)}`); + if (data != abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) { + grant = false; + } + }) + .catch((err: BusinessError) => { + console.error(`GheckAccessToken fail, err->${JSON.stringify(err)}`); + }); + + if (!grant) { + // Display a dialog box for the user to grant the required permission. This API uses an asynchronous callback to return the result. + await atManager.requestPermissionsFromUser(context, ['ohos.permission.WRITE_IMAGEVIDEO']) + .then((data: PermissionRequestResult) => { + console.info('/Request grant:' + JSON.stringify(data)); + console.info('/Request grant permissions:' + data.permissions); + console.info('/Request grant authResults:' + data.authResults); + console.info('/Request grant dialogShownResults:' + data.dialogShownResults); + }).catch((err: BusinessError) => { + console.error('Grant error:' + JSON.stringify(err)); + }); + } + + try { + let photoType: photoAccessHelper.PhotoType = photoAccessHelper.PhotoType.IMAGE; + let extension: string = 'jpg'; + let options: photoAccessHelper.CreateOptions = { + title: 'xxxx' + } + // Obtain a PhotoAccessHelper instance, which can be used for accessing and modifying media files in an album. + let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context); + // Create an image or video asset with the specified file type, file name extension, and options. This API uses a promise to return the result. + let uri: string = await phAccessHelper.createAsset(photoType, extension, options); + console.info('/Request createAsset uri' + uri); + console.info('/Request createAsset successfully'); + + let config: request.agent.Config = { + action: request.agent.Action.DOWNLOAD, + url: 'https://xxxx/xxxx.jpg', + // The saveas field specifies the URI of the file saved by PhotoAccessHelper. + saveas: uri, + gauge: true, + // The overwrite field must be set to true. + overwrite: true, + network: request.agent.Network.WIFI, + // The mode field must be set to request.agent.Mode.FOREGROUND. + mode: request.agent.Mode.FOREGROUND, + }; + request.agent.create(context, config).then((task: request.agent.Task) => { + task.start((err: BusinessError) => { + if (err) { + console.error(`Failed to start the download task, Code: ${err.code} message: ${err.message}`); + return; + } + }); + task.on('progress', async (progress) => { + console.warn(`Request download status ${progress.state}, downloaded ${progress.processed}`); + }) + task.on('completed', async (progress) => { + console.warn('Request download completed, ' + JSON.stringify(progress)); + // This method requires the user to manage the task lifecycle. After the task is complete, call the remove method to release the task object. + request.agent.remove(task.tid); + }) + }).catch((err: BusinessError) => { + console.error(`Failed to operate a download task, Code: ${err.code}, message: ${err.message}`); + }); + } catch (err) { + console.error(`Failed to create a download task, err: ${err}`); + } + }) + } + } + } +} ``` ## Adding Network Configuration ### Intercepting HTTP -You can set the configuration file to intercept HTTP. After HTTP is disabled for the upload and download module, upload and download tasks using plaintext HTTP cannot be created. The configuration file is stored in the **src/main/resources/base/profile/network_config.json** directory of the application. +You can set the configuration file to intercept HTTP. After HTTP is disabled for the upload and download module, upload and download tasks using plaintext HTTP cannot be created. The configuration file is stored in the **src/main/resources/base/profile/network_config.json** directory of the application. For details, see the parameters in the [configuration file](../../reference/apis-network-kit/js-apis-net-connection.md#connectionsetapphttpproxy11) of the network management module . The sample configuration file is as follows: @@ -248,13 +575,4 @@ The sample configuration file is as follows: ] } } - ``` - -The table below lists the description of each field. - -| Field | Type | Description | -| --------------------------| --------------- | -------------------------------------- | -| base-config:
cleartextTrafficPermitted | boolean | Whether plaintext transfer is allowed in the global configuration. The value **true** means that plaintext transfer is allowed, that is, HTTP is not intercepted, and **false** means the opposite.| -| domain-config:
cleartextTrafficPermitted | boolean | Whether plaintext transfer is allowed in a specified domain. The value **true** means that plaintext transfer is allowed, that is, HTTP is not intercepted, and **false** means the opposite.| -| include-subdomains | boolean | Whether a rule applies to subdomains. The value **true** means that the regular expression is used to match the domain name, and **false** means the opposite.| diff --git a/en/application-dev/basic-services/usb/Readme-EN.md b/en/application-dev/basic-services/usb/Readme-EN.md index cce5eebb12a..6883738efda 100644 --- a/en/application-dev/basic-services/usb/Readme-EN.md +++ b/en/application-dev/basic-services/usb/Readme-EN.md @@ -18,5 +18,3 @@ - [USB Serial Communication Management](usbSerial/usbSerial-communication.md) - [FAQs](faqs-usb.md) - [Glossary](usb-glossary.md) - - \ No newline at end of file diff --git a/en/application-dev/basic-services/usb/usb-glossary.md b/en/application-dev/basic-services/usb/usb-glossary.md index c95122e8688..94a3d9117df 100644 --- a/en/application-dev/basic-services/usb/usb-glossary.md +++ b/en/application-dev/basic-services/usb/usb-glossary.md @@ -66,7 +66,7 @@ A pipe is a logical communication channel between a host and an endpoint for dat ### Stop bit -The stop bit is located at the end of a data frame. It is a logic high-level signal and is used to identify the end of a character (data packet) transfer. Its length can be 1 bit, 1.5 bits, or 2 bits. (In actual development, 1 bit is most commonly used, and 1.5 bits and 2 bits are mainly used in anti-interference scenarios.) A core function of this bit is to provide a space to tolerate the errors that may occur during time-sequence synchronization for a receiver and ensure data integrity. +The stop bit is located at the end of a data frame. It is a logic high-level signal and is used to identify the end of a character (data packet) transfer. Its length can be 1 bit or 2 bits. (In actual development, 1 bit is most commonly used and 2 bits are mainly used in anti-interference scenarios.) A core function of this bit is to provide a space to tolerate the errors that may occur during time-sequence synchronization for a receiver and ensure data integrity. ## U diff --git a/en/application-dev/basic-services/usb/usb-guidelines.md b/en/application-dev/basic-services/usb/usb-guidelines.md index 318c234105d..fcea406aafb 100644 --- a/en/application-dev/basic-services/usb/usb-guidelines.md +++ b/en/application-dev/basic-services/usb/usb-guidelines.md @@ -107,9 +107,9 @@ You can set a USB device as a host to connect to a device for data transfer. The let deviceName : string = deviceList[0].name; // Request the permissions to operate a specified device. usbManager.requestRight(deviceName).then((hasRight : boolean) => { - console.info("usb device request right result: " + hasRight); + console.info(`usb device request right result: ${hasRight}`); }).catch((error : BusinessError)=> { - console.info("usb device request right failed : " + error); + console.error(`usb device request right failed : ${error}`); }); ``` @@ -142,22 +142,22 @@ You can set a USB device as a host to connect to a device for data transfer. The let dataUint8Array : Uint8Array = new Uint8Array(1024); usbManager.bulkTransfer(pipe, inEndpoint, dataUint8Array, 15000).then((dataLength : number) => { if (dataLength >= 0) { - console.info("usb readData result Length : " + dataLength); + console.info(`usb readData result Length : ${dataLength}`); } else { - console.info("usb readData failed : " + dataLength); + console.error(`usb readData failed`); } }).catch((error : BusinessError) => { - console.info("usb readData error : " + JSON.stringify(error)); + console.error(`usb readData error : ${error}`); }); // Send data. Select the corresponding TX endpoint from deviceList for data transfer. (endpoint.direction == 0) usbManager.bulkTransfer(pipe, outEndpoint, dataUint8Array, 15000).then((dataLength : number) => { if (dataLength >= 0) { - console.info("usb writeData result write length : " + dataLength); + console.info(`usb writeData result write length : ${dataLength}`); } else { - console.info("writeData failed"); + console.error("usb writeData failed"); } }).catch((error : BusinessError) => { - console.info("usb writeData error : " + JSON.stringify(error)); + console.error(`usb writeData error : ${error}`); }); ``` @@ -180,7 +180,7 @@ You can set a USB device as a host to connect to a device for data transfer. The }; usbManager.usbControlTransfer(pipe, param).then((ret: number) => { - console.info("usbControlTransfer = ${ret}"); + console.info(`usbControlTransfer = ${ret}`); }) ``` diff --git a/en/application-dev/basic-services/usb/usbManager/usbhost/bulkTransfer.md b/en/application-dev/basic-services/usb/usbManager/usbhost/bulkTransfer.md index c56c540c56e..adb169b53da 100644 --- a/en/application-dev/basic-services/usb/usbManager/usbhost/bulkTransfer.md +++ b/en/application-dev/basic-services/usb/usbManager/usbhost/bulkTransfer.md @@ -10,7 +10,7 @@ Bulk transfer is used to transfer and receive a large amount of data without ban - Development tool and configuration: - DevEco Studio, as the driver development tool, allows you to develop, debug, and package drivers. [Download and install](https://developer.huawei.com/consumer/cn/download/) DevEco Studio and verify basic operations to ensure that it can function properly. For details, see [Creating and Running a Project](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V14/ide-create-new-project-V14) in [DevEco Studio User Guide](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V14/ide-tools-overview-V14). + DevEco Studio, as the driver development tool, allows you to develop, debug, and package drivers. [Download and install](https://developer.huawei.com/consumer/en/download/) DevEco Studio and verify basic operations to ensure that it can function properly. For details, see [Creating a Project](https://developer.huawei.com/consumer/en/doc/harmonyos-guides/ide-create-new-project) in [DevEco Studio User Guide](https://developer.huawei.com/consumer/en/doc/harmonyos-guides/ide-tools-overview). - SDK version configuration: @@ -20,13 +20,13 @@ Bulk transfer is used to transfer and receive a large amount of data without ban - HDC configuration: - HarmonyOS Device Connector (hdc) is a command-line tool for debugging. It can be used to interact with real devices or the Emulators on Windows, Linux, and macOS. For details about the configuration, see [hdc](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V5/hdc-V5). + HarmonyOS Device Connector (hdc) is a command-line tool for debugging. It can be used to interact with real devices or the Emulator on Windows, Linux, and macOS. For details about the configuration, see [hdc](https://developer.huawei.com/consumer/en/doc/harmonyos-guides/hdc). ### Environment Setup - Install [DevEco Studio](https://developer.huawei.com/consumer/cn/download/deveco-studio) 4.1 or later on the PC. -- Update the public-SDK to API version 16 or later. For details, see [Switching to Full SDK](https://gitee.com/openharmony/docs/blob/master/en/application-dev/faqs/full-sdk-switch-guide.md). -- Install hdc on the PC. You can use it to interact with a real device or emulator on Windows, Linux, or macOS. For details, see [hdc](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V5/hdc-V5). +- Update the public SDK to API version 16 or later. For details, see [Switching to Full SDK](https://gitee.com/openharmony/docs/blob/master/en/application-dev/faqs/full-sdk-switch-guide.md). +- Install hdc on the PC. You can use it to interact with a real device or the Emulator on Windows, Linux, or macOS. For details, see [HDC Configuration](https://developer.huawei.com/consumer/en/doc/harmonyos-guides/hdc). - Use a USB cable to connect a device to the PC. ## How to Develop @@ -43,6 +43,10 @@ For details about the APIs of device management and transfer modes, see [@ohos.u Connect a host to a device and use the **bulkTransfer** API to transfer data. The following steps describe how to implement a bulk transfer: +> **NOTE** +> +> The following sample code shows only a basic process. You should execute the code in a specific method. When calling this method, you must comply with device protocols to ensure proper data transfer and device compatibility. + 1. Import modules. ```ts @@ -115,9 +119,9 @@ Connect a host to a device and use the **bulkTransfer** API to transfer data. Th let deviceName : string = deviceList[0].name; // Request the permissions to operate a specified device. usbManager.requestRight(deviceName).then((hasRight : boolean) => { - console.info("usb device request right result: " + hasRight); + console.info(`usb device request right result: ${hasRight}`); }).catch((error : BusinessError)=> { - console.info("usb device request right failed : " + error); + console.error(`usb device request right failed : ${error}`); }); ``` @@ -146,22 +150,22 @@ Connect a host to a device and use the **bulkTransfer** API to transfer data. Th let dataUint8Array : Uint8Array = new Uint8Array(1024); usbManager.bulkTransfer(pipe, inEndpoint, dataUint8Array, 15000).then((dataLength : number) => { if (dataLength >= 0) { - console.info("usb readData result Length : " + dataLength); + console.info(`usb readData result Length : ${dataLength}`); } else { - console.info("usb readData failed : " + dataLength); + console.error("usb readData failed"); } }).catch((error : BusinessError) => { - console.info("usb readData error : " + JSON.stringify(error)); + console.error(`usb readData error : ${error}`); }); // Send data. Select the corresponding TX endpoint from deviceList for data transfer. (endpoint.direction == 0) usbManager.bulkTransfer(pipe, outEndpoint, dataUint8Array, 15000).then((dataLength : number) => { if (dataLength >= 0) { - console.info("usb writeData result write length : " + dataLength); + console.info(`usb writeData result write length : ${dataLength}`); } else { - console.info("writeData failed"); + console.error("usb writeData failed"); } }).catch((error : BusinessError) => { - console.info("usb writeData error : " + JSON.stringify(error)); + console.error(`usb writeData error : ${error}`); }); ``` diff --git a/en/application-dev/basic-services/usb/usbManager/usbhost/controlTransfer.md b/en/application-dev/basic-services/usb/usbManager/usbhost/controlTransfer.md index a151c019874..be695a97235 100644 --- a/en/application-dev/basic-services/usb/usbManager/usbhost/controlTransfer.md +++ b/en/application-dev/basic-services/usb/usbManager/usbhost/controlTransfer.md @@ -10,7 +10,7 @@ The control transfer is used to obtain and set the device status, and control th - Development tool and configuration: - DevEco Studio, as the driver development tool, allows you to develop, debug, and package drivers. [Download and install](https://developer.huawei.com/consumer/cn/download/) DevEco Studio and verify basic operations to ensure that it can function properly. For details, see [Creating and Running a Project](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V14/ide-create-new-project-V14) in [DevEco Studio User Guide](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V14/ide-tools-overview-V14). + DevEco Studio, as the driver development tool, allows you to develop, debug, and package drivers. [Download and install](https://developer.huawei.com/consumer/en/download/) DevEco Studio and verify basic operations to ensure that it can function properly. For details, see [Creating a Project](https://developer.huawei.com/consumer/en/doc/harmonyos-guides/ide-create-new-project) in [DevEco Studio User Guide](https://developer.huawei.com/consumer/en/doc/harmonyos-guides/ide-tools-overview). - SDK version configuration: @@ -20,13 +20,13 @@ The control transfer is used to obtain and set the device status, and control th - HDC configuration: - HarmonyOS Device Connector (hdc) is a command-line tool for debugging. It can be used to interact with real devices or the Emulators on Windows, Linux, and macOS. For details about the configuration, see [hdc](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V5/hdc-V5). + HarmonyOS Device Connector (hdc) is a command-line tool for debugging. It can be used to interact with real devices or the Emulators on Windows, Linux, and macOS. For details about the configuration, see [hdc](https://developer.huawei.com/consumer/en/doc/harmonyos-guides/hdc). ### Environment Setup - Install [DevEco Studio](https://developer.huawei.com/consumer/cn/download/deveco-studio) 4.1 or later on the PC. -- Update the public-SDK to API version 16 or later. For details, see [Switching to Full SDK](https://gitee.com/openharmony/docs/blob/master/en/application-dev/faqs/full-sdk-switch-guide.md). -- Install hdc on the PC. You can use it to interact with a real device or the Emulator on Windows, Linux, or macOS. For details, see [hdc](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V5/hdc-V5). +- Update the public SDK to API version 16 or later. For details, see [Switching to Full SDK](https://gitee.com/openharmony/docs/blob/master/en/application-dev/faqs/full-sdk-switch-guide.md). +- Install hdc on the PC. You can use it to interact with a real device or the Emulator on Windows, Linux, or macOS. For details, see [HDC Configuration](https://developer.huawei.com/consumer/en/doc/harmonyos-guides/hdc). - Use a USB cable to connect a device to the PC. ## How to Develop @@ -43,6 +43,9 @@ For details about the APIs of device management and transfer modes, see [@ohos.u Connect a host to a device and use the **usbControlTransfer** API to transfer data. The following steps describe how to implement a control transfer: +> **NOTE** +> +> The following sample code shows only a basic process. You should execute the code in a specific method. When calling this method, you must comply with device protocols to ensure proper data transfer and device compatibility. 1. Import modules. @@ -118,7 +121,7 @@ Connect a host to a device and use the **usbControlTransfer** API to transfer da usbManager.requestRight(deviceName).then((hasRight : boolean) => { console.info("usb device request right result: " + hasRight); }).catch((error : BusinessError)=> { - console.info("usb device request right failed : " + error); + console.error(`usb device request right failed : ${error}`); }); ``` @@ -152,7 +155,7 @@ Connect a host to a device and use the **usbControlTransfer** API to transfer da }; usbManager.usbControlTransfer(pipe, param).then((ret: number) => { - console.info("usbControlTransfer = ${ret}"); + console.info(`usbControlTransfer = ${ret}`); }) ``` diff --git a/en/application-dev/basic-services/usb/usbManager/usbhost/deviceManager.md b/en/application-dev/basic-services/usb/usbManager/usbhost/deviceManager.md index e3ef88cc584..85732ddf42d 100644 --- a/en/application-dev/basic-services/usb/usbManager/usbhost/deviceManager.md +++ b/en/application-dev/basic-services/usb/usbManager/usbhost/deviceManager.md @@ -10,7 +10,7 @@ When a USB device is inserted, you can use **usbManager** to obtain basic inform - Development tool and configuration: - DevEco Studio, as the driver development tool, allows you to develop, debug, and package drivers. [Download and install](https://developer.huawei.com/consumer/cn/download/) DevEco Studio and verify basic operations to ensure that it can function properly. For details, see [Creating and Running a Project](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V14/ide-create-new-project-V14) in [DevEco Studio User Guide](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V14/ide-tools-overview-V14). + DevEco Studio, as the driver development tool, allows you to develop, debug, and package drivers. [Download and install](https://developer.huawei.com/consumer/en/download/) DevEco Studio and verify basic operations to ensure that it can function properly. For details, see [Creating a Project](https://developer.huawei.com/consumer/en/doc/harmonyos-guides/ide-create-new-project) in [DevEco Studio User Guide](https://developer.huawei.com/consumer/en/doc/harmonyos-guides/ide-tools-overview). - SDK version configuration: @@ -20,13 +20,13 @@ When a USB device is inserted, you can use **usbManager** to obtain basic inform - HDC configuration: - HarmonyOS Device Connector (hdc) is a command-line tool for debugging. It can be used to interact with real devices or the Emulators on Windows, Linux, and macOS. For details about the configuration, see [hdc](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V5/hdc-V5). + HarmonyOS Device Connector (hdc) is a command-line tool for debugging. It can be used to interact with real devices or the Emulator on Windows, Linux, and macOS. For details about the configuration, see [hdc](https://developer.huawei.com/consumer/en/doc/harmonyos-guides/hdc). ### Environment Setup - Install [DevEco Studio](https://developer.huawei.com/consumer/cn/download/deveco-studio) 4.1 or later on the PC. - Update the public SDK to API version 16 or later. For details, see [Update Guide](https://gitee.com/openharmony/docs/blob/master/en/application-dev/faqs/full-sdk-switch-guide.md). -- Install hdc on the PC. You can use it to interact with a real device or the Emulator on Windows, Linux, or macOS. For details, see [hdc](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V5/hdc-V5). +- Install hdc on the PC. You can use it to interact with a real device or the Emulator on Windows, Linux, or macOS. For details, see [HDC Configuration](https://developer.huawei.com/consumer/en/doc/harmonyos-guides/hdc). - Use a USB cable to connect an OpenHarmony device to the PC. ## How to Develop @@ -133,7 +133,7 @@ A USB device can be used as a host to connect to a device for management. The pr usbManager.requestRight(deviceName).then((hasRight : boolean) => { console.info("usb device request right result: " + hasRight); }).catch((error : BusinessError)=> { - console.info("usb device request right failed : " + error); + console.error(`usb device request right failed : ${error}`); }); ``` @@ -156,4 +156,3 @@ A USB device can be used as a host to connect to a device for management. The pr usbManager.releaseInterface(pipe, interface1); usbManager.closePipe(pipe); ``` - diff --git a/en/application-dev/basic-services/usb/usbManager/usbhost/interruptTransfer.md b/en/application-dev/basic-services/usb/usbManager/usbhost/interruptTransfer.md index f35ab515681..b92fdef6c07 100644 --- a/en/application-dev/basic-services/usb/usbManager/usbhost/interruptTransfer.md +++ b/en/application-dev/basic-services/usb/usbManager/usbhost/interruptTransfer.md @@ -10,7 +10,7 @@ The interrupt transfer is mainly used by the host to receive a data packet sent - Development tool and configuration: - DevEco Studio, as the driver development tool, allows you to develop, debug, and package drivers. [Download and install](https://developer.huawei.com/consumer/cn/download/) DevEco Studio and verify basic operations to ensure that it can function properly. For details, see [Creating and Running a Project](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V14/ide-create-new-project-V14) in [DevEco Studio User Guide](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V14/ide-tools-overview-V14). + DevEco Studio, as the driver development tool, allows you to develop, debug, and package drivers. [Download and install](https://developer.huawei.com/consumer/en/download/) DevEco Studio and verify basic operations to ensure that it can function properly. For details, see [Creating a Project](https://developer.huawei.com/consumer/en/doc/harmonyos-guides/ide-create-new-project) in [DevEco Studio User Guide](https://developer.huawei.com/consumer/en/doc/harmonyos-guides/ide-tools-overview). - SDK version configuration: @@ -20,13 +20,13 @@ The interrupt transfer is mainly used by the host to receive a data packet sent - HDC configuration: - HarmonyOS Device Connector (hdc) is a command-line tool for debugging. It can be used to interact with real devices or the Emulators on Windows, Linux, and macOS. For details about the configuration, see [hdc](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V5/hdc-V5). + HarmonyOS Device Connector (hdc) is a command-line tool for debugging. It can be used to interact with real devices or the Emulator on Windows, Linux, and macOS. For details about the configuration, see [hdc](https://developer.huawei.com/consumer/en/doc/harmonyos-guides/hdc). ### Environment Setup - Install [DevEco Studio](https://developer.huawei.com/consumer/cn/download/deveco-studio) 4.1 or later on the PC. - Update the public SDK to API version 16 or later. For details, see [Switching to Full SDK](https://gitee.com/openharmony/docs/blob/master/en/application-dev/faqs/full-sdk-switch-guide.md). -- Install hdc on the PC. You can use it to interact with a real device or the Emulator on Windows, Linux, or macOS. For details, see [hdc](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V5/hdc-V5). +- Install hdc on the PC. You can use it to interact with a real device or the Emulator on Windows, Linux, or macOS. For details, see [HDC Configuration](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V5/hdc). - Use a USB cable to connect a device to the PC. ## How to Develop @@ -44,6 +44,10 @@ For details about the APIs of device management and transfer modes, see [@ohos.u Connect a host to a device and use the **usbSubmitTransfer** API to transfer data. The following steps describe how to implement an interrupt transfer: +> **NOTE** +> +> The following sample code shows only a basic process. You should execute the code in a specific method. When calling this method, you must comply with device protocols to ensure proper data transfer and device compatibility. + 1. Import modules. ```ts @@ -56,9 +60,9 @@ Connect a host to a device and use the **usbSubmitTransfer** API to transfer dat ```ts // Obtain the list of USB devices connected to the host. let usbDevices: Array = usbManager.getDevices(); - console.info('usbDevices: ', JSON.stringify(usbDevices)); + console.info(`usbDevices: ${usbDevices}`); if(usbDevices.length === 0) { - console.info('usbDevices is empty'); + console.error('usbDevices is empty'); return; } ``` @@ -72,7 +76,7 @@ Connect a host to a device and use the **usbSubmitTransfer** API to transfer dat await usbManager.requestRight(usbDevice.name).then(result => { if(!result) { // If the USB device does not have the access permission and is not granted by the user, the device exits. - console.info('user is not granted the operation permission'); + console.error('The user does not have permission to perform this operation'); return; } }); @@ -137,13 +141,13 @@ Connect a host to a device and use the **usbSubmitTransfer** API to transfer dat }; transferParams.callback = (err: Error, callBackData: usbManager.SubmitTransferCallback) => { - console.info('callBackData = ' + JSON.stringify(callBackData)); - console.info('transfer success, result = ' + transferParams.buffer.toString()); + console.info(`callBackData = ${callBackData}`); + console.info(`transfer success, result = ${transferParams.buffer}`); } usbManager.usbSubmitTransfer(transferParams); console.info('USB transfer request submitted.'); } catch (error) { - console.error('USB transfer failed:', error); + console.error(`USB transfer failed: ${error}`); } ``` @@ -154,7 +158,7 @@ Connect a host to a device and use the **usbSubmitTransfer** API to transfer dat usbManager.releaseInterface(devicePipe, usbInterface); usbManager.closePipe(devicePipe); ``` - + ### Verification 1. Connect the host to a terminal device (such as a mouse or a keyboard) that supports interrupt transfer through a USB interface. diff --git a/en/application-dev/basic-services/usb/usbManager/usbhost/isochronousTransfer.md b/en/application-dev/basic-services/usb/usbManager/usbhost/isochronousTransfer.md index 9eb31d6682b..299b5fe4611 100644 --- a/en/application-dev/basic-services/usb/usbManager/usbhost/isochronousTransfer.md +++ b/en/application-dev/basic-services/usb/usbManager/usbhost/isochronousTransfer.md @@ -10,7 +10,7 @@ Isochronous transfer is a transfer mode in which data is transferred in a fixed - Development tool and configuration: - DevEco Studio, as the driver development tool, allows you to develop, debug, and package drivers. [Download and install](https://developer.huawei.com/consumer/cn/download/) DevEco Studio and verify basic operations to ensure that it can function properly. For details, see [Creating and Running a Project](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V14/ide-create-new-project-V14) in [DevEco Studio User Guide](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V14/ide-tools-overview-V14). + DevEco Studio, as the driver development tool, allows you to develop, debug, and package drivers. [Download and install](https://developer.huawei.com/consumer/en/download/) DevEco Studio and verify basic operations to ensure that it can function properly. For details, see [Creating a Project](https://developer.huawei.com/consumer/en/doc/harmonyos-guides/ide-create-new-project) in [DevEco Studio User Guide](https://developer.huawei.com/consumer/en/doc/harmonyos-guides/ide-tools-overview). - SDK version configuration: @@ -20,13 +20,13 @@ Isochronous transfer is a transfer mode in which data is transferred in a fixed - HDC configuration: - HarmonyOS Device Connector (hdc) is a command-line tool for debugging. It can be used to interact with real devices or the Emulators on Windows, Linux, and macOS. For details about the configuration, see [hdc](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V5/hdc-V5). + HarmonyOS Device Connector (hdc) is a command-line tool for debugging. It can be used to interact with real devices or the Emulators on Windows, Linux, and macOS. For details about the configuration, see [hdc](https://developer.huawei.com/consumer/en/doc/harmonyos-guides/hdc). ### Environment Setup - Install [DevEco Studio](https://developer.huawei.com/consumer/cn/download/deveco-studio) 4.1 or later on the PC. - Update the public SDK to API version 16 or later. For details, see [Switching to Full SDK](https://gitee.com/openharmony/docs/blob/master/en/application-dev/faqs/full-sdk-switch-guide.md). -- Install hdc on the PC. You can use it to interact with a real device or the Emulator on Windows, Linux, or macOS. For details, see [hdc](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V5/hdc-V5). +- Install hdc on the PC. You can use it to interact with a real device or the Emulator on Windows, Linux, or macOS. For details, see [HDC Configuration](https://developer.huawei.com/consumer/en/doc/harmonyos-guides/hdc). - Use a USB cable to connect a device to the PC. ## How to Develop @@ -44,21 +44,25 @@ For details about the APIs of device management and transfer modes, see [@ohos.u Connect a host to a device and use the **usbSubmitTransfer** API to transfer data. The following steps describe how to implement an interrupt transfer: +> **NOTE** +> +> The following sample code shows only a basic process. You should execute the code in a specific method. When calling this method, you must comply with device protocols to ensure proper data transfer and device compatibility. + 1. Import modules. ```ts // Import the usbManager module. import { usbManager } from '@kit.BasicServicesKit'; - ``` + ``` 2. Obtain the USB device list. ```ts // Obtain the list of USB devices connected to the host. let usbDevices: Array = usbManager.getDevices(); - console.info('usbDevices: ', JSON.stringify(usbDevices)); + console.info(`usbDevices: ${usbDevices}`); if(usbDevices.length === 0) { - console.info('usbDevices is empty'); + console.error('usbDevices is empty'); return; } ``` @@ -72,7 +76,7 @@ Connect a host to a device and use the **usbSubmitTransfer** API to transfer dat await usbManager.requestRight(usbDevice.name).then(result => { if(!result) { // If the USB device does not have the access permission and is not granted by the user, the device exits. - console.info('user is not granted the operation permission'); + console.error('The user does not have permission to perform this operation'); return; } }); @@ -122,7 +126,7 @@ Connect a host to a device and use the **usbSubmitTransfer** API to transfer dat if (this.type === usbManager.UsbEndpointTransferType.TRANSFER_TYPE_ISOCHRONOUS) { let setInterfaceResult = usbManager.setInterface(devicePipe, usbInterface); if (setInterfaceResult !== 0) { - console.info(`setInterfaceResult error = ${setInterfaceResult}`) + console.error(`setInterfaceResult error = ${setInterfaceResult}`) return; } } @@ -147,13 +151,13 @@ Connect a host to a device and use the **usbSubmitTransfer** API to transfer dat }; transferParams.callback = (err: Error, callBackData: usbManager.SubmitTransferCallback) => { - console.info('callBackData = ' + JSON.stringify(callBackData)); + console.info(`callBackData = ${callBackData}`); console.info('transfer success, result = ' + transferParams.buffer.toString()); } usbManager.usbSubmitTransfer(transferParams); console.info('USB transfer request submitted.'); } catch (error) { - console.error('USB transfer failed:', error); + console.error(`USB transfer failed: ${error}`); } ``` diff --git a/en/application-dev/basic-services/usb/usbserial/usbSerial-communication.md b/en/application-dev/basic-services/usb/usbserial/usbSerial-communication.md index 91a8bfb47ca..27f2ffd11b8 100644 --- a/en/application-dev/basic-services/usb/usbserial/usbSerial-communication.md +++ b/en/application-dev/basic-services/usb/usbserial/usbSerial-communication.md @@ -29,22 +29,26 @@ For details, see [Preparing the Environment](usbSerial-overview.md#preparing-the You can read and write data as follows: +> **NOTE** +> +> The following sample code shows only a basic process. You should execute the code in a specific method. + 1. Import the **usbManager** module. ```ts // Import the usbManager module. import serial from '@ohos.usbManager.serial'; import { buffer } from '@kit.ArkTS'; - ``` + ``` 2. Obtain the USB device list. ```ts // Obtain the list of USB devices connected to the host. let portList: serial.SerialPort[] = serial.getPortList(); - console.info('usbSerial portList: ' + JSON.stringify(portList)); + console.info(`usbSerial portList: ${portList}`); if (portList === undefined || portList.length === 0) { - console.info('usbSerial portList is empty'); + console.error('usbSerial portList is empty'); return; } ``` @@ -58,7 +62,7 @@ You can read and write data as follows: await serial.requestSerialRight(portId).then(result => { if(!result) { // If the device does not have the access permission and is not granted by the user, the device exits. - console.info('usbSerial user is not granted the operation permission'); + console.error('The user does not have permission to perform this operation'); return; } }); @@ -70,9 +74,9 @@ You can read and write data as follows: ```ts try { serial.open(portId) - console.info('open usbSerial success, portId: ' + portId); + console.info(`open usbSerial success, portId: ${portId}`); } catch (error) { - console.error('open usbSerial error, ' + JSON.stringify(error)); + console.error(`open usbSerial error: ${error}`); } ``` @@ -82,18 +86,18 @@ You can read and write data as follows: // Read data asynchronously. let readBuffer: Uint8Array = new Uint8Array(64); serial.read(portId, readBuffer, 2000).then((size: number) => { - console.info('read usbSerial success, readBuffer: ' + readBuffer.toString()); + console.info(`read usbSerial success, readBuffer: ${readBuffer}`); }).catch((error: Error) => { - console.error('read usbSerial error, ' + JSON.stringify(error)); + console.error(`read usbSerial error: ${error}`); }) // Read data synchronously. let readSyncBuffer: Uint8Array = new Uint8Array(64); try { serial.readSync(portId, readSyncBuffer, 2000); - console.info('readSync usbSerial success, readSyncBuffer: ' + readSyncBuffer.toString()); + console.info(`readSync usbSerial success, readSyncBuffer: ${readSyncBuffer}`); } catch (error) { - console.error('readSync usbSerial error, ' + JSON.stringify(error)); + console.error(`readSync usbSerial error: ${error}`); } ``` @@ -103,18 +107,18 @@ You can read and write data as follows: // Write data asynchronously. let writeBuffer: Uint8Array = new Uint8Array(buffer.from('Hello World', 'utf-8').buffer) serial.write(portId, writeBuffer, 2000).then((size: number) => { - console.info('write usbSerial success, writeBuffer: ' + writeBuffer.toString()); + console.info(`write usbSerial success, writeBuffer: ${writeBuffer}`); }).catch((error: Error) => { - console.error('write usbSerial error, ' + JSON.stringify(error)); + console.error(`write usbSerial error: ${error}`); }) // Write data synchronously. let writeSyncBuffer: Uint8Array = new Uint8Array(buffer.from('Hello World', 'utf-8').buffer) try { serial.writeSync(portId, writeSyncBuffer, 2000); - console.info('writeSync usbSerial success, writeSyncBuffer: ' + writeSyncBuffer.toString()); + console.info(`writeSync usbSerial success, writeSyncBuffer: ${writeSyncBuffer}`); } catch (error) { - console.error('writeSync usbSerial error, ' + JSON.stringify(error)); + console.error(`writeSync usbSerial error: ${error}`); } ``` @@ -123,9 +127,9 @@ You can read and write data as follows: ```ts try { serial.close(portId); - console.info('close usbSerial success, portId: ' + portId); + console.info(`close usbSerial success, portId: ${portId}`); } catch (error) { - console.error('close usbSerial error, ' + JSON.stringify(error)); + console.error(`close usbSerial error: ${error}`); } ``` diff --git a/en/application-dev/basic-services/usb/usbserial/usbSerial-configuration.md b/en/application-dev/basic-services/usb/usbserial/usbSerial-configuration.md index 578792167a9..537a0262ce1 100644 --- a/en/application-dev/basic-services/usb/usbserial/usbSerial-configuration.md +++ b/en/application-dev/basic-services/usb/usbserial/usbSerial-configuration.md @@ -25,7 +25,7 @@ Before developing the USB serial port, you should have a basic understanding of - Stop bit - The stop bit is located at the end of a data frame. It is a logic high-level signal and is used to identify the end of a character (data packet) transfer. Its length can be 1 bit, 1.5 bits, or 2 bits. (In actual development, 1 bit is most commonly used, and 1.5 bits and 2 bits are mainly used in anti-interference scenarios.) A core function of this bit is to provide a space to tolerate the errors that may occur during time-sequence synchronization for a receiver and ensure data integrity. + The stop bit is located at the end of a data frame. It is a logic high-level signal and is used to identify the end of a character (data packet) transfer. Its length can be 1 bit or 2 bits. (In actual development, 1 bit is most commonly used and 2 bits are mainly used in anti-interference scenarios.) A core function of this bit is to provide a space to tolerate the errors that may occur during time-sequence synchronization for a receiver and ensure data integrity. ## Preparing the Environment @@ -45,21 +45,25 @@ For details, see [Preparing the Environment](usbSerial-overview.md#preparing-the You can obtain and set the serial port configuration as follows: +> **NOTE** +> +> The following sample code shows only a basic process. You should execute the code in a specific method. + 1. Import the **usbManager** module. ```ts // Import the usbManager module. import serial from '@ohos.usbManager.serial'; - ``` + ``` 2. Obtain the USB device list. ```ts // Obtain the list of USB devices connected to the host. let portList: serial.SerialPort[] = serial.getPortList(); - console.info('usbSerial portList: ' + JSON.stringify(portList)); + console.info(`usbSerial portList: ${portList}`); if (portList === undefined || portList.length === 0) { - console.info('usbSerial portList is empty'); + console.error('usbSerial portList is empty'); return; } ``` @@ -73,7 +77,7 @@ You can obtain and set the serial port configuration as follows: await serial.requestSerialRight(portId).then(result => { if(!result) { // If the device does not have the access permission and is not granted by the user, the device exits. - console.info('usbSerial user is not granted the operation permission'); + console.error('The user does not have permission to perform this operation'); return; } }); @@ -85,9 +89,9 @@ You can obtain and set the serial port configuration as follows: ```ts try { serial.open(portId) - console.info('open usbSerial success, portId: ' + portId); + console.info(`open usbSerial success, portId: ${portId}`); } catch (error) { - console.error('open usbSerial error, ' + JSON.stringify(error)); + console.error(`open usbSerial error: ${error}`); } ``` @@ -100,12 +104,12 @@ You can obtain and set the serial port configuration as follows: if (attribute === undefined) { console.error('getAttribute usbSerial error, attribute is undefined'); } else { - console.info('getAttribute usbSerial success, attribute: ' + JSON.stringify(attribute)); + console.info(`getAttribute usbSerial success, attribute: ${attribute}`); } } catch (error) { - console.error('getAttribute usbSerial error, ' + JSON.stringify(error)); + console.error(`getAttribute usbSerial error: ${error}`); } - + // Set the serial port configuration. try { let attribute: serial.SerialAttribute = { @@ -115,9 +119,9 @@ You can obtain and set the serial port configuration as follows: stopBits: serial.StopBits.STOPBIT_1 } serial.setAttribute(portId, attribute); - console.info('setAttribute usbSerial success, attribute: ' + JSON.stringify(attribute)); + console.info(`setAttribute usbSerial success, attribute: ${attribute}`); } catch (error) { - console.error('setAttribute usbSerial error, ' + JSON.stringify(error)); + console.error(`setAttribute usbSerial error: ${error}`); } ``` diff --git a/en/application-dev/basic-services/usb/usbserial/usbSerial-overview.md b/en/application-dev/basic-services/usb/usbserial/usbSerial-overview.md index 8b93123b3a2..591f40da482 100644 --- a/en/application-dev/basic-services/usb/usbserial/usbSerial-overview.md +++ b/en/application-dev/basic-services/usb/usbserial/usbSerial-overview.md @@ -30,7 +30,7 @@ The USB serial port service consists of two phases: Receiving data: The device receives the data from the physical serial port. → The device packages and uploads data to the USB host. → The driver receives and stores data in the serial port buffer. → The application layer reads the data. - + **Figure 1** Process of transmitting and receiving data ![Data Receiving and Transmission Through the Serial Port](../figures/en-us_image_22989BBB5490.png) @@ -55,8 +55,6 @@ The USB serial port service consists of two phases: ### Environment Setup -- Install [DevEco Studio](https://developer.huawei.com/consumer/cn/download/deveco-studio) 4.1 or later on the PC. -- Update the public-SDK to API version 18 or later. For details, see [OpenHarmony SDK Upgrade Assistant](../../../tools/openharmony_sdk_upgrade_assistant.md). +- Install [DevEco Studio](https://developer.huawei.com/consumer/en/download/deveco-studio) 4.1 or later on the PC. +- Update the public SDK to API version 18 or later. - Prepare a USB-to-serial cable. Connect the USB port and the serial port of the cable to that of the OpenHarmony device. - - \ No newline at end of file diff --git a/en/application-dev/reference/apis-basic-services-kit/Readme-EN.md b/en/application-dev/reference/apis-basic-services-kit/Readme-EN.md index 58669a0201d..2f352c9cc77 100644 --- a/en/application-dev/reference/apis-basic-services-kit/Readme-EN.md +++ b/en/application-dev/reference/apis-basic-services-kit/Readme-EN.md @@ -2,7 +2,7 @@ - ArkTS APIs - Account Management - - [@ohos.account.appAccount (App Account Management)](js-apis-appAccount.md) + - [@ohos.account.appAccount (Application Account Management)](js-apis-appAccount.md) - [@ohos.account.distributedAccount (Distributed Account Management)](js-apis-distributed-account.md) - [@ohos.account.osAccount (OS Account Management)](js-apis-osAccount.md) @@ -97,24 +97,23 @@ - Modules - [CommonEvent](capi-common-event.md) - [DeviceInfo](_device_info.md) - - [InitSync](_init_sync.md) - - [OsAccount](_os_account.md) + - [OsAccount](capi-osaccount.md) - [OH_BatteryInfo](oh__batteryinfo.md) - [OH_Scan](c-apis-scan.md) - [OH_Print](_o_h___print.md) - - [Pasteboard](_pasteboard.md) + - [Pasteboard](capi-pasteboard.md) - [TimeService](_time_service.md) - Header Files - [deviceinfo.h](deviceinfo_8h.md) - - [init_sync.h](init__sync_8h.md) - [ohbattery_info.h](ohbattery__info_8h.md) - [oh_commonevent.h](oh_commonevent_8h.md) - [oh_commonevnt_support.h](oh_commonevent_support_8h.md) - - [oh_pasteboard.h](oh__pasteboard_8h.md) - - [oh_pasteboard_err_code.h](oh__pasteboard__err__code_8h.md) - - [os_account.h](os__account_8h.md) - - [os_account_common.h](os__account__common_8h.md) + - [oh_pasteboard.h](capi-oh-pasteboard-h.md) + - [oh_pasteboard_err_code.h](capi-oh-pasteboard-err-code-h.md) + - [os_account.h](capi-os-account-h.md) + - [os_account_common.h](capi-os-account-common-h.md) - [ohprint.h](ohprint_8h.md) + - [ohscan.h](c-apis-scan.md) - [time_service.h](time__service_8h.md) - Structs - [Print_Margin](_print___margin.md) @@ -122,6 +121,10 @@ - [Print_PrintAttributes](_print___print_attributes.md) - [Print_PrintDocCallback](_print___print_doc_callback.md) - [Print_Range](_print___range.md) + - [Pasteboard_ProgressInfo](capi-pasteboard-progressinfo.md) + - [Pasteboard_GetDataParams](capi-pasteboard-getdataparams.md) + - [OH_PasteboardObserver](capi-pasteboard-oh-pasteboardobserver.md) + - [OH_Pasteboard](capi-pasteboard-oh-pasteboard.md) - Error Codes - [USB Error Codes](errorcode-usb.md) - [Running Lock Error Codes](errorcode-runninglock.md) diff --git a/en/application-dev/reference/apis-basic-services-kit/_o_h___print.md b/en/application-dev/reference/apis-basic-services-kit/_o_h___print.md index 8a8e757e736..3c1b869b1e4 100644 --- a/en/application-dev/reference/apis-basic-services-kit/_o_h___print.md +++ b/en/application-dev/reference/apis-basic-services-kit/_o_h___print.md @@ -2,545 +2,545 @@ ## Overview -Provides applications with the ability to access the printing system using CAPI. +Provides applications with the ability to access the print system using CAPI. -**Since:** 12 +**Since**: 12 ## Summary -### Type Definitions +### Types -| Name | Description | +| Name| Description| | -------- | -------- | -| [Print_StringList](#print_stringlist) | Printer device list. | -| [Print_Property](#print_property) | Printer property. | -| [Print_PropertyList](#print_propertylist) | Printer property list. | -| [Print_Resolution](#print_resolution) | Print resolution unit. | -| [Print_Margin](#print_margin) | Print margin. | -| [Print_PageSize](#print_pagesize) | Print paper size. | -| [Print_PrinterCapability](#print_printercapability) | Printer capability. | -| [Print_DefaultValue](#print_defaultvalue) | Print default information. | -| [Print_PrinterInfo](#print_printerinfo) | Printer information. | -| [Print_PrintJob](#print_printjob) | Print job. | -| [Print_Range](#print_range) | Print range. | -| [Print_PrintAttributes](#print_printattributes) | Print attributes. | -| [Print_WriteResultCallback](#print_writeresultcallback) | Write result callback. | -| [Print_OnStartLayoutWrite](#print_onstartlayoutwrite) | Start layout callback. | -| [Print_OnJobStateChanged](#print_onjobstatechanged) | Print job state callback. | -| [Print_PrintDocCallback](#print_printdoccallback) | Print document state callback. | -| [Print_PrinterDiscoveryCallback](#print_printerdiscoverycallback) | Printer discovery callback. | -| [Print_PrinterChangeCallback](#print_printerchangecallback) | Printer state change callback. | - -### Enumerations - -| Name | Description | +| [Print_StringList](#print_stringlist) | Defines a printer list.| +| [Print_Property](#print_property) | Defines a property for the printer.| +| [Print_PropertyList](#print_propertylist) | Defines a property list for the printer.| +| [Print_Resolution](#print_resolution) | Defines the resolution unit for printing.| +| [Print_Margin](#print_margin) | Defines the page margin.| +| [Print_PageSize](#print_pagesize) | Defines the page size for printing.| +| [Print_PrinterCapability](#print_printercapability) | Defines the printer capabilities.| +| [Print_DefaultValue](#print_defaultvalue) | Defines the default printing information.| +| [Print_PrinterInfo](#print_printerinfo) | Defines the printer information.| +| [Print_PrintJob](#print_printjob) | Defines a print job.| +| [Print_Range](#print_range) | Defines the page range.| +| [Print_PrintAttributes](#print_printattributes) | Defines the print attributes.| +| [Print_WriteResultCallback](#print_writeresultcallback) | Defines a callback used to return the write result.| +| [Print_OnStartLayoutWrite](#print_onstartlayoutwrite) | Defines a callback to be invoked when the layout processing starts.| +| [Print_OnJobStateChanged](#print_onjobstatechanged) | Defines a callback to be invoked when the print job state changes.| +| [Print_PrintDocCallback](#print_printdoccallback) | Defines a callback used to return the file state.| +| [Print_PrinterDiscoveryCallback](#print_printerdiscoverycallback) | Defines a callback used to return the discovered printers.| +| [Print_PrinterChangeCallback](#print_printerchangecallback) | Defines a callback to be invoked when the printer state changes.| + +### Enums + +| Name| Description| | -------- | -------- | -| [Print_ErrorCode](#print_errorcode) | Error codes. | -| [Print_PrinterState](#print_printerstate) | Printer state codes. | -| [Print_DiscoveryEvent](#print_discoveryevent) | Printer discovery events. | -| [Print_PrinterEvent](#print_printerevent) | Printer state change events. | -| [Print_DuplexMode](#print_duplexmode) | Print duplex mode. | -| [Print_ColorMode](#print_colormode) | Print color mode. | -| [Print_OrientationMode](#print_orientationmode) | Print orientation. | -| [Print_Quality](#print_quality) | Print quality. | -| [Print_DocumentFormat](#print_documentformat) | Printer document format. | -| [Print_JobDocAdapterState](#print_jobdocadapterstate) | Print job state. | +| [Print_ErrorCode](#print_errorcode) | Enumerates the error codes.| +| [Print_PrinterState](#print_printerstate) | Enumerates the printer state codes.| +| [Print_DiscoveryEvent](#print_discoveryevent) | Enumerates the printer discovery events.| +| [Print_PrinterEvent](#print_printerevent) | Enumerates the printer state change events.| +| [Print_DuplexMode](#print_duplexmode) | Enumerates the duplex modes for printing.| +| [Print_ColorMode](#print_colormode) | Enumerates the color modes for printing.| +| [Print_OrientationMode](#print_orientationmode) | Enumerates the orientation modes for printing.| +| [Print_Quality](#print_quality) | Enumerates the print quality.| +| [Print_DocumentFormat](#print_documentformat) | Enumerates the document formats.| +| [Print_JobDocAdapterState](#print_jobdocadapterstate) | Enumerates the print job adapter states.| ### Functions -| Name | Description | +| Name| Description| | -------- | -------- | -| [OH_Print_Init](#oh_print_init) | Starts the print service, initializes the print client, and establishes a connection to the print service. | -| [OH_Print_Release](#oh_print_release) | Closes the connection to the print service, unregisters callbacks, and releases print client resources. | -| [OH_Print_StartPrinterDiscovery](#oh_print_startprinterdiscovery) | Starts printer discovery. | -| [OH_Print_StopPrinterDiscovery](#oh_print_stopprinterdiscovery) | Stops printer discovery. | -| [OH_Print_ConnectPrinter](#oh_print_connectprinter) | Connects to a printer using the printer ID. | -| [OH_Print_StartPrintJob](#oh_print_startprintjob) | Starts a print job. | -| [OH_Print_RegisterPrinterChangeListener](#oh_print_registerprinterchangelistener) | Registers a printer state change event listener. | -| [OH_Print_UnregisterPrinterChangeListener](#oh_print_unregisterprinterchangelistener) | Unregisters the printer state change event listener. | -| [OH_Print_QueryPrinterList](#oh_print_queryprinterlist) | Queries the printer list. | -| [OH_Print_ReleasePrinterList](#oh_print_releaseprinterlist) | Releases the printer list. | -| [OH_Print_QueryPrinterInfo](#oh_print_queryprinterinfo) | Queries printer information. | -| [OH_Print_ReleasePrinterInfo](#oh_print_releaseprinterinfo) | Releases printer information memory. | -| [OH_Print_LaunchPrinterManager](#oh_print_launchprintermanager) | Launches the printer manager window. | -| [OH_Print_QueryPrinterProperties](#oh_print_queryprinterproperties) | Queries printer properties. | -| [OH_Print_ReleasePrinterProperties](#oh_print_releaseprinterproperties) | Releases printer properties. | -| [OH_Print_UpdatePrinterProperties](#oh_print_updateprinterproperties) | Updates printer properties. | -| [OH_Print_RestorePrinterProperties](#oh_print_restoreprinterproperties) | Restores printer properties to default settings based on the property key list. | -| [OH_Print_StartPrintByNative](#oh_print_startprintbynative) | Starts printing. | - -## Type Definitions +| [OH_Print_Init](#oh_print_init) | Initiates the print service, initializes the print client, and establishes a connection to the print service.| +| [OH_Print_Release](#oh_print_release) | Closes the connection to the print service, unregisters the callback, and releases the print client resources.| +| [OH_Print_StartPrinterDiscovery](#oh_print_startprinterdiscovery) | Starts printer discovery.| +| [OH_Print_StopPrinterDiscovery](#oh_print_stopprinterdiscovery) | Stops printer discovery.| +| [OH_Print_ConnectPrinter](#oh_print_connectprinter) | Connects to a printer by printer ID.| +| [OH_Print_StartPrintJob](#oh_print_startprintjob) | Starts a print job.| +| [OH_Print_RegisterPrinterChangeListener](#oh_print_registerprinterchangelistener) | Registers a listener to listen for the printer state changes.| +| [OH_Print_UnregisterPrinterChangeListener](#oh_print_unregisterprinterchangelistener) | Unregisters the listener used to listen for the printer state changes.| +| [OH_Print_QueryPrinterList](#oh_print_queryprinterlist) | Queries the printer list.| +| [OH_Print_ReleasePrinterList](#oh_print_releaseprinterlist) | Releases the memory allocated for querying the printer list.| +| [OH_Print_QueryPrinterInfo](#oh_print_queryprinterinfo) | Queries the printer information.| +| [OH_Print_ReleasePrinterInfo](#oh_print_releaseprinterinfo) | Releases the memory allocated for querying the printer information.| +| [OH_Print_LaunchPrinterManager](#oh_print_launchprintermanager) | Launches the printer manager.| +| [OH_Print_QueryPrinterProperties](#oh_print_queryprinterproperties) | Queries the printer properties.| +| [OH_Print_ReleasePrinterProperties](#oh_print_releaseprinterproperties) | Releases the memory allocated for querying the printer properties.| +| [OH_Print_UpdatePrinterProperties](#oh_print_updateprinterproperties) | Updates the printer properties.| +| [OH_Print_RestorePrinterProperties](#oh_print_restoreprinterproperties) | Restores printer properties to the default settings based on the property key list.| +| [OH_Print_StartPrintByNative](#oh_print_startprintbynative) | Starts printing.| + +## Type Description ### Print_StringList **Description** -Printer device list. +Defines a printer list. -**Since:** 12 +**Since**: 12 -| Member | Description | +| Member | Description | | ------------ | -------- | -| count | Number of strings. | -| list | String pointer array. | +| count | Number of strings.| +| list | String pointer array. | ### Print_Property **Description** -Printer property. +Defines a property for the printer. -**Since:** 12 +**Since**: 12 -| Member | Description | +| Member | Description | | -------- | ----------------------- | -| key | Property key. | -| value | Property value. | +| key | Property key.| +| value | Property value. | ### Print_PropertyList **Description** -Printer property list. +Defines a property list for the printer. -**Since:** 12 +**Since**: 12 -| Member | Description | +| Member | Description | | ------------ | ------------ | -| count | Number of properties. | -| list | Property pointer array. | +| count | Number of properties. | +| list | Property pointer array.| ### Print_Resolution **Description** -Print resolution unit. +Defines the resolution unit for printing. -**Since:** 12 +**Since**: 12 -| Parameter | Description | +| Parameter | Description | | ----------- | ---------- | -| horizontalDpi | Horizontal resolution (dpi). | -| verticalDpi | Vertical resolution (dpi). | +| horizontalDpi | Horizontal resolution (dpi).| +| verticalDpi | Vertical resolution (dpi). | ### Print_Margin **Description** -Print margin. +Defines the page margin. -**Since:** 12 +**Since**: 12 -| Parameter | Description | +| Parameter | Description | | ----------- | ---------- | -| leftMargin | Left margin (microns). | -| topMargin | Top margin (microns). | -| rightMargin | Right margin (microns). | -| bottomMargin | Bottom margin (microns). | +| leftMargin | Left margin (µm).| +| topMargin | Top margin (µm). | +| rightMargin | Right margin (µm). | +| bottomMargin | Bottom margin (µm). | ### Print_PageSize **Description** -Print paper size. +Defines the page size for printing. -**Since:** 12 +**Since**: 12 -| Parameter | Description | +| Parameter | Description | | ----------- | ---------- | -| id | Paper ID. | -| name | Paper name. | -| width | Paper width (microns). | -| height | Paper height (microns). | +| id | Page ID.| +| name | Page name. | +| width | Paper width (µm). | +| height | Paper height (µm). | ### Print_PrinterCapability **Description** -Printer capability. +Defines the printer capabilities. -**Since:** 12 +**Since**: 12 -| Parameter | Description | +| Parameter | Description | | ----------- | ---------- | -| supportedColorModes | Supported color modes list. | -| supportedColorModesCount | Number of supported color modes. | -| supportedDuplexModes | Supported duplex modes list. | -| supportedDuplexModesCount | Number of supported duplex modes. | -| supportedPageSizes | Supported paper sizes list. | -| supportedPageSizesCount | Number of supported paper sizes. | -| supportedMediaTypes | Supported media types (JSON string array format). | -| supportedQualities | Supported print qualities list. | -| supportedQualitiesCount | Number of supported print qualities. | -| supportedPaperSources | Supported paper sources (JSON string array format). | -| supportedCopies | Maximum supported copies. | -| supportedResolutions | Supported resolutions list. | -| supportedResolutionsCount | Number of supported resolutions. | -| supportedOrientations | Supported orientations list. | -| supportedOrientationsCount | Number of supported orientations. | -| advancedCapability | Advanced capability (JSON format). | +| supportedColorModes | Supported color modes.| +| supportedColorModesCount | Number of supported color modes. | +| supportedDuplexModes | Supported duplex modes. | +| supportedDuplexModesCount | Number of supported duplex modes. | +| supportedPageSizes | Supported page sizes. | +| supportedPageSizesCount | Number of supported paper sizes. | +| supportedMediaTypes | Supported media types (JSON string array format). | +| supportedQualities | Supported print qualities. | +| supportedQualitiesCount | Number of supported print qualities. | +| supportedPaperSources | Supported paper sources (JSON string array format). | +| supportedCopies | Maximum number of copies that can be printed. | +| supportedResolutions | Supported resolutions. | +| supportedResolutionsCount | Number of supported resolutions. | +| supportedOrientations | Supported printing orientations. | +| supportedOrientationsCount | Number of supported printing orientations. | +| advancedCapability | Advanced capabilities (JSON format). | ### Print_DefaultValue **Description** -Printer default information. +Defines the default printing information. -**Since:** 12 +**Since**: 12 -| Parameter | Description | +| Parameter | Description | | ----------- | ---------- | -| defaultColorMode | Default color mode. | -| defaultDuplexMode | Default duplex mode. | -| defaultMediaType | Default media type. | -| defaultPageSizeId | Default paper size ID. | -| defaultMargin | Default margin. | -| defaultPaperSource | Default paper source. | -| defaultPrintQuality | Default print quality. | -| defaultCopies | Default number of copies. | -| defaultResolution | Default resolution. | -| defaultOrientation | Default orientation. | -| otherDefaultValues | Other default values (JSON format). | +| defaultColorMode | Default color mode.| +| defaultDuplexMode | Default duplex mode. | +| defaultMediaType | Default media type. | +| defaultPageSizeId | Default page size ID. | +| defaultMargin | Default margin. | +| defaultPaperSource | Default paper source. | +| defaultPrintQuality | Default print quality. | +| defaultCopies | Default number of copies. | +| defaultResolution | Default resolution. | +| defaultOrientation | Default printing orientation. | +| otherDefaultValues | Other default values (JSON format). | ### Print_PrinterInfo **Description** -Printer information. +Defines the printer information. -**Since:** 12 +**Since**: 12 -| Parameter | Description | +| Parameter | Description | | ----------- | ---------- | -| printerState | Printer state. | -| capability | Printer capability. | -| defaultValue | Printer default properties. | -| isDefaultPrinter | Whether it is the default printer. | -| printerId | Printer ID. | -| printerName | Printer name. | -| description | Printer description. | -| location | Printer location. | -| makeAndModel | Printer manufacturer and model information. | -| printerUri | Printer URI. | -| detailInfo | Detailed information (JSON format). | +| printerState | Printer state.| +| capability | Printer capability. | +| defaultValue | Default printer property. | +| isDefaultPrinter | Whether the printer is the default one. | +| printerId | Printer ID. | +| printerName | Printer name. | +| description | Printer description. | +| location | Printer location. | +| makeAndModel | Printer manufacturer and model information. | +| printerUri | Printer URI. | +| detailInfo | Detailed information (JSON format). | ### Print_PrintJob **Description** -Print job. +Defines a print job. -**Since:** 12 +**Since**: 12 -| Parameter | Description | +| Parameter | Description | | ----------- | ---------- | -| jobName | Print job name. | -| fdList | Print file descriptor array. | -| fdListCount | Number of print file descriptors. | -| printerId | Printer ID. | -| copyNumber | Number of copies. | -| paperSource | Paper source. | -| mediaType | Media type. | -| pageSizeId | Paper size ID. | -| colorMode | Color mode. | -| duplexMode | Duplex mode. | -| resolution | Resolution. | -| printMargin | Print margin. | -| borderless | Whether to print borderless. | -| orientationMode | Print orientation. | -| printQuality | Print quality. | -| documentFormat | Document format. | -| advancedOptions | Advanced options (JSON format). | +| jobName | Print job name.| +| fdList | List of file descriptors of the print job. | +| fdListCount | Number of file descriptors of the print job. | +| printerId | Printer ID. | +| copyNumber | Number of copies to print. | +| paperSource | Paper source. | +| mediaType | Media type. | +| pageSizeId | Page size ID. | +| colorMode | Color mode. | +| duplexMode | Duplex mode. | +| resolution | Resolution. | +| printMargin | Page margin. | +| borderless | Whether to print without margins. | +| orientationMode | Orientation mode. | +| printQuality | Print quality. | +| documentFormat | Document format. | +| advancedOptions | Advanced options (JSON format). | ### Print_Range **Description** -Print range. +Defines the page range. -**Since:** 13 +**Since**: 13 -| Parameter | Description | +| Parameter | Description | | ----------- | ---------- | -| startPage | Start page number. | -| endPage | End page number. | -| pagesArrayLen | Page array length. | -| pagesArray | Page array. | +| startPage | Start page number.| +| endPage | End page number. | +| pagesArrayLen | Length of the page array. | +| pagesArray | Page array. | ### Print_PrintAttributes **Description** -Print attributes. +Defines the print attributes. -**Since:** 13 +**Since**: 13 -| Parameter | Description | +| Parameter | Description | | ----------- | ---------- | -| pageRange | Print range. | -| pageSize | Paper size. | -| pageMargin | Page margin. | -| copyNumber | Number of copies. | -| duplexMode | Duplex mode. | -| colorMode | Color mode. | -| isSequential | Whether to print sequentially. | -| isLandscape | Whether to print in landscape. | -| hasOption | Whether there are print options. | -| options | Print options (256 bytes). | +| pageRange | Defines the page range.| +| pageSize | Paper size. | +| pageMargin | Page margin. | +| copyNumber | Number of copies to print. | +| duplexMode | Duplex mode. | +| colorMode | Color mode. | +| isSequential | Whether to print in sequence. | +| isLandscape | Whether to print in landscape mode. | +| hasOption | Whether print options are provided. | +| options | Print options (in 256 bytes). | ### Print_WriteResultCallback **Description** -Write result callback. +Defines a callback used to return the write result. -**Since:** 13 +**Since**: 13 -**Parameters:** +**Parameters** -| Name | Description | +| Name | Description | | --------- | ---------- | -| jobId | Print job ID. | -| code | Write result status code. | +| jobId | Print job ID.| +| code | State code of the write result. | ### Print_OnStartLayoutWrite **Description** -Start layout callback. +Defines a callback to be invoked when the layout processing starts. -**Since:** 13 +**Since**: 13 -**Parameters:** +**Parameters** -| Name | Description | +| Name | Description | | --------- | ---------- | -| jobId | Print job ID. | -| fd | File descriptor. | -| oldAttrs | Previous print attributes. | -| newAttrs | Current print attributes. | -| writeCallback | Write result callback function. | +| jobId | Print job ID.| +| fd | File descriptor. | +| oldAttrs | Previous print attributes. | +| newAttrs | New print attributes. | +| writeCallback | Callback used to return the write result. | ### Print_OnJobStateChanged **Description** -Print job state change callback. +Defines a callback to be invoked when the print job state changes. -**Since:** 13 +**Since**: 13 -**Parameters:** +**Parameters** -| Name | Description | +| Name | Description | | --------- | ---------- | -| jobId | Print job ID. | -| state | Print job state. | +| jobId | Print job ID.| +| state | Print job state. | ### Print_PrintDocCallback **Description** -Print document state callback. +Defines a callback used to return the file state. -**Since:** 13 +**Since**: 13 -| Parameter | Description | +| Parameter | Description | | ----------- | ---------- | -| startLayoutWriteCb | Start layout write callback. | -| jobStateChangedCb | Job state change callback. | +| startLayoutWriteCb | Callback to be invoked when the layout processing starts.| +| jobStateChangedCb | Callback to be invoked when the print job state changes. | ### Print_PrinterDiscoveryCallback **Description** -Printer discovery callback. +Defines a callback used to return the discovered printers. -**Since:** 12 +**Since**: 12 -**Parameters:** +**Parameters** -| Name | Description | +| Name | Description | | --------- | ---------- | -| event | Discovery event. | -| printerInfo | Printer information. | +| event | Discovery event.| +| printerInfo | Printer information. | ### Print_PrinterChangeCallback **Description** -Printer state change callback. +Defines a callback to be invoked when the printer state changes. -**Since:** 12 +**Since**: 12 -**Parameters:** +**Parameters** -| Name | Description | +| Name | Description | | --------- | ---------- | -| event | Change event. | -| printerInfo | Printer information. | +| event | Change event.| +| printerInfo | Printer information. | -## Enumerations +## Enum Description ### Print_ErrorCode **Description** -Error codes. +Enumerates the error codes. -**Since:** 12 +**Since**: 12 -| Enum Value | Description | Value | +| Name| Description| Value| | -------- | -------- | -------- | -| PRINT_ERROR_NONE | Operation successful. | 0 | -| PRINT_ERROR_NO_PERMISSION | Permission verification failed. | 201 | -| PRINT_ERROR_INVALID_PARAMETER | Invalid parameter. | 401 | -| PRINT_ERROR_GENERIC_FAILURE | Generic internal error. | 24300001 | -| PRINT_ERROR_RPC_FAILURE | RPC communication error. | 24300002 | -| PRINT_ERROR_SERVER_FAILURE | Server error. | 24300003 | -| PRINT_ERROR_INVALID_EXTENSION | Invalid extension. | 24300004 | -| PRINT_ERROR_INVALID_PRINTER | Invalid printer. | 24300005 | -| PRINT_ERROR_INVALID_PRINT_JOB | Invalid print job. | 24300006 | -| PRINT_ERROR_FILE_IO | File I/O error. | 24300007 | -| PRINT_ERROR_UNKNOWN | Unknown error. | 24300255 | +| PRINT_ERROR_NONE | Operation successful.| 0 | +| PRINT_ERROR_NO_PERMISSION | Permission verification failed.| 201 | +| PRINT_ERROR_INVALID_PARAMETER | Invalid parameter.| 401 | +| PRINT_ERROR_GENERIC_FAILURE | Internal error.| 24300001 | +| PRINT_ERROR_RPC_FAILURE | RPC communication error.| 24300002 | +| PRINT_ERROR_SERVER_FAILURE | Server error.| 24300003 | +| PRINT_ERROR_INVALID_EXTENSION | Invalid extension.| 24300004 | +| PRINT_ERROR_INVALID_PRINTER | Invalid printer.| 24300005 | +| PRINT_ERROR_INVALID_PRINT_JOB | Invalid print job.| 24300006 | +| PRINT_ERROR_FILE_IO | File I/O operation failed.| 24300007 | +| PRINT_ERROR_UNKNOWN | Unknown error.| 24300255 | ### Print_PrinterState **Description** -Printer state codes. +Enumerates the printer state codes. -**Since:** 12 +**Since**: 12 -| Enum Value | Description | +| Name| Description| | -------- | -------- | -| PRINTER_IDLE | Printer idle. | -| PRINTER_BUSY | Printer busy. | -| PRINTER_UNAVAILABLE | Printer unavailable. | +| PRINTER_IDLE | The printer is idle.| +| PRINTER_BUSY | The printer is busy.| +| PRINTER_UNAVAILABLE | The printer is unavailable.| ### Print_DiscoveryEvent **Description** -Printer discovery events. +Enumerates the printer discovery events. -**Since:** 12 +**Since**: 12 -| Enum Value | Description | +| Name| Description| | -------- | -------- | -| PRINTER_DISCOVERED | Printer discovered. | -| PRINTER_LOST | Printer lost. | -| PRINTER_CONNECTING | Printer connecting. | -| PRINTER_CONNECTED | Printer connected. | +| PRINTER_DISCOVERED | Printer discovered.| +| PRINTER_LOST | Printer lost.| +| PRINTER_CONNECTING | Printer connecting.| +| PRINTER_CONNECTED | Printer connected.| ### Print_PrinterEvent **Description** -Printer events. +Enumerates the printer state change events. -**Since:** 12 +**Since**: 12 -| Enum Value | Description | +| Name| Description| | -------- | -------- | -| PRINTER_ADDED | Printer added. | -| PRINTER_DELETED | Printer deleted. | -| PRINTER_STATE_CHANGED | Printer state changed. | -| PRINTER_INFO_CHANGED | Printer information changed. | -| PRINTER_PREFERENCE_CHANGED | Printer preference changed. | +| PRINTER_ADDED | A printer is added.| +| PRINTER_DELETED | A printer is deleted.| +| PRINTER_STATE_CHANGED | The printer state has changed.| +| PRINTER_INFO_CHANGED | The printer information has changed.| +| PRINTER_PREFERENCE_CHANGED | The printer preferences have changed.| ### Print_DuplexMode **Description** -Print duplex mode. +Enumerates the duplex modes for printing. -**Since:** 12 +**Since**: 12 -| Enum Value | Description | +| Name| Description| | -------- | -------- | -| DUPLEX_MODE_ONE_SIDED | One-sided printing. | -| DUPLEX_MODE_TWO_SIDED_LONG_EDGE | Two-sided long edge printing. | -| DUPLEX_MODE_TWO_SIDED_SHORT_EDGE | Two-sided short edge printing. | +| DUPLEX_MODE_ONE_SIDED | Single-sided printing.| +| DUPLEX_MODE_TWO_SIDED_LONG_EDGE | Long-edge duplex printing.| +| DUPLEX_MODE_TWO_SIDED_SHORT_EDGE | Short-edge duplex printing.| ### Print_ColorMode **Description** -Print color mode. +Enumerates the color modes for printing. -**Since:** 12 +**Since**: 12 -| Enum Value | Description | +| Name| Description| | -------- | -------- | -| COLOR_MODE_MONOCHROME | Monochrome mode. | -| COLOR_MODE_COLOR | Color mode. | -| COLOR_MODE_AUTO | Auto mode. | +| COLOR_MODE_MONOCHROME | Monochrome mode.| +| COLOR_MODE_COLOR | Color mode.| +| COLOR_MODE_AUTO | Auto mode.| ### Print_OrientationMode **Description** -Print orientation. +Enumerates the orientation modes for printing. -**Since:** 12 +**Since**: 12 -| Enum Value | Description | +| Name| Description| | -------- | -------- | -| ORIENTATION_MODE_PORTRAIT | Portrait. | -| ORIENTATION_MODE_LANDSCAPE | Landscape. | -| ORIENTATION_MODE_REVERSE_LANDSCAPE | Reverse landscape. | -| ORIENTATION_MODE_REVERSE_PORTRAIT | Reverse portrait. | -| ORIENTATION_MODE_NONE | Not specified. | +| ORIENTATION_MODE_PORTRAIT | Portrait.| +| ORIENTATION_MODE_LANDSCAPE | Landscape.| +| ORIENTATION_MODE_REVERSE_LANDSCAPE | Reverse landscape.| +| ORIENTATION_MODE_REVERSE_PORTRAIT | Reverse portrait.| +| ORIENTATION_MODE_NONE | Not specified.| ### Print_Quality **Description** -Print quality. +Enumerates the print qualities. -**Since:** 12 +**Since**: 12 -| Enum Value | Description | +| Name| Description| | -------- | -------- | -| PRINT_QUALITY_DRAFT | Draft quality. | -| PRINT_QUALITY_NORMAL | Normal quality. | -| PRINT_QUALITY_HIGH | High quality. | +| PRINT_QUALITY_DRAFT | Draft quality.| +| PRINT_QUALITY_NORMAL | Normal quality.| +| PRINT_QUALITY_HIGH | High quality.| ### Print_DocumentFormat **Description** -Document format. +Enumerates the document formats. -**Since:** 12 +**Since**: 12 -| Enum Value | Description | MIME Type | +| Name| Description| MIME Type| | -------- | -------- | -------- | -| DOCUMENT_FORMAT_AUTO | Auto detect. | application/octet-stream. | -| DOCUMENT_FORMAT_JPEG | JPEG image. | image/jpeg. | -| DOCUMENT_FORMAT_PDF | PDF document. | application/pdf. | -| DOCUMENT_FORMAT_POSTSCRIPT | PostScript document. | application/postscript. | -| DOCUMENT_FORMAT_TEXT | Plain text. | text/plain. | +| DOCUMENT_FORMAT_AUTO | Auto-detected format.| application/octet-stream. | +| DOCUMENT_FORMAT_JPEG | JPEG image.| image/jpeg. | +| DOCUMENT_FORMAT_PDF | PDF document.| application/pdf. | +| DOCUMENT_FORMAT_POSTSCRIPT | PostScript document.| application/postscript. | +| DOCUMENT_FORMAT_TEXT | Plain text.| text/plain. | ### Print_JobDocAdapterState **Description** -Print job document adapter state. +Enumerates the print job adapter states. -**Since:** 13 +**Since**: 13 -| Enum Value | Description | +| Name| Description| | -------- | -------- | -| PRINT_DOC_ADAPTER_PREVIEW_ABILITY_DESTROY | Print preview ability destroyed. | -| PRINT_DOC_ADAPTER_PRINT_TASK_SUCCEED | Print task succeeded. | -| PRINT_DOC_ADAPTER_PRINT_TASK_FAIL | Print task failed. | -| PRINT_DOC_ADAPTER_PRINT_TASK_CANCEL | Print task canceled. | -| PRINT_DOC_ADAPTER_PRINT_TASK_BLOCK | Print task blocked. | -| PRINT_DOC_ADAPTER_PREVIEW_ABILITY_DESTROY_FOR_CANCELED | Preview ability destroyed due to cancellation. | -| PRINT_DOC_ADAPTER_PREVIEW_ABILITY_DESTROY_FOR_STARTED | Preview ability destroyed due to task start. | +| PRINT_DOC_ADAPTER_PREVIEW_ABILITY_DESTROY | Preview destroyed.| +| PRINT_DOC_ADAPTER_PRINT_TASK_SUCCEED | Successful print job.| +| PRINT_DOC_ADAPTER_PRINT_TASK_FAIL | Print job failed.| +| PRINT_DOC_ADAPTER_PRINT_TASK_CANCEL | Print job canceled.| +| PRINT_DOC_ADAPTER_PRINT_TASK_BLOCK | Print job blocked.| +| PRINT_DOC_ADAPTER_PREVIEW_ABILITY_DESTROY_FOR_CANCELED | Preview destroyed due to print job cancellation.| +| PRINT_DOC_ADAPTER_PREVIEW_ABILITY_DESTROY_FOR_STARTED | Preview destroyed due to print job start.| -## Function Documentation +## Function Description ### OH_Print_Init() @@ -550,22 +550,22 @@ Print_ErrorCode OH_Print_Init(); **Description** -Starts the print service, initializes the print client, and establishes a connection to the print service. +Initiates the print service, initializes the print client, and establishes a connection to the print service. -**Permission:** ohos.permission.PRINT +**Required permissions**: ohos.permission.PRINT -**System Capability:** SystemCapability.Print.PrintFramework +**System capability**: SystemCapability.Print.PrintFramework -**Since:** 12 +**Since**: 12 -**Returns:** +**Returns** -| Error Code | Description | +| Error Code| Description| | -------- | -------- | -| PRINT_ERROR_NONE | Operation successful. | -| PRINT_ERROR_NO_PERMISSION | Missing print permission. | -| PRINT_ERROR_RPC_FAILURE | Unable to connect to print service. | -| PRINT_ERROR_SERVER_FAILURE | CUPS service failed to start. | +| PRINT_ERROR_NONE | Operation successful.| +| PRINT_ERROR_NO_PERMISSION | Permission denied.| +| PRINT_ERROR_RPC_FAILURE | Failed to connect to the print service.| +| PRINT_ERROR_SERVER_FAILURE | Failed to start the CUPS service.| ### OH_Print_Release() @@ -575,17 +575,17 @@ Print_ErrorCode OH_Print_Release(); **Description** -Closes the connection to the print service, unregisters callbacks, and releases print client resources. +Closes the connection to the print service, unregisters the callback, and releases the print client resources. -**System Capability:** SystemCapability.Print.PrintFramework +**System capability**: SystemCapability.Print.PrintFramework -**Since:** 12 +**Since**: 12 -**Returns:** +**Returns** -| Error Code | Description | +| Error Code| Description| | -------- | -------- | -| PRINT_ERROR_NONE | Operation successful. | +| PRINT_ERROR_NONE | Operation successful.| ### OH_Print_StartPrinterDiscovery() @@ -595,29 +595,29 @@ Print_ErrorCode OH_Print_StartPrinterDiscovery(Print_PrinterDiscoveryCallback ca **Description** -Starts the printer discovery process. +Starts printer discovery. -**Permission:** ohos.permission.PRINT +**Required permissions**: ohos.permission.PRINT -**System Capability:** SystemCapability.Print.PrintFramework +**System capability**: SystemCapability.Print.PrintFramework -**Since:** 12 +**Since**: 12 -**Parameters:** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| callback | Printer discovery event callback function. | +| callback | callback used to return the discovered printers.| -**Returns:** +**Returns** -| Error Code | Description | +| Error Code| Description| | -------- | -------- | -| PRINT_ERROR_NONE | Operation successful. | -| PRINT_ERROR_NO_PERMISSION | Missing print permission. | -| PRINT_ERROR_RPC_FAILURE | Unable to connect to print service. | -| PRINT_ERROR_SERVER_FAILURE | Failed to query print extension list from BMS. | -| PRINT_ERROR_INVALID_EXTENSION | No available print extensions found. | +| PRINT_ERROR_NONE | Operation successful.| +| PRINT_ERROR_NO_PERMISSION | Permission denied.| +| PRINT_ERROR_RPC_FAILURE | Failed to connect to the print service.| +| PRINT_ERROR_SERVER_FAILURE | Failed to query the extended printing list from the BMS.| +| PRINT_ERROR_INVALID_EXTENSION | Invalid print extension.| ### OH_Print_StopPrinterDiscovery() @@ -627,21 +627,21 @@ Print_ErrorCode OH_Print_StopPrinterDiscovery(); **Description** -Stops the printer discovery process. +Stops printer discovery. -**Permission:** ohos.permission.PRINT +**Required permissions**: ohos.permission.PRINT -**System Capability:** SystemCapability.Print.PrintFramework +**System capability**: SystemCapability.Print.PrintFramework -**Since:** 12 +**Since**: 12 -**Returns:** +**Returns** -| Error Code | Description | +| Error Code| Description| | -------- | -------- | -| PRINT_ERROR_NONE | Operation successful. | -| PRINT_ERROR_NO_PERMISSION | Missing print permission. | -| PRINT_ERROR_RPC_FAILURE | Unable to connect to print service. | +| PRINT_ERROR_NONE | Operation successful.| +| PRINT_ERROR_NO_PERMISSION | Permission denied.| +| PRINT_ERROR_RPC_FAILURE | Failed to connect to the print service.| ### OH_Print_ConnectPrinter() @@ -651,29 +651,29 @@ Print_ErrorCode OH_Print_ConnectPrinter(const char *printerId); **Description** -Connects to a printer using the printer ID. +Connects to a printer by printer ID. -**Permission:** ohos.permission.PRINT +**Required permissions**: ohos.permission.PRINT -**System Capability:** SystemCapability.Print.PrintFramework +**System capability**: SystemCapability.Print.PrintFramework -**Since:** 12 +**Since**: 12 -**Parameters:** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| printerId | Printer ID to connect to. | +| printerId | ID of the printer to be connected.| -**Returns:** +**Returns** -| Error Code | Description | +| Error Code| Description| | -------- | -------- | -| PRINT_ERROR_NONE | Operation successful. | -| PRINT_ERROR_NO_PERMISSION | Missing print permission. | -| PRINT_ERROR_RPC_FAILURE | Unable to connect to print service. | -| PRINT_ERROR_INVALID_PRINTER | Printer not in discovered list. | -| PRINT_ERROR_SERVER_FAILURE | Unable to find extension responsible for the printer. | +| PRINT_ERROR_NONE | Operation successful.| +| PRINT_ERROR_NO_PERMISSION | Permission denied.| +| PRINT_ERROR_RPC_FAILURE | Failed to connect to the print service.| +| PRINT_ERROR_INVALID_PRINTER | Failed to find the printer in the discovery list.| +| PRINT_ERROR_SERVER_FAILURE | Failed to find the printer extension.| ### OH_Print_StartPrintJob() @@ -685,28 +685,28 @@ Print_ErrorCode OH_Print_StartPrintJob(const Print_PrintJob *printJob); Starts a print job. -**Permission:** ohos.permission.PRINT +**Required permissions**: ohos.permission.PRINT -**System Capability:** SystemCapability.Print.PrintFramework +**System capability**: SystemCapability.Print.PrintFramework -**Since:** 12 +**Since**: 12 -**Parameters:** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| printJob | Pointer to Print_PrintJob structure containing print job information. | +| printJob | Pointer to the **Print_PrintJob** struct that contains the print job information.| -**Returns:** +**Returns** -| Error Code | Description | +| Error Code| Description| | -------- | -------- | -| PRINT_ERROR_NONE | Operation successful. | -| PRINT_ERROR_NO_PERMISSION | Missing print permission. | -| PRINT_ERROR_RPC_FAILURE | Unable to connect to print service. | -| PRINT_ERROR_INVALID_PRINTER | Printer not in connected list. | -| PRINT_ERROR_SERVER_FAILURE | Failed to create print job in print service. | -| PRINT_ERROR_INVALID_PRINT_JOB | Unable to find job in job queue. | +| PRINT_ERROR_NONE | Operation successful.| +| PRINT_ERROR_NO_PERMISSION | Permission denied.| +| PRINT_ERROR_RPC_FAILURE | Failed to connect to the print service.| +| PRINT_ERROR_INVALID_PRINTER | Failed to find the printer in the connection list.| +| PRINT_ERROR_SERVER_FAILURE | Failed to create a print job in the print service.| +| PRINT_ERROR_INVALID_PRINT_JOB | Invalid print job.| ### OH_Print_RegisterPrinterChangeListener() @@ -716,27 +716,27 @@ Print_ErrorCode OH_Print_RegisterPrinterChangeListener(Print_PrinterChangeCallba **Description** -Registers a printer state change listener. +Registers a listener to listen for the printer state changes. -**Permission:** ohos.permission.PRINT +**Required permissions**: ohos.permission.PRINT -**System Capability:** SystemCapability.Print.PrintFramework +**System capability**: SystemCapability.Print.PrintFramework -**Since:** 12 +**Since**: 12 -**Parameters:** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| callback | Printer state change callback function. | +| callback | Callback to be invoked when the printer state changes.| -**Returns:** +**Returns** -| Error Code | Description | +| Error Code| Description| | -------- | -------- | -| PRINT_ERROR_NONE | Operation successful. | -| PRINT_ERROR_NO_PERMISSION | Missing print permission. | -| PRINT_ERROR_RPC_FAILURE | Unable to connect to print service. | +| PRINT_ERROR_NONE | Operation successful.| +| PRINT_ERROR_NO_PERMISSION | Permission denied.| +| PRINT_ERROR_RPC_FAILURE | Failed to connect to the print service.| ### OH_Print_UnregisterPrinterChangeListener() @@ -746,13 +746,13 @@ void OH_Print_UnregisterPrinterChangeListener(); **Description** -Unregisters the printer state change listener. +Unregisters the listener used to listen for the printer state changes. -**Permission:** ohos.permission.PRINT +**Required permissions**: ohos.permission.PRINT -**System Capability:** SystemCapability.Print.PrintFramework +**System capability**: SystemCapability.Print.PrintFramework -**Since:** 12 +**Since**: 12 ### OH_Print_QueryPrinterList() @@ -762,29 +762,29 @@ Print_ErrorCode OH_Print_QueryPrinterList(Print_StringList *printerIdList); **Description** -Queries the list of added printers. +Queries the printer list. -**Permission:** ohos.permission.PRINT +**Required permissions**: ohos.permission.PRINT -**System Capability:** SystemCapability.Print.PrintFramework +**System capability**: SystemCapability.Print.PrintFramework -**Since:** 12 +**Since**: 12 -**Parameters:** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| printerIdList | Pointer to Print_StringList to store the queried printer ID list. | +| printerIdList | Pointer to **Print_StringList** that stores the query result.| -**Returns:** +**Returns** -| Error Code | Description | +| Error Code| Description| | -------- | -------- | -| PRINT_ERROR_NONE | Operation successful. | -| PRINT_ERROR_NO_PERMISSION | Missing print permission. | -| PRINT_ERROR_INVALID_PARAMETER | printerIdList is NULL. | -| PRINT_ERROR_INVALID_PRINTER | Unable to query any connected printers. | -| PRINT_ERROR_GENERIC_FAILURE | Unable to copy printer ID list. | +| PRINT_ERROR_NONE | Operation successful.| +| PRINT_ERROR_NO_PERMISSION | Permission denied.| +| PRINT_ERROR_INVALID_PARAMETER | **printerIdList** is null.| +| PRINT_ERROR_INVALID_PRINTER | Failed to query any connected printers.| +| PRINT_ERROR_GENERIC_FAILURE | Failed to copy the printer ID list.| ### OH_Print_ReleasePrinterList() @@ -794,17 +794,17 @@ void OH_Print_ReleasePrinterList(Print_StringList *printerIdList); **Description** -Releases memory allocated for printer list query. +Releases the memory allocated for querying the printer list. -**System Capability:** SystemCapability.Print.PrintFramework +**System capability**: SystemCapability.Print.PrintFramework -**Since:** 12 +**Since**: 12 -**Parameters:** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| printerIdList | Printer ID list to be released. | +| printerIdList | Printer ID list queried.| ### OH_Print_QueryPrinterInfo() @@ -814,30 +814,30 @@ Print_ErrorCode OH_Print_QueryPrinterInfo(const char *printerId, Print_PrinterIn **Description** -Queries printer information based on printer ID. +Queries printer information based on the printer ID. -**Permission:** ohos.permission.PRINT +**Required permissions**: ohos.permission.PRINT -**System Capability:** SystemCapability.Print.PrintFramework +**System capability**: SystemCapability.Print.PrintFramework -**Since:** 12 +**Since**: 12 -**Parameters:** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| printerId | Printer ID to query. | -| printerInfo | Pointer to Print_PrinterInfo pointer to store printer information. | +| printerId | Printer ID to be queried.| +| printerInfo | Pointer to **Print_PrinterInfo** that stores the query result.| -**Returns:** +**Returns** -| Error Code | Description | +| Error Code| Description| | -------- | -------- | -| PRINT_ERROR_NONE | Operation successful. | -| PRINT_ERROR_NO_PERMISSION | Missing print permission. | -| PRINT_ERROR_RPC_FAILURE | Unable to connect to print service. | -| PRINT_ERROR_INVALID_PARAMETER | printerId or printerInfo is NULL. | -| PRINT_ERROR_INVALID_PRINTER | Unable to find printer in connected printer list. | +| PRINT_ERROR_NONE | Operation successful.| +| PRINT_ERROR_NO_PERMISSION | Permission denied.| +| PRINT_ERROR_RPC_FAILURE | Failed to connect to the print service.| +| PRINT_ERROR_INVALID_PARAMETER | **printerId** or **printerInfo** is null.| +| PRINT_ERROR_INVALID_PRINTER | Failed to find the printer in the connection list.| ### OH_Print_ReleasePrinterInfo() @@ -847,17 +847,17 @@ void OH_Print_ReleasePrinterInfo(Print_PrinterInfo *printerInfo); **Description** -Releases memory allocated for printer information query. +Releases the memory allocated for querying the printer information. -**System Capability:** SystemCapability.Print.PrintFramework +**System capability**: SystemCapability.Print.PrintFramework -**Since:** 12 +**Since**: 12 -**Parameters:** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| printerInfo | Pointer to queried printer information to be released. | +| printerInfo | Pointer to the printer information.| ### OH_Print_LaunchPrinterManager() @@ -867,18 +867,18 @@ Print_ErrorCode OH_Print_LaunchPrinterManager(); **Description** -Launches the system's printer management window. +Launches the system printer manager. -**System Capability:** SystemCapability.Print.PrintFramework +**System capability**: SystemCapability.Print.PrintFramework -**Since:** 12 +**Since**: 12 -**Returns:** +**Returns** -| Error Code | Description | +| Error Code| Description| | -------- | -------- | -| PRINT_ERROR_NONE | Operation successful. | -| PRINT_ERROR_GENERIC_FAILURE | Unable to launch printer manager window. | +| PRINT_ERROR_NONE | Operation successful.| +| PRINT_ERROR_GENERIC_FAILURE | Failed to launch the printer manager.| ### OH_Print_QueryPrinterProperties() @@ -890,31 +890,31 @@ Print_ErrorCode OH_Print_QueryPrinterProperties(const char *printerId, **Description** -Queries printer property values based on property key list. +Queries printer properties based on the property key list. -**Permission:** ohos.permission.PRINT +**Required permissions**: ohos.permission.PRINT -**System Capability:** SystemCapability.Print.PrintFramework +**System capability**: SystemCapability.Print.PrintFramework -**Since:** 12 +**Since**: 12 -**Parameters:** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| printerId | Printer ID to query. | -| propertyKeyList | List of property keys to query. | -| propertyList | List of queried printer property values. | +| printerId | Printer ID to be queried.| +| propertyKeyList | List of property keys.| +| propertyList | Property list used to store the query result.| -**Returns:** +**Returns** -| Error Code | Description | +| Error Code| Description| | -------- | -------- | -| PRINT_ERROR_NONE | Operation successful. | -| PRINT_ERROR_NO_PERMISSION | Missing print permission. | -| PRINT_ERROR_INVALID_PARAMETER | One of the parameters is NULL or key list is empty. | -| PRINT_ERROR_INVALID_PRINTER | Printer properties for specified printer not found. | -| PRINT_ERROR_GENERIC_FAILURE | Unable to copy printer properties. | +| PRINT_ERROR_NONE | Operation successful.| +| PRINT_ERROR_NO_PERMISSION | Permission denied.| +| PRINT_ERROR_INVALID_PARAMETER | The parameter is null or the key list is empty.| +| PRINT_ERROR_INVALID_PRINTER | Failed to find printer properties.| +| PRINT_ERROR_GENERIC_FAILURE | Failed to copy the printer properties.| ### OH_Print_ReleasePrinterProperties() @@ -924,17 +924,17 @@ void OH_Print_ReleasePrinterProperties(Print_PropertyList *propertyList); **Description** -Releases memory allocated for printer properties query. +Releases the memory allocated for querying the printer properties. -**System Capability:** SystemCapability.Print.PrintFramework +**System capability**: SystemCapability.Print.PrintFramework -**Since:** 12 +**Since**: 12 -**Parameters:** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| propertyList | Pointer to queried printer properties to be released. | +| propertyList | Pointer to the property list.| ### OH_Print_UpdatePrinterProperties() @@ -945,28 +945,28 @@ Print_ErrorCode OH_Print_UpdatePrinterProperties(const char *printerId, **Description** -Sets printer properties based on property key-value pair list. +Updates the printer properties based on the KV pairs. -**Permission:** ohos.permission.PRINT +**Required permissions**: ohos.permission.PRINT -**System Capability:** SystemCapability.Print.PrintFramework +**System capability**: SystemCapability.Print.PrintFramework -**Since:** 12 +**Since**: 12 -**Parameters:** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| printerId | Printer ID to set. | -| propertyList | List of printer property values to set. | +| printerId | Printer ID to be set.| +| propertyList | Property list to be set.| -**Returns:** +**Returns** -| Error Code | Description | +| Error Code| Description| | -------- | -------- | -| PRINT_ERROR_NONE | Operation successful. | -| PRINT_ERROR_NO_PERMISSION | Missing print permission. | -| PRINT_ERROR_RPC_FAILURE | Unable to connect to print service. | +| PRINT_ERROR_NONE | Operation successful.| +| PRINT_ERROR_NO_PERMISSION | Permission denied.| +| PRINT_ERROR_RPC_FAILURE | Failed to connect to the print service.| ### OH_Print_RestorePrinterProperties() @@ -977,28 +977,28 @@ Print_ErrorCode OH_Print_RestorePrinterProperties(const char *printerId, **Description** -Restores printer properties to default settings based on property key list. +Restores printer properties to the default settings based on the property key list. -**Permission:** ohos.permission.PRINT +**Required permissions**: ohos.permission.PRINT -**System Capability:** SystemCapability.Print.PrintFramework +**System capability**: SystemCapability.Print.PrintFramework -**Since:** 12 +**Since**: 12 -**Parameters:** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| printerId | Printer ID to restore. | -| propertyKeyList | List of property keys to restore. | +| printerId | Printer ID to be restored.| +| propertyKeyList | Property list to be restored.| -**Returns:** +**Returns** -| Error Code | Description | +| Error Code| Description| | -------- | -------- | -| PRINT_ERROR_NONE | Operation successful. | -| PRINT_ERROR_NO_PERMISSION | Missing print permission. | -| PRINT_ERROR_RPC_FAILURE | Unable to connect to print service. | +| PRINT_ERROR_NONE | Operation successful.| +| PRINT_ERROR_NO_PERMISSION | Permission denied.| +| PRINT_ERROR_RPC_FAILURE | Failed to connect to the print service.| ### OH_Print_StartPrintByNative() @@ -1010,26 +1010,26 @@ Print_ErrorCode OH_Print_StartPrintByNative(const char *printJobName, **Description** -Starts print service. +Starts printing. -**Permission:** ohos.permission.PRINT +**Required permissions**: ohos.permission.PRINT -**System Capability:** SystemCapability.Print.PrintFramework +**System capability**: SystemCapability.Print.PrintFramework -**Since:** 13 +**Since**: 13 -**Parameters:** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| printJobName | Print job name. | -| printDocCallback | Print document state callback. | -| context | Caller application context. | +| printJobName | Print job name.| +| printDocCallback | Callback used to return the file state.| +| context | Context of the caller.| -**Returns:** +**Returns** -| Error Code | Description | +| Error Code| Description| | -------- | -------- | -| PRINT_ERROR_NONE | Operation successful. | -| PRINT_ERROR_NO_PERMISSION | Missing print permission. | -| PRINT_ERROR_RPC_FAILURE | Unable to connect to print service. | \ No newline at end of file +| PRINT_ERROR_NONE | Operation successful.| +| PRINT_ERROR_NO_PERMISSION | Permission denied.| +| PRINT_ERROR_RPC_FAILURE | Failed to connect to the print service.| diff --git a/en/application-dev/reference/apis-basic-services-kit/_print___margin.md b/en/application-dev/reference/apis-basic-services-kit/_print___margin.md index bb94c0f0e7a..bcbae5bc567 100644 --- a/en/application-dev/reference/apis-basic-services-kit/_print___margin.md +++ b/en/application-dev/reference/apis-basic-services-kit/_print___margin.md @@ -9,18 +9,19 @@ Defines the page margin. **Related module**: [OH_Print](_o_h___print.md) +**Header file**: [ohprint.h](ohprint_8h.md) ## Summary ### Member Variables -| Name| Description| +| Name| Description| | -------- | -------- | -| uint32_t [leftMargin](#leftmargin) | Defines the left margin. | -| uint32_t [topMargin](#topmargin) | Defines the top margin. | -| uint32_t [rightMargin](#rightmargin) | Defines the right margin. | -| uint32_t [bottomMargin](#bottommargin) | Defines the bottom margin. | +| uint32_t [leftMargin](#leftmargin) | Defines the left margin. | +| uint32_t [topMargin](#topmargin) | Defines the top margin. | +| uint32_t [rightMargin](#rightmargin) | Defines the right margin. | +| uint32_t [bottomMargin](#bottommargin) | Defines the bottom margin. | ## Member Variable Description @@ -32,6 +33,7 @@ Defines the page margin. uint32_t Print_Margin::bottomMargin ``` **Description** + Defines the bottom margin. @@ -41,6 +43,7 @@ Defines the bottom margin. uint32_t Print_Margin::leftMargin ``` **Description** + Defines the left margin. @@ -50,6 +53,7 @@ Defines the left margin. uint32_t Print_Margin::rightMargin ``` **Description** + Defines the right margin. @@ -59,4 +63,5 @@ Defines the right margin. uint32_t Print_Margin::topMargin ``` **Description** + Defines the top margin. diff --git a/en/application-dev/reference/apis-basic-services-kit/_print___page_size.md b/en/application-dev/reference/apis-basic-services-kit/_print___page_size.md index cd511e27ab7..4e69a35b57e 100644 --- a/en/application-dev/reference/apis-basic-services-kit/_print___page_size.md +++ b/en/application-dev/reference/apis-basic-services-kit/_print___page_size.md @@ -3,12 +3,13 @@ ## Overview -Defines the page size and related information. +Defines the page size. **Since**: 12 **Related module**: [OH_Print](_o_h___print.md) +**Header file**: [ohprint.h](ohprint_8h.md) ## Summary @@ -32,6 +33,7 @@ Defines the page size and related information. uint32_t Print_PageSize::height ``` **Description** + Defines the page height. @@ -41,6 +43,7 @@ Defines the page height. char* Print_PageSize::id ``` **Description** + Defines the page ID. @@ -50,6 +53,7 @@ Defines the page ID. char* Print_PageSize::name ``` **Description** + Defines the page name. @@ -59,4 +63,5 @@ Defines the page name. uint32_t Print_PageSize::width ``` **Description** + Defines the page width. diff --git a/en/application-dev/reference/apis-basic-services-kit/_print___print_attributes.md b/en/application-dev/reference/apis-basic-services-kit/_print___print_attributes.md index 403ff0ab905..e0445e7c06c 100644 --- a/en/application-dev/reference/apis-basic-services-kit/_print___print_attributes.md +++ b/en/application-dev/reference/apis-basic-services-kit/_print___print_attributes.md @@ -9,6 +9,7 @@ Defines the print attributes. **Related module**: [OH_Print](_o_h___print.md) +**Header file**: [ohprint.h](ohprint_8h.md) ## Summary @@ -38,6 +39,7 @@ Defines the print attributes. uint32_t Print_PrintAttributes::colorMode ``` **Description** + Defines the color mode. @@ -47,6 +49,7 @@ Defines the color mode. uint32_t Print_PrintAttributes::copyNumber ``` **Description** + Defines the number of copies to print. @@ -56,6 +59,7 @@ Defines the number of copies to print. uint32_t Print_PrintAttributes::duplexMode ``` **Description** + Defines the duplex mode. @@ -65,6 +69,7 @@ Defines the duplex mode. bool Print_PrintAttributes::hasOption ``` **Description** + Defines whether the printing has an option flag. @@ -74,6 +79,7 @@ Defines whether the printing has an option flag. bool Print_PrintAttributes::isLandscape ``` **Description** + Defines whether to print in the landscape mode. @@ -83,6 +89,7 @@ Defines whether to print in the landscape mode. bool Print_PrintAttributes::isSequential ``` **Description** + Defines whether to print in a sequential manner. @@ -92,6 +99,7 @@ Defines whether to print in a sequential manner. char Print_PrintAttributes::options[256] ``` **Description** + Defines the printing options. @@ -101,6 +109,7 @@ Defines the printing options. Print_Margin Print_PrintAttributes::pageMargin ``` **Description** + Defines the page margin. @@ -110,6 +119,7 @@ Defines the page margin. Print_Range Print_PrintAttributes::pageRange ``` **Description** + Defines the page range. @@ -119,4 +129,5 @@ Defines the page range. Print_PageSize Print_PrintAttributes::pageSize ``` **Description** + Defines the page size. diff --git a/en/application-dev/reference/apis-basic-services-kit/_print___print_doc_callback.md b/en/application-dev/reference/apis-basic-services-kit/_print___print_doc_callback.md index eeb9e7cd483..c6da71ffb47 100644 --- a/en/application-dev/reference/apis-basic-services-kit/_print___print_doc_callback.md +++ b/en/application-dev/reference/apis-basic-services-kit/_print___print_doc_callback.md @@ -9,6 +9,7 @@ Defines the print job callback struct. **Related module**: [OH_Print](_o_h___print.md) +**Header file**: [ohprint.h](ohprint_8h.md) ## Summary @@ -30,6 +31,7 @@ Defines the print job callback struct. Print_OnJobStateChanged Print_PrintDocCallback::jobStateChangedCb ``` **Description** + Defines a callback used to return the print job state. @@ -39,4 +41,5 @@ Defines a callback used to return the print job state. Print_OnStartLayoutWrite Print_PrintDocCallback::startLayoutWriteCb ``` **Description** + Defines a callback to be invoked when the file write-back starts. diff --git a/en/application-dev/reference/apis-basic-services-kit/_print___range.md b/en/application-dev/reference/apis-basic-services-kit/_print___range.md index 8be920fa34e..5d6ea3f685e 100644 --- a/en/application-dev/reference/apis-basic-services-kit/_print___range.md +++ b/en/application-dev/reference/apis-basic-services-kit/_print___range.md @@ -9,6 +9,7 @@ Defines the page range. **Related module**: [OH_Print](_o_h___print.md) +**Header file**: [ohprint.h](ohprint_8h.md) ## Summary @@ -32,6 +33,7 @@ Defines the page range. uint32_t Print_Range::endPage ``` **Description** + Defines the end page to print. @@ -41,6 +43,7 @@ Defines the end page to print. uint32_t* Print_Range::pagesArray ``` **Description** + Defines the pointer to the pages array. diff --git a/en/application-dev/reference/apis-basic-services-kit/_time_service.md b/en/application-dev/reference/apis-basic-services-kit/_time_service.md index c6b406a33cf..16476d0ec6b 100644 --- a/en/application-dev/reference/apis-basic-services-kit/_time_service.md +++ b/en/application-dev/reference/apis-basic-services-kit/_time_service.md @@ -11,32 +11,32 @@ Enables the application to obtain the time and time zone information. ## Summary -### File +### Files -| Name| Description| +| Name| Description| | -------- | -------- | -| [time_service.h](time__service_8h.md) | Declares the API for obtaining the time and time zone information. | +| [time_service.h](time__service_8h.md) | Declares the API for obtaining the time and time zone information.| ### Types -| Name| Description| +| Name| Description| | -------- | -------- | -| typedef enum [TimeService_ErrCode](#timeservice_errcode)[TimeService_ErrCode](#timeservice_errcode) | Enumerates the error codes.| +| typedef enum [TimeService_ErrCode](#timeservice_errcode) [TimeService_ErrCode](#timeservice_errcode) | Defines an enum for error codes.| ### Enums -| Name| Description| +| Name| Description| | -------- | -------- | -| [TimeService_ErrCode](#timeservice_errcode) {
TIMESERVICE_ERR_OK = 0,
TIMESERVICE_ERR_INTERNAL_ERROR = 13000001,
TIMESERVICE_ERR_INVALID_PARAMETER = 13000002
} | Enumerates the error codes.| +| [TimeService_ErrCode](#timeservice_errcode) {
TIMESERVICE_ERR_OK = 0,
TIMESERVICE_ERR_INTERNAL_ERROR = 13000001,
TIMESERVICE_ERR_INVALID_PARAMETER = 13000002
} | Enumerates the error codes.| ### Functions -| Name| Description| +| Name| Description| | -------- | -------- | -| [TimeService_ErrCode](#timeservice_errcode)[OH_TimeService_GetTimeZone](#oh_timeservice_gettimezone) (char \*timeZone, uint32_t len) | Returns the current system time zone. | +| [TimeService_ErrCode](#timeservice_errcode) [OH_TimeService_GetTimeZone](#oh_timeservice_gettimezone) (char \*timeZone, uint32_t len) | Obtains the current system time zone.| ## Type Description @@ -70,11 +70,11 @@ Enumerates the error codes. **Since**: 12 -| Value| Description| +| Value| Description| | -------- | -------- | -| TIMESERVICE_ERR_OK | Obtains system parameters.| -| TIMESERVICE_ERR_INTERNAL_ERROR | Fails to obtain system parameters.| -| TIMESERVICE_ERR_INVALID_PARAMETER | Invalid parameter.| +| TIMESERVICE_ERR_OK | Obtains system parameters.| +| TIMESERVICE_ERR_INTERNAL_ERROR | Fails to obtain system parameters.| +| TIMESERVICE_ERR_INVALID_PARAMETER | Invalid parameter.| ## Function Description @@ -83,12 +83,12 @@ Enumerates the error codes. ### OH_TimeService_GetTimeZone() ``` -TimeService_ErrCode OH_TimeService_GetTimeZone (char * timeZone, uint32_t len ) +TimeService_ErrCode OH_TimeService_GetTimeZone (char * timeZone, uint32_t len) ``` **Description** -Returns the current system time zone. +Obtains the current system time zone. **System capability**: SystemCapability.MiscServices.Time @@ -96,10 +96,10 @@ Returns the current system time zone. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| timeZone | A character array of time zone ID. If the time zone is obtained, the time zone ID string of the current system is written. Otherwise, an empty string is written. The string ends with **\0**. | -| len | Length of a character array of time zone ID without maximum limit. You are advised to apply for sufficient memory for at less 31 bytes. | +| timeZone | A character array of time zone ID. If the time zone is obtained, the time zone ID string of the current system is written. Otherwise, an empty string is written. The string ends with **\0**.| +| len | Length of a character array of time zone ID without maximum limit. You are advised to apply for sufficient memory for at less 31 bytes.| **Returns** @@ -107,4 +107,4 @@ Returns the current system time zone. **TIMESERVICE_ERR_INTERNAL_ERROR**: The system parameters fail to be obtained. -**TIMESERVICE_ERR_INVALID_PARAMETER**: The time zone is null or the length of the time zone name (excluding the end character **\0**) is greater than or equal to **len**. \ No newline at end of file +**TIMESERVICE_ERR_INVALID_PARAMETER**: The time zone is null or the length of the time zone name (excluding the end character **\0**) is greater than or equal to **len**. diff --git a/en/application-dev/reference/apis-basic-services-kit/c-apis-scan.md b/en/application-dev/reference/apis-basic-services-kit/c-apis-scan.md index c9f6c4737b4..45c3dc17a82 100644 --- a/en/application-dev/reference/apis-basic-services-kit/c-apis-scan.md +++ b/en/application-dev/reference/apis-basic-services-kit/c-apis-scan.md @@ -1,4 +1,4 @@ -# OH_Scan +# ohscan.h ## Overview @@ -105,6 +105,8 @@ Defines a callback to be invoked when a scanner is discovered. | devices | Scanner.| | deviceCount | Number of scanners. | + + ## Enum Description @@ -118,19 +120,19 @@ Enumerates the error codes. | Value| Description| | -------- | -------- | -| SCAN_ERROR_NONE | Operation succeeded.| +| SCAN_ERROR_NONE | Operation successful.| | SCAN_ERROR_NO_PERMISSION | Permission denied.| | SCAN_ERROR_INVALID_PARAMETER | Invalid parameter.| | SCAN_ERROR_GENERIC_FAILURE | Internal error.| | SCAN_ERROR_RPC_FAILURE | PRC communication error.| | SCAN_ERROR_SERVER_FAILURE | Server error.| -| SCAN_ERROR_UNSUPPORTED | Operation is not supported.| +| SCAN_ERROR_UNSUPPORTED | Operation not supported.| | SCAN_ERROR_CANCELED | Operation canceled.| -| SCAN_ERROR_DEVICE_BUSY | Device is busy.| +| SCAN_ERROR_DEVICE_BUSY | Device busy.| | SCAN_ERROR_INVALID | Invalid operation.| -| SCAN_ERROR_JAMMED | Paper jammed at the paper feeder.| +| SCAN_ERROR_JAMMED | Paper jam in feeder.| | SCAN_ERROR_NO_DOCS | Out of paper.| -| SCAN_ERROR_COVER_OPEN | The cover of the scanner is opened.| +| SCAN_ERROR_COVER_OPEN | Scanner cover opened.| | SCAN_ERROR_IO_ERROR | Scanner I/O operation error.| | SCAN_ERROR_NO_MEMORY | Insufficient memory.| @@ -154,13 +156,13 @@ Starts the scanning service, initializes the client, and establishes a connectio **Returns** -**Scan_ERROR_NONE**: Operation is succeeded. +**Scan_ERROR_NONE**: Operation successful. -**SCAN_ERROR_NO_PERMISSION**: Permission is denied. +**SCAN_ERROR_NO_PERMISSION**: Permission denied. -**SCAN_ERROR_RPC_FAILURE**: An RPC communication error occurs. +**SCAN_ERROR_RPC_FAILURE**: RPC communication error. -**SCAN_ERROR_SERVER_FAILURE**: A server exception occurs. +**SCAN_ERROR_SERVER_FAILURE**: Server error. ### OH_Scan_StartScannerDiscovery() @@ -184,13 +186,13 @@ Searches for scanners and registers a callback function to process the found sca **Returns** -**Scan_ERROR_NONE**: Operation is succeeded. +**Scan_ERROR_NONE**: Operation successful. -**SCAN_ERROR_NO_PERMISSION**: Permission is denied. +**SCAN_ERROR_NO_PERMISSION**: Permission denied. -**SCAN_ERROR_RPC_FAILURE**: An RPC communication error occurs. +**SCAN_ERROR_RPC_FAILURE**: RPC communication error. -**SCAN_ERROR_SERVER_FAILURE**: A server exception occurs. +**SCAN_ERROR_SERVER_FAILURE**: Server error. ### OH_Scan_OpenScanner() @@ -214,21 +216,21 @@ Connects to a scanner. **Returns** -**Scan_ERROR_NONE**: Operation is succeeded. +**Scan_ERROR_NONE**: Operation successful. -**SCAN_ERROR_NO_PERMISSION**: Permission is denied. +**SCAN_ERROR_NO_PERMISSION**: Permission denied. -**SCAN_ERROR_RPC_FAILURE**: An RPC communication error occurs. +**SCAN_ERROR_RPC_FAILURE**: RPC communication error. -**SCAN_ERROR_SERVER_FAILURE**: A server exception occurs. +**SCAN_ERROR_SERVER_FAILURE**: Server error. -**SCAN_ERROR_DEVICE_BUSY**: The scanner is busy. +**SCAN_ERROR_DEVICE_BUSY**: Scanner busy. -**SCAN_ERROR_INVALID_PARAMETER**: The parameter is invalid. +**SCAN_ERROR_INVALID_PARAMETER**: Invalid parameter. -**SCAN_ERROR_IO_ERROR**: An I/O operation error occurs on the scanner. +**SCAN_ERROR_IO_ERROR**: Scanner I/O operation error. -**SCAN_ERROR_NO_MEMORY**: The scanner memory is insufficient. +**SCAN_ERROR_NO_MEMORY**: Insufficient scanner memory. ### OH_Scan_CloseScanner() @@ -252,15 +254,15 @@ Disconnects from a scanner. **Returns** -**Scan_ERROR_NONE**: Operation is succeeded. +**Scan_ERROR_NONE**: Operation successful. -**SCAN_ERROR_NO_PERMISSION**: Permission is denied. +**SCAN_ERROR_NO_PERMISSION**: Permission denied. -**SCAN_ERROR_RPC_FAILURE**: An RPC communication error occurs. +**SCAN_ERROR_RPC_FAILURE**: RPC communication error. -**SCAN_ERROR_SERVER_FAILURE**: A server exception occurs. +**SCAN_ERROR_SERVER_FAILURE**: Server error. -**SCAN_ERROR_INVALID_PARAMETER**: The parameter is invalid. +**SCAN_ERROR_INVALID_PARAMETER**: Invalid parameter. ### OH_Scan_GetScannerParameter() @@ -270,7 +272,7 @@ Scan_ScannerOptions* OH_Scan_GetScannerParameter(const char* scannerId, int32_t* **Description** -Obtains the scanner setting options. The memory is automatically released when returned structure points to {@link OH_Scan_Exit}. Only one copy of each scanner model is stored in the memory. +Obtains the scanner setting options. The memory is automatically released when returned structure points to [OH_Scan_Exit](#oh_scan_exit). Only one copy of each scanner model is stored in the memory. **System capability**: ohos.permission.PRINT @@ -285,13 +287,13 @@ Obtains the scanner setting options. The memory is automatically released when r **Returns** -**Scan_ERROR_NONE**: Operation is succeeded. +**Scan_ERROR_NONE**: Operation successful. -**SCAN_ERROR_NO_PERMISSION**: Permission is denied. +**SCAN_ERROR_NO_PERMISSION**: Permission denied. -**SCAN_ERROR_RPC_FAILURE**: An RPC communication error occurs. +**SCAN_ERROR_RPC_FAILURE**: RPC communication error. -**SCAN_ERROR_SERVER_FAILURE**: A server exception occurs. +**SCAN_ERROR_SERVER_FAILURE**: Server error. ### OH_Scan_SetScannerParameter() @@ -301,7 +303,7 @@ int32_t OH_Scan_SetScannerParameter(const char* scannerId, const int32_t option, **Description** -Sets the option parameters of the scanner. The option values are obtained through the {@link OH_Scan_GetScannerParameter} API. +Sets the option parameters of the scanner. The option values are obtained through the [OH_Scan_GetScannerParameter](#oh_scan_getscannerparameter) API. **System capability**: ohos.permission.PRINT @@ -317,15 +319,15 @@ Sets the option parameters of the scanner. The option values are obtained throug **Returns** -**Scan_ERROR_NONE**: Operation is succeeded. +**Scan_ERROR_NONE**: Operation successful. -**SCAN_ERROR_NO_PERMISSION**: Permission is denied. +**SCAN_ERROR_NO_PERMISSION**: Permission denied. -**SCAN_ERROR_RPC_FAILURE**: An RPC communication error occurs. +**SCAN_ERROR_RPC_FAILURE**: RPC communication error. -**SCAN_ERROR_SERVER_FAILURE**: A server exception occurs. +**SCAN_ERROR_SERVER_FAILURE**: Server error. -**SCAN_ERROR_INVALID_PARAMETER**: The parameter is invalid. +**SCAN_ERROR_INVALID_PARAMETER**: Invalid parameter. ### OH_Scan_StartScan() @@ -350,26 +352,26 @@ Starts a scanner. **Returns** -**Scan_ERROR_NONE**: Operation is succeeded. -**SCAN_ERROR_NO_PERMISSION**: Permission is denied. +**Scan_ERROR_NONE**: Operation successful. +**SCAN_ERROR_NO_PERMISSION**: Permission denied. -**SCAN_ERROR_RPC_FAILURE**: An RPC communication error occurs. +**SCAN_ERROR_RPC_FAILURE**: RPC communication error. -**SCAN_ERROR_SERVER_FAILURE**: A server exception occurs. +**SCAN_ERROR_SERVER_FAILURE**: Server error. -**SCAN_ERROR_INVALID_PARAMETER**: The parameter is invalid. +**SCAN_ERROR_INVALID_PARAMETER**: Invalid parameter. -**SCAN_ERROR_JAMMED**: Paper jammed at the paper feeder. +**SCAN_ERROR_JAMMED**: Paper jam in feeder. -**SCAN_ERROR_NO_DOCS**: The scanner is out of paper. +**SCAN_ERROR_NO_DOCS**: Scanner out of paper. -**SCAN_ERROR_COVER_OPEN**: The cover of the scanner is opened. +**SCAN_ERROR_COVER_OPEN**: Scanner cover opened. -**SCAN_ERROR_IO_ERROR**: An I/O operation exception occurs on the scanner. +**SCAN_ERROR_IO_ERROR**: Scanner I/O operation error. -**SCAN_ERROR_NO_MEMORY**: The scanner memory is insufficient. +**SCAN_ERROR_NO_MEMORY**: Insufficient scanner memory. -**SCAN_ERROR_DEVICE_BUSY**: The scanner is busy. +**SCAN_ERROR_DEVICE_BUSY**: Scanner busy. ### OH_Scan_CancelScan() @@ -393,15 +395,15 @@ Cancels scanning. **Returns** -**Scan_ERROR_NONE**: Operation is succeeded. +**Scan_ERROR_NONE**: Operation successful. -**SCAN_ERROR_NO_PERMISSION**: Permission is denied. +**SCAN_ERROR_NO_PERMISSION**: Permission denied. -**SCAN_ERROR_RPC_FAILURE**: An RPC communication error occurs. +**SCAN_ERROR_RPC_FAILURE**: RPC communication error. -**SCAN_ERROR_SERVER_FAILURE**: A server exception occurs. +**SCAN_ERROR_SERVER_FAILURE**: Server error. -**SCAN_ERROR_INVALID_PARAMETER**: The parameter is invalid. +**SCAN_ERROR_INVALID_PARAMETER**: Invalid parameter. ### OH_Scan_GetPictureScanProgress() @@ -426,27 +428,27 @@ Queries the image scanning progress. **Returns** -**Scan_ERROR_NONE**: Operation is succeeded. +**Scan_ERROR_NONE**: Operation successful. -**SCAN_ERROR_NO_PERMISSION**: Permission is denied. +**SCAN_ERROR_NO_PERMISSION**: Permission denied. -**SCAN_ERROR_RPC_FAILURE**: An RPC communication error occurs. +**SCAN_ERROR_RPC_FAILURE**: RPC communication error. -**SCAN_ERROR_SERVER_FAILURE**: A server exception occurs. +**SCAN_ERROR_SERVER_FAILURE**: Server error. -**SCAN_ERROR_INVALID_PARAMETER**: The parameter is invalid. +**SCAN_ERROR_INVALID_PARAMETER**: Invalid parameter. -**SCAN_ERROR_JAMMED**: Paper jammed at the paper feeder. +**SCAN_ERROR_JAMMED**: Paper jam in feeder. -**SCAN_ERROR_NO_DOCS**: The scanner is out of paper. +**SCAN_ERROR_NO_DOCS**: Scanner out of paper. -**SCAN_ERROR_COVER_OPEN**: The cover of the scanner is opened. +**SCAN_ERROR_COVER_OPEN**: Scanner cover opened. -**SCAN_ERROR_IO_ERROR**: An I/O operation exception occurs on the scanner. +**SCAN_ERROR_IO_ERROR**: Scanner I/O operation error. -**SCAN_ERROR_NO_MEMORY**: The scanner memory is insufficient. +**SCAN_ERROR_NO_MEMORY**: Insufficient scanner memory. -**SCAN_ERROR_DEVICE_BUSY**: The scanner is busy. +**SCAN_ERROR_DEVICE_BUSY**: Scanner busy. ### OH_Scan_Exit() @@ -464,12 +466,12 @@ Exits the scanning service, clear the client memory, and cancel the registered s **Returns** -**Scan_ERROR_NONE**: Operation is succeeded. +**Scan_ERROR_NONE**: Operation successful. -**SCAN_ERROR_NO_PERMISSION**: Permission is denied. +**SCAN_ERROR_NO_PERMISSION**: Permission denied. -**SCAN_ERROR_RPC_FAILURE**: An RPC communication error occurs. +**SCAN_ERROR_RPC_FAILURE**: RPC communication error. -**SCAN_ERROR_SERVER_FAILURE**: A server exception occurs. +**SCAN_ERROR_SERVER_FAILURE**: Server error. -**SCAN_ERROR_INVALID_PARAMETER**: The parameter is invalid. +**SCAN_ERROR_INVALID_PARAMETER**: Invalid parameter. diff --git a/en/application-dev/reference/apis-basic-services-kit/capi-oh-pasteboard-err-code-h.md b/en/application-dev/reference/apis-basic-services-kit/capi-oh-pasteboard-err-code-h.md new file mode 100644 index 00000000000..df66181a501 --- /dev/null +++ b/en/application-dev/reference/apis-basic-services-kit/capi-oh-pasteboard-err-code-h.md @@ -0,0 +1,50 @@ +# oh_pasteboard_err_code.h + +## Overview + +Declares the error code information of the pasteboard. + +**File to include**: + +**Library**: libpasteboard.so + +**System capability**: SystemCapability.MiscServices.Pasteboard + +**Since**: 13 + +**Related module**: [Pasteboard](capi-pasteboard.md) + +## Summary + +### Enums + +| Name| typedef Keyword| Description| +| -- | -- | -- | +| [PASTEBOARD_ErrCode](#pasteboard_errcode) | PASTEBOARD_ErrCode | Enumerates the error codes.| + +## Enum Description + +### PASTEBOARD_ErrCode + +``` +enum PASTEBOARD_ErrCode +``` + +**Description** + +Enumerates the error codes. + +**Since**: 13 + +| Enum Item| Description| +| -- | -- | +| ERR_OK = 0 | Operation successful.| +| ERR_PERMISSION_ERROR = 201 | Permission verification failed.| +| ERR_INVALID_PARAMETER = 401 | Invalid parameter.| +| ERR_DEVICE_NOT_SUPPORTED = 801 | Device capability not supported.| +| ERR_INNER_ERROR = 12900000 | Internal error.| +| ERR_BUSY = 12900003 | System busy.| +| ERR_PASTEBOARD_COPY_FILE_ERROR = 12900007 | Failed to copy files.| +| ERR_PASTEBOARD_PROGRESS_START_ERROR = 12900008 | Failed to display the progress.| +| ERR_PASTEBOARD_PROGRESS_ABNORMAL = 12900009 | Abnormal progress.| +| ERR_PASTEBOARD_GET_DATA_FAILED = 12900010 | Failed to obtain the pasteboard data.| diff --git a/en/application-dev/reference/apis-basic-services-kit/capi-oh-pasteboard-h.md b/en/application-dev/reference/apis-basic-services-kit/capi-oh-pasteboard-h.md new file mode 100644 index 00000000000..4d04d745923 --- /dev/null +++ b/en/application-dev/reference/apis-basic-services-kit/capi-oh-pasteboard-h.md @@ -0,0 +1,763 @@ +# oh_pasteboard.h + +## Overview + +Provides data structure, enum types, and APIs for accessing the system pasteboard.
+ +**File to include**: + +**Library**: libpasteboard.so + +**System capability**: SystemCapability.MiscServices.Pasteboard + +**Since**: 13 + +**Related module**: [Pasteboard](capi-pasteboard.md) + +## Summary + +### Structs + +| Name| typedef Keyword| Description| +| -- | -- | -- | +| [Pasteboard_ProgressInfo](capi-pasteboard-progressinfo.md) | Pasteboard_ProgressInfo | Defines a struct for the progress information.| +| [Pasteboard_GetDataParams](capi-pasteboard-getdataparams.md) | Pasteboard_GetDataParams | Defines a struct for the parameters required for obtaining the pasteboard data and paste progress.| +| [OH_PasteboardObserver](capi-pasteboard-oh-pasteboardobserver.md) | OH_PasteboardObserver | Defines a struct for the pasteboard observer.| +| [OH_Pasteboard](capi-pasteboard-oh-pasteboard.md) | OH_Pasteboard | Defines a struct for the pasteboard object to operate the system pasteboard.| + +### Enums + +| Name| typedef Keyword| Description| +| -- | -- | -- | +| [Pasteboard_NotifyType](#pasteboard_notifytype) | Pasteboard_NotifyType | Enumerates the data change types of the pasteboard.| +| [Pasteboard_FileConflictOptions](#pasteboard_fileconflictoptions) | Pasteboard_FileConflictOptions | Enumerates the options used to resolve file copy conflicts.| +| [Pasteboard_ProgressIndicator](#pasteboard_progressindicator) | Pasteboard_ProgressIndicator | Enumerates the progress indicator options. You can use the default progress indicator as required.| + +### Functions + +| Name| typedef Keyword| Description| +| -- | -- | -- | +| [typedef void (\*OH_Pasteboard_ProgressListener)(Pasteboard_ProgressInfo* progressInfo)](#oh_pasteboard_progresslistener) | OH_Pasteboard_ProgressListener | Defines a callback to be invoked to obtain the progress information when the default progress indicator is not used.| +| [typedef void (\*Pasteboard_Notify)(void* context, Pasteboard_NotifyType type)](#pasteboard_notify) | Pasteboard_Notify | Defines a callback to be invoked when the pasteboard content changes.| +| [typedef void (\*Pasteboard_Finalize)(void* context)](#pasteboard_finalize) | Pasteboard_Finalize | Defines a callback to be invoked to release the context when the pasteboard observer object is destroyed.| +| [OH_PasteboardObserver* OH_PasteboardObserver_Create()](#oh_pasteboardobserver_create) | - | Creates an [OH_PasteboardObserver](capi-pasteboard-oh-pasteboardobserver.md) instance and a pointer to it.| +| [int OH_PasteboardObserver_Destroy(OH_PasteboardObserver* observer)](#oh_pasteboardobserver_destroy) | - | Destroys the [OH_PasteboardObserver](capi-pasteboard-oh-pasteboardobserver.md) instance.| +| [int OH_PasteboardObserver_SetData(OH_PasteboardObserver* observer, void* context,const Pasteboard_Notify callback, const Pasteboard_Finalize finalize)](#oh_pasteboardobserver_setdata) | - | Sets a callback for the pasteboard observer.| +| [OH_Pasteboard* OH_Pasteboard_Create()](#oh_pasteboard_create) | - | Creates an [OH_Pasteboard](capi-pasteboard-oh-pasteboard.md) instance and a pointer to it.| +| [void OH_Pasteboard_Destroy(OH_Pasteboard* pasteboard)](#oh_pasteboard_destroy) | - | Destroys the [OH_Pasteboard](capi-pasteboard-oh-pasteboard.md) instance.| +| [int OH_Pasteboard_Subscribe(OH_Pasteboard* pasteboard, int type, const OH_PasteboardObserver* observer)](#oh_pasteboard_subscribe) | - | Subscribes to the pasteboard observer.| +| [int OH_Pasteboard_Unsubscribe(OH_Pasteboard* pasteboard, int type, const OH_PasteboardObserver* observer)](#oh_pasteboard_unsubscribe) | - | Unsubscribes from the pasteboard observer.| +| [bool OH_Pasteboard_IsRemoteData(OH_Pasteboard* pasteboard)](#oh_pasteboard_isremotedata) | - | Checks whether the pasteboard data comes from remote devices.| +| [int OH_Pasteboard_GetDataSource(OH_Pasteboard* pasteboard, char* source, unsigned int len)](#oh_pasteboard_getdatasource) | - | Obtains the pasteboard data source.| +| [bool OH_Pasteboard_HasType(OH_Pasteboard* pasteboard, const char* type)](#oh_pasteboard_hastype) | - | Checks whether the pasteboard contains data of the specified type.| +| [bool OH_Pasteboard_HasData(OH_Pasteboard* pasteboard)](#oh_pasteboard_hasdata) | - | Checks whether the pasteboard contains data.| +| [OH_UdmfData* OH_Pasteboard_GetData(OH_Pasteboard* pasteboard, int* status)](#oh_pasteboard_getdata) | - | Obtains data from the pasteboard.| +| [int OH_Pasteboard_SetData(OH_Pasteboard* pasteboard, OH_UdmfData* data)](#oh_pasteboard_setdata) | - | Sets the unified data object in the OH_Pasteboard instance.| +| [int OH_Pasteboard_ClearData(OH_Pasteboard* pasteboard)](#oh_pasteboard_cleardata) | - | Clears data from the pasteboard.| +| [char **OH_Pasteboard_GetMimeTypes(OH_Pasteboard *pasteboard, unsigned int *count)](#oh_pasteboard_getmimetypes) | - | Obtains the MIME types from the pasteboard.| +| [Pasteboard_GetDataParams *OH_Pasteboard_GetDataParams_Create(void)](#oh_pasteboard_getdataparams_create) | - | Creates a [Pasteboard_GetDataParams](capi-pasteboard-getdataparams.md) instance and a pointer to it.| +| [void OH_Pasteboard_GetDataParams_Destroy(Pasteboard_GetDataParams* params)](#oh_pasteboard_getdataparams_destroy) | - | Destroys the [Pasteboard_GetDataParams](capi-pasteboard-getdataparams.md) instance.| +| [void OH_Pasteboard_GetDataParams_SetProgressIndicator(Pasteboard_GetDataParams* params,Pasteboard_ProgressIndicator progressIndicator)](#oh_pasteboard_getdataparams_setprogressindicator) | - | Sets a progress indicator in [Pasteboard_GetDataParams](capi-pasteboard-getdataparams.md). You can use the default progress indicator as required.| +| [void OH_Pasteboard_GetDataParams_SetDestUri(Pasteboard_GetDataParams* params, const char* destUri, uint32_t destUriLen)](#oh_pasteboard_getdataparams_setdesturi) | - | Sets the destination URI in a [Pasteboard_GetDataParams](capi-pasteboard-getdataparams.md) instance for copying files. If file processing is not supported, this parameter is not required. If the application involves complex file processing policies or needs to distinguish file multipathing storage, you are advised not to set this parameter but let the application copies files by itself.| +| [void OH_Pasteboard_GetDataParams_SetFileConflictOptions(Pasteboard_GetDataParams* params,Pasteboard_FileConflictOptions option)](#oh_pasteboard_getdataparams_setfileconflictoptions) | - | Sets the options used to resolve file copy conflicts in a [Pasteboard_GetDataParams](capi-pasteboard-getdataparams.md) instance.| +| [void OH_Pasteboard_GetDataParams_SetProgressListener(Pasteboard_GetDataParams* params,const OH_Pasteboard_ProgressListener listener)](#oh_pasteboard_getdataparams_setprogresslistener) | - | Sets a progress listener in a [Pasteboard_GetDataParams](capi-pasteboard-getdataparams.md) instance.| +| [int OH_Pasteboard_ProgressInfo_GetProgress(Pasteboard_ProgressInfo* progressInfo)](#oh_pasteboard_progressinfo_getprogress) | - | Obtains the paste progress in a [Pasteboard_ProgressInfo](capi-pasteboard-progressinfo.md) instance.| +| [void OH_Pasteboard_ProgressCancel(Pasteboard_GetDataParams* params)](#oh_pasteboard_progresscancel) | - | Cancels the ongoing paste operation when the pasteboard data is obtained.| +| [OH_UdmfData* OH_Pasteboard_GetDataWithProgress(OH_Pasteboard* pasteboard, Pasteboard_GetDataParams* params,int* status)](#oh_pasteboard_getdatawithprogress) | - | Obtains the pasteboard data and paste progress. Folders cannot be copied.| +| [uint32_t OH_Pasteboard_GetChangeCount(OH_Pasteboard *pasteboard)](#oh_pasteboard_getchangecount) | - | Obtains the number of pasteboard content changes.| + +## Enum Description + +### Pasteboard_NotifyType + +``` +enum Pasteboard_NotifyType +``` + +**Description** + +Enumerates the data change types of the pasteboard. + +**Since**: 13 + +| Enum Item| Description| +| -- | -- | +| NOTIFY_LOCAL_DATA_CHANGE = 1 | The pasteboard data of the local device is changed.| +| NOTIFY_REMOTE_DATA_CHANGE = 2 | The pasteboard data of a non-local device on the network is changed.| + +### Pasteboard_FileConflictOptions + +``` +enum Pasteboard_FileConflictOptions +``` + +**Description** + +Enumerates the options used to resolve file copy conflicts. + +**Since**: 15 + +| Enum Item| Description| +| -- | -- | +| PASTEBOARD_OVERWRITE = 0 | Overwrites the file with the same name in the destination directory.| +| PASTEBOARD_SKIP = 1 | Skips the file if there is a file with the same name in the destination directory.| + +### Pasteboard_ProgressIndicator + +``` +enum Pasteboard_ProgressIndicator +``` + +**Description** + +Enumerates the progress indicator options. You can use the default progress indicator as required. + +**Since**: 15 + +| Enum Item| Description| +| -- | -- | +| PASTEBOARD_NONE = 0 | The default progress indicator is not used.| +| PASTEBOARD_DEFAULT = 1 | The default progress indicator is used.| + + +## Function Description + +### OH_Pasteboard_ProgressListener() + +``` +typedef void (*OH_Pasteboard_ProgressListener)(Pasteboard_ProgressInfo* progressInfo) +``` + +**Description** + +Defines a callback to be invoked to obtain the progress information when the default progress indicator is not used. + +**Since**: 15 + + +**Parameters** + +| Name| Description| +| -- | -- | +| [Pasteboard_ProgressInfo](capi-pasteboard-progressinfo.md)* progressInfo | A struct for the progress information. This information is reported only when [Pasteboard_ProgressInfo](capi-pasteboard-progressinfo.md) is set to **NONE**.| + +### Pasteboard_Notify() + +``` +typedef void (*Pasteboard_Notify)(void* context, Pasteboard_NotifyType type) +``` + +**Description** + +Defines a callback to be invoked when the pasteboard content changes. + +**Since**: 13 + + +**Parameters** + +| Name| Description| +| -- | -- | +| void* context | Context information, which is passed by the [OH_PasteboardObserver_SetData](capi-oh-pasteboard-h.md#oh_pasteboardobserver_setdata) function.| +| [Pasteboard_NotifyType](capi-oh-pasteboard-h.md#pasteboard_notifytype) type | Data change type. For details, see [Pasteboard_NotifyType](capi-oh-pasteboard-h.md#pasteboard_notifytype).| + +### Pasteboard_Finalize() + +``` +typedef void (*Pasteboard_Finalize)(void* context) +``` + +**Description** + +Defines a callback to be invoked to release the context when the pasteboard observer object is destroyed. + +**Since**: 13 + + +**Parameters** + +| Name| Description| +| -- | -- | +| void* context | Pointer to the context to release.| + +### OH_PasteboardObserver_Create() + +``` +OH_PasteboardObserver* OH_PasteboardObserver_Create() +``` + +**Description** + +Creates an [OH_PasteboardObserver](capi-pasteboard-oh-pasteboardobserver.md) instance and a pointer to it. + +**Since**: 13 + +**Returns** + +| Type| Description| +| -- | -- | +| [OH_PasteboardObserver](capi-pasteboard-oh-pasteboardobserver.md)* | Returns a pointer to the [OH_PasteboardObserver](capi-pasteboard-oh-pasteboardobserver.md) instance created if the operation is successful; returns **nullptr** otherwise.
If this pointer is no longer required, use [OH_PasteboardObserver_Destroy](capi-oh-pasteboard-h.md#oh_pasteboardobserver_destroy) to destroy it. Otherwise, memory leaks may occur. | + +### OH_PasteboardObserver_Destroy() + +``` +int OH_PasteboardObserver_Destroy(OH_PasteboardObserver* observer) +``` + +**Description** + +Destroys the [OH_PasteboardObserver](capi-pasteboard-oh-pasteboardobserver.md) instance. + +**Since**: 13 + + +**Parameters** + +| Name| Description| +| -- | -- | +| [OH_PasteboardObserver](capi-pasteboard-oh-pasteboardobserver.md)* observer | Pointer to an [OH_PasteboardObserver](capi-pasteboard-oh-pasteboardobserver.md) instance.| + +**Returns** + +| Type| Description | +| -- |-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| int | Error code. For details about the error codes, see [PASTEBOARD_ErrCode](capi-oh-pasteboard-err-code-h.md#pasteboard_errcode).
Returns [ERR_OK](capi-oh-pasteboard-err-code-h.md#pasteboard_errcode) if the operation is successful.
Returns [ERR_INVALID_PARAMETER](capi-oh-pasteboard-err-code-h.md#pasteboard_errcode) if an invalid parameter is passed in.| + +### OH_PasteboardObserver_SetData() + +``` +int OH_PasteboardObserver_SetData(OH_PasteboardObserver* observer, void* context,const Pasteboard_Notify callback, const Pasteboard_Finalize finalize) +``` + +**Description** + +Sets a callback for the pasteboard observer. + +**Since**: 13 + + +**Parameters** + +| Name | Description| +|------------------------------------------------------------------| -- | +| [OH_PasteboardObserver](capi-pasteboard-oh-pasteboardobserver.md)* observer | Pointer to an [OH_PasteboardObserver](capi-pasteboard-oh-pasteboardobserver.md) instance.| +| void* context | Pointer to the context, which is passed to [Pasteboard_Notify](capi-oh-pasteboard-h.md#pasteboard_notify) as the first parameter.| +| const [Pasteboard_Notify](capi-oh-pasteboard-h.md#pasteboard_notify) callback | Callback to be invoked when the data changes. For details, see [Pasteboard_Notify](capi-oh-pasteboard-h.md#pasteboard_notify).| +| const [Pasteboard_Finalize](capi-oh-pasteboard-h.md#pasteboard_finalize) finalize | Optional callback, which can be used to release context data when the pasteboard observer is destroyed. For details, see [Pasteboard_Finalize](capi-oh-pasteboard-h.md#pasteboard_finalize).| + +**Returns** + +| Type| Description| +| -- | -- | +| int | Error code. For details about the error codes, see [PASTEBOARD_ErrCode](capi-oh-pasteboard-err-code-h.md#pasteboard_errcode).
Returns [ERR_OK](capi-oh-pasteboard-err-code-h.md#pasteboard_errcode) if the operation is successful.
Returns [ERR_INVALID_PARAMETER](capi-oh-pasteboard-err-code-h.md#pasteboard_errcode) if an invalid parameter is passed in.| + +### OH_Pasteboard_Create() + +``` +OH_Pasteboard* OH_Pasteboard_Create() +``` + +**Description** + +Creates an [OH_Pasteboard](capi-pasteboard-oh-pasteboard.md) instance and a pointer to it. + +**Since**: 13 + +**Returns** + +| Type| Description| +| -- | -- | +| [OH_Pasteboard](capi-pasteboard-oh-pasteboard.md)* | Returns a pointer to the [OH_Pasteboard](capi-pasteboard-oh-pasteboard.md) instance created if the operation is successful; returns **nullptr** otherwise.| + +### OH_Pasteboard_Destroy() + +``` +void OH_Pasteboard_Destroy(OH_Pasteboard* pasteboard) +``` + +**Description** + +Destroys the [OH_Pasteboard](capi-pasteboard-oh-pasteboard.md) instance. + +**Since**: 13 + + +**Parameters** + +| Name| Description| +| -- | -- | +| [OH_Pasteboard](capi-pasteboard-oh-pasteboard.md)* pasteboard | Pointer to an [OH_Pasteboard](capi-pasteboard-oh-pasteboard.md) instance.| + +### OH_Pasteboard_Subscribe() + +``` +int OH_Pasteboard_Subscribe(OH_Pasteboard* pasteboard, int type, const OH_PasteboardObserver* observer) +``` + +**Description** + +Subscribes to the pasteboard observer. + +**Since**: 13 + + +**Parameters** + +| Name| Description| +| -- | -- | +| [OH_Pasteboard](capi-pasteboard-oh-pasteboard.md)* pasteboard | Pointer to an [OH_Pasteboard](capi-pasteboard-oh-pasteboard.md) instance.| +| int type | Subscribed data change type of the pasteboard. For details, see [Pasteboard_NotifyType](capi-oh-pasteboard-h.md#pasteboard_notifytype).| +| const [OH_PasteboardObserver](capi-pasteboard-oh-pasteboardobserver.md)* observer | Pointer to an [OH_PasteboardObserver](capi-pasteboard-oh-pasteboardobserver.md) instance. It specifies the callback to be invoked when the pasteboard data changes. For details, see [OH_PasteboardObserver](capi-pasteboard-oh-pasteboardobserver.md).| + +**Returns** + +| Type| Description| +| -- | -- | +| int | Error code. For details about the error codes, see [PASTEBOARD_ErrCode](capi-oh-pasteboard-err-code-h.md#pasteboard_errcode).
Returns [ERR_OK](capi-oh-pasteboard-err-code-h.md#pasteboard_errcode) if the operation is successful.
Returns [ERR_INVALID_PARAMETER](capi-oh-pasteboard-err-code-h.md#pasteboard_errcode) if an invalid parameter is passed in.| + +### OH_Pasteboard_Unsubscribe() + +``` +int OH_Pasteboard_Unsubscribe(OH_Pasteboard* pasteboard, int type, const OH_PasteboardObserver* observer) +``` + +**Description** + +Unsubscribes from the pasteboard observer. + +**Since**: 13 + + +**Parameters** + +| Name| Description| +| -- | -- | +| [OH_Pasteboard](capi-pasteboard-oh-pasteboard.md)* pasteboard | Pointer to an [OH_Pasteboard](capi-pasteboard-oh-pasteboard.md) instance.| +| int type | Subscribed data change type of the pasteboard. For details, see [Pasteboard_NotifyType](capi-oh-pasteboard-h.md#pasteboard_notifytype).| +| const [OH_PasteboardObserver](capi-pasteboard-oh-pasteboardobserver.md)* observer | Pointer to an [OH_PasteboardObserver](capi-pasteboard-oh-pasteboardobserver.md) instance. It specifies the callback to be invoked when the pasteboard data changes. For details, see [OH_PasteboardObserver](capi-pasteboard-oh-pasteboardobserver.md).| + +**Returns** + +| Type| Description| +| -- | -- | +| int | Error code. For details about the error codes, see [PASTEBOARD_ErrCode](capi-oh-pasteboard-err-code-h.md#pasteboard_errcode).
Returns [ERR_OK](capi-oh-pasteboard-err-code-h.md#pasteboard_errcode) if the operation is successful.
Returns [ERR_INVALID_PARAMETER](capi-oh-pasteboard-err-code-h.md#pasteboard_errcode) if an invalid parameter is passed in.| + +### OH_Pasteboard_IsRemoteData() + +``` +bool OH_Pasteboard_IsRemoteData(OH_Pasteboard* pasteboard) +``` + +**Description** + +Checks whether the pasteboard data comes from remote devices. + +**Since**: 13 + + +**Parameters** + +| Name| Description| +| -- | -- | +| [OH_Pasteboard](capi-pasteboard-oh-pasteboard.md)* pasteboard | Pointer to an [OH_Pasteboard](capi-pasteboard-oh-pasteboard.md) instance.| + +**Returns** + +| Type| Description| +| -- | -- | +| bool | Returns a Boolean value indicating whether the data is from a remote device. The value **true** means the data is from a remote device; **false** means the data is from the local device.| + +### OH_Pasteboard_GetDataSource() + +``` +int OH_Pasteboard_GetDataSource(OH_Pasteboard* pasteboard, char* source, unsigned int len) +``` + +**Description** + +Obtains the pasteboard data source. + +**Since**: 13 + + +**Parameters** + +| Name| Description| +| -- | -- | +| [OH_Pasteboard](capi-pasteboard-oh-pasteboard.md)* pasteboard | Pointer to an [OH_Pasteboard](capi-pasteboard-oh-pasteboard.md) instance.| +| char* source | Pointer to the pasteboard data source instance. You need to allocate the memory for the pointer before calling this API.| +| unsigned int len | Memory length corresponding to the source. If the memory length is insufficient, the API call will fail. The recommended length is 128.| + +**Returns** + +| Type| Description| +| -- | -- | +| int | Error code. For details about the error codes, see [PASTEBOARD_ErrCode](capi-oh-pasteboard-err-code-h.md#pasteboard_errcode).
Returns [ERR_OK](capi-oh-pasteboard-err-code-h.md#pasteboard_errcode) if the operation is successful.
Returns [ERR_INVALID_PARAMETER](capi-oh-pasteboard-err-code-h.md#pasteboard_errcode) if an invalid parameter is passed in.| + +### OH_Pasteboard_HasType() + +``` +bool OH_Pasteboard_HasType(OH_Pasteboard* pasteboard, const char* type) +``` + +**Description** + +Checks whether the pasteboard contains data of the specified type. + +**Since**: 13 + + +**Parameters** + +| Name| Description| +| -- | -- | +| [OH_Pasteboard](capi-pasteboard-oh-pasteboard.md)* pasteboard | Pointer to an [OH_Pasteboard](capi-pasteboard-oh-pasteboard.md) instance.| +| const char* type | Data type to be checked, which is classified into basic types and custom types. The basic data types include text/plain, text/html, text/uri, text/want, and pixelMap.| + +**Returns** + +| Type| Description| +| -- | -- | +| bool | Returns a Boolean value indicating whether the pasteboard contains data of the specified type. The value **true** means the pasteboard contains data of the specified type; the value **false** means the opposite.| + +### OH_Pasteboard_HasData() + +``` +bool OH_Pasteboard_HasData(OH_Pasteboard* pasteboard) +``` + +**Description** + +Checks whether the pasteboard contains data. + +**Since**: 13 + + +**Parameters** + +| Name| Description| +| -- | -- | +| [OH_Pasteboard](capi-pasteboard-oh-pasteboard.md)* pasteboard | Pointer to an [OH_Pasteboard](capi-pasteboard-oh-pasteboard.md) instance.| + +**Returns** + +| Type| Description| +| -- | -- | +| bool | Returns a Boolean value indicating whether the pasteboard contains data. The value **true** means the pasteboard contains data; the value **false** means the opposite.| + +### OH_Pasteboard_GetData() + +``` +OH_UdmfData* OH_Pasteboard_GetData(OH_Pasteboard* pasteboard, int* status) +``` + +**Description** + +Obtains data from the pasteboard. + +**Since**: 13 + + +**Parameters** + +| Name| Description| +| -- | -- | +| [OH_Pasteboard](capi-pasteboard-oh-pasteboard.md)* pasteboard | Pointer to an [OH_Pasteboard](capi-pasteboard-oh-pasteboard.md) instance.| +| int* status | Output parameter, indicating the error code of the operation. For details about the error codes, see [PASTEBOARD_ErrCode](capi-oh-pasteboard-err-code-h.md#pasteboard_errcode).| + +**Returns** + +| Type| Description| +| -- | -- | +| [OH_UdmfData](../apis-arkdata/capi-udmf-oh-udmfdata.md)* | Returns the pointer to an [OH_UdmfData](../apis-arkdata/capi-udmf-oh-udmfdata.md) instance obtained if the operation is successful; returns a null pointer otherwise.| + +### OH_Pasteboard_SetData() + +``` +int OH_Pasteboard_SetData(OH_Pasteboard* pasteboard, OH_UdmfData* data) +``` + +**Description** + +Sets the unified data object in the OH_Pasteboard instance. + +**Since**: 13 + + +**Parameters** + +| Name| Description| +| -- | -- | +| [OH_Pasteboard](capi-pasteboard-oh-pasteboard.md)* pasteboard | Pointer to an [OH_Pasteboard](capi-pasteboard-oh-pasteboard.md) instance.| +| [OH_UdmfData](../apis-arkdata/capi-udmf-oh-udmfdata.md)* data | Pointer to an [OH_UdmfData](../apis-arkdata/capi-udmf-oh-udmfdata.md) instance.| + +**Returns** + +| Type| Description| +| -- | -- | +| int | Error code. For details about the error codes, see [PASTEBOARD_ErrCode](capi-oh-pasteboard-err-code-h.md#pasteboard_errcode).
Returns [ERR_OK](capi-oh-pasteboard-err-code-h.md#pasteboard_errcode) if the operation is successful.
Returns [ERR_INVALID_PARAMETER](capi-oh-pasteboard-err-code-h.md#pasteboard_errcode) if an invalid parameter is passed in.| + +### OH_Pasteboard_ClearData() + +``` +int OH_Pasteboard_ClearData(OH_Pasteboard* pasteboard) +``` + +**Description** + +Clears data from the pasteboard. + +**Since**: 13 + + +**Parameters** + +| Name| Description| +| -- | -- | +| [OH_Pasteboard](capi-pasteboard-oh-pasteboard.md)* pasteboard | Pointer to an [OH_Pasteboard](capi-pasteboard-oh-pasteboard.md) instance.| + +**Returns** + +| Type| Description| +| -- | -- | +| int | Error code. For details about the error codes, see [PASTEBOARD_ErrCode](capi-oh-pasteboard-err-code-h.md#pasteboard_errcode).
Returns [ERR_OK](capi-oh-pasteboard-err-code-h.md#pasteboard_errcode) if the operation is successful.
Returns [ERR_INVALID_PARAMETER](capi-oh-pasteboard-err-code-h.md#pasteboard_errcode) if an invalid parameter is passed in.| + +### OH_Pasteboard_GetMimeTypes() + +``` +char **OH_Pasteboard_GetMimeTypes(OH_Pasteboard *pasteboard, unsigned int *count) +``` + +**Description** + +Obtains the MIME types from the pasteboard. + +**Since**: 14 + + +**Parameters** + +| Name| Description| +| -- | -- | +| [OH_Pasteboard](capi-pasteboard-oh-pasteboard.md) *pasteboard | Pointer to an [OH_Pasteboard](capi-pasteboard-oh-pasteboard.md) instance.| +| unsigned int *count | Pointer to the number of MIME types obtained.| + +**Returns** + +| Type| Description| +| -- | -- | +| char | Returns the MIME types obtained if the operation is successful; returns **nullptr** otherwise.| + +### OH_Pasteboard_GetDataParams_Create() + +``` +Pasteboard_GetDataParams *OH_Pasteboard_GetDataParams_Create(void) +``` + +**Description** + +Creates a [Pasteboard_GetDataParams](capi-pasteboard-getdataparams.md) instance and a pointer to it. + +**Since**: 15 + +**Returns** + +| Type| Description| +| -- | -- | +| [Pasteboard_GetDataParams](capi-pasteboard-getdataparams.md) | Returns a pointer to the [Pasteboard_GetDataParams](capi-pasteboard-getdataparams.md) instance created if the operation is successful; returns **nullptr** otherwise. If this pointer is no longer required, use [OH_Pasteboard_GetDataParams_Destroy](capi-oh-pasteboard-h.md#oh_pasteboard_getdataparams_destroy) to destroy it. Otherwise, memory leaks may occur. | + +### OH_Pasteboard_GetDataParams_Destroy() + +``` +void OH_Pasteboard_GetDataParams_Destroy(Pasteboard_GetDataParams* params) +``` + +**Description** + +Destroys the [Pasteboard_GetDataParams](capi-pasteboard-getdataparams.md) instance. + +**Since**: 15 + + +**Parameters** + +| Name| Description| +| -- | -- | +| [Pasteboard_GetDataParams](capi-pasteboard-getdataparams.md)* params | Pointer to an **OH_Pasteboard_GetDataParams** instance.| + +### OH_Pasteboard_GetDataParams_SetProgressIndicator() + +``` +void OH_Pasteboard_GetDataParams_SetProgressIndicator(Pasteboard_GetDataParams* params,Pasteboard_ProgressIndicator progressIndicator) +``` + +**Description** + +Sets a progress indicator in [Pasteboard_GetDataParams](capi-pasteboard-getdataparams.md). You can use the default progress indicator as required. + +**Since**: 15 + + +**Parameters** + +| Name| Description| +| -- | -- | +| [Pasteboard_GetDataParams](capi-pasteboard-getdataparams.md)* params | Pointer to an **OH_Pasteboard_GetDataParams** instance.| +| [Pasteboard_ProgressIndicator](#pasteboard_progressindicator) progressIndicator | Progress indicator to set.| + +### OH_Pasteboard_GetDataParams_SetDestUri() + +``` +void OH_Pasteboard_GetDataParams_SetDestUri(Pasteboard_GetDataParams* params, const char* destUri, uint32_t destUriLen) +``` + +**Description** + +Sets the destination URI for copying files. If file processing is not supported, this parameter is not required. If the application involves complex file processing policies or needs to distinguish file multipathing storage, you are advised not to set this parameter but let the application copies files by itself. + +**Since**: 15 + + +**Parameters** + +| Name| Description| +| -- | -- | +| [Pasteboard_GetDataParams](capi-pasteboard-getdataparams.md)* params | Pointer to an **OH_Pasteboard_GetDataParams** instance.| +| const char* destUri | Destination URI of the copied file.| +| uint32_t destUriLen | Length of the destination URI of the copied file.| + +### OH_Pasteboard_GetDataParams_SetFileConflictOptions() + +``` +void OH_Pasteboard_GetDataParams_SetFileConflictOptions(Pasteboard_GetDataParams* params,Pasteboard_FileConflictOptions option) +``` + +**Description** + +Sets the options used to resolve file copy conflicts in a [Pasteboard_GetDataParams](capi-pasteboard-getdataparams.md) instance. + +**Since**: 15 + + +**Parameters** + +| Name| Description| +| -- | -- | +| [Pasteboard_GetDataParams](capi-pasteboard-getdataparams.md)* params | Pointer to an **OH_Pasteboard_GetDataParams** instance.| +| [Pasteboard_FileConflictOptions](#pasteboard_fileconflictoptions) option | Options used to resolve file copy conflicts. The default value is **PASTEBOARD_OVERWRITE**.| + +### OH_Pasteboard_GetDataParams_SetProgressListener() + +``` +void OH_Pasteboard_GetDataParams_SetProgressListener(Pasteboard_GetDataParams* params,const OH_Pasteboard_ProgressListener listener) +``` + +**Description** + +Sets a progress listener in a [Pasteboard_GetDataParams](capi-pasteboard-getdataparams.md) instance. + +**Since**: 15 + + +**Parameters** + +| Name | Description| +|----------------------------------------------------------------------------------| -- | +| [Pasteboard_GetDataParams](capi-pasteboard-getdataparams.md)* params | Pointer to an **OH_Pasteboard_GetDataParams** instance.| +| const [OH_Pasteboard_ProgressListener](#oh_pasteboard_progresslistener) listener | Progress listener.| + +### OH_Pasteboard_ProgressInfo_GetProgress() + +``` +int OH_Pasteboard_ProgressInfo_GetProgress(Pasteboard_ProgressInfo* progressInfo) +``` + +**Description** + +Obtains the paste progress in a [Pasteboard_ProgressInfo](capi-pasteboard-progressinfo.md) instance. + +**Since**: 15 + + +**Parameters** + +| Name| Description| +| -- | -- | +| [Pasteboard_ProgressInfo](capi-pasteboard-progressinfo.md)* progressInfo | Pointer to a [Pasteboard_ProgressInfo](capi-pasteboard-progressinfo.md) instance.| + +**Returns** + +| Type| Description| +| -- | -- | +| int | Percentage of the paste progress.| + +### OH_Pasteboard_ProgressCancel() + +``` +void OH_Pasteboard_ProgressCancel(Pasteboard_GetDataParams* params) +``` + +**Description** + +Cancels the ongoing paste operation when the pasteboard data is obtained. + +**Since**: 15 + + +**Parameters** + +| Name| Description| +| -- | -- | +| [Pasteboard_GetDataParams](capi-pasteboard-getdataparams.md)* params | Pointer to an **OH_Pasteboard_GetDataParams** instance.| + +### OH_Pasteboard_GetDataWithProgress() + +``` +OH_UdmfData* OH_Pasteboard_GetDataWithProgress(OH_Pasteboard* pasteboard, Pasteboard_GetDataParams* params,int* status) +``` + +**Description** + +Obtains the pasteboard data and paste progress. Folders cannot be copied. + +**Since**: 15 + + +**Parameters** + +| Name| Description| +| -- | -- | +| [OH_Pasteboard](capi-pasteboard-oh-pasteboard.md)* pasteboard | Pointer to an [OH_Pasteboard](capi-pasteboard-oh-pasteboard.md) instance.| +| [Pasteboard_GetDataParams](capi-pasteboard-getdataparams.md)* params | Pointer to an **OH_Pasteboard_GetDataParams** instance.| +| int* status | Output parameter, indicating the error code of the operation. For details about the error codes, see [PASTEBOARD_ErrCode](capi-oh-pasteboard-err-code-h.md#pasteboard_errcode).| + +**Returns** + +| Type| Description| +| -- | -- | +| [OH_UdmfData](../apis-arkdata/capi-udmf-oh-udmfdata.md)* | Returns the pointer to an **OH_PasteData** instance obtained if the operation is successful; returns a null pointer otherwise.| + +### OH_Pasteboard_GetChangeCount() + +``` +uint32_t OH_Pasteboard_GetChangeCount(OH_Pasteboard *pasteboard) +``` + +**Description** + +Obtains the number of pasteboard content changes. + +**Since**: 18 + + +**Parameters** + +| Name| Description| +| -- | -- | +| [OH_Pasteboard](capi-pasteboard-oh-pasteboard.md) *pasteboard | Pointer to an [OH_Pasteboard](capi-pasteboard-oh-pasteboard.md) instance.| + +**Returns** + +| Type| Description| +| -- | -- | +| uint32_t | Returns the number of pasteboard content changes if this API is called successfully; otherwise, returns **0**.
Even though the pasteboard data expires, or the data becomes empty because of the called **OH_Pasteboard_ClearData** API, the number of data changes remains.
When the system is restarted, or the pasteboard service is restarted due to an exception, the number of pasteboard data changes counts from 0. In addition, copying the same data repeatedly is considered to change the data for multiple times. Therefore, each time the data is copied, the number of data changes increases. | diff --git a/en/application-dev/reference/apis-basic-services-kit/capi-os-account-common-h.md b/en/application-dev/reference/apis-basic-services-kit/capi-os-account-common-h.md new file mode 100644 index 00000000000..269c280b5e9 --- /dev/null +++ b/en/application-dev/reference/apis-basic-services-kit/capi-os-account-common-h.md @@ -0,0 +1,43 @@ +# os_account_common.h + +## Overview + +Defines common types used in **OsAccount** APIs. + +**Library**: libos_account_ndk.so + +**Header file**: + +**System capability**: SystemCapability.Account.OsAccount + +**Since**: 12 + +**Related module**: [OsAccount](capi-osaccount.md) + +## Summary + +### Enums + +| Name| typedef Keyword| Description| +| -- | -- | -- | +| [OsAccount_ErrCode](#osaccount_errcode) | OsAccount_ErrCode | Enumerates the error codes.| + +## Enum Description + +### OsAccount_ErrCode + +``` +enum OsAccount_ErrCode +``` + +**Description** + +Enumerates the error codes. + +**Since**: 12 + +| Enum Item| Description| +| -- | -- | +| OS_ACCOUNT_ERR_OK = 0 | Success.| +| OS_ACCOUNT_ERR_INTERNAL_ERROR = 12300001 | Internal error.| +| OS_ACCOUNT_ERR_INVALID_PARAMETER = 12300002 | Invalid parameter.| diff --git a/en/application-dev/reference/apis-basic-services-kit/capi-os-account-h.md b/en/application-dev/reference/apis-basic-services-kit/capi-os-account-h.md new file mode 100644 index 00000000000..a2bb6341772 --- /dev/null +++ b/en/application-dev/reference/apis-basic-services-kit/capi-os-account-h.md @@ -0,0 +1,53 @@ +# os_account.h + +## Overview + +Defines the APIs for accessing and managing system account information. + +**Library**: libos_account_ndk.so + +**Header file**: + +**System capability**: SystemCapability.Account.OsAccount + +**Since**: 12 + +**Related module**: [OsAccount](capi-osaccount.md) + +## Summary + +### Functions + +| Name| Description| +| -- | -- | +| [OsAccount_ErrCode OH_OsAccount_GetName(char *buffer, size_t buffer_size)](#oh_osaccount_getname) | Obtains the name of the system account to which the caller process belongs.| + +## Function Description + +### OH_OsAccount_GetName() + +``` +OsAccount_ErrCode OH_OsAccount_GetName(char *buffer, size_t buffer_size) +``` + +**Description** + +Obtains the name of the system account to which the caller process belongs. + +**System capability**: SystemCapability.Account.OsAccount + +**Since**: 12 + + +**Parameters** + +| Name| Description| +| -- | -- | +| char *buffer | Pointer to the system account name, which including the name of the maximum length (**LOGIN_NAME_MAX**) and the end character (**\0**).| +| size_t buffer_size | Length of the system account name.| + +**Returns** + +| Type| Description| +| -- | -- | +| [OsAccount_ErrCode](capi-os-account-common-h.md#osaccount_errcode) | **OS_ACCOUNT_ERR_OK**: Operation successful.
**OS_ACCOUNT_ERR_INTERNAL_ERROR**: Internal error.
**OS_ACCOUNT_ERR_INVALID_PARAMETER**: Invalid parameter, indicating that the buffer is a null pointer, or the length of the system account name (excluding **\0**) is greater than or equal to the buffer size.| diff --git a/en/application-dev/reference/apis-basic-services-kit/capi-osaccount.md b/en/application-dev/reference/apis-basic-services-kit/capi-osaccount.md new file mode 100644 index 00000000000..1128e80a6c5 --- /dev/null +++ b/en/application-dev/reference/apis-basic-services-kit/capi-osaccount.md @@ -0,0 +1,14 @@ +# OsAccount + +## Overview + +The **OsAccount** module provides APIs for managing system accounts for applications. + +**Since**: 12 + +## Files + +| Name| Description| +| -- | -- | +| [os_account.h](capi-os-account-h.md) | Defines the APIs for accessing and managing system account information.| +| [os_account_common.h](capi-os-account-common-h.md) | Defines common types used in **OsAccount** APIs. | diff --git a/en/application-dev/reference/apis-basic-services-kit/capi-pasteboard-getdataparams.md b/en/application-dev/reference/apis-basic-services-kit/capi-pasteboard-getdataparams.md new file mode 100644 index 00000000000..83895471eba --- /dev/null +++ b/en/application-dev/reference/apis-basic-services-kit/capi-pasteboard-getdataparams.md @@ -0,0 +1,11 @@ +# Pasteboard_GetDataParams + +## Overview + +Defines the parameters required for obtaining the pasteboard data and paste progress. + +**Since**: 15 + +**Related module**: [Pasteboard](capi-pasteboard.md) + +**Header file**: [oh_pasteboard.h](capi-oh-pasteboard-h.md) diff --git a/en/application-dev/reference/apis-basic-services-kit/capi-pasteboard-oh-pasteboard.md b/en/application-dev/reference/apis-basic-services-kit/capi-pasteboard-oh-pasteboard.md new file mode 100644 index 00000000000..46b40a0cd04 --- /dev/null +++ b/en/application-dev/reference/apis-basic-services-kit/capi-pasteboard-oh-pasteboard.md @@ -0,0 +1,11 @@ +# OH_Pasteboard + +## Overview + +Defines the pasteboard object to operate the system pasteboard. + +**Since**: 13 + +**Related module**: [Pasteboard](capi-pasteboard.md) + +**Header file**: [oh_pasteboard.h](capi-oh-pasteboard-h.md) diff --git a/en/application-dev/reference/apis-basic-services-kit/capi-pasteboard-oh-pasteboardobserver.md b/en/application-dev/reference/apis-basic-services-kit/capi-pasteboard-oh-pasteboardobserver.md new file mode 100644 index 00000000000..9665ee18af7 --- /dev/null +++ b/en/application-dev/reference/apis-basic-services-kit/capi-pasteboard-oh-pasteboardobserver.md @@ -0,0 +1,11 @@ +# OH_PasteboardObserver + +## Overview + +Defines the pasteboard observer. + +**Since**: 13 + +**Related module**: [Pasteboard](capi-pasteboard.md) + +**Header file**: [oh_pasteboard.h](capi-oh-pasteboard-h.md) diff --git a/en/application-dev/reference/apis-basic-services-kit/capi-pasteboard-progressinfo.md b/en/application-dev/reference/apis-basic-services-kit/capi-pasteboard-progressinfo.md new file mode 100644 index 00000000000..c1e6ab31221 --- /dev/null +++ b/en/application-dev/reference/apis-basic-services-kit/capi-pasteboard-progressinfo.md @@ -0,0 +1,11 @@ +# Pasteboard_ProgressInfo + +## Overview + +Defines a struct for the progress information. + +**Since**: 15 + +**Related module**: [Pasteboard](capi-pasteboard.md) + +**Header file**: [oh_pasteboard.h](capi-oh-pasteboard-h.md) diff --git a/en/application-dev/reference/apis-basic-services-kit/capi-pasteboard.md b/en/application-dev/reference/apis-basic-services-kit/capi-pasteboard.md new file mode 100644 index 00000000000..0b0e9b94351 --- /dev/null +++ b/en/application-dev/reference/apis-basic-services-kit/capi-pasteboard.md @@ -0,0 +1,14 @@ +# Pasteboard + +## Overview + +The **Pasteboard** module supports copying and pasting multiple types of data, including plain text, HTML, URI, and pixel map. + +**Since**: 13 + +## Files + +| Name| Description| +| -- | -- | +| [oh_pasteboard.h](capi-oh-pasteboard-h.md) | Provides data structure, enum types, and APIs for accessing the system pasteboard.| +| [oh_pasteboard_err_code.h](capi-oh-pasteboard-err-code-h.md) | Declares the error code information of the pasteboard.| diff --git a/en/application-dev/reference/apis-basic-services-kit/common_event/commonEvent-definitions.md b/en/application-dev/reference/apis-basic-services-kit/common_event/commonEvent-definitions.md index fa117f85496..bda4603cbca 100644 --- a/en/application-dev/reference/apis-basic-services-kit/common_event/commonEvent-definitions.md +++ b/en/application-dev/reference/apis-basic-services-kit/common_event/commonEvent-definitions.md @@ -1,888 +1,888 @@ # System Common Events (To Be Deprecated Soon) This document provides indexes for predefined system common events. -Common event types are defined in [Support enumeration of the ohos.commonEvent module](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis-basic-services-kit/js-apis-commonEvent.md#support). +Common event types are defined in [Support enumeration of the ohos.commonEvent module](../js-apis-commonEvent.md#support). **System capability**: SystemCapability.Notification.CommonEvent * COMMON_EVENT_BOOT_COMPLETED Indicates that the boot is complete and the system is loaded. - Value: **usual.event.BOOT_COMPLETED** - - Permission required by subscribers: ohos.permission.RECEIVER_STARTUP_COMPLETED (Only system applications can apply for this permission.) + - Required permissions: ohos.permission.RECEIVER_STARTUP_COMPLETED (for system applications only) * COMMON_EVENT_LOCKED_BOOT_COMPLETED -(Reserved event, not supported currently) A message is displayed, indicating that the guidance is complete and the system is loaded, but the screen is still locked. +(Reserved, not supported yet) Indicates that the guidance is complete and the system is loaded, but the screen is still locked. - Value: **usual.event.LOCKED_BOOT_COMPLETED** - - Permission required by subscribers: ohos.permission.RECEIVER_STARTUP_COMPLETED (Only system applications can apply for this permission.) + - Required permissions: ohos.permission.RECEIVER_STARTUP_COMPLETED (for system applications only) * COMMON_EVENT_SHUTDOWN -A message is displayed, indicating that the device is being shut down and will continue until it is finally shut down. +Indicates that the device is being shut down and will continue until it is finally shut down. - Value: **usual.event.SHUTDOWN** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_BATTERY_CHANGED -A message is displayed, indicating that the battery charging status, battery level, and other information has changed. +Indicates that the battery charging status, battery level, and other information has changed. - Value: **usual.event.BATTERY_CHANGED** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_BATTERY_LOW Indicates that the battery level is low. - Value: **usual.event.BATTERY_LOW** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_BATTERY_OKAY Indicates that the battery level is normal. - Value: **usual.event.BATTERY_OKAY** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_POWER_CONNECTED Indicates that the device is connected to an external power supply. - Value: **usual.event.POWER_CONNECTED** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_POWER_DISCONNECTED Indicates that the device is disconnected from the external power supply. - Value: **usual.event.POWER_DISCONNECTED** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_SCREEN_OFF Indicates that the device screen is off and the device is in sleep mode. - Value: **usual.event.SCREEN_OFF** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_SCREEN_ON Indicates that the device screen is on and the device is in interactive state. - Value: **usual.event.SCREEN_ON** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_THERMAL_LEVEL_CHANGED8+ Indicates that the device's thermal level has changed. - Value: **usual.event.THERMAL_LEVEL_CHANGED** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_USER_PRESENT (Reserved, not supported yet) Indicates that the user unlocks the device. - Value: **usual.event.USER_PRESENT** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_TIME_TICK Indicates that the system time has changed as time ticks by. - Value: **usual.event.TIME_TICK** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_TIME_CHANGED Indicates that the system time is set. - Value: **usual.event.TIME_CHANGED** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_DATE_CHANGED -This event is reserved and is not supported currently. A message is displayed, indicating that the system date has been changed. +(Reserved, not supported yet) Indicates that the system date has been changed. - Value: **usual.event.DATE_CHANGED** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_TIMEZONE_CHANGED -A message is displayed, indicating that the system time zone is changed. +Indicates that the system time zone is changed. - Value: **usual.event.TIMEZONE_CHANGED** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_CLOSE_SYSTEM_DIALOGS (Reserved, not supported yet) Indicates that the user closes a temporary system dialog box. - Value: **usual.event.CLOSE_SYSTEM_DIALOGS** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_PACKAGE_ADDED Indicates that a new application package has been installed on the device. - Value: **usual.event.PACKAGE_ADDED** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_PACKAGE_INSTALLATION_STARTED -A message is displayed, indicating that the application package starts to be installed on the device. +Indicates that the application package starts to be installed on the device. - Value: **usual.event.PACKAGE_INSTALLATION_STARTED** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_PACKAGE_REPLACED (Reserved, not supported yet) Indicates that a later version of an installed application package has replaced the previous one on the device. - Value: **usual.event.PACKAGE_REPLACED** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_MY_PACKAGE_REPLACED -(Reserved event, not supported currently) Indicates that the new version of the application package has replaced the previous version. +(Reserved, not supported yet) Indicates that the new version of the application package has replaced the previous version. - Value: **usual.event.MY_PACKAGE_REPLACED** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_PACKAGE_REMOVED Indicates that an installed application has been uninstalled from the device with the application data retained. - Value: **usual.event.PACKAGE_REMOVED** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_BUNDLE_REMOVED (Reserved, not supported yet) Indicates that an installed bundle has been uninstalled from the device with the application data retained. - Value: **usual.event.BUNDLE_REMOVED** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_PACKAGE_FULLY_REMOVED (Reserved, not supported yet) Indicates that an installed application, including both the application data and code, has been completely uninstalled from the device. - Value: **usual.event.PACKAGE_FULLY_REMOVED** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_PACKAGE_CHANGED Indicates that an application package has been changed (for example, an ability in the package has been enabled or disabled). - Value: **usual.event.PACKAGE_CHANGED** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_PACKAGE_RESTARTED Indicates that the user closed all processes of the application and restarted the application. - Value: **usual.event.PACKAGE_RESTARTED** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_PACKAGE_DATA_CLEARED Indicates that the user cleared the application package data. - Value: **usual.event.PACKAGE_DATA_CLEARED** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_PACKAGE_CACHE_CLEARED9+ Indicates that the user cleared the application package cache. - Value: **usual.event.PACKAGE_CACHE_CLEARED** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_PACKAGES_SUSPENDED (Reserved, not supported yet) Indicates that application packages have been suspended. - Value: **usual.event.PACKAGES_SUSPENDED** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_PACKAGES_UNSUSPENDED -(Reserved event, not supported currently) A message is displayed, indicating that the application HAP package is not suspended (resumed from the suspended state). +(Reserved, not supported yet) Indicates that the application HAP package is not suspended (resumed from the suspended state). - Value: **usual.event.PACKAGES_UNSUSPENDED** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_MY_PACKAGE_SUSPENDED -A message is displayed, indicating that the application HAP package is suspended. +Indicates that the application HAP package is suspended. - Value: **usual.event.MY_PACKAGE_SUSPENDED** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_MY_PACKAGE_UNSUSPENDED -A message is displayed, indicating that the application package is not suspended. +Indicates that the application package is not suspended. - Value: **usual.event.MY_PACKAGE_UNSUSPENDED** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_UID_REMOVED (Reserved, not supported yet) Indicates that a user ID has been removed from the system. - Value: **usual.event.UID_REMOVED** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_PACKAGE_FIRST_LAUNCH (Reserved, not supported yet) Indicates that an installed application is started for the first time. - Value: **usual.event.PACKAGE_FIRST_LAUNCH** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_PACKAGE_NEEDS_VERIFICATION (Reserved, not supported yet) Indicates that an application requires system verification. - Value: **usual.event.PACKAGE_NEEDS_VERIFICATION** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_PACKAGE_VERIFIED (Reserved, not supported yet) Indicates that an application has been verified by the system. - Value: **usual.event.PACKAGE_VERIFIED** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_EXTERNAL_APPLICATIONS_AVAILABLE (Reserved, not supported yet) Indicates that applications installed on the external storage are available for the system. - Value: **usual.event.EXTERNAL_APPLICATIONS_AVAILABLE** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_EXTERNAL_APPLICATIONS_UNAVAILABLE (Reserved, not supported yet) Indicates that applications installed on the external storage are not available for the system. - Value: **usual.event.EXTERNAL_APPLICATIONS_UNAVAILABLE** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_CONFIGURATION_CHANGED (Reserved, not supported yet) Indicates that the device state (for example, orientation and locale) has changed. - Value: **usual.event.CONFIGURATION_CHANGED** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_LOCALE_CHANGED (Reserved, not supported yet) Indicates that the device locale has changed. - Value: **usual.event.LOCALE_CHANGED** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_MANAGE_PACKAGE_STORAGE (Reserved, not supported yet) Indicates that the device storage is insufficient. - Value: **usual.event.MANAGE_PACKAGE_STORAGE** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_DRIVE_MODE (Reserved, not supported yet) Indicates that the system is in driving mode. - Value: **common.event.DRIVE_MODE** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_HOME_MODE (Reserved, not supported yet) Indicates that the system is in home mode. - Value: **common.event.HOME_MODE** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_OFFICE_MODE (Reserved, not supported yet) Indicates that the system is in office mode. - Value: **common.event.OFFICE_MODE** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_USER_STARTED (Reserved, not supported yet) Indicates that the user has been started. - Value: **usual.event.USER_STARTED** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_USER_BACKGROUND -This event is reserved and is not supported currently. A message is displayed, indicating that the user has been brought to the background. +(Reserved, not supported yet) Indicates that the user has been brought to the background. - Value: **usual.event.USER_BACKGROUND** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_USER_FOREGROUND -This event is reserved and is not supported currently. A message is displayed, indicating that the user has been brought to the foreground. +(Reserved, not supported yet) Indicates that the user has been brought to the foreground. - Value: **usual.event.USER_FOREGROUND** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_USER_SWITCHED Indicates that user switching is in progress. - Value: **usual.event.USER_SWITCHED** - - The subscriber requires the ohos.permission.MANAGE_LOCAL_ACCOUNTS permission. Only system applications can apply for this permission. + - Required permissions: ohos.permission.MANAGE_LOCAL_ACCOUNTS (for system applications only) * COMMON_EVENT_USER_STARTING (Reserved, not supported yet) Indicates that user starting is in progress. - Value: **usual.event.USER_STARTING** - - Permission required by subscribers: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS. Only system applications can apply for this permission. + - Required permissions: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (for system applications only) * COMMON_EVENT_USER_UNLOCKED -(Reserved event, not supported currently) When a user is unlocked after a restart, a message is displayed, indicating that the credential encryption storage of the current user has been unlocked. +(Reserved, not supported yet) Indicates that the credential encryption storage of the current user has been unlocked upon restart. - Value: **usual.event.USER_UNLOCKED** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_USER_STOPPING -(Reserved event, not supported currently) Prompt the user to stop. +(Reserved, not supported yet) Prompt the user to stop. - Value: **usual.event.USER_STOPPING** - - Permission required by subscribers: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS. Only system applications can apply for this permission. + - Required permissions: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (for system applications only) * COMMON_EVENT_USER_STOPPED (Reserved, not supported yet) Indicates that the user has been stopped. - Value: **usual.event.USER_STOPPED** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_WIFI_POWER_STATE Indicates that the Wi-Fi state has changed, for example, enabled or disabled. - Value: **usual.event.wifi.POWER_STATE** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_WIFI_SCAN_FINISHED -A message is displayed, indicating that the Wi-Fi access point has been scanned and proved available. +Indicates that the Wi-Fi access point has been scanned and proved available. - Value: **usual.event.wifi.SCAN_FINISHED** - - Required subscriber permissions: ohos.permission.LOCATION + - Required permissions: ohos.permission.LOCATION * COMMON_EVENT_WIFI_RSSI_VALUE Indicates that the Wi-Fi signal strength (RSSI) has changed. - Value: **usual.event.wifi.RSSI_VALUE** - - Required subscriber permissions: ohos.permission.GET_WIFI_INFO + - Required permissions: ohos.permission.GET_WIFI_INFO * COMMON_EVENT_WIFI_CONN_STATE Indicates that the Wi-Fi connection state has changed. - Value: **usual.event.wifi.CONN_STATE** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_WIFI_HOTSPOT_STATE Indicates that the Wi-Fi hotspot state has changed, for example, enabled or disabled. - Value: **usual.event.wifi.HOTSPOT_STATE** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_WIFI_AP_STA_JOIN Indicates that a client has joined the Wi-Fi hotspot of the current device. - Value: **usual.event.wifi.WIFI_HS_STA_JOIN** - - Required subscriber permissions: ohos.permission.GET_WIFI_INFO + - Required permissions: ohos.permission.GET_WIFI_INFO * COMMON_EVENT_WIFI_AP_STA_LEAVE -A message is displayed, indicating that the client is disconnected from the Wi-Fi hotspot of the current device. +Indicates that the client is disconnected from the Wi-Fi hotspot of the current device. - Value: **usual.event.wifi.WIFI_HS_STA_LEAVE** - - Required subscriber permissions: ohos.permission.GET_WIFI_INFO + - Required permissions: ohos.permission.GET_WIFI_INFO * COMMON_EVENT_WIFI_MPLINK_STATE_CHANGE -Indicates that the state of MPLINK (an enhanced Wi-Fi feature) has changed. +(Not supported yet) Indicates that the state of MPLINK (an enhanced Wi-Fi feature) has changed. - Value: **usual.event.wifi.mplink.STATE_CHANGE** - - Required subscriber permissions: ohos.permission.MPLINK_CHANGE_STATE + - Required permissions: none * COMMON_EVENT_WIFI_P2P_CONN_STATE Indicates that the Wi-Fi P2P connection state has changed. - Value: **usual.event.wifi.p2p.CONN_STATE_CHANGE** - - Required subscriber permissions: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + - Required permissions: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION * COMMON_EVENT_WIFI_P2P_STATE_CHANGED Indicates that the Wi-Fi P2P state has changed, for example, enabled or disabled. - Value: **usual.event.wifi.p2p.STATE_CHANGE** - - Required subscriber permissions: ohos.permission.GET_WIFI_INFO + - Required permissions: ohos.permission.GET_WIFI_INFO * COMMON_EVENT_WIFI_P2P_PEERS_STATE_CHANGED Indicates that the state of the Wi-Fi P2P peer device has changed. - Value: **usual.event.wifi.p2p.DEVICES_CHANGE** - - Required subscriber permissions: ohos.permission.GET_WIFI_INFO + - Required permissions: ohos.permission.GET_WIFI_INFO * COMMON_EVENT_WIFI_P2P_PEERS_DISCOVERY_STATE_CHANGED Indicates that the Wi-Fi P2P discovery state has changed. - Value: **usual.event.wifi.p2p.PEER_DISCOVERY_STATE_CHANGE** - - Required subscriber permissions: ohos.permission.GET_WIFI_INFO + - Required permissions: ohos.permission.GET_WIFI_INFO * COMMON_EVENT_WIFI_P2P_CURRENT_DEVICE_STATE_CHANGED Indicates that the state of the Wi-Fi P2P local device has changed. - Value: **usual.event.wifi.p2p.CURRENT_DEVICE_CHANGE** - - Required subscriber permissions: ohos.permission.GET_WIFI_INFO + - Required permissions: ohos.permission.GET_WIFI_INFO * COMMON_EVENT_WIFI_P2P_GROUP_STATE_CHANGED Indicates that the Wi-Fi P2P group information has changed. - Value: **usual.event.wifi.p2p.GROUP_STATE_CHANGED** - - Required subscriber permissions: ohos.permission.GET_WIFI_INFO + - Required permissions: ohos.permission.GET_WIFI_INFO * COMMON_EVENT_BLUETOOTH_HANDSFREE_AG_CONNECT_STATE_UPDATE -(Reserved event, not supported yet) Indicates the connection state of Bluetooth handsfree communication. +(Reserved, not supported yet) Indicates the connection state of Bluetooth handsfree communication. - Value: **usual.event.bluetooth.handsfree.ag.CONNECT_STATE_UPDATE** - - Required subscriber permissions: ohos.permission.USE_BLUETOOTH + - Required permissions: ohos.permission.USE_BLUETOOTH * COMMON_EVENT_BLUETOOTH_HANDSFREE_AG_CURRENT_DEVICE_UPDATE -This event is reserved and is not supported currently. It indicates that the device connected to the Bluetooth hands-free function is active. +(Reserved, not supported yet) Indicates that the device connected to the Bluetooth hands-free function is active. - Value: **usual.event.bluetooth.handsfree.ag.CURRENT_DEVICE_UPDATE** - - Required subscriber permissions: ohos.permission.USE_BLUETOOTH + - Required permissions: ohos.permission.USE_BLUETOOTH * COMMON_EVENT_BLUETOOTH_HANDSFREE_AG_AUDIO_STATE_UPDATE (Reserved, not supported yet) Indicates that the connection state of Bluetooth A2DP has changed. - Value: **usual.event.bluetooth.handsfree.ag.AUDIO_STATE_UPDATE** - - Required subscriber permissions: ohos.permission.USE_BLUETOOTH + - Required permissions: ohos.permission.USE_BLUETOOTH * COMMON_EVENT_BLUETOOTH_A2DPSOURCE_CONNECT_STATE_UPDATE (Reserved, not supported yet) Indicates the connection state of Bluetooth A2DP. - Value: **usual.event.bluetooth.a2dpsource.CONNECT_STATE_UPDATE** - - Required subscriber permissions: ohos.permission.USE_BLUETOOTH + - Required permissions: ohos.permission.USE_BLUETOOTH * COMMON_EVENT_BLUETOOTH_A2DPSOURCE_CURRENT_DEVICE_UPDATE -(Reserved event, not supported yet) Indicates that the device connected using Bluetooth A2DP is active. +(Reserved, not supported yet) Indicates that the device connected using Bluetooth A2DP is active. - Value: **usual.event.bluetooth.a2dpsource.CURRENT_DEVICE_UPDATE** - - Required subscriber permissions: ohos.permission.USE_BLUETOOTH + - Required permissions: ohos.permission.USE_BLUETOOTH * COMMON_EVENT_BLUETOOTH_A2DPSOURCE_PLAYING_STATE_UPDATE -(Reserved event, not supported yet) Indicates that the playing state of Bluetooth A2DP has changed. +(Reserved, not supported yet) Indicates that the playing state of Bluetooth A2DP has changed. - Value: **usual.event.bluetooth.a2dpsource.PLAYING_STATE_UPDATE** - - Required subscriber permissions: ohos.permission.USE_BLUETOOTH + - Required permissions: ohos.permission.USE_BLUETOOTH * COMMON_EVENT_BLUETOOTH_A2DPSOURCE_AVRCP_CONNECT_STATE_UPDATE -(Reserved event, not supported yet) Indicates that the AVRCP connection state of Bluetooth A2DP has changed. +(Reserved, not supported yet) Indicates that the AVRCP connection state of Bluetooth A2DP has changed. - Value: **usual.event.bluetooth.a2dpsource.AVRCP_CONNECT_STATE_UPDATE** - - Required subscriber permissions: ohos.permission.USE_BLUETOOTH + - Required permissions: ohos.permission.USE_BLUETOOTH * COMMON_EVENT_BLUETOOTH_A2DPSOURCE_CODEC_VALUE_UPDATE -(Reserved event, not supported yet) Indicates that the audio codec state of Bluetooth A2DP has changed. +(Reserved, not supported yet) Indicates that the audio codec state of Bluetooth A2DP has changed. - Value: **usual.event.bluetooth.a2dpsource.CODEC_VALUE_UPDATE** - - Required subscriber permissions: ohos.permission.USE_BLUETOOTH + - Required permissions: ohos.permission.USE_BLUETOOTH * COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_DISCOVERED -(Reserved event, not supported yet) Indicates that a remote Bluetooth device is discovered. +(Reserved, not supported yet) Indicates that a remote Bluetooth device is discovered. - Value: **usual.event.bluetooth.remotedevice.DISCOVERED** - - Required subscriber permissions: ohos.permission.LOCATION and ohos.permission.USE_BLUETOOTH + - Required permissions: ohos.permission.LOCATION and ohos.permission.USE_BLUETOOTH * COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CLASS_VALUE_UPDATE -(Reserved event, not supported yet) Indicates that the Bluetooth class of a remote Bluetooth device has changed. +(Reserved, not supported yet) Indicates that the Bluetooth class of a remote Bluetooth device has changed. - Value: **usual.event.bluetooth.remotedevice.CLASS_VALUE_UPDATE** - - Required subscriber permissions: ohos.permission.USE_BLUETOOTH + - Required permissions: ohos.permission.USE_BLUETOOTH * COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_ACL_CONNECTED -(Reserved event, not supported currently) A low-level (ACL) connection has been established with the remote Bluetooth device. +(Reserved, not supported yet) A low-level (ACL) connection has been established with the remote Bluetooth device. - Value: **usual.event.bluetooth.remotedevice.ACL_CONNECTED** - - Required subscriber permissions: ohos.permission.USE_BLUETOOTH + - Required permissions: ohos.permission.USE_BLUETOOTH * COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_ACL_DISCONNECTED -(Reserved event, not supported currently) A message is displayed, indicating that the low-level (ACL) connection has been disconnected from the remote Bluetooth device. +(Reserved, not supported yet) Indicates that the low-level (ACL) connection has been disconnected from the remote Bluetooth device. - Value: **usual.event.bluetooth.remotedevice.ACL_DISCONNECTED** - - Required subscriber permissions: ohos.permission.USE_BLUETOOTH + - Required permissions: ohos.permission.USE_BLUETOOTH * COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_NAME_UPDATE (Reserved, not supported yet) Indicates that the friendly name of a remote Bluetooth device is retrieved for the first time or has changed since the last retrieval. - Value: **usual.event.bluetooth.remotedevice.NAME_UPDATE** - - Required subscriber permissions: ohos.permission.USE_BLUETOOTH + - Required permissions: ohos.permission.USE_BLUETOOTH * COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIR_STATE (Reserved, not supported yet) Indicates the connection state with a remote Bluetooth device is changed. - Value: **usual.event.bluetooth.remotedevice.PAIR_STATE** - - Required subscriber permissions: ohos.permission.USE_BLUETOOTH + - Required permissions: ohos.permission.USE_BLUETOOTH * COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_BATTERY_VALUE_UPDATE (Reserved, not supported yet) Indicates that the battery level of a remote Bluetooth device is retrieved for the first time or has changed since the last retrieval. - Value: **usual.event.bluetooth.remotedevice.BATTERY_VALUE_UPDATE** - - Required subscriber permissions: ohos.permission.USE_BLUETOOTH + - Required permissions: ohos.permission.USE_BLUETOOTH * COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_SDP_RESULT (Reserved, not supported yet) Indicates the SDP state of a remote Bluetooth device. - Value: **usual.event.bluetooth.remotedevice.SDP_RESULT** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_UUID_VALUE (Reserved, not supported yet) Indicates the UUID connection state with a remote Bluetooth device. - Value: **usual.event.bluetooth.remotedevice.UUID_VALUE** - - Required subscriber permissions: ohos.permission.DISCOVER_BLUETOOTH + - Required permissions: ohos.permission.DISCOVER_BLUETOOTH * COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIRING_REQ (Reserved, not supported yet) Indicates the pairing request from a remote Bluetooth device. - Value: **usual.event.bluetooth.remotedevice.PAIRING_REQ** - - Required subscriber permissions: ohos.permission.DISCOVER_BLUETOOTH + - Required permissions: ohos.permission.DISCOVER_BLUETOOTH * COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIRING_CANCEL (Reserved, not supported yet) Indicates that Bluetooth pairing has been canceled. - Value: **usual.event.bluetooth.remotedevice.PAIRING_CANCEL** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_REQ (Reserved, not supported yet) Indicates the connection request from a remote Bluetooth device. - Value: **usual.event.bluetooth.remotedevice.CONNECT_REQ** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_REPLY (Reserved, not supported yet) Indicates the response to the connection request from a remote Bluetooth device. - Value: **usual.event.bluetooth.remotedevice.CONNECT_REPLY** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_CANCEL (Reserved, not supported yet) Indicates that the connection to a remote Bluetooth device has been canceled. - Value: **usual.event.bluetooth.remotedevice.CONNECT_CANCEL** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_CONNECT_STATE_UPDATE (Reserved, not supported yet) Indicates that the connection state with a Bluetooth handsfree has changed. - Value: **usual.event.bluetooth.handsfreeunit.CONNECT_STATE_UPDATE** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AUDIO_STATE_UPDATE (Reserved, not supported yet) Indicates that the audio state of a Bluetooth handsfree has changed. - Value: **usual.event.bluetooth.handsfreeunit.AUDIO_STATE_UPDATE** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AG_COMMON_EVENT (Reserved, not supported yet) Indicates that the audio gateway state of a Bluetooth handsfree has changed. - Value: **usual.event.bluetooth.handsfreeunit.AG_COMMON_EVENT** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AG_CALL_STATE_UPDATE (Reserved, not supported yet) Indicates that the calling state of a Bluetooth handsfree has changed. - Value: **usual.event.bluetooth.handsfreeunit.AG_CALL_STATE_UPDATE** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_BLUETOOTH_HOST_STATE_UPDATE -(Reserved event, not supported currently) Displays a message indicating that the Bluetooth adapter status has been changed, for example, Bluetooth has been enabled or disabled. +(Reserved, not supported yet) Displays a message indicating that the Bluetooth adapter status has been changed, for example, Bluetooth has been enabled or disabled. - Value: **usual.event.bluetooth.host.STATE_UPDATE** - - Required subscriber permissions: ohos.permission.USE_BLUETOOTH + - Required permissions: ohos.permission.USE_BLUETOOTH * COMMON_EVENT_BLUETOOTH_HOST_REQ_DISCOVERABLE -(Reserved event, not supported currently) This event is used to notify a subscriber that Bluetooth scanning is allowed. +(Reserved, not supported yet) This event is used to notify a subscriber that Bluetooth scanning is allowed. - Value: **usual.event.bluetooth.host.REQ_DISCOVERABLE** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_BLUETOOTH_HOST_REQ_ENABLE -(Reserved event, not supported currently) Prompt the user to enable the Bluetooth request. +(Reserved, not supported yet) Prompt the user to enable the Bluetooth request. - Value: **usual.event.bluetooth.host.REQ_ENABLE** - - Required subscriber permissions: ohos.permission.USE_BLUETOOTH + - Required permissions: ohos.permission.USE_BLUETOOTH * COMMON_EVENT_BLUETOOTH_HOST_REQ_DISABLE -(Reserved event, not supported currently) Prompt the user to disable the Bluetooth request. +(Reserved, not supported yet) Prompt the user to disable the Bluetooth request. - Value: **usual.event.bluetooth.host.REQ_DISABLE** - - Required subscriber permissions: ohos.permission.USE_BLUETOOTH + - Required permissions: ohos.permission.USE_BLUETOOTH * COMMON_EVENT_BLUETOOTH_HOST_SCAN_MODE_UPDATE -This event is reserved and is not supported currently. It indicates that the Bluetooth scanning mode of the device is changed. +(Reserved, not supported yet) Indicates that the Bluetooth scanning mode of the device is changed. - Value: **usual.event.bluetooth.host.SCAN_MODE_UPDATE** - - Required subscriber permissions: ohos.permission.USE_BLUETOOTH + - Required permissions: ohos.permission.USE_BLUETOOTH * COMMON_EVENT_BLUETOOTH_HOST_DISCOVERY_STARTED -(Reserved event, not supported currently) Displays a message indicating that Bluetooth scanning has been enabled on the device. +(Reserved, not supported yet) Displays a message indicating that Bluetooth scanning has been enabled on the device. - Value: **usual.event.bluetooth.host.DISCOVERY_STARTED** - - Required subscriber permissions: ohos.permission.USE_BLUETOOTH + - Required permissions: ohos.permission.USE_BLUETOOTH * COMMON_EVENT_BLUETOOTH_HOST_DISCOVERY_FINISHED -(Reserved event, not supported currently) Displays a message indicating that Bluetooth scanning on the device is complete. +(Reserved, not supported yet) Displays a message indicating that Bluetooth scanning on the device is complete. - Value: **usual.event.bluetooth.host.DISCOVERY_FINISHED** - - Required subscriber permissions: ohos.permission.USE_BLUETOOTH + - Required permissions: ohos.permission.USE_BLUETOOTH * COMMON_EVENT_BLUETOOTH_HOST_NAME_UPDATE (Reserved, not supported yet) Indicates that the name of the device Bluetooth adapter has changed. - Value: **usual.event.bluetooth.host.NAME_UPDATE** - - Required subscriber permissions: ohos.permission.USE_BLUETOOTH + - Required permissions: ohos.permission.USE_BLUETOOTH * COMMON_EVENT_BLUETOOTH_A2DPSINK_CONNECT_STATE_UPDATE (Reserved, not supported yet) Indicates that the connection state of Bluetooth A2DP Sink has changed. - Value: **usual.event.bluetooth.a2dpsink.CONNECT_STATE_UPDATE** - - Required subscriber permissions: ohos.permission.USE_BLUETOOTH + - Required permissions: ohos.permission.USE_BLUETOOTH * COMMON_EVENT_BLUETOOTH_A2DPSINK_PLAYING_STATE_UPDATE (Reserved, not supported yet) Indicates that the playing state of Bluetooth A2DP Sink has changed. - Value: **usual.event.bluetooth.a2dpsink.PLAYING_STATE_UPDATE** - - Required subscriber permissions: ohos.permission.USE_BLUETOOTH + - Required permissions: ohos.permission.USE_BLUETOOTH * COMMON_EVENT_BLUETOOTH_A2DPSINK_AUDIO_STATE_UPDATE (Reserved, not supported yet) Indicates that the audio state of Bluetooth A2DP Sink has changed. - Value: **usual.event.bluetooth.a2dpsink.AUDIO_STATE_UPDATE** - - Required subscriber permissions: ohos.permission.USE_BLUETOOTH + - Required permissions: ohos.permission.USE_BLUETOOTH * COMMON_EVENT_NFC_ACTION_ADAPTER_STATE_CHANGED (Reserved, not supported yet) Indicates that the state of the device NFC adapter has changed. - Value: **usual.event.nfc.action.ADAPTER_STATE_CHANGED** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_NFC_ACTION_RF_FIELD_ON_DETECTED (Reserved, not supported yet) Indicates that the NFC RF field is detected to be in the enabled state. - Value: **usual.event.nfc.action.RF_FIELD_ON_DETECTED** - - Permission required by subscribers: ohos.permission.MANAGE_SECURE_SETTINGS (Only system applications can apply for this permission.) + - Required permissions: ohos.permission.MANAGE_SECURE_SETTINGS (for system applications only) * COMMON_EVENT_NFC_ACTION_RF_FIELD_OFF_DETECTED (Reserved, not supported yet) Indicates that the NFC RF field is detected to be in the disabled state. - Value: **usual.event.nfc.action.RF_FIELD_OFF_DETECTED** - - Permission required by subscribers: ohos.permission.MANAGE_SECURE_SETTINGS (Only system applications can apply for this permission.) + - Required permissions: ohos.permission.MANAGE_SECURE_SETTINGS (for system applications only) * COMMON_EVENT_DISCHARGING Indicates that the system stops charging the battery. - Value: **usual.event.DISCHARGING** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_CHARGING Indicates that the system starts charging the battery. - Value: **usual.event.CHARGING** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_DEVICE_IDLE_MODE_CHANGED (Reserved, not supported yet) Indicates that the system idle mode has changed. - Value: **usual.event.DEVICE_IDLE_MODE_CHANGED** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_POWER_SAVE_MODE_CHANGED -Indicates that the system power saving mode has changed. +Indicates that the system power-saving mode has changed. - Value: **usual.event.POWER_SAVE_MODE_CHANGED** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_USER_ADDED Indicates that a user has been added to the system. - Value: **usual.event.USER_ADDED** - - The subscriber requires the ohos.permission.MANAGE_LOCAL_ACCOUNTS permission. Only system applications can apply for this permission. + - Required permissions: ohos.permission.MANAGE_LOCAL_ACCOUNTS (for system applications only) * COMMON_EVENT_USER_REMOVED Indicates that a user has been removed from the system. - Value: **usual.event.USER_REMOVED** - - The subscriber requires the ohos.permission.MANAGE_LOCAL_ACCOUNTS permission. Only system applications can apply for this permission. + - Required permissions: ohos.permission.MANAGE_LOCAL_ACCOUNTS (for system applications only) * COMMON_EVENT_ABILITY_ADDED (Reserved, not supported yet) Indicates that an ability has been added. - Value: **usual.event.ABILITY_ADDED** - - Required subscriber permissions: ohos.permission.LISTEN_BUNDLE_CHANGE + - Required permissions: ohos.permission.LISTEN_BUNDLE_CHANGE * COMMON_EVENT_ABILITY_REMOVED (Reserved, not supported yet) Indicates that an ability has been removed. - Value: **usual.event.ABILITY_REMOVED** - - Required subscriber permissions: ohos.permission.LISTEN_BUNDLE_CHANGE + - Required permissions: ohos.permission.LISTEN_BUNDLE_CHANGE * COMMON_EVENT_ABILITY_UPDATED (Reserved, not supported yet) Indicates that an ability has been updated. - Value: **usual.event.ABILITY_UPDATED** - - Required subscriber permissions: ohos.permission.LISTEN_BUNDLE_CHANGE + - Required permissions: ohos.permission.LISTEN_BUNDLE_CHANGE * COMMON_EVENT_LOCATION_MODE_STATE_CHANGED (Reserved, not supported yet) Indicates that the location mode of the system has changed. - Value: **usual.event.location.MODE_STATE_CHANGED** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_IVI_SLEEP -(Reserved event, not supported currently) Indicates that the in-vehicle infotainment (IVI) system of the vehicle is sleeping. +(Reserved, not supported yet) Indicates that the in-vehicle infotainment (IVI) system of the vehicle is sleeping. - Value: **common.event.IVI_SLEEP** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_IVI_PAUSE -(Reserved event, not supported currently) Displays a message indicating that the in-vehicle infotainment (IVI) system of the vehicle is in sleep mode and notifies the application to stop playing. +(Reserved, not supported yet) Displays a message indicating that the in-vehicle infotainment (IVI) system of the vehicle is in sleep mode and notifies the application to stop playing. - Value: **common.event.IVI_PAUSE** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_IVI_STANDBY -(Reserved event, not supported currently) This event is used to notify a third-party application in the in-vehicle infotainment (IVI) system of a vehicle that the current work is suspended. +(Reserved, not supported yet) This event is used to notify a third-party application in the in-vehicle infotainment (IVI) system of a vehicle that the current work is suspended. - Value: **common.event.IVI_STANDBY** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_IVI_LASTMODE_SAVE -(Reserved event, not supported currently) Prompts the third-party application in the in-vehicle infotainment (IVI) system of the vehicle to save the last mode. +(Reserved, not supported yet) Prompts the third-party application in the in-vehicle infotainment (IVI) system of the vehicle to save the last mode. - Value: **common.event.IVI_LASTMODE_SAVE** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_IVI_VOLTAGE_ABNORMAL (Reserved, not supported yet) Indicates that the voltage of the vehicle's power system is abnormal. - Value: **common.event.IVI_VOLTAGE_ABNORMAL** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_IVI_HIGH_TEMPERATURE -(Reserved event, not supported currently) Indicates that the temperature of the in-vehicle infotainment (IVI) system of the vehicle is too high. +(Reserved, not supported yet) Indicates that the temperature of the in-vehicle infotainment (IVI) system of the vehicle is too high. - Value: **common.event.IVI_HIGH_TEMPERATURE** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_IVI_EXTREME_TEMPERATURE -(Reserved event, not supported currently) Indicates that the temperature of the in-vehicle infotainment (IVI) system of the vehicle is extremely high. +(Reserved, not supported yet) Indicates that the temperature of the in-vehicle infotainment (IVI) system of the vehicle is extremely high. - Value: **common.event.IVI_EXTREME_TEMPERATURE** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_IVI_TEMPERATURE_ABNORMAL -(Reserved event, not supported currently) Indicates that the in-vehicle infotainment (IVI) system of the vehicle has an extreme temperature. +(Reserved, not supported yet) Indicates that the in-vehicle infotainment (IVI) system of the vehicle has an extreme temperature. - Value: **common.event.IVI_TEMPERATURE_ABNORMAL** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_IVI_VOLTAGE_RECOVERY (Reserved, not supported yet) Indicates that the voltage of the vehicle's power system is restored to normal. - Value: **common.event.IVI_VOLTAGE_RECOVERY** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_IVI_TEMPERATURE_RECOVERY (Reserved, not supported yet) Indicates that the temperature of the IVI system is restored to normal. - Value: **common.event.IVI_TEMPERATURE_RECOVERY** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_IVI_ACTIVE -(Reserved event, not supported currently) Indicates that the battery service of the vehicle-mounted system is active. +(Reserved, not supported yet) Indicates that the battery service of the vehicle-mounted system is active. - Value: **common.event.IVI_ACTIVE** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_USB_STATE9+ Indicates that the USB device state has changed. - Value: **usual.event.hardware.usb.action.USB_STATE** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_USB_PORT_CHANGED9+ Indicates that the USB port state of the device has changed. - Value: **usual.event.hardware.usb.action.USB_PORT_CHANGED** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_USB_DEVICE_ATTACHED Indicates that a USB device has been attached to the device functioning as a USB host. - Value: **usual.event.hardware.usb.action.USB_DEVICE_ATTACHED** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_USB_DEVICE_DETACHED Indicates that a USB device has been detached from the device functioning as a USB host. - Value: **usual.event.hardware.usb.action.USB_DEVICE_DETACHED** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_USB_ACCESSORY_ATTACHED (Reserved, not supported yet) Indicates that a USB accessory was attached. - Value: **usual.event.hardware.usb.action.USB_ACCESSORY_ATTACHED** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_USB_ACCESSORY_DETACHED -(Reserved event, not supported currently) A message is displayed, indicating that the USB attachment is uninstalled. +(Reserved, not supported yet) Indicates that the USB attachment is uninstalled. - Value: **usual.event.hardware.usb.action.USB_ACCESSORY_DETACHED** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_DISK_REMOVED (Reserved, not supported yet) Indicates that an external storage device was removed. - Value: **usual.event.data.DISK_REMOVED** - - The subscriber requires the ohos.permission.STORAGE_MANAGER permission. Only system applications can apply for this permission. + - Required permissions: ohos.permission.STORAGE_MANAGER (for system applications only) * COMMON_EVENT_DISK_UNMOUNTED (Reserved, not supported yet) Indicates that an external storage device was unmounted. - Value: **usual.event.data.DISK_UNMOUNTED** - - The subscriber requires the ohos.permission.STORAGE_MANAGER permission. Only system applications can apply for this permission. + - Required permissions: ohos.permission.STORAGE_MANAGER (for system applications only) * COMMON_EVENT_DISK_MOUNTED (Reserved, not supported yet) Indicates that an external storage device was mounted. - Value: **usual.event.data.DISK_MOUNTED** - - The subscriber requires the ohos.permission.STORAGE_MANAGER permission. Only system applications can apply for this permission. + - Required permissions: ohos.permission.STORAGE_MANAGER (for system applications only) * COMMON_EVENT_DISK_BAD_REMOVAL (Reserved, not supported yet) Indicates that an external storage device was removed without being unmounted. - Value: **usual.event.data.DISK_BAD_REMOVAL** - - The subscriber requires the ohos.permission.STORAGE_MANAGER permission. Only system applications can apply for this permission. + - Required permissions: ohos.permission.STORAGE_MANAGER (for system applications only) * COMMON_EVENT_DISK_UNMOUNTABLE -This event is reserved and is not supported currently. A message is displayed, indicating that the external storage device cannot be mounted when a card is inserted. +(Reserved, not supported yet) Indicates that the external storage device cannot be mounted when a card is inserted. - Value: **usual.event.data.DISK_UNMOUNTABLE** - - The subscriber requires the ohos.permission.STORAGE_MANAGER permission. Only system applications can apply for this permission. + - Required permissions: ohos.permission.STORAGE_MANAGER (for system applications only) * COMMON_EVENT_DISK_EJECT -(Reserved event, not supported currently) Prompts the user that the external storage medium has been ejected (interactive operation at the system software layer, not directly ejected physically). +(Reserved, not supported yet) Indicates that the external storage medium has been ejected (interactive operation at the system software layer, not directly ejected physically). - Value: **usual.event.data.DISK_EJECT** - - The subscriber requires the ohos.permission.STORAGE_MANAGER permission. Only system applications can apply for this permission. + - Required permissions: ohos.permission.STORAGE_MANAGER (for system applications only) * COMMON_EVENT_VOLUME_REMOVED9+ Indicates that an external storage device was removed. - Value: **usual.event.data.VOLUME_REMOVED** - - The subscriber requires the ohos.permission.STORAGE_MANAGER permission. Only system applications can apply for this permission. + - Required permissions: ohos.permission.STORAGE_MANAGER (for system applications only) * COMMON_EVENT_VOLUME_UNMOUNTED9+ Indicates that an external storage device was unmounted. - Value: **usual.event.data.VOLUME_UNMOUNTED** - - The subscriber requires the ohos.permission.STORAGE_MANAGER permission. Only system applications can apply for this permission. + - Required permissions: ohos.permission.STORAGE_MANAGER (for system applications only) * COMMON_EVENT_VOLUME_MOUNTED9+ Indicates that an external storage device was mounted. - Value: **usual.event.data.VOLUME_MOUNTED** - - The subscriber requires the ohos.permission.STORAGE_MANAGER permission. Only system applications can apply for this permission. + - Required permissions: ohos.permission.STORAGE_MANAGER (for system applications only) * COMMON_EVENT_VOLUME_BAD_REMOVAL9+ Indicates that an external storage device was removed without being unmounted. - Value: **usual.event.data.VOLUME_BAD_REMOVAL** - - The subscriber requires the ohos.permission.STORAGE_MANAGER permission. Only system applications can apply for this permission. + - Required permissions: ohos.permission.STORAGE_MANAGER (for system applications only) * COMMON_EVENT_VOLUME_EJECT9+ -A message is displayed, indicating that the external storage medium has been ejected (interactive operation at the system software layer, not physical ejection). +Indicates that the external storage medium has been ejected (interactive operation at the system software layer, not physical ejection). - Value: **usual.event.data.VOLUME_EJECT** - - The subscriber requires the ohos.permission.STORAGE_MANAGER permission. Only system applications can apply for this permission. + - Required permissions: ohos.permission.STORAGE_MANAGER (for system applications only) * COMMON_EVENT_VISIBLE_ACCOUNTS_UPDATED (Reserved, not supported yet) Indicates that the account visibility changed. - Value: **usual.event.data.VISIBLE_ACCOUNTS_UPDATED** - - The subscriber requires the ohos.permission.GET_APP_ACCOUNTS permission. Only system applications can apply for this permission. + - Required permissions: ohos.permission.GET_APP_ACCOUNTS (for system applications only) * COMMON_EVENT_ACCOUNT_DELETED (Reserved, not supported yet) Indicates that an account was deleted. - Value: **usual.event.data.ACCOUNT_DELETED** - - Permission required by subscribers: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS. Only system applications can apply for this permission. + - Required permissions: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (for system applications only) * COMMON_EVENT_FOUNDATION_READY (Reserved, not supported yet) Indicates that the foundation is ready. - Value: **usual.event.data.FOUNDATION_READY** - - Permission required by subscribers: ohos.permission.RECEIVER_STARTUP_COMPLETED (Only system applications can apply for this permission.) + - Required permissions: ohos.permission.RECEIVER_STARTUP_COMPLETED (for system applications only) * COMMON_EVENT_AIRPLANE_MODE_CHANGED Indicates that the airplane mode of the device has changed. - Value: **usual.event.AIRPLANE_MODE** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_SPLIT_SCREEN8+ @@ -892,24 +892,24 @@ Indicates that the screen has been split. * COMMON_EVENT_SLOT_CHANGE9+ Indicates that the notification slot has been updated. - Value: **usual.event.SLOT_CHANGE** - - Required subscriber permissions: ohos.permission.NOTIFICATION_CONTROLLER + - Required permissions: ohos.permission.NOTIFICATION_CONTROLLER * COMMON_EVENT_SPN_INFO_CHANGED9+ Indicates that the SPN displayed has been updated. - Value: **usual.event.SPN_INFO_CHANGED** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_QUICK_FIX_APPLY_RESULT9+ Indicates the result of quickly repairing an application. - Value: **usual.event.QUICK_FIX_APPLY_RESULT** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_USER_INFO_UPDATED9+ Indicates that the user information has been updated. - Value: **usual.event.USER_INFO_UPDATED** - - Required subscriber permissions: none + - Required permissions: none * COMMON_EVENT_SMS_RECEIVE_COMPLETED Indicates that a new SMS message has been received. diff --git a/en/application-dev/reference/apis-basic-services-kit/common_event/commonEventManager-definitions-sys.md b/en/application-dev/reference/apis-basic-services-kit/common_event/commonEventManager-definitions-sys.md index 54f6279ce89..e7e4d03060b 100644 --- a/en/application-dev/reference/apis-basic-services-kit/common_event/commonEventManager-definitions-sys.md +++ b/en/application-dev/reference/apis-basic-services-kit/common_event/commonEventManager-definitions-sys.md @@ -1,6 +1,6 @@ # System Common Events (System API) -This document provides a list of common events defined by the system. +This topic provides a list of common events defined by the system. Common event types are defined in [Support enumeration of the ohos.commonEventManager module](../js-apis-commonEventManager.md#support). @@ -16,13 +16,13 @@ Common event types are defined in [Support enumeration of the ohos.commonEventMa Indicates that the boot is complete and the system is loaded. -When the specified user finishes the boot process on the device, the event notification service is triggered to publish this event. +When the specified user finishes the boot process on the device, the common event service is triggered to publish this event. **System API**: This is a system API. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.RECEIVER_STARTUP_COMPLETED (for system applications only) +**Required permissions**: ohos.permission.RECEIVER_STARTUP_COMPLETED (for system applications only) **Value**: "usual.event.BOOT_COMPLETED" @@ -30,13 +30,13 @@ When the specified user finishes the boot process on the device, the event notif Indicates that a package is sent by the system verifier when the package is verified. -When a new application starts to be installed by a specified user on the device, the event notification service is triggered to publish this event. +When a new application starts to be installed by a specified user on the device, the common event service is triggered to publish this event. **System API**: This is a system API. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.PACKAGE_INSTALLATION_STARTED" @@ -51,11 +51,68 @@ This common event is sent when the bundle management resource data is updated in **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.GET_BUNDLE_RESOURCES +**Required permissions**: ohos.permission.GET_BUNDLE_RESOURCES **Value**: "usual.event.BUNDLE_RESOURCES_CHANGED" +### COMMON_EVENT_DEFAULT_APPLICATION_CHANGED19+ + +Indicates that the default application for opening a file has changed. + +This common event is sent when the default application for opening a file changes. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Required permissions**: ohos.permission.CHANGE_DEFAULT_APPLICATION + +**Value:** "usual.event.DEFAULT_APPLICATION_CHANGED" + + +### COMMON_EVENT_SHORTCUT_CHANGED20+ + +Indicates that the application shortcut has changed. + +This common event is sent when the shortcut is changed (for example, when [setShortcutVisibleForSelf](../../apis-ability-kit/js-apis-shortcutManager.md#shortcutmanagersetshortcutvisibleforself) of the shortcutManager module is successfully called). + +**System API**: This is a system API. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Required permissions**: ohos.permission.MANAGE_SHORTCUTS + +**Value:** "usual.event.SHORTCUT_CHANGED" + + +### COMMON_EVENT_KIOSK_MODE_ON20+ + +Indicates that the kiosk mode is enabled. When this mode is on, the common event service is triggered to publish this system common event. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Required permissions**: none + +**Value:** usual.event.KIOSK_MODE_ON + + +### COMMON_EVENT_KIOSK_MODE_OFF20+ + +Indicates that the kiosk mode is disabled. When this mode is off, the common event service is triggered to publish this system common event. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Required permissions**: none + +**Value:** usual.event.KIOSK_MODE_OFF + + + ## Background Tasks Kit @@ -63,7 +120,7 @@ This common event is sent when the bundle management resource data is updated in Indicates that the exemption list for resource usage restrictions has been updated in idle mode. -When the exemption list for resource usage restrictions is updated, the event notification service is triggered to publish this event. +When the exemption list for resource usage restrictions is updated, the common event service is triggered to publish this event. Resources include application network access, Timer usage, and WorkScheduler task usage. System applications can call JavaScript APIs to apply for removing resource usage restrictions. @@ -72,12 +129,43 @@ System applications can call JavaScript APIs to apply for removing resource usag **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.DEVICE_IDLE_EXEMPTION_LIST_UPDATED" +## Basic Services Kit - Customization + +### COMMON_EVENT_CUSTOM_CONFIG_POLICY_UPDATED20+ + +Indicates that the configuration directory level and system parameters of a device are updated. + +This common event is sent when the system updates the device configuration directory level and system parameters after identifying the home area and roaming area of the device. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Required permissions**: none + +**Value:** "usual.event.CUSTOM_CONFIG_POLICY_UPDATED" + +### COMMON_EVENT_CUSTOM_ROAMING_REGION_UPDATED20+ + +Indicates that the roaming area of a device is updated. + +When the attributes such as network injection, persistent Connection, and GPS location of a device change, the system identifies the roaming area and updates the parameters if the roaming area changes. After the update is complete, this common event is sent. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Required permissions**: none + +**Value:** "usual.event.CUSTOM_ROAMING_REGION_UPDATED" + + ## Basic Services Kit - Power Supply @@ -85,13 +173,13 @@ System applications can call JavaScript APIs to apply for removing resource usag Indicates that the system charging type has changed. -When the system charging type changes, the event notification service is triggered to publish this event. +When the system charging type changes, the common event service is triggered to publish this event. **System API**: This is a system API. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.CHARGE_TYPE_CHANGED" @@ -100,7 +188,7 @@ When the system charging type changes, the event notification service is trigger Indicates that a user has been added to the system. -When a system account is created, the event notification service is triggered to publish this event carrying the system account ID. +When a system account is created, the common event service is triggered to publish this event carrying the system account ID. APIs related to this event: **createOsAccount** and **createOsAccountForDomain**. These APIs are system APIs. For details, see [@ohos.account.osAccount (System Account Management)](../js-apis-osAccount.md). @@ -108,7 +196,7 @@ APIs related to this event: **createOsAccount** and **createOsAccountForDomain** **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS (for system applications only) +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS (for system applications only) **Value**: "usual.event.USER_ADDED" @@ -117,7 +205,7 @@ APIs related to this event: **createOsAccount** and **createOsAccountForDomain** Indicates that a user has been removed from the system. -When a system account is removed, the event notification service is triggered to publish this event carrying the system account ID. +When a system account is removed, the common event service is triggered to publish this event carrying the system account ID. APIs related to this event: **removeOsAccount**. This API is a system API. For details, see [@ohos.account.osAccount (System Account Management)](../js-apis-osAccount.md). @@ -125,7 +213,7 @@ APIs related to this event: **removeOsAccount**. This API is a system API. For d **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS (for system applications only) +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS (for system applications only) **Value**: "usual.event.USER_REMOVED" @@ -134,7 +222,7 @@ APIs related to this event: **removeOsAccount**. This API is a system API. For d Indicates that the status of the domain account status changes. -When a domain user account is authenticated, deleted, or has the token updated, the event notification service is triggered to publish this event carrying the system account ID, domain name, and account status. +When a domain user account is authenticated, deleted, or has the token updated, the common event service is triggered to publish this event carrying the system account ID, domain name, and account status. APIs related to this event: **removeOsAccount**, **DomainAccountManager.auth**, and **updateAccountToken**. These APIs are system APIs. For details, see [@ohos.account.osAccount (System Account Management)](../js-apis-osAccount.md). @@ -142,7 +230,7 @@ APIs related to this event: **removeOsAccount**, **DomainAccountManager.auth**, **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.GET_LOCAL_ACCOUNTS (for system applications only) +**Required permissions**: ohos.permission.GET_LOCAL_ACCOUNTS (for system applications only) **Value**: "usual.event.DOMAIN_ACCOUNT_STATUS_CHANGED" @@ -151,7 +239,7 @@ APIs related to this event: **removeOsAccount**, **DomainAccountManager.auth**, Indicates that a user switchover is complete. -When a system account is switched, the event notification service is triggered to publish this event carrying the system account ID. +When a system account is switched, the common event service is triggered to publish this event carrying the system account ID. APIs related to this event: **activateOsAccount**. This API is a system API. For details, see [@ohos.account.osAccount (System Account Management)](../js-apis-osAccount.md). @@ -159,7 +247,7 @@ APIs related to this event: **activateOsAccount**. This API is a system API. For **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS (for system applications only) +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS (for system applications only) **Value**: "usual.event.USER_SWITCHED" @@ -181,7 +269,7 @@ This common event is triggered when an external storage device is removed. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.STORAGE_MANAGER +**Required permissions**: ohos.permission.STORAGE_MANAGER **Value**: "usual.event.data.VOLUME_REMOVED" @@ -195,7 +283,7 @@ This common event is triggered when an external storage device is successfully u **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.STORAGE_MANAGER +**Required permissions**: ohos.permission.STORAGE_MANAGER **Value**: "usual.event.data.VOLUME_UNMOUNTED" @@ -210,7 +298,7 @@ This common event is triggered when an external storage device is successfully m **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.STORAGE_MANAGER +**Required permissions**: ohos.permission.STORAGE_MANAGER **Value**: "usual.event.data.VOLUME_MOUNTED" @@ -225,7 +313,7 @@ This common event is triggered when an external storage device is directly remov **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.STORAGE_MANAGER +**Required permissions**: ohos.permission.STORAGE_MANAGER **Value**: "usual.event.data.VOLUME_BAD_REMOVAL" @@ -240,7 +328,7 @@ This common event is triggered when the user calls the **unmount** API on a moun **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.STORAGE_MANAGER +**Required permissions**: ohos.permission.STORAGE_MANAGER **Value**: "usual.event.data.VOLUME_EJECT" @@ -249,13 +337,13 @@ This common event is triggered when the user calls the **unmount** API on a moun Indicates the common event that an application starts to be restored. -When a data migration application starts the backup and restore framework to perform a restoration task, the event notification service is triggered to publish this event. +When a data migration application starts the backup and restore framework to perform a restoration task, the common event service is triggered to publish this event. **System API**: This is a system API. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.START_RESTORE_NOTIFICATION +**Required permissions**: ohos.permission.START_RESTORE_NOTIFICATION **Value**: "usual.event.RESTORE_START" @@ -268,13 +356,13 @@ When a data migration application starts the backup and restore framework to per Indicates that an SMS message is received. -When the device receives an SMS message, the event notification service is triggered to publish this event. +When the device receives an SMS message, the common event service is triggered to publish this event. **System API**: This is a system API. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.RECEIVE_SMS (for system apps only) +**Required permissions**: ohos.permission.RECEIVE_SMS (for system applications only) **Value**: usual.event.SMS_RECEIVED_COMPLETED @@ -283,13 +371,13 @@ When the device receives an SMS message, the event notification service is trigg Indicates that an emergency cell broadcast message is received. -When the device receives an emergency cell broadcast message, the event notification service is triggered to publish this event. +When the device receives an emergency cell broadcast message, the common event service is triggered to publish this event. **System API**: This is a system API. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.RECEIVE_SMS (for system apps only) +**Required permissions**: ohos.permission.RECEIVE_SMS (for system applications only) **Value**: usual.event.SMS_EMERGENCY_CB_RECEIVE_COMPLETED @@ -298,13 +386,13 @@ When the device receives an emergency cell broadcast message, the event notifica Indicates that a cell broadcast message is received. -When the device receives a cell broadcast message, the event notification service is triggered to publish this event. +When the device receives a cell broadcast message, the common event service is triggered to publish this event. **System API**: This is a system API. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.RECEIVE_SMS (for system apps only) +**Required permissions**: ohos.permission.RECEIVE_SMS (for system applications only) **Value**: usual.event.SMS_CB_RECEIVE_COMPLETED @@ -312,13 +400,13 @@ When the device receives a cell broadcast message, the event notification servic Indicates that the carrier configuration has been updated. -When the carrier configuration of the device is updated, the event notification service is triggered to publish this event. +When the carrier configuration of the device is updated, the common event service is triggered to publish this event. **System API**: This is a system API. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: usual.event.OPERATOR_CONFIG_CHANGED @@ -327,13 +415,13 @@ When the carrier configuration of the device is updated, the event notification Indicates that the default primary SIM card for the SMS service has been updated. -When the default primary SIM card for the SMS service is updated, the event notification service is triggered to publish this event. +When the default primary SIM card for the SMS service is updated, the common event service is triggered to publish this event. **System API**: This is a system API. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: usual.event.DEFAULT_SMS_SUBSCRIPTION_CHANGED @@ -342,13 +430,13 @@ When the default primary SIM card for the SMS service is updated, the event noti Indicates that the default primary SIM card for the data service has been updated. -When the default primary SIM card for the data service is updated, the event notification service is triggered to publish this event. +When the default primary SIM card for the data service is updated, the common event service is triggered to publish this event. **System API**: This is a system API. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: usual.event.DEFAULT_DATA_SUBSCRIPTION_CHANGED @@ -357,13 +445,13 @@ When the default primary SIM card for the data service is updated, the event not Indicates that the default primary SIM card of the device has been updated. -When the default primary SIM card of the device is updated, the event notification service is triggered to publish this event. +When the default primary SIM card of the device is updated, the common event service is triggered to publish this event. **System API**: This is a system API. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: usual.event.SIM.DEFAULT_MAIN_SUBSCRIPTION_CHANGED @@ -372,13 +460,13 @@ When the default primary SIM card of the device is updated, the event notificati Indicates that the status of the action for setting the primary SIM card changes. -When the status of the action for setting the primary SIM card changes (for example, when the status is updated to executing or completed), the event notification service is triggered to publish this event. +When the status of the action for setting the primary SIM card changes (for example, when the status is updated to executing or completed), the common event service is triggered to publish this event. **System API**: This is a system API. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: usual.event.SET_PRIMARY_SLOT_STATUS @@ -387,13 +475,13 @@ When the status of the action for setting the primary SIM card changes (for exam Indicates that the roaming status of the default primary SIM card is updated. -When the roaming status of the default primary SIM card changes, the event notification service is triggered to publish this event. +When the roaming status of the default primary SIM card changes, the common event service is triggered to publish this event. **System API**: This is a system API. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: usual.event.PRIMARY_SLOT_ROAMING @@ -402,13 +490,13 @@ When the roaming status of the default primary SIM card changes, the event notif Indicates that the default primary SIM card for the voice service has been updated. -When the default primary SIM card for the voice service is updated, the event notification service is triggered to publish this event. +When the default primary SIM card for the voice service is updated, the common event service is triggered to publish this event. **System API**: This is a system API. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: usual.event.DEFAULT_VOICE_SUBSCRIPTION_CHANGED @@ -417,13 +505,13 @@ When the default primary SIM card for the voice service is updated, the event no Indicates that the cellular data status has been updated. -When the cellular data status of the device is updated, the event notification service is triggered to publish this event. +When the cellular data status of the device is updated, the common event service is triggered to publish this event. **System API**: This is a system API. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: usual.event.CELLULAR_DATA_STATE_CHANGED @@ -432,13 +520,13 @@ When the cellular data status of the device is updated, the event notification s Indicates that an incoming call is missed. -When an incoming call is missed on the device, the event notification service is triggered to publish this event. +When an incoming call is missed on the device, the common event service is triggered to publish this event. **System API**: This is a system API. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.GET_TELEPHONY_STATE (for system apps only) +**Required permissions**: ohos.permission.GET_TELEPHONY_STATE (for system applications only) **Value**: usual.event.INCOMING_CALL_MISSED @@ -447,13 +535,13 @@ When an incoming call is missed on the device, the event notification service is Indicates that the radio status of the device has changed. -When there is a change in the radio status of the device, the event notification service is triggered to publish this event. +When there is a change in the radio status of the device, the common event service is triggered to publish this event. **System API**: This is a system API. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: usual.event.RADIO_STATE_CHANGE @@ -462,13 +550,13 @@ When there is a change in the radio status of the device, the event notification Indicates that a secret code is sent successfully. -When a secret code is successfully sent on the device, the event notification service is triggered to publish this event. +When a secret code is successfully sent on the device, the common event service is triggered to publish this event. **System API**: This is a system API. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: usual.event.DIALER_SPECIAL_CODE @@ -477,13 +565,13 @@ When a secret code is successfully sent on the device, the event notification se Indicates that the audio quality has changed. -When there is a change in the audio quality of the device, the event notification service is triggered to publish this event. +When there is a change in the audio quality of the device, the common event service is triggered to publish this event. **System API**: This is a system API. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: usual.event.AUDIO_QUALITY_CHANGE @@ -498,13 +586,13 @@ Below are reserved common events that are not supported yet. (Reserved, not supported yet) Indicates that an STK command is sent. -When an STK command is sent, the event notification service is triggered to publish this event. +When an STK command is sent, the common event service is triggered to publish this event. **System API**: This is a system API. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: usual.event.STK_COMMAND @@ -513,13 +601,13 @@ When an STK command is sent, the event notification service is triggered to publ (Reserved, not supported yet) Indicates that an STK session has ended. -When an STK session ends, the event notification service is triggered to publish this event. +When an STK session ends, the common event service is triggered to publish this event. **System API**: This is a system API. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: usual.event.STK_SESSION_END @@ -528,13 +616,13 @@ When an STK session ends, the event notification service is triggered to publish (Reserved, not supported yet) Indicates that the STK card status has been updated. -When the STK card status is updated, the event notification service is triggered to publish this event. +When the STK card status is updated, the common event service is triggered to publish this event. **System API**: This is a system API. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: usual.event.STK_CARD_STATE_CHANGED @@ -543,13 +631,13 @@ When the STK card status is updated, the event notification service is triggered (Reserved, not supported yet) Indicates that an STK Alpha identifier is sent. -When an STK Alpha identifier is sent, the event notification service is triggered to publish this event. +When an STK Alpha identifier is sent, the common event service is triggered to publish this event. **System API**: This is a system API. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: usual.event.STK_ALPHA_IDENTIFIER @@ -558,12 +646,12 @@ When an STK Alpha identifier is sent, the event notification service is triggere (Reserved, not supported yet) Indicates that a WAP push message is received. -When the device receives a WAP push message, the event notification service is triggered to publish this event. +When the device receives a WAP push message, the common event service is triggered to publish this event. **System API**: This is a system API. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.RECEIVE_SMS (for system apps only) +**Required permissions**: ohos.permission.RECEIVE_SMS (for system applications only) **Value**: usual.event.SMS_WAPPUSH_RECEIVE_COMPLETED diff --git a/en/application-dev/reference/apis-basic-services-kit/common_event/commonEventManager-definitions.md b/en/application-dev/reference/apis-basic-services-kit/common_event/commonEventManager-definitions.md index d1700701eef..d7374f154ee 100644 --- a/en/application-dev/reference/apis-basic-services-kit/common_event/commonEventManager-definitions.md +++ b/en/application-dev/reference/apis-basic-services-kit/common_event/commonEventManager-definitions.md @@ -3,8 +3,6 @@ This document provides a list of common events defined by the system. Common event types are defined in [Support](../js-apis-commonEventManager.md#support) of the **ohos.commonEventManager** module. - - ## Ability Kit @@ -16,7 +14,7 @@ When the specified user restarts the application and kills all its processes, th **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.PACKAGE_RESTARTED" @@ -28,7 +26,7 @@ When the specified user clears the application package data on the device, the e **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.PACKAGE_DATA_CLEARED" @@ -41,7 +39,7 @@ When the specified user applies a quick fix to the application on the device, th **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.QUICK_FIX_APPLY_RESULT" @@ -53,7 +51,7 @@ When a quick fix to the application is revoked on the device, the event notifica **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.QUICK_FIX_REVOKE_RESULT" @@ -65,7 +63,7 @@ When a new application is installed by a specified user on the device, the event **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.PACKAGE_ADDED" @@ -78,7 +76,7 @@ When a specified application package is removed by a specified user on the devic **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.PACKAGE_REMOVED" @@ -89,7 +87,7 @@ Indicates the common event that an installed bundle has been uninstalled from th **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.BUNDLE_REMOVED" @@ -100,7 +98,7 @@ Indicates the common event that an installed application has been completely uni **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.PACKAGE_FULLY_REMOVED" @@ -113,7 +111,7 @@ When an application package installed on the device is updated or an ability in **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.PACKAGE_CHANGED" @@ -126,7 +124,7 @@ When the cache of an application package installed on the device is cleared, the **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.PACKAGE_CACHE_CLEARED" @@ -137,7 +135,7 @@ Indicates the common event that application packages have been suspended. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.PACKAGES_SUSPENDED" @@ -147,7 +145,7 @@ Sent to a package that has been suspended by the system. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.MY_PACKAGE_SUSPENDED" @@ -158,7 +156,7 @@ Sent to a package that has been unsuspended by the system. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.MY_PACKAGE_UNSUSPENDED" @@ -168,7 +166,7 @@ Notifies the low memory state and package management should be started. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.MANAGE_PACKAGE_STORAGE" @@ -184,7 +182,7 @@ When the minor mode is enabled on the device, the event notification service is **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Atomic service API**: This API can be used in atomic services since API version 12. @@ -198,7 +196,7 @@ When the minor mode is disabled on the device, the event notification service is **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Atomic service API**: This API can be used in atomic services since API version 12. @@ -216,11 +214,11 @@ When any of the following actions is performed, the event notification service i **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions:** ohos.permission.RECEIVER_SPLIT_SCREEN +**Required permissions**: ohos.permission.RECEIVER_SPLIT_SCREEN **Atomic service API**: This API can be used in atomic services since API version 11. -**Value**: usual.event.SPLIT_SCREEN" +**Value**: "usual.event.SPLIT_SCREEN" @@ -234,9 +232,7 @@ When any of the following actions is performed, the event notification service i **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions:** ohos.permission.NOTIFICATION_CONTROLLER - -**System capability**: SystemCapability.Notification.CommonEvent +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER **Value**: "usual.event.SLOT_CHANGE" @@ -253,7 +249,7 @@ When the user does not use the device for the specified period of time and the s **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.DEVICE_IDLE_MODE_CHANGED" @@ -270,7 +266,7 @@ When a USB device is connected to or disconnected from the device, the event not **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.hardware.usb.action.USB_STATE" @@ -283,7 +279,7 @@ When the USB port state changes, the event notification service is triggered to **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.hardware.usb.action.USB_PORT_CHANGED" @@ -296,7 +292,7 @@ When a USB device is attached, the event notification service is triggered to pu **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.hardware.usb.action.USB_DEVICE_ATTACHED" @@ -309,7 +305,7 @@ When a USB device is detached, the event notification service is triggered to pu **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.hardware.usb.action.USB_DEVICE_DETACHED" @@ -322,7 +318,7 @@ When the system time is set, the event notification service is triggered to publ **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.TIME_CHANGED" @@ -335,7 +331,7 @@ When the system time in the unit of minute changes, the event notification servi **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.TIME_TICK" @@ -348,7 +344,7 @@ When the system time zone changes, the event notification service is triggered t **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.TIMEZONE_CHANGED" @@ -362,9 +358,7 @@ APIs related to this event: **setOsAccountName**, **setOsAccountProfilePhoto**, **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none - -**System capability**: SystemCapability.Notification.CommonEvent +**Required permissions**: none **Value**: "usual.event.USER_INFO_UPDATED" @@ -377,9 +371,7 @@ When the device is unlocked with the lock screen password the first time after u **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none - -**System capability**: SystemCapability.Notification.CommonEvent +**Required permissions**: none **Value**: "usual.event.USER_UNLOCKED" @@ -394,7 +386,7 @@ APIs related to this event: **setOsAccountDistributedInfo** and **updateOsAccoun **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Atomic service API**: This API can be used in atomic services since API version 12. @@ -411,7 +403,7 @@ APIs related to this event: **setOsAccountDistributedInfo** and **updateOsAccoun **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Atomic service API**: This API can be used in atomic services since API version 12. @@ -426,10 +418,10 @@ When the token of a distributed account is invalid, the event notification servi APIs related to this event: **setOsAccountDistributedInfo** and **updateOsAccountDistributedInfo** (discarded), and **setOsAccountDistributedInfoByLocalId**. The first two are public APIs, and the last one is a system API. For details, see [@ohos.account.distributedAccount (Distributed Account Management)](../js-apis-distributed-account.md). -**Required subscriber permissions**: none - **System capability**: SystemCapability.Notification.CommonEvent +**Required permissions**: none + **Atomic service API**: This API can be used in atomic services since API version 12. **Value**: "common.event.DISTRIBUTED_ACCOUNT_TOKEN_INVALID" @@ -444,7 +436,7 @@ APIs related to this event: **setOsAccountDistributedInfo** and **updateOsAccoun **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Atomic service API**: This API can be used in atomic services since API version 12. @@ -457,7 +449,7 @@ When the screen is locked, the event notification service is triggered to publis **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Atomic service API**: This API can be used in atomic services since API version 11. @@ -470,7 +462,7 @@ When the screen is unlocked, the event notification service is triggered to publ **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Atomic service API**: This API can be used in atomic services since API version 11. @@ -486,7 +478,7 @@ Indicates the action of a common event that the user unlocks the device. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: usual.event.USER_PRESENT @@ -499,7 +491,7 @@ When any of the following information changes, the event notification service is **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.BATTERY_CHANGED" @@ -512,7 +504,7 @@ When the battery level drops to lower than the low battery level set for the dev **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.BATTERY_LOW" @@ -526,7 +518,7 @@ When the battery level changes from the low level to normal level, the event not **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.BATTERY_OKAY" @@ -539,7 +531,7 @@ When the device connects to an external charger, the event notification service **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.POWER_CONNECTED" @@ -552,7 +544,7 @@ When the device is disconnected from the external power supply, the event notifi **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.POWER_DISCONNECTED" @@ -565,7 +557,7 @@ When the system stops charging the battery, the event notification service is tr **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.DISCHARGING" @@ -578,7 +570,7 @@ When the system starts charging the battery, the event notification service is t **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.CHARGING" @@ -590,7 +582,7 @@ When the device starts charging in idle mode, and the temperature rise is accept **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.CHARGE_IDLE_MODE_CHANGED" @@ -603,7 +595,7 @@ When the device is being shut down until it is powered off, the event notificati **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.SHUTDOWN" @@ -616,7 +608,7 @@ When the device screen-off initiated by the power service is complete, the event **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.SCREEN_OFF" @@ -629,20 +621,20 @@ When the device screen-on initiated by the power service is complete, the event **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.SCREEN_ON" ### COMMON_EVENT_POWER_SAVE_MODE_CHANGED -Indicates that the system power saving mode has changed. +Indicates that the system power-saving mode has changed. When the system power saving mode changes, the event notification service is triggered to publish this event. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.POWER_SAVE_MODE_CHANGED" @@ -655,7 +647,7 @@ When the device's thermal level changes, the event notification service is trigg **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.THERMAL_LEVEL_CHANGED" @@ -669,7 +661,7 @@ When the device is about to enter the forced sleep mode, the event notification **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.ENTER_FORCE_SLEEP" @@ -682,7 +674,7 @@ When the device exits the forced sleep mode, the event notification service is t **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.EXIT_FORCE_SLEEP" @@ -694,7 +686,7 @@ When the device is about to enter the hibernation mode, the event notification s **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.ENTER_HIBERNATE" @@ -706,7 +698,7 @@ When the device exits the hibernation mode, the event notification service is tr **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.EXIT_HIBERNATE" @@ -724,7 +716,7 @@ When the state of the device NFC adapter changes, the event notification service **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.nfc.action.ADAPTER_STATE_CHANGED" @@ -737,7 +729,7 @@ When the NFC RF field becomes available, the event notification service is trigg **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.nfc.action.RF_FIELD_ON_DETECTED" @@ -750,7 +742,7 @@ When the NFC RF field becomes unavailable, the event notification service is tri **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.nfc.action.RF_FIELD_OFF_DETECTED" @@ -765,7 +757,7 @@ State values: **0** indicates that the Wi-Fi is being disabled; **1** indicates **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.wifi.POWER_STATE" @@ -778,7 +770,7 @@ When a Wi-Fi access point is detected and proven to be available, the event noti **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.LOCATION +**Required permissions**: ohos.permission.LOCATION **Value**: "usual.event.wifi.SCAN_FINISHED" @@ -791,32 +783,32 @@ When the Wi-Fi access point state changes, the event notification service is tri **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.LOCATION +**Required permissions**: ohos.permission.LOCATION **Value**: "usual.event.wifi.SCAN_STATE" ### COMMON_EVENT_WIFI_RSSI_VALUE - Indicates that the Wi-Fi signal strength (RSSI) has changed. +Indicates that the Wi-Fi signal strength (RSSI) has changed. - When the Wi-Fi signal strength (RSSI) changes, the event notification service is triggered to publish this event. +When the Wi-Fi signal strength (RSSI) changes, the event notification service is triggered to publish this event. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.GET_WIFI_INFO +**Required permissions**: ohos.permission.GET_WIFI_INFO **Value**: "usual.event.wifi.RSSI_VALUE" ### COMMON_EVENT_WIFI_CONN_STATE - Indicates that the Wi-Fi connection state has changed. +Indicates that the Wi-Fi connection state has changed. - When the Wi-Fi connection state changes, the event notification service is triggered to publish this event. +When the Wi-Fi connection state changes, the event notification service is triggered to publish this event. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.wifi.CONN_STATE" @@ -831,7 +823,7 @@ State values: **2** indicates that the AP is being enabled, **3** indicates that **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.wifi.HOTSPOT_STATE" @@ -844,7 +836,7 @@ When a client joins the Wi-Fi hotspot of the current device, the event notificat **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.GET_WIFI_INFO +**Required permissions**: ohos.permission.GET_WIFI_INFO **Value**: "usual.event.wifi.WIFI_HS_STA_JOIN" @@ -858,7 +850,7 @@ When a client is disconnected from the Wi-Fi hotspot of the current device, the **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.GET_WIFI_INFO +**Required permissions**: ohos.permission.GET_WIFI_INFO **Value**: "usual.event.wifi.WIFI_HS_STA_LEAVE" @@ -867,12 +859,12 @@ When a client is disconnected from the Wi-Fi hotspot of the current device, the Indicates that the state of MPLINK (an enhanced Wi-Fi feature) has changed. -When the state of MPLINK (an enhanced Wi-Fi feature) changes, the event notification service is triggered to publish this event. +When the state of MPLINK changes, the event notification service is triggered to publish this event (not supported yet). **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.MPLINK_CHANGE_STATE +**Required permissions**: none **Value**: "usual.event.wifi.mplink.STATE_CHANGE" @@ -886,7 +878,7 @@ When the Wi-Fi P2P connection state changes, the event notification service is t **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION **Value**: "usual.event.wifi.p2p.CONN_STATE_CHANGE" @@ -901,7 +893,7 @@ State values: **2** indicates that the P2P is being enabled, **3** indicates tha **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.GET_WIFI_INFO +**Required permissions**: ohos.permission.GET_WIFI_INFO **Value**: "usual.event.wifi.p2p.STATE_CHANGE" @@ -914,7 +906,7 @@ When the state of the Wi-Fi P2P peer device changes, the event notification serv **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.GET_WIFI_INFO +**Required permissions**: ohos.permission.GET_WIFI_INFO **Value:** "usual.event.wifi.p2p.DEVICES_CHANGE" @@ -927,7 +919,7 @@ When the Wi-Fi P2P discovery state changes, the event notification service is tr **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.GET_WIFI_INFO +**Required permissions**: ohos.permission.GET_WIFI_INFO **Value**: "usual.event.wifi.p2p.PEER_DISCOVERY_STATE_CHANGE" @@ -940,7 +932,7 @@ When the state of the Wi-Fi P2P local device changes, the event notification ser **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.GET_WIFI_INFO +**Required permissions**: ohos.permission.GET_WIFI_INFO **Value**: "usual.event.wifi.p2p.CURRENT_DEVICE_CHANGE" @@ -953,7 +945,7 @@ When the Wi-Fi P2P group information changes, the event notification service is **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.GET_WIFI_INFO +**Required permissions**: ohos.permission.GET_WIFI_INFO **Value**: "usual.event.wifi.p2p.GROUP_STATE_CHANGED" @@ -970,7 +962,7 @@ When the browser hosting policy changes, the event notification service is trigg **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.MANAGED_BROWSER_POLICY_CHANGED" @@ -986,7 +978,7 @@ When the system language is set, the event notification service is triggered to **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: usual.event.LOCALE_CHANGED @@ -999,7 +991,7 @@ When the system language is set, the event notification service is triggered to Indicates that the network connection state has changed. -When the (Ethernet, Wi-Fi, or cellular) network connection state changes (to disconnected, connecting, or connected), the event notification service is triggered to publish this event. +When the (Ethernet, Wi-Fi, or cellular) network connection state changes (disconnected, connecting, or connected), the event notification service is triggered to publish this event. The following table lists the enumerated values and their corresponding connection status. | Value | Connection State | @@ -1011,7 +1003,7 @@ The following table lists the enumerated values and their corresponding connecti **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Atomic service API**: This API can be used in atomic services since API version 11. @@ -1026,7 +1018,7 @@ When the airplane mode is enabled or disabled, the event notification service is **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: usual.event.AIRPLANE_MODE @@ -1039,7 +1031,7 @@ When the configuration information of the system global proxy or HTTP proxy on v **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: usual.event.HTTP_PROXY_CHANGE @@ -1057,7 +1049,7 @@ When there is a change in the SIM card status of the device, the event notificat **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: usual.event.SIM_STATE_CHANGED @@ -1069,7 +1061,7 @@ When the call state of the device is updated, the event notification service is **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.GET_TELEPHONY_STATE (for system apps only) +**Required permissions**: ohos.permission.GET_TELEPHONY_STATE (for system apps only) **Value**: usual.event.CALL_STATE_CHANGED @@ -1081,7 +1073,7 @@ When the network state of the device is updated, the event notification service **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: usual.event.NETWORK_STATE_CHANGED @@ -1094,12 +1086,10 @@ When the signal information of the device is updated, the event notification ser **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: usual.event.SIGNAL_INFO_CHANGED -**System capability**: SystemCapability.Notification.CommonEvent - ## Store Kit @@ -1111,7 +1101,7 @@ When a user clicks **Agree** in a privacy dialog box, the event notification ser **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.PRIVACY_STATE_CHANGED" @@ -1128,7 +1118,7 @@ Below are reserved common events that are not supported yet. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.PACKAGE_FIRST_LAUNCH" @@ -1139,7 +1129,7 @@ Below are reserved common events that are not supported yet. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.PACKAGE_NEEDS_VERIFICATION" @@ -1150,7 +1140,7 @@ Below are reserved common events that are not supported yet. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.PACKAGE_VERIFIED" @@ -1160,7 +1150,7 @@ Below are reserved common events that are not supported yet. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.PACKAGE_REPLACED" @@ -1171,7 +1161,7 @@ Below are reserved common events that are not supported yet. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.MY_PACKAGE_REPLACED" @@ -1182,7 +1172,7 @@ Below are reserved common events that are not supported yet. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.PACKAGES_UNSUSPENDED" @@ -1193,7 +1183,7 @@ Below are reserved common events that are not supported yet. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.CLOSE_SYSTEM_DIALOGS" @@ -1203,7 +1193,7 @@ Below are reserved common events that are not supported yet. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.UID_REMOVED" @@ -1214,7 +1204,7 @@ Below are reserved common events that are not supported yet. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.EXTERNAL_APPLICATIONS_AVAILABLE" @@ -1225,7 +1215,7 @@ Below are reserved common events that are not supported yet. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.EXTERNAL_APPLICATIONS_UNAVAILABLE" @@ -1236,7 +1226,7 @@ Below are reserved common events that are not supported yet. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.CONFIGURATION_CHANGED" @@ -1245,7 +1235,7 @@ Below are reserved common events that are not supported yet. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "common.event.DRIVE_MODE" @@ -1254,7 +1244,7 @@ Below are reserved common events that are not supported yet. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "common.event.HOME_MODE" @@ -1263,7 +1253,7 @@ Below are reserved common events that are not supported yet. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "common.event.OFFICE_MODE" @@ -1273,7 +1263,7 @@ Below are reserved common events that are not supported yet. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.USER_STARTED" @@ -1284,7 +1274,7 @@ Below are reserved common events that are not supported yet. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.USER_BACKGROUND" @@ -1294,7 +1284,7 @@ Below are reserved common events that are not supported yet. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (for system applications only) +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (for system applications only) **Value**: "usual.event.USER_STARTING" @@ -1303,7 +1293,7 @@ Below are reserved common events that are not supported yet. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (for system applications only) +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (for system applications only) **Value**: "usual.event.USER_STOPPING" @@ -1313,7 +1303,7 @@ Below are reserved common events that are not supported yet. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.USER_STOPPED" @@ -1324,7 +1314,7 @@ Below are reserved common events that are not supported yet. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.STORAGE_MANAGER (for system applications only) +**Required permissions**: ohos.permission.STORAGE_MANAGER (for system applications only) **Value**: "usual.event.data.DISK_BAD_REMOVAL" @@ -1335,7 +1325,7 @@ Below are reserved common events that are not supported yet. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.STORAGE_MANAGER (for system applications only) +**Required permissions**: ohos.permission.STORAGE_MANAGER (for system applications only) **Value**: "usual.event.data.DISK_UNMOUNTABLE" @@ -1346,7 +1336,7 @@ Below are reserved common events that are not supported yet. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.STORAGE_MANAGER (for system applications only) +**Required permissions**: ohos.permission.STORAGE_MANAGER (for system applications only) **Value**: "usual.event.hardware.usb.action.USB_ACCESSORY_DETACHED" @@ -1356,7 +1346,7 @@ Below are reserved common events that are not supported yet. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.STORAGE_MANAGER (for system applications only) +**Required permissions**: ohos.permission.STORAGE_MANAGER (for system applications only) **Value**: "usual.event.data.DISK_REMOVED" @@ -1367,7 +1357,7 @@ Below are reserved common events that are not supported yet. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.STORAGE_MANAGER (for system applications only) +**Required permissions**: ohos.permission.STORAGE_MANAGER (for system applications only) **Value**: "usual.event.data.DISK_UNMOUNTED" @@ -1378,7 +1368,7 @@ Below are reserved common events that are not supported yet. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.STORAGE_MANAGER (for system applications only) +**Required permissions**: ohos.permission.STORAGE_MANAGER (for system applications only) **Value**: "usual.event.data.DISK_EJECT" @@ -1389,7 +1379,7 @@ Below are reserved common events that are not supported yet. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: usual.event.DATE_CHANGED @@ -1399,7 +1389,7 @@ Below are reserved common events that are not supported yet. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.hardware.usb.action.USB_ACCESSORY_ATTACHED" @@ -1410,7 +1400,7 @@ Below are reserved common events that are not supported yet. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.data.DISK_MOUNTED" @@ -1419,7 +1409,7 @@ Below are reserved common events that are not supported yet. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.USE_BLUETOOTH +**Required permissions**: ohos.permission.USE_BLUETOOTH **Value**: "usual.event.bluetooth.handsfree.ag.CONNECT_STATE_UPDATE" @@ -1428,7 +1418,7 @@ Below are reserved common events that are not supported yet. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.USE_BLUETOOTH +**Required permissions**: ohos.permission.USE_BLUETOOTH **Value**: "usual.event.bluetooth.handsfree.ag.CURRENT_DEVICE_UPDATE" @@ -1438,7 +1428,7 @@ Below are reserved common events that are not supported yet. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.USE_BLUETOOTH +**Required permissions**: ohos.permission.USE_BLUETOOTH **Value**: "usual.event.bluetooth.handsfree.ag.AUDIO_STATE_UPDATE" @@ -1448,7 +1438,7 @@ Below are reserved common events that are not supported yet. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.USE_BLUETOOTH +**Required permissions**: ohos.permission.USE_BLUETOOTH **Value**: "usual.event.bluetooth.a2dpsource.CONNECT_STATE_UPDATE" @@ -1458,7 +1448,7 @@ Below are reserved common events that are not supported yet. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.USE_BLUETOOTH +**Required permissions**: ohos.permission.USE_BLUETOOTH **Value**: "usual.event.bluetooth.a2dpsource.CURRENT_DEVICE_UPDATE" @@ -1467,7 +1457,7 @@ Below are reserved common events that are not supported yet. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.USE_BLUETOOTH +**Required permissions**: ohos.permission.USE_BLUETOOTH **Value**: "usual.event.bluetooth.a2dpsource.AVRCP_CONNECT_STATE_UPDATE" @@ -1476,7 +1466,7 @@ Below are reserved common events that are not supported yet. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.USE_BLUETOOTH +**Required permissions**: ohos.permission.USE_BLUETOOTH **Value**: "usual.event.bluetooth.a2dpsource.PLAYING_STATE_UPDATE" @@ -1485,7 +1475,7 @@ Below are reserved common events that are not supported yet. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.USE_BLUETOOTH +**Required permissions**: ohos.permission.USE_BLUETOOTH **Value**: "usual.event.bluetooth.a2dpsource.CODEC_VALUE_UPDATE" @@ -1496,7 +1486,7 @@ Below are reserved common events that are not supported yet. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.USER_FOREGROUND" @@ -1506,7 +1496,7 @@ Below are reserved common events that are not supported yet. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.LOCATION and ohos.permission.USE_BLUETOOTH +**Required permissions**: ohos.permission.LOCATION and ohos.permission.USE_BLUETOOTH **Value**: "usual.event.bluetooth.remotedevice.DISCOVERED" @@ -1516,7 +1506,7 @@ Below are reserved common events that are not supported yet. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.USE_BLUETOOTH +**Required permissions**: ohos.permission.USE_BLUETOOTH **Value**: "usual.event.bluetooth.remotedevice.CLASS_VALUE_UPDATE" @@ -1527,7 +1517,7 @@ Below are reserved common events that are not supported yet. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.bluetooth.remotedevice.ACL_CONNECTED" @@ -1537,7 +1527,7 @@ Below are reserved common events that are not supported yet. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.USE_BLUETOOTH +**Required permissions**: ohos.permission.USE_BLUETOOTH **Value**: "usual.event.bluetooth.remotedevice.ACL_DISCONNECTED" @@ -1548,7 +1538,7 @@ Below are reserved common events that are not supported yet. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.ACCESS_BLUETOOTH +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH **Value**: "usual.event.bluetooth.remotedevice.NAME_UPDATE" @@ -1558,7 +1548,7 @@ Below are reserved common events that are not supported yet. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.USE_BLUETOOTH +**Required permissions**: ohos.permission.USE_BLUETOOTH **Value**: "usual.event.bluetooth.remotedevice.PAIR_STATE" @@ -1567,7 +1557,7 @@ Below are reserved common events that are not supported yet. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.USE_BLUETOOTH +**Required permissions**: ohos.permission.USE_BLUETOOTH **Value**: "usual.event.bluetooth.remotedevice.BATTERY_VALUE_UPDATE" @@ -1577,7 +1567,7 @@ Below are reserved common events that are not supported yet. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.bluetooth.remotedevice.SDP_RESULT" @@ -1587,7 +1577,7 @@ Indicates the action of a common event about the UUID connection state of a remo **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.ACCESS_BLUETOOTH +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH **Value**: "usual.event.bluetooth.remotedevice.UUID_VALUE" @@ -1597,7 +1587,7 @@ Indicates the action of a common event about the UUID connection state of a remo **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.DISCOVER_BLUETOOTH +**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH **Value**: "usual.event.bluetooth.remotedevice.PAIRING_REQ" @@ -1607,7 +1597,7 @@ Indicates the action of a common event about the UUID connection state of a remo **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.bluetooth.remotedevice.PAIRING_CANCEL" @@ -1617,7 +1607,7 @@ Indicates the action of a common event about the UUID connection state of a remo **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.bluetooth.remotedevice.CONNECT_REQ" @@ -1627,7 +1617,7 @@ Indicates the action of a common event about the UUID connection state of a remo **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.bluetooth.remotedevice.CONNECT_REPLY" @@ -1637,7 +1627,7 @@ Indicates the action of a common event about the UUID connection state of a remo **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.bluetooth.remotedevice.CONNECT_CANCEL" @@ -1647,7 +1637,7 @@ Indicates the action of a common event about the UUID connection state of a remo **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.bluetooth.handsfreeunit.CONNECT_STATE_UPDATE" @@ -1657,7 +1647,7 @@ Indicates the action of a common event about the UUID connection state of a remo **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.bluetooth.handsfreeunit.AUDIO_STATE_UPDATE" @@ -1667,7 +1657,7 @@ Indicates the action of a common event about the UUID connection state of a remo **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.bluetooth.handsfreeunit.AG_COMMON_EVENT" @@ -1677,7 +1667,7 @@ Indicates the action of a common event about the UUID connection state of a remo **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.bluetooth.handsfreeunit.AG_CALL_STATE_UPDATE" @@ -1687,7 +1677,7 @@ Indicates the common event that the state of a Bluetooth adapter has been change **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.bluetooth.host.STATE_UPDATE" @@ -1697,7 +1687,7 @@ Indicates the common event that the state of a Bluetooth adapter has been change **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.bluetooth.host.REQ_DISCOVERABLE" @@ -1707,7 +1697,7 @@ Indicates the common event that the state of a Bluetooth adapter has been change **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.USE_BLUETOOTH +**Required permissions**: ohos.permission.USE_BLUETOOTH **Value**: "usual.event.bluetooth.host.REQ_ENABLE" @@ -1716,7 +1706,7 @@ Indicates the common event that the state of a Bluetooth adapter has been change **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.USE_BLUETOOTH +**Required permissions**: ohos.permission.USE_BLUETOOTH **Value**: "usual.event.bluetooth.host.REQ_DISABLE" @@ -1726,7 +1716,7 @@ Indicates the common event that the state of a Bluetooth adapter has been change **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.USE_BLUETOOTH +**Required permissions**: ohos.permission.USE_BLUETOOTH **Value**: "usual.event.bluetooth.host.SCAN_MODE_UPDATE" @@ -1736,7 +1726,7 @@ Indicates the common event that the Bluetooth scanning has been started on the d **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.ACCESS_BLUETOOTH +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH **Value**: "usual.event.bluetooth.host.DISCOVERY_STARTED" @@ -1746,7 +1736,7 @@ Indicates the common event that the Bluetooth scanning is finished on the device **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.ACCESS_BLUETOOTH +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH **Value**: "usual.event.bluetooth.host.DISCOVERY_FINISHED" @@ -1756,7 +1746,7 @@ Indicates the common event that the Bluetooth adapter name of the device has cha **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.ACCESS_BLUETOOTH +**Required permissions**: ohos.permission.ACCESS_BLUETOOTH **Value**: "usual.event.bluetooth.host.NAME_UPDATE" @@ -1766,7 +1756,7 @@ Indicates the common event that the Bluetooth adapter name of the device has cha **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.USE_BLUETOOTH +**Required permissions**: ohos.permission.USE_BLUETOOTH **Value**: "usual.event.bluetooth.a2dpsink.CONNECT_STATE_UPDATE" @@ -1775,7 +1765,7 @@ Indicates the common event that the Bluetooth adapter name of the device has cha **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.USE_BLUETOOTH +**Required permissions**: ohos.permission.USE_BLUETOOTH **Value**: "usual.event.bluetooth.a2dpsink.PLAYING_STATE_UPDATE" @@ -1785,7 +1775,7 @@ Indicates the common event that the Bluetooth adapter name of the device has cha **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.USE_BLUETOOTH +**Required permissions**: ohos.permission.USE_BLUETOOTH **Value**: "usual.event.bluetooth.a2dpsink.AUDIO_STATE_UPDATE" @@ -1795,7 +1785,7 @@ Indicates the common event that the Bluetooth adapter name of the device has cha **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.LISTEN_BUNDLE_CHANGE +**Required permissions**: ohos.permission.LISTEN_BUNDLE_CHANGE **Value**: "usual.event.ABILITY_ADDED" @@ -1805,7 +1795,7 @@ Indicates the common event that the Bluetooth adapter name of the device has cha **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.LISTEN_BUNDLE_CHANGE +**Required permissions**: ohos.permission.LISTEN_BUNDLE_CHANGE **Value**: "usual.event.ABILITY_REMOVED" @@ -1814,7 +1804,7 @@ Indicates the common event that the Bluetooth adapter name of the device has cha **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.LISTEN_BUNDLE_CHANGE +**Required permissions**: ohos.permission.LISTEN_BUNDLE_CHANGE **Value**: "usual.event.ABILITY_UPDATED" @@ -1824,7 +1814,7 @@ Indicates the common event that the Bluetooth adapter name of the device has cha **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.location.MODE_STATE_CHANGED" @@ -1834,7 +1824,7 @@ Indicates the common event that the Bluetooth adapter name of the device has cha **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "common.event.IVI_SLEEP" @@ -1845,7 +1835,7 @@ Indicates the common event that the Bluetooth adapter name of the device has cha **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "common.event.IVI_PAUSE" @@ -1854,7 +1844,7 @@ Indicates the common event that the Bluetooth adapter name of the device has cha **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "common.event.IVI_STANDBY" @@ -1864,7 +1854,7 @@ Indicates the common event that the Bluetooth adapter name of the device has cha **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "common.event.IVI_LASTMODE_SAVE" @@ -1874,7 +1864,7 @@ Indicates the common event that the Bluetooth adapter name of the device has cha **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "common.event.IVI_VOLTAGE_ABNORMAL" @@ -1885,7 +1875,7 @@ Indicates the common event that the Bluetooth adapter name of the device has cha **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "common.event.IVI_HIGH_TEMPERATURE" @@ -1895,7 +1885,7 @@ Indicates the common event that the Bluetooth adapter name of the device has cha **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "common.event.IVI_EXTREME_TEMPERATURE" @@ -1905,7 +1895,7 @@ Indicates the common event that the Bluetooth adapter name of the device has cha **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "common.event.IVI_TEMPERATURE_ABNORMAL" @@ -1915,7 +1905,7 @@ Indicates the common event that the Bluetooth adapter name of the device has cha **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "common.event.IVI_VOLTAGE_RECOVERY" @@ -1925,7 +1915,7 @@ Indicates the common event that the Bluetooth adapter name of the device has cha **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "common.event.IVI_TEMPERATURE_RECOVERY" @@ -1935,7 +1925,7 @@ Indicates the common event that the Bluetooth adapter name of the device has cha **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "common.event.IVI_ACTIVE" @@ -1944,7 +1934,7 @@ Indicates the common event that the Bluetooth adapter name of the device has cha **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.GET_APP_ACCOUNTS (for system applications only) +**Required permissions**: ohos.permission.GET_APP_ACCOUNTS (for system applications only) **Value**: "usual.event.data.VISIBLE_ACCOUNTS_UPDATED" @@ -1954,7 +1944,7 @@ Indicates the common event that the Bluetooth adapter name of the device has cha **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (for system applications only) +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (for system applications only) **Value**: "usual.event.data.ACCOUNT_DELETED" @@ -1963,7 +1953,7 @@ Indicates the common event that the Bluetooth adapter name of the device has cha **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: ohos.permission.RECEIVER_STARTUP_COMPLETED (for system applications only) +**Required permissions**: ohos.permission.RECEIVER_STARTUP_COMPLETED (for system applications only) **Value**: "usual.event.data.FOUNDATION_READY" @@ -1972,7 +1962,8 @@ Indicates the common event of that the SPN information had changed. **System capability**: SystemCapability.Notification.CommonEvent -**Required subscriber permissions**: none +**Required permissions**: none **Value**: "usual.event.SPN_INFO_CHANGED" + diff --git a/en/application-dev/reference/apis-basic-services-kit/errorcode-CommonEventService.md b/en/application-dev/reference/apis-basic-services-kit/errorcode-CommonEventService.md index 8e14eee830d..e57934f75a8 100644 --- a/en/application-dev/reference/apis-basic-services-kit/errorcode-CommonEventService.md +++ b/en/application-dev/reference/apis-basic-services-kit/errorcode-CommonEventService.md @@ -7,126 +7,180 @@ ## 1500001 Want Action Is Null **Error Message** + The action field in the want parameter is null. **Description** + This error code is reported when the **Action** attribute in the **want** object is null for the event to send. **Possible Causes** + The **Action** attribute in the **want** object is null for the event to send. **Solution** + Make sure the **Action** attribute in the **want** object is not null. ## 1500002 Failed to Send Common Events from a Sandbox Application **Error Message** + A sandbox application cannot send common events. **Description** + This error code is reported when an attempt is made to send a common event from a sandbox application. **Possible Causes** + Common events from a sandbox application are blocked. **Solution** + Check whether the application used to send a common event is a sandbox application. If so, switch to another application. ## 1500003 Event Sending Frequency Is Too High **Error Message** -Too many common events are sent in a short period of time. + +The common event sending frequency too high. **Description** + This error code is reported when the application sends common events too frequently. **Possible Causes** + The number of common events sent by the application in a given time frame has reached the maximum. **Solution** + Do not send common events too frequently. ## 1500004 Failed to Send System Common Events **Error Message** + A third-party application cannot send system common events. **Description** + This error code is reported when the application cannot send system common events. **Possible Causes** + The application is not a system application or system service. **Solution** + Make sure the application to send system common events is a system application or system service. ## 1500005 Subscriber Not Found **Error Message** + The subscriber is not found. **Description** + This error code is reported when the subscriber cannot be found. **Possible Causes** + The subscriber is deleted. **Solution** + Check whether the subscription has already been canceled. If the subscription has been canceled, the subscriber is deleted. ## 1500006 Invalid User ID **Error Message** + Invalid userId. **Description** + This error code is reported when the user ID is invalid. **Possible Causes** + The user ID is different from the system user ID, or the application is not a system application or system service. **Solution** + 1. Make sure the current user ID is the same as the system user ID. 2. Make sure the application is a system application or system service. ## 1500007 Failed to Send a Request Through IPC **Error Message** + Failed to send the message to the common event service. **Description** + This error code is reported when the attempt to send a request through IPC fails. **Possible Causes** + The connection object fails to be created. **Solution** + Do not set up connections frequently. Try again later. ## 1500008 Failed to Initialize the Common Event Service **Error Message** + Failed to initialize the common event service. **Description** + This error code is reported when an error occurs on the server. **Possible Causes** + A service exception occurs when the server processes data. **Solution** + Try again later. ## 1500009 Failed to Obtain System Parameters **Error Message** + Failed to obtain system parameters. **Description** + This error code is reported when an exception occurs in the system during service processing, for example, when the current system time fails to be obtained. **Possible Causes** + A system fault occurs. **Solution** + Try again later. + +## 1500010 The Number of Subscribers Exceeds the Upper Limit + +**Error Message** + +The number of subscribers exceeds the upper limit. + +**Description** + +This error code is reported when the number of subscribers exceeds the upper limit. + +**Possible Causes** + +The subscriber is not unregistered in a timely manner when it is no longer used. + +**Solution** + +Unregister the subscriber that is no longer used in the application. If the subscriber has been unregistered, try again later. diff --git a/en/application-dev/reference/apis-basic-services-kit/errorcode-account.md b/en/application-dev/reference/apis-basic-services-kit/errorcode-account.md index 0e55ced5518..821ce824b80 100644 --- a/en/application-dev/reference/apis-basic-services-kit/errorcode-account.md +++ b/en/application-dev/reference/apis-basic-services-kit/errorcode-account.md @@ -4,7 +4,7 @@ > > This topic describes only module-specific error codes. For details about universal error codes, see [Universal Error Codes](../errorcode-universal.md). -The following includes the error codes for system accounts, distributed accounts, and app accounts. +The following includes the error codes for system accounts, distributed accounts, and application accounts. ## 12300001 System Service Abnormal @@ -14,7 +14,7 @@ The system service works abnormally. **Possible Causes** - + 1. The account management service cannot start properly. 2. The IPC object for account management cannot be obtained. 3. The services on which the account management depends cannot start properly, or the IPC object on which the account management depends cannot be obtained. @@ -37,7 +37,7 @@ Invalid parameter. **Possible Causes** - + 1. The user name is empty. 2. The user name of the system account exceeds 1024 characters. 3. The user name of the distributed account exceeds 256 characters. @@ -75,7 +75,7 @@ The account does not exist. **Possible Causes** - + 1. The account to query, activate, or delete is not created. 2. The account to query, activate, or delete has been deleted. 3. The constraint, user name, or profile photo is set for an account that has been deleted. @@ -100,7 +100,7 @@ The account already exists. **Possible Causes** - + The account to create already exists. **Solution** @@ -115,7 +115,7 @@ Multi-user is not supported. **Possible Causes** - + The device does not support multiple users. **Solution** @@ -130,7 +130,6 @@ The account type is not supported. **Possible Causes** - The device does not support the account type. **Solution** @@ -145,7 +144,6 @@ The number of accounts has reached the upper limit. **Possible Causes** - The number of system accounts or application accounts has reached 1000. **Solution** @@ -160,7 +158,7 @@ The specified account is restricted. **Possible Causes** - + 1. The account to delete is a reserved account of the system. 2. The constraint source type to query belongs to a reserved account. 3. The ID of the account to create is 0 to 100. @@ -177,7 +175,7 @@ The account has been activated. **Possible Causes** - + The account to activate is already activated. **Solution** @@ -192,9 +190,9 @@ The account service does not respond. **Possible Causes** - + 1. Repeated requests, such as the requests for activating an account or applying the same settings, are submitted in a short period of time. -2. When the number of authentication sessions for app accounts reaches 256, new authentication requests cannot be processed. +2. When the number of authentication sessions for application accounts reaches 256, new authentication requests cannot be processed. **Solution** @@ -208,7 +206,7 @@ The event listener has been registered. **Possible Causes** - + The listener to register has been registered with the system already. **Solution** @@ -223,7 +221,7 @@ The event listener has not been registered. **Possible Causes** - + The event listener to unregister has not been registered. **Solution** @@ -238,7 +236,7 @@ Network exception. **Possible Causes** - + 1. The device is not connected to the network. 2. The network connection is abnormal. 3. The app does not have the network access permission. @@ -301,7 +299,7 @@ The credential is incorrect. **Possible Causes** - + 1. An incorrect password is entered. 2. The biological feature does not match the feature enrolled. 3. The token is invalid. @@ -318,7 +316,7 @@ The credential does not exist. **Possible Causes** - + 1. The credential to authenticate has not been enrolled. 2. The credential to query has not been enrolled. 3. The credential to delete has not been enrolled. @@ -335,7 +333,7 @@ The credential inputer already exists. **Possible Causes** - + The PIN inputer has been registered and cannot be registered again before deregistration. **Solution** @@ -350,7 +348,7 @@ The credential inputer is not found. **Possible Causes** - + No credential inputer is registered when a credential is authenticated, added or modified. **Solution** @@ -365,7 +363,7 @@ The trust level is not supported. **Possible Causes** - + The trust level passed in is not supported. **Solution** @@ -380,7 +378,7 @@ The authentication type is not supported. **Possible Causes** - + The authentication type passed in is not supported. **Solution** @@ -395,7 +393,7 @@ The authentication type does not exist. **Possible Causes** - + The specified authentication type does not exist when a token is queried or deleted. **Solution** @@ -410,8 +408,6 @@ The authentication session does not exist. **Possible Causes** - - The session callback to query does not exist. **Solution** @@ -426,7 +422,6 @@ The authentication, enrollment, or update operation is canceled. **Possible Causes** - The user cancels the authentication. The user canceled the credential enrollment. The user canceled the update during the credential enrollment process. @@ -443,7 +438,6 @@ The authentication is locked. **Possible Causes** - The number of authentication type errors exceeds the limit. **Solution** @@ -458,7 +452,6 @@ The authentication time out. **Possible Causes** - 1. The authentication or credential enrollment of a system account takes more than three minutes. 2. The authentication service does not respond in time due to network problems. @@ -475,7 +468,6 @@ The authentication service is busy. **Possible Causes** - The total number of system accounts being authenticated exceeds 5. The authentication service of the third-party app does not respond. @@ -491,7 +483,6 @@ The account authentication service does not exist. **Possible Causes** - For application accounts: 1. When an authentication is requested, the app does not support the authentication service. 2. When an account is added implicitly, the app does not support the authentication service. @@ -511,7 +502,6 @@ The account authentication service works abnormally. **Possible Causes** - 1. An unknown error occurs in the identity authentication service. 2. The app authenticator does not comply with specifications. @@ -572,7 +562,7 @@ The application does not exist. **Possible Causes** - + 1. The target app does not exist when the app permission is set. 2. The target app does not exist when the app permission is authorized. @@ -588,7 +578,6 @@ The custom data does not exist. **Possible Causes** - The key does not exist when you query the custom data of the account. **Solution** @@ -603,7 +592,6 @@ The number of custom data records reaches the upper limit. **Possible Causes** - The number of custom data records of the target account has reached 512. **Solution** @@ -618,7 +606,6 @@ The number of tokens reaches the upper limit. **Possible Causes** - The number of tokens of the target account has reached 1024. **Solution** @@ -633,9 +620,8 @@ The size of the authorization list reaches the upper limit. **Possible Causes** - The number of bundles in the authorization list has reached 1024. **Solution** -1. Revoke authorization from the apps that do not require the authorization and try again. +Revoke authorization from the applications that do not require the authorization and try again. diff --git a/en/application-dev/reference/apis-basic-services-kit/errorcode-battery-info.md b/en/application-dev/reference/apis-basic-services-kit/errorcode-battery-info.md index 8b635d93eda..acfd43ee189 100644 --- a/en/application-dev/reference/apis-basic-services-kit/errorcode-battery-info.md +++ b/en/application-dev/reference/apis-basic-services-kit/errorcode-battery-info.md @@ -4,7 +4,7 @@ > > This topic describes only module-specific error codes. For details about universal error codes, see [Universal Error Codes](../errorcode-universal.md). -## 4600101 Service Connection Failure +## 5100101 Service Connection Failure **Error Message** @@ -30,4 +30,4 @@ Check whether the system services are running properly. > hdc shell hidumper -ls ``` -2. Check whether **Battery-info** is included in the system service list. +2. Check whether **BatteryService** is present on the system service list. diff --git a/en/application-dev/reference/apis-basic-services-kit/errorcode-pasteboard.md b/en/application-dev/reference/apis-basic-services-kit/errorcode-pasteboard.md index fb6ec24b7a4..684186f39d6 100644 --- a/en/application-dev/reference/apis-basic-services-kit/errorcode-pasteboard.md +++ b/en/application-dev/reference/apis-basic-services-kit/errorcode-pasteboard.md @@ -87,7 +87,7 @@ The data is read-only and cannot be copied. **Error Message** -Request timed out. +Excessive processing time for internal data. **Description** @@ -123,7 +123,7 @@ Delete the existing settings and then set the new one. **Error Message** -Copy file failed. +Invalid destUri or file system error. **Description** @@ -178,7 +178,7 @@ Check whether the pasting is successful. If yes, ignore this error; otherwise, c **Error Message** -Get Data failed. +System error occurred during paste execution. **Description** diff --git a/en/application-dev/reference/apis-basic-services-kit/errorcode-request.md b/en/application-dev/reference/apis-basic-services-kit/errorcode-request.md index 7de03516b0b..80e22b4868a 100644 --- a/en/application-dev/reference/apis-basic-services-kit/errorcode-request.md +++ b/en/application-dev/reference/apis-basic-services-kit/errorcode-request.md @@ -8,11 +8,11 @@ **Error Message** -File operation error. +Invalid file or file system error. **Description** -This error code is reported when a file operation error occurs in invoking the **uploadFile** or **downloadFile** API. +This error code is reported when the **uploadFile** or **downloadFile** API fails to be invoked to upload or download a file. **Possible Causes** @@ -26,7 +26,7 @@ Make sure you have the required permission on the target files. **Error Message** -Bad file path. +File path not supported or invalid. **Description** @@ -66,7 +66,7 @@ Other error. **Description** -This error code is reported when a special error occurs in invoking the **uploadFile** or **downloadFile** API. +This error code is reported when other error occurs in invoking the **uploadFile** or **downloadFile** API. **Possible Causes** @@ -103,7 +103,7 @@ The application fails to create a background task (resources are preempted by fo **Error Message** -Task mode error. +Operation with wrong task mode. **Description** @@ -123,11 +123,11 @@ The application attempts to create a foreground task when it is not running in t **Error Message** -Task not found. +Task removed or not found. **Description** -This error code is reported when the task is not found. +This error code is reported when the task does not exist. **Possible Causes** @@ -141,15 +141,15 @@ The task to remove or query does not exist. 3. Verify the task ID and try again. -## 21900007 Operation Not Supported in Current State +## 21900007 Operation Not Supported by the Task State **Error Message** -Task state error. +Operation with wrong task state. **Description** -This error code is reported when the operation performed is not supported. +This error code is reported when an operation is not supported by the task state. **Possible Causes** @@ -165,9 +165,9 @@ This error code is reported when the operation performed is not supported. **Solution** -1. Query the task status. +1. Query the task state. -2. Perform the operation supported by the current task status. +2. Perform the operation supported by the current task state. ## 21900008 Task Group Not Found or Deleted @@ -187,4 +187,4 @@ This error code is reported when a task group does not exist or has been deleted **Solution** -1. Check whether the target group has been deleted. +Check whether the target group has been deleted. diff --git a/en/application-dev/reference/apis-basic-services-kit/errorcode-time.md b/en/application-dev/reference/apis-basic-services-kit/errorcode-time.md index 1ae2a32cbe4..a96cc9317cb 100644 --- a/en/application-dev/reference/apis-basic-services-kit/errorcode-time.md +++ b/en/application-dev/reference/apis-basic-services-kit/errorcode-time.md @@ -20,9 +20,9 @@ The system is not running properly due to a common kernel error, such as a memor **Solution** -Make sure the memory is sufficient. +Make sure that the memory is sufficient. -## 13000001 Network or Operating System Error +## 13000001 Network or OS Error **Error Message** @@ -30,11 +30,11 @@ Network connection error or OS error. **Description** -This error code is reported when the network or operating system error occurs. +This error code is reported when the network or OS error occurs. **Possible Cause** -The network or operating system is not running properly due to a system error, such as network connection failure or socket creation failure. +The network or OS is not running properly due to a system error, such as network connection failure or socket creation failure. **Solution** @@ -45,15 +45,15 @@ Make sure the network is connected and the system resources are sufficient. **Error Message** -NTP update failed. +The local NTP time of the system is invalid. **Description** -This error code is reported when the NTP time is not updated. +This error code is reported when the NTP time is invalid. **Possible Cause** -Fail to update the NTP time before obtain it. +The local NTP time has not been updated and becomes invalid. **Solution** diff --git a/en/application-dev/reference/apis-basic-services-kit/errorcode-usb.md b/en/application-dev/reference/apis-basic-services-kit/errorcode-usb.md index 9925ea27708..8d9acacbfbd 100644 --- a/en/application-dev/reference/apis-basic-services-kit/errorcode-usb.md +++ b/en/application-dev/reference/apis-basic-services-kit/errorcode-usb.md @@ -8,7 +8,7 @@ **Error Message** -Permission denied. Call requestRight or requestAccessoryRight to get the permission or USBDevicePipe access right first. +Access right denied. Call requestRight to get the USBDevicePipe access right first. **Description** @@ -18,7 +18,7 @@ This error code is reported if a certain API of the USB module is called but the The permission to access the USB device is not granted. -**Procedure** +**Solution** Call **requestRight** to request for the permission to access the USB device. @@ -36,7 +36,7 @@ This error code is reported if HDC is disabled by the system. The USB debugging permission is not granted. -**Procedure** +**Solution** Apply for the USB debugging permission. @@ -48,13 +48,13 @@ Unsupported operation. The current device does not support port role switching. **Description** -This error code is reported if port role switching is not supported. The device does not support port role switching. +This error code is reported if the port role is switched. **Possible Causes** The port role is incorrect. -**Procedure** +**Solution** Use the correct port role. @@ -72,7 +72,7 @@ This error code is reported if the service is abnormal. No accessory is inserted. -**Procedure** +**Solution** Insert the accessory. @@ -86,7 +86,7 @@ Database operation exception. This error code is reported if the database operation is abnormal. -**Procedure** +**Solution** Call the API again. @@ -98,13 +98,13 @@ Unsupported operation. The function is not supported. **Description** -This error code is reported if the requested USB device function is not supported. +This error code is reported if the USB device function is switched. **Possible Causes** The USB device function is not supported. -**Procedure** +**Solution** Use the correct USB device function. @@ -118,7 +118,7 @@ The target USBAccessory not matched. This error code is reported if the target USB accessory does not match the device. -**Procedure** +**Solution** Call **getAccessoryList** to obtain the accessory list and use a matched USB accessory to try again. @@ -132,7 +132,7 @@ Failed to open the native accessory node. This error code is reported if the attempt to open the native accessory node fails. -**Procedure** +**Solution** Call the API again. @@ -146,7 +146,7 @@ Cannot reopen the accessory. This error code is reported if an accessory is opened repeatedly. -**Procedure** +**Solution** The accessory has been opened. Continue to perform subsequent operations. @@ -154,13 +154,19 @@ The accessory has been opened. Continue to perform subsequent operations. **Error Message** -Resource busy. +Resource busy. Possible causes: 1. The transfer has already been submitted. 2. The interface is claimed by another program or driver. **Description** This error code is reported if the requested resource is in use. -**Procedure** +**Possible Causes** + +1. The transmission task has been submitted. + +2. The API is occupied by another program or driver. + +**Solution** Check whether [usbManager.claimInterface](js-apis-usbManager.md#usbmanagerclaiminterface) is successfully called. @@ -174,7 +180,7 @@ No such device (it may have been disconnected). This error code is reported if the device cannot be identified. -**Procedure** +**Solution** Check whether the device type is correct and whether the device is successfully connected. @@ -182,13 +188,17 @@ Check whether the device type is correct and whether the device is successfully **Error Message** -Insufficient memory. +Insufficient memory. Possible causes: 1. Memory allocation failed. **Description** This error code is reported if no memory is available when being requested. The maximum data size is 1 KB for a single transfer. -**Procedure** +**Possible Causes** + +The memory usage is too high to allocate sufficient space to the current task. + +**Solution** Clear memory in a timely manner. @@ -196,13 +206,13 @@ Clear memory in a timely manner. **Error Message** -Other USB error. Possible causes:Unrecognized discard error code. +Other USB error. Possible causes: Unrecognized discard error code. **Description** This error code is reported if an unknown error occurs. -**Procedure** +**Solution** Correct the error by referring to the related documentation, and try again. @@ -210,13 +220,13 @@ Correct the error by referring to the related documentation, and try again. **Error Message** -If the transfer is not in progress, already complete, or already cancelled. +The transfer is not in progress, or is already complete or cancelled. **Description** This error code is reported if the current data transfer has been canceled or completed. -**Procedure** +**Solution** Initiate a new data transfer request. @@ -228,17 +238,38 @@ Transmission I/O error. **Description** -This error code is reported if the read/write operation fails because the I/O channel is abnormal. +This error code is reported when the read/write operation fails due to the abnormal I/O channel. -**Procedure** +**Solution** Try again. +## 14400013 Parameter Validity Check Failed + +**Error Message** + +The USBDevicePipe validity check failed. Possible causes: 1. The input parameters fail the validation check. 2. The call chain used to obtain the input parameters is not reasonable. + +**Description** + +This error code is reported if the parameter validity check fails. + + **Possible Causes** + +1. The validity check of the input parameter fails. + +2. The input parameter call chain is improper. + +**Solution** + +Use a proper call chain to obtain the input parameter. + + ## 31400001 Serial Port Service Error **Error Message** -serial service exception. +Serial port management exception. **Description** @@ -248,7 +279,7 @@ This error code is reported if the serial port service is abnormal. The process exits due to a program exception. -**Procedure** +**Solution** Check whether the device is connected, and obtain the correct serial port number from the serial port list. @@ -256,7 +287,7 @@ Check whether the device is connected, and obtain the correct serial port number **Error Message** -no access right to serial device, call requestSerialRight first. +Access denied. Call requestSerialRight to request user authorization first. **Description** @@ -266,7 +297,7 @@ This error code is reported if you do not have the permission to access the seri You have not applied for the permission to access the serial port device. -**Procedure** +**Solution** Call **requestSerialRight** to apply for the access permission. @@ -274,7 +305,7 @@ Call **requestSerialRight** to apply for the access permission. **Error Message** -portId not exist. +PortId does not exist. **Description** @@ -284,7 +315,7 @@ This error code is reported if the port number does not exist. The original port number becomes invalid because the device connection is abnormal. -**Procedure** +**Solution** Remove and insert the device, and try again. @@ -292,17 +323,17 @@ Remove and insert the device, and try again. **Error Message** -device is using by other application. +The serial port device is occupied. **Description** -This error code is reported if the device is being used by another application. +This error code is reported if the serial port device is occupied. **Possible Causes** The serial port device is enabled repeatedly. -**Procedure** +**Solution** Remove and insert the device, and try again. @@ -310,35 +341,35 @@ Remove and insert the device, and try again. **Error Message** -device is not open, call open first. +The serial port device is not opened. Call the open API first. **Description** -This error code is reported if the device is not opened. +This error code is reported if the serial port device is not opened. **Possible Causes** A device has not been opened. -**Procedure** +**Solution** Call the **Open** API to open the device before performing subsequent operations. -## 31400006 Transmission Timeout +## 31400006 Data Transfer Timeout **Error Message** -transfer timeout. +Data transfer timed out. **Description** -This error code is reported if the data transfer times out. +This error code is reported if data transfer times out. **Possible Causes** The peer end does not send data. -**Procedure** +**Solution** Check whether the peer device initiates data transfer. @@ -346,7 +377,7 @@ Check whether the peer device initiates data transfer. **Error Message** -I/O exception. +I/O exception.Possible causes: 1. The transfer was canceled. 2. The device offered more data than allowed. **Description** @@ -354,8 +385,10 @@ This error code is reported if an I/O exception occurs. **Possible Causes** -The amount of received data in a single transfer exceeds the configured buffer size. +1. The transfer task is canceled abnormally. + +2. The amount of received data in a single transfer exceeds the buffer size limit. -**Procedure** +**Solution** Adjust the buffer size properly, and perform data transfer again. diff --git a/en/application-dev/reference/apis-basic-services-kit/errorcode-zlib.md b/en/application-dev/reference/apis-basic-services-kit/errorcode-zlib.md index bccce506d08..54cf287d2ff 100644 --- a/en/application-dev/reference/apis-basic-services-kit/errorcode-zlib.md +++ b/en/application-dev/reference/apis-basic-services-kit/errorcode-zlib.md @@ -82,14 +82,14 @@ This error code is reported when the input file path, file descriptor, or file a **Solution** -1. Check whether the **.gz** file path or file descriptor is correct. If a **.gz** file is created, ensure that the file access is in compression mode (such as **w** or **wb**). +1. Check whether the .gz file path or file descriptor is correct. If a .gz file is created, ensure that the file access is in compression mode (such as **w** or **wb**). 2. Check whether the file access mode is **w**, **wb**, **r**, **rb**, **a**, and **ab**. ## 17800004 Compressed or Decompressed Flow Error **Error Message** -ZStream error. +Compression or decompression stream error, which may be caused by an initialization error in the zlib stream structure or a modified structure. **Description** @@ -98,20 +98,20 @@ This error code is reported when an error occurs in compression or decompression **Possible Causes** 1. When the **deflate** or **inflate** API is called, the **deflateInit** or **inflateInit** API is not used to initialize the compression or decompression stream. -2. When the **gzsetparams**, **gzclose**, or **gzflush** API is called, the input refresh mode is incorrect. When the API for opening a **.gz** file is called, the input file access mode is incorrect. +2. When the **gzsetparams**, **gzclose**, or **gzflush** API is called, the input refresh mode is incorrect. When the API for opening a .gz file is called, the input file access mode is incorrect. **Solution** 1. Before calling the **deflate** or **inflate** API, use the **deflateInit** or **inflateInit** API to initialize the compression or decompression stream. -2. Check whether the API for opening the **.gz** file is not called or fails to be called. -3. Check whether the input access mode matches the API when the API for opening the **.gz** file is called. For example, **gzprintf** is a compression API. When the API for opening a **.gz** file is called, the input access mode must be the compression mode (such as **w** or **wb**). +2. Check whether the API for opening the .gz file is not called or fails to be called. +3. Check whether the input access mode matches the API when the API for opening the .gz file is called. For example, **gzprintf** is a compression API. When the API for opening a .gz file is called, the input access mode must be the compression mode (such as **w** or **wb**). 4. Check whether the input enum parameter is correct. ## 17800005 Incorrect Input Data **Error Message** -Data error. +The input data is incorrect. For example, the data does not conform to the zlib compression format, the compressed data is corrupted, or the data is not compressed. **Description** @@ -147,7 +147,7 @@ Check the whether the **gzsetparams** API is called and pass in the correct comp **Error Message** -Buffer error. +The input buffer is incorrect, and the output buffer is too small to accommodate the compressed or decompressed data. **Description** @@ -171,20 +171,20 @@ Internal structure error. **Description** -This error code is reported when the input parameter is incorrect when the **gzputc**, **gzwrite**, or **gzread** API is called, or when the input file access mode is incorrect when the API for opening the **.gz** file is called. +This error code is reported when the input parameter is incorrect when the **gzputc**, **gzwrite**, or **gzread** API is called, or when the input file access mode is incorrect when the API for opening the .gz file is called. **Possible Causes** -1. The API for opening the **.gz** file is not called or fails to be called. -2. When the API for opening the **.gz** file is called, the input file access mode is incorrect. +1. The API for opening the .gz file is not called or fails to be called. +2. When the API for opening the .gz file is called, the input file access mode is incorrect. 3. When the **gzwrite** API is called, the length of the input uncompressed byte is 0. 4. When the **gzfwrite** or **gzfread** API is called, the size or number of input data blocks is 0. 5. When the **gzprintf** API is called, the input format descriptor and plain text are empty strings. 6. When the **gzgets** API is called, the input **ArrayBuffer** is empty. -7. When the **gzgetc** API is called, the **.gz** file is empty. +7. When the **gzgetc** API is called, the .gz file is empty. **Solution** -1. Check whether the API for opening the **.gz** file is not called or fails to be called. -2. Check whether the input access mode matches the API when the API for opening the **.gz** file is called. For example, **gzgetc** is a decompression API, so the input access mode should be decompression mode (such **r** or **rb**). +1. Check whether the API for opening the .gz file is not called or fails to be called. +2. Check whether the input access mode matches the API when the API for opening the .gz file is called. For example, **gzgetc** is a decompression API, so the input access mode should be decompression mode (such **r** or **rb**). 3. Check whether the input parameter is correct. diff --git a/en/application-dev/reference/apis-basic-services-kit/js-apis-app-ability-PrintExtensionAbility-sys.md b/en/application-dev/reference/apis-basic-services-kit/js-apis-app-ability-PrintExtensionAbility-sys.md index 14b56d4d39a..0da2263adc2 100644 --- a/en/application-dev/reference/apis-basic-services-kit/js-apis-app-ability-PrintExtensionAbility-sys.md +++ b/en/application-dev/reference/apis-basic-services-kit/js-apis-app-ability-PrintExtensionAbility-sys.md @@ -37,8 +37,8 @@ For details about the error codes, see [Error Codes of the Print Service](./erro **Example** ```ts -import PrintExtensionAbility from '@ohos.app.ability.PrintExtensionAbility'; -import print from '@ohos.print'; +import { PrintExtensionAbility } from '@kit.BasicServicesKit'; +import { print } from '@kit.BasicServicesKit'; export default class HWPrintExtension extends PrintExtensionAbility { onStartPrintJob(jobInfo: print.PrintJob): void { @@ -72,8 +72,8 @@ For details about the error codes, see [Error Codes of the Print Service](./erro **Example** ```ts -import PrintExtensionAbility from '@ohos.app.ability.PrintExtensionAbility'; -import print from '@ohos.print'; +import { PrintExtensionAbility } from '@kit.BasicServicesKit'; +import { print } from '@kit.BasicServicesKit'; export default class HWPrintExtension extends PrintExtensionAbility { onCancelPrintJob(jobInfo: print.PrintJob): void { @@ -112,8 +112,8 @@ For details about the error codes, see [Error Codes of the Print Service](./erro **Example** ```ts -import PrintExtensionAbility from '@ohos.app.ability.PrintExtensionAbility'; -import print from '@ohos.print'; +import { PrintExtensionAbility } from '@kit.BasicServicesKit'; +import { print } from '@kit.BasicServicesKit'; export default class HWPrintExtension extends PrintExtensionAbility { onRequestPrinterCapability(printerId: number): print.PrinterCapability { @@ -158,8 +158,8 @@ For details about the error codes, see [Error Codes of the Print Service](./erro **Example** ```ts -import PrintExtensionAbility from '@ohos.app.ability.PrintExtensionAbility'; -import print from '@ohos.print'; +import { PrintExtensionAbility } from '@kit.BasicServicesKit'; +import { print } from '@kit.BasicServicesKit'; export default class HWPrintExtension extends PrintExtensionAbility { onRequestPreview(jobInfo: print.PrintJob): string { diff --git a/en/application-dev/reference/apis-basic-services-kit/js-apis-app-ability-PrintExtensionAbility.md b/en/application-dev/reference/apis-basic-services-kit/js-apis-app-ability-PrintExtensionAbility.md index d8a98bd9e7d..49b7a127fde 100644 --- a/en/application-dev/reference/apis-basic-services-kit/js-apis-app-ability-PrintExtensionAbility.md +++ b/en/application-dev/reference/apis-basic-services-kit/js-apis-app-ability-PrintExtensionAbility.md @@ -28,7 +28,7 @@ Called to initialize the print extension when the system connects to the extensi **Example** ```ts -import PrintExtensionAbility from '@ohos.app.ability.PrintExtensionAbility'; +import { PrintExtensionAbility } from '@kit.BasicServicesKit'; import Want from '@ohos.app.ability.Want'; export default class HWPrintExtension extends PrintExtensionAbility { @@ -50,7 +50,7 @@ Called when an attempt to discover printers starts. **Example** ```ts -import PrintExtensionAbility from '@ohos.app.ability.PrintExtensionAbility'; +import { PrintExtensionAbility } from '@kit.BasicServicesKit'; export default class HWPrintExtension extends PrintExtensionAbility { onStartDiscoverPrinter(): void { @@ -71,7 +71,7 @@ Called when the attempt to discover printers stops. **Example** ```ts -import PrintExtensionAbility from '@ohos.app.ability.PrintExtensionAbility'; +import { PrintExtensionAbility } from '@kit.BasicServicesKit'; export default class HWPrintExtension extends PrintExtensionAbility { onStopDiscoverPrinter(): void { @@ -97,7 +97,7 @@ Called when the device connects to the specified printer. **Example** ```ts -import PrintExtensionAbility from '@ohos.app.ability.PrintExtensionAbility'; +import { PrintExtensionAbility } from '@kit.BasicServicesKit'; export default class HWPrintExtension extends PrintExtensionAbility { onConnectPrinter(printerId: number): void { @@ -123,7 +123,7 @@ Called when the device disconnects from the specified printer. **Example** ```ts -import PrintExtensionAbility from '@ohos.app.ability.PrintExtensionAbility'; +import { PrintExtensionAbility } from '@kit.BasicServicesKit'; export default class HWPrintExtension extends PrintExtensionAbility { onDisconnectPrinter(printerId: number): void { @@ -144,7 +144,7 @@ Called when the print extension ability is stopped. **Example** ```ts -import PrintExtensionAbility from '@ohos.app.ability.PrintExtensionAbility'; +import { PrintExtensionAbility } from '@kit.BasicServicesKit'; export default class HWPrintExtension extends PrintExtensionAbility { onDestroy(): void { diff --git a/en/application-dev/reference/apis-basic-services-kit/js-apis-appAccount.md b/en/application-dev/reference/apis-basic-services-kit/js-apis-appAccount.md index 7d2ceda1e35..1c488b2c86e 100644 --- a/en/application-dev/reference/apis-basic-services-kit/js-apis-appAccount.md +++ b/en/application-dev/reference/apis-basic-services-kit/js-apis-appAccount.md @@ -69,10 +69,14 @@ Creates an application account with the given name. This API uses an asynchronou try { appAccountManager.createAccount('WangWu', (err: BusinessError) => { - console.log('createAccount err: ' + JSON.stringify(err)); + if (err) { + console.error('createAccount code: ' + JSON.stringify(err)); + } else { + console.log('createAccount successful.'); + } }); } catch (err) { - console.log('createAccount err: ' + JSON.stringify(err)); + console.error('createAccount err: ' + JSON.stringify(err)); } ``` @@ -115,13 +119,13 @@ Creates an application account with custom data. This API uses an asynchronous c try { appAccountManager.createAccount('LiSi', options, (err: BusinessError) => { if (err) { - console.log('createAccount failed, error: ' + JSON.stringify(err)); + console.error('createAccount failed, error: ' + JSON.stringify(err)); } else { console.log('createAccount successfully'); } }); } catch(err) { - console.log('createAccount exception: ' + JSON.stringify(err)); + console.error('createAccount exception: ' + JSON.stringify(err)); } ``` @@ -170,10 +174,10 @@ Creates an application account with custom data. This API uses a promise to retu appAccountManager.createAccount('LiSi', options).then(() => { console.log('createAccount successfully'); }).catch((err: BusinessError) => { - console.log('createAccount failed, error: ' + JSON.stringify(err)); + console.error('createAccount failed, error: ' + JSON.stringify(err)); }); } catch(err) { - console.log('createAccount exception: ' + JSON.stringify(err)); + console.error('createAccount exception: ' + JSON.stringify(err)); } ``` @@ -210,34 +214,41 @@ Creates an application account implicitly based on the specified account owner. import { BusinessError } from '@kit.BasicServicesKit'; import { Want, common } from '@kit.AbilityKit'; - let context = getContext(this) as common.UIAbilityContext; // UIAbilityContext + @Entry + @Component + struct Index { + context = this.getUIContext().getHostContext() as common.UIAbilityContext; // UIAbilityContext - function onResultCallback(code: number, result?: appAccount.AuthResult): void { - console.log('resultCode: ' + code); - console.log('result: ' + JSON.stringify(result)); - } + onResultCallback(code: number, result?: appAccount.AuthResult): void { + console.log('resultCode: ' + code); + console.log('result: ' + JSON.stringify(result)); + } - function onRequestRedirectedCallback(request: Want): void { - let wantInfo: Want = { - deviceId: '', - bundleName: 'com.example.accountjsdemo', - action: 'ohos.want.action.viewData', - entities: ['entity.system.default'], + onRequestRedirectedCallback(request: Want): void { + let wantInfo: Want = { + deviceId: '', + bundleName: 'com.example.accountjsdemo', + action: 'ohos.want.action.viewData', + entities: ['entity.system.default'], + } + this.context.startAbility(wantInfo).then(() => { + console.log('startAbility successfully'); + }).catch((err: BusinessError) => { + console.error('startAbility err: ' + JSON.stringify(err)); + }) } - context.startAbility(wantInfo).then(() => { - console.log('startAbility successfully'); - }).catch((err: BusinessError) => { - console.log('startAbility err: ' + JSON.stringify(err)); - }) - } - try { - appAccountManager.createAccountImplicitly('com.example.accountjsdemo', { - onResult: onResultCallback, - onRequestRedirected: onRequestRedirectedCallback - }); - } catch (err) { - console.log('createAccountImplicitly exception: ' + JSON.stringify(err)); + aboutToAppear(): void { + try { + appAccountManager.createAccountImplicitly('com.example.accountjsdemo', { + onResult: this.onResultCallback, + onRequestRedirected: this.onRequestRedirectedCallback + }); + } catch (err) { + console.error('createAccountImplicitly exception: ' + JSON.stringify(err)); + } + } + build() {} } ``` @@ -275,38 +286,45 @@ Creates an application account implicitly based on the specified account owner a import { BusinessError } from '@kit.BasicServicesKit'; import { Want, common } from '@kit.AbilityKit'; - let context = getContext(this) as common.UIAbilityContext; // UIAbilityContext + @Entry + @Component + struct Index { + context = this.getUIContext().getHostContext() as common.UIAbilityContext; // UIAbilityContext - function onResultCallback(code: number, result?: appAccount.AuthResult): void { - console.log('resultCode: ' + code); - console.log('result: ' + JSON.stringify(result)); - } + onResultCallback(code: number, result?: appAccount.AuthResult): void { + console.log('resultCode: ' + code); + console.log('result: ' + JSON.stringify(result)); + } - function onRequestRedirectedCallback(request: Want): void { - let wantInfo: Want = { - deviceId: '', - bundleName: 'com.example.accountjsdemo', - action: 'ohos.want.action.viewData', - entities: ['entity.system.default'], + onRequestRedirectedCallback(request: Want): void { + let wantInfo: Want = { + deviceId: '', + bundleName: 'com.example.accountjsdemo', + action: 'ohos.want.action.viewData', + entities: ['entity.system.default'], + } + this.context.startAbility(wantInfo).then(() => { + console.log('startAbility successfully'); + }).catch((err: BusinessError) => { + console.error('startAbility err: ' + JSON.stringify(err)); + }) } - context.startAbility(wantInfo).then(() => { - console.log('startAbility successfully'); - }).catch((err: BusinessError) => { - console.log('startAbility err: ' + JSON.stringify(err)); - }) - } - let options: appAccount.CreateAccountImplicitlyOptions = { - authType: 'getSocialData', - requiredLabels: [ 'student' ] - }; - try { - appAccountManager.createAccountImplicitly('com.example.accountjsdemo', options, { - onResult: onResultCallback, - onRequestRedirected: onRequestRedirectedCallback - }); - } catch (err) { - console.log('createAccountImplicitly exception: ' + JSON.stringify(err)); + aboutToAppear(): void { + let options: appAccount.CreateAccountImplicitlyOptions = { + authType: 'getSocialData', + requiredLabels: [ 'student' ] + }; + try { + appAccountManager.createAccountImplicitly('com.example.accountjsdemo', options, { + onResult: this.onResultCallback, + onRequestRedirected: this.onRequestRedirectedCallback + }); + } catch (err) { + console.error('createAccountImplicitly exception: ' + JSON.stringify(err)); + } + } + build() {} } ``` @@ -342,13 +360,13 @@ Removes an application account. This API uses an asynchronous callback to return try { appAccountManager.removeAccount('ZhaoLiu', (err: BusinessError) => { if (err) { - console.log('removeAccount failed, error: ' + JSON.stringify(err)); + console.error('removeAccount failed, error: ' + JSON.stringify(err)); } else { console.log('removeAccount successfully'); } }); } catch(err) { - console.log('removeAccount exception: ' + JSON.stringify(err)); + console.error('removeAccount exception: ' + JSON.stringify(err)); } ``` @@ -390,10 +408,10 @@ Removes an application account. This API uses a promise to return the result. appAccountManager.removeAccount('Lisi').then(() => { console.log('removeAccount successfully'); }).catch((err: BusinessError) => { - console.log('removeAccount failed, error: ' + JSON.stringify(err)); + console.error('removeAccount failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log('removeAccount exception: ' + JSON.stringify(err)); + console.error('removeAccount exception: ' + JSON.stringify(err)); } ``` @@ -432,13 +450,13 @@ Sets the access to the data of an account for an application. This API uses an a try { appAccountManager.setAppAccess('ZhangSan', 'com.example.accountjsdemo', true, (err: BusinessError) => { if (err) { - console.log('setAppAccess failed: ' + JSON.stringify(err)); + console.error('setAppAccess failed: ' + JSON.stringify(err)); } else { console.log('setAppAccess successfully'); } }); } catch (err) { - console.log('setAppAccess exception: ' + JSON.stringify(err)); + console.error('setAppAccess exception: ' + JSON.stringify(err)); } ``` @@ -483,10 +501,10 @@ Sets the access to the data of an account for an application. This API uses a pr appAccountManager.setAppAccess('ZhangSan', 'com.example.accountjsdemo', true).then(() => { console.log('setAppAccess successfully'); }).catch((err: BusinessError) => { - console.log('setAppAccess failed: ' + JSON.stringify(err)); + console.error('setAppAccess failed: ' + JSON.stringify(err)); }); } catch (err) { - console.log('setAppAccess exception: ' + JSON.stringify(err)); + console.error('setAppAccess exception: ' + JSON.stringify(err)); } ``` @@ -524,13 +542,13 @@ Checks whether an application can access the data of an account. This API uses a appAccountManager.checkAppAccess('ZhangSan', 'com.example.accountjsdemo', (err: BusinessError, isAccessible: boolean) => { if (err) { - console.log('checkAppAccess failed, error: ' + JSON.stringify(err)); + console.error('checkAppAccess failed, error: ' + JSON.stringify(err)); } else { console.log('checkAppAccess successfully'); } }); } catch (err) { - console.log('checkAppAccess exception: ' + JSON.stringify(err)); + console.error('checkAppAccess exception: ' + JSON.stringify(err)); } ``` @@ -573,10 +591,10 @@ Checks whether an application can access the data of an account. This API uses a appAccountManager.checkAppAccess('ZhangSan', 'com.example.accountjsdemo').then((isAccessible: boolean) => { console.log('checkAppAccess successfully, isAccessible: ' + isAccessible); }).catch((err: BusinessError) => { - console.log('checkAppAccess failed, error: ' + JSON.stringify(err)); + console.error('checkAppAccess failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log('checkAppAccess exception: ' + JSON.stringify(err)); + console.error('checkAppAccess exception: ' + JSON.stringify(err)); } ``` @@ -615,10 +633,10 @@ Sets data synchronization for an application account. This API uses an asynchron try { appAccountManager.setDataSyncEnabled('ZhangSan', true, (err: BusinessError) => { - console.log('setDataSyncEnabled err: ' + JSON.stringify(err)); + console.error('setDataSyncEnabled err: ' + JSON.stringify(err)); }); } catch (err) { - console.log('setDataSyncEnabled err: ' + JSON.stringify(err)); + console.error('setDataSyncEnabled err: ' + JSON.stringify(err)); } ``` @@ -664,10 +682,10 @@ Sets data synchronization for an application account. This API uses a promise to appAccountManager .setDataSyncEnabled('ZhangSan', true).then(() => { console.log('setDataSyncEnabled Success'); }).catch((err: BusinessError) => { - console.log('setDataSyncEnabled err: ' + JSON.stringify(err)); + console.error('setDataSyncEnabled err: ' + JSON.stringify(err)); }); } catch (err) { - console.log('setDataSyncEnabled err: ' + JSON.stringify(err)); + console.error('setDataSyncEnabled err: ' + JSON.stringify(err)); } ``` @@ -706,13 +724,13 @@ Checks whether data synchronization is enabled for an application account. This try { appAccountManager.checkDataSyncEnabled('ZhangSan', (err: BusinessError, isEnabled: boolean) => { if (err) { - console.log('checkDataSyncEnabled failed, err: ' + JSON.stringify(err)); + console.error('checkDataSyncEnabled failed, err: ' + JSON.stringify(err)); } else { console.log('checkDataSyncEnabled successfully, isEnabled: ' + isEnabled); } }); } catch (err) { - console.log('checkDataSyncEnabled err: ' + JSON.stringify(err)); + console.error('checkDataSyncEnabled err: ' + JSON.stringify(err)); } ``` @@ -757,10 +775,10 @@ Checks whether data synchronization is enabled for an application account. This appAccountManager.checkDataSyncEnabled('ZhangSan').then((isEnabled: boolean) => { console.log('checkDataSyncEnabled successfully, isEnabled: ' + isEnabled); }).catch((err: BusinessError) => { - console.log('checkDataSyncEnabled failed, err: ' + JSON.stringify(err)); + console.error('checkDataSyncEnabled failed, err: ' + JSON.stringify(err)); }); } catch (err) { - console.log('checkDataSyncEnabled err: ' + JSON.stringify(err)); + console.error('checkDataSyncEnabled err: ' + JSON.stringify(err)); } ``` @@ -798,13 +816,13 @@ Sets a credential for an application account. This API uses an asynchronous call try { appAccountManager.setCredential('ZhangSan', 'PIN_SIX', 'xxxxxx', (err: BusinessError) => { if (err) { - console.log('setCredential failed, error: ' + JSON.stringify(err)); + console.error('setCredential failed, error: ' + JSON.stringify(err)); } else { console.log('setCredential successfully'); } }); } catch (err) { - console.log('setCredential exception: ' + JSON.stringify(err)); + console.error('setCredential exception: ' + JSON.stringify(err)); } ``` @@ -848,10 +866,10 @@ Sets a credential for an application account. This API uses a promise to return appAccountManager.setCredential('ZhangSan', 'PIN_SIX', 'xxxxxx').then(() => { console.log('setCredential successfully'); }).catch((err: BusinessError) => { - console.log('setCredential failed, error: ' + JSON.stringify(err)); + console.error('setCredential failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log('setCredential exception: ' + JSON.stringify(err)); + console.error('setCredential exception: ' + JSON.stringify(err)); } ``` @@ -889,13 +907,13 @@ Obtains the credential of an application account. This API uses an asynchronous try { appAccountManager.getCredential('ZhangSan', 'PIN_SIX', (err: BusinessError, result: string) => { if (err) { - console.log('getCredential failed, error: ' + JSON.stringify(err)); + console.error('getCredential failed, error: ' + JSON.stringify(err)); } else { console.log('getCredential successfully, result: ' + result); } }); } catch (err) { - console.log('getCredential err: ' + JSON.stringify(err)); + console.error('getCredential err: ' + JSON.stringify(err)); } ``` @@ -939,10 +957,10 @@ Obtains the credential of an application account. This API uses a promise to ret appAccountManager.getCredential('ZhangSan', 'PIN_SIX').then((credential: string) => { console.log('getCredential successfully, credential: ' + credential); }).catch((err: BusinessError) => { - console.log('getCredential failed, error: ' + JSON.stringify(err)); + console.error('getCredential failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log('getCredential exception: ' + JSON.stringify(err)); + console.error('getCredential exception: ' + JSON.stringify(err)); } ``` @@ -981,13 +999,13 @@ Sets custom data for an application account. This API uses an asynchronous callb try { appAccountManager.setCustomData('ZhangSan', 'age', '12', (err: BusinessError) => { if (err) { - console.log('setCustomData failed, error: ' + JSON.stringify(err)); + console.error('setCustomData failed, error: ' + JSON.stringify(err)); } else { console.log('setCustomData successfully'); } }); } catch (err) { - console.log('setCustomData exception: ' + JSON.stringify(err)); + console.error('setCustomData exception: ' + JSON.stringify(err)); } ``` @@ -1032,10 +1050,10 @@ Sets custom data for an application account. This API uses a promise to return t appAccountManager.setCustomData('ZhangSan', 'age', '12').then(() => { console.log('setCustomData successfully'); }).catch((err: BusinessError) => { - console.log('setCustomData failed, error: ' + JSON.stringify(err)); + console.error('setCustomData failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log('setCustomData exception: ' + JSON.stringify(err)); + console.error('setCustomData exception: ' + JSON.stringify(err)); } ``` @@ -1073,13 +1091,13 @@ Obtains the custom data of an application account based on the specified key. Th try { appAccountManager.getCustomData('ZhangSan', 'age', (err: BusinessError, data: string) => { if (err) { - console.log('getCustomData failed, error: ' + err); + console.error('getCustomData failed, error: ' + err); } else { console.log('getCustomData successfully, data: ' + data); } }); } catch (err) { - console.log('getCustomData exception: ' + JSON.stringify(err)); + console.error('getCustomData exception: ' + JSON.stringify(err)); } ``` @@ -1123,10 +1141,10 @@ Obtains the custom data of an application account based on the specified key. Th appAccountManager.getCustomData('ZhangSan', 'age').then((data: string) => { console.log('getCustomData successfully, data: ' + data); }).catch((err: BusinessError) => { - console.log('getCustomData failed, error: ' + JSON.stringify(err)); + console.error('getCustomData failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log('getCustomData exception: ' + JSON.stringify(err)); + console.error('getCustomData exception: ' + JSON.stringify(err)); } ``` @@ -1201,13 +1219,13 @@ Obtains information about all accessible application accounts. This API uses an try { appAccountManager.getAllAccounts((err: BusinessError, data: appAccount.AppAccountInfo[]) => { if (err) { - console.debug('getAllAccounts failed, error: ' + JSON.stringify(err)); + console.error('getAllAccounts failed, error: ' + JSON.stringify(err)); } else { console.debug('getAllAccounts successfully'); } }); } catch (err) { - console.debug('getAllAccounts exception: ' + JSON.stringify(err)); + console.error('getAllAccounts exception: ' + JSON.stringify(err)); } ``` @@ -1240,10 +1258,10 @@ Obtains information about all accessible application accounts. This API uses a p appAccountManager.getAllAccounts().then((data: appAccount.AppAccountInfo[]) => { console.debug('getAllAccounts successfully'); }).catch((err: BusinessError) => { - console.debug('getAllAccounts failed, error: ' + JSON.stringify(err)); + console.error('getAllAccounts failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.debug('getAllAccounts exception: ' + JSON.stringify(err)); + console.error('getAllAccounts exception: ' + JSON.stringify(err)); } ``` @@ -1279,13 +1297,13 @@ Obtains the application accounts that can be accessed by the invoker based on th appAccountManager.getAccountsByOwner('com.example.accountjsdemo2', (err: BusinessError, data: appAccount.AppAccountInfo[]) => { if (err) { - console.debug('getAccountsByOwner failed, error:' + JSON.stringify(err)); + console.error('getAccountsByOwner failed, error:' + JSON.stringify(err)); } else { console.debug('getAccountsByOwner successfully, data:' + JSON.stringify(data)); } }); } catch (err) { - console.debug('getAccountsByOwner exception:' + JSON.stringify(err)); + console.error('getAccountsByOwner exception:' + JSON.stringify(err)); } ``` @@ -1327,10 +1345,10 @@ Obtains the application accounts that can be accessed by the invoker based on th data: appAccount.AppAccountInfo[]) => { console.debug('getAccountsByOwner successfully, data: ' + JSON.stringify(data)); }).catch((err: BusinessError) => { - console.debug('getAccountsByOwner failed, error: ' + JSON.stringify(err)); + console.error('getAccountsByOwner failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.debug('getAccountsByOwner exception: ' + JSON.stringify(err)); + console.error('getAccountsByOwner exception: ' + JSON.stringify(err)); } ``` @@ -1347,7 +1365,7 @@ Subscribes to account information changes of apps. | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ------------------------------ | | type | 'accountChange' | Yes | Event type to subscribe to. The value is **'accountChange'**. An event will be reported when the account information of the target application changes.| -| owners | Array<string> | Yes | application bundle names of the account. | +| owners | Array<string> | Yes | Application bundle names of the account. | | callback | Callback<Array<[AppAccountInfo](#appaccountinfo)>> | Yes | Callback registered to return the list of changed application accounts. | **Error codes** @@ -1448,34 +1466,41 @@ Authenticates an application account. This API uses an asynchronous callback to import { BusinessError } from '@kit.BasicServicesKit'; import { Want, common } from '@kit.AbilityKit'; - let context = getContext(this) as common.UIAbilityContext; // UIAbilityContext + @Entry + @Component + struct Index { + context = this.getUIContext().getHostContext() as common.UIAbilityContext; // UIAbilityContext - function onResultCallback(code: number, authResult?: appAccount.AuthResult): void { - console.log('resultCode: ' + code); - console.log('authResult: ' + JSON.stringify(authResult)); - } + onResultCallback(code: number, authResult?: appAccount.AuthResult): void { + console.log('resultCode: ' + code); + console.log('authResult: ' + JSON.stringify(authResult)); + } - function onRequestRedirectedCallback(request: Want): void { - let wantInfo: Want = { - deviceId: '', - bundleName: 'com.example.accountjsdemo', - action: 'ohos.want.action.viewData', - entities: ['entity.system.default'], + onRequestRedirectedCallback(request: Want): void { + let wantInfo: Want = { + deviceId: '', + bundleName: 'com.example.accountjsdemo', + action: 'ohos.want.action.viewData', + entities: ['entity.system.default'], + } + this.context.startAbility(wantInfo).then(() => { + console.log('startAbility successfully'); + }).catch((err: BusinessError) => { + console.error('startAbility err: ' + JSON.stringify(err)); + }) } - context.startAbility(wantInfo).then(() => { - console.log('startAbility successfully'); - }).catch((err: BusinessError) => { - console.log('startAbility err: ' + JSON.stringify(err)); - }) - } - try { - appAccountManager.auth('LiSi', 'com.example.accountjsdemo', 'getSocialData', { - onResult: onResultCallback, - onRequestRedirected: onRequestRedirectedCallback - }); - } catch (err) { - console.log('auth exception: ' + JSON.stringify(err)); + aboutToAppear(): void { + try { + appAccountManager.auth('LiSi', 'com.example.accountjsdemo', 'getSocialData', { + onResult: this.onResultCallback, + onRequestRedirected: this.onRequestRedirectedCallback + }); + } catch (err) { + console.error('auth exception: ' + JSON.stringify(err)); + } + } + build() {} } ``` @@ -1515,37 +1540,44 @@ Authenticates an application account. This API uses an asynchronous callback to import { BusinessError } from '@kit.BasicServicesKit'; import { Want, common } from '@kit.AbilityKit'; - let context = getContext(this) as common.UIAbilityContext; // UIAbilityContext + @Entry + @Component + struct Index { + context = this.getUIContext().getHostContext() as common.UIAbilityContext; // UIAbilityContext - function onResultCallback(code: number, authResult?: appAccount.AuthResult): void { - console.log('resultCode: ' + code); - console.log('authResult: ' + JSON.stringify(authResult)); - } + onResultCallback(code: number, authResult?: appAccount.AuthResult): void { + console.log('resultCode: ' + code); + console.log('authResult: ' + JSON.stringify(authResult)); + } - function onRequestRedirectedCallback(request: Want): void { - let wantInfo: Want = { - deviceId: '', - bundleName: 'com.example.accountjsdemo', - action: 'ohos.want.action.viewData', - entities: ['entity.system.default'], + onRequestRedirectedCallback(request: Want): void { + let wantInfo: Want = { + deviceId: '', + bundleName: 'com.example.accountjsdemo', + action: 'ohos.want.action.viewData', + entities: ['entity.system.default'], + } + this.context.startAbility(wantInfo).then(() => { + console.log('startAbility successfully'); + }).catch((err: BusinessError) => { + console.error('startAbility err: ' + JSON.stringify(err)); + }) } - context.startAbility(wantInfo).then(() => { - console.log('startAbility successfully'); - }).catch((err: BusinessError) => { - console.log('startAbility err: ' + JSON.stringify(err)); - }) - } - let options: Record = { - 'password': 'xxxx', - }; - try { - appAccountManager.auth('LiSi', 'com.example.accountjsdemo', 'getSocialData', options, { - onResult: onResultCallback, - onRequestRedirected: onRequestRedirectedCallback - }); - } catch (err) { - console.log('auth exception: ' + JSON.stringify(err)); + aboutToAppear(): void { + let options: Record = { + 'password': 'xxxx', + }; + try { + appAccountManager.auth('LiSi', 'com.example.accountjsdemo', 'getSocialData', options, { + onResult: this.onResultCallback, + onRequestRedirected: this.onRequestRedirectedCallback + }); + } catch (err) { + console.error('auth exception: ' + JSON.stringify(err)); + } + } + build() {} } ``` @@ -1585,13 +1617,13 @@ Obtains the authorization token of the specified authentication type for an appl appAccountManager.getAuthToken('LiSi', 'com.example.accountjsdemo', 'getSocialData', (err: BusinessError, token: string) => { if (err) { - console.log('getAuthToken failed, error: ' + JSON.stringify(err)); + console.error('getAuthToken failed, error: ' + JSON.stringify(err)); } else { console.log('getAuthToken successfully, token: ' + token); } }); } catch (err) { - console.log('getAuthToken exception: ' + JSON.stringify(err)); + console.error('getAuthToken exception: ' + JSON.stringify(err)); } ``` @@ -1636,10 +1668,10 @@ Obtains the authorization token of the specified authentication type for an appl appAccountManager.getAuthToken('LiSi', 'com.example.accountjsdemo', 'getSocialData').then((token: string) => { console.log('getAuthToken successfully, token: ' + token); }).catch((err: BusinessError) => { - console.log('getAuthToken failed, error: ' + JSON.stringify(err)); + console.error('getAuthToken failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log('getAuthToken exception: ' + JSON.stringify(err)); + console.error('getAuthToken exception: ' + JSON.stringify(err)); } ``` @@ -1678,13 +1710,13 @@ Sets an authorization token of the specific authentication type for an applicati try { appAccountManager.setAuthToken('LiSi', 'getSocialData', 'xxxx', (err: BusinessError) => { if (err) { - console.log('setAuthToken failed, error: ' + JSON.stringify(err)); + console.error('setAuthToken failed, error: ' + JSON.stringify(err)); } else { console.log('setAuthToken successfully'); } }); } catch (err) { - console.log('setAuthToken exception: ' + JSON.stringify(err)); + console.error('setAuthToken exception: ' + JSON.stringify(err)); } ``` @@ -1729,10 +1761,10 @@ Sets an authorization token of the specific authentication type for an applicati appAccountManager.setAuthToken('LiSi', 'getSocialData', 'xxxx').then(() => { console.log('setAuthToken successfully'); }).catch((err: BusinessError) => { - console.log('setAuthToken failed, error: ' + JSON.stringify(err)); + console.error('setAuthToken failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log('setAuthToken exception: ' + JSON.stringify(err)); + console.error('setAuthToken exception: ' + JSON.stringify(err)); } ``` @@ -1773,13 +1805,13 @@ Deletes the authorization token of the specified authentication type for an appl appAccountManager.deleteAuthToken('LiSi', 'com.example.accountjsdemo', 'getSocialData', 'xxxxx', (err: BusinessError) => { if (err) { - console.log('deleteAuthToken failed, error: ' + JSON.stringify(err)); + console.error('deleteAuthToken failed, error: ' + JSON.stringify(err)); } else { console.log('deleteAuthToken successfully'); } }); } catch (err) { - console.log('deleteAuthToken exception: ' + JSON.stringify(err)); + console.error('deleteAuthToken exception: ' + JSON.stringify(err)); } ``` @@ -1825,10 +1857,10 @@ Deletes the authorization token of the specified authentication type for an appl appAccountManager.deleteAuthToken('LiSi', 'com.example.accountjsdemo', 'getSocialData', 'xxxxx').then(() => { console.log('deleteAuthToken successfully'); }).catch((err: BusinessError) => { - console.log('deleteAuthToken failed, error: ' + JSON.stringify(err)); + console.error('deleteAuthToken failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log('deleteAuthToken exception: ' + JSON.stringify(err)); + console.error('deleteAuthToken exception: ' + JSON.stringify(err)); } ``` @@ -1870,13 +1902,13 @@ Sets the visibility of an authorization token to an application. This API uses a appAccountManager.setAuthTokenVisibility('LiSi', 'getSocialData', 'com.example.accountjsdemo', true, (err: BusinessError) => { if (err) { - console.log('setAuthTokenVisibility failed, error: ' + JSON.stringify(err)); + console.error('setAuthTokenVisibility failed, error: ' + JSON.stringify(err)); } else { console.log('setAuthTokenVisibility successfully'); } }); } catch (err) { - console.log('setAuthTokenVisibility exception: ' + JSON.stringify(err)); + console.error('setAuthTokenVisibility exception: ' + JSON.stringify(err)); } ``` @@ -1923,10 +1955,10 @@ Sets the visibility of an authorization token to an application. This API uses a appAccountManager.setAuthTokenVisibility('LiSi', 'getSocialData', 'com.example.accountjsdemo', true).then(() => { console.log('setAuthTokenVisibility successfully'); }).catch((err: BusinessError) => { - console.log('setAuthTokenVisibility failed, error: ' + JSON.stringify(err)); + console.error('setAuthTokenVisibility failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log('setAuthTokenVisibility exception: ' + JSON.stringify(err)); + console.error('setAuthTokenVisibility exception: ' + JSON.stringify(err)); } ``` @@ -1966,13 +1998,13 @@ Checks the visibility of an authorization token of the specified authentication appAccountManager.checkAuthTokenVisibility('LiSi', 'getSocialData', 'com.example.accountjsdemo', (err: BusinessError, isVisible: boolean) => { if (err) { - console.log('checkAuthTokenVisibility failed, error: ' + JSON.stringify(err)); + console.error('checkAuthTokenVisibility failed, error: ' + JSON.stringify(err)); } else { console.log('checkAuthTokenVisibility successfully, isVisible: ' + isVisible); } }); } catch (err) { - console.log('checkAuthTokenVisibility exception: ' + JSON.stringify(err)); + console.error('checkAuthTokenVisibility exception: ' + JSON.stringify(err)); } ``` @@ -2018,10 +2050,10 @@ Checks the visibility of an authorization token of the specified authentication isVisible: boolean) => { console.log('checkAuthTokenVisibility successfully, isVisible: ' + isVisible); }).catch((err: BusinessError) => { - console.log('checkAuthTokenVisibility failed, error: ' + JSON.stringify(err)); + console.error('checkAuthTokenVisibility failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log('checkAuthTokenVisibility exception: ' + JSON.stringify(err)); + console.error('checkAuthTokenVisibility exception: ' + JSON.stringify(err)); } ``` @@ -2059,13 +2091,13 @@ Obtains all tokens visible to the invoker for an application account. This API u appAccountManager.getAllAuthTokens('LiSi', 'com.example.accountjsdemo', (err: BusinessError, tokenArr: appAccount.AuthTokenInfo[]) => { if (err) { - console.log('getAllAuthTokens failed, error: ' + JSON.stringify(err)); + console.error('getAllAuthTokens failed, error: ' + JSON.stringify(err)); } else { console.log('getAllAuthTokens successfully, tokenArr: ' + tokenArr); } }); } catch (err) { - console.log('getAllAuthTokens exception: ' + JSON.stringify(err)); + console.error('getAllAuthTokens exception: ' + JSON.stringify(err)); } ``` @@ -2109,10 +2141,10 @@ Obtains all tokens visible to the invoker for an application account. This API u tokenArr: appAccount.AuthTokenInfo[]) => { console.log('getAllAuthTokens successfully, tokenArr: ' + JSON.stringify(tokenArr)); }).catch((err: BusinessError) => { - console.log('getAllAuthTokens failed, error: ' + JSON.stringify(err)); + console.error('getAllAuthTokens failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log('getAllAuthTokens exception: ' + JSON.stringify(err)); + console.error('getAllAuthTokens exception: ' + JSON.stringify(err)); } ``` @@ -2150,13 +2182,13 @@ Obtains the authorization list of the specified authentication type for an appli try { appAccountManager.getAuthList('LiSi', 'getSocialData', (err: BusinessError, authList: string[]) => { if (err) { - console.log('getAuthList failed, error: ' + JSON.stringify(err)); + console.error('getAuthList failed, error: ' + JSON.stringify(err)); } else { console.log('getAuthList successfully, authList: ' + authList); } }); } catch (err) { - console.log('getAuthList exception: ' + JSON.stringify(err)); + console.error('getAuthList exception: ' + JSON.stringify(err)); } ``` @@ -2200,10 +2232,10 @@ Obtains the authorization list of the specified authentication type for an appli appAccountManager.getAuthList('LiSi', 'getSocialData').then((authList: string[]) => { console.log('getAuthList successfully, authList: ' + authList); }).catch((err: BusinessError) => { - console.log('getAuthList failed, error: ' + JSON.stringify(err)); + console.error('getAuthList failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log('getAuthList exception: ' + JSON.stringify(err)); + console.error('getAuthList exception: ' + JSON.stringify(err)); } ``` @@ -2243,7 +2275,7 @@ Obtains the authenticator callback for an authentication session. This API uses try { appAccountManager.getAuthCallback(sessionId, (err: BusinessError, callback: appAccount.AuthCallback) => { if (err != null) { - console.log('getAuthCallback err: ' + JSON.stringify(err)); + console.error('getAuthCallback err: ' + JSON.stringify(err)); return; } let result: appAccount.AuthResult = { @@ -2259,7 +2291,7 @@ Obtains the authenticator callback for an authentication session. This API uses callback.onResult(0, result); }); } catch (err) { - console.log('getAuthCallback exception: ' + JSON.stringify(err)); + console.error('getAuthCallback exception: ' + JSON.stringify(err)); } } } @@ -2317,10 +2349,10 @@ Obtains the authenticator callback for an authentication session. This API uses }; callback.onResult(0, result); }).catch((err: BusinessError) => { - console.log('getAuthCallback err: ' + JSON.stringify(err)); + console.error('getAuthCallback err: ' + JSON.stringify(err)); }); } catch (err) { - console.log('getAuthCallback exception: ' + JSON.stringify(err)); + console.error('getAuthCallback exception: ' + JSON.stringify(err)); } } } @@ -2359,13 +2391,13 @@ Obtains the authenticator information of an application. This API uses an asynch appAccountManager.queryAuthenticatorInfo('com.example.accountjsdemo', (err: BusinessError, info: appAccount.AuthenticatorInfo) => { if (err) { - console.log('queryAuthenticatorInfo failed, error: ' + JSON.stringify(err)); + console.error('queryAuthenticatorInfo failed, error: ' + JSON.stringify(err)); } else { console.log('queryAuthenticatorInfo successfully, info: ' + JSON.stringify(info)); } }); } catch (err) { - console.log('queryAuthenticatorInfo exception: ' + JSON.stringify(err)); + console.error('queryAuthenticatorInfo exception: ' + JSON.stringify(err)); } ``` @@ -2408,10 +2440,10 @@ Obtains the authenticator information of an application. This API uses a promise info: appAccount.AuthenticatorInfo) => { console.log('queryAuthenticatorInfo successfully, info: ' + JSON.stringify(info)); }).catch((err: BusinessError) => { - console.log('queryAuthenticatorInfo failed, error: ' + JSON.stringify(err)); + console.error('queryAuthenticatorInfo failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log('queryAuthenticatorInfo exception: ' + JSON.stringify(err)); + console.error('queryAuthenticatorInfo exception: ' + JSON.stringify(err)); } ``` @@ -2454,13 +2486,13 @@ Checks whether an application account has specific labels. This API uses an asyn appAccountManager.checkAccountLabels('zhangsan', 'com.example.accountjsdemo', labels, (err: BusinessError, hasAllLabels: boolean) => { if (err) { - console.log('checkAccountLabels failed, error: ' + JSON.stringify(err)); + console.error('checkAccountLabels failed, error: ' + JSON.stringify(err)); } else { console.log('checkAccountLabels successfully, hasAllLabels: ' + hasAllLabels); } }); } catch (err) { - console.log('checkAccountLabels exception: ' + JSON.stringify(err)); + console.error('checkAccountLabels exception: ' + JSON.stringify(err)); } ``` @@ -2509,10 +2541,10 @@ Checks whether an application account has specific labels. This API uses a promi hasAllLabels: boolean) => { console.log('checkAccountLabels successfully: ' + hasAllLabels); }).catch((err: BusinessError) => { - console.log('checkAccountLabels failed, error: ' + JSON.stringify(err)); + console.error('checkAccountLabels failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log('checkAccountLabels exception: ' + JSON.stringify(err)); + console.error('checkAccountLabels exception: ' + JSON.stringify(err)); } ``` @@ -2550,13 +2582,13 @@ Deletes the credential of the specified type from an application account. This A try { appAccountManager.deleteCredential('zhangsan', 'PIN_SIX', (err: BusinessError) => { if (err) { - console.log('deleteCredential failed, error: ' + JSON.stringify(err)); + console.error('deleteCredential failed, error: ' + JSON.stringify(err)); } else { console.log('deleteCredential successfully'); } }); } catch (err) { - console.log('deleteCredential exception: ' + JSON.stringify(err)); + console.error('deleteCredential exception: ' + JSON.stringify(err)); } ``` @@ -2600,10 +2632,10 @@ Deletes the credential of the specified type from an application account. This A appAccountManager.deleteCredential('zhangsan', 'PIN_SIX').then(() => { console.log('deleteCredential successfully'); }).catch((err: BusinessError) => { - console.log('deleteCredential failed, error: ' + JSON.stringify(err)); + console.error('deleteCredential failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log('deleteCredential exception: ' + JSON.stringify(err)); + console.error('deleteCredential exception: ' + JSON.stringify(err)); } ``` @@ -2645,13 +2677,13 @@ Selects the accounts that can be accessed by the invoker based on the options. T appAccountManager.selectAccountsByOptions(options, (err: BusinessError, accountArr: appAccount.AppAccountInfo[]) => { if (err) { - console.log('selectAccountsByOptions failed, error: ' + JSON.stringify(err)); + console.error('selectAccountsByOptions failed, error: ' + JSON.stringify(err)); } else { console.log('selectAccountsByOptions successfully, accountArr: ' + JSON.stringify(accountArr)); } }); } catch (err) { - console.log('selectAccountsByOptions exception: ' + JSON.stringify(err)); + console.error('selectAccountsByOptions exception: ' + JSON.stringify(err)); } ``` @@ -2697,10 +2729,10 @@ Selects the accounts that can be accessed by the invoker based on the options. T appAccountManager.selectAccountsByOptions(options).then((accountArr: appAccount.AppAccountInfo[]) => { console.log('selectAccountsByOptions successfully, accountArr: ' + JSON.stringify(accountArr)); }).catch((err: BusinessError) => { - console.log('selectAccountsByOptions failed, error: ' + JSON.stringify(err)); + console.error('selectAccountsByOptions failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log('selectAccountsByOptions exception: ' + JSON.stringify(err)); + console.error('selectAccountsByOptions exception: ' + JSON.stringify(err)); } ``` @@ -2748,7 +2780,7 @@ Verifies the credential of an application account. This API uses an asynchronous } }); } catch (err) { - console.log('verifyCredential err: ' + JSON.stringify(err)); + console.error('verifyCredential err: ' + JSON.stringify(err)); } ``` @@ -2801,7 +2833,7 @@ Verifies the user credential. This API uses an asynchronous callback to return t } }); } catch (err) { - console.log('verifyCredential err: ' + JSON.stringify(err)); + console.error('verifyCredential err: ' + JSON.stringify(err)); } ``` @@ -2847,7 +2879,7 @@ Sets the authenticator attributes of an application. This API uses an asynchrono } }); } catch (err) { - console.log('setAuthenticatorProperties err: ' + JSON.stringify(err)); + console.error('setAuthenticatorProperties err: ' + JSON.stringify(err)); } ``` @@ -2897,7 +2929,7 @@ Sets the authenticator properties. This API uses an asynchronous callback to ret } }); } catch (err) { - console.log('setAuthenticatorProperties err: ' + JSON.stringify(err)); + console.error('setAuthenticatorProperties err: ' + JSON.stringify(err)); } ``` @@ -2919,7 +2951,7 @@ Adds an application account with the given name. This API uses an asynchronous c | Name | Type | Mandatory | Description | | -------- | ------------------------- | ---- | -------------------- | -| name | string | Yes | Name of the target application account. | +| name | string | Yes | Name of the application account to create. | | callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.| **Example** @@ -2928,7 +2960,7 @@ Adds an application account with the given name. This API uses an asynchronous c import { BusinessError } from '@kit.BasicServicesKit'; appAccountManager.addAccount('WangWu', (err: BusinessError) => { - console.log('addAccount err: ' + JSON.stringify(err)); + console.error('addAccount err: ' + JSON.stringify(err)); }); ``` @@ -2947,7 +2979,7 @@ Adds an application account name and additional information. This API uses an as | Name | Type | Mandatory | Description | | --------- | ------------------------- | ---- | ---------------------------------------- | -| name | string | Yes | Name of the target application account. | +| name | string | Yes | Name of the application account to create. | | extraInfo | string | Yes | Additional information (information that can be converted to the string type). It cannot contain sensitive information, such as the application account password and token.| | callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object. | @@ -2957,7 +2989,7 @@ Adds an application account name and additional information. This API uses an as import { BusinessError } from '@kit.BasicServicesKit'; appAccountManager.addAccount('LiSi', 'token101', (err: BusinessError) => { - console.log('addAccount err: ' + JSON.stringify(err)); + console.error('addAccount err: ' + JSON.stringify(err)); }); ``` @@ -2976,7 +3008,7 @@ Adds an application account name and additional information. This API uses an as | Name | Type | Mandatory | Description | | --------- | ------ | ---- | ---------------------------------------- | -| name | string | Yes | Name of the target application account. | +| name | string | Yes | Name of the application account to create. | | extraInfo | string | No | Additional information (information that can be converted to the string type).
The additional information cannot be sensitive information (such as the password and token) of the application account.
By default, no value is passed, which means no additional information needs to be added for the account.| **Return value** @@ -2993,7 +3025,7 @@ Adds an application account name and additional information. This API uses an as appAccountManager.addAccount('LiSi', 'token101').then(()=> { console.log('addAccount Success'); }).catch((err: BusinessError) => { - console.log('addAccount err: ' + JSON.stringify(err)); + console.error('addAccount err: ' + JSON.stringify(err)); }); ``` @@ -3005,7 +3037,7 @@ Adds an application account implicitly based on the specified owner. This API us > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. Use [createAccountImplicitly](#createaccountimplicitly9) instead. +> This enum is supported since API version 8 and deprecated since API version 9. Use [createAccountImplicitly](#createaccountimplicitly9) instead. **System capability**: SystemCapability.Account.AppAccount @@ -3024,31 +3056,38 @@ Adds an application account implicitly based on the specified owner. This API us import { BusinessError } from '@kit.BasicServicesKit'; import { Want, common } from '@kit.AbilityKit'; - let context = getContext(this) as common.UIAbilityContext; // UIAbilityContext + @Entry + @Component + struct Index { + context = this.getUIContext().getHostContext() as common.UIAbilityContext; // UIAbilityContext - function onResultCallback(code: number, result: Record): void { - console.log('resultCode: ' + code); - console.log('result: ' + JSON.stringify(result)); - } + onResultCallback(code: number, result: Record): void { + console.log('resultCode: ' + code); + console.log('result: ' + JSON.stringify(result)); + } - function onRequestRedirectedCallback(request: Want): void { - let wantInfo: Want = { - deviceId: '', - bundleName: 'com.example.accountjsdemo', - action: 'ohos.want.action.viewData', - entities: ['entity.system.default'], + onRequestRedirectedCallback(request: Want): void { + let wantInfo: Want = { + deviceId: '', + bundleName: 'com.example.accountjsdemo', + action: 'ohos.want.action.viewData', + entities: ['entity.system.default'], + } + this.context.startAbility(wantInfo).then(() => { + console.log('startAbility successfully'); + }).catch((err: BusinessError) => { + console.error('startAbility err: ' + JSON.stringify(err)); + }) } - context.startAbility(wantInfo).then(() => { - console.log('startAbility successfully'); - }).catch((err: BusinessError) => { - console.log('startAbility err: ' + JSON.stringify(err)); - }) - } - appAccountManager.addAccountImplicitly('com.example.accountjsdemo', 'getSocialData', {}, { - onResult: onResultCallback, - onRequestRedirected: onRequestRedirectedCallback - }); + aboutToAppear(): void { + appAccountManager.addAccountImplicitly('com.example.accountjsdemo', 'getSocialData', {}, { + onResult: this.onResultCallback, + onRequestRedirected: this.onRequestRedirectedCallback + }); + } + build() {} + } ``` ### deleteAccount(deprecated) @@ -3076,7 +3115,7 @@ Deletes an application account. This API uses an asynchronous callback to return import { BusinessError } from '@kit.BasicServicesKit'; appAccountManager.deleteAccount('ZhaoLiu', (err: BusinessError) => { - console.log('deleteAccount err: ' + JSON.stringify(err)); + console.error('deleteAccount err: ' + JSON.stringify(err)); }); ``` @@ -3112,7 +3151,7 @@ Deletes an application account. This API uses a promise to return the result. appAccountManager.deleteAccount('ZhaoLiu').then(() => { console.log('deleteAccount Success'); }).catch((err: BusinessError) => { - console.log('deleteAccount err: ' + JSON.stringify(err)); + console.error('deleteAccount err: ' + JSON.stringify(err)); }); ``` ### disableAppAccess(deprecated) @@ -3141,7 +3180,7 @@ Disables an application account from accessing an application. This API uses an import { BusinessError } from '@kit.BasicServicesKit'; appAccountManager.disableAppAccess('ZhangSan', 'com.example.accountjsdemo', (err: BusinessError) => { - console.log('disableAppAccess err: ' + JSON.stringify(err)); + console.error('disableAppAccess err: ' + JSON.stringify(err)); }); ``` @@ -3178,7 +3217,7 @@ Disables an application account from accessing an application. This API uses a p appAccountManager.disableAppAccess('ZhangSan', 'com.example.accountjsdemo').then(() => { console.log('disableAppAccess Success'); }).catch((err: BusinessError) => { - console.log('disableAppAccess err: ' + JSON.stringify(err)); + console.error('disableAppAccess err: ' + JSON.stringify(err)); }); ``` @@ -3207,8 +3246,12 @@ Enables an application account to access an application. This API uses an asynch ```ts import { BusinessError } from '@kit.BasicServicesKit'; - appAccountManager.enableAppAccess('ZhangSan', 'com.example.accountjsdemo', (err: BusinessError) => { - console.log('enableAppAccess: ' + JSON.stringify(err)); + appAccountManager.enableAppAccess('ZhangSan', 'com.example.accountjsdemo', (err: BusinessError) => { + if (err) { + console.error('enableAppAccess err: ' + JSON.stringify(err)); + } else { + console.log('enableAppAccess successful.'); + } }); ``` @@ -3245,7 +3288,7 @@ Enables an application account to access an application. This API uses a promise appAccountManager.enableAppAccess('ZhangSan', 'com.example.accountjsdemo').then(() => { console.log('enableAppAccess Success'); }).catch((err: BusinessError) => { - console.log('enableAppAccess err: ' + JSON.stringify(err)); + console.error('enableAppAccess err: ' + JSON.stringify(err)); }); ``` @@ -3276,8 +3319,11 @@ Checks whether data synchronization is enabled for an application account. This import { BusinessError } from '@kit.BasicServicesKit'; appAccountManager.checkAppAccountSyncEnable('ZhangSan', (err: BusinessError, result: boolean) => { - console.log('checkAppAccountSyncEnable err: ' + JSON.stringify(err)); + if (err) { + console.error('checkAppAccountSyncEnable code: ' + JSON.stringify(err)); + } else { console.log('checkAppAccountSyncEnable result: ' + result); + } }); ``` @@ -3315,7 +3361,7 @@ Checks whether data synchronization is enabled for an application account. This appAccountManager.checkAppAccountSyncEnable('ZhangSan').then((data: boolean) => { console.log('checkAppAccountSyncEnable, result: ' + data); }).catch((err: BusinessError) => { - console.log('checkAppAccountSyncEnable err: ' + JSON.stringify(err)); + console.error('checkAppAccountSyncEnable err: ' + JSON.stringify(err)); }); ``` @@ -3327,7 +3373,7 @@ Sets a credential for an application account. This API uses an asynchronous call > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. Use [setCredential](#setcredential9) instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setCredential](#setcredential9) instead. **System capability**: SystemCapability.Account.AppAccount @@ -3346,7 +3392,11 @@ Sets a credential for an application account. This API uses an asynchronous call import { BusinessError } from '@kit.BasicServicesKit'; appAccountManager.setAccountCredential('ZhangSan', 'credentialType001', 'credential001', (err: BusinessError) => { - console.log('setAccountCredential err: ' + JSON.stringify(err)); + if (err) { + console.error('setAccountCredential err: ' + JSON.stringify(err)); + } else { + console.log('setAccountCredential successful.'); + } }); ``` @@ -3358,7 +3408,7 @@ Sets a credential for an application account. This API uses a promise to return > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. Use [setCredential](#setcredential9-1) instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setCredential](#setcredential9-1) instead. **System capability**: SystemCapability.Account.AppAccount @@ -3384,7 +3434,7 @@ Sets a credential for an application account. This API uses a promise to return appAccountManager.setAccountCredential('ZhangSan', 'credentialType001', 'credential001').then(() => { console.log('setAccountCredential Success'); }).catch((err: BusinessError) => { - console.log('setAccountCredential err: ' + JSON.stringify(err)); + console.error('setAccountCredential err: ' + JSON.stringify(err)); }); ``` @@ -3415,7 +3465,11 @@ Sets additional information for an application account. This API uses an asynchr import { BusinessError } from '@kit.BasicServicesKit'; appAccountManager.setAccountExtraInfo('ZhangSan', 'Tk002', (err: BusinessError) => { - console.log('setAccountExtraInfo err: ' + JSON.stringify(err)); + if (err) { + console.error('setAccountExtraInfo err: ' + JSON.stringify(err)); + } else { + console.log('setAccountExtraInfo successful.'); + } }); ``` @@ -3453,7 +3507,7 @@ Sets additional information for an application account. This API uses a promise appAccountManager.setAccountExtraInfo('ZhangSan', 'Tk002').then(() => { console.log('setAccountExtraInfo Success'); }).catch((err: BusinessError) => { - console.log('setAccountExtraInfo err: ' + JSON.stringify(err)); + console.error('setAccountExtraInfo err: ' + JSON.stringify(err)); }); ``` @@ -3484,8 +3538,12 @@ Sets data synchronization for an application account. This API uses an asynchron ```ts import { BusinessError } from '@kit.BasicServicesKit'; - appAccountManager.setAppAccountSyncEnable('ZhangSan', true, (err: BusinessError) => { - console.log('setAppAccountSyncEnable err: ' + JSON.stringify(err)); + appAccountManager.setAppAccountSyncEnable('ZhangSan', true, (err: BusinessError) => { + if (err) { + console.error('setAppAccountSyncEnable err: ' + JSON.stringify(err)); + } else { + console.log('setAppAccountSyncEnable successful.'); + } }); ``` @@ -3524,7 +3582,7 @@ Sets data synchronization for an application account. This API uses a promise to appAccountManager .setAppAccountSyncEnable('ZhangSan', true).then(() => { console.log('setAppAccountSyncEnable Success'); }).catch((err: BusinessError) => { - console.log('setAppAccountSyncEnable err: ' + JSON.stringify(err)); + console.error('setAppAccountSyncEnable err: ' + JSON.stringify(err)); }); ``` @@ -3555,8 +3613,12 @@ Sets data to be associated with an application account. This API uses an asynchr ```ts import { BusinessError } from '@kit.BasicServicesKit'; - appAccountManager.setAssociatedData('ZhangSan', 'k001', 'v001', (err: BusinessError) => { - console.log('setAssociatedData err: ' + JSON.stringify(err)); + appAccountManager.setAssociatedData('ZhangSan', 'k001', 'v001', (err: BusinessError) => { + if (err) { + console.error('setAssociatedData err: ' + JSON.stringify(err)); + } else { + console.log('setAssociatedData successful.'); + } }); ``` @@ -3595,7 +3657,7 @@ Sets data to be associated with an application account. This API uses a promise appAccountManager.setAssociatedData('ZhangSan', 'k001', 'v001').then(() => { console.log('setAssociatedData Success'); }).catch((err: BusinessError) => { - console.log('setAssociatedData err: ' + JSON.stringify(err)); + console.error('setAssociatedData err: ' + JSON.stringify(err)); }); ``` @@ -3658,7 +3720,7 @@ Obtains information about all accessible application accounts. This API uses a p appAccountManager.getAllAccessibleAccounts().then((data: appAccount.AppAccountInfo[]) => { console.log('getAllAccessibleAccounts: ' + data); }).catch((err: BusinessError) => { - console.log('getAllAccessibleAccounts err: ' + JSON.stringify(err)); + console.error('getAllAccessibleAccounts err: ' + JSON.stringify(err)); }); ``` @@ -3730,7 +3792,7 @@ Obtains the application accounts that can be accessed by the invoker based on th appAccountManager.getAllAccounts(selfBundle).then((data: appAccount.AppAccountInfo[]) => { console.log('getAllAccounts: ' + data); }).catch((err: BusinessError) => { - console.log('getAllAccounts err: ' + JSON.stringify(err)); + console.error('getAllAccounts err: ' + JSON.stringify(err)); }); ``` @@ -3760,8 +3822,11 @@ Obtains the credential of an application account. This API uses an asynchronous import { BusinessError } from '@kit.BasicServicesKit'; appAccountManager.getAccountCredential('ZhangSan', 'credentialType001', (err: BusinessError, result: string) => { - console.log('getAccountCredential err: ' + JSON.stringify(err)); + if (err) { + console.error('getAccountCredential err: ' + JSON.stringify(err)); + } else { console.log('getAccountCredential result: ' + result); + } }); ``` @@ -3798,7 +3863,7 @@ Obtains the credential of an application account. This API uses a promise to ret appAccountManager.getAccountCredential('ZhangSan', 'credentialType001').then((data: string) => { console.log('getAccountCredential, result: ' + data); }).catch((err: BusinessError) => { - console.log('getAccountCredential err: ' + JSON.stringify(err)); + console.error('getAccountCredential err: ' + JSON.stringify(err)); }); ``` @@ -3827,8 +3892,11 @@ Obtains additional information of an application account. Additional information import { BusinessError } from '@kit.BasicServicesKit'; appAccountManager.getAccountExtraInfo('ZhangSan', (err: BusinessError, result: string) => { - console.log('getAccountExtraInfo err: ' + JSON.stringify(err)); + if (err) { + console.error('getAccountExtraInfo err: ' + JSON.stringify(err)); + } else { console.log('getAccountExtraInfo result: ' + result); + } }); ``` @@ -3864,7 +3932,7 @@ Obtains additional information of an application account. Additional information appAccountManager.getAccountExtraInfo('ZhangSan').then((data: string) => { console.log('getAccountExtraInfo, result: ' + data); }).catch((err: BusinessError) => { - console.log('getAccountExtraInfo err: ' + JSON.stringify(err)); + console.error('getAccountExtraInfo err: ' + JSON.stringify(err)); }); ``` @@ -3894,8 +3962,11 @@ Obtains data associated with an application account. This API uses an asynchrono import { BusinessError } from '@kit.BasicServicesKit'; appAccountManager.getAssociatedData('ZhangSan', 'k001', (err: BusinessError, result: string) => { - console.log('getAssociatedData err: ' + JSON.stringify(err)); + if (err) { + console.error('getAssociatedData err: ' + JSON.stringify(err)); + } else { console.log('getAssociatedData result: ' + result); + } }); ``` @@ -3932,7 +4003,7 @@ Obtains data associated with an application account. This API uses a promise to appAccountManager.getAssociatedData('ZhangSan', 'k001').then((data: string) => { console.log('getAssociatedData: ' + data); }).catch((err: BusinessError) => { - console.log('getAssociatedData err: ' + JSON.stringify(err)); + console.error('getAssociatedData err: ' + JSON.stringify(err)); }); ``` @@ -3953,7 +4024,7 @@ Subscribes to account information changes of apps. | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ------------------------------ | | type | 'change' | Yes | Event type to subscribe to. The value is **'change'**. An event will be reported when the account information changes.| -| owners | Array<string> | Yes | application bundle names of the account. | +| owners | Array<string> | Yes | Application bundle names of the account. | | callback | Callback<Array<[AppAccountInfo](#appaccountinfo)>> | Yes | Callback registered to return the list of changed application accounts. | **Example** @@ -4014,7 +4085,7 @@ Authenticates an application account. This API uses an asynchronous callback to > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. Use [auth](#auth9) instead. +> This enum is supported since API version 8 and deprecated since API version 9. Use [auth](#auth9) instead. **System capability**: SystemCapability.Account.AppAccount @@ -4034,31 +4105,38 @@ Authenticates an application account. This API uses an asynchronous callback to import { BusinessError } from '@kit.BasicServicesKit'; import { Want, common } from '@kit.AbilityKit'; - let context = getContext(this) as common.UIAbilityContext; // UIAbilityContext + @Entry + @Component + struct Index { + context = this.getUIContext().getHostContext() as common.UIAbilityContext; // UIAbilityContext - function onResultCallback(code: number, result: Record): void { + onResultCallback(code: number, result: Record): void { console.log('resultCode: ' + code); console.log('result: ' + JSON.stringify(result)); - } + } - function onRequestRedirectedCallback(request: Want): void { - let wantInfo: Want = { - deviceId: '', - bundleName: 'com.example.accountjsdemo', - action: 'ohos.want.action.viewData', - entities: ['entity.system.default'], + onRequestRedirectedCallback(request: Want): void { + let wantInfo: Want = { + deviceId: '', + bundleName: 'com.example.accountjsdemo', + action: 'ohos.want.action.viewData', + entities: ['entity.system.default'], + } + this.context.startAbility(wantInfo).then(() => { + console.log('startAbility successfully'); + }).catch((err: BusinessError) => { + console.error('startAbility err: ' + JSON.stringify(err)); + }) } - context.startAbility(wantInfo).then(() => { - console.log('startAbility successfully'); - }).catch((err: BusinessError) => { - console.log('startAbility err: ' + JSON.stringify(err)); - }) - } - appAccountManager.authenticate('LiSi', 'com.example.accountjsdemo', 'getSocialData', {}, { - onResult: onResultCallback, - onRequestRedirected: onRequestRedirectedCallback - }); + aboutToAppear(): void { + appAccountManager.authenticate('LiSi', 'com.example.accountjsdemo', 'getSocialData', {}, { + onResult: this.onResultCallback, + onRequestRedirected: this.onRequestRedirectedCallback + }); + } + build() {} + } ``` ### getOAuthToken(deprecated) @@ -4069,7 +4147,7 @@ Obtains the authorization token of the specified authentication type for an appl > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. Use [getAuthToken](#getauthtoken9) instead. +> This enum is supported since API version 8 and deprecated since API version 9. Use [getAuthToken](#getauthtoken9) instead. **System capability**: SystemCapability.Account.AppAccount @@ -4089,8 +4167,11 @@ Obtains the authorization token of the specified authentication type for an appl appAccountManager.getOAuthToken('LiSi', 'com.example.accountjsdemo', 'getSocialData', (err: BusinessError, data: string) => { - console.log('getOAuthToken err: ' + JSON.stringify(err)); - console.log('getOAuthToken token: ' + data); + if (err) { + console.error('getOAuthToken err: ' + JSON.stringify(err)); + } else { + console.log('getOAuthToken token: ' + data); + } }); ``` @@ -4102,7 +4183,7 @@ Obtains the authorization token of the specified authentication type for an appl > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. Use [getAuthToken](#getauthtoken9-1) instead. +> This enum is supported since API version 8 and deprecated since API version 9. Use [getAuthToken](#getauthtoken9-1) instead. **System capability**: SystemCapability.Account.AppAccount @@ -4128,7 +4209,7 @@ Obtains the authorization token of the specified authentication type for an appl appAccountManager.getOAuthToken('LiSi', 'com.example.accountjsdemo', 'getSocialData').then((data: string) => { console.log('getOAuthToken token: ' + data); }).catch((err: BusinessError) => { - console.log('getOAuthToken err: ' + JSON.stringify(err)); + console.error('getOAuthToken err: ' + JSON.stringify(err)); }); ``` @@ -4140,7 +4221,7 @@ Sets an authorization token of the specific authentication type for an applicati > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. Use [setAuthToken](#setauthtoken9) instead. +> This enum is supported since API version 8 and deprecated since API version 9. Use [setAuthToken](#setauthtoken9) instead. **System capability**: SystemCapability.Account.AppAccount @@ -4159,7 +4240,11 @@ Sets an authorization token of the specific authentication type for an applicati import { BusinessError } from '@kit.BasicServicesKit'; appAccountManager.setOAuthToken('LiSi', 'getSocialData', 'xxxx', (err: BusinessError) => { - console.log('setOAuthToken err: ' + JSON.stringify(err)); + if (err) { + console.error('setOAuthToken err: ' + JSON.stringify(err)); + } else { + console.log('setOAuthToken successful.'); + } }); ``` @@ -4171,7 +4256,7 @@ Sets an authorization token of the specific authentication type for an applicati > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. Use [setAuthToken](#setauthtoken9-1) instead. +> This enum is supported since API version 8 and deprecated since API version 9. Use [setAuthToken](#setauthtoken9-1) instead. **System capability**: SystemCapability.Account.AppAccount @@ -4197,7 +4282,7 @@ Sets an authorization token of the specific authentication type for an applicati appAccountManager.setOAuthToken('LiSi', 'getSocialData', 'xxxx').then(() => { console.log('setOAuthToken successfully'); }).catch((err: BusinessError) => { - console.log('setOAuthToken err: ' + JSON.stringify(err)); + console.error('setOAuthToken err: ' + JSON.stringify(err)); }); ``` @@ -4209,7 +4294,7 @@ Deletes the authorization token of the specified authentication type for an appl > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. Use [deleteAuthToken](#deleteauthtoken9) instead. +> This enum is supported since API version 8 and deprecated since API version 9. Use [deleteAuthToken](#deleteauthtoken9) instead. **System capability**: SystemCapability.Account.AppAccount @@ -4230,7 +4315,11 @@ Deletes the authorization token of the specified authentication type for an appl appAccountManager.deleteOAuthToken('LiSi', 'com.example.accountjsdemo', 'getSocialData', 'xxxxx', (err: BusinessError) => { - console.log('deleteOAuthToken err: ' + JSON.stringify(err)); + if (err) { + console.error('deleteOAuthToken err: ' + JSON.stringify(err)); + } else { + console.log('deleteOAuthToken successful.'); + } }); ``` @@ -4242,7 +4331,7 @@ Deletes the authorization token of the specified authentication type for an appl > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. Use [deleteAuthToken](#deleteauthtoken9-1) instead. +> This enum is supported since API version 8 and deprecated since API version 9. Use [deleteAuthToken](#deleteauthtoken9-1) instead. **System capability**: SystemCapability.Account.AppAccount @@ -4269,7 +4358,7 @@ Deletes the authorization token of the specified authentication type for an appl appAccountManager.deleteOAuthToken('LiSi', 'com.example.accountjsdemo', 'getSocialData', 'xxxxx').then(() => { console.log('deleteOAuthToken successfully'); }).catch((err: BusinessError) => { - console.log('deleteOAuthToken err: ' + JSON.stringify(err)); + console.error('deleteOAuthToken err: ' + JSON.stringify(err)); }); ``` @@ -4281,7 +4370,7 @@ Sets the visibility of an authorization token to an application. This API uses a > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. Use [setAuthTokenVisibility](#setauthtokenvisibility9) instead. +> This enum is supported since API version 8 and deprecated since API version 9. Use [setAuthTokenVisibility](#setauthtokenvisibility9) instead. **System capability**: SystemCapability.Account.AppAccount @@ -4302,7 +4391,11 @@ Sets the visibility of an authorization token to an application. This API uses a appAccountManager.setOAuthTokenVisibility('LiSi', 'getSocialData', 'com.example.accountjsdemo', true, (err: BusinessError) => { - console.log('setOAuthTokenVisibility err: ' + JSON.stringify(err)); + if (err) { + console.error('setOAuthTokenVisibility err: ' + JSON.stringify(err)); + } else { + console.log('setOAuthTokenVisibility successful.'); + } }); ``` @@ -4314,7 +4407,7 @@ Sets the visibility of an authorization token to an application. This API uses a > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. Use [setAuthTokenVisibility](#setauthtokenvisibility9-1) instead. +> This enum is supported since API version 8 and deprecated since API version 9. Use [setAuthTokenVisibility](#setauthtokenvisibility9-1) instead. **System capability**: SystemCapability.Account.AppAccount @@ -4341,7 +4434,7 @@ Sets the visibility of an authorization token to an application. This API uses a appAccountManager.setOAuthTokenVisibility('LiSi', 'getSocialData', 'com.example.accountjsdemo', true).then(() => { console.log('setOAuthTokenVisibility successfully'); }).catch((err: BusinessError) => { - console.log('setOAuthTokenVisibility err: ' + JSON.stringify(err)); + console.error('setOAuthTokenVisibility err: ' + JSON.stringify(err)); }); ``` @@ -4353,7 +4446,7 @@ Checks the visibility of an authorization token of the specified authentication > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. Use [checkAuthTokenVisibility](#checkauthtokenvisibility9) instead. +> This enum is supported since API version 8 and deprecated since API version 9. Use [checkAuthTokenVisibility](#checkauthtokenvisibility9) instead. **System capability**: SystemCapability.Account.AppAccount @@ -4373,8 +4466,11 @@ Checks the visibility of an authorization token of the specified authentication appAccountManager.checkOAuthTokenVisibility('LiSi', 'getSocialData', 'com.example.accountjsdemo', (err: BusinessError, data: boolean) => { - console.log('checkOAuthTokenVisibility err: ' + JSON.stringify(err)); - console.log('checkOAuthTokenVisibility isVisible: ' + data); + if (err) { + console.error('checkOAuthTokenVisibility err: ' + JSON.stringify(err)); + } else { + console.log('checkOAuthTokenVisibility isVisible: ' + data); + } }); ``` @@ -4386,7 +4482,7 @@ Checks the visibility of an authorization token of the specified authentication > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. Use [checkAuthTokenVisibility](#checkauthtokenvisibility9-1) instead. +> This enum is supported since API version 8 and deprecated since API version 9. Use [checkAuthTokenVisibility](#checkauthtokenvisibility9-1) instead. **System capability**: SystemCapability.Account.AppAccount @@ -4413,7 +4509,7 @@ Checks the visibility of an authorization token of the specified authentication data: boolean) => { console.log('checkOAuthTokenVisibility isVisible: ' + data); }).catch((err: BusinessError) => { - console.log('checkOAuthTokenVisibility err: ' + JSON.stringify(err)); + console.error('checkOAuthTokenVisibility err: ' + JSON.stringify(err)); }); ``` @@ -4425,7 +4521,7 @@ Obtains all tokens visible to the invoker for an application account. This API u > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. Use [getAllAuthTokens](#getallauthtokens9) instead. +> This enum is supported since API version 8 and deprecated since API version 9. Use [getAllAuthTokens](#getallauthtokens9) instead. **System capability**: SystemCapability.Account.AppAccount @@ -4444,8 +4540,11 @@ Obtains all tokens visible to the invoker for an application account. This API u appAccountManager.getAllOAuthTokens('LiSi', 'com.example.accountjsdemo', (err: BusinessError, data: appAccount.OAuthTokenInfo[]) => { - console.log('getAllOAuthTokens err: ' + JSON.stringify(err)); - console.log('getAllOAuthTokens data: ' + JSON.stringify(data)); + if (err) { + console.error('getAllOAuthTokens err: ' + JSON.stringify(err)); + } else { + console.log('getAllOAuthTokens data: ' + JSON.stringify(data)); + } }); ``` @@ -4457,7 +4556,7 @@ Obtains all tokens visible to the invoker for an application account. This API u > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. Use [getAllAuthTokens](#getallauthtokens9-1) instead. +> This enum is supported since API version 8 and deprecated since API version 9. Use [getAllAuthTokens](#getallauthtokens9-1) instead. **System capability**: SystemCapability.Account.AppAccount @@ -4483,7 +4582,7 @@ Obtains all tokens visible to the invoker for an application account. This API u data: appAccount.OAuthTokenInfo[]) => { console.log('getAllOAuthTokens data: ' + JSON.stringify(data)); }).catch((err: BusinessError) => { - console.log('getAllOAuthTokens err: ' + JSON.stringify(err)); + console.error('getAllOAuthTokens err: ' + JSON.stringify(err)); }); ``` @@ -4495,7 +4594,7 @@ Obtains the authorization list of the specified authentication type for an appli > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. Use [getAuthList](#getauthlist9) instead. +> This enum is supported since API version 8 and deprecated since API version 9. Use [getAuthList](#getauthlist9) instead. **System capability**: SystemCapability.Account.AppAccount @@ -4513,8 +4612,11 @@ Obtains the authorization list of the specified authentication type for an appli import { BusinessError } from '@kit.BasicServicesKit'; appAccountManager.getOAuthList('LiSi', 'getSocialData', (err: BusinessError, data: string[]) => { - console.log('getOAuthList err: ' + JSON.stringify(err)); - console.log('getOAuthList data: ' + JSON.stringify(data)); + if (err) { + console.error('getOAuthList err: ' + JSON.stringify(err)); + } else { + console.log('getOAuthList data: ' + JSON.stringify(data)); + } }); ``` @@ -4526,7 +4628,7 @@ Obtains the authorization list of the specified authentication type for an appli > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. Use [getAuthList](#getauthlist9-1) instead. +> This enum is supported since API version 8 and deprecated since API version 9. Use [getAuthList](#getauthlist9-1) instead. **System capability**: SystemCapability.Account.AppAccount @@ -4551,7 +4653,7 @@ Obtains the authorization list of the specified authentication type for an appli appAccountManager.getOAuthList('LiSi', 'getSocialData').then((data: string[]) => { console.log('getOAuthList data: ' + JSON.stringify(data)); }).catch((err: BusinessError) => { - console.log('getOAuthList err: ' + JSON.stringify(err)); + console.error('getOAuthList err: ' + JSON.stringify(err)); }); ``` @@ -4563,7 +4665,7 @@ Obtains the authenticator callback for an authentication session. This API uses > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. Use [getAuthCallback](#getauthcallback9) instead. +> This enum is supported since API version 8 and deprecated since API version 9. Use [getAuthCallback](#getauthcallback9) instead. **System capability**: SystemCapability.Account.AppAccount @@ -4586,7 +4688,7 @@ Obtains the authenticator callback for an authentication session. This API uses appAccountManager.getAuthenticatorCallback(sessionId, (err: BusinessError, callback: appAccount.AuthenticatorCallback) => { if (err.code != appAccount.ResultCode.SUCCESS) { - console.log('getAuthenticatorCallback err: ' + JSON.stringify(err)); + console.error('getAuthenticatorCallback err: ' + JSON.stringify(err)); return; } callback.onResult(appAccount.ResultCode.SUCCESS, { @@ -4608,7 +4710,7 @@ Obtains the authenticator callback for an authentication session. This API uses > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. Use [getAuthCallback](#getauthcallback9-1) instead. +> This enum is supported since API version 8 and deprecated since API version 9. Use [getAuthCallback](#getauthcallback9-1) instead. **System capability**: SystemCapability.Account.AppAccount @@ -4642,7 +4744,7 @@ Obtains the authenticator callback for an authentication session. This API uses token: 'xxxxxx'} ); }).catch((err: BusinessError) => { - console.log('getAuthenticatorCallback err: ' + JSON.stringify(err)); + console.error('getAuthenticatorCallback err: ' + JSON.stringify(err)); }); } } @@ -4656,7 +4758,7 @@ Obtains the authenticator information of an application. This API uses an asynch > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. Use [queryAuthenticatorInfo](#queryauthenticatorinfo9) instead. +> This enum is supported since API version 8 and deprecated since API version 9. Use [queryAuthenticatorInfo](#queryauthenticatorinfo9) instead. **System capability**: SystemCapability.Account.AppAccount @@ -4674,8 +4776,11 @@ Obtains the authenticator information of an application. This API uses an asynch appAccountManager.getAuthenticatorInfo('com.example.accountjsdemo', (err: BusinessError, data: appAccount.AuthenticatorInfo) => { - console.log('getAuthenticatorInfo err: ' + JSON.stringify(err)); - console.log('getAuthenticatorInfo data: ' + JSON.stringify(data)); + if (err) { + console.error('getAuthenticatorInfo err: ' + JSON.stringify(err)); + } else { + console.log('getAuthenticatorInfo data: ' + JSON.stringify(data)); + } }); ``` @@ -4687,7 +4792,7 @@ Obtains the authenticator information of an application. This API uses a promise > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. Use [queryAuthenticatorInfo](#queryauthenticatorinfo9-1) instead. +> This enum is supported since API version 8 and deprecated since API version 9. Use [queryAuthenticatorInfo](#queryauthenticatorinfo9-1) instead. **System capability**: SystemCapability.Account.AppAccount @@ -4712,7 +4817,7 @@ Obtains the authenticator information of an application. This API uses a promise data: appAccount.AuthenticatorInfo) => { console.log('getAuthenticatorInfo: ' + JSON.stringify(data)); }).catch((err: BusinessError) => { - console.log('getAuthenticatorInfo err: ' + JSON.stringify(err)); + console.error('getAuthenticatorInfo err: ' + JSON.stringify(err)); }); ``` @@ -4745,7 +4850,7 @@ Defines authorization token information. > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. Use [AuthTokenInfo](#authtokeninfo9) instead. +> This enum is supported since API version 8 and deprecated since API version 9. Use [AuthTokenInfo](#authtokeninfo9) instead. **System capability**: SystemCapability.Account.AppAccount @@ -4930,7 +5035,7 @@ Called to return the result of an authentication request. }; callback.onResult(appAccount.ResultCode.SUCCESS, result); }).catch((err: BusinessError) => { - console.log('getAuthCallback err: ' + JSON.stringify(err)); + console.error('getAuthCallback err: ' + JSON.stringify(err)); }); ``` @@ -5000,7 +5105,7 @@ Called to continue to process the request. callback.onRequestContinued(); } }).catch((err: BusinessError) => { - console.log('getAuthCallback err: ' + JSON.stringify(err)); + console.error('getAuthCallback err: ' + JSON.stringify(err)); }); ``` @@ -5010,7 +5115,7 @@ Provides OAuth authenticator callbacks. > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. Use [AuthCallback](#authcallback9) instead. +> This enum is supported since API version 8 and deprecated since API version 9. Use [AuthCallback](#authcallback9) instead. ### onResult8+ @@ -5042,7 +5147,7 @@ Called to return the result of an authentication request. token: 'xxxxxx'} ); }).catch((err: BusinessError) => { - console.log('getAuthenticatorCallback err: ' + JSON.stringify(err)); + console.error('getAuthenticatorCallback err: ' + JSON.stringify(err)); }); ``` @@ -5235,6 +5340,12 @@ Obtains the remote object of an authenticator. This API cannot be overloaded. **System capability**: SystemCapability.Account.AppAccount +**Return value** + +| Type | Description | +| ---------------- | ----------------------------------------------------- | +| rpc.RemoteObject | Remote object of the authenticator, which is used for inter-process communication. | + **Example** diff --git a/en/application-dev/reference/apis-basic-services-kit/js-apis-application-StaticSubscriberExtensionContext-sys.md b/en/application-dev/reference/apis-basic-services-kit/js-apis-application-StaticSubscriberExtensionContext-sys.md index e2ba98d2a55..063891a7347 100644 --- a/en/application-dev/reference/apis-basic-services-kit/js-apis-application-StaticSubscriberExtensionContext-sys.md +++ b/en/application-dev/reference/apis-basic-services-kit/js-apis-application-StaticSubscriberExtensionContext-sys.md @@ -56,7 +56,7 @@ Observe the following when using this API: | 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 | Can not start invisible component. | +| 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. | @@ -66,7 +66,7 @@ Observe the following when using this API: | 16000053 | The ability is not on the top of the UI. | | 16000055 | Installation-free timed out. | | 16200001 | The caller has been released. | -| 16300003 | The target application is not self application. | +| 16300003 | The target application is not the current application. | For details about the error codes, see [Ability Error Codes](../apis-ability-kit/errorcode-ability.md). @@ -142,7 +142,7 @@ Observe the following when using this API: | 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 | Can not start invisible component. | +| 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. | @@ -152,7 +152,7 @@ Observe the following when using this API: | 16000053 | The ability is not on the top of the UI. | | 16000055 | Installation-free timed out. | | 16200001 | The caller has been released. | -| 16300003 | The target application is not self application. | +| 16300003 | The target application is not the current application. | For details about the error codes, see [Ability Error Codes](../apis-ability-kit/errorcode-ability.md). diff --git a/en/application-dev/reference/apis-basic-services-kit/js-apis-battery-info-sys.md b/en/application-dev/reference/apis-basic-services-kit/js-apis-battery-info-sys.md index 912e10941dd..681fb956a0c 100644 --- a/en/application-dev/reference/apis-basic-services-kit/js-apis-battery-info-sys.md +++ b/en/application-dev/reference/apis-basic-services-kit/js-apis-battery-info-sys.md @@ -40,11 +40,11 @@ Sets the battery configuration based on the specified scenario. **Error codes** -For details about the error codes, see [Battery Information Error Codes](errorcode-battery-info.md). +For details about the error codes, see [Battery Info Error Codes](errorcode-battery-info.md) and [Universal Error Codes](../errorcode-universal.md). | ID | Error Message | |---------|---------| -| 4900101 | Failed to connect to the service. | +| 5100101 | Failed to connect to the service. | | 401 | Parameter error. Possible causes: 1.Incorrect parameter types. | | 202 | Permission verification failed. A non-system application calls a system API. | @@ -84,11 +84,11 @@ Obtains the battery configuration based on the specified scenario. **Error codes** -For details about the error codes, see [Battery Information Error Codes](errorcode-battery-info.md). +For details about the error codes, see [Battery Info Error Codes](errorcode-battery-info.md) and [Universal Error Codes](../errorcode-universal.md). | ID | Error Message | |---------|---------| -| 4900101 | Failed to connect to the service. | +| 5100101 | Failed to connect to the service. | | 401 | Parameter error. Possible causes: 1.Incorrect parameter types. | | 202 | Permission verification failed. A non-system application calls a system API. | @@ -127,11 +127,11 @@ Checks whether the battery configuration is enabled based on the specified scena **Error codes** -For details about the error codes, see [Battery Information Error Codes](errorcode-battery-info.md). +For details about the error codes, see [Battery Info Error Codes](errorcode-battery-info.md) and [Universal Error Codes](../errorcode-universal.md). | ID | Error Message | |---------|---------| -| 4900101 | Failed to connect to the service. | +| 5100101 | Failed to connect to the service. | | 401 | Parameter error. Possible causes: 1.Incorrect parameter types. | | 202 | Permission verification failed. A non-system application calls a system API. | @@ -146,13 +146,13 @@ For details about the error codes, see [Battery Information Error Codes](errorco console.info("The result is: " + result); ``` -## Attributes +## Properties Describes battery information. **System capability**: SystemCapability.PowerManager.BatteryManager.Core -| Name | Type | Readable| Writable| Description | +| Name | Type | Read-Only| Optional| Description | | --------------- | ------------------- | ---- | ---- | ---------------------| | estimatedRemainingChargeTime9+ | number | Yes | No | Estimated time for fully charging the current device, in unit of milliseconds. This is a system API. | | totalEnergy9+ | number | Yes | No | Total battery capacity of the device, in unit of mAh. This is a system API. | diff --git a/en/application-dev/reference/apis-basic-services-kit/js-apis-battery-info.md b/en/application-dev/reference/apis-basic-services-kit/js-apis-battery-info.md index 092c737c2dc..64d33a7018e 100644 --- a/en/application-dev/reference/apis-basic-services-kit/js-apis-battery-info.md +++ b/en/application-dev/reference/apis-basic-services-kit/js-apis-battery-info.md @@ -19,7 +19,7 @@ Describes battery information. **System capability**: SystemCapability.PowerManager.BatteryManager.Core -| Name | Type | Readable| Writable| Description | +| Name | Type | Read-Only| Optional| Description | | --------------- | ------------------- | ---- | ---- | ---------------------| | batterySOC | number | Yes | No | Battery state of charge (SoC) of the device, in unit of percentage.
**Atomic service API**: This API can be used in atomic services since API version 12. | | chargingStatus | [BatteryChargeState](#batterychargestate) | Yes | No | Battery charging state of the current device.
**Atomic service API**: This API can be used in atomic services since API version 12. | @@ -28,9 +28,9 @@ Describes battery information. | voltage | number | Yes | No | Battery voltage of the device, in unit of microvolt. | | technology | string | Yes | No | Battery technology of the device. | | batteryTemperature | number | Yes | No | Battery temperature of the device, in unit of 0.1°C. | -| isBatteryPresent7+ | boolean | Yes | No | Whether the battery is supported or present. | -| batteryCapacityLevel9+ | [BatteryCapacityLevel](#batterycapacitylevel9) | Yes | No | Battery level of the device. -| nowCurrent12+ | number | Yes | No | Battery current of the device, in unit of mA. | +| isBatteryPresent7+ | boolean | Yes | No | Whether the battery is supported or present. The value **true** means that the battery is supported or present; **false** means the opposite.
Default value: **false**. | +| batteryCapacityLevel9+ | [BatteryCapacityLevel](#batterycapacitylevel9) | Yes | No | Battery level of the device. | +| nowCurrent12+ | number | Yes | No | Battery current of the device, in unit of mA. | **Example** diff --git a/en/application-dev/reference/apis-basic-services-kit/js-apis-batteryStatistics-sys.md b/en/application-dev/reference/apis-basic-services-kit/js-apis-batteryStatistics-sys.md index 029324921a2..95d01c33330 100644 --- a/en/application-dev/reference/apis-basic-services-kit/js-apis-batteryStatistics-sys.md +++ b/en/application-dev/reference/apis-basic-services-kit/js-apis-batteryStatistics-sys.md @@ -32,7 +32,7 @@ Obtains the power consumption information list. This API uses a promise to retur **Error codes** -For details about the error codes, see [Thermal Manager Error Codes](errorcode-batteryStatistics.md). +For details about the error codes, see [Power Consumption Statistics Error Codes](errorcode-batteryStatistics.md) and [Universal Error Codes](../errorcode-universal.md). | Code | Error Message | |---------|---------| @@ -69,7 +69,7 @@ Obtains the power consumption information list. This API uses an asynchronous ca **Error codes** -For details about the error codes, see [Thermal Manager Error Codes](errorcode-batteryStatistics.md). +For details about the error codes, see [Power Consumption Statistics Error Codes](errorcode-batteryStatistics.md) and [Universal Error Codes](../errorcode-universal.md). | Code | Error Message | |---------|---------| @@ -113,7 +113,7 @@ Obtains the power consumption of an application. **Error codes** -For details about the error codes, see [Thermal Manager Error Codes](errorcode-batteryStatistics.md). +For details about the error codes, see [Power Consumption Statistics Error Codes](errorcode-batteryStatistics.md) and [Universal Error Codes](../errorcode-universal.md). | Code | Error Message | |---------|---------| @@ -156,7 +156,7 @@ Obtains the proportion of the power consumption of an application. **Error codes** -For details about the error codes, see [Thermal Manager Error Codes](errorcode-batteryStatistics.md). +For details about the error codes, see [Power Consumption Statistics Error Codes](errorcode-batteryStatistics.md) and [Universal Error Codes](../errorcode-universal.md). | Code | Error Message | |---------|---------| @@ -199,7 +199,7 @@ Obtains the power consumption of a hardware unit according to the consumption ty **Error codes** -For details about the error codes, see [Thermal Manager Error Codes](errorcode-batteryStatistics.md). +For details about the error codes, see [Power Consumption Statistics Error Codes](errorcode-batteryStatistics.md) and [Universal Error Codes](../errorcode-universal.md). | Code | Error Message | |---------|---------| @@ -242,7 +242,7 @@ Obtains the proportion of the power consumption of a hardware unit according to **Error codes** -For details about the error codes, see [Thermal Manager Error Codes](errorcode-batteryStatistics.md). +For details about the error codes, see [Power Consumption Statistics Error Codes](errorcode-batteryStatistics.md) and [Universal Error Codes](../errorcode-universal.md). | Code | Error Message | |---------|---------| @@ -271,7 +271,7 @@ Describes the device power consumption information. ### Attributes -| Name | Type | Readable| Writable| Description | +| Name | Type | Read-Only| Optional| Description | | ----- | ----------------------------------- | ---- | ---- | ---------------------- | | uid | number | Yes | No | UID related to power consumption information. | | type | [ConsumptionType](#consumptiontype) | Yes | No | Power consumption type. | diff --git a/en/application-dev/reference/apis-basic-services-kit/js-apis-brightness-sys.md b/en/application-dev/reference/apis-basic-services-kit/js-apis-brightness-sys.md index 58461538f29..5d2762df07c 100644 --- a/en/application-dev/reference/apis-basic-services-kit/js-apis-brightness-sys.md +++ b/en/application-dev/reference/apis-basic-services-kit/js-apis-brightness-sys.md @@ -32,7 +32,7 @@ Sets the screen brightness. **Error codes** -For details about the error codes, see [Screen Brightness Error Codes](errorcode-brightness.md). +For details about the error codes, see [Brightness Error Codes](errorcode-brightness.md) and [Universal Error Codes](../errorcode-universal.md). | ID | Error Message | |---------|---------| @@ -64,12 +64,12 @@ Sets the screen brightness. This API is used for continuous brightness adjustmen | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ----------------------- | -| value | number | Yes | Brightness value. Value range: 0 to 255. The value of this parameter must be a number.| -| continuous | boolean | Yes | Whether the luminance adjustment is continuous. The value of this parameter must be of the Boolean type.| +| value | number | Yes | Brightness value. Value range: [0, 255]| +| continuous | boolean | Yes | Whether the brightness adjustment is continuous. The value **true** indicates that the brightness adjustment is continuous; **false** indicates the opposite. Default value: **false**| **Error codes** -For details about the error codes, see [Screen Brightness Error Codes](errorcode-brightness.md). +For details about the error codes, see [Brightness Error Codes](errorcode-brightness.md) and [Universal Error Codes](../errorcode-universal.md). | ID | Error Message | |---------|---------| diff --git a/en/application-dev/reference/apis-basic-services-kit/js-apis-commonEventManager-sys.md b/en/application-dev/reference/apis-basic-services-kit/js-apis-commonEventManager-sys.md index 92c6156ba56..1cf404b7e1b 100644 --- a/en/application-dev/reference/apis-basic-services-kit/js-apis-commonEventManager-sys.md +++ b/en/application-dev/reference/apis-basic-services-kit/js-apis-commonEventManager-sys.md @@ -45,7 +45,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ----------------------------------- | | 202 | not system app. | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified.
2. Incorrect parameter types.
3. Parameter verification failed. | +| 1500003 | The common event sending frequency too high. | | 1500007 | Failed to send the message to the common event service. | | 1500008 | Failed to initialize the common event service. | | 1500009 | Failed to obtain system parameters. | @@ -99,7 +99,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ----------------------------------- | | 202 | not system app. | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified.
2. Incorrect parameter types.
3. Parameter verification failed. | +| 1500003 | The common event sending frequency too high. | | 1500007 | Failed to send the message to the common event service. | | 1500008 | Failed to initialize the common event service. | | 1500009 | Failed to obtain system parameters. | diff --git a/en/application-dev/reference/apis-basic-services-kit/js-apis-commonEventManager.md b/en/application-dev/reference/apis-basic-services-kit/js-apis-commonEventManager.md index ddbd448654c..50d7835a059 100644 --- a/en/application-dev/reference/apis-basic-services-kit/js-apis-commonEventManager.md +++ b/en/application-dev/reference/apis-basic-services-kit/js-apis-commonEventManager.md @@ -38,8 +38,8 @@ Publishes a common event. This API uses an asynchronous callback to return the r For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Event Error Codes](./errorcode-CommonEventService.md). | ID| Error Message | -| -------- | ----------------------------------- | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified.
2. Incorrect parameter types.
3. Parameter verification failed. | +| -------- | ----------------------------------- | +| 1500003 | The common event sending frequency too high. | | 1500007 | Failed to send the message to the common event service. | | 1500008 | Failed to initialize the common event service. | | 1500009 | Failed to obtain system parameters. | @@ -80,7 +80,7 @@ Publishes a common event. This API uses an asynchronous callback to return the r | -------- | ---------------------- | ---- | ---------------------- | | event | string | Yes | Name of the common event to publish. For details, see [System Common Events](./common_event/commonEventManager-definitions.md). | | options | [CommonEventPublishData](./js-apis-inner-commonEvent-commonEventPublishData.md) | Yes | Attributes of the common event to publish.| -| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object. | **Error codes** @@ -88,7 +88,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ----------------------------------- | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified.
2. Incorrect parameter types.
3. Parameter verification failed. | +| 1500003 | The common event sending frequency too high. | | 1500007 | Failed to send the message to the common event service. | | 1500008 | Failed to initialize the common event service. | | 1500009 | Failed to obtain system parameters. | @@ -143,7 +143,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ----------------------------------- | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified.
2. Incorrect parameter types.
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified.
2. Incorrect parameter types.
3. Parameter verification failed. | **Example** @@ -201,7 +201,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ----------------------------------- | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified.
2. Incorrect parameter types.
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified.
2. Incorrect parameter types.
3. Parameter verification failed. | **Example** @@ -250,7 +250,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ----------------------------------- | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified.
2. Incorrect parameter types.
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified.
2. Incorrect parameter types.
3. Parameter verification failed. | **Example** @@ -295,10 +295,10 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ----------------------------------- | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified.
2. Incorrect parameter types.
3. Parameter verification failed. | | 801 | capability not supported. | | 1500007 | Failed to send the message to the common event service. | | 1500008 | Failed to initialize the common event service. | +| 1500010 | The count of subscriber exceed system specification. | **Example** @@ -365,7 +365,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ----------------------------------- | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified.
2. Incorrect parameter types.
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified.
2. Incorrect parameter types.
3. Parameter verification failed. | | 801 | capability not supported. | | 1500007 | Failed to send the message to the common event service. | | 1500008 | Failed to initialize the common event service. | @@ -431,6 +431,81 @@ setTimeout(() => { }, 500); ``` +## commonEventManager.subscribeToEvent20+ + +subscribeToEvent(subscriber: CommonEventSubscriber, callback: Callback\): Promise\ + +Subscribes to common events. This API uses a promise to return the result, indicating subscription success or failure. 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.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ---------------------------------------------------- | ---- | -------------------------------- | +| subscriber | [CommonEventSubscriber](./js-apis-inner-commonEvent-commonEventSubscriber.md) | Yes | Subscriber object. | +| callback | Callback\<[CommonEventData](./js-apis-inner-commonEvent-commonEventData.md)> | Yes | Callback to be invoked when a common event is subscribed to.| + +**Return value** +| Type | Description | +| --------------------------------------------------------- | ---------------- | +| Promise\ | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Event Error Codes](./errorcode-CommonEventService.md). + +| ID| Error Message | +| -------- | ----------------------------------- | +| 801 | Capability not supported. | +| 1500007 | Failed to send the message to the common event service. | +| 1500008 | Failed to initialize the common event service. | +| 1500010 | The count of subscriber exceed system specification. | + +**Example** + +```ts +import { BusinessError } from '@kit.BasicServicesKit'; + +// Define a subscriber to save the created subscriber object for subsequent subscription and unsubscription. +let subscriber: commonEventManager.CommonEventSubscriber; +// Attributes of a subscriber. +let subscribeInfo: commonEventManager.CommonEventSubscribeInfo = { + events: ["event"] +}; + +// Create a subscriber. +try { + commonEventManager.createSubscriber(subscribeInfo, + (err: BusinessError, commonEventSubscriber: commonEventManager.CommonEventSubscriber) => { + if (err) { + console.error(`Failed to create subscriber. Code is ${err.code}, message is ${err.message}`); + } else { + console.info(`Succeeded in creating subscriber.`); + subscriber = commonEventSubscriber; + // Subscribe to a common event. + try { + commonEventManager.subscribeToEvent(subscriber, (data: commonEventManager.CommonEventData) => { + console.info(`Succeeded to receive common event, data is ` + JSON.stringify(data)); + }).then(() => { + console.info(`Succeeded to subscribe.`); + }).catch((err: BusinessError) => { + console.error(`Failed to subscribe. Code is ${err.code}, message is ${err.message}`); + }); + } catch (error) { + let err: BusinessError = error as BusinessError; + console.error(`Failed to subscribe. Code is ${err.code}, message is ${err.message}`); + } + } + }); +} catch (error) { + let err: BusinessError = error as BusinessError; + console.error(`Failed to create subscriber. Code is ${err.code}, message is ${err.message}`); +} +``` + ## CommonEventData10+ type CommonEventData = _CommonEventData diff --git a/en/application-dev/reference/apis-basic-services-kit/js-apis-configPolicy-sys.md b/en/application-dev/reference/apis-basic-services-kit/js-apis-configPolicy-sys.md index 0a2781b39fa..80dbe1e6ab9 100644 --- a/en/application-dev/reference/apis-basic-services-kit/js-apis-configPolicy-sys.md +++ b/en/application-dev/reference/apis-basic-services-kit/js-apis-configPolicy-sys.md @@ -36,7 +36,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | ------- | ---------------------------------------------------------------------------- | -| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.| +| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.| **Example** @@ -49,13 +49,13 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ if (error == null) { console.log('value is ' + value); } else { - console.log('error occurs ' + error); + console.error('error: ' + error.code + ', ' + error.message); } }); } catch (error) { let code = (error as BusinessError).code; let message = (error as BusinessError).message; - console.log('error:' + code + ',' + message); + console.error('error:' + code + ', ' + message); } ``` @@ -79,7 +79,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | ------- | ---------------------------------------------------------------------------- | -| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.| +| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.| **Return value** @@ -97,12 +97,12 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ configPolicy.getOneCfgFile(relpath).then((value: string) => { console.log('value is ' + value); }).catch((error: BusinessError) => { - console.log('getOneCfgFile promise ' + error); + console.error('getOneCfgFile promise error: ' + error.code + ', ' + error.message); }); } catch (error) { let code = (error as BusinessError).code; let message = (error as BusinessError).message; - console.log('error:' + code + ',' + message); + console.error('error:' + code + ', ' + message); } ``` @@ -120,7 +120,7 @@ If there are two **config.xml** files, **/system/etc/config.xml** and **/sys_pod | Name | Type | Mandatory| Description | | -------- | ---------------------------------------- | ---- | -------------------------- | | relPath | string | Yes | Name of the configuration file. | -| callback | AsyncCallback<Array<string>> | Yes | Callback used to return the file list.| +| callback | AsyncCallback<Array<string>> | Yes | Callback used to return the file lists.| **Error codes** @@ -128,7 +128,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | ------- | ---------------------------------------------------------------------------- | -| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.| +| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.| **Example** @@ -140,13 +140,13 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ if (error == null) { console.log('value is ' + value); } else { - console.log('error occurs ' + error); + console.error('error: ' + error.code + ', ' + error.message); } }); } catch (error) { let code = (error as BusinessError).code; let message = (error as BusinessError).message; - console.log('error:' + code + ',' + message); + console.error('error:' + code + ', ' + message); } ``` @@ -170,13 +170,13 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | ------- | ---------------------------------------------------------------------------- | -| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.| +| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.| **Return value** | Type | Description | | ---------------------------------- | -------- | -| Promise<Array<string>> | Promise used to return the file list.| +| Promise<Array<string>> | Promise used to return the file lists.| **Example** @@ -188,12 +188,12 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ configPolicy.getCfgFiles(relpath).then((value: Array) => { console.log('value is ' + value); }).catch((error: BusinessError) => { - console.log('getCfgFiles promise ' + error); + console.error('getCfgFiles promise error: ' + error.code + ', ' + error.message); }); } catch (error) { let code = (error as BusinessError).code; let message = (error as BusinessError).message; - console.log('error:' + code + ',' + message); + console.error('error:' + code + ', ' + message); } ``` @@ -217,7 +217,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | ------- | ---------------------------------------------------------------------------- | -| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.| +| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.| **Example** @@ -229,13 +229,13 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ if (error == null) { console.log('value is ' + value); } else { - console.log('error occurs ' + error); + console.error('error: ' + error.code + ', ' + error.message); } }); } catch (error) { let code = (error as BusinessError).code; let message = (error as BusinessError).message; - console.log('error:' + code + ',' + message); + console.error('error:' + code + ', ' + message); } ``` @@ -251,7 +251,7 @@ Obtains the list of configuration level directories. This API uses a promise to | Type | Description | | ---------------------------------- | ---------------- | -| Promise<Array<string>> | Promise used to return the configuration level directory list.| +| Promise<Array<string>> | Obtains the list of configuration level directories. This API returns the result synchronously.| **Example** @@ -262,12 +262,12 @@ Obtains the list of configuration level directories. This API uses a promise to configPolicy.getCfgDirList().then((value: Array) => { console.log('value is ' + value); }).catch((error: BusinessError) => { - console.log('getCfgDirList promise ' + error); + console.error('getCfgDirList promise error: ' + error.code + ', ' + error.message); }); } catch (error) { let code = (error as BusinessError).code; let message = (error as BusinessError).message; - console.log('error:' + code + ',' + message); + console.error('error:' + code + ', ' + message); } ``` @@ -294,7 +294,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | ------- | ---------------------------------------------------------------------------- | -| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.| +| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.| **Example** @@ -308,13 +308,13 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ if (error == null) { console.log('value is ' + value); } else { - console.log('error occurs ' + error); + console.error('error: ' + error.code + ', ' + error.message); } }); } catch (error) { let code = (error as BusinessError).code; let message = (error as BusinessError).message; - console.log('error:' + code + ',' + message); + console.error('error:' + code + ', ' + message); } ``` @@ -322,7 +322,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ getOneCfgFile(relPath: string, followMode: FollowXMode, extra: string, callback: AsyncCallback<string>) -Obtains the path of the configuration file with the highest priority based on the specified file name and custom follow rule. This API uses an asynchronous callback to return the result. +Obtains the path of the configuration file with the highest priority based on the specified file name and follow mode. This API uses an asynchronous callback to return the result. For example, there are three **config.xml** files (in ascending order of priority): **/system/etc/config.xml**, **/sys_pod/etc/config.xml**, and **/sys_pod/etc/carrier/46060/etc/config.xml**. If the opkey of card 1 is **46060**, the follow mode is **USER_DEFINED**, and the custom follow rule is **etc/carrier/${telephony.sim.opkey0}**, **/sys_pod/etc/carrier/46060/etc/config.xml** is returned. **System capability**: SystemCapability.Customization.ConfigPolicy @@ -342,7 +342,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | ------- | ---------------------------------------------------------------------------- | -| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.| +| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.| **Example** @@ -357,13 +357,13 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ if (error == null) { console.log('value is ' + value); } else { - console.log('error occurs ' + error); + console.error('error: ' + error.code + ', ' + error.message); } }); } catch (error) { let code = (error as BusinessError).code; let message = (error as BusinessError).message; - console.log('error:' + code + ',' + message); + console.error('error:' + code + ', ' + message); } ``` @@ -389,7 +389,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | ------- | ---------------------------------------------------------------------------- | -| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3.Parameter verification failed.| +| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3.Parameter verification failed.| **Return value** @@ -408,12 +408,12 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ configPolicy.getOneCfgFile(relpath, configPolicy.FollowXMode.SIM_DEFAULT, extra).then((value: string) => { console.log('value is ' + value); }).catch((error: BusinessError) => { - console.log('getOneCfgFile promise ' + error); + console.error('getOneCfgFile promise error: ' + error.code + ', ' + error.message); }); } catch (error) { let code = (error as BusinessError).code; let message = (error as BusinessError).message; - console.log('error:' + code + ',' + message); + console.error('error:' + code + ', ' + message); } ``` @@ -439,13 +439,13 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | ------- | ---------------------------------------------------------------------------- | -| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3.Parameter verification failed.| +| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3.Parameter verification failed.| **Return value** | Type | Description | | ------ | ------------------------ | -| string | Promise used to return the path of the configuration file.| +| string | Returns the path of the configuration file.| **Example** @@ -461,7 +461,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ } catch (error) { let code = (error as BusinessError).code; let message = (error as BusinessError).message; - console.log('error:' + code + ',' + message); + console.error('error:' + code + ', ' + message); } ``` @@ -480,7 +480,7 @@ For example, there are three **config.xml** files (in ascending order of priorit | ---------- | ---------------------------------------- | ---- | -------------------------- | | relPath | string | Yes | Name of the configuration file. | | followMode | [FollowXMode](#followxmode11) | Yes | Follow mode. | -| callback | AsyncCallback<Array<string>> | Yes | Callback used to return the file list.| +| callback | AsyncCallback<Array<string>> | Yes | Callback used to return the file lists.| **Error codes** @@ -488,7 +488,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | ------- | ---------------------------------------------------------------------------- | -| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.| +| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.| **Example** @@ -502,13 +502,13 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ if (error == null) { console.log('value is ' + value); } else { - console.log('error occurs ' + error); + console.error('error: ' + error.code + ', ' + error.message); } }); } catch (error) { let code = (error as BusinessError).code; let message = (error as BusinessError).message; - console.log('error:' + code + ',' + message); + console.error('error:' + code + ', ' + message); } ``` @@ -528,7 +528,7 @@ For example, there are three **config.xml** files (in ascending order of priorit | relPath | string | Yes | Name of the configuration file. | | followMode | [FollowXMode](#followxmode11) | Yes | Follow mode. | | extra | string | Yes | Custom follow rule. This parameter is valid only when **followMode** is set to **USER_DEFINED**.| -| callback | AsyncCallback<Array<string>> | Yes | Callback used to return the file list. | +| callback | AsyncCallback<Array<string>> | Yes | Callback used to return the file lists. | **Error codes** @@ -536,7 +536,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | ------- | ---------------------------------------------------------------------------- | -| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.| +| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.| **Example** @@ -551,13 +551,13 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ if (error == null) { console.log('value is ' + value); } else { - console.log('error occurs ' + error); + console.error('error: ' + error.code + ', ' + error.message); } }); } catch (error) { let code = (error as BusinessError).code; let message = (error as BusinessError).message; - console.log('error:' + code + ',' + message); + console.error('error:' + code + ', ' + message); } ``` @@ -583,13 +583,13 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | ------- | ---------------------------------------------------------------------------- | -| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3.Parameter verification failed.| +| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3.Parameter verification failed.| **Return value** | Type | Description | | ---------------------------------- | -------- | -| Promise<Array<string>> | Promise used to return the file list.| +| Promise<Array<string>> | Promise used to return the file lists.| **Example** @@ -602,12 +602,12 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ configPolicy.getCfgFiles(relpath, configPolicy.FollowXMode.SIM_DEFAULT, extra).then((value: Array) => { console.log('value is ' + value); }).catch((error: BusinessError) => { - console.log('getCfgFiles promise ' + error); + console.error('getCfgFiles promise error: ' + error.code + ', ' + error.message); }); } catch (error) { let code = (error as BusinessError).code; let message = (error as BusinessError).message; - console.log('error:' + code + ',' + message); + console.error('error:' + code + ', ' + message); } ``` @@ -633,13 +633,13 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | ------- | ---------------------------------------------------------------------------- | -| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3.Parameter verification failed.| +| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3.Parameter verification failed.| **Return value** | Type | Description | | ------------------- | -------- | -| Array<string> | Promise used to return the file list.| +| Array<string> | Returns the file lists.| **Example** @@ -655,7 +655,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ } catch (error) { let code = (error as BusinessError).code; let message = (error as BusinessError).message; - console.log('error:' + code + ',' + message); + console.error('error:' + code + ', ' + message); } ``` @@ -671,7 +671,7 @@ Obtains the list of configuration level directories. This API returns the result | Type | Description | | ------------------- | ---------------- | -| Array<string> | Promise used to return the configuration level directory list.| +| Array<string> | Obtains the list of configuration level directories. This API returns the result synchronously.| **Example** @@ -685,7 +685,7 @@ Obtains the list of configuration level directories. This API returns the result } catch (error) { let code = (error as BusinessError).code; let message = (error as BusinessError).message; - console.log('error:' + code + ',' + message); + console.error('error:' + code + ', ' + message); } ``` diff --git a/en/application-dev/reference/apis-basic-services-kit/js-apis-date-time.md b/en/application-dev/reference/apis-basic-services-kit/js-apis-date-time.md index 44bd318e666..9b4d2fd0b76 100644 --- a/en/application-dev/reference/apis-basic-services-kit/js-apis-date-time.md +++ b/en/application-dev/reference/apis-basic-services-kit/js-apis-date-time.md @@ -58,14 +58,14 @@ import { BusinessError } from '@kit.BasicServicesKit'; try { systemDateTime.getCurrentTime(true, (error: BusinessError, time: number) => { if (error) { - console.info(`Failed to get currentTime. message: ${error.message}, code: ${error.code}`); + console.error(`Failed to get currentTime. message: ${error.message}, code: ${error.code}`); return; } console.info(`Succeeded in getting currentTime : ${time}`); }); } catch(e) { let error = e as BusinessError; - console.info(`Failed to get currentTime. message: ${error.message}, code: ${error.code}`); + console.error(`Failed to get currentTime. message: ${error.message}, code: ${error.code}`); } ``` @@ -103,14 +103,14 @@ import { BusinessError } from '@kit.BasicServicesKit'; try { systemDateTime.getCurrentTime((error: BusinessError, time: number) => { if (error) { - console.info(`Failed to get currentTime. message: ${error.message}, code: ${error.code}`); + console.error(`Failed to get currentTime. message: ${error.message}, code: ${error.code}`); return; } console.info(`Succeeded in getting currentTime : ${time}`); }); } catch(e) { let error = e as BusinessError; - console.info(`Failed to get currentTime. message: ${error.message}, code: ${error.code}`); + console.error(`Failed to get currentTime. message: ${error.message}, code: ${error.code}`); } ``` @@ -155,11 +155,11 @@ try { systemDateTime.getCurrentTime().then((time: number) => { console.info(`Succeeded in getting currentTime : ${time}`); }).catch((error: BusinessError) => { - console.info(`Failed to get currentTime. message: ${error.message}, code: ${error.code}`); + console.error(`Failed to get currentTime. message: ${error.message}, code: ${error.code}`); }); } catch(e) { let error = e as BusinessError; - console.info(`Failed to get currentTime. message: ${error.message}, code: ${error.code}`); + console.error(`Failed to get currentTime. message: ${error.message}, code: ${error.code}`); } ``` @@ -198,14 +198,14 @@ import { BusinessError } from '@kit.BasicServicesKit'; try { systemDateTime.getRealActiveTime(true, (error: BusinessError, time: number) => { if (error) { - console.info(`Failed to get real active time. message: ${error.message}, code: ${error.code}`); + console.error(`Failed to get real active time. message: ${error.message}, code: ${error.code}`); return; } console.info(`Succeeded in getting real active time : ${time}`); }); } catch(e) { let error = e as BusinessError; - console.info(`Failed to get real active time. message: ${error.message}, code: ${error.code}`); + console.error(`Failed to get real active time. message: ${error.message}, code: ${error.code}`); } ``` @@ -243,14 +243,14 @@ import { BusinessError } from '@kit.BasicServicesKit'; try { systemDateTime.getRealActiveTime((error: BusinessError, time: number) => { if (error) { - console.info(`Failed to get real active time. message: ${error.message}, code: ${error.code}`); + console.error(`Failed to get real active time. message: ${error.message}, code: ${error.code}`); return; } console.info(`Succeeded in getting real active time : ${time}`); }); } catch(e) { let error = e as BusinessError; - console.info(`Failed to get real active time. message: ${error.message}, code: ${error.code}`); + console.error(`Failed to get real active time. message: ${error.message}, code: ${error.code}`); } ``` @@ -295,11 +295,11 @@ try { systemDateTime.getRealActiveTime().then((time: number) => { console.info(`Succeeded in getting real active time : ${time}`); }).catch((error: BusinessError) => { - console.info(`Failed to get real active time. message: ${error.message}, code: ${error.code}`); + console.error(`Failed to get real active time. message: ${error.message}, code: ${error.code}`); }); } catch(e) { let error = e as BusinessError; - console.info(`Failed to get real active time. message: ${error.message}, code: ${error.code}`); + console.error(`Failed to get real active time. message: ${error.message}, code: ${error.code}`); } ``` @@ -338,14 +338,14 @@ import { BusinessError } from '@kit.BasicServicesKit'; try { systemDateTime.getRealTime(true, (error: BusinessError, time: number) => { if (error) { - console.info(`Failed to get real time. message: ${error.message}, code: ${error.code}`); + console.error(`Failed to get real time. message: ${error.message}, code: ${error.code}`); return; } console.info(`Succeeded in getting real time : ${time}`); }); } catch(e) { let error = e as BusinessError; - console.info(`Failed to get real time. message: ${error.message}, code: ${error.code}`); + console.error(`Failed to get real time. message: ${error.message}, code: ${error.code}`); } ``` @@ -383,14 +383,14 @@ import { BusinessError } from '@kit.BasicServicesKit'; try { systemDateTime.getRealTime((error: BusinessError, time: number) => { if (error) { - console.info(`Failed to get real time. message: ${error.message}, code: ${error.code}`); + console.error(`Failed to get real time. message: ${error.message}, code: ${error.code}`); return; } console.info(`Succeeded in getting real time : ${time}`); }); } catch(e) { let error = e as BusinessError; - console.info(`Failed to get real time. message: ${error.message}, code: ${error.code}`); + console.error(`Failed to get real time. message: ${error.message}, code: ${error.code}`); } ``` @@ -435,11 +435,11 @@ try { systemDateTime.getRealTime().then((time: number) => { console.info(`Succeeded in getting real time : ${time}`); }).catch((error: BusinessError) => { - console.info(`Failed to get real time. message: ${error.message}, code: ${error.code}`); + console.error(`Failed to get real time. message: ${error.message}, code: ${error.code}`); }); } catch(e) { let error = e as BusinessError; - console.info(`Failed to get real time. message: ${error.message}, code: ${error.code}`); + console.error(`Failed to get real time. message: ${error.message}, code: ${error.code}`); } ``` @@ -472,7 +472,7 @@ try { let time = systemDateTime.getTime(true) } catch(e) { let error = e as BusinessError; - console.info(`Failed to get time. message: ${error.message}, code: ${error.code}`); + console.error(`Failed to get time. message: ${error.message}, code: ${error.code}`); } ``` @@ -503,7 +503,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- |----------------------------------------------------------------------------------------------------------------| -| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3.Parameter verification failed. This error code was added due to missing issues. | +| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3.Parameter verification
failed.This error code was added due to missing issues. | **Example** @@ -514,7 +514,7 @@ try { let time = systemDateTime.getUptime(systemDateTime.TimeType.ACTIVE, false); } catch(e) { let error = e as BusinessError; - console.info(`Failed to get uptime. message: ${error.message}, code: ${error.code}`); + console.error(`Failed to get uptime. message: ${error.message}, code: ${error.code}`); } ``` @@ -552,14 +552,14 @@ import { BusinessError } from '@kit.BasicServicesKit'; try { systemDateTime.getDate((error: BusinessError, date: Date) => { if (error) { - console.info(`Failed to get date. message: ${error.message}, code: ${error.code}`); + console.error(`Failed to get date. message: ${error.message}, code: ${error.code}`); return; } console.info(`Succeeded in getting date : ${date}`);; }); } catch(e) { let error = e as BusinessError; - console.info(`Failed to get date. message: ${error.message}, code: ${error.code}`); + console.error(`Failed to get date. message: ${error.message}, code: ${error.code}`); } ``` @@ -598,11 +598,11 @@ try { systemDateTime.getDate().then((date: Date) => { console.info(`Succeeded in getting date : ${date}`); }).catch((error: BusinessError) => { - console.info(`Failed to get date. message: ${error.message}, code: ${error.code}`); + console.error(`Failed to get date. message: ${error.message}, code: ${error.code}`); }); } catch(e) { let error = e as BusinessError; - console.info(`Failed to get date. message: ${error.message}, code: ${error.code}`); + console.error(`Failed to get date. message: ${error.message}, code: ${error.code}`); } ``` @@ -628,14 +628,14 @@ import { BusinessError } from '@kit.BasicServicesKit'; try { systemDateTime.getTimezone((error: BusinessError, data: string) => { if (error) { - console.info(`Failed to get timezone. message: ${error.message}, code: ${error.code}`); + console.error(`Failed to get timezone. message: ${error.message}, code: ${error.code}`); return; } console.info(`Succeeded in get timezone : ${data}`);; }); } catch(e) { let error = e as BusinessError; - console.info(`Failed to get timezone. message: ${error.message}, code: ${error.code}`); + console.error(`Failed to get timezone. message: ${error.message}, code: ${error.code}`); } ``` @@ -662,11 +662,11 @@ try { systemDateTime.getTimezone().then((data: string) => { console.info(`Succeeded in getting timezone: ${data}`); }).catch((error: BusinessError) => { - console.info(`Failed to get timezone. message: ${error.message}, code: ${error.code}`); + console.error(`Failed to get timezone. message: ${error.message}, code: ${error.code}`); }); } catch(e) { let error = e as BusinessError; - console.info(`Failed to get timezone. message: ${error.message}, code: ${error.code}`); + console.error(`Failed to get timezone. message: ${error.message}, code: ${error.code}`); } ``` @@ -693,7 +693,7 @@ try { let timezone = systemDateTime.getTimezoneSync(); } catch(e) { let error = e as BusinessError; - console.info(`Failed to get timezone. message: ${error.message}, code: ${error.code}`); + console.error(`Failed to get timezone. message: ${error.message}, code: ${error.code}`); } ``` diff --git a/en/application-dev/reference/apis-basic-services-kit/js-apis-device-info.md b/en/application-dev/reference/apis-basic-services-kit/js-apis-device-info.md index 476fe1fd6d8..e87dc6e7c6b 100644 --- a/en/application-dev/reference/apis-basic-services-kit/js-apis-device-info.md +++ b/en/application-dev/reference/apis-basic-services-kit/js-apis-device-info.md @@ -14,7 +14,7 @@ The **deviceInfo** module provides terminal device information query, which cann import { deviceInfo } from '@kit.BasicServicesKit'; ``` -## Attributes +## Constants > **NOTE** > Unless otherwise specified, the maximum data length is 96 bytes. @@ -22,46 +22,47 @@ import { deviceInfo } from '@kit.BasicServicesKit'; **Required permissions**: The items in the table below require different system capabilities. -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| deviceType | string | Yes| No| Device type. For details, see [deviceTypes tag](../../quick-start/module-configuration-file.md#devicetypes).
**Atomic service API**: This API can be used in atomic services since API version 11.
Example: wearable| -| manufacture | string | Yes| No| Device manufacturer.
Example: HUAWEI| -| brand | string | Yes| No| Device brand.
**Atomic service API**: This API can be used in atomic services since API version 11.
Example: HUAWEI| -| marketName | string | Yes| No| Marketing name.
Example: Mate XX | -| productSeries | string | Yes| No| Product series.
Example: TAS | -| productModel | string | Yes| No| Product model.
**Atomic service API**: This API can be used in atomic services since API version 11.
Example: TAS-AL00 | -| productModelAlias14+ | string | Yes| No| Product model alias.
**Atomic service API**: This API can be used in atomic services since API version 14.
Example: TAS-AL00| -| softwareModel | string | Yes| No| Software model.
Example: TAS-AL00 | -| hardwareModel | string | Yes| No| Hardware model.
Example: TASA00CVN1 | -| hardwareProfile(deprecated) | string | Yes| No| Hardware profile.
**NOTE**
This API is supported since API version 6 and deprecated since API version 9.
Example: default| -| serial | string | Yes| No| Device SN.
**NOTE**
The device SN can be used as the unique identifier of a device.
**Required permissions**: ohos.permission.sec.ACCESS_UDID
Example: The SN varies with the device.| -| bootloaderVersion | string | Yes| No| Bootloader version.
Example: bootloader| -| abiList | string | Yes| No| Application binary interface (Abi) list.
Example: arm64-v8a| -| securityPatchTag | string | Yes| No| Security patch tag.
Example: 2021/01/01 | -| displayVersion | string | Yes| No| Product version.
Example: XXX X.X.X.X | -| incrementalVersion | string | Yes| No| Incremental version.
Example: default| -| osReleaseType | string | Yes| No| OS release type. The options are as follows:
- **Canary**: Preliminary release open only to specific developers. This release does not promise API stability and may require tolerance of instability.
- **Beta**: Release open to all developers. This release does not promise API stability and may require tolerance of instability.
- **Release**: Official release open to all developers. This release promises that all APIs are stable.
Example: Canary/Beta/Release | -| osFullName | string | Yes| No| System version. The version number is in the format of **OpenHarmony-x.x.x.x**, where **x** is a digit.
**Atomic service API**: This API can be used in atomic services since API version 11.
Example: Openharmony-5.0.0.1 | -| majorVersion | number | Yes| No| Major version number, which increments with the main version. The value is the first digit in **osFullName**. You are advised to use **deviceInfo.majorVersion** instead of parsing **osFullName** to obtain the value, facilitating efficiency improvement.
Example: 5| -| seniorVersion | number | Yes| No| Senior version number, which increments with architecture and feature updates. The value is the second digit in **osFullName**. You are advised to use **deviceInfo.seniorVersion** instead of parsing **osFullName** to obtain the value, facilitating efficiency improvement.
Example: 0| -| featureVersion | number | Yes| No| Feature version number. The value is the third digit in **osFullName**. You are advised to use **deviceInfo.featureVersion** instead of parsing **osFullName** to obtain the value, facilitating efficiency improvement.
Example: 0| -| buildVersion | number | Yes| No| Build version number. The value is the fourth digit in **osFullName**. You are advised to use **deviceInfo.buildVersion** instead of parsing **osFullName** to obtain the value, facilitating efficiency improvement.
Example: 1| -| sdkApiVersion | number | Yes| No| SDK API version.
**Atomic service API**: This API can be used in atomic services since API version 14.
Example: 12| -| firstApiVersion | number | Yes| No| First API version.
Example: 3| -| versionId | string | Yes| No| Version ID. It consists of the following fields: **deviceType**, **manufacture**, **brand**, **productSeries**, **osFullName**, **productModel**, **softwareModel**, **sdkApiVersion**, **incrementalVersion**, and **buildType**.
Example: wearable/HUAWEI/HUAWEI/TAS/OpenHarmony-5.0.0.1/TAS-AL00/TAS-AL00/12/default/release:nolog| -| buildType | string | Yes| No| Build type.
Example: default| -| buildUser | string | Yes| No| Build user.
Example: default| -| buildHost | string | Yes| No| Build host.
Example: default| -| buildTime | string | Yes| No| Build time.
Example: default| -| buildRootHash | string | Yes| No| Build root hash.
Example: default| -| udid7+ | string | Yes| No| Device UDID.
**NOTE**
The data length is 65 bytes. The UDID can be used as the unique identifier of a device.
**Required permissions**: ohos.permission.sec.ACCESS_UDID
Example: 9D6AABD147XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXE5536412 | -| distributionOSName10+ | string | Yes| No| Distribution OS name. It is defined by the issuer..
Example: OpenHarmony| -| distributionOSVersion10+ | string | Yes| No| Distribution OS version. It is defined by the issuer..
Example: 5.0.0 | -| distributionOSApiVersion10+ | number| Yes| No| Distribution OS API version. It is defined by the issuer..
Example: 50001| -| distributionOSApiName13+ | string | Yes| No| Distribution OS API name. It is defined by the issuer..| -| distributionOSReleaseType10+ | string | Yes| No| Distribution OS release type. It is defined by the issuer..
Example: Release| -| ODID12+ | string | Yes| No|Open device identifier.
An ODID will be regenerated in the following scenarios:
Restore a phone to its factory settings.
Uninstall and reinstall all applications with the same **developerId** on one device.
An ODID is generated based on the following rules:
The value is generated based on the **groupId** parsed from the **developerId** in the signature information. As **groupId.developerId** is the rule, if no **groupId** exists, the **developerId** is used as the **groupId**.
Applications with the same **developerId** use the same ODID on one device.
Applications with different **developerId**s use different ODIDs on one device.
Applications with the same **developerId** use different ODIDs on different devices.
Applications with different **developerId**s use different ODIDs on different devices.
**NOTE**
The data length is 37 bytes.
Example: 1234a567-XXXX-XXXX-XXXX-XXXXXXXXXXXX| -| diskSN15+ | string | Yes| No| Disk SN.
**NOTE**
This field can be queried only on the 2-in-1 device. For other devices, the query result is empty.
**Required permissions**: ohos.permission.ACCESS_DISK_PHY_INFO
Example: 2502EM400567 | +| Name| Type| Read-Only| Description| +| -------- | -------- | -------- | -------- | +| deviceType | string | Yes| Device type. For details, see [deviceTypes tag](../../quick-start/module-configuration-file.md#devicetypes).
**Atomic service API**: This API can be used in atomic services since API version 11.
Example: wearable| +| manufacture | string | Yes| Device manufacturer.
Example: HUAWEI| +| brand | string | Yes| Device brand.
**Atomic service API**: This API can be used in atomic services since API version 11.
Example: HUAWEI| +| marketName | string | Yes| Marketing name.
Example: Mate XX | +| productSeries | string | Yes| Product series.
Example: TAS | +| productModel | string | Yes| Product model.
**Atomic service API**: This API can be used in atomic services since API version 11.
Example: TAS-AL00 | +| productModelAlias14+ | string | Yes| Product model alias.
**Atomic service API**: This API can be used in atomic services since API version 14.
Example: TAS-AL00| +| softwareModel | string | Yes| Software model.
Example: TAS-AL00 | +| hardwareModel | string | Yes| Hardware model.
Example: TASA00CVN1 | +| hardwareProfile(deprecated) | string | Yes| Hardware profile.
**NOTE**
This API is supported since API version 6 and deprecated since API version 9.
Example: default| +| serial | string | Yes| Device serial number (SN).
**NOTE**
The device SN can be used as the unique identifier of a device.
**Required permission**: ohos.permission.sec.ACCESS_UDID (for system applications and enterprise applications only)
Example: The SN varies with the device.| +| bootloaderVersion | string | Yes| Bootloader version.
Example: bootloader| +| abiList | string | Yes| Application binary interface (Abi) list.
Example: arm64-v8a| +| securityPatchTag | string | Yes| Security patch tag.
Example: 2021/01/01 | +| displayVersion | string | Yes| Product version.
Example: XXX X.X.X.X | +| incrementalVersion | string | Yes| Incremental version.
Example: default| +| osReleaseType | string | Yes| OS release type. The options are as follows:
- **Canary**: Preliminary release open only to specific developers. This release does not promise API stability and may require tolerance of instability.
- **Beta**: Release open to all developers. This release does not promise API stability and may require tolerance of instability.
- **Release**: Official release open to all developers. This release promises that all APIs are stable.
Example: Canary/Beta/Release | +| osFullName | string | Yes| System version. The version number is in the format of **OpenHarmony-x.x.x.x**, where **x** is a digit.
**Atomic service API**: This API can be used in atomic services since API version 11.
Example: Openharmony-5.0.0.1 | +| majorVersion | number | Yes| Major version number, which increments with the main version. The value is the first digit in **osFullName**. You are advised to use **deviceInfo.majorVersion** instead of parsing **osFullName** to obtain the value, facilitating efficiency improvement.
Example: 5| +| seniorVersion | number | Yes| Senior version number, which increments with architecture and feature updates. The value is the second digit in **osFullName**. You are advised to use **deviceInfo.seniorVersion** instead of parsing **osFullName** to obtain the value, facilitating efficiency improvement.
Example: 0| +| featureVersion | number | Yes| Feature version number. The value is the third digit in **osFullName**. You are advised to use **deviceInfo.featureVersion** instead of parsing **osFullName** to obtain the value, facilitating efficiency improvement.
Example: 0| +| buildVersion | number | Yes| Build version number. The value is the fourth digit in **osFullName**. You are advised to use **deviceInfo.buildVersion** instead of parsing **osFullName** to obtain the value, facilitating efficiency improvement.
Example: 1| +| sdkApiVersion | number | Yes| SDK API version.
**Atomic service API**: This API can be used in atomic services since API version 14.
Example: 12| +| firstApiVersion | number | Yes| First API version.
Example: 3| +| versionId | string | Yes| Version ID. It consists of the following fields: **deviceType**, **manufacture**, **brand**, **productSeries**, **osFullName**, **productModel**, **softwareModel**, **sdkApiVersion**, **incrementalVersion**, and **buildType**.
Example: wearable/HUAWEI/HUAWEI/TAS/OpenHarmony-5.0.0.1/TAS-AL00/TAS-AL00/12/default/release:nolog| +| buildType | string | Yes| Build type.
Example: default| +| buildUser | string | Yes| Build user.
Example: default| +| buildHost | string | Yes| Build host.
Example: default| +| buildTime | string | Yes| Build time.
Example: default| +| buildRootHash | string | Yes| Build root hash.
Example: default| +| udid7+ | string | Yes| Device UDID.
**NOTE**
The data length is 65 bytes. The UDID can be used as the unique identifier of a device.
**Required permission**: ohos.permission.sec.ACCESS_UDID (for system applications and enterprise applications only)
Example: 9D6AABD147XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXE5536412 | +| distributionOSName10+ | string | Yes| Distribution OS name. It is defined by the issuer.
Example: OpenHarmony| +| distributionOSVersion10+ | string | Yes| Distribution OS version. It is defined by the issuer.
Example: 5.0.0 | +| distributionOSApiVersion10+ | number| Yes| Distribution OS API version. It is defined by the issuer.
Example: 50001| +| distributionOSApiName13+ | string | Yes| Distribution OS API name. It is defined by the issuer.| +| distributionOSReleaseType10+ | string | Yes| Distribution OS release type. It is defined by the issuer.
Example: Release| +| ODID12+ | string | Yes|Open device identifier.
An ODID will be regenerated in the following scenarios:
Restore a phone to its factory settings.
Uninstall and reinstall all applications with the same **developerId** on one device.
An ODID is generated based on the following rules:
The value is generated based on the **groupId** parsed from the **developerId** in the signature information. As **groupId.developerId** is the rule, if no **groupId** exists, the **developerId** is used as the **groupId**.
Applications with the same **developerId** use the same ODID on one device.
Applications with different **developerId**s use different ODIDs on one device.
Applications with the same **developerId** use different ODIDs on different devices.
Applications with different **developerId**s use different ODIDs on different devices.
**NOTE**
The data length is 37 bytes.
Example: 1234a567-XXXX-XXXX-XXXX-XXXXXXXXXXXX| +| diskSN15+ | string | Yes| Disk SN.
**NOTE**
This field can be queried only on the 2-in-1 device. For other devices, the query result is empty.
**Required permissions**: ohos.permission.ACCESS_DISK_PHY_INFO
Example: 2502EM400567 | +| performanceClass19+ | [PerformanceClassLevel](#performanceclasslevel19) | Yes| Device capability level.| **Example** @@ -69,149 +70,215 @@ import { deviceInfo } from '@kit.BasicServicesKit'; import { deviceInfo } from '@kit.BasicServicesKit'; let deviceTypeInfo: string = deviceInfo.deviceType; - // Output: the value of the deviceType is: wearable + // Output: the value of the deviceType is :wearable console.info('the value of the deviceType is :' + deviceTypeInfo); let manufactureInfo: string = deviceInfo.manufacture; - // Output: the value of the manufactureInfo is: HUAWEI + // Output: the value of the manufacture is :HUAWEI console.info('the value of the manufactureInfo is :' + manufactureInfo); let brandInfo: string = deviceInfo.brand; - // Output: the value of the device brand is: HUAWEI + // Output: the value of the brand is :HUAWEI console.info('the value of the device brand is :' + brandInfo); let marketNameInfo: string = deviceInfo.marketName; - // Output: the value of the deviceInfo marketName is: Mate XX + // Output: the value of the marketName is :Mate XX console.info('the value of the deviceInfo marketName is :' + marketNameInfo); let productSeriesInfo: string = deviceInfo.productSeries; - // Output: the value of the deviceInfo productSeries is: TAS + // Output: the value of the productSeries is :TAS console.info('the value of the deviceInfo productSeries is :' + productSeriesInfo); let productModelInfo: string = deviceInfo.productModel; - // Output: the value of the deviceInfo productModel is: TAS-AL00 + // Output: the value of the productModel is :TAS-AL00 console.info('the value of the deviceInfo productModel is :' + productModelInfo); let productModelAliasInfo: string = deviceInfo.productModelAlias; console.info('the value of the deviceInfo productModelAlias is :' + productModelAliasInfo); let softwareModelInfo: string = deviceInfo.softwareModel; - // Output result: the value of the deviceInfo softwareModel is: TAS-AL00 + // Output: the value of the softwareModel is :TAS-AL00 console.info('the value of the deviceInfo softwareModel is :' + softwareModelInfo); let hardwareModelInfo: string = deviceInfo.hardwareModel; - // Output: the value of the deviceInfo hardwareModel is: TASA00CVN1 + // Output: the value of the hardwareModel is :TASA00CVN1 console.info('the value of the deviceInfo hardwareModel is :' + hardwareModelInfo); let serialInfo: string = deviceInfo.serial; - // Output: the value of the deviceInfo serial is: The serial number varies depending on the device. + // Output: the value of the serial is :The SN varies with the device. console.info('the value of the deviceInfo serial is :' + serialInfo); let bootloaderVersionInfo: string = deviceInfo.bootloaderVersion; - // Output: the value of the deviceInfo bootloaderVersion is: bootloader + // Output: the value of the bootloaderVersion is :bootloader console.info('the value of the deviceInfo bootloaderVersion is :' + bootloaderVersionInfo); let abiListInfo: string = deviceInfo.abiList; - // Output: the value of the deviceInfo abiList is: arm64-v8a + // Output: the value of the abiList is :arm64-v8a console.info('the value of the deviceInfo abiList is :' + abiListInfo); let securityPatchTagInfo: string = deviceInfo.securityPatchTag; - // Output: the value of the deviceInfo securityPatchTag is: 2021/01/01 + // Output: the value of the securityPatchTag is :2021/01/01 console.info('the value of the deviceInfo securityPatchTag is :' + securityPatchTagInfo); let displayVersionInfo: string = deviceInfo.displayVersion; - // Output: the value of the deviceInfo displayVersion is: XXX X.X.X.X + // Output: the value of the displayVersion is :XXX X.X.X.X console.info('the value of the deviceInfo displayVersion is :' + displayVersionInfo); let incrementalVersionInfo: string = deviceInfo.incrementalVersion; - // Output: the value of the deviceInfo incrementalVersion is: default + // Output: the value of the incrementalVersion is :default console.info('the value of the deviceInfo incrementalVersion is :' + incrementalVersionInfo); let osReleaseTypeInfo: string = deviceInfo.osReleaseType; - // Output: the value of the deviceInfo osReleaseType is: Release + // Output: the value of the osReleaseType is :Release console.info('the value of the deviceInfo osReleaseType is :' + osReleaseTypeInfo); let osFullNameInfo: string = deviceInfo.osFullName; - // Output: the value of the osFullName is: OpenHarmony-5.0.0.1 + // Output: the value of the osFullName is :OpenHarmony-5.0.0.1 console.info('the value of the deviceInfo osFullName is :' + osFullNameInfo); let majorVersionInfo: number = deviceInfo.majorVersion; - // Output: the value of the deviceInfo majorVersion is: 5 + // Output: the value of the majorVersion is :5 console.info('the value of the deviceInfo majorVersion is :' + majorVersionInfo); let seniorVersionInfo: number = deviceInfo.seniorVersion; - // Output: the value of the deviceInfo seniorVersion is: 0 + // Output: the value of the seniorVersion is :0 console.info('the value of the deviceInfo seniorVersion is :' + seniorVersionInfo); let featureVersionInfo: number = deviceInfo.featureVersion; - // Output: the value of the deviceInfo featureVersion is: 0 + // Output: the value of the featureVersion is :0 console.info('the value of the deviceInfo featureVersion is :' + featureVersionInfo); let buildVersionInfo: number = deviceInfo.buildVersion; - // Output: the value of the deviceInfo buildVersion is: 1 + // Output: the value of the buildVersion is :1 console.info('the value of the deviceInfo buildVersion is :' + buildVersionInfo); let sdkApiVersionInfo: number = deviceInfo.sdkApiVersion; - // Output: the value of the deviceInfo sdkApiVersion is: 12 + // Output: the value of the sdkApiVersion is :12 console.info('the value of the deviceInfo sdkApiVersion is :' + sdkApiVersionInfo); let firstApiVersionInfo: number = deviceInfo.firstApiVersion; - // Output: the value of the deviceInfo firstApiVersion is: 3 + // Output: the value of the firstApiVersion is :3 console.info('the value of the deviceInfo firstApiVersion is :' + firstApiVersionInfo); let versionIdInfo: string = deviceInfo.versionId; - // Output result: the value of the deviceInfo versionId is: wearable/HUAWEI/HUAWEI/TAS/OpenHarmony-5.0.0.1/TAS-AL00/TAS-AL00/12/default/release:nolog + // Output: the value of the versionId is :wearable/HUAWEI/HUAWEI/TAS/OpenHarmony-5.0.0.1/TAS-AL00/TAS-AL00/12/default/release:nolog console.info('the value of the deviceInfo versionId is :' + versionIdInfo); let buildTypeInfo: string = deviceInfo.buildType; - // Output: the value of the deviceInfo buildUser is: default + // Output: the value of the buildType is :default console.info('the value of the deviceInfo buildType is :' + buildTypeInfo); let buildUserInfo: string = deviceInfo.buildUser; - // Output: the value of the deviceInfo buildUser is: default + // Output: the value of the buildUser is :default console.info('the value of the deviceInfo buildUser is :' + buildUserInfo); let buildHostInfo: string = deviceInfo.buildHost; - // Output: the value of the deviceInfo buildHost is: default + // Output: the value of the buildHost is :default console.info('the value of the deviceInfo buildHost is :' + buildHostInfo); let buildTimeInfo: string = deviceInfo.buildTime; - // Output result: the value of the deviceInfo buildTime is: default + // Output: the value of the buildTime is :default console.info('the value of the deviceInfo buildTime is :' + buildTimeInfo); let buildRootHashInfo: string = deviceInfo.buildRootHash; - // Output result: the value of the deviceInfo buildRootHash is: default + // Output: the value of the buildRootHash is :default console.info('the value of the deviceInfo buildRootHash is :' + buildRootHashInfo); let udid: string = deviceInfo.udid; - // Output: the value of the deviceInfo udid is: 9D6AABD147XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXE5536412 + // Output: the value of the udid is :9D6AABD147XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXE5536412 console.info('the value of the deviceInfo udid is :' + udid); let distributionOSName: string = deviceInfo.distributionOSName - // Output: the value of the deviceInfo distributionOSName is: OpenHarmony + // Output: the value of the distributionOSName is :OpenHarmony console.info('the value of the deviceInfo distributionOSName is :' + distributionOSName); let distributionOSVersion: string = deviceInfo.distributionOSVersion - // Output: the value of the deviceInfo distributionOSVersion is: 5.0.0 + // Output: the value of the distributionOSVersion is :5.0.0 console.info('the value of the deviceInfo distributionOSVersion is :' + distributionOSVersion); let distributionOSApiVersion: number = deviceInfo.distributionOSApiVersion - // Output: the value of the deviceInfo distributionOSApiVersion is: 500001 + // Output: the value of the distributionOSApiVersion is :500001 console.info('the value of the deviceInfo distributionOSApiVersion is :' + distributionOSApiVersion); let distributionOSApiName: string = deviceInfo.distributionOSApiName console.info('the value of the deviceInfo distributionOSApiName is :' + distributionOSApiName); let distributionOSReleaseType: string = deviceInfo.distributionOSReleaseType - // Output: the value of the deviceInfo distributionOSReleaseType is: Release + // Output: the value of the distributionOSReleaseType is :Release console.info('the value of the deviceInfo distributionOSReleaseType is :' + distributionOSReleaseType); let odid: string = deviceInfo.ODID; - // Output: the value of the deviceInfo odid is: 1234a567-XXXX-XXXX-XXXX-XXXXXXXXXXXX + // Output: the value of the ODID is :1234a567-XXXX-XXXX-XXXX-XXXXXXXXXXXX console.info('the value of the deviceInfo odid is :' + odid); let diskSN: string = deviceInfo.diskSN; - // Output: the value of the deviceInfo diskSN is: 2502EM400567 + // Output: the value of the deviceInfo diskSN is :2502EM400567 console.info('the value of the deviceInfo diskSN is :' + diskSN); + let performanceClass = deviceInfo.performanceClass; + // Output: the value of the deviceInfo performanceClass is :0 + console.info('the value of the deviceInfo performanceClass is :' + performanceClass); + +``` + +## PerformanceClassLevel19+ + +Enumerates the device capability levels. + +**System capability**: SystemCapability.Startup.SystemInfo + +| Name | Value | Description | +| ---------------------| ---- | -------------- | +| CLASS_LEVEL_HIGH | 0 | High | +| CLASS_LEVEL_MEDIUM | 1 | Medium | +| CLASS_LEVEL_LOW | 2 | Low | + +## DeviceTypes20+ + +Enumerates device types, which can be used to verify the return value of **deviceType**. + +**Atomic service API**: This API can be used in atomic services since API version 20. + +**System capability**: SystemCapability.Startup.SystemInfo + +| Name| Value | Description | +| ---- | ---- | -------------------------- | +| TYPE_DEFAULT | 'default' | Default device| +| TYPE_PHONE | 'phone' | Smartphone| +| TYPE_TABLET | 'tablet' | Tablet| +| TYPE_2IN1 | '2in1' | PC/2-in-1 device| +| TYPE_TV | 'tv' | Smart TV| +| TYPE_WEARABLE | 'wearable' | Wearable| +| TYPE_CAR | 'car' | Head unit| + +**Example** + +```ts + let deviceTypesInfo: string = deviceInfo.DeviceTypes.TYPE_DEFAULT; + // Output: the value of the DeviceTypes is :default + console.info('the value of the DeviceTypes is :' + deviceTypesInfo); + + let deviceTypesInfo: string = deviceInfo.DeviceTypes.TYPE_PHONE; + // Output: the value of the DeviceTypes is :phone-type + console.info('the value of the DeviceTypes is :' + deviceTypesInfo); + + let deviceTypesInfo: string = deviceInfo.DeviceTypes.TYPE_TABLET; + //Output: the value of the DeviceTypes is :tablet + console.info('the value of the DeviceTypes is :' + deviceTypesInfo); + + let deviceTypesInfo: string = deviceInfo.DeviceTypes.TYPE_2IN1; + //Output: the value of the DeviceTypes is :2in1 + console.info('the value of the DeviceTypes is :' + deviceTypesInfo); + + let deviceTypesInfo: string = deviceInfo.DeviceTypes.TYPE_TV; + //Output: the value of the DeviceTypes is :tv + console.info('the value of the DeviceTypes is :' + deviceTypesInfo); + + let deviceTypesInfo: string = deviceInfo.DeviceTypes.TYPE_WEARABLE; + // Output: the value of the DeviceTypes is :wearable + console.info('the value of the DeviceTypes is :' + deviceTypesInfo); + + let deviceTypesInfo: string = deviceInfo.DeviceTypes.TYPE_CAR; + //Output: the value of the DeviceTypes is :car + console.info('the value of the DeviceTypes is :' + deviceTypesInfo); ``` diff --git a/en/application-dev/reference/apis-basic-services-kit/js-apis-deviceAttest-sys.md b/en/application-dev/reference/apis-basic-services-kit/js-apis-deviceAttest-sys.md index 88b9523eb19..55085ea009b 100644 --- a/en/application-dev/reference/apis-basic-services-kit/js-apis-deviceAttest-sys.md +++ b/en/application-dev/reference/apis-basic-services-kit/js-apis-deviceAttest-sys.md @@ -27,13 +27,15 @@ Obtains details about the device attestation result from the cloud. This API use | Name | Type | Mandatory| Description | | -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| callback | AsyncCallback<[AttestResultInfo](#attestresultinfo)> | Yes | Callback invoked to return the result. If the operation is successful, **error** is **undefined**, and **result** is the obtained [AttestResultInfo](#attestresultinfo). Otherwise, **error** is an error object.| - -**Error codes** +| callback | AsyncCallback<[AttestResultInfo](#attestresultinfo)> | Yes | Callback used to return the result. If the operation is successful, **error** is **undefined**, and **result** is the obtained [AttestResultInfo](#attestresultinfo). Otherwise, **error** is an error object.| +**Error codes** +For details about error codes, see [Device Attestation Error Codes](./errorcode-deviceAttest.md) and [Universal Error Codes](../errorcode-universal.md). | ID | Error Message | |----------|----------------------| -| 20000001 | system service exception. | +| 202 | This api is system api, Please use the system application to call this api. | +| 401 | Input parameters wrong, the number of parameters is incorrect, or the type of parameters is incorrect. | +| 20000001 | System service exception, please try again or reboot your device. | **Example** @@ -43,7 +45,7 @@ import base from '@ohos.base'; try { deviceAttest.getAttestStatus((error: base.BusinessError, value: deviceAttest.AttestResultInfo) => { if (typeof error != 'undefined') { - console.info("error code:" + error.code + " message:" + error.message); + console.error("error code:" + error.code + " message:" + error.message); } else { console.info("auth:" + value.authResult + " software:" + value.softwareResult + " ticket:" + value.ticket); console.info("versionIdResult:" + value.softwareResultDetail[0], @@ -56,7 +58,7 @@ try { } catch (error) { let code: number = (error as base.BusinessError).code; let message: string = (error as base.BusinessError).message; - console.info("error code:" + code + " message:" + message); + console.error("error code:" + code + " message:" + message); } ``` @@ -74,11 +76,13 @@ Obtains details about the device attestation result from the cloud. This API use | ----------------------------------------------------- | ------------------------------- | | Promise<[AttestResultInfo](#attestresultinfo)> | Promise used to return the device attestation information obtained.| -**Error codes** - +**Error codes** +For details about error codes, see [Device Attestation Error Codes](./errorcode-deviceAttest.md) and [Universal Error Codes](../errorcode-universal.md). | ID | Error Message | |----------|----------------------| -| 20000001 | system service exception. | +| 202 | This api is system api, Please use the system application to call this api. | +| 401 | Input parameters wrong, the number of parameters is incorrect, or the type of parameters is incorrect. | +| 20000001 | System service exception, please try again or reboot your device. | **Example** @@ -94,12 +98,12 @@ try { " PCIDResult:" + value.softwareResultDetail[3], " reserver:" + value.softwareResultDetail[4]); }).catch((error: base.BusinessError) => { - console.info("error code:" + error.code + " message:" + error.message); + console.error("error code:" + error.code + " message:" + error.message); }); } catch (error) { let code: number = (error as base.BusinessError).code; let message: string = (error as base.BusinessError).message; - console.info("error code:" + code + " message:" + message); + console.error("error code:" + code + " message:" + message); } ``` @@ -117,11 +121,13 @@ Obtains details about the device attestation result from the cloud synchronously | ----------------------------------------------------- | ------------------------------- | | [AttestResultInfo](#attestresultinfo) | Returns the device attestation information obtained.| -**Error codes** - +**Error codes** +For details about error codes, see [Device Attestation Error Codes](./errorcode-deviceAttest.md) and [Universal Error Codes](../errorcode-universal.md). | ID | Error Message | |----------|----------------------| -| 20000001 | system service exception. | +| 202 | This api is system api, Please use the system application to call this api. | +| 401 | Input parameters wrong, the number of parameters is incorrect, or the type of parameters is incorrect. | +| 20000001 | System service exception, please try again or reboot your device. | **Example** @@ -139,7 +145,7 @@ try { } catch (error) { let code: number = (error as base.BusinessError).code; let message: string = (error as base.BusinessError).message; - console.info("error code:" + code + " message:" + message); + console.error("error code:" + code + " message:" + message); } ``` @@ -149,12 +155,12 @@ Defines the device attestation result information. **System capability**: SystemCapability.XTS.DeviceAttest -| Name | Type | Readable| Writable| Description | +| Name | Type | Read-Only| Optional| Description | | --------------------- | --------------------- | ---- | ---- | ---------------------- | -| authResult | number | Yes | No | Device hardware attestation result. | -| softwareResult | number | Yes | No | Device software attestation result. | -| softwareResultDetail | Array<number> | Yes | No | Detailed information about the device software attestation result.
- **softwareResultDetail[0]**: version ID attestation result.
- **softwareResultDetail[1]**: attestation result of the security patch label.
- **softwareResultDetail[2]**: version hash attestation result.
- **softwareResultDetail[3]**: attestation result of the system capability set.
- **softwareResultDetail[4]**: reserved. | -| ticket | string | Yes | No | Soft certificate delivered by the cloud.
If the device hardware attestation is successful, a value is returned. If the attestation fails, this parameter is empty. | +| authResult | number | No | No | Device hardware attestation result. | +| softwareResult | number | No | No | Device software attestation result. | +| softwareResultDetail | Array<number> | No | No | Detailed information about the device software attestation result.
- **softwareResultDetail[0]**: attestation result of version ID.
- **softwareResultDetail[1]**: attestation result of the security patch label.
- **softwareResultDetail[2]**: attestation result of version hash.
- **softwareResultDetail[3]**: attestation result of the system capability set.
- **softwareResultDetail[4]**: reserved. | +| ticket | string | No | No | Soft certificate delivered by the cloud.
If the device hardware attestation is successful, a value is returned. If the attestation fails, this parameter is empty. | > **NOTE** > diff --git a/en/application-dev/reference/apis-basic-services-kit/js-apis-distributed-account-sys.md b/en/application-dev/reference/apis-basic-services-kit/js-apis-distributed-account-sys.md index cecb3a22cb7..4b31ef7aa24 100644 --- a/en/application-dev/reference/apis-basic-services-kit/js-apis-distributed-account-sys.md +++ b/en/application-dev/reference/apis-basic-services-kit/js-apis-distributed-account-sys.md @@ -31,14 +31,14 @@ Obtains distributed information about a system account. This API uses an asynchr **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------- | -------- | -------- | -| localId | number | Yes| ID of the target system account.| -| callback | AsyncCallback<[DistributedInfo](js-apis-distributed-account.md#distributedinfo)> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the distributed account information obtained. Otherwise, **err** is an error object. | + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | localId | number | Yes| ID of the target system account.| + | callback | AsyncCallback<[DistributedInfo](js-apis-distributed-account.md#distributedinfo)> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the distributed account information obtained. Otherwise, **err** is an error object.| **Error codes** -| ID | Error Message| +| ID| Error Message| | -------- | ------------------- | | 201 | Permission denied.| | 202 | Not system application.| @@ -56,13 +56,13 @@ try { accountAbility.getOsAccountDistributedInfoByLocalId(100, (err: BusinessError, data: distributedAccount.DistributedInfo) => { if (err) { - console.log('getOsAccountDistributedInfoByLocalId exception: ' + JSON.stringify(err)); + console.error('getOsAccountDistributedInfoByLocalId exception: ' + JSON.stringify(err)); } else { console.log('distributed information: ' + JSON.stringify(data)); } }); } catch (err) { - console.log('getOsAccountDistributedInfoByLocalId exception: ' + JSON.stringify(err)); + console.error('getOsAccountDistributedInfoByLocalId exception: ' + JSON.stringify(err)); } ``` @@ -80,19 +80,19 @@ Obtains distributed information about a system account. This API uses a promise **Parameters** -| Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | localId | number | Yes | ID of the target system account. | + | localId | number | Yes| ID of the target system account.| **Return value** -| Type | Description | -| -------- | -------- | -| Promise<[DistributedInfo](js-apis-distributed-account.md#distributedinfo)> | Promise used to return the distributed account information obtained. | + | Type| Description| + | -------- | -------- | + | Promise<[DistributedInfo](js-apis-distributed-account.md#distributedinfo)> | Promise used to return the distributed account information obtained.| **Error codes** -| ID | Error Message| +| ID| Error Message| | -------- | ------------------- | | 201 | Permission denied.| | 202 | Not system application.| @@ -111,10 +111,10 @@ try { data: distributedAccount.DistributedInfo) => { console.log('distributed information: ' + JSON.stringify(data)); }).catch((err: BusinessError) => { - console.log('getOsAccountDistributedInfoByLocalId exception: ' + JSON.stringify(err)); + console.error('getOsAccountDistributedInfoByLocalId exception: ' + JSON.stringify(err)); }); } catch (err) { - console.log('getOsAccountDistributedInfoByLocalId exception: ' + JSON.stringify(err)); + console.error('getOsAccountDistributedInfoByLocalId exception: ' + JSON.stringify(err)); } ``` @@ -132,15 +132,15 @@ Sets the distributed information for a system account. This API uses an asynchro **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------- | -------- | -------- | -| localId | number | Yes| ID of the target system account.| -| distributedInfo | [DistributedInfo](js-apis-distributed-account.md#distributedinfo) | Yes| Distributed account information to set.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the distributed information is set successfully, **err** is **undefined**. Otherwise, **err** is an error object. | + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | localId | number | Yes| ID of the target system account.| + | distributedInfo | [DistributedInfo](js-apis-distributed-account.md#distributedinfo) | Yes| Distributed account information to set.| + | callback | AsyncCallback<void> | Yes| Callback used to return the result. If the distributed information is set successfully, **err** is **undefined**. Otherwise, **err** is an error object.| **Error codes** -| ID | Error Message| +| ID| Error Message| | -------- | ------------------- | | 201 | Permission denied.| | 202 | Not system application.| @@ -161,13 +161,13 @@ let accountInfo: distributedAccount.DistributedInfo = try { accountAbility.setOsAccountDistributedInfoByLocalId(100, accountInfo, (err: BusinessError) => { if (err) { - console.log('setOsAccountDistributedInfoByLocalId exception: ' + JSON.stringify(err)); + console.error('setOsAccountDistributedInfoByLocalId exception: ' + JSON.stringify(err)); } else { console.log('setOsAccountDistributedInfoByLocalId successfully'); } }); } catch (err) { - console.log('setOsAccountDistributedInfoByLocalId exception: ' + JSON.stringify(err)); + console.error('setOsAccountDistributedInfoByLocalId exception: ' + JSON.stringify(err)); } ``` @@ -185,20 +185,20 @@ Sets the distributed information for a system account. This API uses a promise t **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------- | -------- | -------- | -| localId | number | Yes| ID of the target system account.| -| distributedInfo | [DistributedInfo](js-apis-distributed-account.md#distributedinfo) | Yes| Distributed account information to set.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | localId | number | Yes| ID of the target system account.| + | distributedInfo | [DistributedInfo](js-apis-distributed-account.md#distributedinfo) | Yes| Distributed account information to set.| **Return value** -| Type | Description | -| -------- | -------- | -| Promise<void> | Promise that returns no value. | + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise that returns no value.| **Error codes** -| ID | Error Message| +| ID| Error Message| | -------- | ------------------- | | 201 | Permission denied.| | 202 | Not system application.| @@ -220,9 +220,9 @@ try { accountAbility.setOsAccountDistributedInfoByLocalId(100, accountInfo).then(() => { console.log('setOsAccountDistributedInfoByLocalId successfully'); }).catch((err: BusinessError) => { - console.log('setOsAccountDistributedInfoByLocalId exception: ' + JSON.stringify(err)); + console.error('setOsAccountDistributedInfoByLocalId exception: ' + JSON.stringify(err)); }); } catch (err) { - console.log('setOsAccountDistributedInfoByLocalId exception: ' + JSON.stringify(err)); + console.error('setOsAccountDistributedInfoByLocalId exception: ' + JSON.stringify(err)); } ``` diff --git a/en/application-dev/reference/apis-basic-services-kit/js-apis-distributed-account.md b/en/application-dev/reference/apis-basic-services-kit/js-apis-distributed-account.md index 714e4817c1d..3b4e3ff9345 100644 --- a/en/application-dev/reference/apis-basic-services-kit/js-apis-distributed-account.md +++ b/en/application-dev/reference/apis-basic-services-kit/js-apis-distributed-account.md @@ -22,9 +22,9 @@ Obtains a **DistributedAccountAbility** instance. **Return value** - | Type| Description| - | -------- | -------- | - | [DistributedAccountAbility](#distributedaccountability) | **DistributedAccountAbility** instance obtained. This instance provides APIs for querying and updating the login state of a distributed account.|| +| Type| Description| +| -------- | -------- | +| [DistributedAccountAbility](#distributedaccountability) | **DistributedAccountAbility** instance obtained. This instance provides APIs for querying and updating the login state of a distributed account.|| **Example** ```ts @@ -43,13 +43,13 @@ Obtains distributed account information. This API uses an asynchronous callback **System capability**: SystemCapability.Account.OsAccount -**Required permissions**: ohos.permission.MANAGE_DISTRIBUTED_ACCOUNTS (available only for system applications), ohos.permission.GET_DISTRIBUTED_ACCOUNTS (available only for system applications), or ohos.permission.DISTRIBUTED_DATASYNC +**Required permissions**: ohos.permission.MANAGE_DISTRIBUTED_ACCOUNTS (for system applications only), ohos.permission.GET_DISTRIBUTED_ACCOUNTS (for system applications only), or ohos.permission.DISTRIBUTED_DATASYNC **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[DistributedInfo](#distributedinfo)> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the distributed account information obtained. Otherwise, **err** is an error object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<[DistributedInfo](#distributedinfo)> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the distributed account information obtained. Otherwise, **err** is an error object.| **Error codes** @@ -68,13 +68,13 @@ Obtains distributed account information. This API uses an asynchronous callback accountAbility.getOsAccountDistributedInfo( (err: BusinessError, data: distributedAccount.DistributedInfo) => { if (err) { - console.log('getOsAccountDistributedInfo exception: ' + JSON.stringify(err)); + console.error('getOsAccountDistributedInfo exception: ' + JSON.stringify(err)); } else { console.log('distributed information: ' + JSON.stringify(data)); } }); } catch (err) { - console.log('getOsAccountDistributedInfo exception: ' + JSON.stringify(err)); + console.error('getOsAccountDistributedInfo exception: ' + JSON.stringify(err)); } ``` @@ -86,13 +86,13 @@ Obtains distributed account information. This API uses a promise to return the r **System capability**: SystemCapability.Account.OsAccount -**Required permissions**: ohos.permission.MANAGE_DISTRIBUTED_ACCOUNTS (available only for system applications), ohos.permission.GET_DISTRIBUTED_ACCOUNTS (available only for system applications), or ohos.permission.DISTRIBUTED_DATASYNC +**Required permissions**: ohos.permission.MANAGE_DISTRIBUTED_ACCOUNTS (for system applications only), ohos.permission.GET_DISTRIBUTED_ACCOUNTS (for system applications only), or ohos.permission.DISTRIBUTED_DATASYNC **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[DistributedInfo](#distributedinfo)> | Promise used to return the distributed account information obtained.| +| Type| Description| +| -------- | -------- | +| Promise<[DistributedInfo](#distributedinfo)> | Promise used to return the distributed account information obtained.| **Error codes** @@ -110,10 +110,10 @@ Obtains distributed account information. This API uses a promise to return the r accountAbility.getOsAccountDistributedInfo().then((data: distributedAccount.DistributedInfo) => { console.log('distributed information: ' + JSON.stringify(data)); }).catch((err: BusinessError) => { - console.log('getOsAccountDistributedInfo exception: ' + JSON.stringify(err)); + console.error('getOsAccountDistributedInfo exception: ' + JSON.stringify(err)); }); } catch (err) { - console.log('getOsAccountDistributedInfo exception: ' + JSON.stringify(err)); + console.error('getOsAccountDistributedInfo exception: ' + JSON.stringify(err)); } ``` @@ -128,13 +128,13 @@ Queries distributed account information. This API uses an asynchronous callback **System capability**: SystemCapability.Account.OsAccount -**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS (available only for system applications) or ohos.permission.DISTRIBUTED_DATASYNC +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS (for system applications only) or ohos.permission.DISTRIBUTED_DATASYNC **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[DistributedInfo](#distributedinfo)> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the distributed account information obtained. Otherwise, **err** is an error object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<[DistributedInfo](#distributedinfo)> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the distributed account information obtained. Otherwise, **err** is an error object.| **Example** ```ts @@ -144,7 +144,7 @@ Queries distributed account information. This API uses an asynchronous callback accountAbility.queryOsAccountDistributedInfo( (err: BusinessError, data: distributedAccount.DistributedInfo) => { if (err) { - console.log('queryOsAccountDistributedInfo exception: ' + JSON.stringify(err)); + console.error('queryOsAccountDistributedInfo exception: ' + JSON.stringify(err)); } else { console.log('distributed information: ' + JSON.stringify(data)); } @@ -163,13 +163,13 @@ Queries distributed account information. This API uses a promise to return the r **System capability**: SystemCapability.Account.OsAccount -**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS (available only for system applications) or ohos.permission.DISTRIBUTED_DATASYNC +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS (for system applications only) or ohos.permission.DISTRIBUTED_DATASYNC **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[DistributedInfo](#distributedinfo)> | Promise used to return the distributed account information obtained.| +| Type| Description| +| -------- | -------- | +| Promise<[DistributedInfo](#distributedinfo)> | Promise used to return the distributed account information obtained.| **Example** ```ts @@ -179,7 +179,7 @@ Queries distributed account information. This API uses a promise to return the r accountAbility.queryOsAccountDistributedInfo().then((data: distributedAccount.DistributedInfo) => { console.log('distributed information: ' + JSON.stringify(data)); }).catch((err: BusinessError) => { - console.log('queryOsAccountDistributedInfo exception: ' + JSON.stringify(err)); + console.error('queryOsAccountDistributedInfo exception: ' + JSON.stringify(err)); }); ``` @@ -195,10 +195,10 @@ Sets the distributed account information. This API uses an asynchronous callback **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | accountInfo | [DistributedInfo](#distributedinfo) | Yes| Distributed account information to set.| - | callback | AsyncCallback<void> | Yes| Callback used to return the result. If the distributed account information is set successfully, **err** is **undefined**. Otherwise, **err** is an error object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| accountInfo | [DistributedInfo](#distributedinfo) | Yes| Distributed account information to set.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the distributed account information is set successfully, **err** is **undefined**. Otherwise, **err** is an error object.| **Error codes** @@ -220,13 +220,13 @@ Sets the distributed account information. This API uses an asynchronous callback try { accountAbility.setOsAccountDistributedInfo(accountInfo, (err: BusinessError) => { if (err) { - console.log('setOsAccountDistributedInfo exception: ' + JSON.stringify(err)); + console.error('setOsAccountDistributedInfo exception: ' + JSON.stringify(err)); } else { console.log('setOsAccountDistributedInfo successfully'); } }); } catch (err) { - console.log('setOsAccountDistributedInfo exception: ' + JSON.stringify(err)); + console.error('setOsAccountDistributedInfo exception: ' + JSON.stringify(err)); } ``` @@ -242,15 +242,15 @@ Sets the distributed account information. This API uses a promise to return the **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | accountInfo | [DistributedInfo](#distributedinfo) | Yes| Distributed account information to set.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| accountInfo | [DistributedInfo](#distributedinfo) | Yes| Distributed account information to set.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise that returns no value.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| **Error codes** @@ -273,10 +273,10 @@ Sets the distributed account information. This API uses a promise to return the accountAbility.setOsAccountDistributedInfo(accountInfo).then(() => { console.log('setOsAccountDistributedInfo successfully'); }).catch((err: BusinessError) => { - console.log('setOsAccountDistributedInfo exception: ' + JSON.stringify(err)); + console.error('setOsAccountDistributedInfo exception: ' + JSON.stringify(err)); }); } catch (err) { - console.log('setOsAccountDistributedInfo exception: ' + JSON.stringify(err)); + console.error('setOsAccountDistributedInfo exception: ' + JSON.stringify(err)); } ``` @@ -296,10 +296,10 @@ Updates the distributed account information. This API uses an asynchronous callb **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | accountInfo | [DistributedInfo](#distributedinfo) | Yes| Distributed account information to set.| - | callback | AsyncCallback<void> | Yes| Callback used to return the result. If the distributed account information is updated successfully, **err** is **undefined**. Otherwise, **err** is an error object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| accountInfo | [DistributedInfo](#distributedinfo) | Yes| Distributed account information to update. | +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the distributed account information is updated successfully, **err** is **undefined**. Otherwise, **err** is an error object.| **Example** ```ts @@ -310,7 +310,7 @@ Updates the distributed account information. This API uses an asynchronous callb {id: '12345', name: 'ZhangSan', event: 'Ohos.account.event.LOGIN'}; accountAbility.updateOsAccountDistributedInfo(accountInfo, (err: BusinessError) => { if (err) { - console.log('queryOsAccountDistributedInfo exception: ' + JSON.stringify(err)); + console.error('queryOsAccountDistributedInfo exception: ' + JSON.stringify(err)); } else { console.log('queryOsAccountDistributedInfo successfully'); } @@ -332,15 +332,15 @@ Updates the distributed account information. This API uses a promise to return t **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | accountInfo | [DistributedInfo](#distributedinfo) | Yes| Distributed account information.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| accountInfo | [DistributedInfo](#distributedinfo) | Yes| Distributed account information to update. | **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise that returns no value.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| **Example** ```ts @@ -352,7 +352,7 @@ Updates the distributed account information. This API uses a promise to return t accountAbility.updateOsAccountDistributedInfo(accountInfo).then(() => { console.log('updateOsAccountDistributedInfo successfully'); }).catch((err: BusinessError) => { - console.log('updateOsAccountDistributedInfo exception: ' + JSON.stringify(err)); + console.error('updateOsAccountDistributedInfo exception: ' + JSON.stringify(err)); }); ``` diff --git a/en/application-dev/reference/apis-basic-services-kit/js-apis-emitter.md b/en/application-dev/reference/apis-basic-services-kit/js-apis-emitter.md index f33905bc0d7..f2b664b02f2 100644 --- a/en/application-dev/reference/apis-basic-services-kit/js-apis-emitter.md +++ b/en/application-dev/reference/apis-basic-services-kit/js-apis-emitter.md @@ -36,7 +36,7 @@ Subscribes to an event in persistent manner and executes a callback after the ev **Example** ```ts -import { Callback} from '@kit.BasicServicesKit'; +import { Callback } from '@kit.BasicServicesKit'; let innerEvent: emitter.InnerEvent = { eventId: 1 @@ -70,7 +70,7 @@ Subscribes to an event in persistent manner and executes a callback after the ev **Example** ```ts -import { Callback} from '@kit.BasicServicesKit'; +import { Callback } from '@kit.BasicServicesKit'; let callback: Callback = (eventData: emitter.EventData) => { console.info(`eventData: ${JSON.stringify(eventData)}`); @@ -99,7 +99,7 @@ Subscribes to an event in persistent manner and executes a callback after the ev **Example** ```ts -import { Callback} from '@kit.BasicServicesKit'; +import { Callback } from '@kit.BasicServicesKit'; @Sendable class Sample { @@ -142,7 +142,7 @@ Subscribes to an event in one-shot manner and unsubscribes from it after the eve **Example** ```ts -import { Callback} from '@kit.BasicServicesKit'; +import { Callback } from '@kit.BasicServicesKit'; let innerEvent: emitter.InnerEvent = { eventId: 1 @@ -175,7 +175,7 @@ Subscribes to an event in one-shot manner and unsubscribes from it after the eve **Example** ```ts -import { Callback} from '@kit.BasicServicesKit'; +import { Callback } from '@kit.BasicServicesKit'; let callback: Callback = (eventData: emitter.EventData) => { console.info(`eventData: ${JSON.stringify(eventData)}`); @@ -204,7 +204,7 @@ Subscribes to an event in one-shot manner and unsubscribes from it after the eve **Example** ```ts -import { Callback} from '@kit.BasicServicesKit'; +import { Callback } from '@kit.BasicServicesKit'; @Sendable class Sample { @@ -299,7 +299,7 @@ After this API is used to unsubscribe from an event, the event that has been pub **Example** ```ts -import { Callback} from '@kit.BasicServicesKit'; +import { Callback } from '@kit.BasicServicesKit'; let callback: Callback = (eventData: emitter.EventData) => { console.info(`eventData: ${JSON.stringify(eventData)}`); @@ -331,7 +331,7 @@ After this API is used to unsubscribe from an event, the event that has been pub **Example** ```ts -import { Callback} from '@kit.BasicServicesKit'; +import { Callback } from '@kit.BasicServicesKit'; let callback: Callback = (eventData: emitter.EventData) => { console.info(`eventData: ${JSON.stringify(eventData)}`); @@ -363,7 +363,7 @@ After this API is used to unsubscribe from an event, the event that has been pub **Example** ```ts -import { Callback} from '@kit.BasicServicesKit'; +import { Callback } from '@kit.BasicServicesKit'; @Sendable class Sample { @@ -580,7 +580,14 @@ Obtains the number of subscriptions to a specified event. | Name | Type | Mandatory| Description | | ------- | -------------- | ---- | -------- | -| eventId | number \| string | Yes | Event ID. The value of the string type cannot be an empty string.| +| eventId | number \| string | Yes | Event ID, which is a custom string. The value cannot be an empty string and exceed 10240 bytes.| + +**Returns** + +| Type | Description | +| ------- |------------| +| number | Number of subscriptions to a specified event.| + **Example** @@ -598,7 +605,7 @@ Enumerates the event priorities. | Name | Value | Description | | --------- | ---- | --------------------------------------------------- | -| IMMEDIATE | 0 | The event will be emitted immediately. | +| IMMEDIATE | 0 | The event will be emitted immediately. | | HIGH | 1 | The event will be emitted before low-priority events. | | LOW | 2 | The event will be emitted before idle-priority events. By default, an event is in LOW priority. | | IDLE | 3 | The event will be emitted after all the other events. | diff --git a/en/application-dev/reference/apis-basic-services-kit/js-apis-inner-commonEvent-commonEventData.md b/en/application-dev/reference/apis-basic-services-kit/js-apis-inner-commonEvent-commonEventData.md index 3fff67fe7e2..c11ea43a3ac 100644 --- a/en/application-dev/reference/apis-basic-services-kit/js-apis-inner-commonEvent-commonEventData.md +++ b/en/application-dev/reference/apis-basic-services-kit/js-apis-inner-commonEvent-commonEventData.md @@ -1,12 +1,12 @@ # CommonEventData -Common event data. +Describes the data of a common event. > **NOTE** > > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. -## Attributes +## Properties **Atomic service API**: This API can be used in atomic services since API version 11. diff --git a/en/application-dev/reference/apis-basic-services-kit/js-apis-inner-commonEvent-commonEventPublishData.md b/en/application-dev/reference/apis-basic-services-kit/js-apis-inner-commonEvent-commonEventPublishData.md index d03ffb64e59..25bd7171ac3 100644 --- a/en/application-dev/reference/apis-basic-services-kit/js-apis-inner-commonEvent-commonEventPublishData.md +++ b/en/application-dev/reference/apis-basic-services-kit/js-apis-inner-commonEvent-commonEventPublishData.md @@ -18,6 +18,6 @@ The **CommonEventPublishData** module provides APIs for defining common event co | code | number | No | Yes | Common event data transferred by the publisher. The default value is **0**.
**Atomic service API**: This API can be used in atomic services since API version 11. | | data | string | No | Yes | Common event data transferred by the publisher. The data size cannot exceed 64 KB.
**Atomic service API**: This API can be used in atomic services since API version 11.| | subscriberPermissions | Array\ | No | Yes | Permissions required for subscribers to receive the common event.
**Atomic service API**: This API can be used in atomic services since API version 11. | -| isOrdered | boolean | No | Yes | Whether the common event is an ordered one. | -| isSticky | boolean | No | Yes | Whether the common event is a sticky one. Only system applications and system services are allowed to send sticky events.
**Required Permissions**: [ohos.permission.COMMONEVENT_STICKY](../../security/AccessToken/permissions-for-all.md#ohospermissioncommonevent_sticky)| +| isOrdered | boolean | No | Yes | Whether the common event is an ordered one. The default value is **false**.
- **true**: This event is an ordered common event. Based on the priority set by the subscriber, the common event is preferentially sent to the subscriber with a higher priority. After the subscriber successfully receives the event, the public event is sent to the subscriber with a lower priority. Subscribers with the same priority receive common events in a random order.
- **false**: This event is an unordered common event. Whether subscribers receive the event is not considered, and the common event which subscribers receive may not comply with the subscription sequence. | +| isSticky | boolean | No | Yes | Whether the common event is a sticky one. The default value is **false**.
- **true**: This event is a sticky common event, which allows subscribers to receive common events that have been sent before subscription.
- **false**: This event is not a sticky common event, which allows subscribers to receive common events sent after subscription.
Only system applications and system services are allowed to send sticky events.
**Required Permissions**: [ohos.permission.COMMONEVENT_STICKY](../../security/AccessToken/permissions-for-all.md#ohospermissioncommonevent_sticky)| | parameters | {[key: string]: any} | No | Yes | Additional information about the common event transferred by the publisher.
**Atomic service API**: This API can be used in atomic services since API version 11. | diff --git a/en/application-dev/reference/apis-basic-services-kit/js-apis-intelligentVoice-sys.md b/en/application-dev/reference/apis-basic-services-kit/js-apis-intelligentVoice-sys.md index 27ac3488e25..c530103b607 100644 --- a/en/application-dev/reference/apis-basic-services-kit/js-apis-intelligentVoice-sys.md +++ b/en/application-dev/reference/apis-basic-services-kit/js-apis-intelligentVoice-sys.md @@ -1,8 +1,8 @@ # @ohos.ai.intelligentVoice (Intelligent Voice) (System API) -The **intelligentVoice** module provides the intelligent voice enrollment and voice wakeup functions. +The **intelligentVoice** module provides the intelligent voice enrollment and voice wakeup functions. Currently, the features are related to chips and are not supported on OpenHarmony yet. -Its functions are implemented by: +Its features are implemented by: - [IntelligentVoiceManager](#intelligentvoicemanager): intelligent voice manager class, which declares the functions provided by the module. Currently, voice enrollment and voice wakeup are supported. Before developing intelligent voice functions, call [getIntelligentVoiceManager()](#intelligentvoicegetintelligentvoicemanager) to check whether they are supported. - [EnrollIntelligentVoiceEngine](#enrollintelligentvoiceengine): class that implements voice enrollment. You need to perform voice enrollment before using voice wakeup. @@ -839,7 +839,7 @@ A sensibility type maps to a wakeup threshold. A higher sensibility indicates a ## WakeupHapInfo -Defines the HAP information for an wakeup application. +Defines the HAP information for a wakeup application. **System capability**: SystemCapability.AI.IntelligentVoice.Core @@ -1430,6 +1430,12 @@ Sets the HAP information for the wakeup application. This API uses a promise to **System capability**: SystemCapability.AI.IntelligentVoice.Core +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------- | --- | ------------------------------------------- | +| info | [WakeupHapInfo](#wakeuphapinfo) | Yes | HAP information for the wakeup application.| + **Return value** | Type | Description | diff --git a/en/application-dev/reference/apis-basic-services-kit/js-apis-osAccount-sys.md b/en/application-dev/reference/apis-basic-services-kit/js-apis-osAccount-sys.md index 6c067e8d02f..e6f17784261 100644 --- a/en/application-dev/reference/apis-basic-services-kit/js-apis-osAccount-sys.md +++ b/en/application-dev/reference/apis-basic-services-kit/js-apis-osAccount-sys.md @@ -47,11 +47,13 @@ Activates a system account. This API uses an asynchronous callback to return the | 12300002 | Invalid localId. | | 12300003 | Account not found. | | 12300008 | Restricted Account. | +| 12300010 | Service busy. Possible causes: The target account is being operated. | | 12300016 | The number of logged in accounts reaches the upper limit. | **Example**: Activate system account 100. ```ts import { BusinessError } from '@kit.BasicServicesKit'; + let accountManager: osAccount.AccountManager = osAccount.getAccountManager(); let localId: number = 100; try { accountManager.activateOsAccount(localId, (err: BusinessError)=>{ @@ -62,7 +64,7 @@ Activates a system account. This API uses an asynchronous callback to return the } }); } catch (err) { - console.log('activateOsAccount failed, error:' + JSON.stringify(err)); + console.error('activateOsAccount failed, error:' + JSON.stringify(err)); } ``` @@ -101,6 +103,7 @@ Activates a system account. This API uses a promise to return the result. | 12300002 | Invalid localId. | | 12300003 | Account not found. | | 12300008 | Restricted Account. | +| 12300010 | Service busy. Possible causes: The target account is being operated. | | 12300016 | The number of logged in accounts reaches the upper limit. | **Example**: Activate system account 100. @@ -112,10 +115,10 @@ Activates a system account. This API uses a promise to return the result. accountManager.activateOsAccount(localId).then(() => { console.log('activateOsAccount successfully'); }).catch((err: BusinessError) => { - console.log('activateOsAccount failed, err:' + JSON.stringify(err)); + console.error('activateOsAccount failed, err:' + JSON.stringify(err)); }); } catch (e) { - console.log('activateOsAccount exception: ' + JSON.stringify(e)); + console.error('activateOsAccount exception: ' + JSON.stringify(e)); } ``` @@ -153,6 +156,7 @@ Deactivates (logs out of) a system account. This API uses a promise to return th | 12300001 | The system service works abnormally. | | 12300003 | Account not found. | | 12300008 | Restricted Account. | +| 12300010 | Service busy. Possible causes: The target account is being operated. | **Example**: Deactivate system account 100. ```ts @@ -163,10 +167,10 @@ Deactivates (logs out of) a system account. This API uses a promise to return th accountManager.deactivateOsAccount(localId).then(() => { console.log('deactivateOsAccount successfully'); }).catch((err: BusinessError) => { - console.log('deactivateOsAccount failed, err:' + JSON.stringify(err)); + console.error('deactivateOsAccount failed, err:' + JSON.stringify(err)); }); } catch (e) { - console.log('deactivateOsAccount exception: ' + JSON.stringify(e)); + console.error('deactivateOsAccount exception: ' + JSON.stringify(e)); } ``` @@ -214,10 +218,10 @@ Checks whether a system account is activated. This API uses a promise to return accountManager.isOsAccountActivated(localId).then((isActivated: boolean) => { console.log('isOsAccountActivated successfully, isActivated: ' + isActivated); }).catch((err: BusinessError) => { - console.log('isOsAccountActivated failed, error: ' + JSON.stringify(err)); + console.error('isOsAccountActivated failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log('isOsAccountActivated exception: ' + JSON.stringify(err)); + console.error('isOsAccountActivated exception: ' + JSON.stringify(err)); } ``` @@ -267,10 +271,10 @@ Checks whether a constraint is enabled for a system account. This API uses a pro accountManager.isOsAccountConstraintEnabled(localId, constraint).then((isEnabled: boolean) => { console.log('isOsAccountConstraintEnabled successfully, isEnabled: ' + isEnabled); }).catch((err: BusinessError) => { - console.log('isOsAccountConstraintEnabled failed, error: ' + JSON.stringify(err)); + console.error('isOsAccountConstraintEnabled failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log('isOsAccountConstraintEnabled exception: ' + JSON.stringify(err)); + console.error('isOsAccountConstraintEnabled exception: ' + JSON.stringify(err)); } ``` @@ -318,10 +322,10 @@ Checks whether a system account has been verified. This API uses a promise to re accountManager.isOsAccountUnlocked(localId).then((isVerified: boolean) => { console.log('isOsAccountUnlocked successfully, isVerified: ' + isVerified); }).catch((err: BusinessError) => { - console.log('isOsAccountUnlocked failed, error: ' + JSON.stringify(err)); + console.error('isOsAccountUnlocked failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log('isOsAccountUnlocked exception: ' + JSON.stringify(err)); + console.error('isOsAccountUnlocked exception: ' + JSON.stringify(err)); } ``` @@ -368,14 +372,14 @@ Removes a system account. This API uses an asynchronous callback to return the r (err: BusinessError, osAccountInfo: osAccount.OsAccountInfo) => { accountManager.removeOsAccount(osAccountInfo.localId, (err: BusinessError)=>{ if (err) { - console.log('removeOsAccount failed, error: ' + JSON.stringify(err)); + console.error('removeOsAccount failed, error: ' + JSON.stringify(err)); } else { console.log('removeOsAccount successfully'); } }); }); } catch (err) { - console.log('removeOsAccount exception: ' + JSON.stringify(err)); + console.error('removeOsAccount exception: ' + JSON.stringify(err)); } ``` @@ -428,11 +432,11 @@ Removes a system account. This API uses a promise to return the result. accountManager.removeOsAccount(osAccountInfo.localId).then(() => { console.log('removeOsAccount successfully'); }).catch((err: BusinessError) => { - console.log('removeOsAccount failed, error: ' + JSON.stringify(err)); + console.error('removeOsAccount failed, error: ' + JSON.stringify(err)); }); }); } catch (err) { - console.log('removeOsAccount exception: ' + JSON.stringify(err)); + console.error('removeOsAccount exception: ' + JSON.stringify(err)); } ``` @@ -454,7 +458,7 @@ Sets or removes constraints for a system account. This API uses an asynchronous | ----------- | ------------------------- | ---- | ----------------------------------------------- | | localId | number | Yes | ID of the target system account. | | constraints | Array<string> | Yes | [Constraints](js-apis-osAccount.md#constraints) to set or remove. | -| enable | boolean | Yes | Set or remove constraints. The value **true** means to set constraints, and **false** means to remove constraints. | +| enable | boolean | Yes | Whether to set or remove constraints. The value **true** means to set constraints, and **false** means to remove constraints. | | callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.| **Error codes** @@ -479,13 +483,13 @@ Sets or removes constraints for a system account. This API uses an asynchronous try { accountManager.setOsAccountConstraints(localId, [constraint], true, (err: BusinessError) => { if (err) { - console.log('setOsAccountConstraints failed, error: ' + JSON.stringify(err)); + console.error('setOsAccountConstraints failed, error: ' + JSON.stringify(err)); } else { console.log('setOsAccountConstraints successfully'); } }); } catch (err) { - console.log('setOsAccountConstraints exception: ' + JSON.stringify(err)); + console.error('setOsAccountConstraints exception: ' + JSON.stringify(err)); } ``` @@ -537,10 +541,10 @@ Sets or removes constraints for a system account. This API uses a promise to ret accountManager.setOsAccountConstraints(localId, ['constraint.location.set'], false).then(() => { console.log('setOsAccountConstraints succsuccessfully'); }).catch((err: BusinessError) => { - console.log('setOsAccountConstraints failed, error: ' + JSON.stringify(err)); + console.error('setOsAccountConstraints failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log('setOsAccountConstraints exception: ' + JSON.stringify(err)); + console.error('setOsAccountConstraints exception: ' + JSON.stringify(err)); } ``` @@ -586,13 +590,13 @@ Sets the name of a system account. This API uses an asynchronous callback to ret try { accountManager.setOsAccountName(localId, name, (err: BusinessError) => { if (err) { - console.log('setOsAccountName failed, error: ' + JSON.stringify(err)); + console.error('setOsAccountName failed, error: ' + JSON.stringify(err)); } else { console.log('setOsAccountName successfully'); } }); } catch (err) { - console.log('setOsAccountName exception: ' + JSON.stringify(err)); + console.error('setOsAccountName exception: ' + JSON.stringify(err)); } ``` @@ -644,10 +648,10 @@ Sets the name of a system account. This API uses a promise to return the result. accountManager.setOsAccountName(localId, name).then(() => { console.log('setOsAccountName successfully'); }).catch((err: BusinessError) => { - console.log('setOsAccountName failed, error: ' + JSON.stringify(err)); + console.error('setOsAccountName failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log('setOsAccountName exception: ' + JSON.stringify(err)); + console.error('setOsAccountName exception: ' + JSON.stringify(err)); } ``` @@ -683,13 +687,13 @@ Queries the maximum number of system accounts that can be created. This API uses try { accountManager.queryMaxOsAccountNumber((err: BusinessError, maxCnt: number) => { if (err) { - console.log('queryMaxOsAccountNumber failed, error:' + JSON.stringify(err)); + console.error('queryMaxOsAccountNumber failed, error:' + JSON.stringify(err)); } else { console.log('queryMaxOsAccountNumber successfully, maxCnt:' + maxCnt); } }); } catch (err) { - console.log('queryMaxOsAccountNumber exception: ' + JSON.stringify(err)); + console.error('queryMaxOsAccountNumber exception: ' + JSON.stringify(err)); } ``` @@ -707,7 +711,7 @@ Queries the maximum number of system accounts that can be created. This API uses | Type | Description | | --------------------- | ------------------------------------------- | -| Promise<number> | Promise used to return the maximum number of system accounts that can be created.| +| Promise<number> | Promise used to return the result.| **Error codes** @@ -725,10 +729,10 @@ Queries the maximum number of system accounts that can be created. This API uses accountManager.queryMaxOsAccountNumber().then((maxCnt: number) => { console.log('queryMaxOsAccountNumber successfully, maxCnt: ' + maxCnt); }).catch((err: BusinessError) => { - console.log('queryMaxOsAccountNumber failed, error: ' + JSON.stringify(err)); + console.error('queryMaxOsAccountNumber failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log('queryMaxOsAccountNumber exception: ' + JSON.stringify(err)); + console.error('queryMaxOsAccountNumber exception: ' + JSON.stringify(err)); } ``` @@ -764,10 +768,10 @@ Queries the maximum number of system accounts allowed to log in to the system. T accountManager.queryMaxLoggedInOsAccountNumber().then((maxNum: number) => { console.log('queryMaxLoggedInOsAccountNumber successfully, maxNum: ' + maxNum); }).catch((err: BusinessError) => { - console.log('queryMaxLoggedInOsAccountNumber failed, error: ' + JSON.stringify(err)); + console.error('queryMaxLoggedInOsAccountNumber failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log('queryMaxLoggedInOsAccountNumber exception: ' + JSON.stringify(err)); + console.error('queryMaxLoggedInOsAccountNumber exception: ' + JSON.stringify(err)); } ``` @@ -815,10 +819,10 @@ Obtains all the enabled constraints of a system account. This API uses a promise accountManager.getEnabledOsAccountConstraints(localId).then((constraints: string[]) => { console.log('getEnabledOsAccountConstraints, constraints: ' + constraints); }).catch((err: BusinessError) => { - console.log('getEnabledOsAccountConstraints err: ' + JSON.stringify(err)); + console.error('getEnabledOsAccountConstraints err: ' + JSON.stringify(err)); }); } catch (e) { - console.log('getEnabledOsAccountConstraints exception: ' + JSON.stringify(e)); + console.error('getEnabledOsAccountConstraints exception: ' + JSON.stringify(e)); } ``` @@ -856,11 +860,14 @@ Queries information about all the system accounts created. This API uses an asyn let accountManager: osAccount.AccountManager = osAccount.getAccountManager(); try { accountManager.queryAllCreatedOsAccounts((err: BusinessError, accountArr: osAccount.OsAccountInfo[])=>{ - console.log('queryAllCreatedOsAccounts err:' + JSON.stringify(err)); - console.log('queryAllCreatedOsAccounts accountArr:' + JSON.stringify(accountArr)); + if (err) { + console.error('queryAllCreatedOsAccounts exception:' + JSON.stringify(err)); + } else { + console.log('queryAllCreatedOsAccounts accountArr:' + JSON.stringify(accountArr)); + } }); } catch (e) { - console.log('queryAllCreatedOsAccounts exception: ' + JSON.stringify(e)); + console.error('queryAllCreatedOsAccounts exception: ' + JSON.stringify(e)); } ``` @@ -899,10 +906,10 @@ Queries information about all the system accounts created. This API uses a promi accountManager.queryAllCreatedOsAccounts().then((accountArr: osAccount.OsAccountInfo[]) => { console.log('queryAllCreatedOsAccounts, accountArr: ' + JSON.stringify(accountArr)); }).catch((err: BusinessError) => { - console.log('queryAllCreatedOsAccounts err: ' + JSON.stringify(err)); + console.error('queryAllCreatedOsAccounts err: ' + JSON.stringify(err)); }); } catch (e) { - console.log('queryAllCreatedOsAccounts exception: ' + JSON.stringify(e)); + console.error('queryAllCreatedOsAccounts exception: ' + JSON.stringify(e)); } ``` @@ -948,11 +955,14 @@ Creates a system account. This API uses an asynchronous callback to return the r try { accountManager.createOsAccount('testName', osAccount.OsAccountType.NORMAL, (err: BusinessError, osAccountInfo: osAccount.OsAccountInfo)=>{ - console.log('createOsAccount err:' + JSON.stringify(err)); - console.log('createOsAccount osAccountInfo:' + JSON.stringify(osAccountInfo)); + if (err) { + console.error('createOsAccount exception:' + JSON.stringify(err)); + } else { + console.log('createOsAccount osAccountInfo:' + JSON.stringify(osAccountInfo)); + } }); } catch (e) { - console.log('createOsAccount exception: ' + JSON.stringify(e)); + console.error('createOsAccount exception: ' + JSON.stringify(e)); } ``` @@ -1003,17 +1013,19 @@ Creates a system account. This API uses a promise to return the result. import { BusinessError } from '@kit.BasicServicesKit'; let accountManager: osAccount.AccountManager = osAccount.getAccountManager(); let options: osAccount.CreateOsAccountOptions = { - shortName: 'myShortName' + shortName: 'myShortName', + disallowedPreinstalledBundles: [], + allowedPreinstalledBundles: [], } try { accountManager.createOsAccount('testAccountName', osAccount.OsAccountType.NORMAL, options).then( (accountInfo: osAccount.OsAccountInfo) => { console.log('createOsAccount, accountInfo: ' + JSON.stringify(accountInfo)); }).catch((err: BusinessError) => { - console.log('createOsAccount err: ' + JSON.stringify(err)); + console.error('createOsAccount err: ' + JSON.stringify(err)); }); } catch (e) { - console.log('createOsAccount exception: ' + JSON.stringify(e)); + console.error('createOsAccount exception: ' + JSON.stringify(e)); } ``` @@ -1062,11 +1074,14 @@ Creates a system account and associates it with the specified domain account. Th try { accountManager.createOsAccountForDomain(osAccount.OsAccountType.NORMAL, domainInfo, (err: BusinessError, osAccountInfo: osAccount.OsAccountInfo)=>{ - console.log('createOsAccountForDomain err:' + JSON.stringify(err)); - console.log('createOsAccountForDomain osAccountInfo:' + JSON.stringify(osAccountInfo)); + if (err) { + console.error('createOsAccountForDomain exception:' + JSON.stringify(err)); + } else { + console.log('createOsAccountForDomain osAccountInfo:' + JSON.stringify(osAccountInfo)); + } }); } catch (e) { - console.log('createOsAccountForDomain exception: ' + JSON.stringify(e)); + console.error('createOsAccountForDomain exception: ' + JSON.stringify(e)); } ``` @@ -1127,10 +1142,10 @@ Creates a system account and associates it with the specified domain account. Th (accountInfo: osAccount.OsAccountInfo) => { console.log('createOsAccountForDomain, account info: ' + JSON.stringify(accountInfo)); }).catch((err: BusinessError) => { - console.log('createOsAccountForDomain err: ' + JSON.stringify(err)); + console.error('createOsAccountForDomain err: ' + JSON.stringify(err)); }); } catch (e) { - console.log('createOsAccountForDomain exception: ' + JSON.stringify(e)); + console.error('createOsAccountForDomain exception: ' + JSON.stringify(e)); } ``` @@ -1169,10 +1184,10 @@ Obtains information about the system account to which the current process belong accountManager.queryOsAccount().then((accountInfo: osAccount.OsAccountInfo) => { console.log('queryOsAccount, accountInfo: ' + JSON.stringify(accountInfo)); }).catch((err: BusinessError) => { - console.log('queryOsAccount err: ' + JSON.stringify(err)); + console.error('queryOsAccount err: ' + JSON.stringify(err)); }); } catch (e) { - console.log('queryOsAccount exception: ' + JSON.stringify(e)); + console.error('queryOsAccount exception: ' + JSON.stringify(e)); } ``` @@ -1214,11 +1229,14 @@ Queries information about the system account of the given ID. This API uses an a let localId: number = 100; try { accountManager.queryOsAccountById(localId, (err: BusinessError, accountInfo: osAccount.OsAccountInfo)=>{ - console.log('queryOsAccountById err:' + JSON.stringify(err)); - console.log('queryOsAccountById accountInfo:' + JSON.stringify(accountInfo)); + if (err) { + console.error('queryOsAccountById exception:' + JSON.stringify(err)); + } else { + console.log('queryOsAccountById accountInfo:' + JSON.stringify(accountInfo)); + } }); } catch (e) { - console.log('queryOsAccountById exception: ' + JSON.stringify(e)); + console.error('queryOsAccountById exception: ' + JSON.stringify(e)); } ``` @@ -1267,10 +1285,10 @@ Queries information about the system account of the given ID. This API uses a pr accountManager.queryOsAccountById(localId).then((accountInfo: osAccount.OsAccountInfo) => { console.log('queryOsAccountById, accountInfo: ' + JSON.stringify(accountInfo)); }).catch((err: BusinessError) => { - console.log('queryOsAccountById err: ' + JSON.stringify(err)); + console.error('queryOsAccountById err: ' + JSON.stringify(err)); }); } catch (e) { - console.log('queryOsAccountById exception: ' + JSON.stringify(e)); + console.error('queryOsAccountById exception: ' + JSON.stringify(e)); } ``` @@ -1312,11 +1330,14 @@ Obtains the profile photo of a system account. This API uses an asynchronous cal let localId: number = 100; try { accountManager.getOsAccountProfilePhoto(localId, (err: BusinessError, photo: string)=>{ - console.log('getOsAccountProfilePhoto err:' + JSON.stringify(err)); - console.log('get photo:' + photo + ' by localId: ' + localId); + if (err) { + console.error('getOsAccountProfilePhoto exception:' + JSON.stringify(err)); + } else { + console.log('get photo:' + photo + ' by localId: ' + localId); + } }); } catch (e) { - console.log('getOsAccountProfilePhoto exception: ' + JSON.stringify(e)); + console.error('getOsAccountProfilePhoto exception: ' + JSON.stringify(e)); } ``` @@ -1365,10 +1386,10 @@ Obtains the profile photo of a system account. This API uses a promise to return accountManager.getOsAccountProfilePhoto(localId).then((photo: string) => { console.log('getOsAccountProfilePhoto: ' + photo); }).catch((err: BusinessError) => { - console.log('getOsAccountProfilePhoto err: ' + JSON.stringify(err)); + console.error('getOsAccountProfilePhoto err: ' + JSON.stringify(err)); }); } catch (e) { - console.log('getOsAccountProfilePhoto exception: ' + JSON.stringify(e)); + console.error('getOsAccountProfilePhoto exception: ' + JSON.stringify(e)); } ``` @@ -1416,10 +1437,14 @@ Sets a profile photo for a system account. This API uses an asynchronous callbac '+7q0mP0DZW9pNmoEFUzrQjp5cCnaen2kSJXLFD8ghbXyZCMQf/8e8Ns1XVAG/XAgqKzVnJFAAAAABJRU5ErkJggg==' try { accountManager.setOsAccountProfilePhoto(localId, photo, (err: BusinessError)=>{ - console.log('setOsAccountProfilePhoto err:' + JSON.stringify(err)); + if (err) { + console.error('setOsAccountProfilePhoto exception:' + JSON.stringify(err)); + } else { + console.log('setOsAccountProfilePhoto successful.'); + } }); } catch (e) { - console.log('setOsAccountProfilePhoto exception: ' + JSON.stringify(e)); + console.error('setOsAccountProfilePhoto exception: ' + JSON.stringify(e)); } ``` @@ -1474,10 +1499,10 @@ Sets a profile photo for a system account. This API uses a promise to return the accountManager.setOsAccountProfilePhoto(localId, photo).then(() => { console.log('setOsAccountProfilePhoto success'); }).catch((err: BusinessError) => { - console.log('setOsAccountProfilePhoto err: ' + JSON.stringify(err)); + console.error('setOsAccountProfilePhoto err: ' + JSON.stringify(err)); }); } catch (e) { - console.log('setOsAccountProfilePhoto exception: ' + JSON.stringify(e)); + console.error('setOsAccountProfilePhoto exception: ' + JSON.stringify(e)); } ``` @@ -1521,7 +1546,7 @@ Subscribes to the system account activation states, including the states of the try { accountManager.on('activating', 'osAccountOnOffNameA', onCallback); } catch (e) { - console.log('receive localId exception: ' + JSON.stringify(e)); + console.error('receive localId exception: ' + JSON.stringify(e)); } ``` @@ -1565,7 +1590,7 @@ Unsubscribes from the system account activation states, including the states of try { accountManager.off('activating', 'osAccountOnOffNameA', offCallback); } catch (e) { - console.log('off exception: ' + JSON.stringify(e)); + console.error('off exception: ' + JSON.stringify(e)); } ``` @@ -1608,7 +1633,7 @@ Subscribes to the switchover between a foreground system account and a backgroun try { accountManager.on('switching', onSwitchingCallback); } catch (e) { - console.log('receive eventData exception: ' + JSON.stringify(e)); + console.error('receive eventData exception: ' + JSON.stringify(e)); } ``` @@ -1648,7 +1673,7 @@ Unsubscribes from the switchover between a foreground system account and a backg try { accountManager.off('switching'); } catch (e) { - console.log('off exception: ' + JSON.stringify(e)); + console.error('off exception: ' + JSON.stringify(e)); } ``` @@ -1691,7 +1716,7 @@ Subscribes to the end of a switchover between a foreground system account and a try { accountManager.on('switched', onSwitchedCallback); } catch (e) { - console.log('receive eventData exception: ' + JSON.stringify(e)); + console.error('receive eventData exception: ' + JSON.stringify(e)); } ``` @@ -1731,7 +1756,7 @@ Unsubscribes from the end of a switchover between a foreground system account an try { accountManager.off('switched'); } catch (e) { - console.log('off exception: ' + JSON.stringify(e)); + console.error('off exception: ' + JSON.stringify(e)); } ``` @@ -1769,11 +1794,14 @@ Obtains the bundle ID based on the UID. This API uses an asynchronous callback t let testUid: number = 1000000; try { accountManager.getBundleIdForUid(testUid, (err: BusinessError, bundleId: number) => { - console.info('getBundleIdForUid errInfo:' + JSON.stringify(err)); - console.info('getBundleIdForUid bundleId:' + JSON.stringify(bundleId)); + if (err) { + console.error('getBundleIdForUid errInfo:' + JSON.stringify(err)); + } else { + console.info('getBundleIdForUid bundleId:' + JSON.stringify(bundleId)); + } }); } catch (e) { - console.info('getBundleIdForUid exception: ' + JSON.stringify(e)); + console.error('getBundleIdForUid exception: ' + JSON.stringify(e)); } ``` @@ -1818,10 +1846,10 @@ Obtains the bundle ID based on the UID. This API uses a promise to return the re accountManager.getBundleIdForUid(testUid).then((result: number) => { console.info('getBundleIdForUid bundleId:' + JSON.stringify(result)); }).catch((err: BusinessError) => { - console.info('getBundleIdForUid errInfo:' + JSON.stringify(err)); + console.error('getBundleIdForUid errInfo:' + JSON.stringify(err)); }); } catch (e) { - console.info('getBundleIdForUid exception: ' + JSON.stringify(e)); + console.error('getBundleIdForUid exception: ' + JSON.stringify(e)); } ``` @@ -1864,7 +1892,7 @@ Obtains the bundle ID based on the specified UID. The API returns the result syn let bundleId : number = accountManager.getBundleIdForUidSync(testUid); console.info('getBundleIdForUidSync bundleId:' + bundleId); } catch (e) { - console.info('getBundleIdForUidSync exception: ' + JSON.stringify(e)); + console.error('getBundleIdForUidSync exception: ' + JSON.stringify(e)); } ``` @@ -1902,11 +1930,14 @@ Checks whether the current process belongs to the main system account. This API let accountManager: osAccount.AccountManager = osAccount.getAccountManager(); try { accountManager.isMainOsAccount((err: BusinessError,result: boolean)=>{ - console.info('isMainOsAccount errInfo:' + JSON.stringify(err)); - console.info('isMainOsAccount result:' + JSON.stringify(result)); + if (err) { + console.error('isMainOsAccount errInfo:' + JSON.stringify(err)); + } else { + console.info('isMainOsAccount result:' + JSON.stringify(result)); + } }); } catch (e) { - console.info('isMainOsAccount exception: ' + JSON.stringify(e)); + console.error('isMainOsAccount exception: ' + JSON.stringify(e)); } ``` @@ -1945,10 +1976,10 @@ Checks whether the current process belongs to the main system account. This API accountManager.isMainOsAccount().then((result: boolean) => { console.info('isMainOsAccount result:' + JSON.stringify(result)); }).catch((err: BusinessError) => { - console.info('isMainOsAccount errInfo:' + JSON.stringify(err)); + console.error('isMainOsAccount errInfo:' + JSON.stringify(err)); }); } catch (e) { - console.info('isMainOsAccount exception: ' + JSON.stringify(e)); + console.error('isMainOsAccount exception: ' + JSON.stringify(e)); } ``` @@ -1991,11 +2022,14 @@ Obtains the constraint source information of a system account. This API uses an try { accountManager.getOsAccountConstraintSourceTypes(100, 'constraint.wifi', (err: BusinessError,sourceTypeInfos: osAccount.ConstraintSourceTypeInfo[])=>{ - console.info('getOsAccountConstraintSourceTypes errInfo:' + JSON.stringify(err)); - console.info('getOsAccountConstraintSourceTypes sourceTypeInfos:' + JSON.stringify(sourceTypeInfos)); + if (err) { + console.error('getOsAccountConstraintSourceTypes errInfo:' + JSON.stringify(err)); + } else { + console.info('getOsAccountConstraintSourceTypes sourceTypeInfos:' + JSON.stringify(sourceTypeInfos)); + } }); } catch (e) { - console.info('getOsAccountConstraintSourceTypes exception: ' + JSON.stringify(e)); + console.error('getOsAccountConstraintSourceTypes exception: ' + JSON.stringify(e)); } ``` @@ -2045,10 +2079,10 @@ Obtains the constraint source information of a system account. This API uses a p (result: osAccount.ConstraintSourceTypeInfo[]) => { console.info('getOsAccountConstraintSourceTypes sourceTypeInfos:' + JSON.stringify(result)); }).catch((err: BusinessError) => { - console.info('getOsAccountConstraintSourceTypes errInfo:' + JSON.stringify(err)); + console.error('getOsAccountConstraintSourceTypes errInfo:' + JSON.stringify(err)); }); } catch (e) { - console.info('getOsAccountConstraintSourceTypes exception: ' + JSON.stringify(e)); + console.error('getOsAccountConstraintSourceTypes exception: ' + JSON.stringify(e)); } ``` @@ -2096,10 +2130,10 @@ Obtains the type of a system account. This API uses a promise to return the resu accountManager.getOsAccountType(localId).then((type: osAccount.OsAccountType) => { console.info('getOsAccountType Type:' + type); }).catch((err: BusinessError) => { - console.info('getOsAccountType errInfo:' + JSON.stringify(err)); + console.error('getOsAccountType errInfo:' + JSON.stringify(err)); }); } catch (e) { - console.info('getOsAccountType exception: ' + JSON.stringify(e)); + console.error('getOsAccountType exception: ' + JSON.stringify(e)); } ``` @@ -2111,8 +2145,6 @@ Provides APIs for user authentication. ### constructor8+ -constructor() - A constructor used to create an instance for user authentication. **System API**: This is a system API. @@ -2203,7 +2235,7 @@ Obtains the available status of the authentication capability corresponding to t let status: number = userAuth.getAvailableStatus(authType, authTrustLevel); console.log('getAvailableStatus status = ' + status); } catch (e) { - console.log('getAvailableStatus exception = ' + JSON.stringify(e)); + console.error('getAvailableStatus exception = ' + JSON.stringify(e)); } ``` @@ -2252,11 +2284,14 @@ Obtains the executor property based on the request. This API uses an asynchronou }; try { userAuth.getProperty(request, (err: BusinessError, result: osAccount.ExecutorProperty) => { - console.log('getProperty err = ' + JSON.stringify(err)); - console.log('getProperty result = ' + JSON.stringify(result)); + if (err) { + console.error('getProperty exception = ' + JSON.stringify(err)); + } else { + console.log('getProperty result = ' + JSON.stringify(result)); + } }); } catch (e) { - console.log('getProperty exception = ' + JSON.stringify(e)); + console.error('getProperty exception = ' + JSON.stringify(e)); } ``` @@ -2312,10 +2347,10 @@ Obtains the executor property based on the request. This API uses a promise to r userAuth.getProperty(request).then((result: osAccount.ExecutorProperty) => { console.log('getProperty result = ' + JSON.stringify(result)); }).catch((err: BusinessError) => { - console.log('getProperty error = ' + JSON.stringify(err)); + console.error('getProperty error = ' + JSON.stringify(err)); }); } catch (e) { - console.log('getProperty exception = ' + JSON.stringify(e)); + console.error('getProperty exception = ' + JSON.stringify(e)); } ``` @@ -2360,31 +2395,33 @@ Obtains the specified property information of the associated executor based on t import { BusinessError } from '@kit.BasicServicesKit'; let userIDM = new osAccount.UserIdentityManager(); let credInfo: osAccount.EnrolledCredInfo[] = []; - try { - credInfo = await userIDM.getAuthInfo(osAccount.AuthType.PRIVATE_PIN); - } catch (e) { - console.log('getAuthInfo exception = ' + JSON.stringify(e)); - return; - } - if (credInfo.length == 0) { - console.log('no credential infos'); - return; - } - let testCredentialId: Uint8Array = credInfo[0].credentialId; - let keys: Array = [ - osAccount.GetPropertyType.AUTH_SUB_TYPE, - osAccount.GetPropertyType.REMAIN_TIMES, - osAccount.GetPropertyType.FREEZING_TIME - ]; - try { - let userAuth = new osAccount.UserAuth(); - userAuth.getPropertyByCredentialId(testCredentialId, keys).then((result: osAccount.ExecutorProperty) => { - console.log('getPropertyByCredentialId result = ' + JSON.stringify(result)); - }).catch((err: BusinessError) => { - console.log('getPropertyByCredentialId error = ' + JSON.stringify(err)); - }); - } catch (e) { - console.log('getPropertyByCredentialId exception = ' + JSON.stringify(e)); + async function getProperty() { + try { + credInfo = await userIDM.getAuthInfo(osAccount.AuthType.PRIVATE_PIN); + } catch (e) { + console.error('getAuthInfo exception = ' + JSON.stringify(e)); + return; + } + if (credInfo.length == 0) { + console.log('no credential infos'); + return; + } + let testCredentialId: Uint8Array = credInfo[0].credentialId; + let keys: Array = [ + osAccount.GetPropertyType.AUTH_SUB_TYPE, + osAccount.GetPropertyType.REMAIN_TIMES, + osAccount.GetPropertyType.FREEZING_TIME + ]; + try { + let userAuth = new osAccount.UserAuth(); + userAuth.getPropertyByCredentialId(testCredentialId, keys).then((result: osAccount.ExecutorProperty) => { + console.log('getPropertyByCredentialId result = ' + JSON.stringify(result)); + }).catch((err: BusinessError) => { + console.error('getPropertyByCredentialId error = ' + JSON.stringify(err)); + }); + } catch (e) { + console.error('getPropertyByCredentialId exception = ' + JSON.stringify(e)); + } } ``` @@ -2429,13 +2466,13 @@ Sets the property for the initialization algorithm. This API uses an asynchronou try { userAuth.setProperty(request, (err: BusinessError) => { if (err) { - console.log('setProperty failed, error = ' + JSON.stringify(err)); + console.error('setProperty failed, error = ' + JSON.stringify(err)); } else { console.log('setProperty successfully'); } }); } catch (e) { - console.log('setProperty exception = ' + JSON.stringify(e)); + console.error('setProperty exception = ' + JSON.stringify(e)); } ``` @@ -2486,10 +2523,10 @@ Sets the property for the initialization algorithm. This API uses a promise to r userAuth.setProperty(request).then(() => { console.log('setProperty successfully'); }).catch((err: BusinessError) => { - console.log('setProperty failed, error = ' + JSON.stringify(err)); + console.error('setProperty failed, error = ' + JSON.stringify(err)); }); } catch (e) { - console.log('setProperty exception = ' + JSON.stringify(e)); + console.error('setProperty exception = ' + JSON.stringify(e)); } ``` @@ -2540,11 +2577,11 @@ Prepares for remote authentication. This API uses a promise to return the result userAuth.prepareRemoteAuth(data[0].networkId).then(() => { console.log('prepareRemoteAuth successfully'); }).catch((err: BusinessError) => { - console.log('prepareRemoteAuth failed, error = ' + JSON.stringify(err)); + console.error('prepareRemoteAuth failed, error = ' + JSON.stringify(err)); }); } } catch (e) { - console.log('prepareRemoteAuth exception = ' + JSON.stringify(e)); + console.error('prepareRemoteAuth exception = ' + JSON.stringify(e)); } } ) @@ -2586,15 +2623,19 @@ Performs authentication of the current user. This API uses an asynchronous callb | 401 |Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | | 12300001 | The system service works abnormally. | | 12300002 | Invalid challenge, authType or authTrustLevel. | +| 12300013 | Network exception. | | 12300101 | The credential is incorrect. | -| 12300102 | Credential not enrolled. | +| 12300102 | The credential does not exist. | | 12300105 | The trust level is not supported. | | 12300106 | The authentication type is not supported. | | 12300109 | The authentication, enrollment, or update operation is canceled. | | 12300110 | The authentication is locked. | | 12300111 | The authentication time out. | | 12300112 | The authentication service is busy. | +| 12300113 | The authentication service does not exist. | +| 12300114 | The authentication service works abnormally. | | 12300117 | PIN is expired. | +| 12300211 | Server unreachable. | **Example** ```ts @@ -2610,7 +2651,7 @@ Performs authentication of the current user. This API uses an asynchronous callb } }); } catch (e) { - console.log('auth exception = ' + JSON.stringify(e)); + console.error('auth exception = ' + JSON.stringify(e)); } ``` @@ -2652,15 +2693,19 @@ Starts user authentication based on the specified challenge value, authenticatio | 12300001 | The system service works abnormally. | | 12300002 | Invalid challenge, authType, authTrustLevel or options. | | 12300003 | Account not found. | +| 12300013 | Network exception. | | 12300101 | The credential is incorrect. | -| 12300102 | Credential not enrolled. | +| 12300102 | The credential does not exist. | | 12300105 | The trust level is not supported. | | 12300106 | The authentication type is not supported. | | 12300109 | The authentication, enrollment, or update operation is canceled. | | 12300110 | The authentication is locked. | | 12300111 | The authentication time out. | | 12300112 | The authentication service is busy. | +| 12300113 | The authentication service does not exist. | +| 12300114 | The authentication service works abnormally. | | 12300117 | PIN is expired. | +| 12300211 | Server unreachable. | **Example** ```ts @@ -2679,7 +2724,7 @@ Starts user authentication based on the specified challenge value, authenticatio } }); } catch (e) { - console.log('auth exception = ' + JSON.stringify(e)); + console.error('auth exception = ' + JSON.stringify(e)); } ``` @@ -2720,16 +2765,20 @@ Performs authentication of the specified user. This API uses an asynchronous cal | 401 |Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | | 12300001 | The system service works abnormally. | | 12300002 | Invalid challenge, authType or authTrustLevel. | -| 12300101 | The credential is incorrect. | -| 12300102 | Credential not enrolled. | | 12300003 | Account not found. | +| 12300013 | Network exception. | +| 12300101 | The credential is incorrect. | +| 12300102 | The credential does not exist. | | 12300105 | The trust level is not supported. | | 12300106 | The authentication type is not supported. | | 12300109 | The authentication, enrollment, or update operation is canceled. | | 12300110 | The authentication is locked. | | 12300111 | The authentication time out. | | 12300112 | The authentication service is busy. | +| 12300113 | The authentication service does not exist. | +| 12300114 | The authentication service works abnormally. | | 12300117 | PIN is expired. | +| 12300211 | Server unreachable. | **Example** ```ts @@ -2746,7 +2795,7 @@ Performs authentication of the specified user. This API uses an asynchronous cal } }); } catch (e) { - console.log('authUser exception = ' + JSON.stringify(e)); + console.error('authUser exception = ' + JSON.stringify(e)); } ``` @@ -2766,7 +2815,7 @@ Cancels an authentication. | Name | Type | Mandatory | Description | | ----------| ---------- | ---- | ------------------------------------------ | -| contextId | Uint8Array | Yes | ID of the authentication context. The context ID is dynamically generated.| +| contextID | Uint8Array | Yes | ID of the authentication context. The context ID is dynamically generated.| **Error codes** @@ -2779,6 +2828,7 @@ Cancels an authentication. | 12300002 | Invalid contextId. | **Example** + ```ts let userAuth = new osAccount.UserAuth(); let pinAuth: osAccount.PINAuth = new osAccount.PINAuth(); @@ -2792,7 +2842,7 @@ Cancels an authentication. try { userAuth.cancelAuth(contextId); } catch (e) { - console.log('cancelAuth exception = ' + JSON.stringify(e)); + console.error('cancelAuth exception = ' + JSON.stringify(e)); } ``` @@ -2804,8 +2854,6 @@ Provides APIs for PIN authentication. ### constructor8+ -constructor() - Creates a PIN authentication instance. **System API**: This is a system API. @@ -2864,7 +2912,7 @@ Registers a PIN inputer. }); console.log('registerInputer success.'); } catch (e) { - console.log('registerInputer exception = ' + JSON.stringify(e)); + console.error('registerInputer exception = ' + JSON.stringify(e)); } ``` @@ -2940,7 +2988,7 @@ Registers a credential inputer. }); console.log('registerInputer success.'); } catch (e) { - console.log('registerInputer exception = ' + JSON.stringify(e)); + console.error('registerInputer exception = ' + JSON.stringify(e)); } ``` @@ -2978,7 +3026,7 @@ Unregisters this credential inputer. osAccount.InputerManager.unregisterInputer(authType); console.log('unregisterInputer success.'); } catch(err) { - console.log('unregisterInputer err:' + JSON.stringify(err)); + console.error('unregisterInputer err:' + JSON.stringify(err)); } ``` @@ -3049,7 +3097,7 @@ Authenticates a domain account. } }); } catch (err) { - console.log('auth exception = ' + JSON.stringify(err)); + console.error('auth exception = ' + JSON.stringify(err)); } ``` @@ -3276,6 +3324,7 @@ Binds a domain account. | Name | Type | Mandatory| Description | | ---------- | --------------------------------------- | ---- | --------------- | | domainAccountInfo | [DomainAccountInfo](#domainaccountinfo8) | Yes | Domain account information.| +| localId | number | Yes | ID of the target system account.| | callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** @@ -3377,7 +3426,7 @@ Checks whether the specified domain account token is valid. | ---------- | --------------------------------------- | ---- | --------------- | | domainAccountInfo | [DomainAccountInfo](#domainaccountinfo8) | Yes | Domain account information.| | token | Uint8Array | Yes| Domain account token to check.| -| callback | AsyncCallback<boolean> | Yes | Callback used to return the result.| +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. The value **true** means that the specified domain account token is valid; the value **false** means the opposite.| **Example** ```ts @@ -3490,7 +3539,8 @@ Registers a domain plug-in. | -------- | --------------------------- | | 201 | Permission denied.| | 202 | Not system application.| -| 401 |Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | +| 801 | Capability not supported.| | 12300201 | The domain plugin has been registered. | **Example** @@ -3518,7 +3568,7 @@ Registers a domain plug-in. osAccount.DomainAccountManager.registerPlugin(plugin); console.log('registerPlugin success.'); } catch(err) { - console.log('registerPlugin err:' + JSON.stringify(err)); + console.error('registerPlugin err:' + JSON.stringify(err)); } ``` @@ -3540,6 +3590,7 @@ Unregisters this domain plug-in. | -------- | --------------------------- | | 201 | Permission denied.| | 202 | Not system application.| +| 801 | Capability not supported.| **Example** ```ts @@ -3547,7 +3598,7 @@ Unregisters this domain plug-in. osAccount.DomainAccountManager.unregisterPlugin(); console.log('unregisterPlugin success.'); } catch(err) { - console.log('unregisterPlugin err:' + JSON.stringify(err)); + console.error('unregisterPlugin err:' + JSON.stringify(err)); } ``` @@ -3590,6 +3641,7 @@ Authenticates a domain account. | 12300112 | The authentication service is busy. | | 12300113 | The account authentication service does not exist. | | 12300114 | The account authentication service works abnormally. | +| 12300211 | Server unreachable. | **Example** ```ts @@ -3606,7 +3658,7 @@ Authenticates a domain account. } }); } catch (err) { - console.log('auth exception = ' + JSON.stringify(err)); + console.error('auth exception = ' + JSON.stringify(err)); } ``` @@ -3648,6 +3700,7 @@ No permission is required since API version 11. Use the SDK of the latest versio | 12300112 | The authentication service is busy. | | 12300113 | The account authentication service does not exist. | | 12300114 | The account authentication service works abnormally. | +| 12300211 | Server unreachable. | **Example** ```ts @@ -3659,7 +3712,7 @@ No permission is required since API version 11. Use the SDK of the latest versio } }) } catch (err) { - console.log('auth exception = ' + JSON.stringify(err)); + console.error('auth exception = ' + JSON.stringify(err)); } ``` @@ -3703,6 +3756,7 @@ No permission is required since API version 11. Use the SDK of the latest versio | 12300112 | The authentication service is busy. | | 12300113 | The account authentication service does not exist. | | 12300114 | The account authentication service works abnormally. | +| 12300211 | Server unreachable. | **Example** ```ts @@ -3714,7 +3768,7 @@ No permission is required since API version 11. Use the SDK of the latest versio } }) } catch (err) { - console.log('authWithPopup exception = ' + JSON.stringify(err)); + console.error('authWithPopup exception = ' + JSON.stringify(err)); } ``` @@ -3735,7 +3789,7 @@ Checks whether a domain account exists. | Name | Type | Mandatory| Description | | ---------- | --------------------------------------- | ---- | --------------- | | domainAccountInfo | [DomainAccountInfo](#domainaccountinfo8) | Yes | Domain account information.| -| callback | AsyncCallback<boolean> | Yes | Callback used to return the result.| +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. The value **true** means that the specified domain account exists; the value **false** means the opposite.| **Error codes** @@ -3748,7 +3802,10 @@ Checks whether a domain account exists. | 12300001 | The system service works abnormally. | | 12300002 | Invalid domainAccountInfo. | | 12300013 | Network exception. | -| 12300111 | The authentication time out. | +| 12300014 | Not authenticated. | +| 12300111 | The operation time out. | +| 12300114 | The authentication service works abnormally. | +| 12300211 | Server unreachable. | **Example** ```ts @@ -3760,13 +3817,13 @@ Checks whether a domain account exists. try { osAccount.DomainAccountManager.hasAccount(domainAccountInfo, (err: BusinessError, result: boolean) => { if (err) { - console.log('call hasAccount failed, error: ' + JSON.stringify(err)); + console.error('call hasAccount failed, error: ' + JSON.stringify(err)); } else { console.log('hasAccount result: ' + result); } }); } catch (err) { - console.log('hasAccount exception = ' + JSON.stringify(err)); + console.error('hasAccount exception = ' + JSON.stringify(err)); } ``` @@ -3792,7 +3849,7 @@ Checks whether a domain account exists. | Type | Description | | :------------------------ | ----------------------- | -| Promise<boolean> | Promise used to return the result.| +| Promise<boolean> | Promise used to return the result. The value **true** means that the specified domain account exists; the value **false** means the opposite.| **Error codes** @@ -3805,7 +3862,10 @@ Checks whether a domain account exists. | 12300001 | The system service works abnormally. | | 12300002 | Invalid domainAccountInfo. | | 12300013 | Network exception. | -| 12300111 | The authentication time out. | +| 12300014 | Not authenticated. | +| 12300111 | The operation time out. | +| 12300114 | The authentication service works abnormally. | +| 12300211 | Server unreachable. | **Example** ```ts @@ -3818,10 +3878,10 @@ Checks whether a domain account exists. osAccount.DomainAccountManager.hasAccount(domainAccountInfo).then((result: boolean) => { console.log('hasAccount result: ' + result); }).catch((err: BusinessError) => { - console.log('call hasAccount failed, error: ' + JSON.stringify(err)); + console.error('call hasAccount failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log('hasAccount exception = ' + JSON.stringify(err)); + console.error('hasAccount exception = ' + JSON.stringify(err)); } ``` @@ -3843,7 +3903,7 @@ Updates the token of a domain account. An empty token means an invalid token. Th | ---------- | --------------------------------------- | ---- | --------------- | | domainAccountInfo | [DomainAccountInfo](#domainaccountinfo8) | Yes | Domain account information.| | token | Uint8Array | Yes | New domain account token.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the token is successfully updated, **err** is **null**. Otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.| **Error codes** @@ -3868,13 +3928,13 @@ Updates the token of a domain account. An empty token means an invalid token. Th try { osAccount.DomainAccountManager.updateAccountToken(domainAccountInfo, token, (err: BusinessError) => { if (err != null) { - console.log('updateAccountToken failed, error: ' + JSON.stringify(err)); + console.error('updateAccountToken failed, error: ' + JSON.stringify(err)); } else { console.log('updateAccountToken successfully'); } }) } catch (err) { - console.log('updateAccountToken exception = ' + JSON.stringify(err)); + console.error('updateAccountToken exception = ' + JSON.stringify(err)); } ``` @@ -3927,60 +3987,10 @@ Updates the token of a domain account. An empty token means an invalid token. Th osAccount.DomainAccountManager.updateAccountToken(domainAccountInfo, token).then(() => { console.log('updateAccountToken successfully'); }).catch((err: BusinessError) => { - console.log('updateAccountToken failed, error: ' + JSON.stringify(err)); + console.error('updateAccountToken failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log('updateAccountToken exception = ' + JSON.stringify(err)); - } - ``` - -### updateAccountInfo12+ - -updateAccountInfo(oldAccountInfo: DomainAccountInfo, newAccountInfo: DomainAccountInfo): Promise<void> - -Updates information of a domain account. This API uses a promise to return the result. - -**System API**: This is a system API. - -**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS - -**System capability**: SystemCapability.Account.OsAccount - -**Parameters** - -| Name | Type | Mandatory| Description | -| ---------- | --------------------------------------- | ---- | --------------- | -| oldAccountInfo | [DomainAccountInfo](#domainaccountinfo8) | Yes | Domain account information.| -| newAccountInfo | [DomainAccountInfo](#domainaccountinfo8) | Yes | New domain account information.| - -**Error codes** - -| ID| Error Message | -| -------- | --------------------------- | -| 201 | Permission denied.| -| 202 | Not system application.| -| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | -| 801 | Capability not supported.| -| 12300001 | The system service works abnormally. | -| 12300002 | The new account info is invalid. | -| 12300003 | The old account not found. | -| 12300004 | The new account already exists. | - -**Example** - ```ts - import { BusinessError } from '@kit.BasicServicesKit'; - let oldDomainInfo: osAccount.DomainAccountInfo = - {domain: 'testDomain', accountName: 'oldtestAccountName'}; - let newDomainInfo: osAccount.DomainAccountInfo = - {domain: 'testDomain', accountName: 'newtestAccountName'}; - try { - osAccount.DomainAccountManager.updateAccountInfo(oldDomainInfo, newDomainInfo).then(() => { - console.log('updateAccountInfo, success'); - }).catch((err: BusinessError) => { - console.log('updateAccountInfo err: ' + err); - }); - } catch (e) { - console.log('updateAccountInfo exception: ' + e); + console.error('updateAccountToken exception = ' + JSON.stringify(err)); } ``` @@ -4014,7 +4024,10 @@ Obtains information about the specified domain account. This API uses an asynchr | 12300001 | The system service works abnormally. | | 12300003 | Account not found. | | 12300013 | Network exception. | -| 12300111 | The authentication time out. | +| 12300014 | Not authenticated. | +| 12300111 | The operation time out. | +| 12300114 | The authentication service works abnormally. | +| 12300211 | Server unreachable. | **Example** ```ts @@ -4027,13 +4040,13 @@ Obtains information about the specified domain account. This API uses an asynchr osAccount.DomainAccountManager.getAccountInfo(domainAccountInfo, (err: BusinessError, result: osAccount.DomainAccountInfo) => { if (err) { - console.log('call getAccountInfo failed, error: ' + JSON.stringify(err)); + console.error('call getAccountInfo failed, error: ' + JSON.stringify(err)); } else { console.log('getAccountInfo result: ' + result); } }); } catch (err) { - console.log('getAccountInfo exception = ' + JSON.stringify(err)); + console.error('getAccountInfo exception = ' + JSON.stringify(err)); } ``` @@ -4072,7 +4085,10 @@ Obtains information about the specified domain account. This API uses a promise | 12300001 | The system service works abnormally. | | 12300003 | Account not found. | | 12300013 | Network exception. | -| 12300111 | The authentication time out. | +| 12300014 | Not authenticated. | +| 12300111 | The operation time out. | +| 12300114 | The authentication service works abnormally. | +| 12300211 | Server unreachable. | **Example** ```ts @@ -4086,10 +4102,10 @@ Obtains information about the specified domain account. This API uses a promise .then((result: osAccount.DomainAccountInfo) => { console.log('getAccountInfo result: ' + result); }).catch((err: BusinessError) => { - console.log('call getAccountInfo failed, error: ' + JSON.stringify(err)); + console.error('call getAccountInfo failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log('getAccountInfo exception = ' + JSON.stringify(err)); + console.error('getAccountInfo exception = ' + JSON.stringify(err)); } ``` @@ -4122,7 +4138,9 @@ Obtains the service access token of this domain account. This API uses an asynch | 12300003 | Domain account not found. | | 12300013 | Network exception. | | 12300014 | The domain account is not authenticated. | -| 12300111 | The authentication time out. | +| 12300111 | The operation time out. | +| 12300114 | The authentication service works abnormally. | +| 12300211 | Server unreachable. | **Example** ```ts @@ -4135,13 +4153,13 @@ Obtains the service access token of this domain account. This API uses an asynch osAccount.DomainAccountManager.getAccessToken(businessParams, (err: BusinessError, result: Uint8Array) => { if (err) { - console.log('getAccessToken failed, error: ' + JSON.stringify(err)); + console.error('getAccessToken failed, error: ' + JSON.stringify(err)); } else { console.log('getAccessToken result: ' + result); } }); } catch (err) { - console.log('getAccessToken exception = ' + JSON.stringify(err)); + console.error('getAccessToken exception = ' + JSON.stringify(err)); } ``` @@ -4179,7 +4197,9 @@ Obtains the service access token of this domain account. This API uses a promise | 12300003 | Domain account not found. | | 12300013 | Network exception. | | 12300014 | The domain account is not authenticated. | -| 12300111 | The authentication time out. | +| 12300111 | The operation time out. | +| 12300114 | The authentication service works abnormally. | +| 12300211 | Server unreachable. | **Example** ```ts @@ -4193,10 +4213,10 @@ Obtains the service access token of this domain account. This API uses a promise .then((result: Uint8Array) => { console.log('getAccessToken result: ' + result); }).catch((err: BusinessError) => { - console.log('getAccessToken failed, error: ' + JSON.stringify(err)); + console.error('getAccessToken failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log('getAccessToken exception = ' + JSON.stringify(err)); + console.error('getAccessToken exception = ' + JSON.stringify(err)); } ``` @@ -4222,7 +4242,7 @@ Checks whether the authentication of a domain account has expired. This API uses | Type | Description | | :------------------------ | ----------------------- | -| Promise<boolean> | Promise used to return the result.| +| Promise<boolean> | Promise used to return the result. The value **true** means that the specified domain account has expired; the value **false** means the opposite.| **Error codes** @@ -4244,185 +4264,13 @@ Checks whether the authentication of a domain account has expired. This API uses osAccount.DomainAccountManager.isAuthenticationExpired(domainInfo).then((result: boolean) => { console.log('isAuthenticationExpired, result: ' + result); }).catch((err: BusinessError) => { - console.log('isAuthenticationExpired err: ' + err); + console.error('isAuthenticationExpired err: ' + err); }); } catch (e) { - console.log('isAuthenticationExpired exception: ' + e); + console.error('isAuthenticationExpired exception: ' + e); } ``` -## DomainServerConfig12+ - -Represents the configuration of a domain server. - -**System API**: This is a system API. - -**System capability**: SystemCapability.Account.OsAccount - -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | ---------- | -| parameters | Record | Yes | Server configuration parameters.| -| id | string | Yes | Server configuration ID.| -| domain | string | Yes| Domain to which the server belongs.| - -## DomainServerConfigManager12+ - -Provides APIs for domain server configuration and management. - -### addServerConfig12+ - -static addServerConfig(parameters: Record<string, Object>): Promise<DomainServerConfig> - -Adds domain server configuration. This API uses a promise to return the result. - -**System API**: This is a system API. - -**System capability**: SystemCapability.Account.OsAccount - -**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS - -**Parameters** - -| Name | Type | Mandatory| Description | -| ----------| ----------------------- | --- | -------------------------- | -| parameters | Record | Yes | Configuration parameters of the domain server.| - -**Return value** - -| Type | Description | -| :------------------------ | ----------------------- | -| Promise<[DomainServerConfig](#domainserverconfig12)> | Promise used to return the configuration of the newly added domain server.| - -**Error codes** - -| ID| Error Message | -| -------- | --------------------------- | -| 201 | Permission denied.| -| 202 | Not system application.| -| 401 |Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | -| 801 | Capability not supported.| -| 12300001 | The system service works abnormally. | -| 12300002 | - Invalid server config parameters. | -| 12300211 | - Server unreachable. | - -**Example** - ```ts - import { BusinessError } from '@kit.BasicServicesKit'; - let configParams: Record = { - 'uri': 'test.example.com', - 'port': 100 - }; - osAccount.DomainServerConfigManager.addServerConfig(configParams).then(( - serverConfig: osAccount.DomainServerConfig) => { - console.log('add server configuration successfully, the return config: ' + JSON.stringify(serverConfig)); - }).catch((err: BusinessError) => { - console.log('add server configuration failed, error: ' + JSON.stringify(err)); - }); - ``` - -### removeServerConfig12+ - -static removeServerConfig(configId: string): Promise<void> - -Deletes domain server configuration. This API uses a promise to return the result. - -**System API**: This is a system API. - -**System capability**: SystemCapability.Account.OsAccount - -**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS - -**Parameters** - -| Name | Type | Mandatory| Description | -| ----------| ----------------------- | --- | -------------------------- | -| configId | string | Yes | Server configuration ID.| - -**Return value** - -| Type | Description | -| :------------------------ | ----------------------- | -| Promise<void> | Promise that returns no value.| - -**Error codes** - -| ID| Error Message | -| -------- | --------------------------- | -| 201 | Permission denied.| -| 202 | Not system application.| -| 401 |Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | -| 801 | Capability not supported.| -| 12300001 | The system service works abnormally. | -| 12300212 | - Server config not found. | - -**Example** - ```ts - import { BusinessError } from '@kit.BasicServicesKit'; - let configParams: Record = { - 'uri': 'test.example.com', - 'port': 100 - }; - osAccount.DomainServerConfigManager.addServerConfig(configParams).then(( - serverConfig: osAccount.DomainServerConfig) => { - console.log('add domain server configuration successfully, the added config: ' + JSON.stringify(serverConfig)); - osAccount.DomainServerConfigManager.removeServerConfig(serverConfig.id); - console.log('remove domain server configuration successfully'); - }).catch((err: BusinessError) => { - console.log('add server configuration failed, error: ' + JSON.stringify(err)); - }); - ``` - -### getAccountServerConfig12+ - -static getAccountServerConfig(domainAccountInfo: DomainAccountInfo): Promise<DomainServerConfig> - -Obtains the server configuration of a domain account. This API uses a promise to return the result. - -**System API**: This is a system API. - -**System capability**: SystemCapability.Account.OsAccount - -**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS - -**Parameters** - -| Name | Type | Mandatory| Description | -| ----------| ----------------------- | --- | -------------------------- | -| domainAccountInfo | [DomainAccountInfo](#domainaccountinfo8) | Yes | Information of the domain account.| - -**Return value** - -| Type | Description | -| :------------------------ | ----------------------- | -| Promise<[DomainServerConfig](#domainserverconfig12)> | Promise used to return the domain server configuration of the account.| - -**Error codes** - -| ID| Error Message | -| -------- | --------------------------- | -| 201 | Permission denied.| -| 202 | Not system application.| -| 401 |Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | -| 801 | Capability not supported.| -| 12300001 | The system service works abnormally. | -| 12300003 | Domain account not found. | - -**Example** - ```ts - import { BusinessError } from '@kit.BasicServicesKit'; - let accountInfo: osAccount.DomainAccountInfo = { - 'accountName': 'demoName', - 'accountId': 'demoId', - 'domain': 'demoDomain' - }; - osAccount.DomainServerConfigManager.getAccountServerConfig(accountInfo).then(( - serverConfig: osAccount.DomainServerConfig) => { - console.log('get account server configuration successfully, the return config: ' + JSON.stringify(serverConfig)); - }).catch((err: BusinessError) => { - console.log('add server configuration failed, error: ' + JSON.stringify(err)); - }); - ``` - ## UserIdentityManager8+ Provides APIs for user IDM. @@ -4481,11 +4329,14 @@ Opens a session to obtain the challenge value. This API uses an asynchronous cal let userIDM = new osAccount.UserIdentityManager(); try { userIDM.openSession((err: BusinessError, challenge: Uint8Array) => { - console.log('openSession error = ' + JSON.stringify(err)); + if (err) { + console.error('openSession exception = ' + JSON.stringify(err)); + } else { console.log('openSession challenge = ' + JSON.stringify(challenge)); + } }); } catch (e) { - console.log('openSession exception = ' + JSON.stringify(e)); + console.error('openSession exception = ' + JSON.stringify(e)); } ``` @@ -4533,10 +4384,10 @@ Opens a session. This API returns a challenge value, which can be used to determ userIDM.openSession(accountId).then((challenge: Uint8Array) => { console.info('openSession challenge = ' + JSON.stringify(challenge)); }).catch((err: BusinessError) => { - console.info('openSession error = ' + JSON.stringify(err)); + console.error('openSession error = ' + JSON.stringify(err)); }); } catch (e) { - console.log('openSession exception = ' + JSON.stringify(e)); + console.error('openSession exception = ' + JSON.stringify(e)); } ``` @@ -4573,7 +4424,7 @@ Adds credential information, including the credential type, subtype, and token ( | 12300101 | The token is invalid. | | 12300106 | The authentication type is not supported. | | 12300109 | The authentication, enrollment, or update operation is canceled. | -| 12300111 | The authentication time out. | +| 12300111 | The operation time out. | | 12300115 | The number of credentials reaches the upper limit. | | 12300116 | Credential complexity verification failed. | @@ -4602,7 +4453,7 @@ Adds credential information, including the credential type, subtype, and token ( } }); } catch (e) { - console.log('addCredential exception = ' + JSON.stringify(e)); + console.error('addCredential exception = ' + JSON.stringify(e)); } }); ``` @@ -4634,13 +4485,13 @@ Updates credential information. This API uses an asynchronous callback to return | 202 | Not system application.| | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | | 12300001 | The system service works abnormally. | -| 12300002 | Invalid credentialInfo, i.e. authType or authSubType or token. | +| 12300002 | Invalid credentialInfo, i.e. authType or authSubType. | | 12300003 | Account not found. | | 12300101 | The token is invalid. | -| 12300102 | Credential not enrolled.| +| 12300102 | The credential does not exist. | | 12300106 | The authentication type is not supported. | | 12300109 | The authentication, enrollment, or update operation is canceled. | -| 12300111 | The authentication time out. | +| 12300111 | The operation time out. | | 12300116 | Credential complexity verification failed. | **Example** @@ -4677,7 +4528,7 @@ Updates credential information. This API uses an asynchronous callback to return } }); } catch (e) { - console.log('updateCredential exception = ' + JSON.stringify(e)); + console.error('updateCredential exception = ' + JSON.stringify(e)); } } }); @@ -4755,7 +4606,7 @@ Cancels an entry based on the challenge value. try { userIDM.cancel(challenge); } catch(err) { - console.log('cancel err:' + JSON.stringify(err)); + console.error('cancel err:' + JSON.stringify(err)); } ``` @@ -4800,7 +4651,7 @@ Deletes a user based on the authentication token. This API uses a callback to re } }); } catch (e) { - console.log('delUser exception = ' + JSON.stringify(e)); + console.error('delUser exception = ' + JSON.stringify(e)); } ``` @@ -4834,7 +4685,7 @@ Deletes user credential information. | 12300001 | The system service works abnormally. | | 12300002 | Invalid credentialId. | | 12300101 | The token is invalid. | -| 12300102 | Credential not enrolled. | +| 12300102 | The credential does not exist. | **Example** ```ts @@ -4849,7 +4700,7 @@ Deletes user credential information. } }); } catch (e) { - console.log('delCred exception = ' + JSON.stringify(e)); + console.error('delCred exception = ' + JSON.stringify(e)); } ``` @@ -4879,7 +4730,6 @@ Obtains authentication information. This API uses an asynchronous callback to re | 202 | Not system application.| | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | | 12300001 | The system service works abnormally. | -| 12300102 | Credential not enrolled. | **Example** ```ts @@ -4887,11 +4737,14 @@ Obtains authentication information. This API uses an asynchronous callback to re let userIDM = new osAccount.UserIdentityManager(); try { userIDM.getAuthInfo((err: BusinessError, result: osAccount.EnrolledCredInfo[]) => { - console.log('getAuthInfo err = ' + JSON.stringify(err)); - console.log('getAuthInfo result = ' + JSON.stringify(result)); + if (err) { + console.error('getAuthInfo exception = ' + JSON.stringify(err)); + } else { + console.log('getAuthInfo result = ' + JSON.stringify(result)); + } }); } catch (e) { - console.log('getAuthInfo exception = ' + JSON.stringify(e)); + console.error('getAuthInfo exception = ' + JSON.stringify(e)); } ``` @@ -4923,7 +4776,6 @@ Obtains authentication information of the specified type. This API uses an async | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | | 12300001 | The system service works abnormally. | | 12300002 | Invalid authType. | -| 12300102 | Credential not enrolled. | **Example** ```ts @@ -4932,11 +4784,14 @@ Obtains authentication information of the specified type. This API uses an async try { userIDM.getAuthInfo(osAccount.AuthType.PIN, (err: BusinessError, result: osAccount.EnrolledCredInfo[]) => { - console.log('getAuthInfo err = ' + JSON.stringify(err)); - console.log('getAuthInfo result = ' + JSON.stringify(result)); + if (err) { + console.error('getAuthInfo exception = ' + JSON.stringify(err)); + } else { + console.log('getAuthInfo result = ' + JSON.stringify(result)); + } }); } catch (e) { - console.log('getAuthInfo exception = ' + JSON.stringify(e)); + console.error('getAuthInfo exception = ' + JSON.stringify(e)); } ``` @@ -4944,7 +4799,7 @@ Obtains authentication information of the specified type. This API uses an async getAuthInfo(authType?: AuthType): Promise<Array<EnrolledCredInfo>>; -Obtains authentication information of the specified type. This API uses a promise to return the result. +Obtains authentication information. This API uses a promise to return the result. **System API**: This is a system API. @@ -4973,7 +4828,6 @@ Obtains authentication information of the specified type. This API uses a promis | 401 | Parameter error. Possible causes: Incorrect parameter types. | | 12300001 | The system service works abnormally. | | 12300002 | Invalid authType. | -| 12300102 | Credential not enrolled. | **Example** ```ts @@ -4983,10 +4837,10 @@ Obtains authentication information of the specified type. This API uses a promis userIDM.getAuthInfo(osAccount.AuthType.PIN).then((result: osAccount.EnrolledCredInfo[]) => { console.log('getAuthInfo result = ' + JSON.stringify(result)) }).catch((err: BusinessError) => { - console.log('getAuthInfo error = ' + JSON.stringify(err)); + console.error('getAuthInfo error = ' + JSON.stringify(err)); }); } catch (e) { - console.log('getAuthInfo exception = ' + JSON.stringify(e)); + console.error('getAuthInfo exception = ' + JSON.stringify(e)); } ``` @@ -5006,7 +4860,7 @@ Obtains authentication information. This API uses a promise to return the result | Name | Type | Mandatory| Description | | -------- | ----------------------------------- | ---- | -------- | -| options | [GetAuthInfoOptions](#getauthinfooptions12) | No | Optional parameters for obtaining authentication information.| +| options | [GetAuthInfoOptions](#getauthinfooptions12) | No | Optional parameters for obtaining authentication information. This parameter is left empty by default, indicating that all enrolled credential information of the current user is obtained.| **Return value** @@ -5037,10 +4891,10 @@ Obtains authentication information. This API uses a promise to return the result userIDM.getAuthInfo(options).then((result: osAccount.EnrolledCredInfo[]) => { console.log('getAuthInfo result = ' + JSON.stringify(result)) }).catch((err: BusinessError) => { - console.log('getAuthInfo error = ' + JSON.stringify(err)); + console.error('getAuthInfo error = ' + JSON.stringify(err)); }); } catch (e) { - console.log('getAuthInfo exception = ' + JSON.stringify(e)); + console.error('getAuthInfo exception = ' + JSON.stringify(e)); } ``` @@ -5079,7 +4933,7 @@ Obtains the ID of the enrolled credential based on the credential type and accou | 12300001 | The system service works abnormally. | | 12300002 | Invalid authType. | | 12300003 | Account not found. | -| 12300102 | Credential not enrolled. | +| 12300102 | The credential does not exist. | | 12300106 | The authentication type is not supported. | **Example** @@ -5092,10 +4946,10 @@ Obtains the ID of the enrolled credential based on the credential type and accou userIDM.getEnrolledId(authType, accountId).then((enrolledId: Uint8Array) => { console.info('getEnrolledId enrolledId = ' + JSON.stringify(enrolledId)); }).catch((err: BusinessError) => { - console.info('getEnrolledId error = ' + JSON.stringify(err)); + console.error('getEnrolledId error = ' + JSON.stringify(err)); }); } catch (e) { - console.log('getEnrolledId exception = ' + JSON.stringify(e)); + console.error('getEnrolledId exception = ' + JSON.stringify(e)); } ``` @@ -5356,15 +5210,16 @@ Defines the executor property. **System capability**: SystemCapability.Account.OsAccount -| Name | Type | Readable| Writable| Description | +| Name | Type | Read-Only| Optional| Description | | ------------ | ---------------------------- | ----- | -----|----------------- | -| result | number | Yes | Yes | Result. | -| authSubType | [AuthSubType](#authsubtype8) | Yes | Yes | Authentication credential subtype.| -| remainTimes | number | Yes | Yes | Number of remaining authentication times. | -| freezingTime | number | Yes | Yes | Freezing time. | -| enrollmentProgress10+ | string | Yes | Yes | Enrollment progress. By default, no value is passed in.| -| sensorInfo10+ | string | Yes | Yes | Sensor information. By default, no value is passed in.| -| nextPhaseFreezingTime12+ | number | Yes | Yes | Next freezing time, which is **undefined** by default.| +| result | number | No | No | Result. | +| authSubType | [AuthSubType](#authsubtype8) | No | No | Authentication credential subtype.| +| remainTimes | number | No | Yes | Number of remaining authentication times. | +| freezingTime | number | No | Yes | Freezing time. | +| enrollmentProgress10+ | string | No | Yes | Enrollment progress, which is left blank by default.| +| sensorInfo10+ | string | No | Yes | Sensor information, which is left blank by default.| +| nextPhaseFreezingTime12+ | number | No | Yes | Next freezing time, which is **undefined** by default.| +| credentialLength20+ | number | No | Yes | Credential length, which is **undefined** by default. When credentials with indefinite-length attributes such as biometric information are queried, **undefined** is returned.| ## AuthResult8+ @@ -5376,8 +5231,8 @@ Defines the authentication result information. | Name | Type | Mandatory | Description | | ------------ | ----------- | ----- | ----------------- | -| token | Uint8Array | No | Authentication token. By default, no value is passed in. | -| remainTimes | number | No | Number of remaining authentication times. By default, no value is passed in. | +| token | Uint8Array | No | Authentication token, which is left blank by default. | +| remainTimes | number | No | Number of remaining authentication times, which is left blank by default. | | freezingTime | number | No | Freezing time. By default, no value is passed in. | | nextPhaseFreezingTime12+ | number | No | Next freezing time, which is **undefined** by default.| | credentialId12+ | Uint8Array | No | Credential ID, which is left blank by default.| @@ -5409,7 +5264,7 @@ Defines the request result information. | Name | Type | Mandatory | Description | | ------------ | ----------- | ----- | ----------------- | -| credentialId | Uint8Array | No | Credential ID. By default, no value is passed in. | +| credentialId | Uint8Array | No | Credential ID, which is left blank by default. | ## EnrolledCredInfo8+ @@ -5425,6 +5280,8 @@ Defines enrolled credential information. | authType | [AuthType](#authtype8) | Yes | Authentication credential type. | | authSubType | [AuthSubType](#authsubtype8) | Yes | Credential subtype.| | templateId | Uint8Array | Yes | Authentication credential template ID. | +| isAbandoned20+ | boolean | No | Whether the credential is abandoned, which is **undefined** by default. The abandoned credential may be stored as a backup credential for a period of time. | +| validityPeriod20+ | number | No | Validity period of the credential, which is **undefined** by default. | ## GetPropertyType8+ @@ -5442,6 +5299,7 @@ Enumerates the types of properties to obtain. | ENROLLMENT_PROGRESS10+ | 4 | Enrollment progress. | | SENSOR_INFO10+ | 5 | Sensor information. | | NEXT_PHASE_FREEZING_TIME12+ | 6 | Next freezing time.| +| CREDENTIAL_LENGTH20+ | 7 | Credential length.| ## SetPropertyType8+ @@ -5594,7 +5452,7 @@ Represents the system account information. | Name | Type | Mandatory| Description | | ----------- | ------ | ---- | ---------- | | shortName12+ | string | No | Short name of the system account.
**System API**: This is a system API and is left blank by default.| -| isLoggedIn12+ | boolean | No | Whether the system account is logged in.
**System API**: This is a system API. The default value is **false**.| +| isLoggedIn12+ | boolean | No | Whether the system account is logged in. The value **true** means that the system account has logged in; the value **false** means the opposite.
**System API**: This is a system API. The default value is **false**.| ## OsAccountType @@ -5615,8 +5473,7 @@ Represents domain account information. | Name | Type | Mandatory| Description | | ----------- | ------ | ---- | ---------- | | accountId10+ | string | No | Domain account ID.
**System API**: This is a system API and is **undefined** by default.| -| isAuthenticated11+| boolean | No| Whether the domain account has been authenticated.
**System API**: This is a system API. The default value is **false**.| -| serverConfigId12+| boolean | No| ID of the server to which the domain account belongs.
**System API**: This is a system API and is **undefined** by default.| +| isAuthenticated11+| boolean | No| Whether the domain account has been authenticated. The value **true** means that the specified domain account has been authenticated; the value **false** means the opposite.
**System API**: This is a system API. The default value is **false**.| ## ConstraintSourceTypeInfo9+ @@ -5656,7 +5513,7 @@ Presents the authentication status information. | Name | Type | Mandatory| Description | | ----------- | ------ | ---- | ---------- | -| remainTimes | number | Yes | Number of remaining authentication times. | +| remainTimes | number | Yes | Number of remaining times. | | freezingTime | number | Yes | Freezing time.| ## GetDomainAccessTokenOptions10+ @@ -5686,7 +5543,7 @@ Defines the options for obtaining domain account information. | ----------- | ------ | ---- | ---------- | | accountName | string | Yes | Domain account name.| | domain | string | No | Domain name, which is **undefined** by default.| -| serverConfigId12+| boolean | No| ID of the server to which the domain account belongs, which is **undefined** by default.| +| serverConfigId12+| string | No| ID of the server to which the domain account belongs, which is **undefined** by default.| ## GetDomainAccountInfoPluginOptions10+ @@ -5724,6 +5581,8 @@ Represents the optional parameter used to create a system account. | Name | Type | Mandatory| Description | | ----------- | ------ | ---- | ---------- | | shortName | string | Yes | Short name of the account (used as the name of the personal folder).
**The short name cannot**:
Contain any of the following characters: \< \>\| : " * ? / \\
Contain any of the following: . or ..
Exceed 255 characters.| +| disallowedPreinstalledBundles19+ | Array<string> | No | Forbidden list of the preinstalled applications, which cannot be installed on the device.| +| allowedPreinstalledBundles19+ | Array<string> | No | Trustlist of the preinstalled applications, which can be installed on the device.| ## CreateOsAccountForDomainOptions12+ @@ -5763,6 +5622,7 @@ Enumerates the authentication intents. | UNLOCK | 1 | Unlock.| | SILENT_AUTH14+ | 2 | Silent authentication.| | QUESTION_AUTH14+ | 3 | Security question authentication.| +| ABANDONED_PIN_AUTH20+ | 4 | Abandoned PIN authentication. After a user changes the lock screen password, the old PIN is abandoned. If a user forgets the current password, the user can reset the lock screen password after passing the authentication with the abandoned PIN.| ## RemoteAuthOptions12+ diff --git a/en/application-dev/reference/apis-basic-services-kit/js-apis-osAccount.md b/en/application-dev/reference/apis-basic-services-kit/js-apis-osAccount.md index 2e670b486fb..0565656f300 100644 --- a/en/application-dev/reference/apis-basic-services-kit/js-apis-osAccount.md +++ b/en/application-dev/reference/apis-basic-services-kit/js-apis-osAccount.md @@ -83,7 +83,7 @@ Checks whether multiple system accounts are supported. This API uses an asynchro } }); } catch (err) { - console.log('checkMultiOsAccountEnabled failed, error:' + JSON.stringify(err)); + console.error('checkMultiOsAccountEnabled failed, error:' + JSON.stringify(err)); } ``` @@ -119,7 +119,7 @@ Checks whether multiple system accounts are supported. This API uses a promise t console.error(`checkMultiOsAccountEnabled failed, code is ${err.code}, message is ${err.message}`); }); } catch (err) { - console.log('checkMultiOsAccountEnabled failed, error:' + JSON.stringify(err)); + console.error('checkMultiOsAccountEnabled failed, error:' + JSON.stringify(err)); } ``` @@ -163,13 +163,13 @@ Checks whether a system account is activated. This API uses an asynchronous call try { accountManager.checkOsAccountActivated(localId, (err: BusinessError, isActivated: boolean) => { if (err) { - console.log('checkOsAccountActivated failed, error:' + JSON.stringify(err)); + console.error('checkOsAccountActivated failed, error:' + JSON.stringify(err)); } else { console.log('checkOsAccountActivated successfully, isActivated:' + isActivated); } }); } catch (err) { - console.log('checkOsAccountActivated exception: ' + JSON.stringify(err)); + console.error('checkOsAccountActivated exception: ' + JSON.stringify(err)); } ``` @@ -219,10 +219,10 @@ Checks whether a system account is activated. This API uses a promise to return accountManager.checkOsAccountActivated(localId).then((isActivated: boolean) => { console.log('checkOsAccountActivated successfully, isActivated: ' + isActivated); }).catch((err: BusinessError) => { - console.log('checkOsAccountActivated failed, error: ' + JSON.stringify(err)); + console.error('checkOsAccountActivated failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log('checkOsAccountActivated exception: ' + JSON.stringify(err)); + console.error('checkOsAccountActivated exception: ' + JSON.stringify(err)); } ``` @@ -263,10 +263,10 @@ Checks whether a constraint is enabled for this system account. This API uses a accountManager.isOsAccountConstraintEnabled(constraint).then((isEnabled: boolean) => { console.log('isOsAccountConstraintEnabled successfully, isEnabled: ' + isEnabled); }).catch((err: BusinessError) => { - console.log('isOsAccountConstraintEnabled failed, error: ' + JSON.stringify(err)); + console.error('isOsAccountConstraintEnabled failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log('isOsAccountConstraintEnabled exception: ' + JSON.stringify(err)); + console.error('isOsAccountConstraintEnabled exception: ' + JSON.stringify(err)); } ``` @@ -312,13 +312,13 @@ Checks whether the specified constraint is enabled for a system account. This AP try { accountManager.checkOsAccountConstraintEnabled(localId, constraint, (err: BusinessError, isEnabled: boolean)=>{ if (err) { - console.log('checkOsAccountConstraintEnabled failed, error: ' + JSON.stringify(err)); + console.error('checkOsAccountConstraintEnabled failed, error: ' + JSON.stringify(err)); } else { console.log('checkOsAccountConstraintEnabled successfully, isEnabled: ' + isEnabled); } }); } catch (err) { - console.log('checkOsAccountConstraintEnabled exception: ' + JSON.stringify(err)); + console.error('checkOsAccountConstraintEnabled exception: ' + JSON.stringify(err)); } ``` @@ -370,10 +370,10 @@ Checks whether the specified constraint is enabled for a system account. This AP accountManager.checkOsAccountConstraintEnabled(localId, constraint).then((isEnabled: boolean) => { console.log('checkOsAccountConstraintEnabled successfully, isEnabled: ' + isEnabled); }).catch((err: BusinessError) => { - console.log('checkOsAccountConstraintEnabled failed, error: ' + JSON.stringify(err)); + console.error('checkOsAccountConstraintEnabled failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log('checkOsAccountConstraintEnabled exception: ' + JSON.stringify(err)); + console.error('checkOsAccountConstraintEnabled exception: ' + JSON.stringify(err)); } ``` @@ -406,13 +406,13 @@ Checks whether this system account is a test account. This API uses an asynchron try { accountManager.checkOsAccountTestable((err: BusinessError, isTestable: boolean) => { if (err) { - console.log('checkOsAccountTestable failed, error: ' + JSON.stringify(err)); + console.error('checkOsAccountTestable failed, error: ' + JSON.stringify(err)); } else { console.log('checkOsAccountTestable successfully, isTestable: ' + isTestable); } }); } catch (err) { - console.log('checkOsAccountTestable error: ' + JSON.stringify(err)); + console.error('checkOsAccountTestable error: ' + JSON.stringify(err)); } ``` @@ -445,10 +445,10 @@ Checks whether this system account is a test account. This API uses a promise to accountManager.checkOsAccountTestable().then((isTestable: boolean) => { console.log('checkOsAccountTestable successfully, isTestable: ' + isTestable); }).catch((err: BusinessError) => { - console.log('checkOsAccountTestable failed, error: ' + JSON.stringify(err)); + console.error('checkOsAccountTestable failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log('checkOsAccountTestable exception: ' + JSON.stringify(err)); + console.error('checkOsAccountTestable exception: ' + JSON.stringify(err)); } ``` @@ -481,10 +481,10 @@ Checks whether this system account is unlocked. This API uses a promise to retur accountManager.isOsAccountUnlocked().then((isVerified: boolean) => { console.log('isOsAccountUnlocked successfully, isVerified: ' + isVerified); }).catch((err: BusinessError) => { - console.log('isOsAccountUnlocked failed, error: ' + JSON.stringify(err)); + console.error('isOsAccountUnlocked failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log('isOsAccountUnlocked exception: ' + JSON.stringify(err)); + console.error('isOsAccountUnlocked exception: ' + JSON.stringify(err)); } ``` @@ -520,13 +520,13 @@ Checks whether this system account has been verified. This API uses an asynchron try { accountManager.checkOsAccountVerified((err: BusinessError, isVerified: boolean) => { if (err) { - console.log('checkOsAccountVerified failed, error: ' + JSON.stringify(err)); + console.error('checkOsAccountVerified failed, error: ' + JSON.stringify(err)); } else { console.log('checkOsAccountVerified successfully, isVerified: ' + isVerified); } }); } catch (err) { - console.log('checkOsAccountVerified exception: ' + JSON.stringify(err)); + console.error('checkOsAccountVerified exception: ' + JSON.stringify(err)); } ``` @@ -546,7 +546,7 @@ Checks whether this system account has been verified. This API uses a promise to | Type | Description | | ---------------------- | ------------------------------------------------------------------------ | -| Promise<boolean> | Promise used to return the result. The value **true** means the system account has been verified; the value **false** means the opposite. | +| Promise<boolean> | Promise used to return the result. The value **true** means the system account has been verified; the value **false** means the opposite.| **Error codes** @@ -563,10 +563,10 @@ Checks whether this system account has been verified. This API uses a promise to accountManager.checkOsAccountVerified().then((isVerified: boolean) => { console.log('checkOsAccountVerified successfully, isVerified: ' + isVerified); }).catch((err: BusinessError) => { - console.log('checkOsAccountVerified failed, error: ' + JSON.stringify(err)); + console.error('checkOsAccountVerified failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log('checkOsAccountVerified exception: ' + JSON.stringify(err)); + console.error('checkOsAccountVerified exception: ' + JSON.stringify(err)); } ``` @@ -589,7 +589,7 @@ Checks whether a system account has been verified. This API uses an asynchronous | Name | Type | Mandatory| Description | | -------- | ---------------------------- | ---- | ------------------------------------------------------------- | | localId | number | Yes | ID of the target system account. | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. The value **true** means the system account has been verified; the value **false** means the opposite. | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. The value **true** means the system account has been verified; the value **false** means the opposite.| **Error codes** @@ -610,13 +610,13 @@ Checks whether a system account has been verified. This API uses an asynchronous try { accountManager.checkOsAccountVerified(localId, (err: BusinessError, isVerified: boolean) => { if (err) { - console.log('checkOsAccountVerified failed, error: ' + JSON.stringify(err)); + console.error('checkOsAccountVerified failed, error: ' + JSON.stringify(err)); } else { console.log('checkOsAccountVerified successfully, isVerified: ' + isVerified); } }); } catch (err) { - console.log('checkOsAccountVerified exception: ' + err); + console.error('checkOsAccountVerified exception: ' + err); } ``` @@ -644,7 +644,7 @@ Checks whether a system account has been verified. This API uses a promise to re | Type | Description | | ---------------------- | ----------------------------------------------------------------- | -| Promise<boolean> | Promise used to return the result. The value **true** means the system account has been verified; the value **false** means the opposite. | +| Promise<boolean> | Promise used to return the result. The value **true** means the system account has been verified; the value **false** means the opposite.| **Error codes** @@ -666,10 +666,10 @@ Checks whether a system account has been verified. This API uses a promise to re accountManager.checkOsAccountVerified(localId).then((isVerified: boolean) => { console.log('checkOsAccountVerified successfully, isVerified: ' + isVerified); }).catch((err: BusinessError) => { - console.log('checkOsAccountVerified failed, error: ' + JSON.stringify(err)); + console.error('checkOsAccountVerified failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log('checkOsAccountVerified exception: ' + JSON.stringify(err)); + console.error('checkOsAccountVerified exception: ' + JSON.stringify(err)); } ``` @@ -705,13 +705,13 @@ Obtains the number of system accounts created. This API uses an asynchronous cal try { accountManager.getOsAccountCount((err: BusinessError, count: number) => { if (err) { - console.log('getOsAccountCount failed, error: ' + JSON.stringify(err)); + console.error('getOsAccountCount failed, error: ' + JSON.stringify(err)); } else { console.log('getOsAccountCount successfully, count: ' + count); } }); } catch (err) { - console.log('getOsAccountCount exception: ' + JSON.stringify(err)); + console.error('getOsAccountCount exception: ' + JSON.stringify(err)); } ``` @@ -747,10 +747,10 @@ Obtains the number of system accounts created. This API uses a promise to return accountManager.getOsAccountCount().then((count: number) => { console.log('getOsAccountCount successfully, count: ' + count); }).catch((err: BusinessError) => { - console.log('getOsAccountCount failed, error: ' + JSON.stringify(err)); + console.error('getOsAccountCount failed, error: ' + JSON.stringify(err)); }); } catch(err) { - console.log('getOsAccountCount exception: ' + JSON.stringify(err)); + console.error('getOsAccountCount exception: ' + JSON.stringify(err)); } ``` @@ -783,13 +783,13 @@ Obtains the ID of the system account to which the current process belongs. This try { accountManager.getOsAccountLocalId((err: BusinessError, localId: number) => { if (err) { - console.log('getOsAccountLocalId failed, error: ' + JSON.stringify(err)); + console.error('getOsAccountLocalId failed, error: ' + JSON.stringify(err)); } else { console.log('getOsAccountLocalId successfully, localId: ' + localId); } }); } catch (err) { - console.log('getOsAccountLocalId exception: ' + JSON.stringify(err)); + console.error('getOsAccountLocalId exception: ' + JSON.stringify(err)); } ``` @@ -822,10 +822,10 @@ Obtains the ID of the system account to which the current process belongs. This accountManager.getOsAccountLocalId().then((localId: number) => { console.log('getOsAccountLocalId successfully, localId: ' + localId); }).catch((err: BusinessError) => { - console.log('getOsAccountLocalId failed, error: ' + JSON.stringify(err)); + console.error('getOsAccountLocalId failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log('getOsAccountLocalId exception: ' + JSON.stringify(err)); + console.error('getOsAccountLocalId exception: ' + JSON.stringify(err)); } ``` @@ -861,12 +861,12 @@ Obtains the system account ID based on the process UID. This API uses an asynchr try { accountManager.getOsAccountLocalIdForUid(uid, (err: BusinessError, localId: number) => { if (err) { - console.log('getOsAccountLocalIdForUid failed, error: ' + JSON.stringify(err)); + console.error('getOsAccountLocalIdForUid failed, error: ' + JSON.stringify(err)); } console.log('getOsAccountLocalIdForUid successfully, localId: ' + localId); }); } catch (err) { - console.log('getOsAccountLocalIdForUid exception: ' + JSON.stringify(err)); + console.error('getOsAccountLocalIdForUid exception: ' + JSON.stringify(err)); } ``` @@ -908,10 +908,10 @@ Obtains the system account ID based on the process UID. This API uses a promise accountManager.getOsAccountLocalIdForUid(uid).then((localId: number) => { console.log('getOsAccountLocalIdForUid successfully, localId: ' + localId); }).catch((err: BusinessError) => { - console.log('getOsAccountLocalIdForUid failed, error: ' + JSON.stringify(err)); + console.error('getOsAccountLocalIdForUid failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log('getOsAccountLocalIdForUid exception: ' + JSON.stringify(err)); + console.error('getOsAccountLocalIdForUid exception: ' + JSON.stringify(err)); } ``` @@ -951,7 +951,7 @@ Obtains the system account ID based on the process UID. The API returns the resu let localId : number = accountManager.getOsAccountLocalIdForUidSync(uid); console.log('getOsAccountLocalIdForUidSync successfully, localId: ' + localId); } catch (err) { - console.log('getOsAccountLocalIdForUidSync exception: ' + JSON.stringify(err)); + console.error('getOsAccountLocalIdForUidSync exception: ' + JSON.stringify(err)); } ``` @@ -990,13 +990,13 @@ Obtains the system account ID based on the domain account information. This API try { accountManager.getOsAccountLocalIdForDomain(domainInfo, (err: BusinessError, localId: number) => { if (err) { - console.log('getOsAccountLocalIdForDomain failed, error: ' + JSON.stringify(err)); + console.error('getOsAccountLocalIdForDomain failed, error: ' + JSON.stringify(err)); } else { console.log('getOsAccountLocalIdForDomain successfully, localId: ' + localId); } }); } catch (err) { - console.log('getOsAccountLocalIdForDomain exception: ' + JSON.stringify(err)); + console.error('getOsAccountLocalIdForDomain exception: ' + JSON.stringify(err)); } ``` @@ -1041,10 +1041,10 @@ Obtains the system account ID based on the domain account information. This API accountManager.getOsAccountLocalIdForDomain(domainInfo).then((localId: number) => { console.log('getOsAccountLocalIdForDomain successfully, localId: ' + localId); }).catch((err: BusinessError) => { - console.log('getOsAccountLocalIdForDomain failed, error: ' + JSON.stringify(err)); + console.error('getOsAccountLocalIdForDomain failed, error: ' + JSON.stringify(err)); }); } catch (err) { - console.log('getOsAccountLocalIdForDomain exception: ' + JSON.stringify(err)); + console.error('getOsAccountLocalIdForDomain exception: ' + JSON.stringify(err)); } ``` @@ -1088,13 +1088,13 @@ Obtains all constraints enabled for a system account. This API uses an asynchron try { accountManager.getOsAccountConstraints(localId, (err: BusinessError, constraints: string[]) => { if (err) { - console.log('getOsAccountConstraints failed, err: ' + JSON.stringify(err)); + console.error('getOsAccountConstraints failed, err: ' + JSON.stringify(err)); } else { console.log('getOsAccountConstraints successfully, constraints: ' + JSON.stringify(constraints)); } }); } catch (err) { - console.log('getOsAccountConstraints exception: ' + JSON.stringify(err)); + console.error('getOsAccountConstraints exception: ' + JSON.stringify(err)); } ``` @@ -1144,10 +1144,10 @@ Obtains all constraints enabled for a system account. This API uses a promise to accountManager.getOsAccountConstraints(localId).then((constraints: string[]) => { console.log('getOsAccountConstraints, constraints: ' + constraints); }).catch((err: BusinessError) => { - console.log('getOsAccountConstraints err: ' + JSON.stringify(err)); + console.error('getOsAccountConstraints err: ' + JSON.stringify(err)); }); } catch (e) { - console.log('getOsAccountConstraints exception: ' + JSON.stringify(e)); + console.error('getOsAccountConstraints exception: ' + JSON.stringify(e)); } ``` @@ -1179,14 +1179,17 @@ Obtains information about all activated system accounts. This API uses an asynch let accountManager: osAccount.AccountManager = osAccount.getAccountManager(); try { accountManager.getActivatedOsAccountLocalIds((err: BusinessError, idArray: number[])=>{ - console.log('getActivatedOsAccountLocalIds err:' + JSON.stringify(err)); - console.log('getActivatedOsAccountLocalIds idArray length:' + idArray.length); - for(let i=0;i { console.log('getActivatedOsAccountLocalIds, idArray: ' + idArray); }).catch((err: BusinessError) => { - console.log('getActivatedOsAccountLocalIds err: ' + JSON.stringify(err)); + console.error('getActivatedOsAccountLocalIds err: ' + JSON.stringify(err)); }); } catch (e) { - console.log('getActivatedOsAccountLocalIds exception: ' + JSON.stringify(e)); + console.error('getActivatedOsAccountLocalIds exception: ' + JSON.stringify(e)); } ``` @@ -1261,11 +1264,14 @@ Obtains information about the system account to which the current process belong let accountManager: osAccount.AccountManager = osAccount.getAccountManager(); try { accountManager.getCurrentOsAccount((err: BusinessError, curAccountInfo: osAccount.OsAccountInfo)=>{ - console.log('getCurrentOsAccount err:' + JSON.stringify(err)); - console.log('getCurrentOsAccount curAccountInfo:' + JSON.stringify(curAccountInfo)); + if (err) { + console.error('getCurrentOsAccount err:' + JSON.stringify(err)); + } else { + console.log('getCurrentOsAccount curAccountInfo:' + JSON.stringify(curAccountInfo)); + } }); } catch (e) { - console.log('getCurrentOsAccount exception: ' + JSON.stringify(e)); + console.error('getCurrentOsAccount exception: ' + JSON.stringify(e)); } ``` @@ -1305,10 +1311,10 @@ Obtains information about the system account to which the current process belong accountManager.getCurrentOsAccount().then((accountInfo: osAccount.OsAccountInfo) => { console.log('getCurrentOsAccount, accountInfo: ' + JSON.stringify(accountInfo)); }).catch((err: BusinessError) => { - console.log('getCurrentOsAccount err: ' + JSON.stringify(err)); + console.error('getCurrentOsAccount err: ' + JSON.stringify(err)); }); } catch (e) { - console.log('getCurrentOsAccount exception: ' + JSON.stringify(e)); + console.error('getCurrentOsAccount exception: ' + JSON.stringify(e)); } ``` @@ -1340,11 +1346,14 @@ Obtains the type of the account to which the current process belongs. This API u let accountManager: osAccount.AccountManager = osAccount.getAccountManager(); try { accountManager.getOsAccountType((err: BusinessError, accountType: osAccount.OsAccountType) => { - console.log('getOsAccountType err: ' + JSON.stringify(err)); - console.log('getOsAccountType accountType: ' + accountType); + if (err) { + console.error('getOsAccountType err: ' + JSON.stringify(err)); + } else { + console.log('getOsAccountType accountType: ' + accountType); + } }); } catch (e) { - console.log('getOsAccountType exception: ' + JSON.stringify(e)); + console.error('getOsAccountType exception: ' + JSON.stringify(e)); } ``` @@ -1377,10 +1386,10 @@ Obtains the type of the account to which the current process belongs. This API u accountManager.getOsAccountType().then((accountType: osAccount.OsAccountType) => { console.log('getOsAccountType, accountType: ' + accountType); }).catch((err: BusinessError) => { - console.log('getOsAccountType err: ' + JSON.stringify(err)); + console.error('getOsAccountType err: ' + JSON.stringify(err)); }); } catch (e) { - console.log('getOsAccountType exception: ' + JSON.stringify(e)); + console.error('getOsAccountType exception: ' + JSON.stringify(e)); } ``` @@ -1415,11 +1424,14 @@ Queries the ID of the distributed virtual device. This API uses an asynchronous let accountManager: osAccount.AccountManager = osAccount.getAccountManager(); try { accountManager.queryDistributedVirtualDeviceId((err: BusinessError, virtualID: string) => { - console.log('queryDistributedVirtualDeviceId err: ' + JSON.stringify(err)); - console.log('queryDistributedVirtualDeviceId virtualID: ' + virtualID); + if (err) { + console.error('queryDistributedVirtualDeviceId err: ' + JSON.stringify(err)); + } else { + console.log('queryDistributedVirtualDeviceId virtualID: ' + virtualID); + } }); } catch (e) { - console.log('queryDistributedVirtualDeviceId exception: ' + JSON.stringify(e)); + console.error('queryDistributedVirtualDeviceId exception: ' + JSON.stringify(e)); } ``` @@ -1455,10 +1467,10 @@ Queries the ID of the distributed virtual device. This API uses a promise to ret accountManager.queryDistributedVirtualDeviceId().then((virtualID: string) => { console.log('queryDistributedVirtualDeviceId, virtualID: ' + virtualID); }).catch((err: BusinessError) => { - console.log('queryDistributedVirtualDeviceId err: ' + JSON.stringify(err)); + console.error('queryDistributedVirtualDeviceId err: ' + JSON.stringify(err)); }); } catch (e) { - console.log('queryDistributedVirtualDeviceId exception: ' + JSON.stringify(e)); + console.error('queryDistributedVirtualDeviceId exception: ' + JSON.stringify(e)); } ``` @@ -1494,11 +1506,14 @@ Obtains the system account ID based on the SN. This API uses an asynchronous cal let serialNumber: number = 12345; try { accountManager.getOsAccountLocalIdForSerialNumber(serialNumber, (err: BusinessError, localId: number)=>{ - console.log('ger localId err:' + JSON.stringify(err)); - console.log('get localId:' + localId + ' by serialNumber: ' + serialNumber); + if (err) { + console.error('ger localId err:' + JSON.stringify(err)); + } else { + console.log('get localId:' + localId + ' by serialNumber: ' + serialNumber); + } }); } catch (e) { - console.log('ger localId exception: ' + JSON.stringify(e)); + console.error('ger localId exception: ' + JSON.stringify(e)); } ``` @@ -1541,10 +1556,10 @@ Obtains the system account ID based on the SN. This API uses a promise to return accountManager.getOsAccountLocalIdForSerialNumber(serialNumber).then((localId: number) => { console.log('getOsAccountLocalIdForSerialNumber localId: ' + localId); }).catch((err: BusinessError) => { - console.log('getOsAccountLocalIdForSerialNumber err: ' + JSON.stringify(err)); + console.error('getOsAccountLocalIdForSerialNumber err: ' + JSON.stringify(err)); }); } catch (e) { - console.log('getOsAccountLocalIdForSerialNumber exception: ' + JSON.stringify(e)); + console.error('getOsAccountLocalIdForSerialNumber exception: ' + JSON.stringify(e)); } ``` @@ -1580,11 +1595,14 @@ Obtains the SN of a system account based on the account ID. This API uses an asy let localId: number = 100; try { accountManager.getSerialNumberForOsAccountLocalId(localId, (err: BusinessError, serialNumber: number)=>{ - console.log('ger serialNumber err:' + JSON.stringify(err)); - console.log('get serialNumber:' + serialNumber + ' by localId: ' + localId); + if (err) { + console.error('ger serialNumber err:' + JSON.stringify(err)); + } else { + console.log('get serialNumber:' + serialNumber + ' by localId: ' + localId); + } }); } catch (e) { - console.log('ger serialNumber exception: ' + JSON.stringify(e)); + console.error('ger serialNumber exception: ' + JSON.stringify(e)); } ``` @@ -1627,10 +1645,10 @@ Obtains the SN of a system account based on the account ID. This API uses a prom accountManager.getSerialNumberForOsAccountLocalId(localId).then((serialNumber: number) => { console.log('getSerialNumberForOsAccountLocalId serialNumber: ' + serialNumber); }).catch((err: BusinessError) => { - console.log('getSerialNumberForOsAccountLocalId err: ' + JSON.stringify(err)); + console.error('getSerialNumberForOsAccountLocalId err: ' + JSON.stringify(err)); }); } catch (e) { - console.log('getSerialNumberForOsAccountLocalId exception: ' + JSON.stringify(e)); + console.error('getSerialNumberForOsAccountLocalId exception: ' + JSON.stringify(e)); } ``` @@ -1659,7 +1677,7 @@ Checks whether multiple system accounts are supported. This API uses an asynchro let accountManager: osAccount.AccountManager = osAccount.getAccountManager(); accountManager.isMultiOsAccountEnable((err: BusinessError, isEnabled: boolean) => { if (err) { - console.log('isMultiOsAccountEnable failed, error: ' + JSON.stringify(err)); + console.error('isMultiOsAccountEnable failed, error: ' + JSON.stringify(err)); } else { console.log('isMultiOsAccountEnable successfully, isEnabled: ' + isEnabled); } @@ -1692,7 +1710,7 @@ Checks whether multiple system accounts are supported. This API uses a promise t accountManager.isMultiOsAccountEnable().then((isEnabled: boolean) => { console.log('isMultiOsAccountEnable successfully, isEnabled: ' + isEnabled); }).catch((err: BusinessError) => { - console.log('isMultiOsAccountEnable failed, error: ' + JSON.stringify(err)); + console.error('isMultiOsAccountEnable failed, error: ' + JSON.stringify(err)); }); ``` @@ -1725,7 +1743,7 @@ Checks whether a system account is activated. This API uses an asynchronous call let localId: number = 100; accountManager.isOsAccountActived(localId, (err: BusinessError, isActived: boolean) => { if (err) { - console.log('isOsAccountActived failed, err:' + JSON.stringify(err)); + console.error('isOsAccountActived failed, err:' + JSON.stringify(err)); } else { console.log('isOsAccountActived successfully, isActived:' + isActived); } @@ -1767,7 +1785,7 @@ Checks whether a system account is activated. This API uses a promise to return accountManager.isOsAccountActived(localId).then((isActived: boolean) => { console.log('isOsAccountActived successfully, isActived: ' + isActived); }).catch((err: BusinessError) => { - console.log('isOsAccountActived failed, error: ' + JSON.stringify(err)); + console.error('isOsAccountActived failed, error: ' + JSON.stringify(err)); }); ``` @@ -1802,7 +1820,7 @@ Checks whether the specified constraint is enabled for a system account. This AP let constraint: string = 'constraint.wifi'; accountManager.isOsAccountConstraintEnable(localId, constraint, (err: BusinessError, isEnabled: boolean) => { if (err) { - console.log('isOsAccountConstraintEnable failed, error: ' + JSON.stringify(err)); + console.error('isOsAccountConstraintEnable failed, error: ' + JSON.stringify(err)); } else { console.log('isOsAccountConstraintEnable successfully, isEnabled: ' + isEnabled); } @@ -1846,7 +1864,7 @@ Checks whether the specified constraint is enabled for a system account. This AP accountManager.isOsAccountConstraintEnable(localId, constraint).then((isEnabled: boolean) => { console.log('isOsAccountConstraintEnable successfully, isEnabled: ' + isEnabled); }).catch((err: BusinessError) => { - console.log('isOsAccountConstraintEnable err: ' + JSON.stringify(err)); + console.error('isOsAccountConstraintEnable err: ' + JSON.stringify(err)); }); ``` @@ -1875,7 +1893,7 @@ Checks whether this system account is a test account. This API uses an asynchron let accountManager: osAccount.AccountManager = osAccount.getAccountManager(); accountManager.isTestOsAccount((err: BusinessError, isTestable: boolean) => { if (err) { - console.log('isTestOsAccount failed, error: ' + JSON.stringify(err)); + console.error('isTestOsAccount failed, error: ' + JSON.stringify(err)); } else { console.log('isTestOsAccount successfully, isTestable: ' + isTestable); } @@ -1908,7 +1926,7 @@ Checks whether this system account is a test account. This API uses a promise to accountManager.isTestOsAccount().then((isTestable: boolean) => { console.log('isTestOsAccount successfully, isTestable: ' + isTestable); }).catch((err: BusinessError) => { - console.log('isTestOsAccount failed, error: ' + JSON.stringify(err)); + console.error('isTestOsAccount failed, error: ' + JSON.stringify(err)); }); ``` @@ -1939,7 +1957,7 @@ Checks whether this system account has been verified. This API uses an asynchron let accountManager: osAccount.AccountManager = osAccount.getAccountManager(); accountManager.isOsAccountVerified((err: BusinessError, isVerified: boolean) => { if (err) { - console.log('isOsAccountVerified failed, error: ' + JSON.stringify(err)); + console.error('isOsAccountVerified failed, error: ' + JSON.stringify(err)); } else { console.log('isOsAccountVerified successfully, isVerified: ' + isVerified); } @@ -1975,7 +1993,7 @@ Checks whether a system account has been verified. This API uses an asynchronous let localId: number = 100; accountManager.isOsAccountVerified(localId, (err: BusinessError, isVerified: boolean) => { if (err) { - console.log('isOsAccountVerified failed, error: ' + JSON.stringify(err)); + console.error('isOsAccountVerified failed, error: ' + JSON.stringify(err)); } else { console.log('isOsAccountVerified successfully, isVerified: ' + isVerified); } @@ -2016,7 +2034,7 @@ Checks whether a system account has been verified. This API uses a promise to re accountManager.isOsAccountVerified().then((isVerified: boolean) => { console.log('isOsAccountVerified successfully, isVerified: ' + isVerified); }).catch((err: BusinessError) => { - console.log('isOsAccountVerified failed, error: ' + JSON.stringify(err)); + console.error('isOsAccountVerified failed, error: ' + JSON.stringify(err)); }); ``` @@ -2047,7 +2065,7 @@ Obtains the number of system accounts created. This API uses an asynchronous cal let accountManager: osAccount.AccountManager = osAccount.getAccountManager(); accountManager.getCreatedOsAccountsCount((err: BusinessError, count: number)=>{ if (err) { - console.log('getCreatedOsAccountsCount failed, error: ' + JSON.stringify(err)); + console.error('getCreatedOsAccountsCount failed, error: ' + JSON.stringify(err)); } else { console.log('getCreatedOsAccountsCount successfully, count: ' + count); } @@ -2082,7 +2100,7 @@ Obtains the number of system accounts created. This API uses a promise to return accountManager.getCreatedOsAccountsCount().then((count: number) => { console.log('getCreatedOsAccountsCount successfully, count: ' + count); }).catch((err: BusinessError) => { - console.log('getCreatedOsAccountsCount failed, error: ' + JSON.stringify(err)); + console.error('getCreatedOsAccountsCount failed, error: ' + JSON.stringify(err)); }); ``` @@ -2111,9 +2129,9 @@ Obtains the ID of the system account to which the current process belongs. This let accountManager: osAccount.AccountManager = osAccount.getAccountManager(); accountManager.getOsAccountLocalIdFromProcess((err: BusinessError, localId: number) => { if (err) { - console.log('getOsAccountLocalIdFromProcess failed, error: ' + JSON.stringify(err)); + console.error('getOsAccountLocalIdFromProcess failed, error: ' + JSON.stringify(err)); } else { - console.log('getOsAccountLocalIdFromProcess failed, error: ' + localId); + console.log('getOsAccountLocalIdFromProcess id:: ' + localId); } }); ``` @@ -2144,7 +2162,7 @@ Obtains the ID of the system account to which the current process belongs. This accountManager.getOsAccountLocalIdFromProcess().then((localId: number) => { console.log('getOsAccountLocalIdFromProcess successfully, localId: ' + localId); }).catch((err: BusinessError) => { - console.log('getOsAccountLocalIdFromProcess failed, error: ' + JSON.stringify(err)); + console.error('getOsAccountLocalIdFromProcess failed, error: ' + JSON.stringify(err)); }); ``` @@ -2175,7 +2193,7 @@ Obtains the system account ID based on the process UID. This API uses an asynchr let uid: number = 12345678; accountManager.getOsAccountLocalIdFromUid(uid, (err: BusinessError, localId: number) => { if (err) { - console.log('getOsAccountLocalIdFromUid failed, error: ' + JSON.stringify(err)); + console.error('getOsAccountLocalIdFromUid failed, error: ' + JSON.stringify(err)); } else { console.log('getOsAccountLocalIdFromUid successfully, localId: ' + localId); } @@ -2215,7 +2233,7 @@ Obtains the system account ID based on the process UID. This API uses a promise accountManager.getOsAccountLocalIdFromUid(uid).then((localId: number) => { console.log('getOsAccountLocalIdFromUid successfully, localId: ' + localId); }).catch((err: BusinessError) => { - console.log('getOsAccountLocalIdFromUid failed, error: ' + JSON.stringify(err)); + console.error('getOsAccountLocalIdFromUid failed, error: ' + JSON.stringify(err)); }); ``` @@ -2248,7 +2266,7 @@ Obtains the system account ID based on the domain account information. This API let accountManager: osAccount.AccountManager = osAccount.getAccountManager(); accountManager.getOsAccountLocalIdFromDomain(domainInfo, (err: BusinessError, localId: number) => { if (err) { - console.log('getOsAccountLocalIdFromDomain failed, error: ' + JSON.stringify(err)); + console.error('getOsAccountLocalIdFromDomain failed, error: ' + JSON.stringify(err)); } else { console.log('getOsAccountLocalIdFromDomain successfully, localId: ' + localId); } @@ -2290,7 +2308,7 @@ Obtains the system account ID based on the domain account information. This API accountManager.getOsAccountLocalIdFromDomain(domainInfo).then((localId: number) => { console.log('getOsAccountLocalIdFromDomain successfully, localId: ' + localId); }).catch((err: BusinessError) => { - console.log('getOsAccountLocalIdFromDomain failed, error: ' + JSON.stringify(err)); + console.error('getOsAccountLocalIdFromDomain failed, error: ' + JSON.stringify(err)); }); ``` @@ -2322,8 +2340,11 @@ Obtains all constraints enabled for a system account. This API uses an asynchron let accountManager: osAccount.AccountManager = osAccount.getAccountManager(); let localId: number = 100; accountManager.getOsAccountAllConstraints(localId, (err: BusinessError, constraints: string[])=>{ - console.log('getOsAccountAllConstraints err:' + JSON.stringify(err)); - console.log('getOsAccountAllConstraints:' + JSON.stringify(constraints)); + if (err) { + console.error('getOsAccountAllConstraints err:' + JSON.stringify(err)); + } else { + console.log('getOsAccountAllConstraints:' + JSON.stringify(constraints)); + } }); ``` @@ -2362,7 +2383,7 @@ Obtains all constraints enabled for a system account. This API uses a promise to accountManager.getOsAccountAllConstraints(localId).then((constraints: string[]) => { console.log('getOsAccountAllConstraints, constraints: ' + constraints); }).catch((err: BusinessError) => { - console.log('getOsAccountAllConstraints err: ' + JSON.stringify(err)); + console.error('getOsAccountAllConstraints err: ' + JSON.stringify(err)); }); ``` @@ -2390,11 +2411,14 @@ Obtains information about all activated system accounts. This API uses an asynch import { BusinessError } from '@kit.BasicServicesKit'; let accountManager: osAccount.AccountManager = osAccount.getAccountManager(); accountManager.queryActivatedOsAccountIds((err: BusinessError, idArray: number[])=>{ - console.log('queryActivatedOsAccountIds err:' + JSON.stringify(err)); - console.log('queryActivatedOsAccountIds idArray length:' + idArray.length); - for(let i=0;i { console.log('queryActivatedOsAccountIds, idArray: ' + idArray); }).catch((err: BusinessError) => { - console.log('queryActivatedOsAccountIds err: ' + JSON.stringify(err)); + console.error('queryActivatedOsAccountIds err: ' + JSON.stringify(err)); }); ``` @@ -2454,8 +2478,11 @@ Obtains information about the system account to which the current process belong import { BusinessError } from '@kit.BasicServicesKit'; let accountManager: osAccount.AccountManager = osAccount.getAccountManager(); accountManager.queryCurrentOsAccount((err: BusinessError, curAccountInfo: osAccount.OsAccountInfo)=>{ - console.log('queryCurrentOsAccount err:' + JSON.stringify(err)); - console.log('queryCurrentOsAccount curAccountInfo:' + JSON.stringify(curAccountInfo)); + if (err) { + console.error('queryCurrentOsAccount err:' + JSON.stringify(err)); + } else { + console.log('queryCurrentOsAccount curAccountInfo:' + JSON.stringify(curAccountInfo)); + } }); ``` @@ -2487,7 +2514,7 @@ Obtains information about the system account to which the current process belong accountManager.queryCurrentOsAccount().then((accountInfo: osAccount.OsAccountInfo) => { console.log('queryCurrentOsAccount, accountInfo: ' + JSON.stringify(accountInfo)); }).catch((err: BusinessError) => { - console.log('queryCurrentOsAccount err: ' + JSON.stringify(err)); + console.error('queryCurrentOsAccount err: ' + JSON.stringify(err)); }); ``` @@ -2515,8 +2542,11 @@ Obtains the type of the account to which the current process belongs. This API u import { BusinessError } from '@kit.BasicServicesKit'; let accountManager: osAccount.AccountManager = osAccount.getAccountManager(); accountManager.getOsAccountTypeFromProcess((err: BusinessError, accountType: osAccount.OsAccountType) => { - console.log('getOsAccountTypeFromProcess err: ' + JSON.stringify(err)); - console.log('getOsAccountTypeFromProcess accountType: ' + accountType); + if (err) { + console.error('getOsAccountTypeFromProcess err: ' + JSON.stringify(err)); + } else { + console.log('getOsAccountTypeFromProcess accountType: ' + accountType); + } }); ``` @@ -2546,7 +2576,7 @@ Obtains the type of the account to which the current process belongs. This API u accountManager.getOsAccountTypeFromProcess().then((accountType: osAccount.OsAccountType) => { console.log('getOsAccountTypeFromProcess, accountType: ' + accountType); }).catch((err: BusinessError) => { - console.log('getOsAccountTypeFromProcess err: ' + JSON.stringify(err)); + console.error('getOsAccountTypeFromProcess err: ' + JSON.stringify(err)); }); ``` @@ -2576,8 +2606,11 @@ Obtains the ID of this distributed virtual device. This API uses an asynchronous import { BusinessError } from '@kit.BasicServicesKit'; let accountManager: osAccount.AccountManager = osAccount.getAccountManager(); accountManager.getDistributedVirtualDeviceId((err: BusinessError, virtualID: string) => { - console.log('getDistributedVirtualDeviceId err: ' + JSON.stringify(err)); - console.log('getDistributedVirtualDeviceId virtualID: ' + virtualID); + if (err) { + console.error('getDistributedVirtualDeviceId err: ' + JSON.stringify(err)); + } else { + console.log('getDistributedVirtualDeviceId virtualID: ' + virtualID); + } }); ``` @@ -2609,7 +2642,7 @@ Obtains the ID of this distributed virtual device. This API uses a promise to re accountManager.getDistributedVirtualDeviceId().then((virtualID: string) => { console.log('getDistributedVirtualDeviceId, virtualID: ' + virtualID); }).catch((err: BusinessError) => { - console.log('getDistributedVirtualDeviceId err: ' + JSON.stringify(err)); + console.error('getDistributedVirtualDeviceId err: ' + JSON.stringify(err)); }); ``` @@ -2639,8 +2672,11 @@ Obtains the system account ID based on the SN. This API uses an asynchronous cal let accountManager: osAccount.AccountManager = osAccount.getAccountManager(); let serialNumber: number = 12345; accountManager.getOsAccountLocalIdBySerialNumber(serialNumber, (err: BusinessError, localId: number)=>{ - console.log('ger localId err:' + JSON.stringify(err)); - console.log('get localId:' + localId + ' by serialNumber: ' + serialNumber); + if (err) { + console.error('ger localId err:' + JSON.stringify(err)); + } else { + console.log('get localId:' + localId + ' by serialNumber: ' + serialNumber); + } }); ``` @@ -2677,7 +2713,7 @@ Obtains the system account ID based on the SN. This API uses a promise to return accountManager.getOsAccountLocalIdBySerialNumber(serialNumber).then((localId: number) => { console.log('getOsAccountLocalIdBySerialNumber localId: ' + localId); }).catch((err: BusinessError) => { - console.log('getOsAccountLocalIdBySerialNumber err: ' + JSON.stringify(err)); + console.error('getOsAccountLocalIdBySerialNumber err: ' + JSON.stringify(err)); }); ``` @@ -2707,8 +2743,11 @@ Obtains the SN of a system account based on the account ID. This API uses an asy let accountManager: osAccount.AccountManager = osAccount.getAccountManager(); let localId: number = 100; accountManager.getSerialNumberByOsAccountLocalId(localId, (err: BusinessError, serialNumber: number)=>{ - console.log('ger serialNumber err:' + JSON.stringify(err)); - console.log('get serialNumber:' + serialNumber + ' by localId: ' + localId); + if (err) { + console.error('ger serialNumber err:' + JSON.stringify(err)); + } else { + console.log('get serialNumber:' + serialNumber + ' by localId: ' + localId); + } }); ``` @@ -2745,7 +2784,7 @@ Obtains the SN of a system account based on the account ID. This API uses a prom accountManager.getSerialNumberByOsAccountLocalId(localId).then((serialNumber: number) => { console.log('getSerialNumberByOsAccountLocalId serialNumber: ' + serialNumber); }).catch((err: BusinessError) => { - console.log('getSerialNumberByOsAccountLocalId err: ' + JSON.stringify(err)); + console.error('getSerialNumberByOsAccountLocalId err: ' + JSON.stringify(err)); }); ``` @@ -2777,10 +2816,10 @@ Obtains the name of the system account of the caller. This API uses a promise to accountManager.getOsAccountName().then((name: string) => { console.log('getOsAccountName, name: ' + name); }).catch((err: BusinessError) => { - console.log('getOsAccountName err: ' + err); + console.error('getOsAccountName err: ' + err); }); } catch (e) { - console.log('getOsAccountName exception: ' + e); + console.error('getOsAccountName exception: ' + e); } ``` @@ -2813,10 +2852,10 @@ Obtains the ID of the foreground system account. accountManager.getForegroundOsAccountLocalId().then((localId: number) => { console.log('getForegroundOsAccountLocalId, localId: ' + localId); }).catch((err: BusinessError) => { - console.log('getForegroundOsAccountLocalId err: ' + JSON.stringify(err)); + console.error('getForegroundOsAccountLocalId err: ' + JSON.stringify(err)); }); } catch (e) { - console.log('getForegroundOsAccountLocalId exception: ' + JSON.stringify(e)); + console.error('getForegroundOsAccountLocalId exception: ' + JSON.stringify(e)); } ``` @@ -2830,6 +2869,12 @@ Obtains the domain account information associated with a specified system accoun **System capability**: SystemCapability.Account.OsAccount +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ----------- | +| localId | number | Yes | ID of the target system account.| + **Return value** | Type | Description | @@ -2859,10 +2904,14 @@ Obtains the domain account information associated with a specified system accoun console.log('getOsAccountDomainInfo accountName: ' + domainAccountInfo.accountName); } }).catch((err: BusinessError) => { - console.log('getOsAccountDomainInfo err: ' + JSON.stringify(err)); + console.error('getOsAccountDomainInfo err: ' + JSON.stringify(err)); }) ``` +## DomainAccountManager18+ + +Provides APIs for domain account management. + ### updateAccountInfo18+ updateAccountInfo(oldAccountInfo: DomainAccountInfo, newAccountInfo: DomainAccountInfo): Promise<void> @@ -2891,7 +2940,6 @@ Updates information of a domain account. This API uses a promise to return the r | ID| Error Message | | -------- | --------------------------- | | 201 | Permission denied.| -| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | | 801 | Capability not supported.| | 12300001 | The system service works abnormally. | | 12300002 | The new account info is invalid. | @@ -2909,10 +2957,10 @@ Updates information of a domain account. This API uses a promise to return the r osAccount.DomainAccountManager.updateAccountInfo(oldDomainInfo, newDomainInfo).then(() => { console.log('updateAccountInfo, success'); }).catch((err: BusinessError) => { - console.log('updateAccountInfo err: ' + err); + console.error('updateAccountInfo err: ' + err); }); } catch (e) { - console.log('updateAccountInfo exception: ' + e); + console.error('updateAccountInfo exception: ' + e); } ``` @@ -2995,13 +3043,12 @@ Adds domain server configuration. This API uses a promise to return the result. | ID| Error Message | | -------- | --------------------------- | | 201 | Permission denied.| -| 401 |Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | | 801 | Capability not supported.| | 12300001 | The system service works abnormally. | -| 12300002 | - Invalid server config parameters. | -| 12300211 | - Server unreachable. | -| 12300213 | - Server config already exists. | -| 12300215 | - The number of server config reaches the upper limit. | +| 12300002 | Invalid server config parameters. | +| 12300211 | Server unreachable. | +| 12300213 | Server config already exists. | +| 12300215 | The number of server config reaches the upper limit. | **Example** ```ts @@ -3014,7 +3061,7 @@ Adds domain server configuration. This API uses a promise to return the result. serverConfig: osAccount.DomainServerConfig) => { console.log('add server configuration successfully, the return config: ' + JSON.stringify(serverConfig)); }).catch((err: BusinessError) => { - console.log('add server configuration failed, error: ' + JSON.stringify(err)); + console.error('add server configuration failed, error: ' + JSON.stringify(err)); }); ``` @@ -3045,11 +3092,10 @@ Removes domain server configuration. This API uses a promise to return the resul | ID| Error Message | | -------- | --------------------------- | | 201 | Permission denied.| -| 401 |Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | | 801 | Capability not supported.| | 12300001 | The system service works abnormally. | -| 12300212 | - Server config not found. | -| 12300214 | - Server config has been associated with an account. | +| 12300212 | Server config not found. | +| 12300214 | Server config has been associated with an account. | **Example** ```ts @@ -3064,7 +3110,7 @@ Removes domain server configuration. This API uses a promise to return the resul osAccount.DomainServerConfigManager.removeServerConfig(serverConfig.id); console.log('remove domain server configuration successfully'); }).catch((err: BusinessError) => { - console.log('add server configuration failed, error: ' + JSON.stringify(err)); + console.error('add server configuration failed, error: ' + JSON.stringify(err)); }); ``` @@ -3096,14 +3142,13 @@ Updates the domain server configuration. This API uses a promise to return the r | ID| Error Message | | -------- | --------------------------- | | 201 | Permission denied.| -| 401 |Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | | 801 | Capability not supported.| | 12300001 | The system service works abnormally. | | 12300002 | Invalid server config parameters. | -| 12300211 | - Server unreachable. | -| 12300212 | - Server config not found. | -| 12300213 | - Server config already exists. | -| 12300214 | - Server config has been associated with an account. | +| 12300211 | Server unreachable. | +| 12300212 | Server config not found. | +| 12300213 | Server config already exists. | +| 12300214 | Server config has been associated with an account. | **Example** ```ts @@ -3118,10 +3163,10 @@ Updates the domain server configuration. This API uses a promise to return the r osAccount.DomainServerConfigManager.updateServerConfig(serverConfig.id, configParams).then((data) => { console.log('update domain server configuration successfully, return config: ' + JSON.stringify(data)); }).catch((err: BusinessError) => { - console.log('update domain server configuration failed, error: ' + JSON.stringify(err)); + console.error('update domain server configuration failed, error: ' + JSON.stringify(err)); }); }).catch((err: BusinessError) => { - console.log('add server configuration failed, error: ' + JSON.stringify(err)); + console.error('add server configuration failed, error: ' + JSON.stringify(err)); }); ``` @@ -3152,7 +3197,6 @@ Obtains the domain server configuration. This API uses a promise to return the r | ID| Error Message | | -------- | --------------------------- | | 201 | Permission denied.| -| 401 |Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | | 801 | Capability not supported.| | 12300001 | The system service works abnormally. | | 12300212 | Server config not found. | @@ -3167,13 +3211,13 @@ Obtains the domain server configuration. This API uses a promise to return the r osAccount.DomainServerConfigManager.addServerConfig(configParams).then(( serverConfig: osAccount.DomainServerConfig) => { console.log('add domain server configuration successfully, the added config: ' + JSON.stringify(serverConfig)); - osAccount.DomainServerConfigManager.getServerConfig(serverConfig.id).then((data: osaccount.DomainServerConfig) => { + osAccount.DomainServerConfigManager.getServerConfig(serverConfig.id).then((data: osAccount.DomainServerConfig) => { console.log('get domain server configuration successfully, return config: ' + JSON.stringify(data)); }).catch((err: BusinessError) => { - console.log('get domain server configuration failed, error: ' + JSON.stringify(err)); + console.error('get domain server configuration failed, error: ' + JSON.stringify(err)); }); }).catch((err: BusinessError) => { - console.log('add server configuration failed, error: ' + JSON.stringify(err)); + console.error('add server configuration failed, error: ' + JSON.stringify(err)); }); ``` @@ -3211,13 +3255,13 @@ Obtains the configurations of all domain servers. This API uses a promise to ret osAccount.DomainServerConfigManager.addServerConfig(configParams).then(( serverConfig: osAccount.DomainServerConfig) => { console.log('add domain server configuration successfully, the added config: ' + JSON.stringify(serverConfig)); - osAccount.DomainServerConfigManager.getAllServerConfigs().then((data: Array) => { - console.log('get all domain server configuration successfully, return config: ' + JSON.stringfy(data)); + osAccount.DomainServerConfigManager.getAllServerConfigs().then((data: Array) => { + console.log('get all domain server configuration successfully, return config: ' + JSON.stringify(data)); }).catch((err: BusinessError) => { - console.log('get all domain server configuration failed, error: ' + JSON.stringfy(err)); + console.error('get all domain server configuration failed, error: ' + JSON.stringify(err)); }); }).catch((err: BusinessError) => { - console.log('add server configuration failed, error: ' + JSON.stringify(err)); + console.error('add server configuration failed, error: ' + JSON.stringify(err)); }); ``` @@ -3248,7 +3292,6 @@ Obtains the server configuration of a domain account. This API uses a promise to | ID| Error Message | | -------- | --------------------------- | | 201 | Permission denied.| -| 401 |Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | | 801 | Capability not supported.| | 12300001 | The system service works abnormally. | | 12300003 | Domain account not found. | @@ -3258,14 +3301,13 @@ Obtains the server configuration of a domain account. This API uses a promise to import { BusinessError } from '@kit.BasicServicesKit'; let accountInfo: osAccount.DomainAccountInfo = { 'accountName': 'demoName', - 'accountId': 'demoId', 'domain': 'demoDomain' }; osAccount.DomainServerConfigManager.getAccountServerConfig(accountInfo).then(( serverConfig: osAccount.DomainServerConfig) => { console.log('get account server configuration successfully, the return config: ' + JSON.stringify(serverConfig)); }).catch((err: BusinessError) => { - console.log('add server configuration failed, error: ' + JSON.stringify(err)); + console.error('add server configuration failed, error: ' + JSON.stringify(err)); }); ``` @@ -3276,9 +3318,9 @@ Obtains the server configuration of a domain account. This API uses a promise to | constraint.wifi | Disallow the use of Wi-Fi. | | constraint.wifi.set | Disallow setting of Wi-Fi. | | constraint.locale.set | Disallow setting of the language to use. | -| constraint.app.accounts | Disallow adding or deletion of app accounts. | -| constraint.apps.install | Disallow app installation. | -| constraint.apps.uninstall | Disallow app uninstallation. | +| constraint.app.accounts | Disallow addition or deletion of application accounts. | +| constraint.apps.install | Disallow application installation. | +| constraint.apps.uninstall | Disallow application uninstallation. | | constraint.location.shared | Disallow location sharing. | | constraint.unknown.sources.install | Disallow installation of apps from unknown sources. | | constraint.global.unknown.app.install | Disallow installation of apps from unknown sources for all users.| @@ -3297,7 +3339,7 @@ Obtains the server configuration of a domain account. This API uses a promise to | constraint.factory.reset | Disallow reset to factory settings.| | constraint.os.account.create | Disallow creation of new users.| | constraint.add.managed.profile | Disallow addition of managed profiles.| -| constraint.apps.verify.disable | Disallow app verification from being disabled.| +| constraint.apps.verify.disable | Disallow application verification from being disabled.| | constraint.cell.broadcasts.set | Disallow setting of cell broadcasts.| | constraint.mobile.networks.set | Disallow setting of mobile networks.| | constraint.control.apps | Disallow modification of apps in **Settings** or the boot module.| @@ -3308,13 +3350,13 @@ Obtains the server configuration of a domain account. This API uses a promise to | constraint.calls.outgoing | Disallow outgoing calls.| | constraint.sms.use | Disallow the use of the short message service (SMS).| | constraint.fun | Disallow the use of entertainment features.| -| constraint.windows.create | Disallow creation of the windows other than app windows.| +| constraint.windows.create | Disallow creation of the windows other than application windows.| | constraint.system.error.dialogs | Disallow display of error dialogs for crashed or unresponsive apps.| | constraint.cross.profile.copy.paste | Disallow pasting of clipboard content to other users or profiles.| | constraint.beam.outgoing | Disallow the use of Near Field Communications (NFC) to transfer data from apps.| | constraint.wallpaper | Disallow wallpaper management.| | constraint.safe.boot | Disallow reboot of the device in safe boot mode.| -| constraint.parent.profile.app.linking | Disallow the app in the parent profile from handling web links from the managed profiles.| +| constraint.parent.profile.app.linking | Disallow the application in the parent profile from handling web links from the managed profiles.| | constraint.audio.record | Disallow audio recording.| | constraint.camera.use | Disallow the use of cameras.| | constraint.os.account.background.run | Disallow background system accounts.| diff --git a/en/application-dev/reference/apis-basic-services-kit/js-apis-pasteboard.md b/en/application-dev/reference/apis-basic-services-kit/js-apis-pasteboard.md index e4ef7367b8f..b69e5c07e9a 100644 --- a/en/application-dev/reference/apis-basic-services-kit/js-apis-pasteboard.md +++ b/en/application-dev/reference/apis-basic-services-kit/js-apis-pasteboard.md @@ -1,6 +1,6 @@ # @ohos.pasteboard (Pasteboard) -The **Pasteboard** module provides the copy and paste support for the system pasteboard. You can use the APIs of this module to operate pasteboard content of the plain text, HTML, URI, Want, pixel map, and other types. +This module provides the capabilities of managing the system pasteboard to support the copy and paste functions. You can use the APIs of this module to operate pasteboard content of the plain text, HTML, URI, Want, pixel map, and other types. > **NOTE** > @@ -39,8 +39,8 @@ Enumerates the value types. | Type| Description| | -------- | -------- | -| string | The value is a string.| -| image.PixelMap | The value is of the [image.PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7) type.| +| string | The value is of the string type.| +| image.PixelMap | The value is of the [image.PixelMap](../apis-image-kit/arkts-apis-image-PixelMap.md) type.| | Want | The value is of the [Want](../apis-ability-kit/js-apis-app-ability-want.md) type.| | ArrayBuffer | The value is of the **ArrayBuffer** type.| @@ -58,7 +58,7 @@ Creates a **PasteData** object of the specified type. | Name| Type| Mandatory| Description | | -------- | -------- | -------- |--------------------------------------------------------------------------------------------------------| -| mimeType | string | Yes| MIME type of custom data. The value can a predefined MIME type listed in [Constants](#constants), including HTML, WANT, plain text, URI, and pixel map, or a custom MIME type. The value of **mimeType** cannot exceed 1024 bytes.| +| mimeType | string | Yes| MIME type of custom data. The value can be a predefined MIME type listed in [Constants](#constants), including HTML, WANT, plain text, URI, and pixel map, or a custom MIME type. The value of **mimeType** cannot exceed 1024 bytes.| | value | [ValueType](#valuetype9) | Yes| Content of custom data. | **Return value** @@ -137,7 +137,7 @@ let pasteData: pasteboard.PasteData = pasteboard.createData(record); ## pasteboard.createRecord9+ -createRecord(mimeType: string, value: ValueType):PasteDataRecord +createRecord(mimeType: string, value: ValueType): PasteDataRecord Creates a **PasteDataRecord** object of the specified type. @@ -149,7 +149,7 @@ Creates a **PasteDataRecord** object of the specified type. | Name| Type| Mandatory| Description | | -------- | -------- | -------- |-------------------| -| mimeType | string | Yes| MIME type of custom data. The value can a predefined MIME type listed in [Constants](#constants), including HTML, WANT, plain text, URI, and pixel map, or a custom MIME type. The value of **mimeType** cannot exceed 1024 bytes. | +| mimeType | string | Yes| MIME type of custom data. The value can be a predefined MIME type listed in [Constants](#constants), including HTML, WANT, plain text, URI, and pixel map, or a custom MIME type. The value of **mimeType** cannot exceed 1024 bytes. | | value | [ValueType](#valuetype9) | Yes| Data content of the specified type. | **Return value** @@ -215,7 +215,7 @@ Enumerates the pasteable ranges of pasteboard data. | ---------------------------------- | --- | ------------------------------------------------------------------------------------- | | INAPP | 0 | Only intra-application pasting is allowed. | | LOCALDEVICE | 1 | Paste is allowed in any application. | -| CROSSDEVICE(deprecated) | 2 | Paste is allowed in any application across devices.
This API is deprecated since API version 12 without any alternative API or method.| +| CROSSDEVICE(deprecated) | 2 | Paste is allowed in any application across devices.
This API is deprecated since API version 12 without any alternative API or method. | ## pasteboard.createHtmlData(deprecated) @@ -224,7 +224,7 @@ createHtmlData(htmlText: string): PasteData Creates a **PasteData** object of the HTML type. > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [pasteboard.createData](#pasteboardcreatedata9). +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [pasteboard.createData](#pasteboardcreatedata9) instead. **System capability**: SystemCapability.MiscServices.Pasteboard @@ -254,7 +254,7 @@ createWantData(want: Want): PasteData Creates a **PasteData** object of the Want type. > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [pasteboard.createData](#pasteboardcreatedata9). +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [pasteboard.createData](#pasteboardcreatedata9) instead. **System capability**: SystemCapability.MiscServices.Pasteboard @@ -289,7 +289,7 @@ createPlainTextData(text: string): PasteData Creates a **PasteData** object of the plain text type. > **NOTE** > -> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [pasteboard.createData](#pasteboardcreatedata9). +> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [pasteboard.createData](#pasteboardcreatedata9) instead. **System capability**: SystemCapability.MiscServices.Pasteboard @@ -318,7 +318,7 @@ createUriData(uri: string): PasteData Creates a **PasteData** object of the URI type. > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [pasteboard.createData](#pasteboardcreatedata9). +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [pasteboard.createData](#pasteboardcreatedata9) instead. **System capability**: SystemCapability.MiscServices.Pasteboard @@ -346,7 +346,7 @@ createHtmlTextRecord(htmlText: string): PasteDataRecord Creates a **PasteDataRecord** object of the HTML text type. > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [pasteboard.createRecord](#pasteboardcreaterecord9). +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [pasteboard.createRecord](#pasteboardcreaterecord9) instead. **System capability**: SystemCapability.MiscServices.Pasteboard @@ -376,7 +376,7 @@ createWantRecord(want: Want): PasteDataRecord Creates a **PasteDataRecord** object of the Want type. > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [pasteboard.createRecord](#pasteboardcreaterecord9). +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [pasteboard.createRecord](#pasteboardcreaterecord9) instead. **System capability**: SystemCapability.MiscServices.Pasteboard @@ -411,7 +411,7 @@ createPlainTextRecord(text: string): PasteDataRecord Creates a **PasteDataRecord** object of the plain text type. > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [pasteboard.createRecord](#pasteboardcreaterecord9). +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [pasteboard.createRecord](#pasteboardcreaterecord9) instead. **System capability**: SystemCapability.MiscServices.Pasteboard @@ -440,7 +440,7 @@ createUriRecord(uri: string): PasteDataRecord Creates a **PasteDataRecord** object of the URI type. > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [pasteboard.createRecord](#pasteboardcreaterecord9). +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [pasteboard.createRecord](#pasteboardcreaterecord9) instead. **System capability**: SystemCapability.MiscServices.Pasteboard @@ -471,14 +471,14 @@ Defines the properties of all data records on the pasteboard, including the time **System capability**: SystemCapability.MiscServices.Pasteboard -| Name| Type| Readable| Writable| Description| +| Name| Type| Read-Only| Optional| Description| | -------- | -------- | -------- | -------- |-------------------------------| -| additions7+ | {[key:string]:object} | Yes| Yes| Additional data. It does not allow for dynamic adding of attributes. Attributes can be added only by re-assigning values. For details, see the example of **setProperty**.| +| additions7+ | {[key:string]:object} | No| Yes| Additional data. It does not allow for dynamic adding of attributes. Attributes can be added only by re-assigning values. For details, see the example of **setProperty**.| | mimeTypes7+ | Array<string> | Yes| No| Non-repeating data types of the data records on the pasteboard.| -| tag7+ | string | Yes| Yes| Custom tag.| +| tag7+ | string | No| Yes| Custom tag.| | timestamp7+ | number | Yes| No| Timestamp when data is written to the pasteboard (unit: ms).| -| localOnly7+ | boolean | Yes| Yes| Whether the pasteboard content is for local access only. The default value is **false**. The value will be overwritten by the value of the **shareOption** attribute. You are advised to use the [ShareOption](#shareoption9) attribute instead.| -| shareOption9+ | [ShareOption](#shareoption9) | Yes| Yes| Pasteable ranges of pasteboard data.| +| localOnly7+ | boolean | No| Yes| Whether the pasteboard content is for local access only. The default value is **false**. The value will be overwritten by the value of the **shareOption** attribute. You are advised to use the [ShareOption](#shareoption9) attribute instead.| +| shareOption9+ | [ShareOption](#shareoption9) | No| Yes| Pasteable ranges of pasteboard data.| ## FileConflictOptions15+ @@ -514,7 +514,7 @@ Defines the progress information. This information is reported only when [Progre **System capability**: SystemCapability.MiscServices.Pasteboard -| Name | Type | Readable| Writable| Description | +| Name | Type | Read-Only| Optional| Description | | -------- | ------ | ---- | ---- | ---------------------------------------------------------- | | progress | number | Yes | No | If the progress indicator provided by the system is not used, the system reports the progress percentage of the copy-and-paste task.| @@ -615,14 +615,14 @@ Provides **PasteDataRecord** APIs. A **PasteDataRecord** is an abstract definiti **System capability**: SystemCapability.MiscServices.Pasteboard -| Name| Type| Readable| Writable| Description| +| Name| Type| Read-Only| Optional| Description| | -------- | -------- | -------- | -------- | -------- | | htmlText7+ | string | Yes| No| HTML content.| | want7+ | [Want](../apis-ability-kit/js-apis-app-ability-want.md) | Yes| No| Want content.| | mimeType7+ | string | Yes| No| Default data type.| | plainText7+ | string | Yes| No| Plain text.| | uri7+ | string | Yes| No| URI content.| -| pixelMap9+ | [image.PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7) | Yes| No| Pixel map.| +| pixelMap9+ | [image.PixelMap](../apis-image-kit/arkts-apis-image-PixelMap.md) | Yes| No| Pixel map.| | data9+ | {[mimeType: string]: ArrayBuffer} | Yes| No| Content of custom data.| ### toPlainText9+ @@ -661,7 +661,7 @@ Adds custom data of an extra type to **PasteDataRecord**. The MIME type added us | Name | Type| Mandatory| Description | |-------| -------- | -------- |-------------------| -| type | string | Yes| MIME type of custom data. The value can a predefined MIME type listed in [Constants](#constants), including HTML, WANT, plain text, URI, and pixel map, or a custom MIME type. The value of **mimeType** cannot exceed 1024 bytes. | +| type | string | Yes| MIME type of custom data. The value can be a predefined MIME type listed in [Constants](#constants), including HTML, WANT, plain text, URI, and pixel map, or a custom MIME type. The value of **mimeType** cannot exceed 1024 bytes. | | value | [ValueType](#valuetype9) | Yes| Content of custom data. | **Error codes** @@ -783,7 +783,7 @@ convertToText(callback: AsyncCallback<string>): void Forcibly converts the content in a **PasteData** object to text. This API uses an asynchronous callback to return the result. > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [toPlainText](#toplaintext9). +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [toPlainText](#toplaintext9) instead. **System capability**: SystemCapability.MiscServices.Pasteboard @@ -823,7 +823,7 @@ convertToText(): Promise<string> Forcibly converts the content in a **PasteData** object to text. This API uses a promise to return the result. > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [toPlainText](#toplaintext9). +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [toPlainText](#toplaintext9) instead. **System capability**: SystemCapability.MiscServices.Pasteboard @@ -985,7 +985,7 @@ Obtains the pixel map of the primary record. | Type| Description| | -------- | -------- | -| [image.PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7) | Pixel map. If the **PasteData** object does not contain the pixel map, **undefined** is returned by default.| +| [image.PixelMap](../apis-image-kit/arkts-apis-image-PixelMap.md) | Pixel map. If the **PasteData** object does not contain the pixel map, **undefined** is returned by default.| **Example** @@ -1449,7 +1449,7 @@ Adds an HTML record to this pasteboard, and adds **MIMETYPE_TEXT_HTML** to **mim > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [addRecord](#addrecord9). +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [addRecord](#addrecord9) instead. **System capability**: SystemCapability.MiscServices.Pasteboard @@ -1475,7 +1475,7 @@ Adds a Want record to this pasteboard, and adds **MIMETYPE_TEXT_WANT** to **mime > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [addRecord](#addrecord9). +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [addRecord](#addrecord9) instead. **System capability**: SystemCapability.MiscServices.Pasteboard @@ -1506,7 +1506,7 @@ Adds a plain text record to this pasteboard, and adds **MIME_TEXT_PLAIN** to **m > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [addRecord](#addrecord9). +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [addRecord](#addrecord9) instead. **System capability**: SystemCapability.MiscServices.Pasteboard @@ -1531,7 +1531,7 @@ Adds a URI record to this pasteboard, and adds **MIMETYPE_TEXT_URI** to **mimeTy > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [addRecord](#addrecord9). +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [addRecord](#addrecord9) instead. **System capability**: SystemCapability.MiscServices.Pasteboard @@ -1554,7 +1554,7 @@ getRecordAt(index: number): PasteDataRecord Obtains the record with a specific index from the pasteboard. > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getRecord](#getrecord9). +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getRecord](#getrecord9) instead. **System capability**: SystemCapability.MiscServices.Pasteboard @@ -1592,7 +1592,7 @@ hasMimeType(mimeType: string): boolean Checks whether the pasteboard contains data of the specified type. > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [hasType](#hastype9). +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [hasType](#hastype9) instead. **System capability**: SystemCapability.MiscServices.Pasteboard @@ -1629,7 +1629,7 @@ removeRecordAt(index: number): boolean Removes the record with a specific index from the pasteboard. > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [removeRecord](#removerecord9). +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [removeRecord](#removerecord9) instead. **System capability**: SystemCapability.MiscServices.Pasteboard @@ -1666,7 +1666,7 @@ replaceRecordAt(index: number, record: PasteDataRecord): boolean Replaces the record with a specific index from the pasteboard. > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [replaceRecord](#replacerecord9). +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [replaceRecord](#replacerecord9) instead. **System capability**: SystemCapability.MiscServices.Pasteboard @@ -1703,7 +1703,7 @@ let systemPasteboard: pasteboard.SystemPasteboard = pasteboard.getSystemPasteboa ### on('update')7+ -on(type: 'update', callback: () =>void ): void +on(type: 'update', callback: () =>void): void Subscribes to the content change event of the system pasteboard. @@ -1736,7 +1736,7 @@ systemPasteboard.on('update', listener); ### off('update')7+ -off(type: 'update', callback?: () =>void ): void +off(type: 'update', callback?: () =>void): void Unsubscribes from the system pasteboard content change event. @@ -1922,7 +1922,7 @@ systemPasteboard.setData(pasteData).then((data: void) => { ### getData9+ -getData( callback: AsyncCallback<PasteData>): void +getData(callback: AsyncCallback<PasteData>): void Obtains a **PasteData** object from the pasteboard. This API uses an asynchronous callback to return the result. @@ -2078,7 +2078,7 @@ clear(callback: AsyncCallback<void>): void Clears the system pasteboard. This API uses an asynchronous callback to return the result. > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [pasteboard.clearData](#cleardata9). +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [pasteboard.clearData](#cleardata9) instead. **System capability**: SystemCapability.MiscServices.Pasteboard @@ -2116,7 +2116,7 @@ clear(): Promise<void> Clears the system pasteboard. This API uses a promise to return the result. > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [pasteboard.clearData](#cleardata9-1). +> This parameter is supported since API version 7 and deprecated since API version 9. Use [pasteboard.clearData](#cleardata9-1) instead. **System capability**: SystemCapability.MiscServices.Pasteboard @@ -2141,12 +2141,12 @@ systemPasteboard.clear().then((data) => { ### getPasteData(deprecated) -getPasteData( callback: AsyncCallback<PasteData>): void +getPasteData(callback: AsyncCallback<PasteData>): void Obtains a **PasteData** object from the pasteboard. This API uses an asynchronous callback to return the result. > **NOTE** > -> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [getData](#getdata9). +> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [getData](#getdata9) instead. **System capability**: SystemCapability.MiscServices.Pasteboard @@ -2186,7 +2186,7 @@ getPasteData(): Promise<PasteData> Obtains a **PasteData** object from the pasteboard. This API uses a promise to return the result. > **NOTE** > -> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [getData](#getdata9-1). +> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [getData](#getdata9-1) instead. **System capability**: SystemCapability.MiscServices.Pasteboard @@ -2216,7 +2216,7 @@ hasPasteData(callback: AsyncCallback<boolean>): void Checks whether the system pasteboard contains data. This API uses an asynchronous callback to return the result. > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [hasData](#hasdata9). +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [hasData](#hasdata9) instead. **System capability**: SystemCapability.MiscServices.Pasteboard @@ -2256,7 +2256,7 @@ hasPasteData(): Promise<boolean> Checks whether the system pasteboard contains data. This API uses a promise to return the result. > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [hasData](#hasdata9-1). +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [hasData](#hasdata9-1) instead. **System capability**: SystemCapability.MiscServices.Pasteboard @@ -2286,7 +2286,7 @@ setPasteData(data: PasteData, callback: AsyncCallback<void>): void Writes a **PasteData** object to the pasteboard. This API uses an asynchronous callback to return the result. > **NOTE** > -> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [setData](#setdata9). +> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [setData](#setdata9) instead. **System capability**: SystemCapability.MiscServices.Pasteboard @@ -2325,7 +2325,7 @@ setPasteData(data: PasteData): Promise<void> Writes a **PasteData** object to the pasteboard. This API uses a promise to return the result. > **NOTE** > -> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [setData](#setdata9-1). +> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [setData](#setdata9-1) instead. **System capability**: SystemCapability.MiscServices.Pasteboard @@ -2376,7 +2376,7 @@ For details about the error codes, see [Pasteboard Error Codes](errorcode-pasteb | Error Code ID| Error Message| | -------- | -------- | -| 12900005 | Request timed out. | +| 12900005 | Excessive processing time for internal data. | **Example** @@ -2412,7 +2412,7 @@ For details about the error codes, see [Pasteboard Error Codes](errorcode-pasteb | Error Code ID| Error Message| | -------- | -------- | -| 12900005 | Request timed out. | +| 12900005 | Excessive processing time for internal data. | **Example** @@ -2455,7 +2455,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | Error Code ID| Error Message| | -------- | -------- | | 401 | Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types. | -| 12900005 | Request timed out. | +| 12900005 | Excessive processing time for internal data. | **Example** @@ -2485,7 +2485,7 @@ For details about the error codes, see [Pasteboard Error Codes](errorcode-pasteb | Error Code ID| Error Message| | -------- | -------- | -| 12900005 | Request timed out. | +| 12900005 | Excessive processing time for internal data. | **Example** @@ -2523,7 +2523,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | Error Code ID| Error Message| | -------- | -------- | -| 12900005 | Request timed out. | +| 12900005 | Excessive processing time for internal data. | | 201 | Permission verification failed. The application does not have the permission required to call the API. | **Example** @@ -2561,7 +2561,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | Error Code ID| Error Message| | -------- | -------- | | 401 | Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types. | -| 12900005 | Request timed out. | +| 12900005 | Excessive processing time for internal data. | **Example** @@ -2598,7 +2598,7 @@ For details about the error codes, see [Pasteboard Error Codes](errorcode-pasteb | Error Code ID| Error Message| | -------- | -------- | -| 12900005 | Request timed out. | +| 12900005 | Excessive processing time for internal data. | **Example** @@ -2684,7 +2684,7 @@ For details about the error codes, see [Pasteboard Error Codes](errorcode-pasteb | Error Code ID| Error Message| | -------- | -------- | | 201 | Permission verification failed. The application does not have the permission required to call the API. | -| 12900005 | Request timed out. | +| 12900005 | Excessive processing time for internal data. | **Example** @@ -2778,7 +2778,7 @@ For details about the error codes, see [Pasteboard Error Codes](errorcode-pasteb | Error Code ID| Error Message| | -------- | -------- | | 401 | Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types. | -| 12900005 | Request timed out. | +| 12900005 | Excessive processing time for internal data. | **Example** @@ -3002,10 +3002,10 @@ For details about the error codes, see [Pasteboard Error Codes](errorcode-pasteb | 201 | Permission verification failed. The application does not have the permission required to call the API. | | 401 | Parameter error. | | 12900003 | Another copy or paste operation is in progress. | -| 12900007 | Copy file failed. | +| 12900007 | Invalid destUri or file system error. | | 12900008 | Failed to start progress. | | 12900009 | Progress exits abnormally. | -| 12900010 | Get pasteData error. | +| 12900010 | System error occurred during paste execution. | **Example** @@ -3050,9 +3050,9 @@ struct PasteboardTest { getChangeCount(): number -Obtains the number of times that the pasteboard data changes. +Obtains the number of pasteboard content changes. -Returns the result if this API is called successfully; otherwise, returns **0**. +Returns the number of pasteboard content changes if this API is called successfully; returns **0** otherwise. Even though the pasteboard data expires, or the data becomes empty because of the called [clearDataSync](#cleardatasync11) API, the number of data changes remains. @@ -3066,7 +3066,7 @@ When the system is restarted, or the pasteboard service is restarted due to an e | Type| Description| | -------- | -------- | -| number | Number of times that the pasteboard data changes.| +| number | The number of pasteboard content changes obtained.| **Example** diff --git a/en/application-dev/reference/apis-basic-services-kit/js-apis-power-sys.md b/en/application-dev/reference/apis-basic-services-kit/js-apis-power-sys.md index 53148fd6c60..064c92ca496 100644 --- a/en/application-dev/reference/apis-basic-services-kit/js-apis-power-sys.md +++ b/en/application-dev/reference/apis-basic-services-kit/js-apis-power-sys.md @@ -34,7 +34,7 @@ Shuts down the system. **Error codes** -For details about the error codes, see [Power Manager Error Codes](errorcode-power.md). +For details about the error codes, see [Power Manager Error Codes]errorcode-power.md) and [Universal Error Codes](../errorcode-universal.md). | ID | Error Message | |---------|---------| @@ -74,7 +74,7 @@ The device is restarted. **Error codes** -For details about the error codes, see [Power Manager Error Codes](errorcode-power.md). +For details about the error codes, see [Power Manager Error Codes]errorcode-power.md) and [Universal Error Codes](../errorcode-universal.md). | ID | Error Message | |---------|---------| @@ -103,7 +103,7 @@ Wakes up a device. **Required permissions**: ohos.permission.POWER_MANAGER -For API version 9 to 17, no permission is required to use this API. Since API version 18, this permission is required. +For API version 9 to 18, no permission is required; since API version 19, this permission is required. **System capability**: SystemCapability.PowerManager.PowerManager.Core @@ -115,7 +115,7 @@ For API version 9 to 17, no permission is required to use this API. Since API ve **Error codes** -For details about the error codes, see [Power Manager Error Codes](errorcode-power.md). +For details about the error codes, see [Power Manager Error Codes]errorcode-power.md) and [Universal Error Codes](../errorcode-universal.md). | ID | Error Message | |---------|---------| @@ -144,7 +144,7 @@ Hibernates a device. **Required permissions**: ohos.permission.POWER_MANAGER -For API version 9 to 17, no permission is required to use this API. Since API version 18, this permission is required. +For API version 9 to 18, no permission is required; since API version 19, this permission is required. **System capability**: SystemCapability.PowerManager.PowerManager.Core @@ -152,12 +152,12 @@ For API version 9 to 17, no permission is required to use this API. Since API ve | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ---------- | -| isImmediate10+ | boolean | No | Whether to hibernate a device immediately. If this parameter is not specified, the default value **false** is used. The system automatically determines when to enter the hibernation state.
**NOTE**: This parameter is supported since API version 10.| +| isImmediate10+ | boolean | No | Whether to hibernate a device immediately after the screen is turned off. The value **true** indicates that the device is hibernated immediately; **false** indicates that the system controls when the device is hibernated. If this parameter is not set, the default value **false** is used. If you only want to turn off the screen, you are advised not to set this parameter.
**NOTE**: This parameter is supported since API version 10.| **Error codes** -For details about the error codes, see [Power Manager Error Codes](errorcode-power.md). +For details about the error codes, see [Power Manager Error Codes]errorcode-power.md) and [Universal Error Codes](../errorcode-universal.md). | ID | Error Message | |---------|---------| @@ -197,11 +197,10 @@ Sets the power mode of this device. This API uses an asynchronous callback to re **Error codes** -For details about the error codes, see [Power Manager Error Codes](errorcode-power.md). +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). | ID | Error Message | |---------|---------| -| 4900101 | Failed to connect to the service. | | 401 | Parameter error. Possible causes: 1.Parameter verification failed. | | 201 | Permission verification failed. The application does not have the permission required to call the API. | | 202 | Permission verification failed. A non-system application calls a system API. | @@ -244,11 +243,10 @@ Sets the power mode of this device. This API uses a promise to return the result **Error codes** -For details about the error codes, see [Power Manager Error Codes](errorcode-power.md). +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). | ID | Error Message | |---------|---------| -| 4900101 | Failed to connect to the service. | | 401 | Parameter error. Possible causes: 1.Parameter verification failed. | | 201 | Permission verification failed. The application does not have the permission required to call the API. | | 202 | Permission verification failed. A non-system application calls a system API. | @@ -275,7 +273,7 @@ Set the screen-off timeout duration. **Required permissions**: ohos.permission.POWER_MANAGER -For API version 12 to 17, no permission is required to use this API. Since API version 18, this permission is required. +For API version 12 to 18, no permission is required; since API version 19, this permission is required. **System capability**: SystemCapability.PowerManager.PowerManager.Core @@ -287,7 +285,7 @@ For API version 12 to 17, no permission is required to use this API. Since API v **Error codes** -For details about the error codes, see [Power Manager Error Codes](errorcode-power.md). +For details about the error codes, see [Power Manager Error Codes]errorcode-power.md) and [Universal Error Codes](../errorcode-universal.md). | ID | Error Message | |---------|---------| @@ -316,7 +314,7 @@ Hibernates a device. **Required permissions**: ohos.permission.POWER_MANAGER -For API version 12 to 17, no permission is required to use this API. Since API version 18, this permission is required. +For API version 12 to 18, no permission is required; since API version 19, this permission is required. **System capability**: SystemCapability.PowerManager.PowerManager.Core @@ -328,7 +326,7 @@ For API version 12 to 17, no permission is required to use this API. Since API v **Error codes** -For details about the error codes, see [Power Manager Error Codes](errorcode-power.md). +For details about the error codes, see [Power Manager Error Codes]errorcode-power.md) and [Universal Error Codes](../errorcode-universal.md). | ID | Error Message | |---------|---------| diff --git a/en/application-dev/reference/apis-basic-services-kit/js-apis-power.md b/en/application-dev/reference/apis-basic-services-kit/js-apis-power.md index dbbb65b2b52..521c55d7136 100644 --- a/en/application-dev/reference/apis-basic-services-kit/js-apis-power.md +++ b/en/application-dev/reference/apis-basic-services-kit/js-apis-power.md @@ -1,7 +1,6 @@ # @ohos.power (Power Management) -The **power** module provides APIs for rebooting and shutting down the system, as well as querying the screen status. - +The **power** module provides APIs for rebooting and shutting down the system, as well as querying the screen status. You can use these APIs to obtain the device activity status, power mode, and screen on/off status. > **NOTE** > > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -16,27 +15,23 @@ import {power} from '@kit.BasicServicesKit'; isActive(): boolean -Checks whether the current device is active. In the active state, the screen is on if the device has a screen and the device is not in sleep state if the device does not have a screen. - -**System capability:** SystemCapability.PowerManager.PowerManager.Core +Checks whether the current device is active. +- A device with a screen is active when the screen is on and inactive when the screen is off. +- A device without a screen is active when it exits the sleep mode and inactive when it enters the sleep mode. -**Error codes** +**System capability**: SystemCapability.PowerManager.PowerManager.Core -For details about the error codes, see [Power Manager Error Codes](errorcode-power.md). +**Returns** -| ID | Error Message | -|---------|---------| -| 4900101 | Failed to connect to the service. | +| Type | Description | +| ------------------- | -------------------------------------- | +| boolean | Returns **true** if the device is active; returns **false** otherwise.| **Example** ```js -try { - let isActive = power.isActive(); - console.info('power is active: ' + isActive); -} catch(err) { - console.error('check active status failed, err: ' + err); -} +let isActive = power.isActive(); +console.info('power is active: ' + isActive); ``` ## power.rebootDevice(deprecated) @@ -49,7 +44,7 @@ Reboots a device. **Required permissions**: ohos.permission.REBOOT (available only for system applications) -**System capability:** SystemCapability.PowerManager.PowerManager.Core +**System capability**: SystemCapability.PowerManager.PowerManager.Core **Parameters** @@ -70,31 +65,19 @@ getPowerMode(): DevicePowerMode Obtains the power mode of this device. -**System capability:** SystemCapability.PowerManager.PowerManager.Core +**System capability**: SystemCapability.PowerManager.PowerManager.Core -**Return value** +**Returns** | Type | Description | | ------------------------------------ | ---------- | | [DevicePowerMode](#devicepowermode9) | Power mode.| -**Error codes** - -For details about the error codes, see [Power Manager Error Codes](errorcode-power.md). - -| ID | Error Message | -|---------|---------| -| 4900101 | Failed to connect to the service. | - **Example** ```js -try { - let mode = power.getPowerMode(); - console.info('power mode: ' + mode); -} catch(err) { - console.error('get power mode failed, err: ' + err); -} +let mode = power.getPowerMode(); +console.info('power mode: ' + mode); ``` ## power.isStandby10+ @@ -103,9 +86,9 @@ isStandby(): boolean Checks whether the device is in standby mode. -**System capability:** SystemCapability.PowerManager.PowerManager.Core +**System capability**: SystemCapability.PowerManager.PowerManager.Core -**Return value** +**Returns** | Type | Description | | ------------------- | -------------------------------------- | @@ -138,7 +121,7 @@ isScreenOn(callback: AsyncCallback<boolean>): void Checks the screen status of the current device. This API uses an asynchronous callback to return the result. -**System capability:** SystemCapability.PowerManager.PowerManager.Core +**System capability**: SystemCapability.PowerManager.PowerManager.Core **Parameters** @@ -166,9 +149,9 @@ isScreenOn(): Promise<boolean> Checks the screen status of the current device. This API uses a promise to return the result. -**System capability:** SystemCapability.PowerManager.PowerManager.Core +**System capability**: SystemCapability.PowerManager.PowerManager.Core -**Return value** +**Returns** | Type | Description | | ---------------------- | -------------------------------------------------- | | Promise<boolean> | Promise used to return the result. The value **true** indicates that the screen is on, and the value **false** indicates the opposite.| @@ -189,7 +172,7 @@ power.isScreenOn() Enumerates power modes. -**System capability:** SystemCapability.PowerManager.PowerManager.Core +**System capability**: SystemCapability.PowerManager.PowerManager.Core | Name | Value | Description | | ----------------------- | ---- | ---------------------- | diff --git a/en/application-dev/reference/apis-basic-services-kit/js-apis-print-sys.md b/en/application-dev/reference/apis-basic-services-kit/js-apis-print-sys.md index 4cc54be75ae..9a3c5844d1a 100644 --- a/en/application-dev/reference/apis-basic-services-kit/js-apis-print-sys.md +++ b/en/application-dev/reference/apis-basic-services-kit/js-apis-print-sys.md @@ -13,7 +13,7 @@ import { print } from '@kit.BasicServicesKit'; ``` -## print.PrintMargin +## PrintMargin Defines the page margins for printing. @@ -24,12 +24,12 @@ Defines the page margins for printing. **Attributes** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | -| top | number | No| Top margin of the page.| -| bottom | number | No| Bottom margin of the page.| -| left | number | No| Left margin of the page.| -| right | number | No| Right margin of the page.| +| top | number | No| Top margin of the page. The default value is **0**.| +| bottom | number | No| Bottom margin of the page. The default value is **0**.| +| left | number | No| Left margin of the page. The default value is **0**.| +| right | number | No| Right margin of the page. The default value is **0**.| -## print.PrinterRange +## PrinterRange Defines the print range. @@ -40,11 +40,11 @@ Defines the print range. **Attributes** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | -| startPage | number | No| Start page.| -| endPage | number | No| End page.| -| pages | Array<number> | No| Discrete pages.| +| startPage | number | No| Start page. The default value is **1**.| +| endPage | number | No| End page. The default value is the maximum number of pages of the file to be printed.| +| pages | Array<number> | No| Page range set of the file to print. The default value is empty.| -## print.PreviewAttribute +## PreviewAttribute Defines the print preview attributes. @@ -55,10 +55,10 @@ Defines the print preview attributes. **Attributes** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | -| previewRange | [PrinterRange](#printprinterrange) | Yes| Preview page range.| -| result | number | No| Print preview result.| +| previewRange | [PrinterRange](#printerrange) | Yes| Preview page range.| +| result | number | No| Print preview result. The default value is **-1**.| -## print.PrintResolution +## PrintResolution Defines the resolution for printing. @@ -73,7 +73,9 @@ Defines the resolution for printing. | horizontalDpi | number | Yes| Horizontal DPI.| | verticalDpi | number | Yes| Vertical DPI.| -## print.PrinterCapability + + +## PrinterCapability Defines the printer capabilities. @@ -86,12 +88,12 @@ Defines the printer capabilities. | -------- | -------- | -------- | -------- | | colorMode | number | Yes| Color mode.| | duplexMode | number | Yes| Single-sided or double-sided printing mode.| -| pageSize | Array<[PrintPageSize](./js-apis-print.md#printprintpagesize11)> | Yes| List of page sizes supported by the printer.| -| resolution | Array<[PrintResolution](#printprintresolution)> | No| List of resolutions supported by the printer.| -| minMargin | [PrintMargin](#printprintmargin) | No| Minimum margin of the printer.| +| pageSize | Array<[PrintPageSize](./js-apis-print.md#printpagesize11)> | Yes| List of page sizes supported by the printer.| +| resolution | Array<[PrintResolution](#printresolution)> | No| List of resolutions supported by the printer.| +| minMargin | [PrintMargin](#printmargin) | No| Minimum margin of the printer.| | options11+ | Object | No| Printer options. The value is a JSON object string.| -## print.PrinterInfo +## PrinterInfo Provides the printer information. @@ -104,13 +106,13 @@ Provides the printer information. | -------- | -------- | -------- | -------- | | printerId | string | Yes| Printer ID.| | printerName | string | Yes| Printer name.| -| printerState | [PrinterState](./js-apis-print.md#printprinterstate14) | Yes| Printer state.| -| printerIcon | number | No| Resource ID of the printer icon.| +| printerState | [PrinterState](./js-apis-print.md#printerstate14) | Yes| Printer state.| +| printerIcon | number | No| Resource ID of the printer icon. The default value is **-1**.| | description | string | No| Printer description.| -| capability | [PrinterCapability](#printprintercapability) | No| Printer capability.| +| capability | [PrinterCapability](#printercapability) | No| Printer capability.| | options | Object | No| Printer options. The value is a JSON object string.| -## print.PrintJob +## PrintJob Defines a print job. @@ -124,20 +126,20 @@ Defines a print job. | fdList | Array<number> | Yes| FD list of files to print.| | jobId | string | Yes| ID of the print job.| | printerId | string | Yes| ID of the printer used for printing.| -| jobState | [PrintJobState](./js-apis-print.md#printprintjobstate14) | Yes| State of the print job.| -| jobSubstate11+ | [PrintJobSubState](./js-apis-print.md#printprintjobsubstate14) | Yes| Substate of the print job.| +| jobState | [PrintJobState](./js-apis-print.md#printjobstate14) | Yes| State of the print job.| +| jobSubstate11+ | [PrintJobSubState](./js-apis-print.md#printjobsubstate14) | Yes| Substate of the print job.| | copyNumber | number | Yes| Copy of the file list.| -| pageRange | [PrinterRange](#printprinterrange) | Yes| Print range.| +| pageRange | [PrinterRange](#printerrange) | Yes| Print range.| | isSequential | boolean | Yes| Whether the printing is sequential. The value **true** means that the printing is sequential; the value **false** means the opposite. The default value is **false**.| -| pageSize | [PrintPageSize](./js-apis-print.md#printprintpagesize11) | Yes| Selected page size.| +| pageSize | [PrintPageSize](./js-apis-print.md#printpagesize11) | Yes| Selected page size.| | isLandscape | boolean | Yes| Whether the printing is in landscape mode. The value **true** means that the printing is in landscape mode; the value **false** means the printing is in portrait mode The default value is **false**.| | colorMode | number | Yes| Color mode.| | duplexMode | number | Yes| Single-sided or double-sided printing mode.| -| margin | [PrintMargin](#printprintmargin) | No| Current page margin.| -| preview | [PreviewAttribute](#printpreviewattribute) | No| Preview settings.| +| margin | [PrintMargin](#printmargin) | No| Current page margin.| +| preview | [PreviewAttribute](#previewattribute) | No| Preview settings.| | options | Object | No| Printer options. The value is a JSON object string.| -## print.PrinterExtensionInfo +## PrinterExtensionInfo Provides the printer extension information. @@ -169,7 +171,7 @@ Obtains the information of all installed printer extensions. This API uses an as **Parameters** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<Array<[PrinterExtensionInfo](#printprinterextensioninfo)>> | Yes| Callback used to return the result.| +| callback | AsyncCallback<Array<[PrinterExtensionInfo](#printerextensioninfo)>> | Yes| Callback used to return the result.| **Error codes** @@ -188,7 +190,7 @@ import { BusinessError } from '@ohos.base'; print.queryAllPrinterExtensionInfos((err: BusinessError, extensionInfos: print.PrinterExtensionInfo[]) => { if (err) { - console.log('queryAllPrinterExtensionInfos err ' + JSON.stringify(err)); + console.error('queryAllPrinterExtensionInfos err ' + JSON.stringify(err)); } else { console.log('queryAllPrinterExtensionInfos success ' + JSON.stringify(extensionInfos)); } @@ -210,7 +212,7 @@ Obtains the information of all installed printer extensions. This API uses a pro **Return value** | **Type**| **Description**| | -------- | -------- | -| Promise<Array<[PrinterExtensionInfo](#printprinterextensioninfo)>> | Promise used to return the result.used to return the result.| +| Promise<Array<[PrinterExtensionInfo](#printerextensioninfo)>> | Promise used to return the result.used to return the result.| **Error codes** @@ -231,7 +233,7 @@ print.queryAllPrinterExtensionInfos().then((extensionInfos: print.PrinterExtensi console.log('queryAllPrinterExtensionInfos success ' + JSON.stringify(extensionInfos)); // ... }).catch((error: BusinessError) => { - console.log('failed to get AllPrinterExtension bacause ' + JSON.stringify(error)); + console.error('failed to get AllPrinterExtension because ' + JSON.stringify(error)); }) ``` @@ -273,7 +275,7 @@ let extensionList: string[] = []; // If there is no information in extensionList, all extensions are used for printer discovery. print.startDiscoverPrinter(extensionList, (err: BusinessError, data : void) => { if (err) { - console.log('failed to start Discover Printer because : ' + JSON.stringify(err)); + console.error('failed to start Discover Printer because : ' + JSON.stringify(err)); } else { console.log('start Discover Printer success data : ' + JSON.stringify(data)); } @@ -323,7 +325,7 @@ let extensionList: string[] = []; print.startDiscoverPrinter(extensionList).then((data : void) => { console.log('start Discovery success data : ' + JSON.stringify(data)); }).catch((error: BusinessError) => { - console.log('failed to start Discovery because : ' + JSON.stringify(error)); + console.error('failed to start Discovery because : ' + JSON.stringify(error)); }) ``` @@ -361,7 +363,7 @@ import { BusinessError } from '@ohos.base'; print.stopDiscoverPrinter((err: BusinessError, data : void) => { if (err) { - console.log('failed to stop Discover Printer because : ' + JSON.stringify(err)); + console.error('failed to stop Discover Printer because : ' + JSON.stringify(err)); } else { console.log('stop Discover Printer success data : ' + JSON.stringify(data)); } @@ -403,7 +405,7 @@ import { BusinessError } from '@ohos.base'; print.stopDiscoverPrinter().then((data : void) => { console.log('stop Discovery success data : ' + JSON.stringify(data)); }).catch((error: BusinessError) => { - console.log('failed to stop Discovery because : ' + JSON.stringify(error)); + console.error('failed to stop Discovery because : ' + JSON.stringify(error)); }) ``` @@ -444,7 +446,7 @@ import { BusinessError } from '@ohos.base'; let printerId: string = 'printerId_32'; print.connectPrinter(printerId, (err: BusinessError, data : void) => { if (err) { - console.log('failed to connect Printer because : ' + JSON.stringify(err)); + console.error('failed to connect Printer because : ' + JSON.stringify(err)); } else { console.log('start connect Printer success data : ' + JSON.stringify(data)); } @@ -493,7 +495,7 @@ let printerId: string = 'printerId_32'; print.connectPrinter(printerId).then((data : void) => { console.log('start connect Printer success data : ' + JSON.stringify(data)); }).catch((error: BusinessError) => { - console.log('failed to connect Printer because : ' + JSON.stringify(error)); + console.error('failed to connect Printer because : ' + JSON.stringify(error)); }) ``` @@ -534,7 +536,7 @@ import { BusinessError } from '@ohos.base'; let printerId: string = 'printerId_32'; print.disconnectPrinter(printerId, (err: BusinessError, data : void) => { if (err) { - console.log('failed to disconnect Printer because : ' + JSON.stringify(err)); + console.error('failed to disconnect Printer because : ' + JSON.stringify(err)); } else { console.log('start disconnect Printer success data : ' + JSON.stringify(data)); } @@ -583,7 +585,7 @@ let printerId: string = 'printerId_32'; print.disconnectPrinter(printerId).then((data : void) => { console.log('start disconnect Printer success data : ' + JSON.stringify(data)); }).catch((error: BusinessError) => { - console.log('failed to disconnect Printer because : ' + JSON.stringify(error)); + console.error('failed to disconnect Printer because : ' + JSON.stringify(error)); }) ``` @@ -624,7 +626,7 @@ import { BusinessError } from '@ohos.base'; let printerId: string = 'printerId_32'; print.queryPrinterCapability(printerId, (err: BusinessError, data : void) => { if (err) { - console.log('failed to query Printer Capability because : ' + JSON.stringify(err)); + console.error('failed to query Printer Capability because : ' + JSON.stringify(err)); } else { console.log('start query Printer Capability success data : ' + JSON.stringify(data)); } @@ -673,7 +675,7 @@ let printerId: string = 'printerId_32'; print.queryPrinterCapability(printerId).then((data : void) => { console.log('start query Printer success data : ' + JSON.stringify(data)); }).catch((error: BusinessError) => { - console.log('failed to query Printer Capability because : ' + JSON.stringify(error)); + console.error('failed to query Printer Capability because : ' + JSON.stringify(error)); }) ``` @@ -692,7 +694,7 @@ Starts the specified print job. This API uses an asynchronous callback to return **Parameters** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | -| jobInfo | [PrintJob](#printprintjob) | Yes| Information about the print job.| +| jobInfo | [PrintJob](#printjob) | Yes| Information about the print job.| | callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Error codes** @@ -730,7 +732,7 @@ let jobInfo : print.PrintJob = { }; print.startPrintJob(jobInfo, (err: BusinessError, data : void) => { if (err) { - console.log('failed to start Print Job because : ' + JSON.stringify(err)); + console.error('failed to start Print Job because : ' + JSON.stringify(err)); } else { console.log('start Print Job success data : ' + JSON.stringify(data)); } @@ -752,7 +754,7 @@ Starts the specified print job. This API uses a promise to return the result. **Parameters** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | -| jobInfo | [PrintJob](#printprintjob) | Yes| Information about the print job.| +| jobInfo | [PrintJob](#printjob) | Yes| Information about the print job.| **Return value** | **Type**| **Description**| @@ -795,7 +797,7 @@ let jobInfo : print.PrintJob = { print.startPrintJob(jobInfo).then((data : void) => { console.log('start Print success data : ' + JSON.stringify(data)); }).catch((error: BusinessError) => { - console.log('failed to start Print because : ' + JSON.stringify(error)); + console.error('failed to start Print because : ' + JSON.stringify(error)); }) ``` @@ -836,7 +838,7 @@ import { BusinessError } from '@ohos.base'; let jobId : string = '121212'; print.cancelPrintJob(jobId, (err: BusinessError, data : void) => { if (err) { - console.log('cancelPrintJob failed, because : ' + JSON.stringify(err)); + console.error('cancelPrintJob failed, because : ' + JSON.stringify(err)); } else { console.log('cancelPrintJob success, data: ' + JSON.stringify(data)); } @@ -885,7 +887,7 @@ let jobId : string = '121212'; print.cancelPrintJob(jobId).then((data : void) => { console.log('cancelPrintJob success, data : ' + JSON.stringify(data)); }).catch((error: BusinessError) => { - console.log('cancelPrintJob failed, because : ' + JSON.stringify(error)); + console.error('cancelPrintJob failed, because : ' + JSON.stringify(error)); }) ``` @@ -904,7 +906,7 @@ Requests print preview data. This API uses a callback to return the result. **Parameters** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | -| jobInfo | [PrintJob](#printprintjob) | Yes| Information about the print job.| +| jobInfo | [PrintJob](#printjob) | Yes| Information about the print job.| | callback | Callback<number> | Yes| Callback used to return the result.| **Error codes** @@ -960,7 +962,7 @@ Requests print preview data. This API uses a promise to return the result. **Parameters** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | -| jobInfo | [PrintJob](#printprintjob) | Yes| Information about the print job.| +| jobInfo | [PrintJob](#printjob) | Yes| Information about the print job.| **Return value** | **Type**| **Description**| @@ -1003,7 +1005,7 @@ let jobInfo : print.PrintJob = { print.requestPrintPreview(jobInfo).then((num: number) => { console.log('requestPrintPreview success, num : ' + JSON.stringify(num)); }).catch((error: BusinessError) => { - console.log('requestPrintPreview failed, because : ' + JSON.stringify(error)); + console.error('requestPrintPreview failed, because : ' + JSON.stringify(error)); }) ``` @@ -1023,7 +1025,7 @@ Registers a listener for printer state change events. This API uses a callback t | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | 'printerStateChange' | Yes| Listening type. The value is fixed at **'printerStateChange'**.| -| callback | (state: [PrinterState](./js-apis-print.md#printprinterstate14), info: [PrinterInfo](#printprinterinfo)) => void | Yes| Callback used to return the result.| +| callback | (state: [PrinterState](./js-apis-print.md#printerstate14), info: [PrinterInfo](#printerinfo)) => void | Yes| Callback used to return the result.| **Error codes** @@ -1042,7 +1044,7 @@ import { print } from '@kit.BasicServicesKit'; print.on('printerStateChange', (state: print.PrinterState, info: print.PrinterInfo) => { if (state === null || info === null) { - console.log('printer state changed state is null or info is null'); + console.error('printer state changed state is null or info is null'); return; } else { console.log('on printer state changed, state : ' + JSON.stringify(state)); @@ -1105,7 +1107,7 @@ Registers a listener for print job state change events. This API uses a callback | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | 'jobStateChange' | Yes| Listening type. The value is fixed at **'jobStateChange'**.| -| callback | (state: [PrintJobState](./js-apis-print.md#printprintjobstate14), job: [PrintJob](#printprintjob)) => void | Yes| Callback used to return the result.| +| callback | (state: [PrintJobState](./js-apis-print.md#printjobstate14), job: [PrintJob](#printjob)) => void | Yes| Callback used to return the result.| **Error codes** @@ -1256,7 +1258,7 @@ Adds printers. This API uses an asynchronous callback to return the result. **Parameters** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | -| printers | Array<[PrinterInfo](#printprinterinfo)> | Yes| List of printers to add.| +| printers | Array<[PrinterInfo](#printerinfo)> | Yes| List of printers to add.| | callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Error codes** @@ -1286,7 +1288,7 @@ let printerInfo : print.PrinterInfo = { }; print.addPrinters([printerInfo], (err: BusinessError, data : void) => { if (err) { - console.log('addPrinters failed, because : ' + JSON.stringify(err)); + console.error('addPrinters failed, because : ' + JSON.stringify(err)); } else { console.log('addPrinters success, data : ' + JSON.stringify(data)); } @@ -1308,7 +1310,7 @@ Adds printers. This API uses a promise to return the result. **Parameters** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | -| printers | Array<[PrinterInfo](#printprinterinfo)> | Yes| List of printers to add.| +| printers | Array<[PrinterInfo](#printerinfo)> | Yes| List of printers to add.| **Return value** | **Type**| **Description**| @@ -1343,7 +1345,7 @@ let printerInfo : print.PrinterInfo = { print.addPrinters([printerInfo]).then((data : void) => { console.log('add printers data : ' + JSON.stringify(data)); }).catch((error: BusinessError) => { - console.log('add printers error : ' + JSON.stringify(error)); + console.error('add printers error : ' + JSON.stringify(error)); }) ``` @@ -1384,7 +1386,7 @@ import { BusinessError } from '@ohos.base'; let printerId : string = '1212'; print.removePrinters([printerId], (err: BusinessError, data : void) => { if (err) { - console.log('removePrinters failed, because : ' + JSON.stringify(err)); + console.error('removePrinters failed, because : ' + JSON.stringify(err)); } else { console.log('removePrinters success, data : ' + JSON.stringify(data)); } @@ -1433,7 +1435,7 @@ let printerId : string = '1212'; print.removePrinters([printerId]).then((data : void) => { console.log('remove printers data : ' + JSON.stringify(data)); }).catch((error: BusinessError) => { - console.log('remove printers error : ' + JSON.stringify(error)); + console.error('remove printers error : ' + JSON.stringify(error)); }) ``` @@ -1452,7 +1454,7 @@ Updates information about the specified printers. This API uses an asynchronous **Parameters** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | -| printers | Array<[PrinterInfo](#printprinterinfo)> | Yes| List of printers whose information is to be updated.| +| printers | Array<[PrinterInfo](#printerinfo)> | Yes| List of printers whose information is to be updated.| | callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Error codes** @@ -1482,7 +1484,7 @@ let printerInfo : print.PrinterInfo = { }; print.updatePrinters([printerInfo], (err: BusinessError, data : void) => { if (err) { - console.log('updataPrinters failed, because : ' + JSON.stringify(err)); + console.error('updataPrinters failed, because : ' + JSON.stringify(err)); } else { console.log('updataPrinters success, data : ' + JSON.stringify(data)); } @@ -1504,7 +1506,7 @@ Updates information about the specified printers. This API uses a promise to ret **Parameters** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | -| printers | Array<[PrinterInfo](#printprinterinfo)> | Yes| List of printers whose information is to be updated.| +| printers | Array<[PrinterInfo](#printerinfo)> | Yes| List of printers whose information is to be updated.| **Return value** | **Type**| **Description**| @@ -1539,7 +1541,7 @@ let printerInfo : print.PrinterInfo = { print.updatePrinters([printerInfo]).then((data : void) => { console.log('update printers data : ' + JSON.stringify(data)); }).catch((error: BusinessError) => { - console.log('update printers error : ' + JSON.stringify(error)); + console.error('update printers error : ' + JSON.stringify(error)); }) ``` @@ -1559,7 +1561,7 @@ Updates the printer state. This API uses an asynchronous callback to return the | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | printerId | string | Yes| Printer ID.| -| state | [PrinterState](./js-apis-print.md#printprinterstate14) | Yes| Printer state.| +| state | [PrinterState](./js-apis-print.md#printerstate14) | Yes| Printer state.| | callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Error codes** @@ -1582,7 +1584,7 @@ let printerId : string = '1212'; let state : print.PrinterState = print.PrinterState.PRINTER_CONNECTED; print.updatePrinterState(printerId, state, (err: BusinessError, data : void) => { if (err) { - console.log('updataPrinterState failed, because : ' + JSON.stringify(err)); + console.error('updataPrinterState failed, because : ' + JSON.stringify(err)); } else { console.log('updataPrinterState success, data : ' + JSON.stringify(data)); } @@ -1605,7 +1607,7 @@ Updates the printer state. This API uses a promise to return the result. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | printerId | string | Yes| Printer ID.| -| state | [PrinterState](./js-apis-print.md#printprinterstate14) | Yes| Printer state.| +| state | [PrinterState](./js-apis-print.md#printerstate14) | Yes| Printer state.| **Return value** | **Type**| **Description**| @@ -1633,7 +1635,7 @@ let state : print.PrinterState = print.PrinterState.PRINTER_CONNECTED; print.updatePrinterState(printerId, state).then((data : void) => { console.log('update printer state data : ' + JSON.stringify(data)); }).catch((error: BusinessError) => { - console.log('update printer state error : ' + JSON.stringify(error)); + console.error('update printer state error : ' + JSON.stringify(error)); }) ``` @@ -1653,8 +1655,8 @@ Updates the print job state. This API uses an asynchronous callback to return th | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | jobId | string | Yes| ID of the print job.| -| state | [PrintJobState](./js-apis-print.md#printprintjobstate14) | Yes| State of the print job.| -| subState | [PrintJobSubState](./js-apis-print.md#printprintjobsubstate14) | Yes| Substate of the print job.| +| state | [PrintJobState](./js-apis-print.md#printjobstate14) | Yes| State of the print job.| +| subState | [PrintJobSubState](./js-apis-print.md#printjobsubstate14) | Yes| Substate of the print job.| | callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Error codes** @@ -1678,7 +1680,7 @@ let state : print.PrintJobState = print.PrintJobState.PRINT_JOB_PREPARE; let subState : print.PrintJobSubState = print.PrintJobSubState.PRINT_JOB_COMPLETED_SUCCESS; print.updatePrintJobState(jobId, state, subState, (err: BusinessError, data : void) => { if (err) { - console.log('updataPrintJobState failed, because : ' + JSON.stringify(err)); + console.error('updataPrintJobState failed, because : ' + JSON.stringify(err)); } else { console.log('updatePrintJobState success, data : ' + JSON.stringify(data)); } @@ -1701,8 +1703,8 @@ Updates the print job state. This API uses a promise to return the result. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | jobId | string | Yes| ID of the print job.| -| state | [PrintJobState](./js-apis-print.md#printprintjobstate14) | Yes| State of the print job.| -| subState | [PrintJobSubState](./js-apis-print.md#printprintjobsubstate14) | Yes| Substate of the print job.| +| state | [PrintJobState](./js-apis-print.md#printjobstate14) | Yes| State of the print job.| +| subState | [PrintJobSubState](./js-apis-print.md#printjobsubstate14) | Yes| Substate of the print job.| **Return value** | **Type**| **Description**| @@ -1731,7 +1733,7 @@ let subState : print.PrintJobSubState = print.PrintJobSubState.PRINT_JOB_COMPLET print.updatePrintJobState(jobId, state, subState).then((data : void) => { console.log('update print job state data : ' + JSON.stringify(data)); }).catch((error: BusinessError) => { - console.log('update print job state error : ' + JSON.stringify(error)); + console.error('update print job state error : ' + JSON.stringify(error)); }) ``` @@ -1772,7 +1774,7 @@ import { BusinessError } from '@ohos.base'; let info : string = 'WIFI_INACTIVE'; print.updateExtensionInfo(info, (err: BusinessError, data : void) => { if (err) { - console.log('updateExtensionInfo failed, because : ' + JSON.stringify(err)); + console.error('updateExtensionInfo failed, because : ' + JSON.stringify(err)); } else { console.log('updateExtensionInfo success, data : ' + JSON.stringify(data)); } @@ -1821,7 +1823,7 @@ let info : string = 'WIFI_INACTIVE'; print.updateExtensionInfo(info).then((data : void) => { console.log('update print job state data : ' + JSON.stringify(data)); }).catch((error: BusinessError) => { - console.log('update print job state error : ' + JSON.stringify(error)); + console.error('update print job state error : ' + JSON.stringify(error)); }) ``` @@ -1862,7 +1864,7 @@ import { BusinessError } from '@ohos.base'; print.queryAllPrintJobs((err: BusinessError, data : void) => { if (err) { - console.log('queryAllPrintJobs failed, because : ' + JSON.stringify(err)); + console.error('queryAllPrintJobs failed, because : ' + JSON.stringify(err)); } else { console.log('queryAllPrintJobs success, data : ' + JSON.stringify(data)); } @@ -1907,7 +1909,7 @@ import { BusinessError } from '@ohos.base'; print.queryAllPrintJobs().then((data : void) => { console.log('queryAllPrintJobs success, data : ' + JSON.stringify(data)); }).catch((error: BusinessError) => { - console.log('queryAllPrintJobs failed, error : ' + JSON.stringify(error)); + console.error('queryAllPrintJobs failed, error : ' + JSON.stringify(error)); }) ``` @@ -1926,7 +1928,7 @@ Queries all print jobs. This API uses an asynchronous callback to return the res **Parameters** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<Array<[PrintJob](#printprintjob)>> | Yes| Callback used to return the result.| +| callback | AsyncCallback<Array<[PrintJob](#printjob)>> | Yes| Callback used to return the result.| **Error codes** @@ -1945,7 +1947,7 @@ import { BusinessError } from '@ohos.base'; print.queryPrintJobList((err: BusinessError, printJobs : print.PrintJob[]) => { if (err) { - console.log('queryPrintJobList failed, because : ' + JSON.stringify(err)); + console.error('queryPrintJobList failed, because : ' + JSON.stringify(err)); } else { console.log('queryPrintJobList success, data : ' + JSON.stringify(printJobs)); } @@ -1967,7 +1969,7 @@ Queries all print jobs. This API uses a promise to return the result. **Return value** | **Type**| **Description**| | -------- | -------- | -| Promise<Array<[PrintJob](#printprintjob)>> | Promise used to return the result.| +| Promise<Array<[PrintJob](#printjob)>> | Promise used to return the result.| **Error codes** @@ -1987,7 +1989,7 @@ import { BusinessError } from '@ohos.base'; print.queryPrintJobList().then((printJobs : print.PrintJob[]) => { console.log('queryPrintJobList success, data : ' + JSON.stringify(printJobs)); }).catch((error: BusinessError) => { - console.log('queryPrintJobList failed, error : ' + JSON.stringify(error)); + console.error('queryPrintJobList failed, error : ' + JSON.stringify(error)); }) ``` @@ -2007,7 +2009,7 @@ Queries a print job by ID. This API uses an asynchronous callback to return the | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | jobId | string | Yes| ID of the print job.| -| callback | AsyncCallback<[PrintJob](#printprintjob)> | Yes| Callback used to return the result.| +| callback | AsyncCallback<[PrintJob](#printjob)> | Yes| Callback used to return the result.| **Error codes** @@ -2028,7 +2030,7 @@ import { BusinessError } from '@ohos.base'; let jobId : string = '1'; print.queryPrintJobById(jobId, (err: BusinessError, printJob : print.PrintJob) => { if (err) { - console.log('queryPrintJobById failed, because : ' + JSON.stringify(err)); + console.error('queryPrintJobById failed, because : ' + JSON.stringify(err)); } else { console.log('queryPrintJobById success, data : ' + JSON.stringify(printJob)); } @@ -2055,7 +2057,7 @@ Queries a print job by ID. This API uses a promise to return the result. **Return value** | **Type**| **Description**| | -------- | -------- | -| Promise<[PrintJob](#printprintjob)> | Promise used to return the result.| +| Promise<[PrintJob](#printjob)> | Promise used to return the result.| **Error codes** @@ -2077,7 +2079,7 @@ let jobId : string = '1'; print.queryPrintJobById(jobId).then((printJob : print.PrintJob) => { console.log('queryPrintJobById data : ' + JSON.stringify(printJob)); }).catch((error: BusinessError) => { - console.log('queryPrintJobById error : ' + JSON.stringify(error)); + console.error('queryPrintJobById error : ' + JSON.stringify(error)); }) ``` @@ -2097,9 +2099,9 @@ Starts to obtain the print file. This API uses an asynchronous callback to retur | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | jobId | string | Yes| ID of the print job.| -| printAttributes | [PrintAttributes](./js-apis-print.md#printprintattributes11) | Yes| Print attributes.| +| printAttributes | [PrintAttributes](./js-apis-print.md#printattributes11) | Yes| Print attributes.| | fd | number | Yes| File descriptor.| -| onFileStateChanged | Callback<[PrintFileCreationState](./js-apis-print.md#printprintfilecreationstate11)> | Yes| Callback for updating the file state.| +| onFileStateChanged | Callback<[PrintFileCreationState](./js-apis-print.md#printfilecreationstate11)> | Yes| Callback for updating the file state.| **Error codes** @@ -2195,7 +2197,7 @@ import { BusinessError } from '@ohos.base'; let jobId : string = '1'; print.notifyPrintService(jobId, 'spooler_closed_for_started', (err: BusinessError, data : void) => { if (err) { - console.log('notifyPrintService failed, because : ' + JSON.stringify(err)); + console.error('notifyPrintService failed, because : ' + JSON.stringify(err)); } else { console.log('notifyPrintService success, data : ' + JSON.stringify(data)); } @@ -2245,15 +2247,15 @@ let jobId : string = '1'; print.notifyPrintService(jobId, 'spooler_closed_for_started').then((data : void) => { console.log('notifyPrintService data : ' + JSON.stringify(data)); }).catch((error: BusinessError) => { - console.log('notifyPrintService error : ' + JSON.stringify(error)); + console.error('notifyPrintService error : ' + JSON.stringify(error)); }) ``` -## print.getAddedPrinters12+ +## print.getPrinterInfoById12+ -getAddedPrinters(): Promise<Array<string>> +getPrinterInfoById(printerId: string): Promise<PrinterInfo> -Obtains the list of printers that have been added to the CUPS. This API uses a promise to return the result. +Obtains printer information based on the printer ID. This API uses a promise to return the result. **Required permissions**: ohos.permission.MANAGE_PRINT_JOB @@ -2261,10 +2263,15 @@ Obtains the list of printers that have been added to the CUPS. This API uses a p **System capability**: SystemCapability.Print.PrintFramework +**Parameters** +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| printerId | string | Yes| Printer ID.| + **Return value** | **Type**| **Description**| | -------- | -------- | -| Promise<Array<string>> | Promise used to return the result.| +| Promise<[PrinterInfo](#printerinfo)> | Promise used to return the result.| **Error codes** @@ -2274,6 +2281,7 @@ For details about the error codes, see [Error Codes of the Print Service](./erro | -------- | ------------------------------------------- | | 201 | the application does not have permission to call this function. | | 202 | not system application | +| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | **Example** @@ -2281,19 +2289,137 @@ For details about the error codes, see [Error Codes of the Print Service](./erro import { print } from '@kit.BasicServicesKit'; import { BusinessError } from '@ohos.base'; -print.getAddedPrinters().then((printers: string[]) => { - console.log('getAddedPrinters success ' + JSON.stringify(printers)); - // ... +let printerId : string = '1'; +print.getPrinterInfoById(printerId).then((printerInfo : print.PrinterInfo) => { + console.log('getPrinterInfoById data : ' + JSON.stringify(printerInfo)); }).catch((error: BusinessError) => { - console.log('failed to getAddedPrinters bacause ' + JSON.stringify(error)); + console.error('getPrinterInfoById error : ' + JSON.stringify(error)); }) ``` -## print.getPrinterInfoById12+ +## print.notifyPrintServiceEvent12+ -getPrinterInfoById(printerId: string): Promise<PrinterInfo> +notifyPrintServiceEvent(event: ApplicationEvent): Promise<void> -Obtains printer information based on the printer ID. This API uses a promise to return the result. +Notifies the print service of the print application events. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.MANAGE_PRINT_JOB + +**System API**: This is a system API. + +**System capability**: SystemCapability.Print.PrintFramework + +**Parameters** +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| event | [ApplicationEvent](./js-apis-print.md#applicationevent14) | Yes| Print application events.| + +**Return value** +| **Type**| **Description**| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Error Codes of the Print Service](./errorcode-print.md). + +| ID| Error Message | +| -------- | ------------------------------------------- | +| 201 | the application does not have permission to call this function. | +| 202 | not system application | +| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | + +**Example** + +```ts +import { print } from '@kit.BasicServicesKit'; +import { BusinessError } from '@ohos.base'; + +let event : print.ApplicationEvent = print.ApplicationEvent.APPLICATION_CREATED; +print.notifyPrintServiceEvent(event).then((data : void) => { + console.log('notifyPrintServiceEvent data : ' + JSON.stringify(data)); +}).catch((error: BusinessError) => { + console.error('notifyPrintServiceEvent error : ' + JSON.stringify(error)); +}) +``` + +## print.updatePrinterInformation18+ + +updatePrinterInformation(printerInformation: PrinterInformation): Promise<void> + +Updates the information of a printer in the system. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.MANAGE_PRINT_JOB + +**System API**: This is a system API. + +**System capability**: SystemCapability.Print.PrintFramework + +**Parameters** +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| printerInformation | [PrinterInformation](./js-apis-print.md#printerinformation14) | Yes| Printer whose information is to be updated.| + +**Return value** +| **Type**| **Description**| +| -------- | -------- | +| Promise<void> | Promise used to return the result of updating the printer information to the printer discovery list.| + +**Error codes** + +For details about the error codes, see [Error Codes of the Print Service](./errorcode-print.md). + +| ID| Error Message | +| -------- | ------------------------------------------- | +| 201 | the application does not have permission to call this function. | +| 202 | not system application | +| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | + +**Example** + +```ts +import { print } from '@kit.BasicServicesKit'; +import { BusinessError } from '@ohos.base'; + +let testPageSize : print.PrintPageSize = { + id : 'ISO_A4', + name : 'iso_a4_210x297mm', + width : 8268, + height : 11692 +}; + +let testCapability : print.PrinterCapabilities = { + supportedPageSizes : [testPageSize], + supportedColorModes : [print.PrintColorMode.COLOR_MODE_MONOCHROME], + supportedDuplexModes : [print.PrintDuplexMode.DUPLEX_MODE_NONE], + supportedMediaTypes : ['stationery'], + supportedQualities : [print.PrintQuality.QUALITY_NORMAL], + supportedOrientations : [print.PrintOrientationMode.ORIENTATION_MODE_PORTRAIT], + options : 'testOptions' +}; + +let printerInformation : print.PrinterInformation = { + printerId : 'testPrinterId', + printerName : 'testPrinterName', + printerStatus : 0, + description : 'testDesc', + capability : testCapability, + uri : 'testUri', + printerMake : 'testPrinterMake', + options : 'testOptions' +}; +print.updatePrinterInformation(printerInformation).then((data : void) => { + console.log('updatePrinterInformation data : ' + JSON.stringify(data)); +}).catch((error: BusinessError) => { + console.error('updatePrinterInformation error : ' + JSON.stringify(error)); +}) +``` + +## print.setPrinterPreferences18+ + +setPrinterPreferences(printerId: string, printerPreferences: PrinterPreferences): Promise<void> + +Sets the printer preferences. This API uses a promise to return the result. **Required permissions**: ohos.permission.MANAGE_PRINT_JOB @@ -2305,11 +2431,101 @@ Obtains printer information based on the printer ID. This API uses a promise to | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | printerId | string | Yes| Printer ID.| +| printerPreferences | [PrinterPreferences](./js-apis-print.md#printerpreferences18) | Yes| Printer preferences.| **Return value** | **Type**| **Description**| | -------- | -------- | -| Promise<[PrinterInfo](#printprinterinfo)> | Promise used to return the result.| +| Promise<void> | Promise used to return the result of setting printer preferences.| + +**Error codes** + +For details about the error codes, see [Error Codes of the Print Service](./errorcode-print.md). + +| ID| Error Message | +| -------- | ------------------------------------------- | +| 201 | the application does not have permission to call this function. | +| 202 | not system application | +| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | + +**Example** + +```ts +import { print } from '@kit.BasicServicesKit'; +import { BusinessError } from '@ohos.base'; + +let printerId : string = 'testPrinterId'; +let preferences : print.PrinterPreferences = { + defaultDuplexMode: print.PrintDuplexMode.DUPLEX_MODE_NONE +}; +print.setPrinterPreferences(printerId, preferences).then((data : void) => { + console.log('setPrinterPreferences data : ' + JSON.stringify(data)); +}).catch((error: BusinessError) => { + console.error('setPrinterPreferences error : ' + JSON.stringify(error)); +}) +``` + +## print.discoverUsbPrinters18+ + +discoverUsbPrinters(): Promise<Array<PrinterInformation>> + +Discovers USB printers. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.MANAGE_PRINT_JOB + +**System API**: This is a system API. + +**System capability**: SystemCapability.Print.PrintFramework + +**Return value** +| **Type**| **Description**| +| -------- | -------- | +| Promise<Array<[PrinterInformation](./js-apis-print.md#printerinformation14)>> | Promise used to return the discovered USB printer list.| + +**Error codes** + +For details about the error codes, see [Error Codes of the Print Service](./errorcode-print.md). + +| ID| Error Message | +| -------- | ------------------------------------------- | +| 201 | the application does not have permission to call this function. | +| 202 | not system application | + +**Example** + +```ts +import { print } from '@kit.BasicServicesKit'; +import { BusinessError } from '@ohos.base'; + +print.discoverUsbPrinters().then((printers : print.PrinterInformation[]) => { + console.log('discoverUsbPrinters data : ' + JSON.stringify(printers)); +}).catch((error: BusinessError) => { + console.error('discoverUsbPrinters error : ' + JSON.stringify(error)); +}) +``` + +## print.setDefaultPrinter18+ + +setDefaultPrinter(printerId: string, type: DefaultPrinterType): Promise<void> + +Sets the default printer. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.MANAGE_PRINT_JOB + +**System API**: This is a system API. + +**System capability**: SystemCapability.Print.PrintFramework + +**Parameters** +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| printerId | string | Yes| Printer ID.| +| type | [DefaultPrinterType](./js-apis-print.md#defaultprintertype18) | Yes| Default printer type.| + +**Return value** +| **Type**| **Description**| +| -------- | -------- | +| Promise<void> | Promise used to return the result of setting the default printer.| **Error codes** @@ -2328,16 +2544,17 @@ import { print } from '@kit.BasicServicesKit'; import { BusinessError } from '@ohos.base'; let printerId : string = '1'; -print.getPrinterInfoById(printerId).then((printerInfo : print.PrinterInfo) => { - console.log('getPrinterInfoById data : ' + JSON.stringify(printerInfo)); +let type : print.DefaultPrinterType = print.DefaultPrinterType.DEFAULT_PRINTER_TYPE_SET_BY_USER; +print.setDefaultPrinter(printerId, type).then((data : void) => { + console.log('setDefaultPrinter data : ' + JSON.stringify(data)); }).catch((error: BusinessError) => { - console.log('getPrinterInfoById error : ' + JSON.stringify(error)); + console.error('setDefaultPrinter error : ' + JSON.stringify(error)); }) ``` -## print.notifyPrintServiceEvent12+ +## print.notifyPrintServiceEvent18+ -notifyPrintServiceEvent(event: ApplicationEvent): Promise<void> +notifyPrintServiceEvent(event: ApplicationEvent, jobId: string): Promise<void> Notifies the print service of the print application events. This API uses a promise to return the result. @@ -2350,7 +2567,8 @@ Notifies the print service of the print application events. This API uses a prom **Parameters** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | -| event | [ApplicationEvent](./js-apis-print.md#printapplicationevent14) | Yes| Print application events.| +| event | [ApplicationEvent](./js-apis-print.md#applicationevent14) | Yes| Print application events.| +| jobId | string | Yes| ID of the print job.| **Return value** | **Type**| **Description**| @@ -2374,9 +2592,10 @@ import { print } from '@kit.BasicServicesKit'; import { BusinessError } from '@ohos.base'; let event : print.ApplicationEvent = print.ApplicationEvent.APPLICATION_CREATED; -print.notifyPrintServiceEvent(event).then((data : void) => { +let jobId : string = '1'; +print.notifyPrintServiceEvent(event, jobId).then((data : void) => { console.log('notifyPrintServiceEvent data : ' + JSON.stringify(data)); }).catch((error: BusinessError) => { - console.log('notifyPrintServiceEvent error : ' + JSON.stringify(error)); + console.error('notifyPrintServiceEvent error : ' + JSON.stringify(error)); }) ``` diff --git a/en/application-dev/reference/apis-basic-services-kit/js-apis-print.md b/en/application-dev/reference/apis-basic-services-kit/js-apis-print.md index 262fb1bcb38..e8621cf28b3 100644 --- a/en/application-dev/reference/apis-basic-services-kit/js-apis-print.md +++ b/en/application-dev/reference/apis-basic-services-kit/js-apis-print.md @@ -11,15 +11,15 @@ The **print** module provides APIs for basic print operations. import { print } from '@kit.BasicServicesKit'; ``` -## print.PrintTask +## PrintTask Implements event listeners for print tasks. -### on +### PrintTask.on on(type: 'block', callback: Callback<void>): void -Registers a listener for the print task blocking event. This API uses a callback to return the result. +Registers a listener for the print task block event. This API uses a callback to return the result. **Required permissions**: ohos.permission.PRINT @@ -45,23 +45,24 @@ For details about the error codes, see [Error Codes of the Print Service](./erro ```ts import { print } from '@kit.BasicServicesKit'; import { BusinessError } from '@ohos.base'; +import { fileUri } from '@kit.CoreFileKit'; -let file = ['file://data/print/a.png', 'file://data/print/b.png']; -print.print(file).then((printTask: print.PrintTask) => { +let filePath = '/data/storage/el2/base/haps/entry/files/test.pdf'; +print.print([fileUri.getUriFromPath(filePath)]).then((printTask: print.PrintTask) => { printTask.on('block', () => { console.log('print state is block'); }) // ... }).catch((error: BusinessError) => { - console.log('print err ' + JSON.stringify(error)); + console.error('print err ' + JSON.stringify(error)); }) ``` -### on +### PrintTask.on on(type: 'succeed', callback: Callback<void>): void -Registers a listener for the print task blocking event. This API uses a callback to return the result. +Registers a listener for the print task success event. This API uses a callback to return the result. **Required permissions**: ohos.permission.PRINT @@ -87,23 +88,24 @@ For details about the error codes, see [Error Codes of the Print Service](./erro ```ts import { print } from '@kit.BasicServicesKit'; import { BusinessError } from '@ohos.base'; +import { fileUri } from '@kit.CoreFileKit'; -let file = ['file://data/print/a.png', 'file://data/print/b.png']; -print.print(file).then((printTask: print.PrintTask) => { +let filePath = '/data/storage/el2/base/haps/entry/files/test.pdf'; +print.print([fileUri.getUriFromPath(filePath)]).then((printTask: print.PrintTask) => { printTask.on('succeed', () => { console.log('print state is succeed'); }) // ... }).catch((error: BusinessError) => { - console.log('print err ' + JSON.stringify(error)); + console.error('print err ' + JSON.stringify(error)); }) ``` -### on +### PrintTask.on on(type: 'fail', callback: Callback<void>): void -Registers a listener for the print task blocking event. This API uses a callback to return the result. +Registers a listener for the print task failure event. This API uses a callback to return the result. **Required permissions**: ohos.permission.PRINT @@ -129,23 +131,24 @@ For details about the error codes, see [Error Codes of the Print Service](./erro ```ts import { print } from '@kit.BasicServicesKit'; import { BusinessError } from '@ohos.base'; +import { fileUri } from '@kit.CoreFileKit'; -let file = ['file://data/print/a.png', 'file://data/print/b.png']; -print.print(file).then((printTask: print.PrintTask) => { +let filePath = '/data/storage/el2/base/haps/entry/files/test.pdf'; +print.print([fileUri.getUriFromPath(filePath)]).then((printTask: print.PrintTask) => { printTask.on('fail', () => { console.log('print state is fail'); }) // ... }).catch((error: BusinessError) => { - console.log('print err ' + JSON.stringify(error)); + console.error('print err ' + JSON.stringify(error)); }) ``` -### on +### PrintTask.on on(type: 'cancel', callback: Callback<void>): void -Registers a listener for the print task blocking event. This API uses a callback to return the result. +Registers a listener for the print task cancellation event. This API uses a callback to return the result. **Required permissions**: ohos.permission.PRINT @@ -154,7 +157,7 @@ Registers a listener for the print task blocking event. This API uses a callback **Parameters** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | -| type | string | Yes| Listening type.
The value is fixed at **'cancel'**,
indicating canceling of the print task.| +| type | string | Yes| Listening type.
The value is fixed at **'cancel'**,
indicating cancellation of the print task.| | callback | Callback<void> | Yes| Callback used to return the result.| **Error codes** @@ -171,23 +174,24 @@ For details about the error codes, see [Error Codes of the Print Service](./erro ```ts import { print } from '@kit.BasicServicesKit'; import { BusinessError } from '@ohos.base'; +import { fileUri } from '@kit.CoreFileKit'; -let file = ['file://data/print/a.png', 'file://data/print/b.png']; -print.print(file).then((printTask: print.PrintTask) => { +let filePath = '/data/storage/el2/base/haps/entry/files/test.pdf'; +print.print([fileUri.getUriFromPath(filePath)]).then((printTask: print.PrintTask) => { printTask.on('cancel', () => { console.log('print state is cancel'); }) // ... }).catch((error: BusinessError) => { - console.log('print err ' + JSON.stringify(error)); + console.error('print err ' + JSON.stringify(error)); }) ``` -### off +### PrintTask.off off(type: 'block', callback?: Callback<void>): void -Unregisters the listener for the print task blocking event. This API uses a callback to return the result. +Unregisters the listener for the print task block event. This API uses a callback to return the result. **Required permissions**: ohos.permission.PRINT @@ -213,23 +217,24 @@ For details about the error codes, see [Error Codes of the Print Service](./erro ```ts import { print } from '@kit.BasicServicesKit'; import { BusinessError } from '@ohos.base'; +import { fileUri } from '@kit.CoreFileKit'; -let file = ['file://data/print/a.png', 'file://data/print/b.png']; -print.print(file).then((printTask: print.PrintTask) => { +let filePath = '/data/storage/el2/base/haps/entry/files/test.pdf'; +print.print([fileUri.getUriFromPath(filePath)]).then((printTask: print.PrintTask) => { printTask.off('block', () => { console.log('unregister state block'); }) // ... }).catch((error: BusinessError) => { - console.log('print err ' + JSON.stringify(error)); + console.error('print err ' + JSON.stringify(error)); }) ``` -### off +### PrintTask.off off(type: 'succeed', callback?: Callback<void>): void -Unregisters the listener for the print task blocking event. This API uses a callback to return the result. +Unregisters the listener for the print task success event. This API uses a callback to return the result. **Required permissions**: ohos.permission.PRINT @@ -255,23 +260,24 @@ For details about the error codes, see [Error Codes of the Print Service](./erro ```ts import { print } from '@kit.BasicServicesKit'; import { BusinessError } from '@ohos.base'; +import { fileUri } from '@kit.CoreFileKit'; -let file = ['file://data/print/a.png', 'file://data/print/b.png']; -print.print(file).then((printTask: print.PrintTask) => { +let filePath = '/data/storage/el2/base/haps/entry/files/test.pdf'; +print.print([fileUri.getUriFromPath(filePath)]).then((printTask: print.PrintTask) => { printTask.off('succeed', () => { console.log('unregister state succeed'); }) // ... }).catch((error: BusinessError) => { - console.log('print err ' + JSON.stringify(error)); + console.error('print err ' + JSON.stringify(error)); }) ``` -### off +### PrintTask.off off(type: 'fail', callback?: Callback<void>): void -Unregisters the listener for the print task blocking event. This API uses a callback to return the result. +Unregisters the listener for the print task failure event. This API uses a callback to return the result. **Required permissions**: ohos.permission.PRINT @@ -297,23 +303,24 @@ For details about the error codes, see [Error Codes of the Print Service](./erro ```ts import { print } from '@kit.BasicServicesKit'; import { BusinessError } from '@ohos.base'; +import { fileUri } from '@kit.CoreFileKit'; -let file = ['file://data/print/a.png', 'file://data/print/b.png']; -print.print(file).then((printTask: print.PrintTask) => { +let filePath = '/data/storage/el2/base/haps/entry/files/test.pdf'; +print.print([fileUri.getUriFromPath(filePath)]).then((printTask: print.PrintTask) => { printTask.off('fail', () => { console.log('unregister state fail'); }) // ... }).catch((error: BusinessError) => { - console.log('print err ' + JSON.stringify(error)); + console.error('print err ' + JSON.stringify(error)); }) ``` -### off +### PrintTask.off off(type: 'cancel', callback?: Callback<void>): void -Unregisters the listener for the print task blocking event. This API uses a callback to return the result. +Unregisters the listener for the print task cancellation event. This API uses a callback to return the result. **Required permissions**: ohos.permission.PRINT @@ -322,7 +329,7 @@ Unregisters the listener for the print task blocking event. This API uses a call **Parameters** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | -| type | string | Yes| Listening type.
The value is fixed at **'cancel'**,
indicating canceling of the print task.| +| type | string | Yes| Listening type.
The value is fixed at **'cancel'**,
indicating cancellation of the print task.| | callback | Callback<void> | No| Callback used to return the result.| **Error codes** @@ -339,19 +346,20 @@ For details about the error codes, see [Error Codes of the Print Service](./erro ```ts import { print } from '@kit.BasicServicesKit'; import { BusinessError } from '@ohos.base'; +import { fileUri } from '@kit.CoreFileKit'; -let file = ['file://data/print/a.png', 'file://data/print/b.png']; -print.print(file).then((printTask: print.PrintTask) => { +let filePath = '/data/storage/el2/base/haps/entry/files/test.pdf'; +print.print([fileUri.getUriFromPath(filePath)]).then((printTask: print.PrintTask) => { printTask.off('cancel', () => { console.log('unregister state cancel'); }) // ... }).catch((error: BusinessError) => { - console.log('print err ' + JSON.stringify(error)); + console.error('print err ' + JSON.stringify(error)); }) ``` -## print.PrintDocumentAdapter11+ +## PrintDocumentAdapter11+ Provides information about the document to print. This API must be implemented by a third-party application. @@ -369,10 +377,10 @@ Sends an empty PDF file descriptor to a third-party application. The third-party | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | jobId | string | Yes| ID of the print job.| -| oldAttrs | [PrintAttributes](#printprintattributes11) | Yes| Old print attributes.| -| newAttrs | [PrintAttributes](#printprintattributes11) | Yes| New print attributes.| +| oldAttrs | [PrintAttributes](#printattributes11) | Yes| Old print attributes.| +| newAttrs | [PrintAttributes](#printattributes11) | Yes| New print attributes.| | fd | number | Yes| PDF file descriptor sent to the API caller.| -| writeResultCallback | (jobId: string, writeResult: [PrintFileCreationState](#printprintfilecreationstate11)) | Yes| Callback used to print the updated file.| +| writeResultCallback | (jobId: string, writeResult: [PrintFileCreationState](#printfilecreationstate11)) => void | Yes| Callback used to print the updated file.| **Error codes** @@ -424,7 +432,7 @@ Registers a listener for print job state changes. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | jobId | string | Yes| ID of the print job.| -| state | [PrintDocumentAdapterState](#printprintdocumentadapterstate11) | Yes| New state of the print job.| +| state | [PrintDocumentAdapterState](#printdocumentadapterstate11) | Yes| New state of the print job.| **Error codes** @@ -475,8 +483,8 @@ Prints files. This API uses an asynchronous callback to return the result. **Parameters** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | -| files | Array<string> | Yes| List of files to print. Images (in .jpg, .png, .gif, .bmp, or .webp format) and PDF files are supported. Before a system application passes in the URI, it needs to call **uriPermissionManager.grantUriPermission()** to authorize the print application. This API is a system API. [print](#printprint11-2) is recommended for third-party application.| -| callback | AsyncCallback<[PrintTask](#printprinttask)> | Yes| Callback used to return the result.| +| files | Array<string> | Yes| List of files to print. Images (in .jpg, .png, .gif, .bmp, or .webp format) and PDF files are supported. You should save the files to the application sandbox, obtain the sandbox URI through **fileUri.getUriFromPath**, and then pass this URI as a parameter to this API.| +| callback | AsyncCallback<[PrintTask](#printtask)> | Yes| Callback used to return the result.| **Error codes** @@ -492,14 +500,13 @@ For details about the error codes, see [Error Codes of the Print Service](./erro ```ts import { print } from '@kit.BasicServicesKit'; import { BusinessError } from '@ohos.base'; +import { fileUri } from '@kit.CoreFileKit'; // Pass in the URIs of the files. -let files = ['file://data/print/a.png', 'file://data/print/b.png']; -// Alternatively, pass in the fd. -//let files = ['fd://1', 'fd://2']; -print.print(files, (err: BusinessError, printTask: print.PrintTask) => { +let filePath = '/data/storage/el2/base/haps/entry/files/test.pdf'; +print.print([fileUri.getUriFromPath(filePath)], (err: BusinessError, printTask: print.PrintTask) => { if (err) { - console.log('print err ' + JSON.stringify(err)); + console.error('print err ' + JSON.stringify(err)); } else { printTask.on('succeed', () => { console.log('print state is succeed'); @@ -522,12 +529,12 @@ Prints files. This API uses a promise to return the result. **Parameters** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | -| files | Array<string> | Yes| List of files to print. Images (in .jpg, .png, .gif, .bmp, or .webp format) and PDF files are supported. Before a system application passes in the URI, it needs to call **uriPermissionManager.grantUriPermission()** to authorize the print application. This API is a system API. [print](#printprint11-2) is recommended for third-party application.| +| files | Array<string> | Yes| List of files to print. Images (in .jpg, .png, .gif, .bmp, or .webp format) and PDF files are supported. You should save the files to the application sandbox, obtain the sandbox URI through **fileUri.getUriFromPath**, and then pass this URI as a parameter to this API.| **Return value** | **Type**| **Description**| | -------- | -------- | -| Promise<[PrintTask](#printprinttask)> | Print result.| +| Promise<[PrintTask](#printtask)> | Print result.| **Error codes** @@ -543,18 +550,17 @@ For details about the error codes, see [Error Codes of the Print Service](./erro ```ts import { print } from '@kit.BasicServicesKit'; import { BusinessError } from '@ohos.base'; +import { fileUri } from '@kit.CoreFileKit'; // Pass in the URIs of the files. -let files = ['file://data/print/a.png', 'file://data/print/b.png']; -// Alternatively, pass in the fd. -//let files = ['fd://1', 'fd://2']; -print.print(files).then((printTask: print.PrintTask) => { +let filePath = '/data/storage/el2/base/haps/entry/files/test.pdf'; +print.print([fileUri.getUriFromPath(filePath)]).then((printTask: print.PrintTask) => { printTask.on('succeed', () => { console.log('print state is succeed'); }) // ... }).catch((error: BusinessError) => { - console.log('print err ' + JSON.stringify(error)); + console.error('print err ' + JSON.stringify(error)); }) ``` @@ -571,9 +577,9 @@ Prints files. This API uses an asynchronous callback to return the result. **Parameters** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | -| files | Array<string> | Yes| List of files to print. Images (in .jpg, .png, .gif, .bmp, or .webp format) and PDF files are supported. Before a system application passes in the URI, it needs to call **uriPermissionManager.grantUriPermission()** to authorize the print application. This API is a system API. [print](#printprint11-2) is recommended for third-party application.| +| files | Array<string> | Yes| List of files to print. Images (in .jpg, .png, .gif, .bmp, or .webp format) and PDF files are supported. You should save the files to the application sandbox, obtain the sandbox URI through **fileUri.getUriFromPath**, and then pass this URI as a parameter to this API.| | context | Context | Yes| UIAbilityContext used to start the system print UI.| -| callback | AsyncCallback<[PrintTask](#printprinttask)> | Yes| Callback used to return the result.| +| callback | AsyncCallback<[PrintTask](#printtask)> | Yes| Callback used to return the result.| **Error codes** @@ -589,22 +595,36 @@ For details about the error codes, see [Error Codes of the Print Service](./erro ```ts import { print } from '@kit.BasicServicesKit'; import { BusinessError } from '@ohos.base'; - -// Pass in the URIs of the files. -let files = ['file://data/print/a.png', 'file://data/print/b.png']; -// Alternatively, pass in the fd. -//let files = ['fd://1', 'fd://2']; -let context = getContext(this); -print.print(files, context, (err: BusinessError, printTask: print.PrintTask) => { - if (err) { - console.log('print err ' + JSON.stringify(err)); - } else { - printTask.on('succeed', () => { - console.log('print state is succeed'); - }) - // ... +import { fileUri } from '@kit.CoreFileKit'; + +@Entry +@Component +struct Index { + build() { + Scroll() { + Column({ space: 10 }) { + Button("Print").width('90%').height(50).onClick(() => { + let filePath = '/data/storage/el2/base/haps/entry/files/test.pdf'; + let context = this.getUIContext().getHostContext(); + print.print([fileUri.getUriFromPath(filePath)], context, (err: BusinessError, printTask: print.PrintTask) => { + if (err) { + console.error('print err ' + JSON.stringify(err)); + } else { + printTask.on('succeed', () => { + console.log('print state is succeed'); + }) + // ... + } + }) + }) + } + .justifyContent(FlexAlign.Center) + .constraintSize({ minHeight: '100%' }) + .width('100%') + } + .height('100%') } -}) +} ``` ## print.print11+ @@ -620,13 +640,13 @@ Prints files. This API uses a promise to return the result. **Parameters** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | -| files | Array<string> | Yes| List of files to print. Images (in .jpg, .png, .gif, .bmp, or .webp format) and PDF files are supported. Before a system application passes in the URI, it needs to call **uriPermissionManager.grantUriPermission()** to authorize the print application. This API is a system API. [print](#printprint11-2) is recommended for third-party application.| +| files | Array<string> | Yes| List of files to print. Images (in .jpg, .png, .gif, .bmp, or .webp format) and PDF files are supported. You should save the files to the application sandbox, obtain the sandbox URI through **fileUri.getUriFromPath**, and then pass this URI as a parameter to this API.| | context | Context | Yes| UIAbilityContext used to start the system print UI.| **Return value** | **Type**| **Description**| | -------- | -------- | -| Promise<[PrintTask](#printprinttask)> | Print result.| +| Promise<[PrintTask](#printtask)> | Print result.| **Error codes** @@ -642,20 +662,34 @@ For details about the error codes, see [Error Codes of the Print Service](./erro ```ts import { print } from '@kit.BasicServicesKit'; import { BusinessError } from '@ohos.base'; - -// Pass in the URIs of the files. -let files = ['file://data/print/a.png', 'file://data/print/b.png']; -// Alternatively, pass in the fd. -//let files = ['fd://1', 'fd://2']; -let context = getContext(this); -print.print(files, context).then((printTask: print.PrintTask) => { - printTask.on('succeed', () => { - console.log('print state is succeed'); - }) - // ... -}).catch((error: BusinessError) => { - console.log('print err ' + JSON.stringify(error)); -}) +import { fileUri } from '@kit.CoreFileKit'; + +@Entry +@Component +struct Index { + build() { + Scroll() { + Column({ space: 10 }) { + Button("Print").width('90%').height(50).onClick(() => { + let filePath = '/data/storage/el2/base/haps/entry/files/test.pdf'; + let context = this.getUIContext().getHostContext(); + print.print([fileUri.getUriFromPath(filePath)], context).then((printTask: print.PrintTask) => { + printTask.on('succeed', () => { + console.log('print state is succeed'); + }) + // ... + }).catch((error: BusinessError) => { + console.error('print err ' + JSON.stringify(error)); + }) + }) + } + .justifyContent(FlexAlign.Center) + .constraintSize({ minHeight: '100%' }) + .width('100%') + } + .height('100%') + } +} ``` ## print.print11+ @@ -672,14 +706,14 @@ Prints a file. This API uses a promise to return the result. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | jobName | string | Yes| Name of the file to print, for example, **test.pdf**. The printer uses the [onStartLayoutWrite](#onstartlayoutwrite) API to send the **fd** of the empty PDF file to the API caller. The API caller uses the new print attributes to update the file to print.| -| printAdapter | [PrintDocumentAdapter](#printprintdocumentadapter11) | Yes| [PrintDocumentAdapter](#printprintdocumentadapter11) API instance implemented by a third-party application.| -| printAttributes | [PrintAttributes](#printprintattributes11) | Yes| Print attributes.| +| printAdapter | [PrintDocumentAdapter](#printdocumentadapter11) | Yes| [PrintDocumentAdapter](#printdocumentadapter11) API instance implemented by a third-party application.| +| printAttributes | [PrintAttributes](#printattributes11) | Yes| Print attributes.| | context | Context | Yes| UIAbilityContext used to start the system print UI.| **Return value** | **Type**| **Description**| | -------- | -------- | -| Promise<[PrintTask](#printprinttask)> | Print result.| +| Promise<[PrintTask](#printtask)> | Print result.| **Error codes** @@ -696,33 +730,49 @@ For details about the error codes, see [Error Codes of the Print Service](./erro import { print } from '@kit.BasicServicesKit'; import { BusinessError } from '@ohos.base'; -let jobName : string = "jobName"; -let printAdapter : print.PrintDocumentAdapter | null = null; -let printAttributes : print.PrintAttributes = { - copyNumber: 1, - pageRange: { - startPage: 0, - endPage: 5, - pages: [] - }, - pageSize: print.PrintPageType.PAGE_ISO_A3, - directionMode: print.PrintDirectionMode.DIRECTION_MODE_AUTO, - colorMode: print.PrintColorMode.COLOR_MODE_MONOCHROME, - duplexMode: print.PrintDuplexMode.DUPLEX_MODE_NONE +@Entry +@Component +struct Index { + build() { + Scroll() { + Column({ space: 10 }) { + Button("Print").width('90%').height(50).onClick(() => { + let jobName : string = "jobName"; + let printAdapter : print.PrintDocumentAdapter | null = null; + let printAttributes : print.PrintAttributes = { + copyNumber: 1, + pageRange: { + startPage: 0, + endPage: 5, + pages: [] + }, + pageSize: print.PrintPageType.PAGE_ISO_A3, + directionMode: print.PrintDirectionMode.DIRECTION_MODE_AUTO, + colorMode: print.PrintColorMode.COLOR_MODE_MONOCHROME, + duplexMode: print.PrintDuplexMode.DUPLEX_MODE_NONE + } + let context = this.getUIContext().getHostContext(); + + print.print(jobName, printAdapter, printAttributes, context).then((printTask: print.PrintTask) => { + printTask.on('succeed', () => { + console.log('print state is succeed'); + }) + // ... + }).catch((error: BusinessError) => { + console.error('print err ' + JSON.stringify(error)); + }) + }) + } + .justifyContent(FlexAlign.Center) + .constraintSize({ minHeight: '100%' }) + .width('100%') + } + .height('100%') + } } -let context = getContext(); - -print.print(jobName, printAdapter, printAttributes, context).then((printTask: print.PrintTask) => { - printTask.on('succeed', () => { - console.log('print state is succeed'); - }) - // ... -}).catch((error: BusinessError) => { - console.log('print err ' + JSON.stringify(error)); -}) ``` -## print.PrintAttributes11+ +## PrintAttributes11+ Defines the print attributes. @@ -731,14 +781,14 @@ Defines the print attributes. **Attributes** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | -| copyNumber | number | No| Number of printed file copies.| -| pageRange | [PrintPageRange](#printprintpagerange11) | No| Page range of the file to print.| -| pageSize | [PrintPageSize](#printprintpagesize11) \| [PrintPageType](#printprintpagetype11) | No| Page size of the file to print.| -| directionMode | [PrintDirectionMode](#printprintdirectionmode11) | No| Print direction mode.| -| colorMode | [PrintColorMode](#printprintcolormode11) | No| Color mode of the files to print.| -| duplexMode | [PrintDuplexMode](#printprintduplexmode11) | No| Duplex mode of the files to print.| +| copyNumber | number | No| Number of printed file copies. The default value is **1**.| +| pageRange | [PrintPageRange](#printpagerange11) | No| Page range of the file to print.| +| pageSize | [PrintPageSize](#printpagesize11) \| [PrintPageType](#printpagetype11) | No| Page size of the file to print.| +| directionMode | [PrintDirectionMode](#printdirectionmode11) | No| Print direction mode.| +| colorMode | [PrintColorMode](#printcolormode11) | No| Color mode of the files to print.| +| duplexMode | [PrintDuplexMode](#printduplexmode11) | No| Duplex mode of the files to print.| -## print.PrintPageRange11+ +## PrintPageRange11+ Defines the print range. @@ -747,12 +797,12 @@ Defines the print range. **Attributes** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | -| startPage | number | No| Start page.| -| endPage | number | No| End page.| -| pages | Array<number> | No| Page range set of the file to print.| +| startPage | number | No| Start page. The default value is **1**.| +| endPage | number | No| End page. The default value is the maximum number of pages of the file to be printed.| +| pages | Array<number> | No| Page range set of the file to print. The default value is empty.| -## print.PrintPageSize11+ +## PrintPageSize11+ Defines the size of the printed page. @@ -768,7 +818,7 @@ Defines the size of the printed page. -## print.PrintDirectionMode11+ +## PrintDirectionMode11+ Enumerates the print direction modes. @@ -780,7 +830,7 @@ Enumerates the print direction modes. | DIRECTION_MODE_PORTRAIT | 1 | Portrait mode.| | DIRECTION_MODE_LANDSCAPE | 2 | Landscape mode.| -## print.PrintColorMode11+ +## PrintColorMode11+ Enumerates the color modes. @@ -791,7 +841,7 @@ Enumerates the color modes. | COLOR_MODE_MONOCHROME | 0 | Black and white.| | COLOR_MODE_COLOR | 1 | Color.| -## print.PrintDuplexMode11+ +## PrintDuplexMode11+ Enumerates the duplex modes. @@ -803,7 +853,7 @@ Enumerates the duplex modes. | DUPLEX_MODE_LONG_EDGE | 1 | Duplex (double-sided) with flipping on long edge.| | DUPLEX_MODE_SHORT_EDGE | 2 | Duplex (double-sided) with flipping on short edge.| -## print.PrintPageType11+ +## PrintPageType11+ Enumerates the print page types. @@ -824,7 +874,7 @@ Enumerates the print page types. | PAGE_INT_DL_ENVELOPE | 10 | International envelope DL.| | PAGE_B_TABLOID | 11 | B Tabloid.| -## print.PrintDocumentAdapterState11+ +## PrintDocumentAdapterState11+ Enumerates the print job states. @@ -838,7 +888,7 @@ Enumerates the print job states. | PRINT_TASK_CANCEL | 3 | The print job is canceled.| | PRINT_TASK_BLOCK | 4 | The print job is blocked.| -## print.PrintFileCreationState11+ +## PrintFileCreationState11+ Enumerates the print file creation status. @@ -850,7 +900,7 @@ Enumerates the print file creation status. | PRINT_FILE_CREATION_FAILED | 1 | The print file fails to be created.| | PRINT_FILE_CREATED_UNRENDERED | 2 | The print file is successfully created but not rendered.| -## print.PrinterState14+ +## PrinterState14+ Enumerates the printer states. @@ -865,7 +915,7 @@ Enumerates the printer states. | PRINTER_DISCONNECTED | 4 | The printer is disconnected.| | PRINTER_RUNNING | 5 | The printer is running.| -## print.PrintJobState14+ +## PrintJobState14+ Enumerates the print job states. @@ -879,7 +929,7 @@ Enumerates the print job states. | PRINT_JOB_BLOCKED | 3 | The print job is blocked.| | PRINT_JOB_COMPLETED | 4 | The print job is complete.| -## print.PrintJobSubState14+ +## PrintJobSubState14+ Enumerates the print job substates. @@ -914,9 +964,10 @@ Enumerates the print job substates. | PRINT_JOB_BLOCK_SLOW_FILE_CONVERSION | 25 | The file conversion is slow.| | PRINT_JOB_RUNNING_UPLOADING_FILES | 26 | The file is uploading.| | PRINT_JOB_RUNNING_CONVERTING_FILES | 27 | The file is converting.| +| PRINT_JOB_BLOCK_FILE_UPLOADING_ERROR18+ | 30 | The file fails to be uploaded.| | PRINT_JOB_BLOCK_UNKNOWN | 99 | There is an unknown error with the printer.| -## print.PrintErrorCode14+ +## PrintErrorCode14+ Enumerates the print error codes. @@ -934,8 +985,9 @@ Enumerates the print error codes. | E_PRINT_INVALID_PRINTER | 13100005 | Invalid printer.| | E_PRINT_INVALID_PRINT_JOB | 13100006 | Invalid print job.| | E_PRINT_FILE_IO | 13100007 | Incorrect file input/output.| +| E_PRINT_TOO_MANY_FILES18+ | 13100010 | Excessive files. Maximum number: 99.| -## print.ApplicationEvent14+ +## ApplicationEvent14+ Enumerates print application events. @@ -960,7 +1012,7 @@ Adds a printer to the printer discovery list. This API uses a promise to return **Parameters** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | -| printerInformation | [PrinterInformation](#printprinterinformation14) | Yes| The added printer.| +| printerInformation | [PrinterInformation](#printerinformation14) | Yes| The added printer.| **Return value** | **Type**| **Description**| @@ -994,7 +1046,7 @@ let printerInformation : print.PrinterInformation = { print.addPrinterToDiscovery(printerInformation).then((data : void) => { console.log('addPrinterToDiscovery data : ' + JSON.stringify(data)); }).catch((error: BusinessError) => { - console.log('addPrinterToDiscovery error : ' + JSON.stringify(error)); + console.error('addPrinterToDiscovery error : ' + JSON.stringify(error)); }) ``` @@ -1011,7 +1063,7 @@ Updates the printer capabilities to the printer discovery list. This API uses a **Parameters** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | -| printerInformation | [PrinterInformation](#printprinterinformation14) | Yes| Printer whose capability is to be updated.| +| printerInformation | [PrinterInformation](#printerinformation14) | Yes| Printer whose capability is to be updated.| **Return value** | **Type**| **Description**| @@ -1063,7 +1115,7 @@ let printerInformation : print.PrinterInformation = { print.updatePrinterInDiscovery(printerInformation).then((data : void) => { console.log('updatePrinterInDiscovery data : ' + JSON.stringify(data)); }).catch((error: BusinessError) => { - console.log('updatePrinterInDiscovery error : ' + JSON.stringify(error)); + console.error('updatePrinterInDiscovery error : ' + JSON.stringify(error)); }) ``` @@ -1106,7 +1158,7 @@ let printerId : string = 'testPrinterId'; print.removePrinterFromDiscovery(printerId).then((data : void) => { console.log('removePrinterFromDiscovery data : ' + JSON.stringify(data)); }).catch((error: BusinessError) => { - console.log('removePrinterFromDiscovery error : ' + JSON.stringify(error)); + console.error('removePrinterFromDiscovery error : ' + JSON.stringify(error)); }) ``` @@ -1128,7 +1180,7 @@ Obtains printer information based on the printer ID. This API uses a promise to **Return value** | **Type**| **Description**| | -------- | -------- | -| Promise<[PrinterInformation](#printprinterinformation14)> | Printer information obtained based on the printer ID.| +| Promise<[PrinterInformation](#printerinformation14)> | Printer information obtained based on the printer ID.| **Error codes** @@ -1149,11 +1201,11 @@ let printerId : string = 'testPrinterId'; print.getPrinterInformationById(printerId).then((printerInformation : print.PrinterInformation) => { console.log('getPrinterInformationById data : ' + JSON.stringify(printerInformation)); }).catch((error: BusinessError) => { - console.log('getPrinterInformationById error : ' + JSON.stringify(error)); + console.error('getPrinterInformationById error : ' + JSON.stringify(error)); }) ``` -## print.PrinterInformation14+ +## PrinterInformation14+ Defines the printer information. @@ -1164,14 +1216,16 @@ Defines the printer information. | -------- | -------- | -------- | -------- | | printerId | string | Yes| Printer ID.| | printerName | string | Yes| Printer name.| -| printerStatus | [PrinterStatus](#printprinterstatus14) | Yes| Printer state.| +| printerStatus | [PrinterStatus](#printerstatus14) | Yes| Printer state.| | description | string | No| Printer description.| -| capability | [PrinterCapabilities](#printprintercapabilities14) | No| Printer capabilities.| +| capability | [PrinterCapabilities](#printercapabilities14) | No| Printer capabilities.| | uri | string | No| Printer URI.| | printerMake | string | No| Printer model.| +| preferences18+ | [PrinterPreferences](#printerpreferences18) | No| Printer preferences.| +| alias18+ | string | No| Printer alias.| | options | string | No| Printer details.| -## print.PrinterCapabilities14+ +## PrinterCapabilities14+ Defines the printer capabilities. @@ -1180,15 +1234,15 @@ Defines the printer capabilities. **Attributes** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | -| supportedPageSizes | Array<[PrintPageSize](#printprintpagesize11)> | Yes| List of paper sizes supported by the printer.| -| supportedColorModes | Array<[PrintColorMode](#printprintcolormode11)> | Yes| List of color modes supported by the printer.| -| supportedDuplexModes | Array<[PrintDuplexMode](#printprintduplexmode11)> | Yes| List of single- and double-sided modes supported by the printer.| +| supportedPageSizes | Array<[PrintPageSize](#printpagesize11)> | Yes| List of paper sizes supported by the printer.| +| supportedColorModes | Array<[PrintColorMode](#printcolormode11)> | Yes| List of color modes supported by the printer.| +| supportedDuplexModes | Array<[PrintDuplexMode](#printduplexmode11)> | Yes| List of single- and double-sided modes supported by the printer.| | supportedMediaTypes | Array<string> | No| List of paper types supported by the printer.| -| supportedQualities | Array<[PrintQuality](#printprintquality14)> | No| List of print quality supported by the printer.| -| supportedOrientations | Array<[PrintOrientationMode](#printprintorientationmode14)> | No| List of print directions supported by the printer.| +| supportedQualities | Array<[PrintQuality](#printquality14)> | No| List of print quality supported by the printer.| +| supportedOrientations | Array<[PrintOrientationMode](#printorientationmode14)> | No| List of print directions supported by the printer.| | options | string | No| Printer capability details.| -## print.PrintQuality14+ +## PrintQuality14+ Enumerates the print qualities. @@ -1200,7 +1254,7 @@ Enumerates the print qualities. | QUALITY_NORMAL | 4 | Standard| | QUALITY_HIGH | 5 | High| -## print.PrintOrientationMode14+ +## PrintOrientationMode14+ Enumerates the print directions. @@ -1214,7 +1268,7 @@ Enumerates the print directions. | ORIENTATION_MODE_REVERSE_PORTRAIT | 3 | Reverse portrait mode.| | ORIENTATION_MODE_NONE | 4 | Adaptive mode.| -## print.PrinterStatus14+ +## PrinterStatus14+ Enumerates the printer states. @@ -1225,3 +1279,174 @@ Enumerates the printer states. | PRINTER_IDLE | 0 | The printer is idle.| | PRINTER_BUSY | 1 | The printer is busy.| | PRINTER_UNAVAILABLE | 2 | The printer is unavailable.| + +## PrinterPreferences18+ + +Defines the printer preferences. + +**System capability**: SystemCapability.Print.PrintFramework + +**Attributes** +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| defaultDuplexMode | [PrintDuplexMode](#printduplexmode11) | No| Default duplex mode.| +| defaultPrintQuality | [PrintQuality](#printquality14) | No| Default print quality.| +| defaultMediaType | string | No| Default paper type.| +| defaultPageSizeId | string | No| ID of the default paper size. The value can be a standard paper size defined by the International Organization for Standardization (ISO), for example, ISO_A4, or a non-standard paper size defined in the system, for example, Custom.178 × 254 mm.| +| defaultOrientation | [PrintOrientationMode](#printorientationmode14) | No| Default print orientation.| +| borderless | boolean | No| Whether to print without margins.
- **true**: Print without margins.
- **false** (default): Print with margins.| +| options | string | No| Other fields in the printer preferences. The fields are queried from the printer or obtained from the printer driver and stored in the string in JSON format.| + +## PrinterEvent18+ + +Enumerates printer-related events. + +**System capability**: SystemCapability.Print.PrintFramework + +| **Name**| **Value**| **Description**| +| -------- | -------- | -------- | +| PRINTER_EVENT_ADDED | 0 | Printer added.| +| PRINTER_EVENT_DELETED | 1 | Printer deleted.| +| PRINTER_EVENT_STATE_CHANGED | 2 | Printer state changed.| +| PRINTER_EVENT_INFO_CHANGED | 3 | Printer information changed.| +| PRINTER_EVENT_PREFERENCE_CHANGED | 4 | Printer preferences changed.| +| PRINTER_EVENT_LAST_USED_PRINTER_CHANGED | 5 | The last used printer changed.| + +## DefaultPrinterType18+ + +Enumerates default printer types. + +**System capability**: SystemCapability.Print.PrintFramework + +| **Name**| **Value**| **Description**| +| -------- | -------- | -------- | +| DEFAULT_PRINTER_TYPE_SET_BY_USER | 0 | The printer set by the user serves as the default printer.| +| DEFAULT_PRINTER_TYPE_LAST_USED_PRINTER | 1 | The printer used last time serves as the default printer.| + +## print.getAddedPrinters18+ + +getAddedPrinters(): Promise<Array<string>> + +Obtains the list of printers added to the system. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.MANAGE_PRINT_JOB or ohos.permission.PRINT + +**System capability**: SystemCapability.Print.PrintFramework + +**Return value** +| **Type**| **Description**| +| -------- | -------- | +| Promise<Array<string>> | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Error Codes of the Print Service](./errorcode-print.md). + +| ID| Error Message | +| -------- | ------------------------------------------- | +| 201 | the application does not have permission to call this function. | + +**Example** + +```ts +import { print } from '@kit.BasicServicesKit'; +import { BusinessError } from '@ohos.base'; + +print.getAddedPrinters().then((printers: string[]) => { + console.log('getAddedPrinters success ' + JSON.stringify(printers)); + // ... +}).catch((error: BusinessError) => { + console.error('failed to getAddedPrinters because ' + JSON.stringify(error)); +}) +``` + +## PrinterChangeCallback18+ + +type PrinterChangeCallback = (event: PrinterEvent, printerInformation: PrinterInformation) => void + +Defines a callback that takes the printer event and printer information as parameters. + +**System capability**: SystemCapability.Print.PrintFramework + +**Parameters** +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| event | [PrinterEvent](#printerevent18) | Yes| Printer event.| +| printerInformation | PrinterInformation | Yes| Printer information.| + +## print.on18+ + +on(type: 'printerChange', callback: PrinterChangeCallback): void + +Registers a listener for the printer change events. + +**Required permissions**: ohos.permission.PRINT + +**System capability**: SystemCapability.Print.PrintFramework + +**Parameters** +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | 'printerChange' | Yes| Printer change event.| +| callback | [PrinterChangeCallback](#printerchangecallback18) | Yes| Callback to be invoked when the printer changes.| + +**Error codes** + +For details about the error codes, see [Error Codes of the Print Service](./errorcode-print.md). + +| ID| Error Message | +| -------- | ------------------------------------------- | +| 201 | the application does not have permission to call this function. | +| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | + +**Example** + +```ts +import { print } from '@kit.BasicServicesKit'; + +// Trigger this callback when an added printer is changed. +let onPrinterChange = + (event: print.PrinterEvent, printerInformation: print.PrinterInformation) => { + console.log('printerChange, event: ' + event + ', printerInformation: ' + JSON.stringify(printerInformation)); + }; +print.on('printerChange', onPrinterChange); +``` + +## print.off18+ + +off(type: 'printerChange', callback?: PrinterChangeCallback): void + +Unregisters the listener for printer state change events. This API uses a callback to return the result. + +**Required permissions**: ohos.permission.PRINT + +**System capability**: SystemCapability.Print.PrintFramework + +**Parameters** +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | 'printerChange' | Yes| Printer change event.| +| callback | [PrinterChangeCallback](#printerchangecallback18) | No| Callback to unregister.| + +**Error codes** + +For details about the error codes, see [Error Codes of the Print Service](./errorcode-print.md). + +| ID| Error Message | +| -------- | ------------------------------------------- | +| 201 | the application does not have permission to call this function. | +| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | + +**Example** + +```ts +import { print } from '@kit.BasicServicesKit'; + +// Trigger this callback when an added printer is changed. +let onPrinterChange = + (event: print.PrinterEvent, printerInformation: print.PrinterInformation) => { + console.log('printerChange, event: ' + event + ', printerInformation: ' + JSON.stringify(printerInformation)); + }; +print.on('printerChange', onPrinterChange); +print.off('printerChange'); +``` diff --git a/en/application-dev/reference/apis-basic-services-kit/js-apis-request-cacheDownload.md b/en/application-dev/reference/apis-basic-services-kit/js-apis-request-cacheDownload.md index 5c7dce447e5..ca0ea6c4185 100644 --- a/en/application-dev/reference/apis-basic-services-kit/js-apis-request-cacheDownload.md +++ b/en/application-dev/reference/apis-basic-services-kit/js-apis-request-cacheDownload.md @@ -18,7 +18,7 @@ The **request** module provides applications with the basic capabilities of file import { cacheDownload } from '@kit.BasicServicesKit'; ``` -## cacheDownload.CacheDownloadOptions +## CacheDownloadOptions Provides configuration options for download and cache in terms of HTTP, transfer, and task. @@ -51,7 +51,7 @@ Downloads a task from a specified URL. If the transfer is successful, the data i | Name | Type | Mandatory| Description | |---------|------------------------------------------------------------|----|--------------------------------| | url | string | Yes | URL of the target resource. Only the HTTP protocol is supported. The URL length cannot exceed 8192 bytes.| -| options | [CacheDownloadOptions](#cachedownloadcachedownloadoptions) | Yes | Cache download options for the target resource. | +| options | [CacheDownloadOptions](#cachedownloadoptions) | Yes | Cache download options for the target resource. | **Error codes** @@ -206,3 +206,4 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ console.error(`Failed to set file cache size. err: ${JSON.stringify(err)}`); } ``` + diff --git a/en/application-dev/reference/apis-basic-services-kit/js-apis-request-sys.md b/en/application-dev/reference/apis-basic-services-kit/js-apis-request-sys.md index 55386813785..7d0120f77f2 100644 --- a/en/application-dev/reference/apis-basic-services-kit/js-apis-request-sys.md +++ b/en/application-dev/reference/apis-basic-services-kit/js-apis-request-sys.md @@ -39,7 +39,19 @@ Defines the data structure of the task information for query. The fields availab | uid | string | No| UID of the application. It is only available for query by system applications.
**System API**: This is a system API.| | bundle | string | No| Bundle name of the application. It is only available for query by system applications.
**System API**: This is a system API.| +## Notification15+ +Describes the custom information of the notification bar. + +**Required permissions**: ohos.permission.REQUEST_DISABLE_NOTIFICATION + +**System capability**: SystemCapability.Request.FileTransferAgent + + + +| Name| Type| Mandatory| Description | +| -------- | -------- | -------- |-------------------------------------------------------------------------| +| disable20+ | boolean | No| Whether to disable the display of the notification bar. The value **true** means to disable the display of the notification bar; **false** means the opposite.
Default value: **false**.
**System API**: This is a system API.| ## request.agent.query10+ @@ -82,7 +94,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ console.error(`Failed to query a upload task, Code: ${err.code}, message: ${err.message}`); return; } - console.info(`Succeeded in querying the upload task. Result: ${taskInfo.uid}`); + console.info(`Succeeded in querying a upload task. result: ${taskInfo.uid}`); }); ``` @@ -129,7 +141,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ import { BusinessError } from '@kit.BasicServicesKit'; request.agent.query("123456").then((taskInfo: request.agent.TaskInfo) => { - console.info(`Succeeded in querying the upload task. Result: ${taskInfo.uid}`); + console.info(`Succeeded in querying a upload task. result: ${taskInfo.uid}`); }).catch((err: BusinessError) => { console.error(`Failed to query a upload task, Code: ${err.code}, message: ${err.message}`); }); diff --git a/en/application-dev/reference/apis-basic-services-kit/js-apis-request.md b/en/application-dev/reference/apis-basic-services-kit/js-apis-request.md index 64b995b2f8f..40b0f154568 100644 --- a/en/application-dev/reference/apis-basic-services-kit/js-apis-request.md +++ b/en/application-dev/reference/apis-basic-services-kit/js-apis-request.md @@ -1,6 +1,6 @@ # @ohos.request (Upload and Download) -The **request** module provides applications with basic upload, download, and background transmission agent capabilities. +The request module provides applications with basic upload, download, and background transmission agent capabilities. > **NOTE** > @@ -51,7 +51,7 @@ import { request } from '@kit.BasicServicesKit'; | ERROR_OFFLINE9+ | number | 9 | (Download error codes) No network connection.| | ERROR_UNSUPPORTED_NETWORK_TYPE9+ | number | 10 | (Download error codes) Network type mismatch.| | PAUSED_QUEUED_FOR_WIFI7+ | number | 0 | (Causes of download pause) Download paused and queuing for a WLAN connection, because the file size exceeds the maximum value allowed for a mobile network session.| -| PAUSED_WAITING_FOR_NETWORK7+ | number | 1 | (Causes of download pause) Download paused due to a network connection problem, for example, network disconnection.| +| PAUSED_WAITING_FOR_NETWORK7+ | number | 1 | (Causes of download pause) Download paused due to a network connection problem,
for example, network disconnection.| | PAUSED_WAITING_TO_RETRY7+ | number | 2 | (Causes of download pause) Download paused due to network error and then retried.| | PAUSED_BY_USER9+ | number | 3 | (Causes of download pause) The user paused the session.| | PAUSED_UNKNOWN7+ | number | 4 | (Causes of download pause) Download paused due to unknown reasons.| @@ -97,7 +97,7 @@ For details about the error codes, see [Upload and Download Error Codes](errorco | 13400002 | File path not supported or invalid. | **Example** - + ```ts import { BusinessError } from '@kit.BasicServicesKit'; import { common } from '@kit.AbilityKit'; @@ -157,7 +157,7 @@ For details about the error codes, see [Upload and Download Error Codes](errorco | 13400002 | File path not supported or invalid. | **Example** - + ```ts import { BusinessError } from '@kit.BasicServicesKit'; import { common } from '@kit.AbilityKit'; @@ -359,7 +359,7 @@ Subscribes to HTTP response events for the upload task.This API uses an asynchro | type | string | Yes| Type of the event to subscribe to.
- **'headerReceive'**: The HTTP request receives a response.| | callback | function | Yes| Callback used to return the response content.| -Parameters of the callback function + Parameters of the callback function | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | @@ -858,7 +858,7 @@ For details about the error codes, see [Upload and Download Error Codes](errorco | 13400003 | Task service ability error. | **Example** - + ```ts import { BusinessError } from '@kit.BasicServicesKit'; import { common } from '@kit.AbilityKit'; @@ -913,7 +913,7 @@ For details about the error codes, see [Upload and Download Error Codes](errorco | 13400003 | Task service ability error. | **Example** - + ```ts import { BusinessError } from '@kit.BasicServicesKit'; import { common } from '@kit.AbilityKit'; @@ -1076,7 +1076,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 401 | The parameters check fails. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | **Example** - + ```ts import { BusinessError } from '@kit.BasicServicesKit'; import { common } from '@kit.AbilityKit'; @@ -1132,35 +1132,35 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 401 | The parameters check fails. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | **Example** - + ```ts -import { BusinessError } from '@kit.BasicServicesKit'; -import { common } from '@kit.AbilityKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + import { common } from '@kit.AbilityKit'; -// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. -let context = this.getUIContext().getHostContext() as common.UIAbilityContext; -try { - // Replace the URL with the HTTP address of the real server. - request.downloadFile(context, { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { - let downloadTask: request.DownloadTask = data; - let progressCallback1 = (receivedSize: number, totalSize: number) => { - console.info('Download delete progress notification.' + 'receivedSize:' + receivedSize + 'totalSize:' + totalSize); - }; - let progressCallback2 = (receivedSize: number, totalSize: number) => { - console.info('Download delete progress notification.' + 'receivedSize:' + receivedSize + 'totalSize:' + totalSize); - }; - downloadTask.on('progress', progressCallback1); - downloadTask.on('progress', progressCallback2); - // Unsubscribe from progressCallback1. - downloadTask.off('progress', progressCallback1); - // Unsubscribe from all callbacks of download progress events. - downloadTask.off('progress'); - }).catch((err: BusinessError) => { - console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); - }) -} catch (err) { - console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); -} + // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + try { + // Replace the URL with the HTTP address of the real server. + request.downloadFile(context, { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { + let downloadTask: request.DownloadTask = data; + let progressCallback1 = (receivedSize: number, totalSize: number) => { + console.info('Download delete progress notification.' + 'receivedSize:' + receivedSize + 'totalSize:' + totalSize); + }; + let progressCallback2 = (receivedSize: number, totalSize: number) => { + console.info('Download delete progress notification.' + 'receivedSize:' + receivedSize + 'totalSize:' + totalSize); + }; + downloadTask.on('progress', progressCallback1); + downloadTask.on('progress', progressCallback2); + // Unsubscribe from progressCallback1. + downloadTask.off('progress', progressCallback1); + // Unsubscribe from all callbacks of download progress events. + downloadTask.off('progress'); + }).catch((err: BusinessError) => { + console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); + }) + } catch (err) { + console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); + } ``` @@ -1188,37 +1188,37 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 401 | The parameters check fails. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | **Example** - + ```ts -import { BusinessError } from '@kit.BasicServicesKit'; -import { common } from '@kit.AbilityKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + import { common } from '@kit.AbilityKit'; -// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. -let context = this.getUIContext().getHostContext() as common.UIAbilityContext; -try { - // Replace the URL with the HTTP address of the real server. - request.downloadFile(context, { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { - let downloadTask: request.DownloadTask = data; - let completeCallback = () => { - console.info('Download task completed.'); - }; - downloadTask.on('complete', completeCallback); - - let pauseCallback = () => { - console.info('Download task pause.'); - }; - downloadTask.on('pause', pauseCallback); - - let removeCallback = () => { - console.info('Download task remove.'); - }; - downloadTask.on('remove', removeCallback); - }).catch((err: BusinessError) => { - console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); - }) -} catch (err) { - console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); -} + // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + try { + // Replace the URL with the HTTP address of the real server. + request.downloadFile(context, { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { + let downloadTask: request.DownloadTask = data; + let completeCallback = () => { + console.info('Download task completed.'); + }; + downloadTask.on('complete', completeCallback); + + let pauseCallback = () => { + console.info('Download task pause.'); + }; + downloadTask.on('pause', pauseCallback); + + let removeCallback = () => { + console.info('Download task remove.'); + }; + downloadTask.on('remove', removeCallback); + }).catch((err: BusinessError) => { + console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); + }) + } catch (err) { + console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); + } ``` @@ -1246,62 +1246,61 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 401 | The parameters check fails. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | **Example** - + ```ts -import { BusinessError } from '@kit.BasicServicesKit'; -import { common } from '@kit.AbilityKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + import { common } from '@kit.AbilityKit'; -// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. -let context = this.getUIContext().getHostContext() as common.UIAbilityContext; -try { - // Replace the URL with the HTTP address of the real server. - request.downloadFile(context, { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { - let downloadTask: request.DownloadTask = data; - let completeCallback1 = () => { - console.info('Download delete complete notification.'); - }; - let completeCallback2 = () => { - console.info('Download delete complete notification.'); - }; - downloadTask.on('complete', completeCallback1); - downloadTask.on('complete', completeCallback2); - // Unsubscribe from completeCallback1. - downloadTask.off('complete', completeCallback1); - // Unsubscribe from all callbacks of the download completion events. - downloadTask.off('complete'); - - let pauseCallback1 = () => { - console.info('Download delete pause notification.'); - }; - let pauseCallback2 = () => { - console.info('Download delete pause notification.'); - }; - downloadTask.on('pause', pauseCallback1); - downloadTask.on('pause', pauseCallback2); - // Unsubscribe from pauseCallback1. - downloadTask.off('pause', pauseCallback1); - // Unsubscribe from all callbacks of the download pause events. - downloadTask.off('pause'); - - let removeCallback1 = () => { - console.info('Download delete remove notification.'); - }; - let removeCallback2 = () => { - console.info('Download delete remove notification.'); - }; - downloadTask.on('remove', removeCallback1); - downloadTask.on('remove', removeCallback2); - // Unsubscribe from removeCallback1. - downloadTask.off('remove', removeCallback1); - // Unsubscribe from all callbacks of the download removal events. - downloadTask.off('remove'); - }).catch((err: BusinessError) => { - console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); - }) -} catch (err) { - console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); -} - + // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + try { + // Replace the URL with the HTTP address of the real server. + request.downloadFile(context, { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { + let downloadTask: request.DownloadTask = data; + let completeCallback1 = () => { + console.info('Download delete complete notification.'); + }; + let completeCallback2 = () => { + console.info('Download delete complete notification.'); + }; + downloadTask.on('complete', completeCallback1); + downloadTask.on('complete', completeCallback2); + // Unsubscribe from completeCallback1. + downloadTask.off('complete', completeCallback1); + // Unsubscribe from all callbacks of the download completion events. + downloadTask.off('complete'); + + let pauseCallback1 = () => { + console.info('Download delete pause notification.'); + }; + let pauseCallback2 = () => { + console.info('Download delete pause notification.'); + }; + downloadTask.on('pause', pauseCallback1); + downloadTask.on('pause', pauseCallback2); + // Unsubscribe from pauseCallback1. + downloadTask.off('pause', pauseCallback1); + // Unsubscribe from all callbacks of the download pause events. + downloadTask.off('pause'); + + let removeCallback1 = () => { + console.info('Download delete remove notification.'); + }; + let removeCallback2 = () => { + console.info('Download delete remove notification.'); + }; + downloadTask.on('remove', removeCallback1); + downloadTask.on('remove', removeCallback2); + // Unsubscribe from removeCallback1. + downloadTask.off('remove', removeCallback1); + // Unsubscribe from all callbacks of the download removal events. + downloadTask.off('remove'); + }).catch((err: BusinessError) => { + console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); + }) + } catch (err) { + console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); + } ``` @@ -1335,27 +1334,27 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 401 | The parameters check fails. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | **Example** - + ```ts -import { BusinessError } from '@kit.BasicServicesKit'; -import { common } from '@kit.AbilityKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + import { common } from '@kit.AbilityKit'; -// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. -let context = this.getUIContext().getHostContext() as common.UIAbilityContext; -try { - // Replace the URL with the HTTP address of the real server. - request.downloadFile(context, { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { - let downloadTask: request.DownloadTask = data; - let failCallback = (err: number) => { - console.error(`Failed to download the task. Code: ${err}`); - }; - downloadTask.on('fail', failCallback); - }).catch((err: BusinessError) => { - console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); - }) -} catch (err) { - console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); -} + // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + try { + // Replace the URL with the HTTP address of the real server. + request.downloadFile(context, { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { + let downloadTask: request.DownloadTask = data; + let failCallback = (err: number) => { + console.error(`Failed to download the task. Code: ${err}`); + }; + downloadTask.on('fail', failCallback); + }).catch((err: BusinessError) => { + console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); + }) + } catch (err) { + console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); + } ``` @@ -1389,35 +1388,35 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 401 | The parameters check fails. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | **Example** - + ```ts -import { BusinessError } from '@kit.BasicServicesKit'; -import { common } from '@kit.AbilityKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + import { common } from '@kit.AbilityKit'; -// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. -let context = this.getUIContext().getHostContext() as common.UIAbilityContext; -try { - // Replace the URL with the HTTP address of the real server. - request.downloadFile(context, { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { - let downloadTask: request.DownloadTask = data; - let failCallback1 = (err: number) => { - console.error(`Failed to download the task. Code: ${err}`); - }; - let failCallback2 = (err: number) => { - console.error(`Failed to download the task. Code: ${err}`); - }; - downloadTask.on('fail', failCallback1); - downloadTask.on('fail', failCallback2); - // Unsubscribe from failCallback1. - downloadTask.off('fail', failCallback1); - // Unsubscribe from all callbacks of the download failure events. - downloadTask.off('fail'); - }).catch((err: BusinessError) => { - console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); - }) -} catch (err) { - console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); -} + // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + try { + // Replace the URL with the HTTP address of the real server. + request.downloadFile(context, { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { + let downloadTask: request.DownloadTask = data; + let failCallback1 = (err: number) => { + console.error(`Failed to download the task. Code: ${err}`); + }; + let failCallback2 = (err: number) => { + console.error(`Failed to download the task. Code: ${err}`); + }; + downloadTask.on('fail', failCallback1); + downloadTask.on('fail', failCallback2); + // Unsubscribe from failCallback1. + downloadTask.off('fail', failCallback1); + // Unsubscribe from all callbacks of the download failure events. + downloadTask.off('fail'); + }).catch((err: BusinessError) => { + console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); + }) + } catch (err) { + console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); + } ``` ### delete9+ @@ -1434,7 +1433,7 @@ Deletes this download task. This API uses a promise to return the result. | Type| Description| | -------- | -------- | -| Promise<boolean> | Promise The value **true** indicates that the operation is successful; **false** indicates the opposite.| +| Promise<boolean> | Promise used to return the result. The value **true** indicates that the operation is successful; **false** indicates the opposite.| **Error codes** @@ -1445,28 +1444,28 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 201 | The permissions check fails. | **Example** - + ```ts -import { BusinessError } from '@kit.BasicServicesKit'; -import { common } from '@kit.AbilityKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + import { common } from '@kit.AbilityKit'; -// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. -let context = this.getUIContext().getHostContext() as common.UIAbilityContext; -try { - // Replace the URL with the HTTP address of the real server. - request.downloadFile(context, { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { - let downloadTask: request.DownloadTask = data; - downloadTask.delete().then((result: boolean) => { - console.info('Succeeded in removing the download task.'); + // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + try { + // Replace the URL with the HTTP address of the real server. + request.downloadFile(context, { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { + let downloadTask: request.DownloadTask = data; + downloadTask.delete().then((result: boolean) => { + console.info('Succeeded in removing the download task.'); + }).catch((err: BusinessError) => { + console.error(`Failed to remove the download task. Code: ${err.code}, message: ${err.message}`); + }); }).catch((err: BusinessError) => { - console.error(`Failed to remove the download task. Code: ${err.code}, message: ${err.message}`); - }); - }).catch((err: BusinessError) => { - console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); - }) -} catch (err) { - console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); -} + console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); + }) + } catch (err) { + console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); + } ``` > **NOTE** @@ -1499,30 +1498,30 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 201 | The permissions check fails. | **Example** - + ```ts -import { BusinessError } from '@kit.BasicServicesKit'; -import { common } from '@kit.AbilityKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + import { common } from '@kit.AbilityKit'; -// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. -let context = this.getUIContext().getHostContext() as common.UIAbilityContext; -try { - // Replace the URL with the HTTP address of the real server. - request.downloadFile(context, { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { - let downloadTask: request.DownloadTask = data; - downloadTask.delete((err: BusinessError, result: boolean) => { - if (err) { - console.error(`Failed to remove the download task. Code: ${err.code}, message: ${err.message}`); - return; - } - console.info('Succeeded in removing the download task.'); - }); - }).catch((err: BusinessError) => { - console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); - }) -} catch (err) { - console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); -} + // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + try { + // Replace the URL with the HTTP address of the real server. + request.downloadFile(context, { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { + let downloadTask: request.DownloadTask = data; + downloadTask.delete((err: BusinessError, result: boolean) => { + if (err) { + console.error(`Failed to remove the download task. Code: ${err.code}, message: ${err.message}`); + return; + } + console.info('Succeeded in removing the download task.'); + }); + }).catch((err: BusinessError) => { + console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); + }) + } catch (err) { + console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); + } ``` > **NOTE** @@ -1555,28 +1554,28 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 201 | The permissions check fails. | **Example** - + ```ts -import { BusinessError } from '@kit.BasicServicesKit'; -import { common } from '@kit.AbilityKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + import { common } from '@kit.AbilityKit'; -// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. -let context = this.getUIContext().getHostContext() as common.UIAbilityContext; -try { - // Replace the URL with the HTTP address of the real server. - request.downloadFile(context, { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { - let downloadTask: request.DownloadTask = data; - downloadTask.getTaskInfo().then((downloadInfo: request.DownloadInfo) => { - console.info('Succeeded in querying the download task') + // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + try { + // Replace the URL with the HTTP address of the real server. + request.downloadFile(context, { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { + let downloadTask: request.DownloadTask = data; + downloadTask.getTaskInfo().then((downloadInfo: request.DownloadInfo) => { + console.info('Succeeded in querying the download task') + }).catch((err: BusinessError) => { + console.error(`Failed to query the download task. Code: ${err.code}, message: ${err.message}`) + }); }).catch((err: BusinessError) => { - console.error(`Failed to query the download task. Code: ${err.code}, message: ${err.message}`) - }); - }).catch((err: BusinessError) => { - console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); - }) -} catch (err) { - console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); -} + console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); + }) + } catch (err) { + console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); + } ``` > **NOTE** @@ -1609,30 +1608,30 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 201 | The permissions check fails. | **Example** - + ```ts -import { BusinessError } from '@kit.BasicServicesKit'; -import { common } from '@kit.AbilityKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + import { common } from '@kit.AbilityKit'; -// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. -let context = this.getUIContext().getHostContext() as common.UIAbilityContext; -try { - // Replace the URL with the HTTP address of the real server. - request.downloadFile(context, { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { - let downloadTask: request.DownloadTask = data; - downloadTask.getTaskInfo((err: BusinessError, downloadInfo: request.DownloadInfo) => { - if (err) { - console.error(`Failed to query the download mimeType. Code: ${err.code}, message: ${err.message}`); - } else { - console.info('Succeeded in querying the download mimeType'); - } - }); - }).catch((err: BusinessError) => { - console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); - }) -} catch (err) { - console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); -} + // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + try { + // Replace the URL with the HTTP address of the real server. + request.downloadFile(context, { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { + let downloadTask: request.DownloadTask = data; + downloadTask.getTaskInfo((err: BusinessError, downloadInfo: request.DownloadInfo) => { + if (err) { + console.error(`Failed to query the download mimeType. Code: ${err.code}, message: ${err.message}`); + } else { + console.info('Succeeded in querying the download mimeType'); + } + }); + }).catch((err: BusinessError) => { + console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); + }) + } catch (err) { + console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); + } ``` > **NOTE** @@ -1644,7 +1643,7 @@ try { getTaskMimeType(): Promise<string> -Obtains **MimeType** (that is, media type of resources in HTTP) of a download task. This API uses a promise to return the result. +Obtains the MIME type (that is, media type of resources in HTTP) of a download task. This API uses a promise to return the result. **Required permissions**: ohos.permission.INTERNET @@ -1654,7 +1653,7 @@ Obtains **MimeType** (that is, media type of resources in HTTP) of a download ta | Type| Description| | -------- | -------- | -| Promise<string> | Promise used to return the MimeType object.| +| Promise<string> | Promise used to return the result.| **Error codes** @@ -1665,28 +1664,28 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 201 | The permissions check fails. | **Example** - + ```ts -import { BusinessError } from '@kit.BasicServicesKit'; -import { common } from '@kit.AbilityKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + import { common } from '@kit.AbilityKit'; -// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. -let context = this.getUIContext().getHostContext() as common.UIAbilityContext; -try { - // Replace the URL with the HTTP address of the real server. - request.downloadFile(context, { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { - let downloadTask: request.DownloadTask = data; - downloadTask.getTaskMimeType().then((data: string) => { - console.info('Succeeded in querying the download MimeType'); + // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + try { + // Replace the URL with the HTTP address of the real server. + request.downloadFile(context, { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { + let downloadTask: request.DownloadTask = data; + downloadTask.getTaskMimeType().then((data: string) => { + console.info('Succeeded in querying the download MimeType'); + }).catch((err: BusinessError) => { + console.error(`Failed to query the download MimeType. Code: ${err.code}, message: ${err.message}`) + }); }).catch((err: BusinessError) => { - console.error(`Failed to query the download MimeType. Code: ${err.code}, message: ${err.message}`) - }); - }).catch((err: BusinessError) => { - console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); - }) -} catch (err) { - console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); -} + console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); + }) + } catch (err) { + console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); + } ``` > **NOTE** @@ -1698,7 +1697,7 @@ try { getTaskMimeType(callback: AsyncCallback<string>): void -Obtains **MimeType** (that is, media type of resources in HTTP) of a download task. This API uses an asynchronous callback to return the result. +Obtains the MIME type (that is, media type of resources in HTTP) of a download task. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.INTERNET @@ -1719,30 +1718,30 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 201 | The permissions check fails. | **Example** - + ```ts -import { BusinessError } from '@kit.BasicServicesKit'; -import { common } from '@kit.AbilityKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + import { common } from '@kit.AbilityKit'; -// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. -let context = this.getUIContext().getHostContext() as common.UIAbilityContext; -try { - // Replace the URL with the HTTP address of the real server. - request.downloadFile(context, { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { - let downloadTask: request.DownloadTask = data; - downloadTask.getTaskMimeType((err: BusinessError, data: string) => { - if (err) { - console.error(`Failed to query the download mimeType. Code: ${err.code}, message: ${err.message}`); - } else { - console.info('Succeeded in querying the download mimeType'); - } - }); - }).catch((err: BusinessError) => { - console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); - }) -} catch (err) { - console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); -} + // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + try { + // Replace the URL with the HTTP address of the real server. + request.downloadFile(context, { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { + let downloadTask: request.DownloadTask = data; + downloadTask.getTaskMimeType((err: BusinessError, data: string) => { + if (err) { + console.error(`Failed to query the download mimeType. Code: ${err.code}, message: ${err.message}`); + } else { + console.info('Succeeded in querying the download mimeType'); + } + }); + }).catch((err: BusinessError) => { + console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); + }) + } catch (err) { + console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); + } ``` > **NOTE** @@ -1775,28 +1774,28 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 201 | The permissions check fails. | **Example** - + ```ts -import { BusinessError } from '@kit.BasicServicesKit'; -import { common } from '@kit.AbilityKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + import { common } from '@kit.AbilityKit'; -// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. -let context = this.getUIContext().getHostContext() as common.UIAbilityContext; -try { - // Replace the URL with the HTTP address of the real server. - request.downloadFile(context, { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { - let downloadTask: request.DownloadTask = data; - downloadTask.suspend().then((result: boolean) => { - console.info('Succeeded in pausing the download task.'); + // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + try { + // Replace the URL with the HTTP address of the real server. + request.downloadFile(context, { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { + let downloadTask: request.DownloadTask = data; + downloadTask.suspend().then((result: boolean) => { + console.info('Succeeded in pausing the download task.'); + }).catch((err: BusinessError) => { + console.error(`Failed to pause the download task. Code: ${err.code}, message: ${err.message}`); + }); }).catch((err: BusinessError) => { - console.error(`Failed to pause the download task. Code: ${err.code}, message: ${err.message}`); - }); - }).catch((err: BusinessError) => { - console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); - }) -} catch (err) { - console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); -} + console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); + }) + } catch (err) { + console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); + } ``` > **NOTE** @@ -1829,30 +1828,30 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 201 | The permissions check fails. | **Example** - + ```ts -import { BusinessError } from '@kit.BasicServicesKit'; -import { common } from '@kit.AbilityKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + import { common } from '@kit.AbilityKit'; -// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. -let context = this.getUIContext().getHostContext() as common.UIAbilityContext; -try { - // Replace the URL with the HTTP address of the real server. - request.downloadFile(context, { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { - let downloadTask: request.DownloadTask = data; - downloadTask.suspend((err: BusinessError, result: boolean) => { - if (err) { - console.error(`Failed to pause the download task. Code: ${err.code}, message: ${err.message}`); - return; - } - console.info('Succeeded in pausing the download task.'); - }); - }).catch((err: BusinessError) => { - console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); - }) -} catch (err) { - console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); -} + // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + try { + // Replace the URL with the HTTP address of the real server. + request.downloadFile(context, { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { + let downloadTask: request.DownloadTask = data; + downloadTask.suspend((err: BusinessError, result: boolean) => { + if (err) { + console.error(`Failed to pause the download task. Code: ${err.code}, message: ${err.message}`); + return; + } + console.info('Succeeded in pausing the download task.'); + }); + }).catch((err: BusinessError) => { + console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); + }) + } catch (err) { + console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); + } ``` > **NOTE** @@ -1874,7 +1873,7 @@ Restores this download task. This API uses a promise to return the result. | Type| Description| | -------- | -------- | -| Promise<boolean> | Promise The value **true** indicates that the operation is successful; **false** indicates the opposite.| +| Promise<boolean> | Promise used to return the result. The value **true** indicates that the operation is successful; **false** indicates the opposite.| **Error codes** @@ -1885,28 +1884,28 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 201 | The permissions check fails. | **Example** - + ```ts -import { BusinessError } from '@kit.BasicServicesKit'; -import { common } from '@kit.AbilityKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + import { common } from '@kit.AbilityKit'; -// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. -let context = this.getUIContext().getHostContext() as common.UIAbilityContext; -try { - // Replace the URL with the HTTP address of the real server. - request.downloadFile(context, { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { - let downloadTask: request.DownloadTask = data; - downloadTask.restore().then((result: boolean) => { - console.info('Succeeded in resuming the download task.') + // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + try { + // Replace the URL with the HTTP address of the real server. + request.downloadFile(context, { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { + let downloadTask: request.DownloadTask = data; + downloadTask.restore().then((result: boolean) => { + console.info('Succeeded in resuming the download task.') + }).catch((err: BusinessError) => { + console.error(`Failed to resume the download task. Code: ${err.code}, message: ${err.message}`); + }); }).catch((err: BusinessError) => { - console.error(`Failed to resume the download task. Code: ${err.code}, message: ${err.message}`); - }); - }).catch((err: BusinessError) => { - console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); - }) -} catch (err) { - console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); -} + console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); + }) + } catch (err) { + console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); + } ``` > **NOTE** @@ -1939,30 +1938,30 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 201 | The permissions check fails. | **Example** - + ```ts -import { BusinessError } from '@kit.BasicServicesKit'; -import { common } from '@kit.AbilityKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + import { common } from '@kit.AbilityKit'; -// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. -let context = this.getUIContext().getHostContext() as common.UIAbilityContext; -try { - // Replace the URL with the HTTP address of the real server. - request.downloadFile(context, { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { - let downloadTask: request.DownloadTask = data; - downloadTask.restore((err: BusinessError, result: boolean) => { - if (err) { - console.error(`Failed to resume the download task. Code: ${err.code}, message: ${err.message}`); - return; - } - console.info('Succeeded in resuming the download task.'); - }); - }).catch((err: BusinessError) => { - console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); - }) -} catch (err) { - console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); -} + // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + try { + // Replace the URL with the HTTP address of the real server. + request.downloadFile(context, { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { + let downloadTask: request.DownloadTask = data; + downloadTask.restore((err: BusinessError, result: boolean) => { + if (err) { + console.error(`Failed to resume the download task. Code: ${err.code}, message: ${err.message}`); + return; + } + console.info('Succeeded in resuming the download task.'); + }); + }).catch((err: BusinessError) => { + console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); + }) + } catch (err) { + console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); + } ``` > **NOTE** @@ -1988,7 +1987,7 @@ Removes this download task. This API uses a promise to return the result. | Type| Description| | -------- | -------- | -| Promise<boolean> | Promise The value **true** indicates that the operation is successful; **false** indicates the opposite.| +| Promise<boolean> | Promise used to return the result. The value **true** indicates that the operation is successful; **false** indicates the opposite.| **Error codes** @@ -2134,7 +2133,7 @@ For details about the error codes, see [Upload and Download Error Codes](errorco queryMimeType(): Promise<string> -Queries the **MimeType** of this download task. This API uses a promise to return the result. +Queries the MIME type of this download task. This API uses a promise to return the result. > **NOTE** > @@ -2148,7 +2147,7 @@ Queries the **MimeType** of this download task. This API uses a promise to retur | Type| Description| | -------- | -------- | -| Promise<string> | Promise used to return the **MimeType** object.| +| Promise<string> | Promise used to return the result.| **Error codes** @@ -2173,7 +2172,7 @@ For details about the error codes, see [Upload and Download Error Codes](errorco queryMimeType(callback: AsyncCallback<string>): void -Queries the **MimeType** of this download task. This API uses an asynchronous callback to return the result. +Queries the MIME type of this download task. This API uses an asynchronous callback to return the result. > **NOTE** > @@ -2503,14 +2502,14 @@ Provides the configuration information of an upload or download task. | url | string | Yes| Resource URL. From API version 6 to 14, the value contains a maximum of 2048 characters; since API version 15, the value contains a maximum of 8192 characters. [Intercepting HTTP](../../basic-services/request/app-file-upload-download.md#adding-network-configuration) is supported.
**Atomic service API**: This API can be used in atomic services since API version 11.| | title | string | No| Task title. The value contains a maximum of 256 characters. The default value is **upload** or **download** in lowercase. Set the value to that of **action**.
**Atomic service API**: This API can be used in atomic services since API version 11.| | description | string | No| Task description. The value contains a maximum of 1024 characters. The default value is a null string.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| mode | [Mode](#mode10) | No| Task mode. The default mode is background.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| overwrite | boolean | No| Whether to overwrite an existing file during the download. The default value is **false**.
- **true**: Overwrite the existing file.
- **false**: Do not overwrite the existing file. In this case, the download fails.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| mode | [Mode](#mode10) | No| Task mode. The default mode is background. Since API version 20, the task mode for downloading files to the user file folder must be set to **request.agent.Mode.FOREGROUND**.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| overwrite | boolean | No| Whether to overwrite an existing file during the download. The default value is **false**.
- **true**: Overwrite the existing file.
- **false**: Do not overwrite the existing file. In this case, the download fails.
Since API version 20, the overwrite mode for downloading files to the user file folder must be set to **true**.
**Atomic service API**: This API can be used in atomic services since API version 11.| | method | string | No| Standard HTTP method for the task. The value can be **GET**, **POST**, or **PUT**, which is case-insensitive.
- For the upload task, use **PUT** or **POST**. The default value is **PUT**.
- For the download task, use **GET** or **POST**. The default value is **GET**.
**Atomic service API**: This API can be used in atomic services since API version 11.| | headers | object | No| HTTP headers to be included in the task.
- For the upload task, the default **Content-Type** is **multipart/form-data**.
- For the download task, the default **Content-Type** is **application/json**.
**Atomic service API**: This API can be used in atomic services since API version 11.| | data | string \| Array<[FormItem](#formitem10)> | No| - For the download task, the value is a string, typically in JSON format (an object will be converted to a JSON string); the default value is null.
- For the upload task, the value is Array<[FormItem](#formitem10)>. Since API version 15, a maximum of 100 files can be uploaded in a single task. This parameter is left empty by default.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| saveas | string | No| Path for storing downloaded files. The options are as follows:
- Relative path, which is in the cache directory of the caller, for example, **./xxx/yyy/zzz.html** or **xxx/yyy/zzz.html**.
- Internal protocol path, which can be **internal://** or its subdirectory. **internal** indicates the cache directory of the caller (that is, the input **context**), and **internal://cache** corresponds to **context.cacheDir**, for example, **internal://cache/path/to/file.txt**.
- Application sandbox path. Only the **base** directory and its subdirectories are supported, for example, **/data/storage/el1/base/path/to/file.txt**.
- File protocol path, which must match the application bundle name. Only the **base** directory and its subdirectories are supported, for example, **file://com.example.test/data/storage/el2/base/file.txt**.
The default value is the cache directory of the caller (that is, the input **context**). The default file name is the part truncated from the last slash (/) in the URL.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| saveas | string | No| Path for storing downloaded files. The options are as follows:
- Relative path, which is in the cache directory of the caller, for example, **./xxx/yyy/zzz.html** or **xxx/yyy/zzz.html**.
- Internal protocol path, which can be **internal://** or its subdirectory. **internal** indicates the cache directory of the caller (that is, the input **context**), and **internal://cache** corresponds to **context.cacheDir**, for example, **internal://cache/path/to/file.txt**.
- Application sandbox path. Only the **base** directory and its subdirectories are supported, for example, **/data/storage/el1/base/path/to/file.txt**.
- File protocol path, which can be the path of an application file or a user file. For the application file, the application bundle name must be matched and only the **base** directory and its subdirectories are supported, for example, **file://com.example.test/data/storage/el2/base/file.txt**. For the user file, its path must be the user file URI created by the caller.
Since API version 20, the default file path can be the cache path of the caller (that is, the passed context), except for [downloading network resource files to the user file](../../basic-services/request/app-file-upload-download.md#downloading-network-resource-files-to-the-user-file). The default file name is the part truncated from the last slash (/) in the URL.
**Atomic service API**: This API can be used in atomic services since API version 11.| | network | [Network](#network10) | No| Network used for the task. The default value is **ANY** (Wi-Fi or cellular).
**Atomic service API**: This API can be used in atomic services since API version 11.| -| metered | boolean | No| Whether the task is allowed on a metered connection.
- **true**: The task is allowed on a metered connection.
- **false**: The task is not allowed on a metered connection.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| metered | boolean | No| Whether the task is allowed on a metered connection.
- **true**: The task is allowed on a metered connection.
- **false** (default): The task is not allowed on a metered connection.
**Atomic service API**: This API can be used in atomic services since API version 11.| | roaming | boolean | No| Whether the task is allowed on a roaming network.
- **true** (default): The task is allowed on a roaming connection.
- **false**: The task is not allowed on a roaming connection.
**Atomic service API**: This API can be used in atomic services since API version 11.| | retry | boolean | No| Whether automatic retry is enabled for the task. This parameter is only applicable to background tasks.
- **true** (default): The automatic retry is enabled.
- **false**: The automatic retry is disabled.
**Atomic service API**: This API can be used in atomic services since API version 11.| | redirect | boolean | No| Whether redirection is allowed.
- **true** (default): The redirection is allowed.
- **false**: The redirection is not allowed.
**Atomic service API**: This API can be used in atomic services since API version 11.| @@ -2525,6 +2524,8 @@ Provides the configuration information of an upload or download task. | extras | object | No| Additional information of the task. This parameter is left empty by default.
**Atomic service API**: This API can be used in atomic services since API version 11.| | multipart15+ | boolean | No| Whether to use a single request to upload multiple files. If yes, **multipart/form-data** must be used.
- **false**: A single request is used to upload one file.
- **true**: A single request is used to upload multiple files.
The default value is **false**.| | notification15+ | [Notification](#notification15) | No| Custom settings for the notification bar. The default value is **{}**.| +| minSpeed20+ | [MinSpeed](#minspeed20) | No| Minimum speed, which is disabled by default.| +| timeout20+ | [Timeout](#timeout20) | No| Custom timeout interval. The default connection timeout interval is 60 seconds, and the default total timeout interval is 604800 seconds (one week).| ## State10+ @@ -2567,22 +2568,21 @@ Describes the data structure of the task progress. Defines the cause of a task failure. -**Atomic service API**: This API can be used in atomic services since API version 11. - **System capability**: SystemCapability.Request.FileTransferAgent | Name| Value| Description | | -------- | -------- |--------------------------------------------------------------------------------| -| OTHERS | 0xFF | Other fault. | -| DISCONNECTED | 0x00 | Network disconnection. | -| TIMEOUT | 0x10 | Timeout. | -| PROTOCOL | 0x20 | Protocol error, for example, an internal server error (500) or a data range that cannot be processed (416). | +| OTHERS | 0xFF | Other fault.
**Atomic service API**: This API can be used in atomic services since API version 11. | +| DISCONNECTED | 0x00 | Network disconnection.
**Atomic service API**: This API can be used in atomic services since API version 11. | +| TIMEOUT | 0x10 | Timeout.
**Atomic service API**: This API can be used in atomic services since API version 11. | +| PROTOCOL | 0x20 | Protocol error, for example, an internal server error (500) or a data range that cannot be processed (416).
**Atomic service API**: This API can be used in atomic services since API version 11. | | PARAM12+ | 0x30 | Parameter error, for example, incorrect URL format.
**Atomic service API**: This API can be used in atomic services since API version 12. | -| FSIO | 0x40 | File system I/O error, for example, an error that occurs during the open, search, read, write, or close operation. | +| FSIO | 0x40 | File system I/O error, for example, an error that occurs during the open, search, read, write, or close operation.
**Atomic service API**: This API can be used in atomic services since API version 11. | | DNS12+ | 0x50 | DNS resolution error.
**Atomic service API**: This API can be used in atomic services since API version 12. | | TCP12+ | 0x60 | TCP connection error.
**Atomic service API**: This API can be used in atomic services since API version 12. | | SSL12+ | 0x70 | SSL connection error, for example, a certificate error or certificate verification failure.
**Atomic service API**: This API can be used in atomic services since API version 12.| | REDIRECT12+ | 0x80 | Redirection error.
**Atomic service API**: This API can be used in atomic services since API version 12. | +| LOW_SPEED20+ | 0x90 | Low speed. | > **NOTE** > @@ -2664,6 +2664,42 @@ Describes group configuration options for download tasks. | gauge | boolean | No | Whether to send progress notifications. This parameter applies only to background tasks.
- **true**: The progress, success, and failure notifications are displayed.
- **false**: Only success and failure notifications are displayed.
The default value is **false**.| | notification15+ | [Notification](#notification15) | Yes | Custom settings for the notification bar. The default value is **{}**. | +## WaitingReason20+ + +Enumerates the reasons why a task is waiting. + +**System capability**: SystemCapability.Request.FileTransferAgent + +| Name| Value | Description | +| -------- |------|--------------------------| +| TASK_QUEUE_FULL | 0x00 | The task queue is full. | +| NETWORK_NOT_MATCH | 0x01 | The required network conditions are not met. | +| APP_BACKGROUND | 0x02 | The application has been running in the background for a long time. | +| USER_INACTIVATED | 0x03 | The user is inactive.| + +## MinSpeed20+ + +Defines the minimum speed of a task. If the task speed is lower than the preset value for a specified period of time, the task fails. The failure cause is [LOW_SPEED](#faults10). + +**System capability**: SystemCapability.Request.FileTransferAgent + +| Name | Type | Read-Only| Optional| Description | +|---------|----------|----|----|--------------------------------------------------------------| +| speed | number | No | No | Minimum speed of a task, in byte/s. If the task speed is lower than this value for a specified period of time, the task fails. If the value is set to **0**, there is no minimum speed limit.| +| duration | number | No | No | Duration during which the task speed can be lower than the minimum speed, in seconds. If the task speed is lower than the preset value for a specified period of time, the task fails. If the value is set to **0**, there is no minimum speed limit. | + +## Timeout20+ + +Defines the timeout configuration of a task. + +**System capability**: SystemCapability.Request.FileTransferAgent + +| Name | Type | Read-Only| Optional| Description | +|---------|--------|----|----|-----------------------------------------| +| connectionTimeout | number | No | Yes | Task connection timeout interval, in seconds. The connection timeout interval indicates the maximum time required for establishing a connection between the client and server. If this parameter is not set, the default value **60** is used. The minimum value is **1**.| +| totalTimeout | number | No | Yes |Total timeout interval of a task, in seconds. The total timeout interval includes the time required for establishing a connection, sending a request, and receiving a response. If this parameter is not set, the default value **604800** is used. The minimum value is 1, and the maximum value is **604800** (that is, one week). | + + ## Task10+ Implements an upload or download task. Before using this API, you must obtain a **Task** object, from a promise through [request.agent.create10+](#requestagentcreate10-1) or from a callback through [request.agent.create10+](#requestagentcreate10). @@ -2715,7 +2751,7 @@ For details about the error codes, see [Upload and Download Error Codes](errorco | 401 | Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | **Example** - + ```ts import { BusinessError } from '@kit.BasicServicesKit'; import { common } from '@kit.AbilityKit'; @@ -2799,7 +2835,7 @@ For details about the error codes, see [Upload and Download Error Codes](errorco | 401 | Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | **Example** - + ```ts import { BusinessError } from '@kit.BasicServicesKit'; import { common } from '@kit.AbilityKit'; @@ -2865,7 +2901,173 @@ Subscribes to task failure events. This API uses an asynchronous callback to ret | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| event | string | Yes| Type of the event to subscribe to.
- **'fail'**: task failure.| +| event | string | Yes| Type of the event to subscribe to.
- **'fail'**: task failure.| +| callback | function | Yes| Callback used to return the data structure of the task progress.| + +Parameters of the callback function + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| progress | [Progress](#progress10) | Yes| Task progress.| + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message| +| -------- | -------- | +| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | + +**Example** + + ```ts + import { BusinessError } from '@kit.BasicServicesKit'; + import { common } from '@kit.AbilityKit'; + + // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + let attachments: Array = [{ + name: "taskOnTest", + value: { + filename: "taskOnTest.avi", + path: "./taskOnTest.avi", + } + }]; + let config: request.agent.Config = { + action: request.agent.Action.UPLOAD, + url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. + title: 'taskOnTest', + description: 'Sample code for event listening', + mode: request.agent.Mode.FOREGROUND, + overwrite: false, + method: "PUT", + data: attachments, + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" + }; + let createOnCallback = (progress: request.agent.Progress) => { + console.info('upload task failed.'); + }; + request.agent.create(context, config).then((task: request.agent.Task) => { + task.on('failed', createOnCallback); + console.info(`Succeeded in creating a upload task. result: ${task.tid}`); + task.start(); + }).catch((err: BusinessError) => { + console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); + }); + ``` + +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + +### on('pause')11+ + +on(event: 'pause', callback: (progress: [Progress](#progress10)) => void): void + +Subscribes to task pause events. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | string | Yes| Type of the event to subscribe to.
- **'pause'**: task pause.| +| callback | function | Yes| Callback used to return the data structure of the task progress.| + +Parameters of the callback function + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| progress | [Progress](#progress10) | Yes| Task progress.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message| +| -------- | -------- | +| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | + +**Example** + + ```ts + import { BusinessError } from '@kit.BasicServicesKit'; + import { common } from '@kit.AbilityKit'; + + // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + let attachments: Array = [{ + name: "taskOnTest", + value: { + filename: "taskOnTest.avi", + path: "./taskOnTest.avi", + } + }]; + let config: request.agent.Config = { + action: request.agent.Action.UPLOAD, + url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. + title: 'taskOnTest', + description: 'Sample code for event listening', + mode: request.agent.Mode.FOREGROUND, + overwrite: false, + method: "PUT", + data: attachments, + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" + }; + let createOnCallback = (progress: request.agent.Progress) => { + console.info('upload task pause.'); + }; + request.agent.create(context, config).then((task: request.agent.Task) => { + task.on('pause', createOnCallback); + console.info(`Succeeded in creating a upload task. result: ${task.tid}`); + task.start(); + for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. + task.pause(); + }).catch((err: BusinessError) => { + console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); + }); + ``` + +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + +### on('resume')11+ + +on(event: 'resume', callback: (progress: [Progress](#progress10)) => void): void + +Subscribes to task resume events. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | string | Yes| Type of the event to subscribe to.
- **'resume'**: task resume.| | callback | function | Yes| Callback used to return the data structure of the task progress.| Parameters of the callback function @@ -2876,14 +3078,14 @@ Parameters of the callback function **Error codes** -For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). | ID| Error Message| | -------- | -------- | | 401 | Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | **Example** - + ```ts import { BusinessError } from '@kit.BasicServicesKit'; import { common } from '@kit.AbilityKit'; @@ -2920,12 +3122,16 @@ For details about the error codes, see [Upload and Download Error Codes](errorco token: "it is a secret" }; let createOnCallback = (progress: request.agent.Progress) => { - console.info('upload task failed.'); + console.info('upload task resume.'); }; request.agent.create(context, config).then((task: request.agent.Task) => { - task.on('failed', createOnCallback); + task.on('resume', createOnCallback); console.info(`Succeeded in creating a upload task. result: ${task.tid}`); task.start(); + for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. + task.pause(); + for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. + task.resume(); }).catch((err: BusinessError) => { console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); }); @@ -2935,11 +3141,11 @@ For details about the error codes, see [Upload and Download Error Codes](errorco > > For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). -### on('pause')11+ +### on('remove')11+ -on(event: 'pause', callback: (progress: [Progress](#progress10)) => void): void +on(event: 'remove', callback: (progress: [Progress](#progress10)) => void): void -Subscribes to task pause events. This API uses an asynchronous callback to return the result. +Subscribes to task removal events. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Request.FileTransferAgent @@ -2947,7 +3153,7 @@ Subscribes to task pause events. This API uses an asynchronous callback to retur | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| event | string | Yes| Type of the event to subscribe to.
- **'pause'**: task pause.| +| event | string | Yes| Type of the event to subscribe to.
- **'remove'**: task removal.| | callback | function | Yes| Callback used to return the data structure of the task progress.| Parameters of the callback function @@ -2965,7 +3171,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 401 | Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | **Example** - + ```ts import { BusinessError } from '@kit.BasicServicesKit'; import { common } from '@kit.AbilityKit'; @@ -3002,14 +3208,14 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ token: "it is a secret" }; let createOnCallback = (progress: request.agent.Progress) => { - console.info('upload task pause.'); + console.info('upload task remove.'); }; request.agent.create(context, config).then((task: request.agent.Task) => { - task.on('pause', createOnCallback); + task.on('remove', createOnCallback); console.info(`Succeeded in creating a upload task. result: ${task.tid}`); task.start(); for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. - task.pause(); + request.agent.remove(task.tid); }).catch((err: BusinessError) => { console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); }); @@ -3019,11 +3225,13 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ > > For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). -### on('resume')11+ +### on('response')12+ -on(event: 'resume', callback: (progress: [Progress](#progress10)) => void): void +on(event: 'response', callback: Callback<HttpResponse>): void -Subscribes to task resume events. This API uses an asynchronous callback to return the result. +Subscribes to task response headers. This API uses an asynchronous callback to return the result. + +**Atomic service API**: This API can be used in atomic services since API version 12. **System capability**: SystemCapability.Request.FileTransferAgent @@ -3031,14 +3239,8 @@ Subscribes to task resume events. This API uses an asynchronous callback to retu | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| event | string | Yes| Type of the event to subscribe to.
- **'resume'**: task resume.| -| callback | function | Yes| Callback used to return the data structure of the task progress.| - -Parameters of the callback function - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| progress | [Progress](#progress10) | Yes| Task progress.| +| event | string | Yes| Type of the event to subscribe to.
- **'response'**: task response.| +| callback | Callback<[HttpResponse](#httpresponse12)> | Yes| Callback used to return the data structure of the task response header.| **Error codes** @@ -3049,7 +3251,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 401 | Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | **Example** - + ```ts import { BusinessError } from '@kit.BasicServicesKit'; import { common } from '@kit.AbilityKit'; @@ -3085,17 +3287,13 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ precise: false, token: "it is a secret" }; - let createOnCallback = (progress: request.agent.Progress) => { - console.info('upload task resume.'); + let createOnCallback = (response: request.agent.HttpResponse) => { + console.info('upload task response.'); }; request.agent.create(context, config).then((task: request.agent.Task) => { - task.on('resume', createOnCallback); + task.on('response', createOnCallback); console.info(`Succeeded in creating a upload task. result: ${task.tid}`); task.start(); - for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. - task.pause(); - for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. - task.resume(); }).catch((err: BusinessError) => { console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); }); @@ -3105,47 +3303,41 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ > > For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). -### on('remove')11+ +### on('faultOccur')20+ -on(event: 'remove', callback: (progress: [Progress](#progress10)) => void): void +on(event: 'faultOccur', callback: Callback<Faults>): void -Subscribes to task removal events. This API uses an asynchronous callback to return the result. +Subscribes to task failure events. This API uses a callback to return the result. **System capability**: SystemCapability.Request.FileTransferAgent **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| event | string | Yes| Type of the event to subscribe to.
- **'remove'**: task removal.| -| callback | function | Yes| Callback used to return the data structure of the task progress.| - -Parameters of the callback function - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| progress | [Progress](#progress10) | Yes| Task progress.| +| Name| Type | Mandatory| Description | +| -------- |-------------------------------------| -------- |----------------------------| +| event | string | Yes| Type of the event to subscribe to.
- **'faultOccur'**: task failure.| +| callback | Callback<[Faults](#faults10)> | Yes| Callback used to return the failure cause of the task.| **Error codes** -For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). +For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). | ID| Error Message| | -------- | -------- | | 401 | Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | **Example** - + ```ts import { BusinessError } from '@kit.BasicServicesKit'; import { common } from '@kit.AbilityKit'; - - // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; let attachments: Array = [{ name: "taskOnTest", value: { filename: "taskOnTest.avi", + mimeType: "application/octet-stream", path: "./taskOnTest.avi", } }]; @@ -3171,15 +3363,13 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ precise: false, token: "it is a secret" }; - let createOnCallback = (progress: request.agent.Progress) => { - console.info('upload task remove.'); + let faultOnCallback = (faults: request.agent.Faults) => { + console.info('upload task failed.'); }; request.agent.create(context, config).then((task: request.agent.Task) => { - task.on('remove', createOnCallback); + task.on('faultOccur', faultOnCallback); console.info(`Succeeded in creating a upload task. result: ${task.tid}`); task.start(); - for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. - request.agent.remove(task.tid); }).catch((err: BusinessError) => { console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); }); @@ -3189,43 +3379,41 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ > > For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). -### on('response')12+ - -on(event: 'response', callback: Callback<HttpResponse>): void +### on('wait')20+ -Subscribes to task response headers. This API uses an asynchronous callback to return the result. +on(event: 'wait', callback: Callback<WaitingReason>): void -**Atomic service API**: This API can be used in atomic services since API version 12. +Subscribes to task wait events. This API uses a callback to return the result. **System capability**: SystemCapability.Request.FileTransferAgent **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| event | string | Yes| Type of the event to subscribe to.
- **'response'**: task response.| -| callback | Callback<[HttpResponse](#httpresponse12)> | Yes| Callback used to return the data structure of the task response header.| +| Name| Type | Mandatory| Description | +| -------- |---------------------------------------------------| -------- |---------------------------------| +| event | string | Yes| Type of the event to subscribe to.
- 'wait': The task is waiting.| +| callback | Callback<[WaitingReason](#waitingreason20)> | Yes| Callback used to return the waiting reason of the task. | **Error codes** -For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). +For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). | ID| Error Message| | -------- | -------- | | 401 | Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | **Example** - + ```ts import { BusinessError } from '@kit.BasicServicesKit'; import { common } from '@kit.AbilityKit'; - - // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; let attachments: Array = [{ name: "taskOnTest", value: { filename: "taskOnTest.avi", + mimeType: "application/octet-stream", path: "./taskOnTest.avi", } }]; @@ -3251,11 +3439,11 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ precise: false, token: "it is a secret" }; - let createOnCallback = (response: request.agent.HttpResponse) => { - console.info('upload task response.'); + let waitOnCallback = (reason: request.agent.WaitingReason) => { + console.info('upload task waiting.'); }; request.agent.create(context, config).then((task: request.agent.Task) => { - task.on('response', createOnCallback); + task.on('wait', waitOnCallback); console.info(`Succeeded in creating a upload task. result: ${task.tid}`); task.start(); }).catch((err: BusinessError) => { @@ -3300,7 +3488,7 @@ For details about the error codes, see [Upload and Download Error Codes](errorco | 401 | Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | **Example** - + ```ts import { BusinessError } from '@kit.BasicServicesKit'; import { common } from '@kit.AbilityKit'; @@ -3393,7 +3581,7 @@ For details about the error codes, see [Upload and Download Error Codes](errorco | 401 | Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | **Example** - + ```ts import { BusinessError } from '@kit.BasicServicesKit'; import { common } from '@kit.AbilityKit'; @@ -3485,7 +3673,7 @@ For details about the error codes, see [Upload and Download Error Codes](errorco | 401 | Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | **Example** - + ```ts import { BusinessError } from '@kit.BasicServicesKit'; import { common } from '@kit.AbilityKit'; @@ -3575,7 +3763,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 401 | Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | **Example** - + ```ts import { BusinessError } from '@kit.BasicServicesKit'; import { common } from '@kit.AbilityKit'; @@ -3665,7 +3853,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 401 | Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | **Example** - + ```ts import { BusinessError } from '@kit.BasicServicesKit'; import { common } from '@kit.AbilityKit'; @@ -3755,7 +3943,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 401 | Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | **Example** - + ```ts import { BusinessError } from '@kit.BasicServicesKit'; import { common } from '@kit.AbilityKit'; @@ -3841,7 +4029,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 401 | Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | **Example** - + ```ts import { BusinessError } from '@kit.BasicServicesKit'; import { common } from '@kit.AbilityKit'; @@ -3888,7 +4076,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ task.on('response', createOffCallback2); // Unsubscribe from createOffCallback1. task.off('response', createOffCallback1); - // Unsubscribe from all callbacks of the task removal event. + // Unsubscribe from all callbacks of the task response event. task.off('response'); console.info(`Succeeded in creating a upload task. result: ${task.tid}`); task.start(); @@ -3901,6 +4089,176 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ > > For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). +### off('faultOccur')20+ + +off(event: 'faultOccur', callback?: Callback<Faults>): void + +Unsubscribes from the task failure event. + + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name| Type | Mandatory| Description | +| -------- |----------------------------| -------- |---------------------------------------| +| event | string | Yes| Type of the event to subscribe to.
- **'faultOccur'**: task failure. | +| callback | Callback<[Faults](#faults10)> | No| Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.| + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message| +| -------- | -------- | +| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | + +**Example** + + ```ts + import { BusinessError } from '@kit.BasicServicesKit'; + import { common } from '@kit.AbilityKit'; + + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + let attachments: Array = [{ + name: "taskOffTest", + value: { + filename: "taskOffTest.avi", + mimeType: "application/octet-stream", + path: "./taskOffTest.avi", + } + }]; + let config: request.agent.Config = { + action: request.agent.Action.UPLOAD, + url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. + title: 'taskOffTest', + description: 'Sample code for event listening', + mode: request.agent.Mode.FOREGROUND, + overwrite: false, + method: "PUT", + data: attachments, + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" + }; + let faultOffCallback1 = (faults: request.agent.Faults) => { + console.info('upload task failed.'); + }; + let faultOffCallback2 = (faults: request.agent.Faults) => { + console.info('upload task failed.'); + }; + request.agent.create(context, config).then((task: request.agent.Task) => { + task.on('faultOccur', faultOffCallback1); + task.on('faultOccur', faultOffCallback2); + // Unsubscribe from faultOffCallback1. + task.off('faultOccur', faultOffCallback1); + // Unsubscribe from all callbacks of the task failure event. + task.off('faultOccur'); + console.info(`Succeeded in creating a upload task. result: ${task.tid}`); + task.start(); + }).catch((err: BusinessError) => { + console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); + }); + ``` + +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + +### off('wait')20+ + +off(event: 'wait', callback?: Callback<WaitingReason>): void + +Unsubscribes from the task wait event. + + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name| Type | Mandatory| Description | +| -------- |-----------------------------------| -------- |---------------------------------------| +| event | string | Yes| Type of the event to subscribe to.
- 'wait': The task is waiting. | +| callback | Callback<[WaitingReason](#waitingreason20)> | No| Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.| + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message| +| -------- | -------- | +| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | + +**Example** + + ```ts + import { BusinessError } from '@kit.BasicServicesKit'; + import { common } from '@kit.AbilityKit'; + + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + let attachments: Array = [{ + name: "taskOffTest", + value: { + filename: "taskOffTest.avi", + mimeType: "application/octet-stream", + path: "./taskOffTest.avi", + } + }]; + let config: request.agent.Config = { + action: request.agent.Action.UPLOAD, + url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. + title: 'taskOffTest', + description: 'Sample code for event listening', + mode: request.agent.Mode.FOREGROUND, + overwrite: false, + method: "PUT", + data: attachments, + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" + }; + let waitOffCallback1 = (reason: request.agent.WaitingReason) => { + console.info('upload task waiting.'); + }; + let waitOffCallback2 = (reason: request.agent.WaitingReason) => { + console.info('upload task waiting.'); + }; + request.agent.create(context, config).then((task: request.agent.Task) => { + task.on('wait', waitOffCallback1); + task.on('wait', waitOffCallback2); + // Unsubscribe from waitOffCallback1. + task.off('wait', waitOffCallback1); + // Unsubscribe from all callbacks of the task wait event. + task.off('wait'); + console.info(`Succeeded in creating a upload task. result: ${task.tid}`); + task.start(); + }).catch((err: BusinessError) => { + console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); + }); + ``` + +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + ### start10+ start(callback: AsyncCallback<void>): void @@ -3933,7 +4291,7 @@ For details about the error codes, see [Upload and Download Error Codes](errorco | 21900007 | Operation with wrong task state. | **Example** - + ```ts import { BusinessError } from '@kit.BasicServicesKit'; import { common } from '@kit.AbilityKit'; @@ -4012,7 +4370,7 @@ For details about the error codes, see [Upload and Download Error Codes](errorco | 21900007 | Operation with wrong task state. | **Example** - + ```ts import { BusinessError } from '@kit.BasicServicesKit'; import { common } from '@kit.AbilityKit'; @@ -4081,7 +4439,7 @@ For details about the error codes, see [Upload and Download Error Codes](errorco | 21900007 | Operation with wrong task state. | **Example** - + ```ts import { BusinessError } from '@kit.BasicServicesKit'; import { common } from '@kit.AbilityKit'; @@ -4150,7 +4508,7 @@ For details about the error codes, see [Upload and Download Error Codes](errorco | 21900007 | Operation with wrong task state. | **Example** - + ```ts import { BusinessError } from '@kit.BasicServicesKit'; import { common } from '@kit.AbilityKit'; @@ -4220,7 +4578,7 @@ For details about the error codes, see [Upload and Download Error Codes](errorco | 21900007 | Operation with wrong task state. | **Example** - + ```ts import { BusinessError } from '@kit.BasicServicesKit'; import { common } from '@kit.AbilityKit'; @@ -4294,7 +4652,7 @@ For details about the error codes, see [Upload and Download Error Codes](errorco | 21900007 | Operation with wrong task state. | **Example** - + ```ts import { BusinessError } from '@kit.BasicServicesKit'; import { common } from '@kit.AbilityKit'; @@ -4365,7 +4723,7 @@ For details about the error codes, see [Upload and Download Error Codes](errorco | 21900007 | Operation with wrong task state. | **Example** - + ```ts import { BusinessError } from '@kit.BasicServicesKit'; import { common } from '@kit.AbilityKit'; @@ -4437,7 +4795,7 @@ For details about the error codes, see [Upload and Download Error Codes](errorco | 21900007 | Operation with wrong task state. | **Example** - + ```ts import { BusinessError } from '@kit.BasicServicesKit'; import { common } from '@kit.AbilityKit'; @@ -4490,9 +4848,9 @@ Sets the maximum number of bytes that can be transmitted by a task per second. T **Parameters** -| Name | Type | Mandatory| Description | -|-------|--------|----|------------------------------------| -| speed | number | Yes | Maximum number of bytes that can be transmitted by a task per second, with a minimum of 16384 bytes.| +| Name | Type | Mandatory| Description | +|-------|--------|----|------------------------------------------------------------------------------| +| speed | number | Yes | Maximum number of bytes that can be transmitted by a task per second, with a minimum of 16384 bytes. The value cannot be less than the minimum speed value specified by [MinSpeed](#minspeed20).| **Return value** @@ -4510,7 +4868,7 @@ For details about the error codes, see [Upload and Download Error Codes](errorco | 13400003 | Task service ability error. | **Example** - + ```ts import { BusinessError } from '@kit.BasicServicesKit'; import { common } from '@kit.AbilityKit'; @@ -4569,7 +4927,7 @@ For details about the error codes, see [Upload and Download Error Codes](errorco | 21900005 | Operation with wrong task mode. | **Example** - + ```ts import { BusinessError } from '@kit.BasicServicesKit'; import { common } from '@kit.AbilityKit'; @@ -4661,7 +5019,7 @@ For details about the error codes, see [Upload and Download Error Codes](errorco | 21900005 | Operation with wrong task mode. | **Example** - + ```ts import { BusinessError } from '@kit.BasicServicesKit'; import { common } from '@kit.AbilityKit'; @@ -4731,7 +5089,7 @@ Obtains task information based on the task ID. This API uses a promise to return | Type | Description | | ------------------- | ------------------------- | -| Promise<[Task](#task10)> | Promise used to return the configuration about the created task.| +| Promise<[Task](#task10)> | Promise used to return the configuration about the obtained task.| **Error codes** @@ -4744,7 +5102,7 @@ For details about the error codes, see [Upload and Download Error Codes](errorco | 21900006 | Task removed or not found. | **Example** - + ```ts import { BusinessError } from '@kit.BasicServicesKit'; import { common } from '@kit.AbilityKit'; @@ -5110,7 +5468,7 @@ Searches for task IDs based on [Filter](#filter10). This API uses a promise to r | Type | Description | | ------------------- | ------------------------- | -| Promise<Array<string>> | Promise Promise used to return task ID matches.| +| Promise<Array<string>> | Promise used to return the task IDs that meet the filter criteria.| **Error codes** diff --git a/en/application-dev/reference/apis-basic-services-kit/js-apis-resourceschedule-systemload.md b/en/application-dev/reference/apis-basic-services-kit/js-apis-resourceschedule-systemload.md index 4f01cae532a..a283fe7751a 100644 --- a/en/application-dev/reference/apis-basic-services-kit/js-apis-resourceschedule-systemload.md +++ b/en/application-dev/reference/apis-basic-services-kit/js-apis-resourceschedule-systemload.md @@ -25,7 +25,7 @@ Enables listening for system load level changes. This API uses an asynchronous c | Name | Type | Mandatory | Description | | --------- | --------------------------- | ---- | ---------------------------------------- | | type | string | Yes | Change type. This parameter has a fixed value of **systemLoadChange**. | -| callback | AsyncCallback<[SystemLoadLevel](#systemloadlevel)> | Yes | Callback used to return the system load level.| +| callback | Callback<[SystemLoadLevel](#systemloadlevel)> | Yes | Callback used to return the system load level.| **Error codes** @@ -65,14 +65,15 @@ Disables listening for system load level changes. This API uses an asynchronous | Name | Type | Mandatory | Description | | --------- | --------------------------- | ---- | ---------------------------------------- | | type | string | Yes | Change type. This parameter has a fixed value of **systemLoadChange**. | -| callback | AsyncCallback<[SystemLoadLevel](#systemloadlevel)> | No | Callback used to return the system load level.| +| callback | Callback<[SystemLoadLevel](#systemloadlevel)> | No | Callback used to return the system load level.| + **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). | ID | Error Message | | ---- | --------------------- | -| 401 | Parameter error. Possible cause: 1. Callback parameter error; 2. Register a exist callback type; 3. Parameter verification failed. | +| 401 | Parameter error. Possible cause: 1. Callback parameter error; 2. Unregister type has not register; 3. Parameter verification failed. | **Example** diff --git a/en/application-dev/reference/apis-basic-services-kit/js-apis-runninglock.md b/en/application-dev/reference/apis-basic-services-kit/js-apis-runninglock.md index 1132245d18a..5009025840d 100644 --- a/en/application-dev/reference/apis-basic-services-kit/js-apis-runninglock.md +++ b/en/application-dev/reference/apis-basic-services-kit/js-apis-runninglock.md @@ -14,7 +14,7 @@ import {runningLock} from '@kit.BasicServicesKit'; ## runningLock.isSupported9+ -isSupported(type: RunningLockType): boolean; +isSupported(type: RunningLockType): boolean Checks whether the specified type of running locks is supported. @@ -30,7 +30,7 @@ Checks whether the specified type of running locks is supported. | Type | Description | | ------- | --------------------------------------- | -| boolean | The value **true** indicates that the specified type of running locks is supported, and the value **false** indicates the opposite.| +| boolean | The value **true** indicates that the specified type of the running lock is supported, and the value **false** indicates the opposite.| **Error codes** @@ -38,7 +38,6 @@ For details about the error codes, see [RunningLock Error Codes](errorcode-runni | ID | Error Message | |---------|---------| -| 4900101 | Failed to connect to the service. | | 401 | Parameter error. Possible causes: 1.Incorrect parameter types; 2.Parameter verification failed. | **Example** @@ -66,8 +65,8 @@ Creates a **RunningLock** object. | Name | Type | Mandatory| Description | | -------- | ------------------------------------------ | ---- | ------------------------------------------------------------ | -| name | string | Yes | Name of the running lock. The value must be a string. | -| type | [RunningLockType](#runninglocktype) | Yes | Type of the running lock. The value must be an enum. | +| name | string | Yes | Name of the **RunningLock** object. The value must be a string. | +| type | [RunningLockType](#runninglocktype) | Yes | Type of the **RunningLock** object. The value must be an enum. | | callback | AsyncCallback<[RunningLock](#runninglock)> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and data is the created **RunningLock** object. Otherwise, **err** is an error object. **AsyncCallback** has encapsulated an API of the **RunningLock** class.| **Error codes** @@ -106,8 +105,8 @@ Creates a **RunningLock** object. | Name| Type | Mandatory| Description | | ------ | ----------------------------------- | ---- | ------------------ | -| name | string | Yes | Name of the running lock. The value must be a string.| -| type | [RunningLockType](#runninglocktype) | Yes | Type of the running lock. The value must be an enum.| +| name | string | Yes | Name of the **RunningLock** object. The value must be a string. | +| type | [RunningLockType](#runninglocktype) | Yes | Type of the **RunningLock** object. The value must be an enum. | **Return value** @@ -151,8 +150,8 @@ Checks whether the specified type of running locks is supported. This API uses a | Name | Type | Mandatory| Description | | -------- | ----------------------------------- | ---- | ------------------------------------------------------------ | -| type | [RunningLockType](#runninglocktype) | Yes | Type of the **RunningLock** object. | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the query result obtained, where the value **true** indicates that the specified type of **RunningLock** is supported and **false** indicates the opposite. Otherwise, **err** is an error object.| +| type | [RunningLockType](#runninglocktype) | Yes | Type of the running lock. | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the query result obtained, where the value **true** indicates that the specified type of the running lock is supported and **false** indicates the opposite. Otherwise, **err** is an error object. | **Example** @@ -172,7 +171,7 @@ isRunningLockTypeSupported(type: RunningLockType): Promise<boolean> > **NOTE**
This API is deprecated since API version 9. You are advised to use [runningLock.isSupported](#runninglockissupported9). -Checks whether the specified type of running locks is supported. This API uses a promise to return the result. +Checks whether the specified type of the running lock is supported. This API uses a promise to return the result. **System capability**: SystemCapability.PowerManager.PowerManager.Core @@ -180,13 +179,13 @@ Checks whether the specified type of running locks is supported. This API uses a | Name| Type | Mandatory| Description | | ------ | ----------------------------------- | ---- | -------------------- | -| type | [RunningLockType](#runninglocktype) | Yes | Type of the **RunningLock** object.| +| type | [RunningLockType](#runninglocktype) | Yes | Type of the running lock.| **Return value** | Type | Description | | ---------------------- | ---------------------------------------------------- | -| Promise<boolean> | Promise used to return the result. The value **true** indicates that the specified type of **RunningLock** is supported, and the value **false** indicates the opposite.| +| Promise<boolean> | Promise used to return the result. The value **true** indicates that the specified type of the running lock is supported, and the value **false** indicates the opposite.| **Example** @@ -295,8 +294,7 @@ For details about the error codes, see [RunningLock Error Codes](errorcode-runni | ID | Error Message | |---------|----------| -| 4900101 | Failed to connect to the service. | -| 401 | Parameter error. Possible causes: 1. Incorrect parameter types; | +| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. | | 201 | If the permission is denied.| **Example** @@ -346,7 +344,6 @@ For details about the error codes, see [RunningLock Error Codes](errorcode-runni | ID | Error Message | |---------|----------| -| 4900101 | Failed to connect to the service. | | 201 | If the permission is denied.| @@ -360,7 +357,7 @@ class RunningLockTest { public static unholdRunningLock(): void { if (RunningLockTest.recordLock) { RunningLockTest.recordLock.unhold(); - console.info('hold running lock success'); + console.info('unhold running lock success'); } else { runningLock.create('running_lock_test', runningLock.RunningLockType.PROXIMITY_SCREEN_CONTROL, (err: Error, lock: runningLock.RunningLock) => { if (typeof err === 'undefined') { @@ -395,14 +392,6 @@ Checks the hold status of the **RunningLock** object. | ------- | ------------------------------------------------------------ | | boolean | The value **true** indicates that the **RunningLock** object is held; and the value **false** indicates that the **RunningLock** object is released.| -**Error codes** - -For details about the error codes, see [RunningLock Error Codes](errorcode-runninglock.md). - -| ID | Error Message | -|---------|---------| -| 4900101 | Failed to connect to the service. | - **Example** ```ts @@ -419,12 +408,8 @@ class RunningLockTest { if (typeof err === 'undefined') { console.info('create running lock: ' + lock); RunningLockTest.recordLock = lock; - try { - let isHolding = lock.isHolding(); - console.info('check running lock holding status: ' + isHolding); - } catch(err) { - console.error('check running lock holding status failed, err: ' + err); - } + let isHolding = lock.isHolding(); + console.info('check running lock holding status: ' + isHolding); } else { console.error('create running lock failed, err: ' + err); } diff --git a/en/application-dev/reference/apis-basic-services-kit/js-apis-screen-lock-sys.md b/en/application-dev/reference/apis-basic-services-kit/js-apis-screen-lock-sys.md index 46f08700ddf..5f3b62b9265 100644 --- a/en/application-dev/reference/apis-basic-services-kit/js-apis-screen-lock-sys.md +++ b/en/application-dev/reference/apis-basic-services-kit/js-apis-screen-lock-sys.md @@ -294,11 +294,11 @@ For details about error codes, see [Universal Error Codes](../errorcode-universa try { let isSuccess = screenLock.onSystemEvent((event: screenLock.SystemEvent) => { - console.log(`Succeeded in Registering the system event which related to screenlock. eventType: ${event.eventType}`) + console.info(`Succeeded in Registering the system event which related to screenlock. eventType: ${event.eventType}`); }); } catch (err) { let error = err as BusinessError; - console.error(`Failed to register the system event which related to screenlock, Code: ${error.code}, message: ${error.message}`) + console.error(`Failed to register the system event which related to screenlock, Code: ${error.code}, message: ${error.message}`); } ``` @@ -319,7 +319,7 @@ Sends an event to the screen lock service. This API can be called only by screen | Name | Type | Mandatory| Description | | --------- | ------------------------ | ---- |-------------------------------------------------------------------------------------------------------------------| | event | String | Yes | Event type. Options are as follows:
- **"unlockScreenResult"**: Screen unlock result.
- **"lockScreenResult"**: Screen lock result.
- **"screenDrawDone"**: Screen drawing is complete.| -| parameter | number | Yes | Result.
- **0**: The operation is successful. For example, the screen is locked or unlocked successfully.
- **1**, the operation fails. For example, screen locking or unlocking fails.
- **2**: The operation is canceled. For example, screen locking or unlocking is canceled.| +| parameter | number | Yes | Result.
- **0**: The operation is successful. For example, the screen is locked or unlocked successfully.
- **1**: The operation fails. For example, screen locking or unlocking fails.
- **2**: The operation is canceled. For example, screen locking or unlocking is canceled. | | callback | AsyncCallback\ | Yes | Callback used to return the result. The **value** true means that the event is sent successfully, and **false** means the opposite. | **Error codes** @@ -364,7 +364,7 @@ Sends an event to the screen lock service. This API can be called only by screen | Name | Type | Mandatory| Description | | --------- | ------ | ---- |-------------------------------------------------------------------------------------------------------------------| | event | String | Yes | Event type. Options are as follows:
- **"unlockScreenResult"**: Screen unlock result.
- **"lockScreenResult"**: Screen lock result.
- **"screenDrawDone"**: Screen drawing is complete.| -| parameter | number | Yes | Result.
- **0**: The operation is successful. For example, the screen is locked or unlocked successfully.
- **1**, the operation fails. For example, screen locking or unlocking fails.
- **2**: The operation is canceled. For example, screen locking or unlocking is canceled.| +| parameter | number | Yes | Result.
- **0**: The operation is successful. For example, the screen is locked or unlocked successfully.
- **1**: The operation fails. For example, screen locking or unlocking fails.
- **2**: The operation is canceled. For example, screen locking or unlocking is canceled. | **Return value** diff --git a/en/application-dev/reference/apis-basic-services-kit/js-apis-serialManager-sys.md b/en/application-dev/reference/apis-basic-services-kit/js-apis-serialManager-sys.md index 59d2bacc656..305d56fd074 100644 --- a/en/application-dev/reference/apis-basic-services-kit/js-apis-serialManager-sys.md +++ b/en/application-dev/reference/apis-basic-services-kit/js-apis-serialManager-sys.md @@ -1,10 +1,10 @@ # @ohos.usbManager.serial (Serial Port Management) (system API) -This module provides the serial port management functions, including enabling and disabling the serial port of the device, writing and reading data, setting and obtaining the configuration parameters of the serial port, and managing permissions. +This module provides the serial port management features, including enabling and disabling the serial port of the device, writing and reading data, setting and obtaining the configuration parameters of the serial port, and managing permissions. > **NOTE** > -> The initial APIs of this module are supported since API version 18. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The initial APIs of this module are supported since API version 19. Newly added APIs will be marked with a superscript to indicate their earliest API version. > > This topic describes only the system APIs provided by the module. For details about its public APIs, see [@ohos.usbManager.serial (USB Manager)](js-apis-serialManager.md). @@ -16,7 +16,7 @@ import { serialManager } from '@kit.BasicServicesKit'; ## serialManager.addSerialRight -addSerialRight(tokenId: number, portId: number): void; +addSerialRight(tokenId: number, portId: number): void Adds the permission to an application for accessing the serial port device. diff --git a/en/application-dev/reference/apis-basic-services-kit/js-apis-serialManager.md b/en/application-dev/reference/apis-basic-services-kit/js-apis-serialManager.md index 7264c72c245..8113047b0da 100644 --- a/en/application-dev/reference/apis-basic-services-kit/js-apis-serialManager.md +++ b/en/application-dev/reference/apis-basic-services-kit/js-apis-serialManager.md @@ -4,7 +4,7 @@ This module provides the serial port management functions, including enabling an > **NOTE** > -> The initial APIs of this module are supported since API version 18. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The initial APIs of this module are supported since API version 19. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -14,7 +14,7 @@ import { serialManager } from '@kit.BasicServicesKit'; ## serialManager.getPortList -getPortList(): Readonly<serialport>[]; +getPortList(): Readonly<SerialPort>[] Obtains the serial port device list, including the device name and port number. @@ -28,6 +28,11 @@ Obtains the serial port device list, including the device name and port number. **Example** +> **NOTE** +> +> The following sample code shows the basic process for calling the **getPortList** API and it needs to be executed in a specific method. In actual calling, you must comply with the device-related protocols. + + ```ts import { JSON } from '@kit.ArkTS'; import { serialManager } from '@kit.BasicServicesKit'; @@ -44,9 +49,9 @@ let portId: number = portList[0].portId; ## serialManager.hasSerialRight -hasSerialRight(portId: number): boolean; +hasSerialRight(portId: number): boolean -Checks whether the application has the permission to access the serial port device. When an application is restarted after exiting, you need to request the permission from the user again. +Checks whether the application has the permission to access the serial port device. When an application is restarted after exits, you need to request the permission from the user again. **System capability**: SystemCapability.USB.USBManager.Serial @@ -71,10 +76,15 @@ For details about the error codes, see [USB Service Error Codes](errorcode-usb.m | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 14400005 | Database operation exception. | | 31400001 | Serial port management exception. | -| 31400003 | Device does not exist. | +| 31400003 | PortId does not exist. | **Example** +> **NOTE** +> +> The following sample code shows the basic process for calling the **hasSerialRight** API and it needs to be executed in a specific method. In actual calling, you must comply with the device-related protocols. + + ```ts import { JSON } from '@kit.ArkTS'; import { serialManager } from '@kit.BasicServicesKit'; @@ -125,10 +135,15 @@ For details about the error codes, see [USB Service Error Codes](errorcode-usb.m | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 14400005 | Database operation exception. | | 31400001 | Serial port management exception. | -| 31400003 | Device does not exist. | +| 31400003 | PortId does not exist. | **Example** +> **NOTE** +> +> The following sample code shows the basic process for calling the **requestSerialRight** API and it needs to be executed in a specific method. In actual calling, you must comply with the device-related protocols. + + ```ts import { JSON } from '@kit.ArkTS'; import { serialManager } from '@kit.BasicServicesKit'; @@ -158,7 +173,7 @@ if (!serialManager.hasSerialRight(portId)) { ## serialManager.open -open(portId: number): void; +open(portId: number): void Opens a serial port device. @@ -179,11 +194,16 @@ For details about the error codes, see [USB Service Error Codes](errorcode-usb.m | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 31400001 | Serial port management exception. | | 31400002 | Access denied. Call requestSerialRight to request user authorization first. | -| 31400003 | Device does not exist. | +| 31400003 | PortId does not exist. | | 31400004 | The serial port device is occupied. | **Example** +> **NOTE** +> +> The following sample code shows the basic process for calling the **open** API and it needs to be executed in a specific method. In actual calling, you must comply with the device-related protocols. + + ```ts import { JSON } from '@kit.ArkTS'; import { serialManager } from '@kit.BasicServicesKit'; @@ -221,7 +241,7 @@ try { ## serialManager.getAttribute -getAttribute(portId: number): Readonly<[SerialAttribute](#serialattribute)>; +getAttribute(portId: number): Readonly<[SerialAttribute](#serialattribute)> Obtains the configuration parameters of a specified serial port. @@ -247,11 +267,16 @@ For details about the error codes, see [USB Service Error Codes](errorcode-usb.m | -------- | ------------------------------------------------------------ | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 31400001 | Serial port management exception. | -| 31400003 | Device does not exist. | +| 31400003 | PortId does not exist. | | 31400005 | The serial port device is not opened. Call the open API first. | **Example** +> **NOTE** +> +> The following sample code shows the basic process for calling the **getAttribute** API and it needs to be executed in a specific method. In actual calling, you must comply with the device-related protocols. + + ```ts import { JSON } from '@kit.ArkTS'; import { serialManager } from '@kit.BasicServicesKit'; @@ -301,7 +326,7 @@ try { ## serialManager.setAttribute -setAttribute(portId: number, attribute: [SerialAttribute](#serialattribute)): void; +setAttribute(portId: number, attribute: [SerialAttribute](#serialattribute)): void Sets the parameters of the serial port. If this method is not called, the default configuration parameters are used (baud rate: 9600 bit/s; data bit: 8; parity bit: 0; stop bit: 1). @@ -322,11 +347,16 @@ For details about the error codes, see [USB Service Error Codes](errorcode-usb.m | -------- | ------------------------------------------------------------ | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 31400001 | Serial port management exception. | -| 31400003 | Device does not exist. | +| 31400003 | PortId does not exist. | | 31400005 | The serial port device is not opened. Call the open API first. | **Example** +> **NOTE** +> +> The following sample code shows the basic process for calling the **setAttribute** API and it needs to be executed in a specific method. In actual calling, you must comply with the device-related protocols. + + ```ts import { JSON } from '@kit.ArkTS'; import { serialManager } from '@kit.BasicServicesKit'; @@ -378,7 +408,7 @@ try { ## serialManager.read -read(portId: number, buffer: Uint8Array, timeout?: number): Promise<number>; +read(portId: number, buffer: Uint8Array, timeout?: number): Promise<number> Reads data from the serial port device asynchronously. @@ -390,7 +420,7 @@ Reads data from the serial port device asynchronously. |---------|------------|----|------------------| | portId | number | Yes | Port number. | | buffer | Uint8Array | Yes | Buffer for reading data.| -| timeout | number | No | Timeout duration for reading data, in milliseconds.| +| timeout | number | No | (Optional) Timeout duration, in ms. The default value is **0**, indicating no timeout. You can set this parameter as required.| **Returns** @@ -406,13 +436,18 @@ For details about the error codes, see [USB Service Error Codes](errorcode-usb.m | -------- | ------------------------------------------------------------ | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 31400001 | Serial port management exception. | -| 31400003 | Device does not exist. | +| 31400003 | PortId does not exist. | | 31400005 | The serial port device is not opened. Call the open API first. | | 31400006 | Data transfer timed out. | -| 31400007 | I/O exception. | +| 31400007 | I/O exception. Possible causes: 1. The transfer was canceled. 2. The device offered more data than allowed. | **Example** +> **NOTE** +> +> The following sample code shows the basic process for calling the **read** API and it needs to be executed in a specific method. In actual calling, you must comply with the device-related protocols. + + ```ts import { JSON } from '@kit.ArkTS'; import { serialManager } from '@kit.BasicServicesKit'; @@ -458,7 +493,7 @@ serialManager.read(portId, readBuffer, 2000).then((size: number) => { ## serialManager.readSync -readSync(portId: number, buffer: Uint8Array, timeout?: number): number; +readSync(portId: number, buffer: Uint8Array, timeout?: number): number Reads data from the serial port device synchronously. @@ -470,7 +505,7 @@ Reads data from the serial port device synchronously. |---------|------------|----|------------------| | portId | number | Yes | Port number.| | buffer | Uint8Array | Yes | Buffer for reading data.| -| timeout | number | No | Timeout duration for reading data, in milliseconds.| +| timeout | number | No | (Optional) Timeout duration, in ms. The default value is **0**, indicating no timeout. You can set this parameter as required.| **Returns** @@ -486,13 +521,18 @@ For details about the error codes, see [USB Service Error Codes](errorcode-usb.m | -------- | ------------------------------------------------------------ | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 31400001 | Serial port management exception. | -| 31400003 | Device does not exist. | +| 31400003 | PortId does not exist. | | 31400005 | The serial port device is not opened. Call the open API first. | | 31400006 | Data transfer timed out. | -| 31400007 | I/O exception. | +| 31400007 | I/O exception. Possible causes: 1. The transfer was canceled. 2. The device offered more data than allowed. | **Example** +> **NOTE** +> +> The following sample code shows the basic process for calling the **readSync** API and it needs to be executed in a specific method. In actual calling, you must comply with the device-related protocols. + + ```ts import { JSON } from '@kit.ArkTS'; import { serialManager } from '@kit.BasicServicesKit'; @@ -539,7 +579,7 @@ try { ## serialManager.write -write(portId: number, buffer: Uint8Array, timeout?: number): Promise<number>; +write(portId: number, buffer: Uint8Array, timeout?: number): Promise<number> Writes data to the serial port device asynchronously. @@ -551,7 +591,7 @@ Writes data to the serial port device asynchronously. |---------|------------|----|------------------| | portId | number | Yes | Port number. | | buffer | Uint8Array | Yes | Buffer for writing data.| -| timeout | number | No | Timeout duration for writing data, in milliseconds.| +| timeout | number | No | (Optional) Timeout duration, in ms. The default value is **0**, indicating no timeout. You can set this parameter as required.| **Returns** @@ -567,13 +607,18 @@ For details about the error codes, see [USB Service Error Codes](errorcode-usb.m | -------- | ------------------------------------------------------------ | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 31400001 | Serial port management exception. | -| 31400003 | Device does not exist. | +| 31400003 | PortId does not exist. | | 31400005 | The serial port device is not opened. Call the open API first. | | 31400006 | Data transfer timed out. | -| 31400007 | I/O exception. | +| 31400007 | I/O exception. Possible causes: 1. The transfer was canceled. 2. The device offered more data than allowed. | **Example** +> **NOTE** +> +> The following sample code shows the basic process for calling the **addSerialRight** API and it needs to be executed in a specific method. In actual calling, you must comply with the device-related protocols. + + ```ts import { JSON } from '@kit.ArkTS'; import { serialManager } from '@kit.BasicServicesKit'; @@ -619,7 +664,7 @@ serialManager.write(portId, writeBuffer, 2000).then((size: number) => { ## serialManager.writeSync -writeSync(portId: number, buffer: Uint8Array, timeout?: number): number; +writeSync(portId: number, buffer: Uint8Array, timeout?: number): number Writes data to the serial port device synchronously. @@ -631,7 +676,7 @@ Writes data to the serial port device synchronously. |---------|------------|----|------------------| | portId | number | Yes | Port number. | | buffer | Uint8Array | Yes | Destination buffer for writing data.| -| timeout | number | No | Timeout duration for writing data, in milliseconds.| +| timeout | number | No | (Optional) Timeout duration, in ms. The default value is **0**, indicating no timeout. You can set this parameter as required.| **Returns** @@ -647,13 +692,18 @@ For details about the error codes, see [USB Service Error Codes](errorcode-usb.m | -------- | ------------------------------------------------------------ | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 31400001 | Serial port management exception. | -| 31400003 | Device does not exist. | +| 31400003 | PortId does not exist. | | 31400005 | The serial port device is not opened. Call the open API first. | | 31400006 | Data transfer timed out. | -| 31400007 | I/O exception. | +| 31400007 | I/O exception. Possible causes: 1. The transfer was canceled. 2. The device offered more data than allowed. | **Example** +> **NOTE** +> +> The following sample code shows the basic process for calling the **writeSync** API and it needs to be executed in a specific method. In actual calling, you must comply with the device-related protocols. + + ```ts import { JSON } from '@kit.ArkTS'; import { serialManager } from '@kit.BasicServicesKit'; @@ -700,7 +750,7 @@ try { ## serialManager.close -close(portId: number): void; +close(portId: number): void Closes the serial port device. @@ -720,11 +770,16 @@ For details about the error codes, see [USB Service Error Codes](errorcode-usb.m | -------- | ------------------------------------------------------------ | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 31400001 | Serial port management exception. | -| 31400003 | Device does not exist. | +| 31400003 | PortId does not exist. | | 31400005 | The serial port device is not opened. Call the open API first. | **Example** +> **NOTE** +> +> The following sample code shows the basic process for calling the **close** API and it needs to be executed in a specific method. In actual calling, you must comply with the device-related protocols. + + ```ts import { JSON } from '@kit.ArkTS'; import { serialManager } from '@kit.BasicServicesKit'; @@ -770,7 +825,7 @@ try { ## serialManager.cancelSerialRight -cancelSerialRight(portId: number): void; +cancelSerialRight(portId: number): void Cancels the permission to access the serial port device when the application is running. This API is used to close the enabled serial port device. @@ -792,10 +847,15 @@ For details about the error codes, see [USB Service Error Codes](errorcode-usb.m | 14400005 | Database operation exception. | | 31400001 | Serial port management exception. | | 31400002 | Access denied. Call requestSerialRight to request user authorization first. | -| 31400003 | Device does not exist. | +| 31400003 | PortId does not exist. | **Example** +> **NOTE** +> +> The following sample code shows the basic process for calling the **cancelSerialRight** API and it needs to be executed in a specific method. In actual calling, you must comply with the device-related protocols. + + ```ts import { JSON } from '@kit.ArkTS'; import { serialManager } from '@kit.BasicServicesKit'; @@ -837,12 +897,12 @@ Represents the configuration parameters of a serial port. **System capability**: SystemCapability.USB.USBManager.Serial -| Name | Type | Mandatory| Description | -|----------|--------|----|-----------| -| baudrate | number | Yes | Baud rate. | -| dataBits | number | No | Data bit. | -| parity | number | No | Parity check.| -| stopBits | number | No | Stop bit. | +| Name | Type | Read-Only | Optional| Description | +|----------|--------|----------|-----------|----------------------| +| baudRate | [BaudRates](#baudrates) | No | No | Baud rate. | +| dataBits | [DataBits](#databits) | No | Yes | Data bits. The default value is **8**. | +| parity | [Parity](#parity) | No | Yes | Parity check. The default value is **None**, indicating that no parity check is performed.| +| stopBits | [StopBits](#stopbits) | No | Yes | Stop bits. The default value is **1**. | ## SerialPort @@ -850,10 +910,10 @@ Represents the parameters of a serial port. **System capability**: SystemCapability.USB.USBManager.Serial -| Name | Type | Mandatory| Description | -|--------|--------|----|-------| -| portId | number | Yes | Port number.| -| deviceName | string | Yes | Serial port device name.| +| Name | Type | Read-Only| Optional| Description | +|--------|--------|------|-------|--------| +| portId | number | No | No| Port number.| +| deviceName | string | No | No| Serial port device name.| ## BaudRates @@ -930,5 +990,4 @@ Enumerates of the number of stop bits. | Name | Value | Description | |-----------|-----------|-----------| | STOPBIT_1 | 0 | The number of stop bits is 1.| -| STOPBIT_1P5 | 1 | The number of stop bits is 1.5.| -| STOPBIT_2 | 2 | The number of stop bits is 2.| +| STOPBIT_2 | 1 | The number of stop bits is 2.| diff --git a/en/application-dev/reference/apis-basic-services-kit/js-apis-settings.md b/en/application-dev/reference/apis-basic-services-kit/js-apis-settings.md index 38d27b582f9..7b7bb9c2b5c 100644 --- a/en/application-dev/reference/apis-basic-services-kit/js-apis-settings.md +++ b/en/application-dev/reference/apis-basic-services-kit/js-apis-settings.md @@ -11,7 +11,7 @@ The **settings** module provides APIs for setting data items. ## Modules to Import ```js -import settings from '@ohos.settings'; +import { settings } from '@kit.BasicServicesKit'; ``` ## domainName @@ -21,10 +21,10 @@ Provides the domain name. **System capability**: SystemCapability.Applications.Settings.Core -| Name | Type | Readable| Writable| Description | -|-----------------------------| ------ | ---- | ---- | ------------------------------------------------------------ | -| DEVICE_SHARED11+ | string | Yes | Yes | Shared device domain. | -| USER_PROPERTY11+ | string | Yes | Yes | User property domain. | +| Name | Type | Readable| Writable| Description | +|-----------------------------| ------ | ---- | ---- |----------------------| +| DEVICE_SHARED11+ | string | Yes | Yes | Shared device domain. All configurations in this domain are not distinguished between multiple users.| +| USER_PROPERTY11+ | string | Yes | Yes | User attribute domain. All configurations in this domain are distinguished between multiple users.| ## date @@ -34,12 +34,12 @@ Provides data items for setting the time and date formats. (Not supported yet.) **System capability**: SystemCapability.Applications.Settings.Core -| Name | Type | Readable| Writable| Description | -| ------------------- | ------ | ---- | ---- | ------------------------------------------------------------ | +| Name | Type | Readable| Writable| Description | +| ------------------- | ------ | ---- | ---- |----------------------------------------------------------------------------| | DATE_FORMAT | string | Yes | Yes | Date format.
The value can be **mm/dd/yyyy**, **dd/mm/yyyy**, or **yyyy/mm/dd**, where **mm** indicates the month, **dd** indicates the day, and **yyyy** indicates the year.| -| TIME_FORMAT | string | Yes | Yes | Time format. The options are as follows:
- **12**: 12-hour format.
- **24**: 24-hour format.| -| AUTO_GAIN_TIME | string | Yes | Yes | Whether the date, time, and time zone are automatically obtained from the Network Identity and Time Zone (NITZ).
The value **true** means that the date, time, and time zone are automatically obtained from NITZ;
**false** means the opposite.| -| AUTO_GAIN_TIME_ZONE | string | Yes | Yes | Whether the time zone is automatically obtained from NITZ.
The value **true** means that the time zone is automatically obtained from NITZ;
**false** means the opposite.| +| TIME_FORMAT | string | Yes | Yes | Time format. The options are as follows:
- **12**: 12-hour format.
- **24**: 24-hour format. | +| AUTO_GAIN_TIME | string | Yes | Yes | Whether the date, time, and time zone are automatically obtained from the Network Identity and Time Zone (NITZ).
- **true**: Information is automatically obtained.
- **false**: Information is not automatically obtained. | +| AUTO_GAIN_TIME_ZONE | string | Yes | Yes | Whether the time zone is automatically obtained from NITZ.
- **1**: Time zone is automatically obtained.
- **false**: Time zone is not automatically obtained. | ## display @@ -49,19 +49,19 @@ Provides data items for setting the display effects. (Not supported yet.) **System capability**: SystemCapability.Applications.Settings.Core -| Name | Type | Readable| Writable| Description | -| ----------------------------- | ------ | ---- | ---- |-------------------------------------------------------------------------------------------------------------| -| FONT_SCALE | string | Yes | Yes | Scale factor of the font. The value is a floating point number. (In the current version, only fixed values can be queried.) | -| SCREEN_BRIGHTNESS_STATUS | string | Yes | Yes | Screen brightness, with the value ranging from 0 to 255. | -| AUTO_SCREEN_BRIGHTNESS | string | Yes | Yes | Whether automatic screen brightness adjustment is enabled.
- **AUTO_SCREEN_BRIGHTNESS_MODE**: Automatic screen brightness adjustment is enabled.
- **MANUAL_SCREEN_BRIGHTNESS_MODE**: Automatic screen brightness adjustment is disabled. | -| AUTO_SCREEN_BRIGHTNESS_MODE | number | Yes | Yes | Value of **AUTO_SCREEN_BRIGHTNESS** when automatic screen brightness adjustment is enabled. | -| MANUAL_SCREEN_BRIGHTNESS_MODE | number | Yes | Yes | Value of **AUTO_SCREEN_BRIGHTNESS** when automatic screen brightness adjustment is disabled. | -| SCREEN_OFF_TIMEOUT | string | Yes | Yes | Waiting time for the device to enter the sleep state when not in use (unit: ms). | +| Name | Type | Readable| Writable| Description | +| ----------------------------- | ------ | ---- | ---- |----------------------------------------------------------------------------------------------------------------------| +| FONT_SCALE | string | Yes | Yes | Scale factor of the font. The value is a floating point number. (In the current version, only fixed values can be queried.) | +| SCREEN_BRIGHTNESS_STATUS | string | Yes | Yes | Screen brightness, with the value ranging from 0 to 255. | +| AUTO_SCREEN_BRIGHTNESS | string | Yes | Yes | Whether automatic screen brightness adjustment is enabled.
- **AUTO_SCREEN_BRIGHTNESS_MODE**: Automatic screen brightness adjustment is enabled.
- **MANUAL_SCREEN_BRIGHTNESS_MODE**: Automatic screen brightness adjustment is disabled. | +| AUTO_SCREEN_BRIGHTNESS_MODE | number | Yes | Yes | Value of **AUTO_SCREEN_BRIGHTNESS** when automatic screen brightness adjustment is enabled. | +| MANUAL_SCREEN_BRIGHTNESS_MODE | number | Yes | Yes | Value of **AUTO_SCREEN_BRIGHTNESS** when automatic screen brightness adjustment is disabled. | +| SCREEN_OFF_TIMEOUT | string | Yes | Yes | Waiting time for the device to enter the sleep state when not in use (unit: ms). | | DEFAULT_SCREEN_ROTATION | string | Yes | Yes | This attribute is invalid when screen auto-rotation is enabled; otherwise, the following options are available:
- **0**: The screen rotates by 0 degrees.
- **1**: The screen rotates by 90 degrees.
- **2**: The screen rotates by 180 degrees.
- **3**: The screen rotates by 270 degrees.| -| ANIMATOR_DURATION_SCALE | string | Yes | Yes | Scale factor for the animation duration, which affects the start delay and duration of all such animations.
If the value is **0**, the animation ends immediately. The default value is **1**. | -| TRANSITION_ANIMATION_SCALE | string | Yes | Yes | Scale factor for transition animations.
The value **0** indicates that the transition animations are disabled. | -| WINDOW_ANIMATION_SCALE | string | Yes | Yes | Scale factor for normal window animations.
The value **0** indicates that window animations are disabled. | -| DISPLAY_INVERSION_STATUS | string | Yes | Yes | Whether display color inversion is enabled.
- **1**: Display color inversion is enabled.
- **0**: Display color inversion is disabled. | +| ANIMATOR_DURATION_SCALE | string | Yes | Yes | Scale factor for the animation duration, which affects the start delay and duration of all such animations.
- **0**: The animation ends immediately. The default value is **1**. | +| TRANSITION_ANIMATION_SCALE | string | Yes | Yes | Scale factor for transition animations.
The value **0** indicates that the transition animations are disabled. | +| WINDOW_ANIMATION_SCALE | string | Yes | Yes | Scale factor for normal window animations.
The value **0** indicates that window animations are disabled. | +| DISPLAY_INVERSION_STATUS | string | Yes | Yes | Whether display color inversion is enabled.
- **1**: Display color inversion is enabled.
- **0**: Display color inversion is disabled. | ## general @@ -71,24 +71,24 @@ Provides data items for setting the general information about the device. (Not s **System capability**: SystemCapability.Applications.Settings.Core -| Name | Type | Readable| Writable| Description | -| -------------------------------- | ------ | ---- | ---- | ------------------------------------------------------------ | -| SETUP_WIZARD_FINISHED | string | Yes | Yes | Whether the startup wizard is running.
- If the value is **0**, the startup wizard is not running.
- If the value is not **0**, the startup wizard is running.| +| Name | Type | Readable| Writable| Description | +| -------------------------------- | ------ | ---- | ---- |-------------------------------------------------------------------------------------------------------------------------------------| +| SETUP_WIZARD_FINISHED | string | Yes | Yes | Whether the startup wizard has been run.
- **0**: The startup wizard is not run.
- Other than **0**: The startup wizard has been run. | | END_BUTTON_ACTION | string | Yes | Yes | Action after the call end button is pressed if the user is not in a call.
- **0**: Nothing happens.
- **1**: The home screen is displayed.
- **2**: The device enters sleep mode and the screen is locked.
- **3**: The home screen is displayed. If the focus is already on the home screen, the device will enter sleep mode.| -| ACCELEROMETER_ROTATION_STATUS | string | Yes | Yes | Whether the accelerometer is used to change screen orientation, that is, whether to enable auto-rotation.
- **1**: The accelerometer is used.
- **0**: The accelerometer is not used.| -| DEVICE_PROVISION_STATUS | string | Yes | Yes | Whether the device is preconfigured.
On a multi-user device with a single system user, the screen may be locked when the value is **true**. In addition, other features cannot be started on the system user unless they are marked to display on the lock screen.| -| HDC_STATUS | string | Yes | Yes | Whether the hard disk controller (HDC) on the USB device is enabled.
- **true**: HDC is enabled.
- **false**: HDC is disabled.| -| BOOT_COUNTING | string | Yes | Yes | Number of boot operations after the device is powered on. | -| CONTACT_METADATA_SYNC_STATUS | string | Yes | Yes | Whether contacts metadata synchronization is enabled.
- **true**: Contacts metadata synchronization is enabled.
- **false**: Contacts metadata synchronization is disabled.| -| DEVICE_NAME | string | Yes | Yes | Device name. | -| USB_STORAGE_STATUS | string | Yes | Yes | Whether USB mass storage is enabled.
- **true**: USB mass storage is enabled.
- **false**: USB mass storage is disabled.| -| DEBUGGER_WAITING | string | Yes | Yes | Whether the device waits for the debugger when starting an application to debug.
- **1**: The device waits for the debugger.
- **0**: The device does not wait for the debugger. In this case, the application runs normally.| -| DEBUG_APP_PACKAGE | string | Yes | Yes | Bundle name of the application to be debugged. | -| ACCESSIBILITY_STATUS | string | Yes | Yes | Whether accessibility is enabled.
- **1**: Accessibility is enabled.
- **0**: Accessibility is disabled.| -| ACTIVATED_ACCESSIBILITY_SERVICES | string | Yes | Yes | List of activated accessibility features. | -| GEOLOCATION_ORIGINS_ALLOWED | string | Yes | Yes | Default geographic location that can be used by the browser. Multiple geographic locations are separated by spaces. | -| SKIP_USE_HINTS | string | Yes | Yes | Whether the application should attempt to skip all introductory hints at the first startup. This feature is intended for temporary or experienced users.
- **1**: The application attempts to skip all introductory hints at the first startup.
- **0**: The application does not skip all introductory hints at the first startup.| -| TOUCH_EXPLORATION_STATUS | string | Yes | Yes | Whether touch exploration is enabled.
- **1**: Touch exploration is enabled.
- **0**: Touch exploration is disabled.| +| ACCELEROMETER_ROTATION_STATUS | string | Yes | Yes | Whether the accelerometer is used to change screen orientation, that is, whether to enable auto-rotation.
- **1**: The accelerometer is used.
- **0**: The accelerometer is not used. | +| DEVICE_PROVISION_STATUS | string | Yes | Yes | Whether the device is preconfigured.
On a multi-user device with a single system user, the screen may be locked when the value is **true**. In addition, other features cannot be started on the system user unless they are marked to display on the lock screen. | +| HDC_STATUS | string | Yes | Yes | Whether the hard disk controller (HDC) on the USB device is enabled.
- **true**: HDC is enabled.
- **false**: HDC is disabled. | +| BOOT_COUNTING | string | Yes | Yes | Number of boot operations after the device is powered on. | +| CONTACT_METADATA_SYNC_STATUS | string | Yes | Yes | Whether contacts metadata synchronization is enabled.
- **true**: Contacts metadata synchronization is enabled.
- **false**: Contacts metadata synchronization is disabled. | +| DEVICE_NAME | string | Yes | Yes | Device name. | +| USB_STORAGE_STATUS | string | Yes | Yes | Whether USB mass storage is enabled.
- **true**: USB mass storage is enabled.
- **false**: USB mass storage is disabled. | +| DEBUGGER_WAITING | string | Yes | Yes | Whether the device waits for the debugger when starting an application to debug.
- **1**: The device waits for the debugger.
- **0**: The device does not wait for the debugger. In this case, the application runs normally. | +| DEBUG_APP_PACKAGE | string | Yes | Yes | Bundle name of the application to be debugged. | +| ACCESSIBILITY_STATUS | string | Yes | Yes | Whether accessibility is enabled.
- **1**: Accessibility is enabled.
- **0**: Accessibility is disabled. | +| ACTIVATED_ACCESSIBILITY_SERVICES | string | Yes | Yes | List of activated accessibility features. | +| GEOLOCATION_ORIGINS_ALLOWED | string | Yes | Yes | Default geographic location that can be used by the browser. Multiple geographic locations are separated by spaces. | +| SKIP_USE_HINTS | string | Yes | Yes | Whether the application should attempt to skip all introductory hints at the first startup. This feature is intended for temporary or experienced users.
- **1**: The application will skip all introductory hints at the first startup.
- **0**: The application does not skip all introductory hints at the first startup. | +| TOUCH_EXPLORATION_STATUS | string | Yes | Yes | Whether touch exploration is enabled.
- **1**: Touch exploration is enabled.
- **0**: Touch exploration is disabled. | ## input @@ -98,16 +98,16 @@ Provides data items for setting input methods. (Not supported yet.) **System capability**: SystemCapability.Applications.Settings.Core -| Name | Type | Readable| Writable| Description | -| ------------------------------------ | ------ | ---- | ---- | ------------------------------------------------------------ | -| DEFAULT_INPUT_METHOD | string | Yes | Yes | Default input method and its ID. | -| ACTIVATED_INPUT_METHOD_SUB_MODE | string | Yes | Yes | Type and ID of the default input method keyboard. | +| Name | Type | Readable| Writable| Description | +| ------------------------------------ | ------ | ---- | ---- |-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| DEFAULT_INPUT_METHOD | string | Yes | Yes | Default input method and its ID. | +| ACTIVATED_INPUT_METHOD_SUB_MODE | string | Yes | Yes | Type and ID of the default input method keyboard. | | ACTIVATED_INPUT_METHODS | string | Yes | Yes | List of activated input methods.
The list is a string that contains the IDs and keyboard types of activated input methods.
The IDs are separated by colons (:), and keyboard types are separated by semicolons (;).
An example format is **ima0:keyboardType0;keyboardType1;ima1:ima2:keyboardTypes0,** where **ima** indicates the ID of an input method, and **keyboardType** indicates the keyboard type.| -| SELECTOR_VISIBILITY_FOR_INPUT_METHOD | string | Yes | Yes | Whether the input method selector is visible.
- **1**: The input method selector is visible.
- **0**: The input method selector is invisible.| -| AUTO_CAPS_TEXT_INPUT | string | Yes | Yes | Whether automatic capitalization is enabled for the text editor.
- **0**: Automatic capitalization is disabled.
- **1**: Automatic capitalization is enabled.| -| AUTO_PUNCTUATE_TEXT_INPUT | string | Yes | Yes | Whether automatic punctuation is enabled for the text editor. Automatic punctuation enables the text editor to convert two spaces into a period (.) and a space.
- **0**: Automatic punctuation is disabled.
- **1**: Automatic punctuation is enabled.| -| AUTO_REPLACE_TEXT_INPUT | string | Yes | Yes | Whether autocorrect is enabled for the text editor. Autocorrect enables the text editor to correct typos.
- **0**: Autocorrect is disabled.
- **1**: Autocorrect is enabled | -| SHOW_PASSWORD_TEXT_INPUT | string | Yes | Yes | Whether password presentation is enabled in the text editor. Password presentation enables the text editor to show password characters when the user types them.
- **0**: Password presentation is disabled.
- **1**: Password presentation is enabled.| +| SELECTOR_VISIBILITY_FOR_INPUT_METHOD | string | Yes | Yes | Whether the input method selector is visible.
- **1**: The input method selector is visible.
- **0**: The input method selector is invisible. | +| AUTO_CAPS_TEXT_INPUT | string | Yes | Yes | Whether automatic capitalization is enabled for the text editor.
- **0**: Automatic capitalization is disabled.
- **1**: Automatic capitalization is enabled. | +| AUTO_PUNCTUATE_TEXT_INPUT | string | Yes | Yes | Whether automatic punctuation is enabled for the text editor. Automatic punctuation enables the text editor to convert two spaces into a period (.) and a space.
- **0**: Automatic punctuation is disabled.
- **1**: Automatic punctuation is enabled. | +| AUTO_REPLACE_TEXT_INPUT | string | Yes | Yes | Whether autocorrect is enabled for the text editor. Autocorrect enables the text editor to correct typos.
- **0**: Autocorrect is disabled.
- **1**: Autocorrect is enabled | +| SHOW_PASSWORD_TEXT_INPUT | string | Yes | Yes | Whether password presentation is enabled in the text editor. Password presentation enables the text editor to show password characters when the user types them.
- **0**: Password presentation is disabled.
- **1**: Password presentation is enabled. | ## network @@ -117,11 +117,11 @@ Provides data items for setting network information. (Not supported yet.) **System capability**: SystemCapability.Applications.Settings.Core -| Name | Type | Readable| Writable| Description | -| ------------------------ | ------ | ---- | ---- | ------------------------------------------------------------ | -| DATA_ROAMING_STATUS | string | Yes | Yes | Whether data roaming is enabled.
**true**: Data roaming is enabled.
**false**: Data roaming is disabled.| -| HTTP_PROXY_CFG | string | Yes | Yes | Host name and port number of the global HTTP proxy. The host name and port number are separated by a colon (:).| -| NETWORK_PREFERENCE_USAGE | string | Yes | Yes | User preferences for the network to use. | +| Name | Type | Readable| Writable| Description | +| ------------------------ | ------ | ---- | ---- |----------------------------------------------------------| +| DATA_ROAMING_STATUS | string | Yes | Yes | Whether data roaming is enabled.
- **true**: Data roaming is enabled.
- **false**: Data roaming is disabled.| +| HTTP_PROXY_CFG | string | Yes | Yes | Host name and port number of the global HTTP proxy. The host name and port number are separated by a colon (:). | +| NETWORK_PREFERENCE_USAGE | string | Yes | Yes | User preferences for the network to use. | ## phone @@ -131,9 +131,9 @@ Provides data items for setting the modes of answering incoming and outgoing cal **System capability**: SystemCapability.Applications.Settings.Core -| Name | Type | Readable| Writable| Description | -| ------------------ | ------ | ---- | ---- | ------------------------------------------------------------ | -| RTT_CALLING_STATUS | string | Yes | Yes | Whether the real-time text (RTT) feature is enabled. If this feature is enabled, incoming and outgoing calls are answered as RTT calls when supported by the device and carrier.
**1**: RTT is enabled.
**0**: RTT is disabled.| +| Name | Type | Readable| Writable| Description | +| ------------------ | ------ | ---- | ---- |--------------------------------------------------------------------------------------------| +| RTT_CALLING_STATUS | string | Yes | Yes | Whether the real-time text (RTT) call feature is enabled. If this feature is enabled, incoming and outgoing calls are answered as RTT calls when supported by the device and carrier.
- **1**: RTT is enabled.
- **0**: RTT is disabled.| ## sound @@ -143,19 +143,19 @@ Provides data items for setting the sound effects. (Not supported yet.) **System capability**: SystemCapability.Applications.Settings.Core -| Name | Type | Readable| Writable| Description | -| ---------------------------- | ------ | ---- | ---- | ------------------------------------------------------------ | +| Name | Type | Readable| Writable| Description | +| ---------------------------- | ------ | ---- | ---- |--------------------------------------------------------------------------| | VIBRATE_WHILE_RINGING | string | Yes | Yes | Whether the device vibrates when it is ringing for an incoming call. This attribute is applicable to the phone and settings applications
and affects only the scenario where the device rings for an incoming call. It does not affect any other application or scenario.| -| DEFAULT_ALARM_ALERT | string | Yes | Yes | Storage area of the system default alarms and alerts. | -| DTMF_TONE_TYPE_WHILE_DIALING | string | Yes | Yes | Type of the dual tone multi-frequency (DTMF) tone played while dialing.
**0**: normal short tone.
**1**: long tone.| -| DTMF_TONE_WHILE_DIALING | string | Yes | Yes | Whether the DTMF tone is played when dialing.
**1**: DTMF tone is played when dialing.
**0**: DTMF tone is not played when dialing.| -| AFFECTED_MODE_RINGER_STREAMS | string | Yes | Yes | Effect on audio streams determined by changes in the ringing mode and Do Not Disturb (DND) mode. If you want a specific audio stream to be affected by changes of the ringing mode and DDN mode, set the corresponding bit to **1**.| -| AFFECTED_MUTE_STREAMS | string | Yes | Yes | Audio streams affected by the mute mode. If you want a specific audio stream to remain muted in mute mode, set the corresponding bit to **1**.| -| DEFAULT_NOTIFICATION_SOUND | string | Yes | Yes | Storage area of the system default notification tone. | -| DEFAULT_RINGTONE | string | Yes | Yes | Storage area of the system default ringtone. | -| SOUND_EFFECTS_STATUS | string | Yes | Yes | Whether the sound feature is available.
**0**: The feature is not available.
**1**: The feature is available. | -| VIBRATE_STATUS | string | Yes | Yes | Whether the device vibrates for an event. This attribute is used inside the system.
**1**: The device vibrates for an event.
**0**: The device does not vibrate for an event.| -| HAPTIC_FEEDBACK_STATUS | string | Yes | Yes | Whether haptic feedback is enabled.
**true**: Haptic feedback is enabled.
**false**: Haptic feedback is disabled.| +| DEFAULT_ALARM_ALERT | string | Yes | Yes | Storage area of the system default alarms and alerts. | +| DTMF_TONE_TYPE_WHILE_DIALING | string | Yes | Yes | Type of the dual tone multi-frequency (DTMF) tone played while dialing.
- **0**: normal short tone.
- **1**: long tone. | +| DTMF_TONE_WHILE_DIALING | string | Yes | Yes | Whether the DTMF tone is played when dialing.
- **1**: DTMF tone is played when dialing.
- **0**: DTMF tone is not played when dialing. | +| AFFECTED_MODE_RINGER_STREAMS | string | Yes | Yes | Effect on audio streams determined by changes in the ringing mode and Do Not Disturb (DND) mode. If you want a specific audio stream to be affected by changes of the ringing mode and DND mode, set the corresponding bit to **1**. | +| AFFECTED_MUTE_STREAMS | string | Yes | Yes | Audio streams affected by the mute mode. If you want a specific audio stream to remain muted in mute mode, set the corresponding bit to **1**. | +| DEFAULT_NOTIFICATION_SOUND | string | Yes | Yes | Storage area of the system default notification tone. | +| DEFAULT_RINGTONE | string | Yes | Yes | Storage area of the system default ringtone. | +| SOUND_EFFECTS_STATUS | string | Yes | Yes | Whether the sound feature is available.
- **0**: The feature is not available.
- **1**: The feature is available. | +| VIBRATE_STATUS | string | Yes | Yes | Whether the device vibrates for an event. This attribute is used inside the system.
- **1**: The device vibrates for an event.
- **0**: The device does not vibrate for an event. | +| HAPTIC_FEEDBACK_STATUS | string | Yes | Yes | Whether haptic feedback is enabled.
- **true**: Haptic feedback is enabled.
- **false**: Haptic feedback is disabled. | ## TTS @@ -181,28 +181,28 @@ Provides data items for setting wireless network information. (Not supported yet **System capability**: SystemCapability.Applications.Settings.Core -| Name | Type | Readable| Writable| Description | -| --------------------------------- | ------ | ---- | ---- | ------------------------------------------------------------ | -| BLUETOOTH_DISCOVER_ABILITY_STATUS | string | Yes | Yes | Whether the device can be discovered or connected by other devices through Bluetooth.
**0**: The device cannot be discovered or connected.
**1**: The device can be connected but cannot be discovered.
**2**: The device can be discovered and connected.| -| BLUETOOTH_DISCOVER_TIMEOUT | string | Yes | Yes | Duration for discovering a device through Bluetooth, in seconds.
After the duration expires, the device cannot be discovered through Bluetooth.| +| Name | Type | Readable| Writable| Description | +| --------------------------------- | ------ | ---- | ---- |----------------------------------------------------------------------------------------------------------| +| BLUETOOTH_DISCOVER_ABILITY_STATUS | string | Yes | Yes | Whether the device can be discovered or connected by other devices through Bluetooth.
- **0**: The device cannot be discovered or connected.
- **1**: The device can be connected but cannot be discovered.
- **2**: The device can be discovered and connected. | +| BLUETOOTH_DISCOVER_TIMEOUT | string | Yes | Yes | Duration for discovering a device through Bluetooth, in seconds.
After the duration expires, the device cannot be discovered through Bluetooth. | | AIRPLANE_MODE_RADIOS | string | Yes | Yes | List of radio signals to be disabled when airplane mode is enabled.
Multiple radio signals are separated by commas (,).
The list can include the following: **BLUETOOTH_RADIO**, **CELL_RADIO**, **NFC_RADIO**, and **WIFI_RADIO**.| -| BLUETOOTH_RADIO | string | Yes | No | A value of **AIRPLANE_MODE_RADIOS** to indicate that Bluetooth is disabled in airplane mode.| -| CELL_RADIO | string | Yes | No | A value of **AIRPLANE_MODE_RADIOS** to indicate that cellular radio is disabled in airplane mode.| -| NFC_RADIO | string | Yes | No | A value of **AIRPLANE_MODE_RADIOS** to indicate that NFC is disabled in airplane mode.| -| WIFI_RADIO | string | Yes | No | A value of **AIRPLANE_MODE_RADIOS** to indicate that Wi-Fi is disabled in airplane mode.| -| BLUETOOTH_STATUS | string | Yes | Yes | Whether Bluetooth is available.
- **true**: Bluetooth is available.
- **false**: Bluetooth is unavailable.| -| OWNER_LOCKDOWN_WIFI_CFG | string | Yes | Yes | Whether the Wi-Fi configuration created by the application of the device owner should be locked down.
- **true**: The Wi-Fi configuration should be locked down.
- **false**: The Wi-Fi configuration should not be locked down.| -| WIFI_DHCP_MAX_RETRY_COUNT | string | Yes | Yes | Maximum number of attempts to obtain an IP address from the DHCP server. | -| WIFI_TO_MOBILE_DATA_AWAKE_TIMEOUT | string | Yes | Yes | Maximum duration to hold a wake lock when waiting for the mobile data connection after the Wi-Fi connection is disconnected. | -| WIFI_STATUS | string | Yes | Yes | Whether Wi-Fi is available.
- **true**: Wi-Fi is available.
- **false**: Wi-Fi is unavailable.| -| WIFI_WATCHDOG_STATUS | string | Yes | Yes | Whether Wi-Fi watchdog is available.
- **true**: Wi-Fi watchdog is available.
- **false**: Wi-Fi watchdog is unavailable.| +| BLUETOOTH_RADIO | string | Yes | No | A value of **AIRPLANE_MODE_RADIOS** to indicate that Bluetooth is disabled in airplane mode. | +| CELL_RADIO | string | Yes | No | A value of **AIRPLANE_MODE_RADIOS** to indicate that cellular radio is disabled in airplane mode. | +| NFC_RADIO | string | Yes | No | A value of **AIRPLANE_MODE_RADIOS** to indicate that NFC is disabled in airplane mode. | +| WIFI_RADIO | string | Yes | No | A value of **AIRPLANE_MODE_RADIOS** to indicate that Wi-Fi is disabled in airplane mode. | +| BLUETOOTH_STATUS | string | Yes | Yes | Whether Bluetooth is available.
- **true**: Bluetooth is available.
- **false**: Bluetooth is unavailable. | +| OWNER_LOCKDOWN_WIFI_CFG | string | Yes | Yes | Whether the Wi-Fi configuration created by the application of the device owner should be locked down.
- **true**: The Wi-Fi configuration should be locked down.
- **false**: The Wi-Fi configuration should not be locked down. | +| WIFI_DHCP_MAX_RETRY_COUNT | string | Yes | Yes | Maximum number of attempts to obtain an IP address from the DHCP server. | +| WIFI_TO_MOBILE_DATA_AWAKE_TIMEOUT | string | Yes | Yes | Maximum duration to hold a wake lock when waiting for the mobile data connection after the Wi-Fi connection is disconnected. | +| WIFI_STATUS | string | Yes | Yes | Whether Wi-Fi is available.
- **true**: Wi-Fi is available.
- **false**: Wi-Fi is unavailable. | +| WIFI_WATCHDOG_STATUS | string | Yes | Yes | Whether Wi-Fi watchdog is available.
- **true**: Wi-Fi watchdog is available.
- **false**: Wi-Fi watchdog is unavailable. | ## settings.setValue10+ setValue(context: Context, name: string, value: string, callback: AsyncCallback\): void -Sets the value for a data item. This API uses an asynchronous callback to return the result. +Sets the value for a data item in the **DEVICE_SHARED** domain of the database. This API uses an asynchronous callback to return the result. **Model restriction**: This API can be used only in the stage model. @@ -212,20 +212,23 @@ Sets the value for a data item. This API uses an asynchronous callback to return **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------- | ---- | ------------------------------------------------------------ | +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- |--------------------------------------------------------------------------------------------------------------------------------------------| | context | Context | Yes | Application context. Only UIAbilityContext and ExtensionContext are supported.
For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-application-context.md).| -| name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items| -| value | string | Yes | Value of the data item. The value range varies by service. | -| callback | AsyncCallback\ | Yes | Callback used to return the result. Returns **true** if the operation is successful; returns **false** otherwise. | +| name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items | +| value | string | Yes | Value of the data item. The value range varies by service. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. The value **true** means that the operation is successful, and **false** means the opposite. | **Example** + ```js -import settings from '@ohos.settings'; +import { settings } from '@kit.BasicServicesKit'; +import { common } from '@kit.AbilityKit'; // Update the value of SCREEN_BRIGHTNESS_STATUS. (As this data item exists in the database, the setValue API will update its value.) -const context: Context = getContext(this); +// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. +const context: Context = this.getUIContext().getHostContext() as common.UIAbilityContext; settings.setValue(context, settings.display.SCREEN_BRIGHTNESS_STATUS, '100', (status) => { console.log('Callback return whether value is set.'); }); @@ -235,7 +238,7 @@ settings.setValue(context, settings.display.SCREEN_BRIGHTNESS_STATUS, '100', (st setValue(context: Context, name: string, value: string): Promise\ -Sets the value for a data item. This API uses a promise to return the result. +Sets the value for a data item in the **DEVICE_SHARED** domain of the database. This API uses a promise to return the result. **Model restriction**: This API can be used only in the stage model. @@ -245,25 +248,28 @@ Sets the value for a data item. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------- | ---- | ------------------------------------------------------------ | +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- |--------------------------------------------------------------------------------------------------------------------------------------------| | context | Context | Yes | Application context. Only UIAbilityContext and ExtensionContext are supported.
For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-application-context.md).| -| name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items| -| value | string | Yes | Value of the data item. The value range varies by service. | +| name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items | +| value | string | Yes | Value of the data item. The value range varies by service. | **Return value** -| Type | Description | -| ----------------- | -------------------------------------------------- | -| Promise\ | Promise used to return the result. Returns **true** if the operation is successful; returns **false** otherwise.| +| Type | Description | +| ----------------- |---------------------------------------| +| Promise\ | Promise used to return the result. The value **true** means that the operation is successful, and **false** means the opposite.| **Example** + ```js -import settings from '@ohos.settings'; +import { settings } from '@kit.BasicServicesKit'; +import { common } from '@kit.AbilityKit'; // Update the value of SCREEN_BRIGHTNESS_STATUS. (As this data item exists in the database, the setValue API will update its value.) -const context: Context = getContext(this); +// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. +const context: Context = this.getUIContext().getHostContext() as common.UIAbilityContext; settings.setValue(context, settings.display.SCREEN_BRIGHTNESS_STATUS, '100').then((status) => { console.log('Callback return whether value is set.'); }); @@ -285,18 +291,18 @@ Sets the value for a data item. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- |---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| context | Context | Yes | Application context. Only UIAbilityContext and ExtensionContext are supported.
For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-application-context.md). | -| name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items | -| value | string | Yes | Value of the data item. The value range varies by service. | +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- |---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| context | Context | Yes | Application context. Only UIAbilityContext and ExtensionContext are supported.
For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-application-context.md). | +| name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items | +| value | string | Yes | Value of the data item. The value range varies by service. | |domainName| string | Yes | Domain name to set.
- **domainName.DEVICE_SHARED**:
   shared device domain
- **domainName.USER_PROPERTY**:
   user property domain
- **domainName.USER_SECURITY**:
   user security domain (for system applications only)| **Return value** -| Type | Description | -| ---------------- | ----------------------------------- | -| Promise\ | Promise used to return the result. Returns **true** if the operation is successful; returns **false** otherwise.| +| Type | Description | +|-------------------|---------------------------------------| +| Promise\ | Promise used to return the result. The value **true** means that the operation is successful, and **false** means the opposite.| **Error codes** @@ -308,11 +314,14 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** + ```js -import settings from '@ohos.settings'; +import { settings } from '@kit.BasicServicesKit'; +import { common } from '@kit.AbilityKit'; // Update the value of SCREEN_BRIGHTNESS_STATUS. (As this data item exists in the database, the setValue API will update its value.) -const context: Context = getContext(this); +// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. +const context: Context = this.getUIContext().getHostContext() as common.UIAbilityContext; settings.setValue(context, settings.display.SCREEN_BRIGHTNESS_STATUS, '100', settings.domainName.DEVICE_SHARED).then((status) => { console.log(`callback:return whether value is set.`) }); @@ -322,7 +331,7 @@ settings.setValue(context, settings.display.SCREEN_BRIGHTNESS_STATUS, '100', set getValue(context: Context, name: string, callback: AsyncCallback\): void -Obtains the value of a data item in the database. This API uses an asynchronous callback to return the result. +Obtains the value of a data item in the **DEVICE_SHARD** domain of the database. This API uses an asynchronous callback to return the result. **Model restriction**: This API can be used only in the stage model. @@ -330,17 +339,21 @@ Obtains the value of a data item in the database. This API uses an asynchronous **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ------------------------------------------------------------ | +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- |--------------------------------------------------------------------------------------------------------------------------------------------| | context | Context | Yes | Application context. Only UIAbilityContext and ExtensionContext are supported.
For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-application-context.md).| -| name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items| -| callback | AsyncCallback\ | Yes | Callback used to return the value of the data item. | +| name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items | +| callback | AsyncCallback\ | Yes | Callback used to return the value of the data item. | **Example** + ```js -import settings from '@ohos.settings'; -const context: Context = getContext(this); +import { settings } from '@kit.BasicServicesKit'; +import { common } from '@kit.AbilityKit'; + +// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. +const context: Context = this.getUIContext().getHostContext() as common.UIAbilityContext; settings.getValue(context, settings.display.SCREEN_BRIGHTNESS_STATUS, (err, value) => { if (err) { console.error(`Failed to get the setting. ${err.message} `); @@ -354,7 +367,7 @@ settings.getValue(context, settings.display.SCREEN_BRIGHTNESS_STATUS, (err, valu getValue(context: Context, name: string): Promise\ -Obtains the value of a data item in the database. This API uses a promise to return the result. +Obtains the value of a data item in the **DEVICE_SHARD** domain of the database. This API uses a promise to return the result. **Model restriction**: This API can be used only in the stage model. @@ -362,10 +375,10 @@ Obtains the value of a data item in the database. This API uses a promise to ret **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------- | ---- | ------------------------------------------------------------ | +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- |--------------------------------------------------------------------------------------------------------------------------------------------| | context | Context | Yes | Application context. Only UIAbilityContext and ExtensionContext are supported.
For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-application-context.md).| -| name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items| +| name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items | **Return value** @@ -375,9 +388,13 @@ Obtains the value of a data item in the database. This API uses a promise to ret **Example** + ```js -import settings from '@ohos.settings'; -const context: Context = getContext(this); +import { settings } from '@kit.BasicServicesKit'; +import { common } from '@kit.AbilityKit'; + +// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. +const context: Context = this.getUIContext().getHostContext() as common.UIAbilityContext; settings.getValue(context, settings.display.SCREEN_BRIGHTNESS_STATUS).then((value) => { console.log(`promise:value -> ${value}`) }); @@ -385,7 +402,7 @@ settings.getValue(context, settings.display.SCREEN_BRIGHTNESS_STATUS).then((valu ## settings.getValue11+ -getValue(context: Context, name: string, domainName: string): Promise\; +getValue(context: Context, name: string, domainName: string): Promise\ Obtains the value of a data item in the database. This API uses a promise to return the result. @@ -398,10 +415,10 @@ Obtains the value of a data item in the database. This API uses a promise to ret **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ------------------------------------------------------------ | -| context | Context | Yes | Application context. Only UIAbilityContext and ExtensionContext are supported.
For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-application-context.md).| -| name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items| +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- |---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| context | Context | Yes | Application context. Only UIAbilityContext and ExtensionContext are supported.
For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-application-context.md). | +| name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items | |domainName| string | Yes | Domain name to set.
- **domainName.DEVICE_SHARED**:
   shared device domain
- **domainName.USER_PROPERTY**:
   user property domain
- **domainName.USER_SECURITY**:
   user security domain (for system applications only)| **Return value** @@ -412,11 +429,14 @@ Obtains the value of a data item in the database. This API uses a promise to ret **Example** + ```js -import settings from '@ohos.settings'; +import { settings } from '@kit.BasicServicesKit'; +import { common } from '@kit.AbilityKit'; // Update the value of SCREEN_BRIGHTNESS_STATUS. (As this data item exists in the database, the getValue API will update its value.) -const context: Context = getContext(this); +// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. +const context: Context = this.getUIContext().getHostContext() as common.UIAbilityContext; settings.getValue(context, settings.display.SCREEN_BRIGHTNESS_STATUS, settings.domainName.DEVICE_SHARED).then((value) => { console.log(`Promise:value -> ${value}`); }); @@ -424,7 +444,7 @@ settings.getValue(context, settings.display.SCREEN_BRIGHTNESS_STATUS, settings.d ## settings.getValueSync10+ -getValueSync(context: Context, name: string, defValue: string): string; +getValueSync(context: Context, name: string, defValue: string): string Obtains the value of a data item. Unlike **getValue**, this API returns the result synchronously. @@ -434,11 +454,11 @@ Obtains the value of a data item. Unlike **getValue**, this API returns the resu **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------- | ---- | ------------------------------------------------------------ | +| Name | Type | Mandatory| Description | +| -------- | ------- | ---- |-------------------------------------------------------------------------------------------------------------------------------------------| | context | Context | Yes | Application context. Only UIAbilityContext and ExtensionContext are supported.
For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-application-context.md).| -| name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items| -| defValue | string | Yes | Default value, which is returned when the value of a data item is not found in the database. Set this parameter as needed.| +| name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items | +| defValue | string | Yes | Default value, which is returned when the value of a data item is not found in the database. Set this parameter as needed. | **Return value** @@ -448,17 +468,20 @@ Obtains the value of a data item. Unlike **getValue**, this API returns the resu **Example** + ```js -import settings from '@ohos.settings'; +import { settings } from '@kit.BasicServicesKit'; +import { common } from '@kit.AbilityKit'; // Obtain the value of SCREEN_BRIGHTNESS_STATUS (this data item already exists in the database). -const context: Context = getContext(this); +// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. +const context: Context = this.getUIContext().getHostContext() as common.UIAbilityContext; let value = settings.getValueSync(context, settings.display.SCREEN_BRIGHTNESS_STATUS, '10'); ``` ## settings.getValueSync11+ -getValueSync(context: Context, name: string, defValue: string, domainName: string): string; +getValueSync(context: Context, name: string, defValue: string, domainName: string): string Obtains the value of a data item. Unlike **getValue**, this API returns the result synchronously. @@ -471,11 +494,11 @@ Obtains the value of a data item. Unlike **getValue**, this API returns the resu **Parameters** -| Name | Type | Mandatory| Description | -|------------| ---------------------- | ---- | ------------------------------------------------------------ | -| context | Context | Yes | Application context. Only UIAbilityContext and ExtensionContext are supported.
For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-application-context.md).| -| name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items| -| defValue | string | Yes | Value of the data item. The value range varies by service. | +| Name | Type | Mandatory| Description | +|------------| ---------------------- | ---- |--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| context | Context | Yes | Application context. Only UIAbilityContext and ExtensionContext are supported.
For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-application-context.md). | +| name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items | +| defValue | string | Yes | Default value, which is returned when the value of a data item is not found in the database. Set this parameter as needed. | | domainName | string | Yes | Domain name to set.
- **domainName.DEVICE_SHARED**:
   shared device domain
- **domainName.USER_PROPERTY**:
   user property domain
- **domainName.USER_SECURITY**:
   user security domain (for system applications only)| @@ -487,11 +510,14 @@ Obtains the value of a data item. Unlike **getValue**, this API returns the resu **Example** + ```js -import settings from '@ohos.settings'; +import { settings } from '@kit.BasicServicesKit'; +import { common } from '@kit.AbilityKit'; // Update the value of .SCREEN_BRIGHTNESS_STATUS (this data item already exists in the database). -const context: Context = getContext(this); +// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. +const context: Context = this.getUIContext().getHostContext() as common.UIAbilityContext; let value = settings.getValueSync(context, settings.display.SCREEN_BRIGHTNESS_STATUS, '100', settings.domainName.DEVICE_SHARED); ``` @@ -512,25 +538,28 @@ Sets the value for a data item. Unlike **setValue**, this API returns the result **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------- | ---- | ------------------------------------------------------------ | +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- |--------------------------------------------------------------------------------------------------------------------------------------------| | context | Context | Yes | Application context. Only UIAbilityContext and ExtensionContext are supported.
For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-application-context.md).| -| name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items| -| value | string | Yes | Value of the data item. The value range varies by service. | +| name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items | +| value | string | Yes | Value of the data item. The value range varies by service. | **Return value** | Type | Description | | ------- | ------------------------------------------------------------ | -| boolean | Result indicating whether the value is set successfully. Returns **true** if the value is set successfully; returns **false** otherwise.| +| boolean | Result indicating whether the value is set successfully. Returns **true** if the operation is successful; returns **false** otherwise.| **Example** + ```js -import settings from '@ohos.settings'; +import { settings } from '@kit.BasicServicesKit'; +import { common } from '@kit.AbilityKit'; // Update the value of SCREEN_BRIGHTNESS_STATUS. (As this data item exists in the database, the setValueSync API will update its value.) -const context: Context = getContext(this); +// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. +const context: Context = this.getUIContext().getHostContext() as common.UIAbilityContext; let ret = settings.setValueSync(context, settings.display.SCREEN_BRIGHTNESS_STATUS, '100'); ``` @@ -553,18 +582,18 @@ Sets the value for a data item. Unlike **setValue**, this API returns the result **Parameters** -| Name | Type | Mandatory| Description | -|---------| ---------------------- | ---- | ------------------------------------------------------------ | -| context | Context | Yes | Application context. Only UIAbilityContext and ExtensionContext are supported.
For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-application-context.md).| -| name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items| -| value | string | Yes | Value of the data item. The value range varies by service. | +| Name | Type | Mandatory| Description | +|---------| ---------------------- | ---- |---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| context | Context | Yes | Application context. Only UIAbilityContext and ExtensionContext are supported.
For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-application-context.md). | +| name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items | +| value | string | Yes | Value of the data item. The value range varies by service. | | domainName | string | Yes | Domain name to set.
- **domainName.DEVICE_SHARED**:
   shared device domain
- **domainName.USER_PROPERTY**:
   user property domain
- **domainName.USER_SECURITY**:
   user security domain (for system applications only)| **Return value** | Type | Description | | ---------------- | ----------------------------------- | -| boolean | Result indicating whether the value is set successfully. Returns **true** if the value is set successfully; returns **false** otherwise.| +| boolean | Result indicating whether the value is set successfully. Returns **true** if the operation is successful; returns **false** otherwise.| **Error codes** @@ -576,11 +605,14 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** + ```js -import settings from '@ohos.settings'; +import { settings } from '@kit.BasicServicesKit'; +import { common } from '@kit.AbilityKit'; // Update the value of SCREEN_BRIGHTNESS_STATUS. (As this data item exists in the database, the setValueSync API will update its value.) -const context: Context = getContext(this); +// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. +const context: Context = this.getUIContext().getHostContext() as common.UIAbilityContext; let ret = settings.setValueSync(context, settings.display.SCREEN_BRIGHTNESS_STATUS, '100', settings.domainName.DEVICE_SHARED); ``` @@ -588,7 +620,7 @@ let ret = settings.setValueSync(context, settings.display.SCREEN_BRIGHTNESS_STAT registerKeyObserver(context: Context, name: string, domainName: string, observer:AsyncCallback\): boolean -Registers an observer in the specified context so that the specified data item can be observed in the specified domain name. When the data item value changes, the registered callback is called. Returns **true** if the registration is successful; returns **false** otherwise. +Registers an observer in the specified context so that the specified data item can be observed in the specified domain name. When the data item value changes, the registered callback is called. Returns **true** if the operation is successful; returns **false** otherwise. **Model restriction**: This API can be used only in the stage model. @@ -596,25 +628,28 @@ Registers an observer in the specified context so that the specified data item c **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ------------------------------------------------------------ | -| context | Context | Yes | Application context. Only UIAbilityContext and ExtensionContext are supported.
For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-application-context.md).| -| name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items| +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- |---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| context | Context | Yes | Application context. Only UIAbilityContext and ExtensionContext are supported.
For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-application-context.md). | +| name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items | |domainName| string | Yes | Domain name to set.
- **domainName.DEVICE_SHARED**:
   shared device domain
- **domainName.USER_PROPERTY**:
   user property domain
- **domainName.USER_SECURITY**:
   user security domain (for system applications only)| -|observer | AsyncCallback\ | Yes | Callback used to return the value of the data item. | +|observer | AsyncCallback\ | Yes | Callback used to return the value of the data item. | **Return value** -| Type | Description | -| ---------------- | ----------------------------------- | -| boolean | Result indicating whether the value is set successfully. Returns **true** if the value is set successfully; returns **false** otherwise.| +| Type | Description | +| ---------------- |----------------------------------------| +| boolean | Result indicating whether an observer is successfully registered. Returns **true** if the operation is successful; returns **false** otherwise.| **Example** + ```js -import settings from '@ohos.settings'; +import { settings } from '@kit.BasicServicesKit'; +import { common } from '@kit.AbilityKit'; -const context: Context = getContext(this); +// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. +const context: Context = this.getUIContext().getHostContext() as common.UIAbilityContext; settings.registerKeyObserver(context, settings.display.SCREEN_BRIGHTNESS_STATUS, settings.domainName.DEVICE_SHARED, (err, val) => { if (err) { console.error(`Failed to get the setting. ${err.message} `); @@ -636,24 +671,27 @@ Unregisters the observer under the specified domain name. This API returns the r **System capability**: SystemCapability.Applications.Settings.Core -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ------------------------------------------------------------ | -| context | Context | Yes | Application context. Only UIAbilityContext and ExtensionContext are supported.
For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-application-context.md).| -| name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items| +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- |--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| context | Context | Yes | Application context. Only UIAbilityContext and ExtensionContext are supported.
For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-application-context.md). | +| name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items | |domainName| string | Yes | Domain name to set.
- **domainName.DEVICE_SHARED**:
   shared device domain
- **domainName.USER_PROPERTY**:
   user property domain
- **domainName.USER_SECURITY**:
   user security domain (for system applications only)| **Return value** | Type | Description | | ---------------- | ----------------------------------- | -| boolean | Whether the observer under the specified domain name is successfully unregistered. Returns **true** if the deregistration is successful; returns **false** otherwise.| +| boolean | Result indicating whether the observer under the specified domain name is successfully unregistered. Returns **true** if the operation is successful; returns **false** otherwise.| **Example** + ```js -import settings from '@ohos.settings'; +import { settings } from '@kit.BasicServicesKit'; +import { common } from '@kit.AbilityKit'; -const context: Context = getContext(this); +// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. +const context: Context = this.getUIContext().getHostContext() as common.UIAbilityContext; let ret = settings.unregisterKeyObserver(context, settings.display.SCREEN_BRIGHTNESS_STATUS, settings.domainName.DEVICE_SHARED); ``` @@ -669,15 +707,15 @@ Opens the network manager settings page. This API uses a promise to return the r **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- |---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| context | Context | Yes | Application context. Only UIAbilityContext and ExtensionContext are supported.
For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-application-context.md). | +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- |--------------------------------------------------------------------------------------------------------------------------------------------| +| context | Context | Yes | Application context. Only UIAbilityContext and ExtensionContext are supported.
For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-application-context.md).| **Return value** -| Type | Description | -| ---------------- | ----------------------------------- | -| Promise\ | Promise used to return the result. Returns **true** if the operation is successful; returns **false** otherwise.| +| Type | Description | +| ---------------- |---------------------------------------| +| Promise\ | Promise used to return the result. The value **true** means that the operation is successful, and **false** means the opposite.| **Error codes** @@ -690,11 +728,14 @@ For details about the error codes, see [Settings Error Codes](./errorcode-settin **Example** + ```js -import settings from '@ohos.settings'; +import { settings } from '@kit.BasicServicesKit'; +import { common } from '@kit.AbilityKit'; // Redirect to the network manager settings page. -const context: Context = getContext(this); +// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. +const context: Context = this.getUIContext().getHostContext() as common.UIAbilityContext; settings.openNetworkManagerSettings(context).then((status) => { console.log(`callback:return whether settings is open.`) }); @@ -712,7 +753,7 @@ Enables or disables airplane mode. This API uses an asynchronous callback to ret | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ----------------------------------------------- | -| enable | boolean | Yes | Whether airplane mode is enabled. **true** means that airplane mode is enabled, and **false** means the opposite.| +| enable | boolean | Yes | Whether airplane mode is enabled. The value **true** means that airplane mode is enabled, and **false** means the opposite.| | callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -721,7 +762,7 @@ Enables or disables airplane mode. This API uses an asynchronous callback to ret let isEnabled :boolean = true; settings.enableAirplaneMode(isEnabled, (err:Error) => { if (err) { - console.log('Failed to enable AirplaneMode.'); + console.error('Failed to enable AirplaneMode.'); return; } console.log('Return true if enable.'); @@ -740,7 +781,7 @@ Enables or disables airplane mode. This API uses a promise to return the result. | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ----------------------------------------------- | -| enable | boolean | Yes | Whether airplane mode is enabled. **true** means that airplane mode is enabled, and **false** means the opposite.| +| enable | boolean | Yes | Whether airplane mode is enabled. The value **true** means that airplane mode is enabled, and **false** means the opposite.| **Return value** @@ -755,7 +796,7 @@ let isEnabled :boolean = true; settings.enableAirplaneMode(isEnabled).then(() => { console.log('Succeeded in enabling AirplaneMode.'); }).catch((err:Error) => { - console.log(`Failed to enable AirplaneMode. Cause: ${err}`); + console.error(`Failed to enable AirplaneMode. Cause: ${err}`); }) ``` @@ -771,7 +812,7 @@ Checks whether the application can be displayed in a floating window. This API u | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | ------------------------------------------------------------ | -| callback | AsyncCallback\ | Yes | Callback used to return the result.
The value **true** means the application can be displayed in a floating window; **false** means the opposite.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.
The value **true** means that the application can be displayed in a floating window, and **false** means the opposite.| **Example** @@ -797,7 +838,7 @@ Checks whether the application can be displayed in a floating window. This API u | Type | Description | | ----------------- | ------------------------------------------------------------ | -| Promise\ | Promise used to return the result.
The value **true** means the application can be displayed in a floating window; **false** means the opposite.| +| Promise\ | Promise used to return the result.
The value **true** means that the application can be displayed in a floating window, and **false** means the opposite.| **Example** @@ -817,8 +858,8 @@ Obtains the URI of a data item. (Not supported yet.) **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------------------------------------------------------------ | +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- |---------------------------------------------------------------| | name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items| **Return value** @@ -848,10 +889,10 @@ Obtains the URI of a data item. This API uses an asynchronous callback to return **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ------------------------------------------------------------ | +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- |---------------------------------------------------------------| | name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items| -| callback | AsyncCallback\ | Yes | Callback used to return the result. Obtains the URI of a data item. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. Obtains the URI of a data item. | **Example** @@ -875,8 +916,8 @@ Obtains the URI of a data item. This API uses a promise to return the result. (N **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------------------------------------------------------------ | +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- |---------------------------------------------------------------| | name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items| **Return value** @@ -899,7 +940,7 @@ settings.getURI(settings.display.SCREEN_BRIGHTNESS_STATUS).then((uri:string) => getValue(dataAbilityHelper: DataAbilityHelper, name: string, callback: AsyncCallback\): void -Obtains the value of a data item in the database. This API uses an asynchronous callback to return the result. +Obtains the value of a data item in the **DEVICE_SHARD** domain of the database. This API uses an asynchronous callback to return the result. > **NOTE** > @@ -911,11 +952,11 @@ Obtains the value of a data item in the database. This API uses an asynchronous **Parameters** -| Name | Type | Mandatory| Description | -| ----------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| dataAbilityHelper | [DataAbilityHelper](../apis-ability-kit/js-apis-inner-ability-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. | +| Name | Type | Mandatory| Description | +| ----------------- | ------------------------------------------------------------ | ---- |---------------------------------------------------------------| +| dataAbilityHelper | [DataAbilityHelper](../apis-ability-kit/js-apis-inner-ability-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. | | name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items| -| callback | AsyncCallback\ | Yes | Callback used to return the value of the data item. | +| callback | AsyncCallback\ | Yes | Callback used to return the value of the data item. | **Example** @@ -937,7 +978,7 @@ settings.getValue(helper, settings.display.SCREEN_BRIGHTNESS_STATUS, (err:Error, getValue(dataAbilityHelper: DataAbilityHelper, name: string): Promise\ -Obtains the value of a data item in the database. This API uses a promise to return the result. +Obtains the value of a data item in the **DEVICE_SHARD** domain of the database. This API uses a promise to return the result. > **NOTE** > @@ -949,16 +990,16 @@ Obtains the value of a data item in the database. This API uses a promise to ret **Parameters** -| Name | Type | Mandatory| Description | -| ----------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| dataAbilityHelper | [DataAbilityHelper](../apis-ability-kit/js-apis-inner-ability-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. | +| Name | Type | Mandatory| Description | +| ----------------- | ------------------------------------------------------------ | ---- |---------------------------------------------------------------| +| dataAbilityHelper | [DataAbilityHelper](../apis-ability-kit/js-apis-inner-ability-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. | | name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items| **Return value** -| Type | Description | -| ---------------- | ----------------------------------- | -| Promise\ | Promise used to return the result. return the value of the data item.| +| Type | Description | +| ---------------- |-----------------------| +| Promise\ | Promise used to return the result.| **Example** @@ -988,11 +1029,11 @@ Obtains the value of a data item. Unlike **getValue**, this API returns the resu **Parameters** -| Name | Type | Mandatory| Description | -| ----------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| dataAbilityHelper | [DataAbilityHelper](../apis-ability-kit/js-apis-inner-ability-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. | +| Name | Type | Mandatory| Description | +| ----------------- | ------------------------------------------------------------ | ---- |--------------------------------------------------------------| +| dataAbilityHelper | [DataAbilityHelper](../apis-ability-kit/js-apis-inner-ability-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. | | name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items| -| defValue | string | Yes | Default value, which is returned when the value of a data item is not found in the database. Set this parameter as needed.| +| defValue | string | Yes | Default value, which is returned when the value of a data item is not found in the database. Set this parameter as needed. | **Return value** @@ -1032,17 +1073,17 @@ Sets the value for a data item. Unlike **setValue**, this API returns the result **Parameters** -| Name | Type | Mandatory| Description | -| ----------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| dataAbilityHelper | [DataAbilityHelper](../apis-ability-kit/js-apis-inner-ability-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. | +| Name | Type | Mandatory| Description | +| ----------------- | ------------------------------------------------------------ | ---- |---------------------------------------------------------------| +| dataAbilityHelper | [DataAbilityHelper](../apis-ability-kit/js-apis-inner-ability-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. | | name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items| -| value | string | Yes | Value of the data item. The value range varies by service. | +| value | string | Yes | Value of the data item. The value range varies by service. | **Return value** | Type | Description | | ------- | ------------------------------------------------------------ | -| boolean | Result indicating whether the value is set successfully. Returns **true** if the value is set successfully; returns **false** otherwise.| +| boolean | Result indicating whether the value is set successfully. Returns **true** if the operation is successful; returns **false** otherwise.| **Example** diff --git a/en/application-dev/reference/apis-basic-services-kit/js-apis-system-battery.md b/en/application-dev/reference/apis-basic-services-kit/js-apis-system-battery.md index 2d443a84824..499df99c0a3 100644 --- a/en/application-dev/reference/apis-basic-services-kit/js-apis-system-battery.md +++ b/en/application-dev/reference/apis-basic-services-kit/js-apis-system-battery.md @@ -62,5 +62,5 @@ Defines a response that returns the charging status and remaining power of the d | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| charging | boolean | Yes| No| Whether the battery is being charged.| +| charging | boolean | Yes| No| Whether the battery is being charged. The value **true** indicates that the battery is being changed; **false** indicates the opposite. The default value is **false**.| | level | number | Yes| No| Current battery level, which ranges from **0.00** to **1.00**.| diff --git a/en/application-dev/reference/apis-basic-services-kit/js-apis-system-brightness.md b/en/application-dev/reference/apis-basic-services-kit/js-apis-system-brightness.md index 1c64592c5f6..9099ab54004 100644 --- a/en/application-dev/reference/apis-basic-services-kit/js-apis-system-brightness.md +++ b/en/application-dev/reference/apis-basic-services-kit/js-apis-system-brightness.md @@ -105,7 +105,7 @@ Obtains the screen brightness adjustment mode. setMode(options?: SetBrightnessModeOptions): void -Sets the screen brightness adjustment mode. +Sets the screen brightness mode. **System capability**: SystemCapability.PowerManager.DisplayPowerManager.Lite @@ -133,7 +133,7 @@ Sets the screen brightness adjustment mode. setKeepScreenOn(options?: SetKeepScreenOnOptions): void ->This API is no longer maintained since API version 7. You are advised to use [window.setWindowKeepScreenOn()](../apis-arkui/js-apis-window.md#setwindowkeepscreenon9). +>This API is no longer maintained since API version 7. You are advised to use [window.setWindowKeepScreenOn()](../apis-arkui/arkts-apis-window-Window.md#setwindowkeepscreenon9). Sets whether to always keep the screen on. Call this API in **onShow()**. @@ -195,7 +195,7 @@ Defines a response that returns the screen brightness. ## GetBrightnessModeOptions(deprecated) -Defines the options for obtaining the screen brightness mode. +Options for obtaining the screen brightness mode. **System capability**: SystemCapability.PowerManager.DisplayPowerManager.Lite diff --git a/en/application-dev/reference/apis-basic-services-kit/js-apis-system-capability-sys.md b/en/application-dev/reference/apis-basic-services-kit/js-apis-system-capability-sys.md index 61e811abd3c..c8e7bcfd580 100644 --- a/en/application-dev/reference/apis-basic-services-kit/js-apis-system-capability-sys.md +++ b/en/application-dev/reference/apis-basic-services-kit/js-apis-system-capability-sys.md @@ -37,10 +37,10 @@ try { if (err == undefined) { console.log("get system capabilities:" + data) } else { - console.log(" get system capabilities err:" + err) + console.error(" get system capabilities err:" + err) }}); }catch(e){ - console.log("get unexpected error: " + e); + console.error("get unexpected error: " + e); } ``` @@ -66,10 +66,10 @@ try { systemcapability.querySystemCapabilities().then((value:string) => { console.log("get system capabilities: " + value); }).catch((err:Error) => { - console.log("get system capabilities error: " + err); + console.error("get system capabilities error: " + err); }); }catch(e){ - console.log("get unexpected error: " + e); + console.error("get unexpected error: " + e); } ``` diff --git a/en/application-dev/reference/apis-basic-services-kit/js-apis-system-date-time-sys.md b/en/application-dev/reference/apis-basic-services-kit/js-apis-system-date-time-sys.md index 4313fef93fc..9923e71489d 100644 --- a/en/application-dev/reference/apis-basic-services-kit/js-apis-system-date-time-sys.md +++ b/en/application-dev/reference/apis-basic-services-kit/js-apis-system-date-time-sys.md @@ -398,7 +398,7 @@ For details about the error codes, see [Time and Time Zone Service Error Codes]( | ID| Error Message | |-------|-------------------------------------------------------------------------------------------------------------| -| 13000002 | updateNtpTime() is not called successfully. | +| 13000002 | Location NTP time of the system is invalid. | | 202 | Permission verification failed. A non-system application calls a system API. | **Example** diff --git a/en/application-dev/reference/apis-basic-services-kit/js-apis-system-device.md b/en/application-dev/reference/apis-basic-services-kit/js-apis-system-device.md index 601851189d5..ff28e12e615 100644 --- a/en/application-dev/reference/apis-basic-services-kit/js-apis-system-device.md +++ b/en/application-dev/reference/apis-basic-services-kit/js-apis-system-device.md @@ -39,7 +39,7 @@ Defines the parameters for obtaining the device information. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| success | (data: DeviceResponse)=> void| No| Called when an API call is successful. **data** indicates the returned device information. For details, see [DeviceResponse](#deviceresponsedeprecated).| +| success | (data: DeviceResponse) => void | No| Called when an API call is successful. **data** indicates the returned device information. For details, see [DeviceResponse](#deviceresponsedeprecated).| | fail | (data: any,code:number)=> void| No| Called when an API call has failed. **code** indicates the error code returned upon a failure.
**code:200**: Certain information could not be obtained.| | complete | () => void| No| Called when an API call is complete.| diff --git a/en/application-dev/reference/apis-basic-services-kit/js-apis-system-parameterEnhance-sys.md b/en/application-dev/reference/apis-basic-services-kit/js-apis-system-parameterEnhance-sys.md index 7b1982654db..9669077dc2e 100644 --- a/en/application-dev/reference/apis-basic-services-kit/js-apis-system-parameterEnhance-sys.md +++ b/en/application-dev/reference/apis-basic-services-kit/js-apis-system-parameterEnhance-sys.md @@ -1,7 +1,6 @@ # @ohos.systemParameterEnhance (System Parameter) (System API) -The **SystemParameter** module provides system services with easy access to key-value pairs. You can use the APIs provided by this module to describe the service status and change the service behavior. The basic operation primitives are get and set. You can obtain the values of system parameters through getter APIs and modify the values through setter APIs. -For details about the system parameter design principles and definitions, see [Parameter Management](../../../device-dev/subsystems/subsys-boot-init-sysparam.md). +The **SystemParameter** module provides system services with easy access to key-value pairs. You can use the APIs provided by this module to describe the service status and change the service behavior. The basic operation primitives are get and set. You can obtain the values of system parameters through getter APIs and modify the values through setter APIs. For details about the system parameter design principles and definitions, see [Parameter Management](../../../device-dev/subsystems/subsys-boot-init-sysparam.md). > **NOTE** > @@ -54,7 +53,7 @@ try { let info: string = systemParameterEnhance.getSync("const.ohos.apiversion"); console.log(JSON.stringify(info)); } catch(e) { - console.log("getSync unexpected error: " + e); + console.error("getSync unexpected error: " + e); } ``` @@ -62,7 +61,7 @@ try { get(key: string, callback: AsyncCallback<string>): void -Obtains the value of the system parameter with the specified key. +Obtains the value of the system parameter with the specified key. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Startup.SystemInfo @@ -94,10 +93,10 @@ try { if (err == undefined) { console.log("get test.parameter.key value success:" + data) } else { - console.log(" get test.parameter.key value err:" + err.code) + console.error(" get test.parameter.key value err:" + err.code) }}); } catch(e) { - console.log("get unexpected error: " + e); + console.error("get unexpected error: " + e); } ``` @@ -138,11 +137,11 @@ try { if (err == undefined) { console.log("get test.parameter.key value success:" + data) } else { - console.log(" get test.parameter.key value err:" + err.code) + console.error(" get test.parameter.key value err:" + err.code) } }); } catch(e) { - console.log("get unexpected error:" + e) + console.error("get unexpected error:" + e) } ``` @@ -188,10 +187,10 @@ try { p.then((value: string) => { console.log("get test.parameter.key success: " + value); }).catch((err: BusinessError) => { - console.log("get test.parameter.key error: " + err.code); + console.error("get test.parameter.key error: " + err.code); }); } catch(e) { - console.log("get unexpected error: " + e); + console.error("get unexpected error: " + e); } ``` @@ -229,7 +228,7 @@ import { BusinessError } from '@kit.BasicServicesKit'; try { systemParameterEnhance.setSync("test.parameter.key", "default"); } catch(e) { - console.log("set unexpected error: " + e); + console.error("set unexpected error: " + e); } ``` @@ -270,10 +269,10 @@ try { if (err == undefined) { console.log("set test.parameter.key value success :" + data) } else { - console.log("set test.parameter.key value err:" + err.code) + console.error("set test.parameter.key value err:" + err.code) }}); } catch(e) { - console.log("set unexpected error: " + e); + console.error("set unexpected error: " + e); } ``` @@ -319,9 +318,9 @@ try { p.then((value: void) => { console.log("set test.parameter.key success: " + value); }).catch((err: BusinessError) => { - console.log(" set test.parameter.key error: " + err.code); + console.error(" set test.parameter.key error: " + err.code); }); } catch(e) { - console.log("set unexpected error: " + e); + console.error("set unexpected error: " + e); } ``` diff --git a/en/application-dev/reference/apis-basic-services-kit/js-apis-system-time.md b/en/application-dev/reference/apis-basic-services-kit/js-apis-system-time.md index d40a5da23a5..ef39e4669f1 100644 --- a/en/application-dev/reference/apis-basic-services-kit/js-apis-system-time.md +++ b/en/application-dev/reference/apis-basic-services-kit/js-apis-system-time.md @@ -154,7 +154,7 @@ Obtains the time elapsed since system startup, excluding the deep sleep time. Th | Name | Type | Mandatory| Description | | -------- | ---------- | ---- | -------------------------- | | isNano | boolean | Yes | Whether the time to return is in nanoseconds.
- **true**: in nanoseconds.
- **false**: in milliseconds.| -| callback | AsyncCallback<number> | Yes | Callback used to return the time.| +| callback | AsyncCallback<number> | Yes | Callback used to return the result.| **Error codes** @@ -195,7 +195,7 @@ Obtains the time elapsed since system startup, excluding the deep sleep time. Th | Name | Type | Mandatory| Description | | -------- | -------------- | ---- | --------------------- | -| callback | AsyncCallback<number> | Yes | Callback used to return the time.| +| callback | AsyncCallback<number> | Yes | Callback used to return the result.| **Error codes** @@ -236,7 +236,7 @@ Obtains the time elapsed since system startup, excluding the deep sleep time. Th | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ----------------------------------- | -| isNano | boolean | No | Whether the time to return is in nanoseconds. The default value is **false**.
The default value is false.
- **true**: in nanoseconds.
- **false**: in milliseconds.| +| isNano | boolean | No | Whether the time to return is in nanoseconds. The default value is **false**.
- **true**: in nanoseconds.
- **false**: in milliseconds.| **Return value** @@ -282,7 +282,7 @@ Obtains the time elapsed since system startup, including the deep sleep time. Th | Name | Type | Mandatory| Description | | -------- | --------------- | ---- | ------------------------------- | | isNano | boolean | Yes | Whether the time to return is in nanoseconds.
- **true**: in nanoseconds.
- **false**: in milliseconds.| -| callback | AsyncCallback<number> | Yes | Callback used to return the time. | +| callback | AsyncCallback<number> | Yes | Callback used to return the result. | **Error codes** @@ -323,7 +323,7 @@ Obtains the time elapsed since system startup, including the deep sleep time. Th | Name | Type | Mandatory| Description | | -------- | --------- | ---- | --------------------------- | -| callback | AsyncCallback<number> | Yes | Callback used to return the time. | +| callback | AsyncCallback<number> | Yes | Callback used to return the result. | **Error codes** diff --git a/en/application-dev/reference/apis-basic-services-kit/js-apis-system-timer-sys.md b/en/application-dev/reference/apis-basic-services-kit/js-apis-system-timer-sys.md index 836900e02cb..8c059abb456 100644 --- a/en/application-dev/reference/apis-basic-services-kit/js-apis-system-timer-sys.md +++ b/en/application-dev/reference/apis-basic-services-kit/js-apis-system-timer-sys.md @@ -35,11 +35,11 @@ Defines the initialization options for **createTimer**. | Name | Type | Mandatory| Description | |-----------| --------------------------------------------- | ---- |------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| type | number | Yes | Timer types. Use pipe (\|) symbol to combine two or more types.
**1**: CPU time type. (The start time of the timer cannot be later than the current system time.)
**2**: wakeup type.
**4**: exact type. (If an application is frozen, the timer is also frozen. In addition, the timer is controlled by a unified heartbeat. Therefore, even a timer of the exact type cannot be triggered at specified time.)
**8**: idle timer type (supported only for system services, but not applications).| +| type | number | Yes | Timer types. Use pipe (\|) symbol|to combine two or more types.
**1**: CPU time type. (The start time of the timer cannot be later than the current system time.)
**2**: wakeup type.
**4**: exact type. (If an application is frozen, the timer is also frozen. In addition, the timer is controlled by a unified heartbeat. Therefore, even a timer of the exact type cannot be triggered at specified time.)
**8**: idle timer type (supported only for system services, but not applications).| | repeat | boolean | Yes | Whether the timer is a repeating timer.
The value **true** means that the timer is a repeating timer, and **false** means that the timer is a one-shot timer. | -| autoRestore15+ | boolean | No | Whether the timer is restored after the device is restarted.
The value **true** means that the timer is restored after the restart, and the value **false** means the opposite.
This parameter can be set to **true** only for timers that are not of the **TIMER_TYPE_REALTIME** type and have **wantAgent** configured. | | | | -| name15+ | string | No| Timer name, with a maximum length of 64 bytes.
A UID cannot contain two timers with the same name. If a timer with the same name as an existing timer is created, the existing timer is destroyed.| -| interval | number | No | Repeat interval.
For a repeating timer, the minimum value of **interval** is 1s and the maximum value is 365 days. It is recommended that the value be greater than or equal to 5000 ms.
For a one-shot timer, the value is **0**. | +| autoRestore15+ | boolean | No | Whether the timer is restored after the device is restarted.
The value **true** means that the timer is restored after the restart, and the value **false** means the opposite.
This parameter can be set to **true** only for timers that are not of the **TIMER_TYPE_REALTIME** type and have **wantAgent** configured. | | | | +| name15+ | string | No| Timer name, with a maximum length of 64 bytes.
A UID cannot contain two timers with the same name. If a timer with the same name as an existing timer is created, the existing timer is destroyed.| +| interval | number | No | Repeat interval. Default value: **0**.
For a repeating timer, the minimum value of **interval** is 1s and the maximum value is 365 days. It is recommended that the value be greater than or equal to 5000 ms.
For a one-shot timer, the value is **0**. | | wantAgent | WantAgent | No | **WantAgent** object of the notification to be sent when the timer expires. (An application MainAbility can be started, but not a Service ability.) | | callback | void | No | Callback to be executed by the user. | @@ -82,14 +82,14 @@ let options: systemTimer.TimerOptions = { try { systemTimer.createTimer(options, (error: BusinessError, timerId: Number) => { if (error) { - console.info(`Failed to create a timer. Message: ${error.message}, code: ${error.code}`); + console.error(`Failed to create timer. message: ${error.message}, code: ${error.code}`); return; } console.info(`Succeeded in creating a timer. timerId: ${timerId}`); }); } catch(e) { let error = e as BusinessError; - console.info(`Failed to create a timer. Message: ${error.message}, code: ${error.code}`); + console.error(`Failed to create timer. message: ${error.message}, code: ${error.code}`); } ``` @@ -137,11 +137,11 @@ try { systemTimer.createTimer(options).then((timerId: Number) => { console.info(`Succeeded in creating a timer. timerId: ${timerId}`); }).catch((error: BusinessError) => { - console.info(`Failed to create a timer. Message: ${error.message}, code: ${error.code}`); + console.error(`Failed to create timer. message: ${error.message}, code: ${error.code}`); }); } catch(e) { let error = e as BusinessError; - console.info(`Failed to create a timer. Message: ${error.message}, code: ${error.code}`); + console.error(`Failed to create timer. message: ${error.message}, code: ${error.code}`); } ``` @@ -186,18 +186,18 @@ try { systemTimer.createTimer(options).then((timerId: number) => { systemTimer.startTimer(timerId, triggerTime, (error: BusinessError) => { if (error) { - console.info(`Failed to start the timer. Message: ${error.message}, code: ${error.code}`); + console.error(`Failed to start timer. message: ${error.message}, code: ${error.code}`); return; } console.info(`Succeeded in starting the timer.`); }); console.info(`Succeeded in creating a timer. timerId: ${timerId}`); }).catch((error: BusinessError) => { - console.info(`Failed to create a timer. Message: ${error.message}, code: ${error.code}`); + console.error(`Failed to create timer. message: ${error.message}, code: ${error.code}`); }); } catch(e) { let error = e as BusinessError; - console.info(`Failed to create a timer. Message: ${error.message}, code: ${error.code}`); + console.error(`Failed to create timer. message: ${error.message}, code: ${error.code}`); } ``` @@ -248,15 +248,15 @@ try { systemTimer.startTimer(timerId, triggerTime).then(() => { console.info(`Succeeded in starting the timer.`); }).catch((error: BusinessError) => { - console.info(`Failed to start the timer. Message: ${error.message}, code: ${error.code}`); + console.error(`Failed to start timer. message: ${error.message}, code: ${error.code}`); }); console.info(`Succeeded in creating a timer. timerId: ${timerId}`); }).catch((error: BusinessError) => { - console.info(`Failed to create a timer. Message: ${error.message}, code: ${error.code}`); + console.error(`Failed to create timer. message: ${error.message}, code: ${error.code}`); }); } catch(e) { let error = e as BusinessError; - console.info(`Failed to create a timer. Message: ${error.message}, code: ${error.code}`); + console.error(`Failed to create timer. message: ${error.message}, code: ${error.code}`); } ``` @@ -301,18 +301,18 @@ try { systemTimer.startTimer(timerId, triggerTime); systemTimer.stopTimer(timerId, (error: BusinessError) => { if (error) { - console.info(`Failed to stop the timer. Message: ${error.message}, code: ${error.code}`); + console.error(`Failed to stop timer. message: ${error.message}, code: ${error.code}`); return; } console.info(`Succeeded in stopping the timer.`); }); console.info(`Succeeded in creating a timer. timerId: ${timerId}`); }).catch((error: BusinessError) => { - console.info(`Failed to create a timer. Message: ${error.message}, code: ${error.code}`); + console.error(`Failed to create timer. message: ${error.message}, code: ${error.code}`); }); } catch(e) { let error = e as BusinessError; - console.info(`Failed to create a timer. Message: ${error.message}, code: ${error.code}`); + console.error(`Failed to create timer. message: ${error.message}, code: ${error.code}`); } ``` @@ -363,15 +363,15 @@ try { systemTimer.stopTimer(timerId).then(() => { console.info(`Succeeded in stopping the timer.`); }).catch((error: BusinessError) => { - console.info(`Failed to stop the timer. Message: ${error.message}, code: ${error.code}`); + console.error(`Failed to stop timer. message: ${error.message}, code: ${error.code}`); }); console.info(`Succeeded in creating a timer. timerId: ${timerId}`); }).catch((error: BusinessError) => { - console.info(`Failed to create a timer. Message: ${error.message}, code: ${error.code}`); + console.error(`Failed to create timer. message: ${error.message}, code: ${error.code}`); }); } catch(e) { let error = e as BusinessError; - console.info(`Failed to create a timer. Message: ${error.message}, code: ${error.code}`); + console.error(`Failed to create timer. message: ${error.message}, code: ${error.code}`); } ``` @@ -417,18 +417,18 @@ try { systemTimer.stopTimer(timerId); systemTimer.destroyTimer(timerId, (error: BusinessError) => { if (error) { - console.info(`Failed to destroy the timer. Message: ${error.message}, code: ${error.code}`); + console.error(`Failed to destroy timer. message: ${error.message}, code: ${error.code}`); return; } console.info(`Succeeded in destroying the timer.`); }); console.info(`Succeeded in creating a timer. timerId: ${timerId}`); }).catch((error: BusinessError) => { - console.info(`Failed to create a timer. Message: ${error.message}, code: ${error.code}`); + console.error(`Failed to create timer. message: ${error.message}, code: ${error.code}`); }); } catch(e) { let error = e as BusinessError; - console.info(`Failed to create a timer. Message: ${error.message}, code: ${error.code}`); + console.error(`Failed to create timer. message: ${error.message}, code: ${error.code}`); } ``` @@ -480,14 +480,14 @@ try { systemTimer.destroyTimer(timerId).then(() => { console.info(`Succeeded in destroying the timer.`); }).catch((error: BusinessError) => { - console.info(`Failed to destroy the timer. Message: ${error.message}, code: ${error.code}`); + console.error(`Failed to destroy timer. message: ${error.message}, code: ${error.code}`); }); console.info(`Succeeded in creating a timer. timerId: ${timerId}`); }).catch((error: BusinessError) => { - console.info(`Failed to create a timer. Message: ${error.message}, code: ${error.code}`); + console.error(`Failed to create timer. message: ${error.message}, code: ${error.code}`); }); } catch(e) { let error = e as BusinessError; - console.info(`Failed to create a timer. Message: ${error.message}, code: ${error.code}`); + console.error(`Failed to create timer. message: ${error.message}, code: ${error.code}`); } ``` diff --git a/en/application-dev/reference/apis-basic-services-kit/js-apis-thermal.md b/en/application-dev/reference/apis-basic-services-kit/js-apis-thermal.md index 7ee6d5eb88c..bc6fcd0291c 100644 --- a/en/application-dev/reference/apis-basic-services-kit/js-apis-thermal.md +++ b/en/application-dev/reference/apis-basic-services-kit/js-apis-thermal.md @@ -18,7 +18,7 @@ registerThermalLevelCallback(callback: Callback<ThermalLevel>): void Subscribes to thermal level changes. -**System capability:** SystemCapability.PowerManager.ThermalManager +**System capability**: SystemCapability.PowerManager.ThermalManager **Parameters** @@ -28,12 +28,11 @@ Subscribes to thermal level changes. **Error codes** -For details about the error codes, see [Thermal Manager Error Codes](errorcode-thermal.md). +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). | ID | Error Message | |---------|---------| -| 4800101 | Failed to connect to the service. | -| 401 | Parameter error. Possible causes: 1.Incorrect parameter types. | +| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. | **Example** @@ -54,22 +53,21 @@ unregisterThermalLevelCallback(callback?: Callback\): void Unsubscribes from thermal level changes. -**System capability:** SystemCapability.PowerManager.ThermalManager +**System capability**: SystemCapability.PowerManager.ThermalManager **Parameters** | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ---------------------------------------------- | -| callback | Callback<void> | No | Callback that returns no value. If this parameter is not set, all callbacks will be unregistered.| +| callback | Callback<void> | No | (Optional) Callback that returns no value.| **Error codes** -For details about the error codes, see [Thermal Manager Error Codes](errorcode-thermal.md). +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). | ID | Error Message | |---------|---------| -| 4800101 | Failed to connect to the service. | -| 401 | Parameter error. Possible causes: 1.Incorrect parameter types. | +| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. | **Example** @@ -90,7 +88,7 @@ getLevel(): ThermalLevel Obtains the current thermal level. -**System capability:** SystemCapability.PowerManager.ThermalManager +**System capability**: SystemCapability.PowerManager.ThermalManager **Return value** @@ -98,23 +96,11 @@ Obtains the current thermal level. | ------------ | ------------ | | ThermalLevel | Thermal level.| -**Error codes** - -For details about the error codes, see [Thermal Manager Error Codes](errorcode-thermal.md). - -| ID | Error Message | -|---------|---------| -| 4800101 | Failed to connect to the service. | - **Example** ```js -try { - let level = thermal.getLevel(); - console.info('thermal level is: ' + level); -} catch(err) { - console.error('get thermal level failed, err: ' + err); -} +let level = thermal.getLevel(); +console.info('thermal level is: ' + level); ``` ## thermal.subscribeThermalLevel(deprecated) @@ -125,7 +111,7 @@ subscribeThermalLevel(callback: AsyncCallback<ThermalLevel>): void Subscribes to thermal level changes. -**System capability:** SystemCapability.PowerManager.ThermalManager +**System capability**: SystemCapability.PowerManager.ThermalManager **Parameters** @@ -149,7 +135,7 @@ unsubscribeThermalLevel(callback?: AsyncCallback\): void Unsubscribes from thermal level changes. -**System capability:** SystemCapability.PowerManager.ThermalManager +**System capability**: SystemCapability.PowerManager.ThermalManager **Parameters** @@ -173,7 +159,7 @@ getThermalLevel(): ThermalLevel Obtains the current thermal level. -**System capability:** SystemCapability.PowerManager.ThermalManager +**System capability**: SystemCapability.PowerManager.ThermalManager **Return value** @@ -192,7 +178,7 @@ console.info('thermal level is: ' + level); Enumerates thermal levels. -**System capability:** SystemCapability.PowerManager.ThermalManager +**System capability**: SystemCapability.PowerManager.ThermalManager | Name | Value | Description | | ---------- | ---- | ------------------------------------------------------------ | diff --git a/en/application-dev/reference/apis-basic-services-kit/js-apis-update-sys.md b/en/application-dev/reference/apis-basic-services-kit/js-apis-update-sys.md index e67d6a87db9..8343c63a4af 100644 --- a/en/application-dev/reference/apis-basic-services-kit/js-apis-update-sys.md +++ b/en/application-dev/reference/apis-basic-services-kit/js-apis-update-sys.md @@ -133,6 +133,7 @@ For details about the error codes, see [Update Error Codes](errorcode-update.md) | ID | Error Message | | ------- | ---------------------------------------------------- | | 201 | Permission denied. | +| 202 | not system application. | | 11500104 | IPC error. | **Example** @@ -168,6 +169,7 @@ For details about the error codes, see [Update Error Codes](errorcode-update.md) | ID | Error Message | | ------- | ---------------------------------------------------- | | 201 | Permission denied. | +| 202 | not system application. | | 11500104 | IPC error. | **Example** @@ -209,6 +211,7 @@ For details about the error codes, see [Update Error Codes](errorcode-update.md) | ID | Error Message | | ------- | ---------------------------------------------------- | | 201 | Permission denied. | +| 202 | not system application. | | 11500104 | IPC error. | **Example** @@ -245,6 +248,7 @@ For details about the error codes, see [Update Error Codes](errorcode-update.md) | ID | Error Message | | ------- | ---------------------------------------------------- | | 201 | Permission denied. | +| 202 | not system application. | | 11500104 | IPC error. | **Example** @@ -285,6 +289,7 @@ For details about the error codes, see [Update Error Codes](errorcode-update.md) | ID | Error Message | | ------- | ---------------------------------------------------- | | 201 | Permission denied. | +| 202 | not system application. | | 401 | Parameter verification failed. | | 11500104 | IPC error. | @@ -341,6 +346,7 @@ For details about the error codes, see [Update Error Codes](errorcode-update.md) | ID | Error Message | | ------- | ---------------------------------------------------- | | 201 | Permission denied. | +| 202 | not system application. | | 401 | Parameter verification failed. | | 11500104 | IPC error. | @@ -390,6 +396,7 @@ For details about the error codes, see [Update Error Codes](errorcode-update.md) | ID | Error Message | | ------- | ---------------------------------------------------- | | 201 | Permission denied. | +| 202 | not system application. | | 11500104 | IPC error. | **Example** @@ -427,6 +434,7 @@ For details about the error codes, see [Update Error Codes](errorcode-update.md) | ID | Error Message | | ------- | ---------------------------------------------------- | | 201 | Permission denied. | +| 202 | not system application. | | 11500104 | IPC error. | **Example** @@ -467,6 +475,7 @@ For details about the error codes, see [Update Error Codes](errorcode-update.md) | ID | Error Message | | ------- | ---------------------------------------------------- | | 201 | Permission denied. | +| 202 | not system application. | | 401 | Parameter verification failed. | | 11500104 | IPC error. | @@ -514,6 +523,7 @@ For details about the error codes, see [Update Error Codes](errorcode-update.md) | ID | Error Message | | ------- | ---------------------------------------------------- | | 201 | Permission denied. | +| 202 | not system application. | | 401 | Parameter verification failed. | | 11500104 | IPC error. | @@ -556,6 +566,7 @@ For details about the error codes, see [Update Error Codes](errorcode-update.md) | ID | Error Message | | ------- | ---------------------------------------------------- | | 201 | Permission denied. | +| 202 | not system application. | | 11500104 | IPC error. | **Example** @@ -591,6 +602,7 @@ For details about the error codes, see [Update Error Codes](errorcode-update.md) | ID | Error Message | | ------- | ---------------------------------------------------- | | 201 | Permission denied. | +| 202 | not system application. | | 11500104 | IPC error. | **Example** @@ -630,6 +642,7 @@ For details about the error codes, see [Update Error Codes](errorcode-update.md) | ID | Error Message | | ------- | ---------------------------------------------------- | | 201 | Permission denied. | +| 202 | not system application. | | 401 | Parameter verification failed. | | 11500104 | IPC error. | @@ -683,6 +696,7 @@ For details about the error codes, see [Update Error Codes](errorcode-update.md) | ID | Error Message | | ------- | ---------------------------------------------------- | | 201 | Permission denied. | +| 202 | not system application. | | 401 | Parameter verification failed. | | 11500104 | IPC error. | @@ -733,6 +747,7 @@ For details about the error codes, see [Update Error Codes](errorcode-update.md) | ID | Error Message | | ------- | ---------------------------------------------------- | | 201 | Permission denied. | +| 202 | not system application. | | 401 | Parameter verification failed. | | 11500104 | IPC error. | @@ -785,6 +800,7 @@ For details about the error codes, see [Update Error Codes](errorcode-update.md) | ID | Error Message | | ------- | ---------------------------------------------------- | | 201 | Permission denied. | +| 202 | not system application. | | 401 | Parameter verification failed. | | 11500104 | IPC error. | @@ -834,6 +850,7 @@ For details about the error codes, see [Update Error Codes](errorcode-update.md) | ID | Error Message | | ------- | ---------------------------------------------------- | | 201 | Permission denied. | +| 202 | not system application. | | 401 | Parameter verification failed. | | 11500104 | IPC error. | @@ -886,6 +903,7 @@ For details about the error codes, see [Update Error Codes](errorcode-update.md) | ID | Error Message | | ------- | ---------------------------------------------------- | | 201 | Permission denied. | +| 202 | not system application. | | 401 | Parameter verification failed. | | 11500104 | IPC error. | @@ -935,6 +953,7 @@ For details about the error codes, see [Update Error Codes](errorcode-update.md) | ID | Error Message | | ------- | ---------------------------------------------------- | | 201 | Permission denied. | +| 202 | not system application. | | 401 | Parameter verification failed. | | 11500104 | IPC error. | @@ -987,6 +1006,7 @@ For details about the error codes, see [Update Error Codes](errorcode-update.md) | ID | Error Message | | ------- | ---------------------------------------------------- | | 201 | Permission denied. | +| 202 | not system application. | | 401 | Parameter verification failed. | | 11500104 | IPC error. | @@ -1036,6 +1056,7 @@ For details about the error codes, see [Update Error Codes](errorcode-update.md) | ID | Error Message | | ------- | ---------------------------------------------------- | | 201 | Permission denied. | +| 202 | not system application. | | 401 | Parameter verification failed. | | 11500104 | IPC error. | @@ -1088,6 +1109,7 @@ For details about the error codes, see [Update Error Codes](errorcode-update.md) | ID | Error Message | | ------- | ---------------------------------------------------- | | 201 | Permission denied. | +| 202 | not system application. | | 401 | Parameter verification failed. | | 11500104 | IPC error. | @@ -1135,6 +1157,7 @@ For details about the error codes, see [Update Error Codes](errorcode-update.md) | ID | Error Message | | ------- | ---------------------------------------------------- | | 201 | Permission denied. | +| 202 | not system application. | | 11500104 | IPC error. | **Example** @@ -1142,7 +1165,7 @@ For details about the error codes, see [Update Error Codes](errorcode-update.md) ```ts import { BusinessError } from '@kit.BasicServicesKit'; -updater.getUpgradePolicy(err: BusinessError, policy: update.UpgradePolicy) => { +updater.getUpgradePolicy((err: BusinessError, policy: update.UpgradePolicy) => { console.log(`policy downloadStrategy = ${policy?.downloadStrategy}`); console.log(`policy autoUpgradeStrategy = ${policy?.autoUpgradeStrategy}`); }); @@ -1171,6 +1194,7 @@ For details about the error codes, see [Update Error Codes](errorcode-update.md) | ID | Error Message | | ------- | ---------------------------------------------------- | | 201 | Permission denied. | +| 202 | not system application. | | 11500104 | IPC error. | **Example** @@ -1210,6 +1234,7 @@ For details about the error codes, see [Update Error Codes](errorcode-update.md) | ID | Error Message | | ------- | ---------------------------------------------------- | | 201 | Permission denied. | +| 202 | not system application. | | 11500104 | IPC error. | **Example** @@ -1256,6 +1281,7 @@ For details about the error codes, see [Update Error Codes](errorcode-update.md) | ID | Error Message | | ------- | ---------------------------------------------------- | | 201 | Permission denied. | +| 202 | not system application. | | 11500104 | IPC error. | **Example** @@ -1298,6 +1324,7 @@ For details about the error codes, see [Update Error Codes](errorcode-update.md) | ID | Error Message | | ------- | ---------------------------------------------------- | | 201 | Permission denied. | +| 202 | not system application. | | 11500104 | IPC error. | **Example** @@ -1333,6 +1360,7 @@ For details about the error codes, see [Update Error Codes](errorcode-update.md) | ID | Error Message | | ------- | ---------------------------------------------------- | | 201 | Permission denied. | +| 202 | not system application. | | 11500104 | IPC error. | **Example** @@ -1429,6 +1457,7 @@ For details about the error codes, see [Update Error Codes](errorcode-update.md) | ID | Error Message | | ------- | ---------------------------------------------------- | | 201 | Permission denied. | +| 202 | not system application. | | 11500104 | IPC error. | **Example** @@ -1462,6 +1491,7 @@ For details about the error codes, see [Update Error Codes](errorcode-update.md) | ID | Error Message | | ------- | ---------------------------------------------------- | | 201 | Permission denied. | +| 202 | not system application. | | 11500104 | IPC error. | **Example** @@ -1503,6 +1533,7 @@ For details about the error codes, see [Update Error Codes](errorcode-update.md) | ID | Error Message | | ------- | ---------------------------------------------------- | | 201 | Permission denied. | +| 202 | not system application. | | 401 | Parameter verification failed. | | 11500104 | IPC error. | @@ -1549,6 +1580,7 @@ For details about the error codes, see [Update Error Codes](errorcode-update.md) | ID | Error Message | | ------- | ---------------------------------------------------- | | 201 | Permission denied. | +| 202 | not system application. | | 401 | Parameter verification failed. | | 11500104 | IPC error. | @@ -1591,6 +1623,7 @@ For details about the error codes, see [Update Error Codes](errorcode-update.md) | ID | Error Message | | ------- | ---------------------------------------------------- | | 201 | Permission denied. | +| 202 | not system application. | | 401 | Parameter verification failed. | | 11500104 | IPC error. | @@ -1630,6 +1663,7 @@ For details about the error codes, see [Update Error Codes](errorcode-update.md) | ID | Error Message | | ------- | ---------------------------------------------------- | | 201 | Permission denied. | +| 202 | not system application. | | 401 | Parameter verification failed. | | 11500104 | IPC error. | diff --git a/en/application-dev/reference/apis-basic-services-kit/js-apis-usbManager-sys.md b/en/application-dev/reference/apis-basic-services-kit/js-apis-usbManager-sys.md index a6f04ee7e4d..35ff23c698a 100644 --- a/en/application-dev/reference/apis-basic-services-kit/js-apis-usbManager-sys.md +++ b/en/application-dev/reference/apis-basic-services-kit/js-apis-usbManager-sys.md @@ -36,6 +36,12 @@ Adds the device access permission for the application. System applications are g | deviceName | string | Yes | Device name. | | bundleName | string | Yes | Bundle name of the application.| +**Return value** + +| Type | Description | +| ------- | ------------------------------------------------------------------------- | +| boolean | Permission addition result. The value **true** indicates that the access permission is added successfully; and the value **false** indicates the opposite.| + **Error codes** For details about the error codes, see [USB Service Error Codes](errorcode-usb.md). @@ -45,12 +51,6 @@ For details about the error codes, see [USB Service Error Codes](errorcode-usb.m | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | | 202 | Permission denied. Normal application do not have permission to use system api. | -**Return value** - -| Type | Description | -| ------- | ------------------------------------------------------------------------- | -| boolean | Permission addition result. The value **true** indicates that the access permission is added successfully; and the value **false** indicates the opposite.| - **Example** ```ts @@ -81,6 +81,12 @@ Converts the USB function list in the string format to a numeric mask in Device | ------ | ------ | ---- | ---------------------- | | funcs | string | Yes | Function list in string format.| +**Return value** + +| Type | Description | +| ------ | ------------------ | +| number | Function list in numeric mask format.| + **Error codes** For details about the error codes, see [USB Service Error Codes](errorcode-usb.md). @@ -90,12 +96,6 @@ For details about the error codes, see [USB Service Error Codes](errorcode-usb.m | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | | 202 | Permission denied. Normal application do not have permission to use system api. | -**Return value** - -| Type | Description | -| ------ | ------------------ | -| number | Function list in numeric mask format.| - **Example** ```ts @@ -123,6 +123,12 @@ Converts the USB function list in the numeric mask format to a string in Device | ------ | ----------------------------- | ---- | ----------------- | | funcs | [FunctionType](#functiontype) | Yes | USB function list in numeric mask format.| +**Return value** + +| Type | Description | +| ------ | ------------------------------ | +| string | Function list in string format.| + **Error codes** For details about the error codes, see [USB Service Error Codes](errorcode-usb.md). @@ -132,12 +138,6 @@ For details about the error codes, see [USB Service Error Codes](errorcode-usb.m | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | | 202 | Permission denied. Normal application do not have permission to use system api. | -**Return value** - -| Type | Description | -| ------ | ------------------------------ | -| string | Function list in string format.| - **Example** ```ts @@ -165,6 +165,12 @@ Sets the current USB function list in Device mode. | ------ | ----------------------------- | ---- | ----------------- | | funcs | [FunctionType](#functiontype) | Yes | USB function list in numeric mask format.| +**Return value** + +| Type | Description | +| ------------------- | ------------- | +| Promise\ | Promise used to return the result.| + **Error codes** For details about the error codes, see [USB Service Error Codes](errorcode-usb.md). @@ -174,12 +180,6 @@ For details about the error codes, see [USB Service Error Codes](errorcode-usb.m | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | | 14400002 | Permission denied. The HDC is disabled by the system. | -**Return value** - -| Type | Description | -| ------------------- | ------------- | -| Promise\ | Promise used to return the result.| - **Example** ```ts @@ -206,6 +206,12 @@ Obtains the numeric mask combination for the USB function list in Device mode. W **System capability**: SystemCapability.USB.USBManager +**Return value** + +| Type | Description | +| ----------------------------- | --------------------------------- | +| [FunctionType](#functiontype) | Numeric mask combination for the USB function list.| + **Error codes** For details about the error codes, see [USB Service Error Codes](errorcode-usb.md). @@ -215,12 +221,6 @@ For details about the error codes, see [USB Service Error Codes](errorcode-usb.m | 401 | Parameter error. No parameters are required. | | 202 | Permission denied. Normal application do not have permission to use system api. | -**Return value** - -| Type | Description | -| ----------------------------- | --------------------------------- | -| [FunctionType](#functiontype) | Numeric mask combination for the USB function list.| - **Example** ```ts @@ -241,6 +241,12 @@ Obtains the list of all physical USB ports. When the developer mode is disabled, **System capability**: SystemCapability.USB.USBManager +**Return value** + +| Type | Description | +| -------------------------- | --------------------- | +| Array<[USBPort](#usbport)> | List of physical USB ports.| + **Error codes** For details about the error codes, see [USB Service Error Codes](errorcode-usb.md). @@ -250,12 +256,6 @@ For details about the error codes, see [USB Service Error Codes](errorcode-usb.m | 401 | Parameter error. No parameters are required. | | 202 | Permission denied. Normal application do not have permission to use system api. | -**Return value** - -| Type | Description | -| -------------------------- | --------------------- | -| Array<[USBPort](#usbport)> | List of physical USB ports.| - **Example** ```ts @@ -282,6 +282,12 @@ Obtains the mask combination for the supported mode list of a given USB port. | ------ | ------ | ---- | -------- | | portId | number | Yes | Port number.| +**Return value** + +| Type | Description | +| ----------------------------- | -------------------------- | +| [PortModeType](#portmodetype) | Mask combination for the supported mode list.| + **Error codes** For details about the error codes, see [USB Service Error Codes](errorcode-usb.md). @@ -291,12 +297,6 @@ For details about the error codes, see [USB Service Error Codes](errorcode-usb.m | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | | 202 | Permission denied. Normal application do not have permission to use system api. | -**Return value** - -| Type | Description | -| ----------------------------- | -------------------------- | -| [PortModeType](#portmodetype) | Mask combination for the supported mode list.| - **Example** ```ts @@ -325,6 +325,12 @@ Sets the role types supported by a specified port, which can be **powerRole** (f | powerRole | [PowerRoleType](#powerroletype) | Yes | Role for charging. | | dataRole | [DataRoleType](#dataroletype) | Yes | Role for data transfer.| +**Return value** + +| Type | Description | +| ------------------- | ------------- | +| Promise\ | Promise used to return the result.| + **Error codes** For details about the error codes, see [USB Service Error Codes](errorcode-usb.md). @@ -333,12 +339,6 @@ For details about the error codes, see [USB Service Error Codes](errorcode-usb.m | -------- | ------------------------------------------------------------------------------------------------------- | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | -**Return value** - -| Type | Description | -| ------------------- | ------------- | -| Promise\ | Promise used to return the result.| - **Example** ```ts @@ -376,6 +376,12 @@ Adds the device access permission for the application. System applications are g | deviceName | string | Yes | Device name. | | tokenId | string | Yes | Token ID of the software package.| +**Return value** + +| Type | Description | +| ------- | ------------------------------------------------------------------------- | +| boolean | Permission addition result. The value **true** indicates that the access permission is added successfully; and the value **false** indicates the opposite.| + **Error codes** For details about the error codes, see [USB Service Error Codes](errorcode-usb.md). @@ -387,12 +393,6 @@ For details about the error codes, see [USB Service Error Codes](errorcode-usb.m | 202 | Permission denied. Normal application do not have permission to use system api. | | 801 | Capability not supported. | -**Return value** - -| Type | Description | -| ------- | ------------------------------------------------------------------------- | -| boolean | Permission addition result. The value **true** indicates that the access permission is added successfully; and the value **false** indicates the opposite.| - **Example** ```ts @@ -440,6 +440,12 @@ Converts the USB function list in the string format to a numeric mask in Device | ------ | ------ | ---- | ---------------------- | | funcs | string | Yes | Function list in string format.| +**Return value** + +| Type | Description | +| ------ | ------------------ | +| number | Function list in numeric mask format.| + **Error codes** For details about the error codes, see [USB Service Error Codes](errorcode-usb.md). @@ -451,12 +457,6 @@ For details about the error codes, see [USB Service Error Codes](errorcode-usb.m | 202 | Permission denied. Normal application do not have permission to use system api. | | 801 | Capability not supported. | -**Return value** - -| Type | Description | -| ------ | ------------------ | -| number | Function list in numeric mask format.| - **Example** ```ts @@ -486,6 +486,12 @@ Converts the USB function list in the numeric mask format to a string in Device | ------ | ----------------------------- | ---- | ----------------- | | funcs | [FunctionType](#functiontype) | Yes | USB function list in numeric mask format.| +**Return value** + +| Type | Description | +| ------ | ------------------------------ | +| string | Function list in string format.| + **Error codes** For details about the error codes, see [USB Service Error Codes](errorcode-usb.md). @@ -497,12 +503,6 @@ For details about the error codes, see [USB Service Error Codes](errorcode-usb.m | 202 | Permission denied. Normal application do not have permission to use system api. | | 801 | Capability not supported. | -**Return value** - -| Type | Description | -| ------ | ------------------------------ | -| string | Function list in string format.| - **Example** ```ts @@ -532,6 +532,12 @@ Sets the current USB function list in Device mode. | ------ | ----------------------------- | ---- | ----------------- | | funcs | [FunctionType](#functiontype) | Yes | USB function list in numeric mask format.| +**Return value** + +| Type | Description | +| ------------------- | ------------- | +| Promise\ | Promise used to return the result.| + **Error codes** For details about the error codes, see [USB Service Error Codes](errorcode-usb.md). @@ -545,12 +551,6 @@ For details about the error codes, see [USB Service Error Codes](errorcode-usb.m | 14400002 | Permission denied. The HDC is disabled by the system. | | 14400006 | Unsupported operation. The function is not supported. | -**Return value** - -| Type | Description | -| ------------------- | ------------- | -| Promise\ | Promise used to return the result.| - **Example** ```ts @@ -579,6 +579,12 @@ Obtains the numeric mask combination for the USB function list in Device mode. W **System capability**: SystemCapability.USB.USBManager +**Return value** + +| Type | Description | +| ----------------------------- | --------------------------------- | +| [FunctionType](#functiontype) | Numeric mask combination for the USB function list.| + **Error codes** For details about the error codes, see [USB Service Error Codes](errorcode-usb.md). @@ -590,12 +596,6 @@ For details about the error codes, see [USB Service Error Codes](errorcode-usb.m | 202 | Permission denied. Normal application do not have permission to use system api. | | 801 | Capability not supported. | -**Return value** - -| Type | Description | -| ----------------------------- | --------------------------------- | -| [FunctionType](#functiontype) | Numeric mask combination for the USB function list.| - **Example** ```ts @@ -618,6 +618,12 @@ Obtains the list of all physical USB ports. When the developer mode is disabled, **System capability**: SystemCapability.USB.USBManager +**Return value** + +| Type | Description | +| -------------------------- | --------------------- | +| Array<[USBPort](#usbport)> | List of physical USB ports.| + **Error codes** For details about the error codes, see [USB Service Error Codes](errorcode-usb.md). @@ -626,14 +632,9 @@ For details about the error codes, see [USB Service Error Codes](errorcode-usb.m | -------- | ------------------------------------------------------------------------------------------------------- | | 201 | Permission verification failed. The application does not have the permission required to call the API. | | 202 | Permission denied. Normal application do not have permission to use system api. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | | 801 | Capability not supported. | -**Return value** - -| Type | Description | -| -------------------------- | --------------------- | -| Array<[USBPort](#usbport)> | List of physical USB ports.| - **Example** ```ts @@ -658,6 +659,12 @@ Obtains the mask combination for the supported mode list of a given USB port. | ------ | ------ | ---- | -------- | | portId | number | Yes | Port number.| +**Return value** + +| Type | Description | +| ----------------------------- | -------------------------- | +| [PortModeType](#portmodetype) | Mask combination for the supported mode list.| + **Error codes** For details about the error codes, see [USB Service Error Codes](errorcode-usb.md). @@ -668,12 +675,7 @@ For details about the error codes, see [USB Service Error Codes](errorcode-usb.m | 201 | Permission verification failed. The application does not have the permission required to call the API. | | 202 | Permission denied. Normal application do not have permission to use system api. | | 801 | Capability not supported. | - -**Return value** - -| Type | Description | -| ----------------------------- | -------------------------- | -| [PortModeType](#portmodetype) | Mask combination for the supported mode list.| +| 14400003 | Unsupported operation. The current device does not support port role switching. | **Example** @@ -705,6 +707,12 @@ Sets the role types supported by a specified port, which can be **powerRole** (f | powerRole | [PowerRoleType](#powerroletype) | Yes | Role for charging. | | dataRole | [DataRoleType](#dataroletype) | Yes | Role for data transfer.| +**Return value** + +| Type | Description | +| ------------------- | ------------- | +| Promise\ | Promise used to return the result.| + **Error codes** For details about the error codes, see [USB Service Error Codes](errorcode-usb.md). @@ -717,12 +725,6 @@ For details about the error codes, see [USB Service Error Codes](errorcode-usb.m | 801 | Capability not supported. | | 14400003 | Unsupported operation. The current device does not support port role switching. | -**Return value** - -| Type | Description | -| ------------------- | ------------- | -| Promise\ | Promise used to return the result.| - **Example** ```ts @@ -776,7 +778,7 @@ import { hilog } from '@kit.PerformanceAnalysisKit'; import { bundleManager } from '@kit.AbilityKit'; try { let accList: usbManager.USBAccessory[] = usbManager.getAccessoryList() - let flags = bundleManager.BundleFlah.GET_BUNDLE_INFO_WITH_APPLICATION | bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_EXTENSION_ABILITY + let flags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION | bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_EXTENSION_ABILITY let bundleInfo = await bundleManager.getBundleInfoForSelf(flags) let tokenId: number = bundleInfo.appInfo.accessTokenId usbManager.addAccessoryRight(tokenId, accList[0]) diff --git a/en/application-dev/reference/apis-basic-services-kit/js-apis-usbManager.md b/en/application-dev/reference/apis-basic-services-kit/js-apis-usbManager.md index 92101baf525..784df87a24e 100644 --- a/en/application-dev/reference/apis-basic-services-kit/js-apis-usbManager.md +++ b/en/application-dev/reference/apis-basic-services-kit/js-apis-usbManager.md @@ -20,6 +20,12 @@ Obtains the list of USB devices connected to the host. If no device is connected **System capability**: SystemCapability.USB.USBManager +**Returns** + +| Type | Description | +| ---------------------------------------------------- | ------- | +| Array<Readonly<[USBDevice](#usbdevice)>> | USB device list.| + **Error codes** For details about the error codes, see [USB Service Error Codes](errorcode-usb.md). @@ -28,12 +34,6 @@ For details about the error codes, see [USB Service Error Codes](errorcode-usb.m | -------- | ------------------------- | | 801 | Capability not supported. | -**Return value** - -| Type | Description | -| ---------------------------------------------------- | ------- | -| Array<Readonly<[USBDevice](#usbdevice)>> | USB device list.| - **Example** ```ts @@ -109,7 +109,7 @@ Connects to the USB device based on the device information returned by **getDevi | -------- | -------- | -------- | ---------------- | | device | [USBDevice](#usbdevice) | Yes| USB device. The **busNum** and **devAddress** parameters obtained by **getDevices** are used to determine a USB device. Other parameters are passed transparently.| -**Return value** +**Returns** | Type| Description| | -------- | -------- | @@ -155,6 +155,12 @@ Checks whether the user, for example, the application or system, has the device | -------- | -------- | -------- | -------- | | deviceName | string | Yes| Device name, which can be obtained from the device list returned by **getDevices**.| +**Returns** + +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the application has the permission to access the device; returns **false** otherwise. If this API fails to be called, the following error codes are returned:
- 88080385: This API is not initialized.
- 88080492: An error occurs when the service data packet is written.
- 88080493: An error occurs when the service data packet is read.| + **Error codes** For details about the error codes, see [USB Service Error Codes](errorcode-usb.md). @@ -164,12 +170,6 @@ For details about the error codes, see [USB Service Error Codes](errorcode-usb.m | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | | 801 | Capability not supported. | -**Return value** - -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the application has the permission to access the device; returns **false** otherwise. If this API fails to be called, the following error codes are returned:
- 88080385: This API is not initialized.
- 88080492: An error occurs when the service data packet is written.
- 88080493: An error occurs when the service data packet is read.| - **Example** ```ts @@ -198,6 +198,12 @@ Requests the temporary device access permission for the application. This API us | -------- | -------- | -------- | -------- | | deviceName | string | Yes| Device name, which can be obtained from the device list returned by **getDevices**.| +**Returns** + +| Type| Description| +| -------- | -------- | +| Promise<boolean> | Promise used to return the result. The value **true** indicates that the temporary device access permissions are granted; and the value **false** indicates the opposite. If this API fails to be called, the following error codes are returned:
- 88080385: This API is not initialized.
- 88080392: An error occurs when the API data packet is written.
- 88080393: An error occurs when the API data packet is read.
- 88080492: An error occurs when the service data packet is written.
- 88080493: An error occurs when the service data packet is read.
- 88080497: An error occurs when the internal logic of the service is executed.| + **Error codes** For details about the error codes, see [USB Service Error Codes](errorcode-usb.md). @@ -207,12 +213,6 @@ For details about the error codes, see [USB Service Error Codes](errorcode-usb.m | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | | 801 | Capability not supported. | -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise<boolean> | Promise used to return the result. The value **true** indicates that the temporary device access permissions are granted; and the value **false** indicates the opposite. If this API fails to be called, the following error codes are returned:
- 88080385: This API is not initialized.
- 88080392: An error occurs when the API data packet is written.
- 88080393: An error occurs when the API data packet is read.
- 88080492: An error occurs when the service data packet is written.
- 88080493: An error occurs when the service data packet is read.
- 88080497: An error occurs when the internal logic of the service is executed.| - **Example** ```ts @@ -241,6 +241,12 @@ Removes the device access permission for the application. System applications ar | -------- | -------- | -------- | -------- | | deviceName | string | Yes| Device name, which can be obtained from the device list returned by **getDevices**.| +**Returns** + +| Type| Description| +| -------- | -------- | +| boolean | Permission removal result. The value **true** indicates that the access permission is removed successfully; and the value **false** indicates the opposite. If this API fails to be called, the following error codes are returned:
- 88080382: An invalid value or parameter occurs during the API operation.
- 88080385: This API is not initialized.
- 88080392: An error occurs when the API data packet is written.
- 88080393: An error occurs when the API data packet is read.
- 88080492: An error occurs when the service data packet is written.
- 88080493: An error occurs when the service data packet is read.
- 88080497: An error occurs when the internal logic of the service is executed.| + **Error codes** For details about the error codes, see [USB Service Error Codes](errorcode-usb.md). @@ -250,12 +256,6 @@ For details about the error codes, see [USB Service Error Codes](errorcode-usb.m | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | | 801 | Capability not supported. | -**Return value** - -| Type| Description| -| -------- | -------- | -| boolean | Permission removal result. The value **true** indicates that the access permission is removed successfully; and the value **false** indicates the opposite. If this API fails to be called, the following error codes are returned:
- 88080382: An invalid value or parameter occurs during the API operation.
- 88080385: This API is not initialized.
- 88080392: An error occurs when the API data packet is written.
- 88080393: An error occurs when the API data packet is read.
- 88080492: An error occurs when the service data packet is written.
- 88080493: An error occurs when the service data packet is read.
- 88080497: An error occurs when the internal logic of the service is executed.| - **Example** ```ts @@ -290,6 +290,12 @@ Claims a USB interface. | iface | [USBInterface](#usbinterface) | Yes| USB interface. You can use **getDevices** to obtain device information and identify the USB interface based on its ID.| | force | boolean | No| Whether to forcibly claim a USB interface. The default value is **false**, which means not to forcibly claim a USB interface. You can set the value as required.| +**Returns** + +| Type| Description| +| -------- | -------- | +| number | Returns **0** if the USB interface is successfully claimed; returns an error code otherwise. The error codes are as follows:
- 63: The data exceeds the expected maximum volume.
- 88080385: This API is not initialized.
- 88080482: An invalid value or parameter occurs during the service.
- 88080484: No permission.
- 88080492: An error occurs when the service data packet is written.
- 88080493: An error occurs when the service data packet is read.
- 88080497: An error occurs when the internal logic of the service is executed.
- -1: The underlying interface fails to be called.| + **Error codes** For details about the error codes, see [USB Service Error Codes](errorcode-usb.md). @@ -299,12 +305,6 @@ For details about the error codes, see [USB Service Error Codes](errorcode-usb.m | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | | 801 | Capability not supported. | -**Return value** - -| Type| Description| -| -------- | -------- | -| number | Returns **0** if the USB interface is successfully claimed; returns an error code otherwise. The error codes are as follows:
- 63: The data exceeds the expected maximum volume.
- 88080385: This API is not initialized.
- 88080482: An invalid value or parameter occurs during the service.
- 88080484: No permission.
- 88080492: An error occurs when the service data packet is written.
- 88080493: An error occurs when the service data packet is read.
- 88080497: An error occurs when the internal logic of the service is executed.
- -1: The underlying interface fails to be called.| - **Example** ```ts @@ -338,6 +338,12 @@ Before you do this, ensure that you have claimed the interface by calling [usbMa | pipe | [USBDevicePipe](#usbdevicepipe) | Yes| USB device pipe, which is used to determine the bus number and device address. You need to call **connectDevice** to obtain its value.| | iface | [USBInterface](#usbinterface) | Yes| USB interface. You can use **getDevices** to obtain device information and identify the USB interface based on its ID.| +**Returns** + +| Type| Description| +| -------- | -------- | +| number | Returns **0** if the USB interface is successfully released; returns an error code otherwise. The error codes are as follows:
- 63: The data exceeds the expected maximum volume.
- 88080381: Invalid interface operation.
- 88080385: This API is not initialized.
- 88080482: An invalid value or parameter occurs during the service.
- 88080484: No permission.
- 88080492: An error occurs when the service data packet is written.
- 88080493: An error occurs when the service data packet is read.
- 88080497: An error occurs when the internal logic of the service is executed.
- -1: The underlying interface fails to be called.| + **Error codes** For details about the error codes, see [USB Service Error Codes](errorcode-usb.md). @@ -347,12 +353,6 @@ For details about the error codes, see [USB Service Error Codes](errorcode-usb.m | 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified.2.Incorrect parameter types. | | 801 | Capability not supported. | -**Return value** - -| Type| Description| -| -------- | -------- | -| number | Returns **0** if the USB interface is successfully released; returns an error code otherwise. The error codes are as follows:
- 63: The data exceeds the expected maximum volume.
- 88080381: Invalid interface operation.
- 88080385: This API is not initialized.
- 88080482: An invalid value or parameter occurs during the service.
- 88080484: No permission.
- 88080492: An error occurs when the service data packet is written.
- 88080493: An error occurs when the service data packet is read.
- 88080497: An error occurs when the internal logic of the service is executed.
- -1: The underlying interface fails to be called.| - **Example** ```ts @@ -389,6 +389,12 @@ Sets the device configuration. | pipe | [USBDevicePipe](#usbdevicepipe) | Yes| USB device pipe, which is used to determine the bus number and device address. You need to call **connectDevice** to obtain its value.| | config | [USBConfiguration](#usbconfiguration) | Yes| USB configuration. You can use **getDevices** to obtain device information and identify the USB configuration based on the ID.| +**Returns** + +| Type| Description| +| -------- | -------- | +| number | Returns **0** if the USB configuration is successfully set; returns an error code otherwise. The error codes are as follows:
- 63: The data exceeds the expected maximum volume.
- 88080385: This API is not initialized.
- 88080482: An invalid value or parameter occurs during the service.
- 88080484: No permission.
- 88080492: An error occurs when the service data packet is written.
- 88080493: An error occurs when the service data packet is read.
- 88080497: An error occurs when the internal logic of the service is executed.
- -1: The underlying interface fails to be called.
- -17: I/O failure.| + **Error codes** For details about the error codes, see [USB Service Error Codes](errorcode-usb.md). @@ -398,12 +404,6 @@ For details about the error codes, see [USB Service Error Codes](errorcode-usb.m | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | | 801 | Capability not supported. | -**Return value** - -| Type| Description| -| -------- | -------- | -| number | Returns **0** if the USB configuration is successfully set; returns an error code otherwise. The error codes are as follows:
- 63: The data exceeds the expected maximum volume.
- 88080385: This API is not initialized.
- 88080482: An invalid value or parameter occurs during the service.
- 88080484: No permission.
- 88080492: An error occurs when the service data packet is written.
- 88080493: An error occurs when the service data packet is read.
- 88080497: An error occurs when the internal logic of the service is executed.
- -1: The underlying interface fails to be called.
- -17: I/O failure.| - **Example** ```ts @@ -440,6 +440,12 @@ Sets a USB interface. | pipe | [USBDevicePipe](#usbdevicepipe) | Yes| USB device pipe, which is used to determine the bus number and device address. You need to call **connectDevice** to obtain its value.| | iface | [USBInterface](#usbinterface) | Yes| USB interface. You can use **getDevices** to obtain device information and identify the USB interface based on its **id** and **alternateSetting**.| +**Returns** + +| Type| Description| +| -------- | -------- | +| number | Returns **0** if the USB interface is successfully set; returns an error code otherwise. The error codes are as follows:
- 63: The data exceeds the expected maximum volume.
- 88080385: This API is not initialized.
- 88080482: An invalid value or parameter occurs during the service.
- 88080484: No permission.
- 88080492: An error occurs when the service data packet is written.
- 88080493: An error occurs when the service data packet is read.
- 88080497: An error occurs when the internal logic of the service is executed.
- -1: The underlying interface fails to be called.| + **Error codes** For details about the error codes, see [USB Service Error Codes](errorcode-usb.md). @@ -449,12 +455,6 @@ For details about the error codes, see [USB Service Error Codes](errorcode-usb.m | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | | 801 | Capability not supported. | -**Return value** - -| Type| Description| -| -------- | -------- | -| number | Returns **0** if the USB interface is successfully set; returns an error code otherwise. The error codes are as follows:
- 63: The data exceeds the expected maximum volume.
- 88080385: This API is not initialized.
- 88080482: An invalid value or parameter occurs during the service.
- 88080484: No permission.
- 88080492: An error occurs when the service data packet is written.
- 88080493: An error occurs when the service data packet is read.
- 88080497: An error occurs when the internal logic of the service is executed.
- -1: The underlying interface fails to be called.| - **Example** ```ts @@ -490,6 +490,12 @@ Obtains the raw USB descriptor. If the USB service is abnormal, **undefined** ma | -------- | -------- | -------- | -------- | | pipe | [USBDevicePipe](#usbdevicepipe) | Yes| USB device pipe, which is used to determine the bus number and device address. You need to call **connectDevice** to obtain its value.| +**Returns** + +| Type| Description| +| -------- | -------- | +| Uint8Array | Returns the raw USB descriptor if the operation is successful; returns **undefined** otherwise.| + **Error codes** For details about the error codes, see [USB Service Error Codes](errorcode-usb.md). @@ -499,12 +505,6 @@ For details about the error codes, see [USB Service Error Codes](errorcode-usb.m | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | | 801 | Capability not supported. | -**Return value** - -| Type| Description| -| -------- | -------- | -| Uint8Array | Returns the raw USB descriptor if the operation is successful; returns **undefined** otherwise.| - **Example** ```ts @@ -536,6 +536,12 @@ Obtains the file descriptor. | -------- | -------- | -------- | -------- | | pipe | [USBDevicePipe](#usbdevicepipe) | Yes| USB device pipe, which is used to determine the bus number and device address. You need to call **connectDevice** to obtain its value.| +**Returns** + +| Type | Description | +| ------ | -------------------- | +| number | Returns the file descriptor corresponding to the device if this API is successful called; returns an error code otherwise. The error codes are as follows:
- 63: The data exceeds the expected maximum volume.
- 88080385: This API is not initialized.
- 88080482: An invalid value or parameter occurs during the service.
- 88080484: No permission.
- 88080492: An error occurs when the service data packet is written.
- 88080493: An error occurs when the service data packet is read.
- 88080497: An error occurs when the internal logic of the service is executed.
- -1: The underlying interface fails to be called.| + **Error codes** For details about the error codes, see [USB Service Error Codes](errorcode-usb.md). @@ -545,12 +551,6 @@ For details about the error codes, see [USB Service Error Codes](errorcode-usb.m | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | | 801 | Capability not supported. | -**Return value** - -| Type | Description | -| ------ | -------------------- | -| number | Returns the file descriptor corresponding to the device if this API is successful called; returns an error code otherwise. The error codes are as follows:
- 63: The data exceeds the expected maximum volume.
- 88080385: This API is not initialized.
- 88080482: An invalid value or parameter occurs during the service.
- 88080484: No permission.
- 88080492: An error occurs when the service data packet is written.
- 88080493: An error occurs when the service data packet is read.
- 88080497: An error occurs when the internal logic of the service is executed.
- -1: The underlying interface fails to be called.| - **Example** ```ts @@ -588,6 +588,12 @@ Performs control transfer. | controlparam | [USBControlParams](#usbcontrolparamsdeprecated) | Yes| Control transfer parameters. Set the parameters as required. For details, see the USB protocol.| | timeout | number | No| (Optional) Timeout duration, in ms. The default value is **0**. You can set this parameter as required.| +**Returns** + +| Type| Description| +| -------- | -------- | +| Promise<number> | Promise used to return the result, which is the size of the transferred or received data block if the transfer is successful. If the API call fails, the following error codes are returned:
- 88080385: This API is not initialized.
- 88080482: An invalid value or parameter occurs during the service.
- 88080484: No permission.
- 88080492: An error occurs when the service data packet is written.
- 88080493: An error occurs when the service data packet is read.
- 88080497: An error occurs when the internal logic of the service is executed.
- -1: The underlying interface fails to be called.| + **Error codes** For details about the error codes, see [USB Service Error Codes](errorcode-usb.md). @@ -596,12 +602,6 @@ For details about the error codes, see [USB Service Error Codes](errorcode-usb.m | -------- | ------------------------------------------------------------ | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise<number> | Promise used to return the result, which is the size of the transferred or received data block if the transfer is successful. If the API call fails, the following error codes are returned:
- 88080385: This API is not initialized.
- 88080482: An invalid value or parameter occurs during the service.
- 88080484: No permission.
- 88080492: An error occurs when the service data packet is written.
- 88080493: An error occurs when the service data packet is read.
- 88080497: An error occurs when the internal logic of the service is executed.
- -1: The underlying interface fails to be called.| - **Example** ```ts @@ -655,6 +655,12 @@ Performs control transfer. | requestparam | [USBDeviceRequestParams](#usbdevicerequestparams12) | Yes| Control transfer parameters. Set the parameters as required. For details, see the USB protocol.| | timeout | number | No| (Optional) Timeout duration, in ms. The default value is **0**, indicating no timeout.| +**Returns** + +| Type| Description| +| -------- | -------- | +| Promise<number> | Promise used to return the result, which is the size of the transferred or received data block if the transfer is successful. If the API call fails, the following error codes are returned:
- 88080385: This API is not initialized.
- 88080482: An invalid value or parameter occurs during the service.
- 88080484: No permission.
- 88080492: An error occurs when the service data packet is written.
- 88080493: An error occurs when the service data packet is read.
- 88080497: An error occurs when the internal logic of the service is executed.
- -1: The underlying interface fails to be called.| + **Error codes** For details about the error codes, see [USB Service Error Codes](errorcode-usb.md). @@ -664,12 +670,6 @@ For details about the error codes, see [USB Service Error Codes](errorcode-usb.m | 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified.2.Incorrect parameter types. | | 801 | Capability not supported. | -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise<number> | Promise used to return the result, which is the size of the transferred or received data block if the transfer is successful. If the API call fails, the following error codes are returned:
- 88080385: This API is not initialized.
- 88080482: An invalid value or parameter occurs during the service.
- 88080484: No permission.
- 88080492: An error occurs when the service data packet is written.
- 88080493: An error occurs when the service data packet is read.
- 88080497: An error occurs when the internal logic of the service is executed.
- -1: The underlying interface fails to be called.| - **Example** ```ts @@ -731,6 +731,12 @@ Performs bulk transfer. | buffer | Uint8Array | Yes| Buffer used to write or read data.| | timeout | number | No| (Optional) Timeout duration, in ms. The default value is **0**. You can set this parameter as required.| +**Returns** + +| Type| Description| +| -------- | -------- | +| Promise<number> | Promise used to return the result, which is the size of the transferred or received data block if the transfer is successful. If the API call fails, the following error codes are returned:
- 63: The data exceeds the expected maximum volume.
- 88080385: This API is not initialized.
- 88080482: An invalid value or parameter occurs during the service.
- 88080484: No permission.
- 88080492: An error occurs when the service data packet is written.
- 88080493: An error occurs when the service data packet is read.
- 88080497: An error occurs when the internal logic of the service is executed.
- -1: The underlying interface fails to be called.
- -3: The parameter is invalid.
- -202: The device is not found.| + **Error codes** For details about the error codes, see [USB Service Error Codes](errorcode-usb.md). @@ -740,12 +746,6 @@ For details about the error codes, see [USB Service Error Codes](errorcode-usb.m | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | | 801 | Capability not supported. | -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise<number> | Promise used to return the result, which is the size of the transferred or received data block if the transfer is successful. If the API call fails, the following error codes are returned:
- 63: The data exceeds the expected maximum volume.
- 88080385: This API is not initialized.
- 88080482: An invalid value or parameter occurs during the service.
- 88080484: No permission.
- 88080492: An error occurs when the service data packet is written.
- 88080493: An error occurs when the service data packet is read.
- 88080497: An error occurs when the internal logic of the service is executed.
- -1: The underlying interface fails to be called.
- -3: The parameter is invalid.
- -202: The device is not found.| - **Example** > **NOTE** @@ -806,12 +806,11 @@ For details about the error codes, see [USB Service Error Codes](errorcode-usb.m | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | | 801 | Capability not supported. | | 14400001 | Access right denied. Call requestRight to get the USBDevicePipe access right first. | -| 14400007 | Resource busy. | +| 14400007 | Resource busy. Possible causes: 1. The transfer has already been submitted. 2. The interface is claimed by another program or driver.| | 14400008 | No such device (it may have been disconnected). | -| 14400009 | Insufficient memory. | +| 14400009 | Insufficient memory. Possible causes: 1. Memory allocation failed. | | 14400012 | Transmission I/O error. | **Example** @@ -820,6 +819,7 @@ For details about the error codes, see [USB Service Error Codes](errorcode-usb.m > > The following sample code shows the basic process for calling the **usbSubmitTransfer** API and it needs to be executed in a specific method. In actual calling, you must comply with the device-related protocols to ensure correct data transfer and device compatibility. + ```ts // Call usbManager.getDevices to obtain a data set. Then, obtain a USB device and its access permission. // Pass the obtained USB device as a parameter to usbManager.connectDevice. Then, call usbManager.connectDevice to connect the USB device. @@ -883,31 +883,31 @@ Cancels an asynchronous USB data transfer request. | -------- | -------- | -------- | -------- | | transfer | [UsbDataTransferParams](#usbdatatransferparams18) | Yes| Only **USBDevicePipe** and **endpoint** are required for canceling the transfer.| +**Returns** + +| Type| Description| +| -------- | -------- | +| <void> | None.| + **Error codes** For details about the error codes, see [USB Service Error Codes](errorcode-usb.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | | 801 | Capability not supported. | | 14400001 | Access right denied. Call requestRight to get the USBDevicePipe access right first. | | 14400008 | No such device (it may have been disconnected). | | 14400010 | Other USB error. Possible causes:
1.Unrecognized discard error code. | | 14400011 | The transfer is not in progress, or is already complete or cancelled.| -**Return value** - -| Type| Description| -| -------- | -------- | -| <void> | None.| - **Example** > **NOTE** > > The following sample code shows the basic process for calling the **usbCancelTransfer** API and it needs to be executed in a specific method. In actual calling, you must comply with the device-related protocols to ensure correct data transfer and device compatibility. + ```ts // Call usbManager.getDevices to obtain a data set. Then, obtain a USB device and its access permission. // Pass the obtained USB device as a parameter to usbManager.connectDevice. Then, call usbManager.connectDevice to connect the USB device. @@ -969,6 +969,12 @@ Closes a USB device pipe. | -------- | -------- | -------- | -------- | | pipe | [USBDevicePipe](#usbdevicepipe) | Yes| USB device pipe, which is used to determine the message control channel. You need to call **connectDevice** to obtain its value.| +**Returns** + +| Type| Description| +| -------- | -------- | +| number | Returns **0** if the USB device pipe is closed successfully; returns an error code otherwise. The error codes are as follows:
- 63: The data exceeds the expected maximum volume.
- 88080393: An error occurs when the API data packet is read.
- 88080482: An invalid value or parameter occurs during the service.
- 88080484: No permission.
- 88080493: An error occurs when the service data packet is read.
- 88080497: An error occurs when the internal logic of the service is executed.
- -1: The underlying interface fails to be called.| + **Error codes** For details about the error codes, see [USB Service Error Codes](errorcode-usb.md). @@ -978,12 +984,6 @@ For details about the error codes, see [USB Service Error Codes](errorcode-usb.m | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | | 801 | Capability not supported. | -**Return value** - -| Type| Description| -| -------- | -------- | -| number | Returns **0** if the USB device pipe is closed successfully; returns an error code otherwise. The error codes are as follows:
- 63: The data exceeds the expected maximum volume.
- 88080393: An error occurs when the API data packet is read.
- 88080482: An invalid value or parameter occurs during the service.
- 88080484: No permission.
- 88080493: An error occurs when the service data packet is read.
- 88080497: An error occurs when the internal logic of the service is executed.
- -1: The underlying interface fails to be called.| - **Example** ```ts @@ -1014,6 +1014,12 @@ You need to call [usbManager.getAccessoryList](#usbmanagergetaccessorylist14) to | --------- | ------------ | ---- | ------------------------------------- | | accessory | [USBAccessory](#usbaccessory14) | Yes | USB accessory.| +**Returns** + +| Type | Description | +| ------- | ----------------------------- | +| boolean | The value **true** indicates that the application has the permission to access the USB accessory; **false** indicates the opposite.| + **Error codes** For details about the error codes, see [USB Service Error Codes](errorcode-usb.md). @@ -1026,12 +1032,6 @@ For details about the error codes, see [USB Service Error Codes](errorcode-usb.m | 14400005 | Database operation exception. | | 14401001 | The target USBAccessory not matched. | -**Return value** - -| Type | Description | -| ------- | ----------------------------- | -| boolean | The value **true** indicates that the application has the permission to access the USB accessory; **false** indicates the opposite.| - **Example** ```ts @@ -1061,6 +1061,12 @@ You need to call [usbManager.getAccessoryList](#usbmanagergetaccessorylist14) to | --------- | ------------ | ---- | ------------------------------------- | | accessory | [USBAccessory](#usbaccessory14) | Yes | USB accessory.| +**Returns** + +| Type | Description | +| ---------------- | ----------------------------- | +| Promise<boolean> | Promise used to return the application result. The value **true** indicates that the device access permissions are granted; **false** indicates the opposite.| + **Error codes** For details about the error codes, see [USB Service Error Codes](errorcode-usb.md). @@ -1073,12 +1079,6 @@ For details about the error codes, see [USB Service Error Codes](errorcode-usb.m | 14400005 | Database operation exception. | | 14401001 | The target USBAccessory not matched. | -**Return value** - -| Type | Description | -| ---------------- | ----------------------------- | -| Promise<boolean> | Promise used to return the application result. The value **true** indicates that the device access permissions are granted; **false** indicates the opposite.| - **Example** ```ts @@ -1142,6 +1142,12 @@ Obtains the list of USB accessories connected to the host. **System capability**: SystemCapability.USB.USBManager +**Returns** + +| Type | Description | +| ----------------------------- | -------------------------------------------------- | +| Array | List of USB accessories (read-only). Currently, only one USB accessory is contained in the list.| + **Error codes** For details about the error codes, see [USB Service Error Codes](errorcode-usb.md). @@ -1151,12 +1157,6 @@ For details about the error codes, see [USB Service Error Codes](errorcode-usb.m | 801 | Capability not supported. | | 14400004 | Service exception. Possible causes: 1. No accessory is plugged in. | -**Return value** - -| Type | Description | -| ----------------------------- | -------------------------------------------------- | -| Array | List of USB accessories (read-only). Currently, only one USB accessory is contained in the list.| - **Example** ```ts @@ -1173,7 +1173,7 @@ try { openAccessory(accessory: USBAccessory): USBAccessoryHandle -Obtains the accessory handle and opens the accessory file descriptor. +Obtains the accessory handle and opens the accessory file descriptor. Then, the host can communicate with the accessory through the **read** and **write** APIs provided by Core File Kit. You need to call [usbManager.getAccessoryList](#usbmanagergetaccessorylist14) to obtain the accessory list and use [USBAccessory](#usbaccessory14) as a parameter. @@ -1185,6 +1185,12 @@ You need to call [usbManager.getAccessoryList](#usbmanagergetaccessorylist14) to | --------- | ------------ | ---- | ------------------------------------- | | accessory | [USBAccessory](#usbaccessory14) | Yes | USB accessory.| +**Returns** + +| Type | Description | +| ------------------ | ----------- | +| [USBAccessoryHandle](#usbaccessoryhandle14) | USB accessory handle.| + **Error codes** For details about the error codes, see [USB Service Error Codes](errorcode-usb.md). @@ -1193,27 +1199,25 @@ For details about the error codes, see [USB Service Error Codes](errorcode-usb.m | -------- | ------------------------------------------------------------ | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | | 801 | Capability not supported. | -| 14400001 | Permission denied. Call requestAccessoryRight to get the right first. | +| 14400001 | Access right denied. Call requestRight to get the USBDevicePipe access right first. | | 14400004 | Service exception. Possible causes: 1. No accessory is plugged in. | | 14401001 | The target USBAccessory not matched. | | 14401002 | Failed to open the native accessory node. | | 14401003 | Cannot reopen the accessory. | -**Return value** - -| Type | Description | -| ------------------ | ----------- | -| [USBAccessoryHandle](#usbaccessoryhandle14) | USB accessory handle.| - **Example** ```ts import { hilog } from '@kit.PerformanceAnalysisKit'; +import { fileIo as fs } from '@kit.CoreFileKit'; try { let accList: usbManager.USBAccessory[] = usbManager.getAccessoryList() let flag = usbManager.requestAccessoryRight(accList[0]) let handle = usbManager.openAccessory(accList[0]) hilog.info(0, 'testTag ui', `openAccessory success`) + let arrayBuffer = new ArrayBuffer(4096); + let readLength = fs.readSync(handle.accessoryFd, arrayBuffer, {offset: 0, length: 4096}); + hilog.info(0, 'testTag ui', 'readSync ret: ' + readLength.toString(10)); } catch (error) { hilog.info(0, 'testTag ui', `openAccessory error ${error.code}, message is ${error.message}`) } @@ -1233,7 +1237,7 @@ You need to call [usbManager.openAccessory](#usbmanageropenaccessory14) to obtai | Name | Type | Mandatory| Description | | --------------- | ------------------ | ---- | -------------------------------------- | -| accessoryHandle | [USBAccessoryHandle](#usbaccessoryhandle14) | Yes | USB accessory handle, obtained through [openAccessory](#usbmanageropenaccessory14).| +| accessoryHandle | [USBAccessoryHandle](#usbaccessoryhandle14) | Yes | USB accessory handle. | **Error codes** @@ -1260,6 +1264,63 @@ try { } ``` +## usbManager.resetUsbDevice20+ + +resetUsbDevice(pipe: USBDevicePipe): boolean + +Resets a USB peripheral. + +Previous configurations and APIs will be reset. Ensure that the related services have been completed before calling this API. Before calling this API, perform the following operations: + +1. Call [usbManager.getDevices](#usbmanagergetdevices) to obtain the device list. +2. Call [usbManager.requestRight](#usbmanagerrequestright) to request the device access permission. +3. Call [usbManager.connectDevice](#usbmanagerconnectdevice) to obtain **devicepipe** as the input parameter of this API. + +**System capability**: SystemCapability.USB.USBManager + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| USB device pipe, which is used to determine the bus number and device address. You need to call **connectDevice** to obtain its value.| + +**Returns** + +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the device is reset successfully; returns **false** otherwise.| + +**Error codes** + +For details about the error codes, see [USB Service Error Codes](errorcode-usb.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 801 | Capability not supported. | +| 14400001 | Access right denied. Call requestRight to get the USBDevicePipe access right first.| +| 14400004 | Service exception. Possible causes: 1. No accessory is plugged in. | +| 14400008 | No such device (it may have been disconnected). | +| 14400010 | Other USB error. Possible causes:
1.Unrecognized discard error code. | +| 14400013 | The USBDevicePipe validity check failed. Possible causes:
1. The input parameters fail the validation check.
2. The call chain used to obtain the input parameters is not reasonable. | + +**Example** + +```ts +let devicesList: Array = usbManager.getDevices(); +if (devicesList.length == 0) { + console.error(`device list is empty`); +} + +usbManager.requestRight(devicesList[0].name); +let devicepipe: usbManager.USBDevicePipe = usbManager.connectDevice(devicesList[0]); +try { + let ret: boolean = usbManager.resetUsbDevice(devicepipe); + console.info(`resetUsbDevice = ${ret}`); +} catch (err) { + console.error(`resetUsbDevice failed: ` + err); +} +``` + ## USBEndpoint Represents the USB endpoint from which data is sent or received. You can obtain the USB endpoint through [USBInterface](#usbinterface). @@ -1494,7 +1555,7 @@ Transfers USB data packets in an asynchronous manner. ## UsbTransferStatus18+ -Enumerates the statuses returned by **libusb** through callback after the actual processing is complete. +Enumerates the status code returned after data processing is complete. **System capability**: SystemCapability.USB.USBManager diff --git a/en/application-dev/reference/apis-basic-services-kit/js-apis-wallpaper-sys.md b/en/application-dev/reference/apis-basic-services-kit/js-apis-wallpaper-sys.md index 6b53bbc814e..0b7578413de 100644 --- a/en/application-dev/reference/apis-basic-services-kit/js-apis-wallpaper-sys.md +++ b/en/application-dev/reference/apis-basic-services-kit/js-apis-wallpaper-sys.md @@ -573,7 +573,7 @@ Sets a specified source as the wallpaper of a specified type. This API uses an a | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| source | string \| [image.PixelMap](../apis-image-kit/js-apis-image.md) | Yes| URI of a JPEG or PNG file, or pixel map of a PNG file.| +| source | string \| [image.PixelMap](../apis-image-kit/arkts-apis-image-PixelMap.md) | Yes| URI of a JPEG or PNG file, or pixel map of a PNG file.| | wallpaperType | [WallpaperType](js-apis-wallpaper.md#wallpapertype7) | Yes| Wallpaper type.| | callback | AsyncCallback<void> | Yes| Callback used to return the result. If the wallpaper is set, **err** is **undefined**. Otherwise, **err** is an error object.| @@ -640,7 +640,7 @@ Sets a specified source as the wallpaper of a specified type. This API uses a pr | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| source | string \| [image.PixelMap](../apis-image-kit/js-apis-image.md) | Yes| URI of a JPEG or PNG file, or pixel map of a PNG file.| +| source | string \| [image.PixelMap](../apis-image-kit/arkts-apis-image-PixelMap.md) | Yes| URI of a JPEG or PNG file, or pixel map of a PNG file.| | wallpaperType | [WallpaperType](js-apis-wallpaper.md#wallpapertype7) | Yes| Wallpaper type.| **Return value** @@ -694,7 +694,7 @@ imageSource.createPixelMap(opts).then((pixelMap: image.PixelMap) => { ## wallpaper.getImage9+ -getImage(wallpaperType: WallpaperType, callback: AsyncCallback<image.PixelMap>): void; +getImage(wallpaperType: WallpaperType, callback: AsyncCallback<image.PixelMap>): void Obtains the pixel map for the wallpaper of the specified type. This API only works for the static wallpaper set using **setImage**. This API uses an asynchronous callback to return the result. @@ -709,7 +709,7 @@ Obtains the pixel map for the wallpaper of the specified type. This API only wor | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | wallpaperType | [WallpaperType](js-apis-wallpaper.md#wallpapertype7) | Yes| Wallpaper type.| -| callback | AsyncCallback<[image.PixelMap](../apis-image-kit/js-apis-image.md)> | Yes| Callback used to return the result. If the operation is successful, the pixel map of the wallpaper is returned. Otherwise, error information is returned.| +| callback | AsyncCallback<[image.PixelMap](../apis-image-kit/arkts-apis-image-PixelMap.md)> | Yes| Callback used to return the result. If the operation is successful, the pixel map of the wallpaper is returned. Otherwise, error information is returned.| **Error codes** @@ -758,7 +758,7 @@ Obtains the pixel map for the wallpaper of the specified type. This API only wor | Type| Description| | -------- | -------- | -| Promise<[image.PixelMap](../apis-image-kit/js-apis-image.md)> | Promise used to return the result. If the operation is successful, the pixel map of the wallpaper is returned. Otherwise, error information is returned.| +| Promise<[image.PixelMap](../apis-image-kit/arkts-apis-image-PixelMap.md)> | Promise used to return the result. If the operation is successful, the pixel map of the wallpaper is returned. Otherwise, error information is returned.| **Error codes** @@ -806,7 +806,7 @@ Obtains the pixel map of the wallpaper of a specific type, folding state, or lan | Type| Description| | -------- | -------- | -| Promise<[image.PixelMap](../apis-image-kit/js-apis-image.md)> | Promise used to return the result. If the operation is successful, the pixel map of the wallpaper is returned. Otherwise, error information is returned.| +| Promise<[image.PixelMap](../apis-image-kit/arkts-apis-image-PixelMap.md)> | Promise used to return the result. If the operation is successful, the pixel map of the wallpaper is returned. Otherwise, error information is returned.| **Error codes** @@ -900,7 +900,7 @@ wallpaper.setAllWallpapers(wallpaperInfos, wallpaper.WallpaperType.WALLPAPER_SYS ## wallpaper.getPixelMap(deprecated) -getPixelMap(wallpaperType: WallpaperType, callback: AsyncCallback<image.PixelMap>): void; +getPixelMap(wallpaperType: WallpaperType, callback: AsyncCallback<image.PixelMap>): void Obtains the pixel map for the wallpaper of the specified type. diff --git a/en/application-dev/reference/apis-basic-services-kit/js-apis-wallpaper.md b/en/application-dev/reference/apis-basic-services-kit/js-apis-wallpaper.md index 1f05f9ff0c0..c4d6d84152a 100644 --- a/en/application-dev/reference/apis-basic-services-kit/js-apis-wallpaper.md +++ b/en/application-dev/reference/apis-basic-services-kit/js-apis-wallpaper.md @@ -672,7 +672,7 @@ Sets a specified source as the wallpaper of a specified type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| source | string \| [image.PixelMap](../apis-image-kit/js-apis-image.md) | Yes| URI of a JPEG or PNG file, or pixel map of a PNG file.| +| source | string \| [image.PixelMap](../apis-image-kit/arkts-apis-image-PixelMap.md) | Yes| URI of a JPEG or PNG file, or pixel map of a PNG file.| | wallpaperType | [WallpaperType](#wallpapertype7) | Yes| Wallpaper type.| | callback | AsyncCallback<void> | Yes| Callback used to return the result. If the wallpaper is set, **err** is **undefined**. Otherwise, **err** is an error object.| @@ -731,7 +731,7 @@ Sets a specified source as the wallpaper of a specified type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| source | string \| [image.PixelMap](../apis-image-kit/js-apis-image.md) | Yes| URI of a JPEG or PNG file, or pixel map of a PNG file.| +| source | string \| [image.PixelMap](../apis-image-kit/arkts-apis-image-PixelMap.md) | Yes| URI of a JPEG or PNG file, or pixel map of a PNG file.| | wallpaperType | [WallpaperType](#wallpapertype7) | Yes| Wallpaper type.| **Return value** diff --git a/en/application-dev/reference/apis-basic-services-kit/js-apis-zlib.md b/en/application-dev/reference/apis-basic-services-kit/js-apis-zlib.md index fd183d77823..b2eeeb2717b 100644 --- a/en/application-dev/reference/apis-basic-services-kit/js-apis-zlib.md +++ b/en/application-dev/reference/apis-basic-services-kit/js-apis-zlib.md @@ -31,7 +31,7 @@ Zips a file. This API uses a promise to return the result. | outFile | string | Yes | Path of the zipped file. The file name extension is .zip. | | options | [Options](#options) | Yes | Optional parameters for the zip operation. | -**Return value** +**Returns** | Type | Description | | -------------- | ------------------------------------------------------------ | @@ -67,6 +67,8 @@ Unzips a file. This API uses a promise to return the result. > **NOTE** > > This API is supported since API version 7 and deprecated since API version 9. You are advised to use [zlib.decompressFile](#zlibdecompressfile9) instead. +> +> The name of the zipped file or zipped folder cannot contain two consecutive periods (..) or start with a slash (/). **System capability**: SystemCapability.BundleManager.Zlib @@ -74,11 +76,11 @@ Unzips a file. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ------- | ------------------- | ---- | ------------------------------------------------------------ | -| inFile | string | Yes | Path of the file to unzip. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](../apis-ability-kit/js-apis-inner-app-context.md) and [Stage Model](../apis-ability-kit/js-apis-inner-application-context.md).| +| inFile | string | Yes | Path of the file to unzip. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](../apis-ability-kit/js-apis-inner-app-context.md) and [Stage Model](../apis-ability-kit/js-apis-inner-application-context.md). If the.zip file to be unzipped contains Chinese file names or folder names, use UTF-8 to encode them. Otherwise, garbled characters may be displayed after unzipping.| | outFile | string | Yes | Path of the unzipped file. | | options | [Options](#options) | Yes | Optional parameters for the unzip operation. | -**Return value** +**Returns** | Type | Description | | -------------- | ------------------------------------------------------------ | @@ -113,7 +115,7 @@ Compresses a file. This API uses an asynchronous callback to return the result. > **NOTE** > ->To avoid path traversal, the input parameters of **inFile** and **outFile** cannot contain **../** since API version 13. Otherwise, error codes 900001 and 900002 are returned. +> To avoid path traversal, the input parameters of **inFile** and **outFile** cannot contain **../** since API version 13. Otherwise, error codes 900001 and 900002 are returned. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -173,7 +175,7 @@ Compresses a file. This API uses a promise to return the result. If the operatio > **NOTE** > ->To avoid path traversal, the input parameters of **inFile** and **outFile** cannot contain **../** since API version 13. Otherwise, error codes 900001 and 900002 are returned. +> To avoid path traversal, the input parameters of **inFile** and **outFile** cannot contain **../** since API version 13. Otherwise, error codes 900001 and 900002 are returned. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -187,7 +189,7 @@ Compresses a file. This API uses a promise to return the result. If the operatio | outFile | string | Yes | Path of the compressed file. When multiple threads compress files at the same time, the values of **outFile** must be different. | | options | [Options](#options) | Yes | Compression parameters. | -**Return value** +**Returns** | Type | Description | | -------------- | ----------------------- | @@ -238,7 +240,9 @@ Decompresses a file. This API uses an asynchronous callback to return the result > **NOTE** > ->To avoid path traversal, the input parameters of **inFile** and **outFile** cannot contain **../** since API version 13. Otherwise, error codes 900001 and 900002 are returned. +> To avoid path traversal, the input parameters of **inFile** and **outFile** cannot contain **../** since API version 13. Otherwise, error codes 900001 and 900002 are returned. +> +> The name of the zipped file or zipped folder cannot contain two consecutive periods (..) or start with a slash (/). Otherwise, the error code 900003 is returned. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -248,7 +252,7 @@ Decompresses a file. This API uses an asynchronous callback to return the result | Name | Type | Mandatory| Description | | ----------------------- | ------------------- | ---- | ------------------------------------------------------------ | -| inFile | string | Yes | Path of the file to decompress. The file name extension must be .zip. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](../apis-ability-kit/js-apis-inner-app-context.md) and [Stage Model](../apis-ability-kit/js-apis-inner-application-context.md).| +| inFile | string | Yes | Path of the file to decompress. The file name extension must be .zip. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](../apis-ability-kit/js-apis-inner-app-context.md) and [Stage Model](../apis-ability-kit/js-apis-inner-application-context.md). If the.zip file to be unzipped contains Chinese file names or folder names, use UTF-8 to encode them. Otherwise, garbled characters may be displayed after unzipping.| | outFile | string | Yes | Path of the decompressed file. The path must exist in the system. Otherwise, the decompression fails. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](../apis-ability-kit/js-apis-inner-app-context.md) and [Stage Model](../apis-ability-kit/js-apis-inner-application-context.md). If a file or folder with the same name already exists in the path, they will be overwritten. When multiple threads decompress files at the same time, the values of **outFile** must be different.| | options | [Options](#options) | Yes | Decompression parameters. | | callback | AsyncCallback\ | Yes | Callback used to return the result. | @@ -298,7 +302,9 @@ Decompresses a file. This API uses a promise to return the result. > **NOTE** > ->To avoid path traversal, the input parameters of **inFile** and **outFile** cannot contain **../** since API version 13. Otherwise, error codes 900001 and 900002 are returned. +> To avoid path traversal, the input parameters of **inFile** and **outFile** cannot contain **../** since API version 13. Otherwise, error codes 900001 and 900002 are returned. +> +> The name of the zipped file or zipped folder cannot contain two consecutive periods (..) or start with a slash (/). Otherwise, the error code 900003 is returned. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -308,11 +314,11 @@ Decompresses a file. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ------- | ------------------- | ---- | ------------------------------------------------------------ | -| inFile | string | Yes | Path of the file to decompress. The file name extension must be .zip. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](../apis-ability-kit/js-apis-inner-app-context.md) and [Stage Model](../apis-ability-kit/js-apis-inner-application-context.md).| +| inFile | string | Yes | Path of the file to decompress. The file name extension must be .zip. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](../apis-ability-kit/js-apis-inner-app-context.md) and [Stage Model](../apis-ability-kit/js-apis-inner-application-context.md). If the.zip file to be unzipped contains Chinese file names or folder names, use UTF-8 to encode them. Otherwise, garbled characters may be displayed after unzipping.| | outFile | string | Yes | Path of the decompressed file. The path must exist in the system. Otherwise, the decompression fails. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](../apis-ability-kit/js-apis-inner-app-context.md) and [Stage Model](../apis-ability-kit/js-apis-inner-application-context.md). If a file or folder with the same name already exists in the path, they will be overwritten. When multiple threads decompress files at the same time, the values of **outFile** must be different.| | options | [Options](#options) | No | Decompression parameters. | -**Return value** +**Returns** | Type | Description | | -------------- | ----------------------- | @@ -362,7 +368,9 @@ Decompresses a file. This API uses an asynchronous callback to return the result > **NOTE** > ->To avoid path traversal, the input parameters of **inFile** and **outFile** cannot contain **../** since API version 13. Otherwise, error codes 900001 and 900002 are returned. +> To avoid path traversal, the input parameters of **inFile** and **outFile** cannot contain **../** since API version 13. Otherwise, error codes 900001 and 900002 are returned. +> +> The name of the zipped file or zipped folder cannot contain two consecutive periods (..) or start with a slash (/). Otherwise, the error code 900003 is returned. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -372,7 +380,7 @@ Decompresses a file. This API uses an asynchronous callback to return the result | Name | Type | Mandatory| Description | | ----------------------- | ------------------- | ---- | ------------------------------------------------------------ | -| inFile | string | Yes | Path of the file to decompress. The file name extension must be .zip. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](../apis-ability-kit/js-apis-inner-app-context.md) and [Stage Model](../apis-ability-kit/js-apis-inner-application-context.md).| +| inFile | string | Yes | Path of the file to decompress. The file name extension must be .zip. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](../apis-ability-kit/js-apis-inner-app-context.md) and [Stage Model](../apis-ability-kit/js-apis-inner-application-context.md). If the.zip file to be unzipped contains Chinese file names or folder names, use UTF-8 to encode them. Otherwise, garbled characters may be displayed after unzipping.| | outFile | string | Yes | Path of the decompressed file. The path must exist in the system. Otherwise, the decompression fails. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](../apis-ability-kit/js-apis-inner-app-context.md) and [Stage Model](../apis-ability-kit/js-apis-inner-application-context.md). If a file or folder with the same name already exists in the path, they will be overwritten. When multiple threads decompress files at the same time, the values of **outFile** must be different.| | callback | AsyncCallback\ | Yes | Callback used to return the result. | @@ -425,7 +433,7 @@ Obtains the original size of a compressed file and uses a promise to asynchronou | ------- | ------------------- | ---- | ------------------------------------------------------------ | | compressedFile | string | Yes | Specifies the path of the compressed file. Only .zip files are supported. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](../apis-ability-kit/js-apis-inner-app-context.md) and [Stage Model](../apis-ability-kit/js-apis-inner-application-context.md).| -**Return value** +**Returns** | Type | Description | | -------------- | ----------------------- | @@ -480,7 +488,7 @@ Compresses multiple specified files and uses a promise to asynchronously return | outFile | string | Yes | Path of the compressed file. When multiple threads compress files at the same time, the values of **outFile** must be different.| | options | [Options](#options) | Yes | Compression parameters. | -**Return value** +**Returns** | Type | Description | | ------------------- | ----------------------- | @@ -534,7 +542,7 @@ Creates a checksum object and uses a promise to asynchronously return the result **System capability**: SystemCapability.BundleManager.Zlib -**Return value** +**Returns** | Type | Description | | -------------------------------------- | ------------------------------- | @@ -560,7 +568,7 @@ Creates a checksum object. A checksum object instance is returned upon a success **System capability**: SystemCapability.BundleManager.Zlib -**Return value** +**Returns** | Type | Description | | ----------------------- | -------------- | @@ -595,7 +603,7 @@ Calculates the Adler-32 checksum. This API uses a promise to return the result. | adler | number | Yes | Initial value of the Adler-32 checksum.| | buf | ArrayBuffer | Yes | Data buffer for calculating the checksum. | -**Return value** +**Returns** | Type | Description | | --------------------- | ----------------------------------------- | @@ -647,7 +655,7 @@ Combines two Adler-32 checksums. This API uses a promise to return the result. T | adler2 | number | Yes | The second Adler-32 checksum to be combined. | | len2 | number | Yes | Length of the data block of the second Adler-32 checksum.| -**Return value** +**Returns** | Type | Description | | --------------------- | ----------------------------------------- | @@ -709,7 +717,7 @@ Updates the CRC-32 checksum. This API uses a promise to return the result. The u | crc | number | Yes | Initial value of the CRC-32 checksum.| | buf | ArrayBuffer | Yes | Data buffer for calculating the checksum.| -**Return value** +**Returns** | Type | Description | | --------------------- | ------------------------------------- | @@ -763,7 +771,7 @@ Combines two CRC-32 checksums and uses a promise to asynchronously return the re | crc2 | number | Yes | The second CRC-32 checksum to be combined. | | len2 | number | Yes | Indicates the length of the second data block checked by CRC-32| -**Return value** +**Returns** | Type | Description | | --------------------- | ------------------------------------- | @@ -825,11 +833,11 @@ Updates the CRC-64 checksum. This API uses a promise to return the result. The u | crc | number | Yes | Initial value of the CRC-64 checksum.| | buf | ArrayBuffer | Yes | Data buffer for calculating the checksum.| -**Return value** +**Returns** | Type | Description | | --------------------- | ------------------------------------- | -| Promise<number> | Promise used to return the result. | +| Promise<number> | Promise used to return the result. | **Error codes** @@ -871,7 +879,7 @@ Outputs the CRC-32 checksum table and uses a promise to asynchronously return th **System capability**: SystemCapability.BundleManager.Zlib -**Return value** +**Returns** | Type | Description | | ---------------------------------- | ------------------------------- | @@ -901,7 +909,7 @@ Outputs the CRC-64 checksum table and uses a promise to asynchronously return th **System capability**: SystemCapability.BundleManager.Zlib -**Return value** +**Returns** | Type | Description | | ---------------------------------- | ------------------------------- | @@ -931,7 +939,7 @@ Creates an instance of a compressed or decompressed object and uses a promise to **System capability**: SystemCapability.BundleManager.Zlib -**Return value** +**Returns** | Type | Description | | ---------------------------- | ------------------------------------- | @@ -961,7 +969,7 @@ Creates an instance of a compressed or decompressed object. The instance of the **System capability**: SystemCapability.BundleManager.Zlib -**Return value** +**Returns** | Type | Description | | ------------- | ------------------------ | @@ -977,19 +985,19 @@ let zip = zlib.createZipSync(); ## Zip12+ -Compresses and decompresses an object instance. +Provides APIs to zip or unzip data in Zlib, Deflate, or Gzip format. ### getZStream12+ getZStream(): Promise<ZStream> -Outputs a stream. This API uses a promise to return the result. A zlib stream is returned upon success. +Outputs a stream. 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.BundleManager.Zlib -**Return value** +**Returns** | Type | Description | | ------------------------------------ | ------------------------- | @@ -1017,7 +1025,7 @@ Obtains the version information of the currently linked **zlib** library. This A **System capability**: SystemCapability.BundleManager.Zlib -**Return value** +**Returns** | Type | Description | | --------------------- | --------------------------------------- | @@ -1045,7 +1053,7 @@ Returns a flag indicating a compile-time option. This API uses a promise to retu **System capability**: SystemCapability.BundleManager.Zlib -**Return value** +**Returns** | Type | Description | | --------------------- | --------------------------------------- | @@ -1079,9 +1087,9 @@ Compresses the source buffer to the destination buffer. This API uses a promise | --------- | ----------- | ---- | -------------- | | dest | ArrayBuffer | Yes | Destination buffer. | | source | ArrayBuffer | Yes | Source buffer.| -| sourceLen | number | No | Length of the source data. | +| sourceLen | number | No | Length of the source data. The default value is **0**. | -**Return value** +**Returns** | Type | Description | | ------------------------------------------------ | ----------------------------------------------- | @@ -1094,7 +1102,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | | 401 | The parameter check failed. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | -| 17800007 | Buffer error. | +| 17800007 | The input buffer is incorrect, and the output buffer is too small to accommodate the compressed or decompressed data. | **Example** @@ -1136,9 +1144,9 @@ Compresses the source buffer to the destination buffer. This API uses a promise | dest | ArrayBuffer | Yes | Destination buffer. | | source | ArrayBuffer | Yes | Source buffer. | | level | CompressLevel | Yes | For details, see [CompressLevel](#compresslevel).| -| sourceLen | number | No | Length of the source data. | +| sourceLen | number | No | Length of the source data. The default value is **0**. | -**Return value** +**Returns** | Type | Description | | ------------------------------------------------ | ----------------------------------------------- | @@ -1151,8 +1159,8 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | | 401 | The parameter check failed. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | -| 17800004 | ZStream error. | -| 17800007 | Buffer error. | +| 17800004 | Compression or decompression stream error, which may be caused by an initialization error in the zlib stream structure or a modified structure. | +| 17800007 | The input buffer is incorrect, and the output buffer is too small to accommodate the compressed or decompressed data. | **Example** @@ -1193,9 +1201,9 @@ Decompresses the compressed data into the original form. This API uses a promise | --------- | ----------- | ---- | -------------- | | dest | ArrayBuffer | Yes | Destination buffer. | | source | ArrayBuffer | Yes | Source buffer.| -| sourceLen | number | No | Length of the source data. | +| sourceLen | number | No | Length of the source data. The default value is **0**. | -**Return value** +**Returns** | Type | Description | | ------------------------------------------------ | ----------------------------------------------- | @@ -1208,8 +1216,8 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | | 401 | The parameter check failed. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | -| 17800005 | Data error. | -| 17800007 | Buffer error. | +| 17800005 | The input data is incorrect. For example, the data does not conform to the zlib compression format, the compressed data is corrupted, or the data is not compressed. | +| 17800007 | The input buffer is incorrect, and the output buffer is too small to accommodate the compressed or decompressed data. | **Example** @@ -1254,9 +1262,9 @@ Decompresses the compressed data into the original form. This API uses a promise | --------- | ----------- | ---- | -------------- | | dest | ArrayBuffer | Yes | Destination buffer. | | source | ArrayBuffer | Yes | Source buffer.| -| sourceLen | number | No | Length of the source data. | +| sourceLen | number | No | Length of the source data. The default value is **0**. | -**Return value** +**Returns** | Type | Description | | ------------------------------------------------------------ | ----------------------------------------------------------- | @@ -1269,8 +1277,8 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | | 401 | The parameter check failed. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | -| 17800005 | Data error. | -| 17800007 | Buffer error. | +| 17800005 | The input data is incorrect. For example, the data does not conform to the zlib compression format, the compressed data is corrupted, or the data is not compressed. | +| 17800007 | The input buffer is incorrect, and the output buffer is too small to accommodate the compressed or decompressed data. | **Example** @@ -1315,7 +1323,7 @@ Calculates the maximum size of the compressed data to be returned. This API uses | --------- | ------ | ---- | ------------ | | sourceLen | number | Yes | Length of the source data.| -**Return value** +**Returns** | Type | Description | | --------------------- | --------------------------------- | @@ -1368,7 +1376,7 @@ Verifies the checksum inside the compressed stream. This API uses a promise to r | strm | ZStream | Yes | For details, see [ZStream12+](#zstream12).| | check | number | Yes | Expected checksum. | -**Return value** +**Returns** | Type | Description | | ---------------------------------------------- | --------------------------- | @@ -1381,7 +1389,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | | 401 | The parameter check failed. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | -| 17800004 | ZStream error. | +| 17800004 | Compression or decompression stream error, which may be caused by an initialization error in the zlib stream structure or a modified structure. | **Example** @@ -1427,7 +1435,7 @@ Finds the synchronization point of the current decompressed stream. This API use | ------ | ------- | ---- | ------------------------------- | | strm | ZStream | Yes | For details, see [ZStream12+](#zstream12).| -**Return value** +**Returns** | Type | Description | | ---------------------------------------------- | --------------------------- | @@ -1440,7 +1448,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | | 401 | The parameter check failed. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | -| 17800004 | ZStream error. | +| 17800004 | Compression or decompression stream error, which may be caused by an initialization error in the zlib stream structure or a modified structure. | **Example** @@ -1486,7 +1494,7 @@ Skips invalid compressed data until a complete re-render point is found. This AP | ------ | ------- | ---- | ------------------------------- | | strm | ZStream | Yes | For details, see [ZStream12+](#zstream12).| -**Return value** +**Returns** | Type | Description | | ---------------------------------------------- | --------------------------- | @@ -1499,9 +1507,9 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | | 401 | The parameter check failed. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | -| 17800004 | ZStream error. | -| 17800005 | Data error. | -| 17800007 | Buffer error. | +| 17800004 | Compression or decompression stream error, which may be caused by an initialization error in the zlib stream structure or a modified structure. | +| 17800005 | The input data is incorrect. For example, the data does not conform to the zlib compression format, the compressed data is corrupted, or the data is not compressed. | +| 17800007 | The input buffer is incorrect, and the output buffer is too small to accommodate the compressed or decompressed data. | **Example** @@ -1578,7 +1586,7 @@ Resets the state of the decompressed stream to preserve the allocated Huffman Tr | ------ | ------- | ---- | ------------------------------- | | strm | ZStream | Yes | For details, see [ZStream12+](#zstream12).| -**Return value** +**Returns** | Type | Description | | ---------------------------------------------- | --------------------------- | @@ -1591,7 +1599,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | | 401 | The parameter check failed. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | -| 17800004 | ZStream error. | +| 17800004 | Compression or decompression stream error, which may be caused by an initialization error in the zlib stream structure or a modified structure. | **Example** @@ -1638,7 +1646,7 @@ Initializes the decompression dictionary from a given uncompressed byte sequence | strm | ZStream | Yes | For details, see [ZStream12+](#zstream12).| | dictionary | ArrayBuffer | Yes | Dictionary data. | -**Return value** +**Returns** | Type | Description | | ---------------------------------------------- | --------------------------- | @@ -1651,8 +1659,8 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | | 401 | The parameter check failed. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | -| 17800004 | ZStream error. | -| 17800005 | Data error. | +| 17800004 | Compression or decompression stream error, which may be caused by an initialization error in the zlib stream structure or a modified structure. | +| 17800005 | The input data is incorrect. For example, the data does not conform to the zlib compression format, the compressed data is corrupted, or the data is not compressed. | **Example** @@ -1734,9 +1742,9 @@ Initializes the decompression dictionary from a given uncompressed byte sequence | Name | Type | Mandatory| Description | | ---------- | ------- | ---- | ------------------------------- | | strm | ZStream | Yes | For details, see [ZStream12+](#zstream12).| -| windowBits | number | Yes | The logarithm with base 2 based on the maximum window size. | +| windowBits | number | Yes | Memory window size. The value is restricted in certain range based on the data formats. The options are as follows:
Zlib: [1, 15]
Gzip: (15, +∞)
Raw Deflate: [-15, -1] | -**Return value** +**Returns** | Type | Description | | ---------------------------------------------- | --------------------------- | @@ -1749,7 +1757,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | | 401 | The parameter check failed. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | -| 17800004 | ZStream error. | +| 17800004 | Compression or decompression stream error, which may be caused by an initialization error in the zlib stream structure or a modified structure. | **Example** @@ -1795,7 +1803,7 @@ Equivalent to call the **inflateEnd** API and then **inflateInit** API. However, | ------ | ------- | ---- | ------------------------------- | | strm | ZStream | Yes | For details, see [ZStream12+](#zstream12).| -**Return value** +**Returns** | Type | Description | | ---------------------------------------------- | --------------------------- | @@ -1808,7 +1816,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | | 401 | The parameter check failed. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | -| 17800004 | ZStream error. | +| 17800004 | Compression or decompression stream error, which may be caused by an initialization error in the zlib stream structure or a modified structure. | **Example** @@ -1856,7 +1864,7 @@ Initializes the decompression dictionary from a given uncompressed byte sequence | bits | number | Yes | Given bits. | | value | number | Yes | Given value. | -**Return value** +**Returns** | Type | Description | | ---------------------------------------------- | --------------------------- | @@ -1869,7 +1877,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | | 401 | The parameter check failed. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | -| 17800004 | ZStream error. | +| 17800004 | Compression or decompression stream error, which may be caused by an initialization error in the zlib stream structure or a modified structure. | **Example** @@ -1915,7 +1923,7 @@ Marks the location of the input data for random access. This API uses a promise | ------ | ------- | ---- | ------------------------------- | | strm | ZStream | Yes | For details, see [ZStream12+](#zstream12).| -**Return value** +**Returns** | Type | Description | | --------------------- | --------------------------- | @@ -1972,9 +1980,9 @@ Initializes the internal stream state for decompression. This API uses a promise | Name | Type | Mandatory| Description | | ---------- | ------- | ---- | ------------------------------- | | strm | ZStream | Yes | For details, see [ZStream12+](#zstream12).| -| windowBits | number | Yes | The logarithm with base 2 based on the maximum window size. | +| windowBits | number | Yes | Memory window size. The value is restricted in certain range based on the data formats. The options are as follows:
Zlib: [1, 15]
Gzip: (15, +∞)
Raw Deflate: [-15, -1] | -**Return value** +**Returns** | Type | Description | | ---------------------------------------------- | --------------------------- | @@ -1987,7 +1995,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | | 401 | The parameter check failed. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | -| 17800004 | ZStream error. | +| 17800004 | Compression or decompression stream error, which may be caused by an initialization error in the zlib stream structure or a modified structure. | **Example** @@ -2029,7 +2037,7 @@ Initializes the internal stream state for decompression. This API uses a promise | ------ | ------- | ---- | ------------------------------- | | strm | ZStream | Yes | For details, see [ZStream12+](#zstream12).| -**Return value** +**Returns** | Type | Description | | ---------------------------------------------- | --------------------------- | @@ -2084,7 +2092,7 @@ Sets the header information of a gzip file before decompressing data. This API u | strm | ZStream | Yes | For details, see [ZStream12+](#zstream12). | | header | [GzHeader](#gzheader12) | Yes | Header information of a gzip file extracted from the compressed data stream.| -**Return value** +**Returns** | Type | Description | | ---------------------------------------------- | --------------------------- | @@ -2097,7 +2105,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | | 401 | The parameter check failed. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | -| 17800004 | ZStream error. | +| 17800004 | Compression or decompression stream error, which may be caused by an initialization error in the zlib stream structure or a modified structure. | **Example** @@ -2144,7 +2152,7 @@ Obtains the content and length of the decompression dictionary used in the curre | strm | ZStream | Yes | For details, see [ZStream12+](#zstream12).| | dictionary | ArrayBuffer | Yes | Receives the actual contents of the decompression dictionary. | -**Return value** +**Returns** | Type | Description | | ------------------------------------------------------------ | --------------------------------------- | @@ -2157,7 +2165,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | | 401 | The parameter check failed. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | -| 17800004 | ZStream error. | +| 17800004 | Compression or decompression stream error, which may be caused by an initialization error in the zlib stream structure or a modified structure. | **Example** @@ -2203,7 +2211,7 @@ Frees up all dynamically allocated data structures of the decompression stream. | ------ | ------- | ---- | ------------------------------- | | strm | ZStream | Yes | For details, see [ZStream12+](#zstream12).| -**Return value** +**Returns** | Type | Description | | ---------------------------------------------- | --------------------------- | @@ -2216,7 +2224,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | | 401 | The parameter check failed. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | -| 17800004 | ZStream error. | +| 17800004 | Compression or decompression stream error, which may be caused by an initialization error in the zlib stream structure or a modified structure. | **Example** @@ -2267,7 +2275,7 @@ Copies the decompression stream. This API uses a promise to return the result. T | ------ | ---- | ---- | ----------------------- | | source | Zip | Yes | For details, see [Zip12+](#zip12).| -**Return value** +**Returns** | Type | Description | | ---------------------------------------------- | --------------------------- | @@ -2280,7 +2288,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | | 401 | The parameter check failed. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | -| 17800004 | ZStream error. | +| 17800004 | Compression or decompression stream error, which may be caused by an initialization error in the zlib stream structure or a modified structure. | **Example** @@ -2326,7 +2334,7 @@ Describes the number of Huffman Trees used in the current decompression stream. | ------ | ------- | ---- | ------------------------------- | | strm | ZStream | Yes | For details, see [ZStream12+](#zstream12).| -**Return value** +**Returns** | Type | Description | | --------------------- | --------------------------------------------- | @@ -2383,10 +2391,10 @@ Initializes the internal stream state for decompression before using the **infla | Name | Type | Mandatory| Description | | ---------- | ----------- | ---- | --------------------------------------------- | | strm | ZStream | Yes | For details, see [ZStream12+](#zstream12). | -| windowBits | number | Yes | The logarithm with base 2 based on the maximum window size. The value ranges from 8 to 15.| +| windowBits | number | Yes | Memory window size. The value is restricted in certain range based on the data formats. The options are as follows:
Zlib: [1, 15]
Gzip: (15, +∞)
Raw Deflate: [-15, -1]| | window | ArrayBuffer | Yes | Preset window buffer. | -**Return value** +**Returns** | Type | Description | | ---------------------------------------------- | --------------------------- | @@ -2399,7 +2407,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | | 401 | The parameter check failed. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | -| 17800004 | ZStream error. | +| 17800004 | Compression or decompression stream error, which may be caused by an initialization error in the zlib stream structure or a modified structure. | **Example** @@ -2421,7 +2429,7 @@ Releases all memory allocated by the **inflateBackInit()** function. This API us | ------ | ------- | ---- | ------------------------------- | | strm | ZStream | Yes | For details, see [ZStream12+](#zstream12).| -**Return value** +**Returns** | Type | Description | | ---------------------------------------------- | --------------------------- | @@ -2434,7 +2442,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | | 401 | The parameter check failed. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | -| 17800004 | ZStream error. | +| 17800004 | Compression or decompression stream error, which may be caused by an initialization error in the zlib stream structure or a modified structure. | **Example** @@ -2460,7 +2468,7 @@ Uses callback APIs to input and output data for raw decompression. This API uses | backOut | InflateBackOutputCallback | Yes | Writes the decompressed data to the destination buffer. | | outDesc | object | Yes | Common object. | -**Return value** +**Returns** | Type | Description | | ---------------------------------------------- | --------------------------- | @@ -2473,7 +2481,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | | 401 | The parameter check failed. Possible causes:
1. Mandatory parameters are left unspecified.
2. Incorrect parameter types.
3. Parameter verification failed. | -| 17800004 | ZStream error. | +| 17800004 | Compression or decompression stream error, which may be caused by an initialization error in the zlib stream structure or a modified structure. | **Example** @@ -2628,7 +2636,7 @@ Inputs data. | ------ | ------ | ---- | ------------------ | | inDesc | object | Yes | User-defined data object.| -**Return value** +**Returns** | Type | Description | | ---------------------------------------------- | --------------------------- | @@ -2652,7 +2660,7 @@ Outputs data. | buf | ArrayBuffer | Yes | Stores the data to be written.| | length | number | Yes | Length of the data written to the output buffer.| -**Return value** +**Returns** | Type | Description | | ---------------------------------------------- | --------------------------- | @@ -2675,7 +2683,7 @@ Decompresses the data. This API uses a promise to return the result. The result | strm | ZStream | Yes | For details, see [ZStream12+](#zstream12). | | flush | CompressFlushMode | Yes | For details, see [CompressFlushMode](#compressflushmode12).| -**Return value** +**Returns** | Type | Description | | ---------------------------------------------- | --------------------------- | @@ -2688,8 +2696,8 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | | 401 | The parameter check failed. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | -| 17800004 | ZStream error. | -| 17800005 | Data error. | +| 17800004 | Compression or decompression stream error, which may be caused by an initialization error in the zlib stream structure or a modified structure. | +| 17800005 | The input data is incorrect. For example, the data does not conform to the zlib compression format, the compressed data is corrupted, or the data is not compressed. | **Example** @@ -2762,7 +2770,7 @@ Initializes the internal stream state for compression. This API uses a promise t | strm | ZStream | Yes | For details, see [ZStream12+](#zstream12). | | level | CompressLevel | Yes | For details, see [CompressLevel](#compresslevel).| -**Return value** +**Returns** | Type | Description | | ---------------------------------------------- | --------------------------- | @@ -2775,7 +2783,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | | 401 | The parameter check failed. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | -| 17800004 | ZStream error. | +| 17800004 | Compression or decompression stream error, which may be caused by an initialization error in the zlib stream structure or a modified structure. | **Example** @@ -2822,11 +2830,11 @@ Initializes the internal stream state for compression. This API uses a promise t | strm | ZStream | Yes | For details, see [ZStream12+](#zstream12). | | level | CompressLevel | Yes | For details, see [CompressLevel](#compresslevel). | | method | CompressMethod | Yes | For details, see [CompressMethod](#compressmethod12). | -| windowBits | number | Yes | The logarithm with base 2 based on the maximum window size. | +| windowBits | number | Yes | Memory window size. The value is restricted in certain range based on the data formats. The options are as follows:
Zlib: [1, 15]
Gzip: (15, +∞)
Raw Deflate: [-15, -1] | | memLevel | MemLevel | Yes | For details, see [MemLevel](#memlevel). | | strategy | CompressStrategy | Yes | For details, see [CompressStrategy](#compressstrategy).| -**Return value** +**Returns** | Type | Description | | ---------------------------------------------- | --------------------------- | @@ -2839,7 +2847,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | | 401 | The parameter check failed. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | -| 17800004 | ZStream error. | +| 17800004 | Compression or decompression stream error, which may be caused by an initialization error in the zlib stream structure or a modified structure. | **Example** @@ -2887,7 +2895,7 @@ Compresses data. This API uses a promise to return the result. The result state | strm | ZStream | Yes | For details, see [ZStream12+](#zstream12). | | flush | CompressFlushMode | Yes | For details, see [CompressFlushMode](#compressflushmode12).| -**Return value** +**Returns** | Type | Description | | ---------------------------------------------- | --------------------------- | @@ -2900,8 +2908,8 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | | 401 | The parameter check failed. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | -| 17800004 | ZStream error. | -| 17800007 | Buffer error. | +| 17800004 | Compression or decompression stream error, which may be caused by an initialization error in the zlib stream structure or a modified structure. | +| 17800007 | The input buffer is incorrect, and the output buffer is too small to accommodate the compressed or decompressed data. | **Example** @@ -2952,7 +2960,7 @@ Frees up all dynamically allocated data structures of the compression stream. Th | ------ | ------- | ---- | ------------------------------- | | strm | ZStream | Yes | For details, see [ZStream12+](#zstream12).| -**Return value** +**Returns** | Type | Description | | ---------------------------------------------- | --------------------------- | @@ -2965,7 +2973,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | | 401 | The parameter check failed. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | -| 17800004 | ZStream error. | +| 17800004 | Compression or decompression stream error, which may be caused by an initialization error in the zlib stream structure or a modified structure. | **Example** @@ -3022,7 +3030,7 @@ Calculates the maximum size of the compressed data. This API uses a promise to r | strm | ZStream | Yes | For details, see [ZStream12+](#zstream12).| | sourceLength | number | Yes | Length of the source data. | -**Return value** +**Returns** | Type | Description | | --------------------- | --------------------------------- | @@ -3086,7 +3094,7 @@ Provides the header information of the gzip file when **deflateInit2()** request | strm | ZStream | Yes | For details, see [ZStream12+](#zstream12). | | head | [GzHeader](#gzheader12) | Yes | Header information of a gzip file extracted from the compressed data stream.| -**Return value** +**Returns** | Type | Description | | ---------------------------------------------- | --------------------------- | @@ -3099,7 +3107,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | | 401 | The parameter check failed. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | -| 17800004 | ZStream error. | +| 17800004 | Compression or decompression stream error, which may be caused by an initialization error in the zlib stream structure or a modified structure. | **Example** @@ -3151,7 +3159,7 @@ Copies the compression stream. This API uses a promise to return the result. The | ------ | ---- | ---- | ----------------------- | | source | Zip | Yes | For details, see [Zip12+](#zip12).| -**Return value** +**Returns** | Type | Description | | ---------------------------------------------- | --------------------------- | @@ -3164,7 +3172,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | | 401 | The parameter check failed. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | -| 17800004 | ZStream error. | +| 17800004 | Compression or decompression stream error, which may be caused by an initialization error in the zlib stream structure or a modified structure. | **Example** @@ -3216,7 +3224,7 @@ Initializes the compression dictionary from a given sequence of bytes. This API | strm | ZStream | Yes | For details, see [ZStream12+](#zstream12).| | dictionary | ArrayBuffer | Yes | Dictionary data. | -**Return value** +**Returns** | Type | Description | | ---------------------------------------------- | --------------------------- | @@ -3229,7 +3237,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | | 401 | The parameter check failed. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | -| 17800004 | ZStream error. | +| 17800004 | Compression or decompression stream error, which may be caused by an initialization error in the zlib stream structure or a modified structure. | **Example** @@ -3281,7 +3289,7 @@ Obtains the content and length of the decompression dictionary used in the curre | strm | ZStream | Yes | For details, see [ZStream12+](#zstream12).| | dictionary | ArrayBuffer | Yes | Receives the actual contents of the decompression dictionary. | -**Return value** +**Returns** | Type | Description | | ------------------------------------------------------------ | --------------------------------------- | @@ -3294,7 +3302,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | | 401 | The parameter check failed. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | -| 17800004 | ZStream error. | +| 17800004 | Compression or decompression stream error, which may be caused by an initialization error in the zlib stream structure or a modified structure. | **Example** @@ -3349,12 +3357,12 @@ Fine-tunes the internal compressed parameters of **deflate**. This API uses a pr | Name | Type | Mandatory| Description | | ---------- | ------- | ---- | ------------------------------- | | strm | ZStream | Yes | For details, see [ZStream12+](#zstream12).| -| goodLength | number | Yes | Matching length threshold. | -| maxLazy | number | Yes | Matching maximum delay. | +| goodLength | number | Yes | Matched length threshold. | +| maxLazy | number | Yes | Delay matching policy used when the compression algorithm builds a Huffman tree. The value is an integer ranging from 0 to 4. **1**–**4**: A larger value indicates a lazier algorithm, which performs a slower matching process but generates a better compression result. **0**: Lazy matching is disabled. The algorithm builds a Huffman tree as soon as possible. The compression speed is fast, but the compression ratio is low. | | niceLength | number | Yes | Appropriate delay length threshold. | | maxChain | number | Yes | Maximum chain length. | -**Return value** +**Returns** | Type | Description | | ---------------------------------------------- | --------------------------- | @@ -3367,7 +3375,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | | 401 | The parameter check failed. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | -| 17800004 | ZStream error. | +| 17800004 | Compression or decompression stream error, which may be caused by an initialization error in the zlib stream structure or a modified structure. | **Example** @@ -3418,7 +3426,7 @@ Equivalent to call the **deflateEnd** API and then **deflateInit** API. However, | ------ | ------- | ---- | ------------------------------- | | strm | ZStream | Yes | For details, see [ZStream12+](#zstream12).| -**Return value** +**Returns** | Type | Description | | ---------------------------------------------- | --------------------------- | @@ -3431,7 +3439,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | | 401 | The parameter check failed. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | -| 17800004 | ZStream error. | +| 17800004 | Compression or decompression stream error, which may be caused by an initialization error in the zlib stream structure or a modified structure. | **Example** @@ -3482,7 +3490,7 @@ Resets the initialized deflate compression stream, but retains the compression p | ------ | ------- | ---- | ------------------------------- | | strm | ZStream | Yes | For details, see [ZStream12+](#zstream12).| -**Return value** +**Returns** | Type | Description | | ---------------------------------------------- | --------------------------- | @@ -3495,7 +3503,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | | 401 | The parameter check failed. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | -| 17800004 | ZStream error. | +| 17800004 | Compression or decompression stream error, which may be caused by an initialization error in the zlib stream structure or a modified structure. | **Example** @@ -3546,7 +3554,7 @@ Returns the number of bytes and bits that has been generated but has not yet bee | ------ | ------- | ---- | ------------------------------- | | strm | ZStream | Yes | For details, see [ZStream12+](#zstream12).| -**Return value** +**Returns** | Type | Description | | ------------------------------------------------------------ | ------------------------------------------------- | @@ -3559,7 +3567,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | | 401 | The parameter check failed. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | -| 17800004 | ZStream error. | +| 17800004 | Compression or decompression stream error, which may be caused by an initialization error in the zlib stream structure or a modified structure. | **Example** @@ -3612,7 +3620,7 @@ Dynamically updates the compression level and compression strategy. This API use | level | CompressLevel | Yes | For details, see [CompressLevel](#compresslevel). | | strategy | CompressStrategy | Yes | For details, see [CompressStrategy](#compressstrategy).| -**Return value** +**Returns** | Type | Description | | ---------------------------------------------- | --------------------------- | @@ -3625,7 +3633,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | | 401 | The parameter check failed. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | -| 17800004 | ZStream error. | +| 17800004 | Compression or decompression stream error, which may be caused by an initialization error in the zlib stream structure or a modified structure. | **Example** @@ -3678,7 +3686,7 @@ Inserts bits and values into the compression stream. This API uses a promise to | bits | number | Yes | Number of bits to be inserted. The value ranges from 0 to 16. | | value | number | Yes | Bit value corresponding to the number of bits. | -**Return value** +**Returns** | Type | Description | | ---------------------------------------------- | --------------------------- | @@ -3691,7 +3699,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | | 401 | The parameter check failed. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | -| 17800004 | ZStream error. | +| 17800004 | Compression or decompression stream error, which may be caused by an initialization error in the zlib stream structure or a modified structure. | **Example** @@ -3787,7 +3795,13 @@ async function demo() { | PARALLEL_STRATEGY_SEQUENTIAL | 0 | Serial compression/decompression policy (default).| | PARALLEL_STRATEGY_PARALLEL_DECOMPRESSION | 1 | Parallel decompression policy. | -## ErrorCode +## ErrorCode(deprecated) + +> **NOTE** +> +> The initial APIs of this module are supported since API version 7. +> +> This module is deprecated since API version 9. **System capability**: SystemCapability.BundleManager.Zlib @@ -3926,7 +3940,7 @@ Creates a gzip object. This API uses a promise to return the result. The gzip ob **System capability**: SystemCapability.BundleManager.Zlib -**Return value** +**Returns** | Type | Description | | ------------------------------ | ------------------------------- | @@ -3952,7 +3966,7 @@ Creates a gzip object. The gzip object instance is returned upon a success. **System capability**: SystemCapability.BundleManager.Zlib -**Return value** +**Returns** | Type | Description | | --------------- | -------------- | @@ -3987,7 +4001,7 @@ Associates gzip file with the file descriptor (fd) and opens the file for readin | fd | number | Yes | File descriptor. Generally, the value is obtained by calling the **open** method or other methods.| | mode | string | Yes | Specifies the access mode. | -**Return value** +**Returns** | Type | Description | | ------------------- | ----------------------- | @@ -4028,9 +4042,10 @@ struct Index { .height(60) .width(200) .onClick(() => { - let context = getContext(this); - let pathDir = context.cacheDir; - gzdopenDemo(pathDir); + let pathDir = this.getUIContext()?.getHostContext()?.cacheDir; + if (typeof pathDir === 'string') { + gzdopenDemo(pathDir); + } }) } .width('100%') @@ -4056,7 +4071,7 @@ Sets the internal buffer size for the current library function. This API uses a | ------ | ------ | ---- | -------------------------- | | size | number | Yes | Size of the internal buffer to be set.| -**Return value** +**Returns** | Type | Description | | --------------------- | ---------------------------- | @@ -4075,7 +4090,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ ```ts import { fileIo as fs } from '@kit.CoreFileKit'; -import { zlib } from '@kit.BasicServicesKit' +import { zlib } from '@kit.BasicServicesKit'; async function gzbufferDemo(pathDir: string) { fs.mkdirSync(pathDir + "/gzbuffer"); @@ -4099,9 +4114,10 @@ struct Index { .height(60) .width(200) .onClick(() => { - let context = getContext(this); - let pathDir = context.cacheDir; - gzbufferDemo(pathDir); + let pathDir = this.getUIContext()?.getHostContext()?.cacheDir; + if (typeof pathDir === 'string') { + gzbufferDemo(pathDir); + } }) } .width('100%') @@ -4115,7 +4131,7 @@ struct Index { gzopen(path: string, mode: string): Promise<void> -Opens the gzip file in the specified path for reading and decompressing, or compressing and writing. This API uses a promise to return the result. +Opens the .gz file in the specified path for reading and decompressing, or compressing and writing. This API uses a promise to return the result. **Atomic service API**: This API can be used in atomic services since API version 12. @@ -4128,7 +4144,7 @@ Opens the gzip file in the specified path for reading and decompressing, or comp | path | string | Yes | Path of the file to be opened.| | mode | string | Yes | Specifies a method for opening a file. | -**Return value** +**Returns** | Type | Description | | ------------------- | ----------------------- | @@ -4168,9 +4184,10 @@ struct Index { .height(60) .width(200) .onClick(() => { - let context = getContext(this); - let pathDir = context.cacheDir; - gzopenDemo(pathDir); + let pathDir = this.getUIContext()?.getHostContext()?.cacheDir; + if (typeof pathDir === 'string') { + gzopenDemo(pathDir); + } }) } .width('100%') @@ -4190,7 +4207,7 @@ Checks whether the read position (position from which data is read) of the gzip **System capability**: SystemCapability.BundleManager.Zlib -**Return value** +**Returns** | Type | Description | | --------------------- | ------------------------------------------------------------ | @@ -4232,9 +4249,10 @@ struct Index { .height(60) .width(200) .onClick(() => { - let context = getContext(this); - let pathDir = context.cacheDir; - gzeofDemo(pathDir); + let pathDir = this.getUIContext()?.getHostContext()?.cacheDir; + if (typeof pathDir === 'string') { + gzeofDemo(pathDir); + } }) } .width('100%') @@ -4254,7 +4272,7 @@ Checks whether the specified gzip file handle directly accesses the original unc **System capability**: SystemCapability.BundleManager.Zlib -**Return value** +**Returns** | Type | Description | | --------------------- | -------------------------------------------------- | @@ -4286,9 +4304,10 @@ struct Index { .height(60) .width(200) .onClick(() => { - let context = getContext(this); - let pathDir = context.cacheDir; - gzdirectDemo(pathDir); + let pathDir = this.getUIContext()?.getHostContext()?.cacheDir; + if (typeof pathDir === 'string') { + gzdirectDemo(pathDir); + } }) } .width('100%') @@ -4302,13 +4321,13 @@ struct Index { gzclose(): Promise<ReturnStatus> -Clears all pending output of the file. Closes the file and releases decompression or compression state if necessary. This API uses a promise to return the result. The result state is returned. +Clears all pending output of the file. Closes the file and releases the decompression or compression state if necessary. This API uses a promise to return the result. The result state is returned. **Atomic service API**: This API can be used in atomic services since API version 12. **System capability**: SystemCapability.BundleManager.Zlib -**Return value** +**Returns** | Type | Description | | ---------------------------------------------- | --------------------------- | @@ -4320,7 +4339,7 @@ For details about the error codes, see [zlib Error Codes](errorcode-zlib.md). | ID| Error Message | | -------- | ------------------------- | -| 17800004 | ZStream error. | +| 17800004 | Compression or decompression stream error, which may be caused by an initialization error in the zlib stream structure or a modified structure. | | 17800006 | Memory allocation failed. | **Example** @@ -4348,9 +4367,10 @@ struct Index { .height(60) .width(200) .onClick(() => { - let context = getContext(this); - let pathDir = context.cacheDir; - gzcloseDemo(pathDir); + let pathDir = this.getUIContext()?.getHostContext()?.cacheDir; + if (typeof pathDir === 'string') { + gzcloseDemo(pathDir); + } }) } .width('100%') @@ -4370,7 +4390,7 @@ Clears the errors and end-of-file flags of a file. This API uses a promise to re **System capability**: SystemCapability.BundleManager.Zlib -**Return value** +**Returns** | Type | Description | | ------------------- | ----------------------- | @@ -4414,9 +4434,10 @@ struct Index { .height(60) .width(200) .onClick(() => { - let context = getContext(this); - let pathDir = context.cacheDir; - gzclearerrDemo(pathDir); + let pathDir = this.getUIContext()?.getHostContext()?.cacheDir; + if (typeof pathDir === 'string') { + gzclearerrDemo(pathDir); + } }) } .width('100%') @@ -4436,7 +4457,7 @@ Describes the last error message that reported for the file. This API uses a pro **System capability**: SystemCapability.BundleManager.Zlib -**Return value** +**Returns** | Type | Description | | -------------------------------------------------------- | --------------------------------------------------------- | @@ -4448,7 +4469,7 @@ For details about the error codes, see [zlib Error Codes](errorcode-zlib.md). | ID| Error Message | | -------- | -------------- | -| 17800004 | ZStream error. | +| 17800004 | Compression or decompression stream error, which may be caused by an initialization error in the zlib stream structure or a modified structure. | **Example** @@ -4488,9 +4509,10 @@ struct Index { .height(60) .width(200) .onClick(() => { - let context = getContext(this); - let pathDir = context.cacheDir; - gzerrorDemo(pathDir); + let pathDir = this.getUIContext()?.getHostContext()?.cacheDir; + if (typeof pathDir === 'string') { + gzerrorDemo(pathDir); + } }) } .width('100%') @@ -4510,7 +4532,7 @@ Reads and decompresses a byte from a file. This API uses a promise to return the **System capability**: SystemCapability.BundleManager.Zlib -**Return value** +**Returns** | Type | Description | | --------------------- | ------------------------------------ | @@ -4553,9 +4575,10 @@ struct Index { .height(60) .width(200) .onClick(() => { - let context = getContext(this); - let pathDir = context.cacheDir; - gzgetcDemo(pathDir); + let pathDir = this.getUIContext()?.getHostContext()?.cacheDir; + if (typeof pathDir === 'string') { + gzgetcDemo(pathDir); + } }) } .width('100%') @@ -4581,7 +4604,7 @@ Flushes all pending output into a compressed file. This API uses a promise to re | ------ | ----------------- | ---- | ------------------------------------------------------------ | | flush | CompressFlushMode | Yes | Controls the flushing mode. For details, see [CompressFlushMode](#compressflushmode12).| -**Return value** +**Returns** | Type | Description | | ---------------------------------------------- | --------------------------- | @@ -4594,7 +4617,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | | 401 | The parameter check failed. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | -| 17800004 | ZStream error. | +| 17800004 | Compression or decompression stream error, which may be caused by an initialization error in the zlib stream structure or a modified structure. | **Example** @@ -4622,9 +4645,10 @@ struct Index { .height(60) .width(200) .onClick(() => { - let context = getContext(this); - let pathDir = context.cacheDir; - gzflushDemo(pathDir); + let pathDir = this.getUIContext()?.getHostContext()?.cacheDir; + if (typeof pathDir === 'string') { + gzflushDemo(pathDir); + } }) } .width('100%') @@ -4652,7 +4676,7 @@ Compresses data blocks that are declared with size and nitems from the buffer an | size | number | Yes | Number of bytes in a single data block.| | nitems | number | Yes | Number of data blocks to be written. | -**Return value** +**Returns** | Type | Description | | --------------------- | --------------------------------------------------- | @@ -4698,9 +4722,10 @@ struct Index { .height(60) .width(200) .onClick(() => { - let context = getContext(this); - let pathDir = context.cacheDir; - gzfwriteDemo(pathDir); + let pathDir = this.getUIContext()?.getHostContext()?.cacheDir; + if (typeof pathDir === 'string') { + gzfwriteDemo(pathDir); + } }) } .width('100%') @@ -4728,7 +4753,7 @@ Decompresses and reads data from a gzip file. This API uses a promise to return | size | number | Yes | Number of bytes in a single data block. | | nitems | number | Yes | Number of data blocks to be written. | -**Return value** +**Returns** | Type | Description | | --------------------- | --------------------------------------------------- | @@ -4778,9 +4803,10 @@ struct Index { .height(60) .width(200) .onClick(() => { - let context = getContext(this); - let pathDir = context.cacheDir; - gzfreadDemo(pathDir); + let pathDir = this.getUIContext()?.getHostContext()?.cacheDir; + if (typeof pathDir === 'string') { + gzfreadDemo(pathDir); + } }) } .width('100%') @@ -4800,7 +4826,7 @@ Implements the same functions as that of **gzclose()** for writing or appending. **System capability**: SystemCapability.BundleManager.Zlib -**Return value** +**Returns** | Type | Description | | ---------------------------------------------- | --------------------------- | @@ -4812,7 +4838,7 @@ For details about the error codes, see [zlib Error Codes](errorcode-zlib.md). | ID| Error Message | | -------- | ------------------------- | -| 17800004 | ZStream error. | +| 17800004 | Compression or decompression stream error, which may be caused by an initialization error in the zlib stream structure or a modified structure. | | 17800006 | Memory allocation failed. | **Example** @@ -4840,9 +4866,10 @@ struct Index { .height(60) .width(200) .onClick(() => { - let context = getContext(this); - let pathDir = context.cacheDir; - gzclosewDemo(pathDir); + let pathDir = this.getUIContext()?.getHostContext()?.cacheDir; + if (typeof pathDir === 'string') { + gzclosewDemo(pathDir); + } }) } .width('100%') @@ -4862,7 +4889,7 @@ Implements the same functions as that of **gzclose()** for reading only. This AP **System capability**: SystemCapability.BundleManager.Zlib -**Return value** +**Returns** | Type | Description | | ---------------------------------------------- | --------------------------- | @@ -4874,7 +4901,7 @@ For details about the error codes, see [zlib Error Codes](errorcode-zlib.md). | ID| Error Message | | -------- | -------------- | -| 17800004 | ZStream error. | +| 17800004 | Compression or decompression stream error, which may be caused by an initialization error in the zlib stream structure or a modified structure. | **Example** @@ -4903,9 +4930,10 @@ struct Index { .height(60) .width(200) .onClick(() => { - let context = getContext(this); - let pathDir = context.cacheDir; - gzcloserDemo(pathDir); + let pathDir = this.getUIContext()?.getHostContext()?.cacheDir; + if (typeof pathDir === 'string') { + gzcloserDemo(pathDir); + } }) } .width('100%') @@ -4930,7 +4958,7 @@ Compresses the uncompressed bytes of the declared length in the buffer and write | buf | ArrayBuffer | Yes | Data buffer pointed by an object to be written.| | len | number | Yes | Length of uncompressed bytes. | -**Return value** +**Returns** | Type | Description | | --------------------- | ------------------------------------- | @@ -4976,9 +5004,10 @@ struct Index { .height(60) .width(200) .onClick(() => { - let context = getContext(this); - let pathDir = context.cacheDir; - gzwriteDemo(pathDir); + let pathDir = this.getUIContext()?.getHostContext()?.cacheDir; + if (typeof pathDir === 'string') { + gzwriteDemo(pathDir); + } }) } .width('100%') @@ -5002,7 +5031,7 @@ Pushes **c** back into the input stream so that it will be read as the first cha | ------ | ------ | ---- | ------------------------ | | c | number | Yes | Characters before being pushed into the input stream.| -**Return value** +**Returns** | Type | Description | | --------------------- | ----------------------------- | @@ -5046,9 +5075,10 @@ struct Index { .height(60) .width(200) .onClick(() => { - let context = getContext(this); - let pathDir = context.cacheDir; - gzungetcDemo(pathDir); + let pathDir = this.getUIContext()?.getHostContext()?.cacheDir; + if (typeof pathDir === 'string') { + gzungetcDemo(pathDir); + } }) } .width('100%') @@ -5068,7 +5098,7 @@ Returns the start position of the next **gzread** or **gzwrite** in the file. Th **System capability**: SystemCapability.BundleManager.Zlib -**Return value** +**Returns** | Type | Description | | --------------------- | -------------------------------------------------------- | @@ -5108,9 +5138,10 @@ struct Index { .height(60) .width(200) .onClick(() => { - let context = getContext(this); - let pathDir = context.cacheDir; - gztellDemo(pathDir); + let pathDir = this.getUIContext()?.getHostContext()?.cacheDir; + if (typeof pathDir === 'string') { + gztellDemo(pathDir); + } }) } .width('100%') @@ -5137,7 +5168,7 @@ Dynamically updates the compression level and compression policy of a file. This | level | CompressLevel | Yes | Compression level. For details, see [CompressLevel](#compresslevel). | | strategy | CompressStrategy | Yes | Compression policy. For details, see [CompressStrategy](#compressstrategy).| -**Return value** +**Returns** | Type | Description | | ---------------------------------------------- | --------------------------- | @@ -5150,7 +5181,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | | 401 | The parameter check failed. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | -| 17800004 | ZStream error. | +| 17800004 | Compression or decompression stream error, which may be caused by an initialization error in the zlib stream structure or a modified structure. | **Example** @@ -5179,9 +5210,10 @@ struct Index { .height(60) .width(200) .onClick(() => { - let context = getContext(this); - let pathDir = context.cacheDir; - gzsetparamsDemo(pathDir); + let pathDir = this.getUIContext()?.getHostContext()?.cacheDir; + if (typeof pathDir === 'string') { + gzsetparamsDemo(pathDir); + } }) } .width('100%') @@ -5208,7 +5240,7 @@ Sets the start position to the offset position relative to the next **gzread** o | offset | number | Yes | Target offset position. | | whence | OffsetReferencePoint | Yes | Defines the reference point for the offset. For details, see [OffsetReferencePoint](#offsetreferencepoint12).| -**Return value** +**Returns** | Type | Description | | --------------------- | ------------------------------------------------------------ | @@ -5249,9 +5281,10 @@ struct Index { .height(60) .width(200) .onClick(() => { - let context = getContext(this); - let pathDir = context.cacheDir; - gzseekDemo(pathDir); + let pathDir = this.getUIContext()?.getHostContext()?.cacheDir; + if (typeof pathDir === 'string') { + gzseekDemo(pathDir); + } }) } .width('100%') @@ -5271,7 +5304,7 @@ Repositions the file pointer to the beginning of the file. This feature is appli **System capability**: SystemCapability.BundleManager.Zlib -**Return value** +**Returns** | Type | Description | | ---------------------------------------------- | --------------------------- | @@ -5313,9 +5346,10 @@ struct Index { .height(60) .width(200) .onClick(() => { - let context = getContext(this); - let pathDir = context.cacheDir; - gzrewindDemo(pathDir); + let pathDir = this.getUIContext()?.getHostContext()?.cacheDir; + if (typeof pathDir === 'string') { + gzrewindDemo(pathDir); + } }) } .width('100%') @@ -5341,7 +5375,7 @@ Reads a maximum of **len** uncompressed bytes from a file and decompresses them | ------ | ----------- | ---- | -------------- | | buf | ArrayBuffer | Yes | Target offset position.| -**Return value** +**Returns** | Type | Description | | --------------------- | ----------------------------------------- | @@ -5391,9 +5425,10 @@ struct Index { .height(60) .width(200) .onClick(() => { - let context = getContext(this); - let pathDir = context.cacheDir; - gzreadDemo(pathDir); + let pathDir = this.getUIContext()?.getHostContext()?.cacheDir; + if (typeof pathDir === 'string') { + gzreadDemo(pathDir); + } }) } .width('100%') @@ -5419,7 +5454,7 @@ Compresses the given null-terminated strings and writes them to the file, exclud | ------ | ------ | ---- | ---------------------- | | str | string | Yes | Format descriptors and plain text.| -**Return value** +**Returns** | Type | Description | | --------------------- | ------------------------------- | @@ -5460,9 +5495,10 @@ struct Index { .height(60) .width(200) .onClick(() => { - let context = getContext(this); - let pathDir = context.cacheDir; - gzputsDemo(pathDir); + let pathDir = this.getUIContext()?.getHostContext()?.cacheDir; + if (typeof pathDir === 'string') { + gzputsDemo(pathDir); + } }) } .width('100%') @@ -5488,7 +5524,7 @@ Compresses **char** converted to an unsigned character and writes it to a file. | ------ | ------ | ---- | --------------- | | char | number | Yes | Write character ASCII.| -**Return value** +**Returns** | Type | Description | | --------------------- | ----------------------------- | @@ -5529,9 +5565,10 @@ struct Index { .height(60) .width(200) .onClick(() => { - let context = getContext(this); - let pathDir = context.cacheDir; - gzputcDemo(pathDir); + let pathDir = this.getUIContext()?.getHostContext()?.cacheDir; + if (typeof pathDir === 'string') { + gzputcDemo(pathDir); + } }) } .width('100%') @@ -5558,7 +5595,7 @@ Converts and formats the parameters under the control of the string format and t | format | string | Yes | Format descriptors and plain text.| | ...args | Array<string \| number> | No | List of variable parameters. | -**Return value** +**Returns** | Type | Description | | --------------------- | ----------------------------------------- | @@ -5571,7 +5608,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | | 401 | The parameter check failed. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | -| 17800004 | ZStream error. | +| 17800004 | Compression or decompression stream error, which may be caused by an initialization error in the zlib stream structure or a modified structure. | | 17800009 | Internal structure error. | **Example** @@ -5600,9 +5637,10 @@ struct Index { .height(60) .width(200) .onClick(() => { - let context = getContext(this); - let pathDir = context.cacheDir; - gzprintfDemo(pathDir); + let pathDir = this.getUIContext()?.getHostContext()?.cacheDir; + if (typeof pathDir === 'string') { + gzprintfDemo(pathDir); + } }) } .width('100%') @@ -5622,7 +5660,7 @@ Returns the current compressed read or write offset of the file. This API uses a **System capability**: SystemCapability.BundleManager.Zlib -**Return value** +**Returns** | Type | Description | | --------------------- | ----------------------------------------------------- | @@ -5662,9 +5700,10 @@ struct Index { .height(60) .width(200) .onClick(() => { - let context = getContext(this); - let pathDir = context.cacheDir; - gzoffsetDemo(pathDir); + let pathDir = this.getUIContext()?.getHostContext()?.cacheDir; + if (typeof pathDir === 'string') { + gzoffsetDemo(pathDir); + } }) } .width('100%') @@ -5690,11 +5729,11 @@ Reads bytes from a compressed file until len-1 characters are read, a newline ch | ------ | ----------- | ---- | ------------------ | | buf | ArrayBuffer | Yes | Stores the read row data.| -**Return value** +**Returns** | Type | Description | | --------------------- | ------------------------------------- | -| Promise<string> | Promise used to return the result.| +| Promise<string> | Promise used to return a string ended with **null**.| **Error codes** @@ -5735,9 +5774,10 @@ struct Index { .height(60) .width(200) .onClick(() => { - let context = getContext(this); - let pathDir = context.cacheDir; - gzgetsDemo(pathDir); + let pathDir = this.getUIContext()?.getHostContext()?.cacheDir; + if (typeof pathDir === 'string') { + gzgetsDemo(pathDir); + } }) } .width('100%') diff --git a/en/application-dev/reference/apis-basic-services-kit/oh__batteryinfo.md b/en/application-dev/reference/apis-basic-services-kit/oh__batteryinfo.md index 9e44cd56645..0ea00447449 100644 --- a/en/application-dev/reference/apis-basic-services-kit/oh__batteryinfo.md +++ b/en/application-dev/reference/apis-basic-services-kit/oh__batteryinfo.md @@ -31,7 +31,7 @@ Provides APIs for the BatteryInfo module to obtain battery information. | Name| Description| | -------- | -------- | | int32_t [OH_BatteryInfo_GetCapacity](#oh_batteryinfo_getcapacity) () | Obtains the current battery capacity.| -| [BatteryInfo_BatteryPluggedType](#batteryinfo_batterypluggedtype)[OH_BatteryInfo_GetPluggedType](#oh_batteryinfo_getpluggedtype) () | Obtains the plug type.| +| [BatteryInfo_BatteryPluggedType](#batteryinfo_batterypluggedtype) [OH_BatteryInfo_GetPluggedType](#oh_batteryinfo_getpluggedtype) () | Obtains the plug type.| ### Variables diff --git a/en/application-dev/reference/apis-basic-services-kit/ohbattery__info_8h.md b/en/application-dev/reference/apis-basic-services-kit/ohbattery__info_8h.md index d57e911b59e..0dee7ce23f8 100644 --- a/en/application-dev/reference/apis-basic-services-kit/ohbattery__info_8h.md +++ b/en/application-dev/reference/apis-basic-services-kit/ohbattery__info_8h.md @@ -29,7 +29,7 @@ Declares the battery APIs that are used to obtain the current battery capacity a | Name| Description| | -------- | -------- | | int32_t [OH_BatteryInfo_GetCapacity](oh__batteryinfo.md#oh_batteryinfo_getcapacity) () | Obtains the current battery capacity.| -| [BatteryInfo_BatteryPluggedType](oh__batteryinfo.md#batteryinfo_batterypluggedtype)[OH_BatteryInfo_GetPluggedType](oh__batteryinfo.md#oh_batteryinfo_getpluggedtype) () | Obtains the plug type.| +| [BatteryInfo_BatteryPluggedType](oh__batteryinfo.md#batteryinfo_batterypluggedtype) [OH_BatteryInfo_GetPluggedType](oh__batteryinfo.md#oh_batteryinfo_getpluggedtype) () | Obtains the plug type.| ### Variables diff --git a/en/application-dev/reference/apis-basic-services-kit/time__service_8h.md b/en/application-dev/reference/apis-basic-services-kit/time__service_8h.md index 6a439548dda..d0ac73542b0 100644 --- a/en/application-dev/reference/apis-basic-services-kit/time__service_8h.md +++ b/en/application-dev/reference/apis-basic-services-kit/time__service_8h.md @@ -28,11 +28,11 @@ Declares the API for obtaining the time and time zone information. | Name| Description| | -------- | -------- | -| [TimeService_ErrCode](_time_service.md#timeservice_errcode) {
[TIMESERVICE_ERR_OK](_time_service.md) = 0,
[TIMESERVICE_ERR_INTERNAL_ERROR](_time_service.md) = 13000001,
[TIMESERVICE_ERR_INVALID_PARAMETER](_time_service.md) = 13000002
} | Enumerates the error codes.| +| [TimeService_ErrCode](_time_service.md#timeservice_errcode) {
TIMESERVICE_ERR_OK = 0,
TIMESERVICE_ERR_INTERNAL_ERROR = 13000001,
TIMESERVICE_ERR_INVALID_PARAMETER = 13000002
} | Enumerates the error codes.| ### Functions | Name| Description| | -------- | -------- | -| [TimeService_ErrCode](_time_service.md#timeservice_errcode)[OH_TimeService_GetTimeZone](_time_service.md#oh_timeservice_gettimezone) (char \*timeZone, uint32_t len) | Returns the current system time zone.| +| [TimeService_ErrCode](_time_service.md#timeservice_errcode) [OH_TimeService_GetTimeZone](_time_service.md#oh_timeservice_gettimezone) (char \*timeZone, uint32_t len) | Returns the current system time zone.| -- Gitee