diff --git a/CODEOWNERS b/CODEOWNERS index 290a26ec5a16959c3d13f5862973fed533bffe6b..b1111c1c967054802a20679b8d569c8092449ddc 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -133,7 +133,7 @@ zh-cn/device-dev/subsystems/subsys-xts-guide.md @Austin23 zh-cn/application-dev/ability/ @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen zh-cn/application-dev/IDL/ @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen zh-cn/application-dev/device-usage-statistics/ @RayShih @shuaytao @wangzhen107 @inter515 -zh-cn/application-dev/ui/ @HelloCrease @qieqiewl @tomatodevboy @niulihua +zh-cn/application-dev/ui/ @HelloCrease @huaweimaxuchu @tomatodevboy @niulihua zh-cn/application-dev/notification/ @RayShih @jayleehw @li-weifeng2 @currydavids zh-cn/application-dev/windowmanager/ @ge-yafang @zhangqiang183 @zhouyaoying @zxg-gitee zh-cn/application-dev/webgl/ @zengyawen @zhangqiang183 @wind_zj @zxg-gitee diff --git a/en/application-dev/IDL/figures/SDKpath.png b/en/application-dev/IDL/figures/SDKpath.png new file mode 100644 index 0000000000000000000000000000000000000000..aa7e33f0246e07fa9f6b8aeb0677c7159dfceb3d Binary files /dev/null and b/en/application-dev/IDL/figures/SDKpath.png differ diff --git a/en/application-dev/IDL/figures/SDKpath2.png b/en/application-dev/IDL/figures/SDKpath2.png new file mode 100644 index 0000000000000000000000000000000000000000..51ac48d2f04d876a204493415b79a5f12e183685 Binary files /dev/null and b/en/application-dev/IDL/figures/SDKpath2.png differ diff --git a/en/application-dev/IDL/idl-guidelines.md b/en/application-dev/IDL/idl-guidelines.md index 5b3a5d7990d4dfe55ddef2ad77ef7dab84033a2e..f165215bad4d663b794c249f8029d33aeeda5863 100644 --- a/en/application-dev/IDL/idl-guidelines.md +++ b/en/application-dev/IDL/idl-guidelines.md @@ -149,198 +149,53 @@ The value of <*formal_param_attr*> can be **in**, **out**, or **inout**, indicat ## How to Develop -### Development Using C++ +### Obtaining IDL +On DevEco Studio, choose **Tools > SDK Manager** to view the local installation path of the OpenHarmony SDK. The following figure uses DevEco Studio 3.0.0.993 as an example. +![SDKpath](./figures/SDKpath.png) +![SDKpath](./figures/SDKpath2.png) -#### Creating an IDL File - - You can use C++ to create IDL files. An example IDL file is as follows: +Go to the local installation path, choose **toolchains > 3.x.x.x** (the folder named after the version number), and check whether the executable file of IDL exists. -```cpp - interface OHOS.IIdlTestService { - int TestIntTransaction([in] int data); - void TestStringTransaction([in] String data); - } -``` +> **NOTE**: Use the SDK of the latest version. The use of an earlier version may cause errors in some statements. -You can run the **./idl -gen-cpp -d dir -c dir/iTest.idl** command (**-d** indicates the output directory) to generate the interface file, stub file, and proxy file in the **dir** directory in the execution environment. The names of the generated interface class files are the same as that of the IDL file, except that the file name extensions are **.h** and **.cpp**. For example, the files generated for **IIdlTestService.idl** are **i_idl_test_service.h**, **idl_test_service_proxy.h**, **idl_test_service_stub.h**, **idl_test_service_proxy.cpp**, and **idl_test_service_stub.cpp**. +If the executable file does not exist, download the SDK package from the mirror as instructed in the [Release Notes](../../release-notes). The following uses the [3.2 Beta3](../../release-notes/OpenHarmony-v3.2-beta3.md#acquiring-source-code-from-mirrors) as an example. -#### Exposing Interfaces on the Server +For details about how to replace the SDK package, see [Guide to Switching to Full SDK](../quick-start/full-sdk-switch-guide.md). -The stub class generated by IDL is an abstract implementation of the interface class and declares all methods in the IDL file. +After obtaining the executable file, perform subsequent development steps based on your scenario. -```cpp -#ifndef OHOS_IDLTESTSERVICESTUB_H -#define OHOS_IDLTESTSERVICESTUB_H -#include -#include "iidl_test_service.h" - -namespace OHOS { -class IdlTestServiceStub : public IRemoteStub { -public: - int OnRemoteRequest( - /* [in] */ uint32_t code, - /* [in] */ MessageParcel& data, - /* [out] */ MessageParcel& reply, - /* [in] */ MessageOption& option) override; - -private: - static constexpr int COMMAND_TEST_INT_TRANSACTION = MIN_TRANSACTION_ID + 0; - static constexpr int COMMAND_TEST_STRING_TRANSACTION = MIN_TRANSACTION_ID + 1; -}; -} // namespace OHOS -#endif // OHOS_IDLTESTSERVICESTUB_H -``` +### Development Using TS -You need to inherit the interface class defined in the IDL file and implement the methods in the class. In addition, you need to register the defined services with SAMGR during service initialization. In the following code snippet, **TestService** inherits the **IdlTestServiceStub** interface class and implements the **TestIntTransaction** and **TestStringTransaction** methods. +#### Creating an IDL File -```cpp -#ifndef OHOS_IPC_TEST_SERVICE_H -#define OHOS_IPC_TEST_SERVICE_H - -#include "hilog/log.h" -#include "log_tags.h" -#include "idl_test_service_stub.h" - -namespace OHOS { -class TestService : public IdlTestServiceStub { -public: - TestService(); - ~TestService(); - static int Instantiate(); - ErrCode TestIntTransaction(int data, int &rep) override; - ErrCode TestStringTransaction(const std::string& data) override; -private: - static constexpr HiviewDFX::HiLogLabel LABEL = { LOG_CORE, LOG_ID_IPC, "TestService" }; -}; -} // namespace OHOS -#endif // OHOS_IPC_TEST_SERVICE_H -``` +You can use TS to create IDL files. -The sample code for registering a service is as follows: + For example, create a file named **IIdlTestService.idl** with the following content: ```cpp -#include "test_service.h" - -#include - -#include "if_system_ability_manager.h" -#include "ipc_debug.h" -#include "ipc_skeleton.h" -#include "iservice_registry.h" -#include "system_ability_definition.h" - -namespace OHOS { -using namespace OHOS::HiviewDFX; - -int TestService::Instantiate() -{ - ZLOGI(LABEL, "%{public}s call in", __func__); - auto saMgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - if (saMgr == nullptr) { - ZLOGE(LABEL, "%{public}s:fail to get Registry", __func__); - return -ENODEV; - } - - sptr newInstance = new TestService(); - int result = saMgr->AddSystemAbility(IPC_TEST_SERVICE, newInstance); - ZLOGI(LABEL, "%{public}s: IPC_TEST_SERVICE result = %{public}d", __func__, result); - return result; -} - -TestService::TestService() -{ -} - -TestService::~TestService() -{ -} - -ErrCode TestService::TestIntTransaction(int data, int &rep) -{ - ZLOGE(LABEL, " TestService:read from client data = %{public}d", data); - rep = data + data; - return ERR_NONE; -} - -ErrCode TestService::TestStringTransaction(const std::string &data) -{ - ZLOGE(LABEL, "TestService:read string from client data = %{public}s", data.c_str()); - return data.size(); -} -} // namespace OHOS + interface OHOS.IIdlTestService { + int TestIntTransaction([in] int data); + void TestStringTransaction([in] String data); + } ``` -#### Calling Methods from the Client for IPC - -The C++ client obtains the service proxy defined in the system through SAMGR and then invokes the interface provided by the proxy. The sample code is as follows: +Run the **idl -gen-ts -d *dir* -c dir/IIdlTestService.idl** command in the folder where the executable file is located. -```cpp -#include "test_client.h" - -#include "if_system_ability_manager.h" -#include "ipc_debug.h" -#include "ipc_skeleton.h" -#include "iservice_registry.h" -#include "system_ability_definition.h" - -namespace OHOS { -int TestClient::ConnectService() -{ - auto saMgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - if (saMgr == nullptr) { - ZLOGE(LABEL, "get registry fail"); - return -1; - } +-*dir* next to **d** is the target output folder. For example, if the target output folder is **IIdlTestServiceTs**, run the **idl -gen-ts -d IIdlTestServiceTs -c IIdlTestServiceTs/IIdlTestService.idl** command in the folder where the executable file is located. The interface file, stub file, and proxy file are generated in the *dir* directory (**IIdlTestServiceTs** directory in this example) in the execution environment. - sptr object = saMgr->GetSystemAbility(IPC_TEST_SERVICE); - if (object != nullptr) { - ZLOGE(LABEL, "Got test Service object"); - testService_ = (new (std::nothrow) IdlTestServiceProxy(object)); - } +> **NOTE**: The generated interface class file name must be the same as that of the .idl file. Otherwise, an error occurs during code generation. - if (testService_ == nullptr) { - ZLOGE(LABEL, "Could not find Test Service!"); - return -1; - } - - return 0; -} +For example, for an .idl file named **IIdlTestService.idl** and target output directory named **IIdlTestServiceTs**, the directory structure is similar to the following: -void TestClient::StartIntTransaction() -{ - if (testService_ != nullptr) { - ZLOGE(LABEL, "StartIntTransaction"); - [[maybe_unused]] int result = 0; - testService_->TestIntTransaction(1234, result); // 1234 : test number - ZLOGE(LABEL, "Rec result from server %{public}d.", result); - } -} - -void TestClient::StartStringTransaction() -{ - if (testService_ != nullptr) { - ZLOGI(LABEL, "StartIntTransaction"); - testService_->TestStringTransaction("IDL Test"); - } -} -} // namespace OHOS ``` - -### Development Using TS - -#### Creating an IDL File - - You can use TS to create IDL files. An example IDL file is as follows: - -```ts - interface OHOS.IIdlTestService { - int TestIntTransaction([in] int data); - void TestStringTransaction([in] String data); - } +├── IIdlTestServiceTs # IDL code output folder +│ ├── i_idl_test_service.ts # File generated +│ ├── idl_test_service_proxy.ts # File generated +│ ├── idl_test_service_stub.ts # File generated +│ └── IIdlTestService.idl # Constructed .idl file +└── idl.exe # Executable file of IDL ``` -Run the **./idl -c IIdlTestService.idl -gen-ts -d /data/ts/** command (**-d** indicates the output directory) to generate the interface file, stub file, and proxy file in the **/data/ts** directory in the execution environment. The names of the generated interface class files are the same as that of the IDL file, except that the file name extension is **.ts**. For example, the files generated for the **IIdlTestService.idl** file are **i_idl_test_service.ts**, **idl_test_service_proxy.ts**, and **idl_test_service_stub.ts**. - #### Exposing Interfaces on the Server The stub class generated by IDL is an abstract implementation of the interface class and declares all methods in the IDL file. @@ -356,8 +211,8 @@ export default class IdlTestServiceStub extends rpc.RemoteObject implements IIdl super(des); } - onRemoteRequest(code: number, data, reply, option): boolean { - console.log("onRemoteRequest called, code = " + code); + async onRemoteRequestEx(code: number, data, reply, option): Promise { + console.log("onRemoteRequestEx called, code = " + code); switch(code) { case IdlTestServiceStub.COMMAND_TEST_INT_TRANSACTION: { let _data = data.readInt(); @@ -529,137 +384,3 @@ export default class MySequenceable { private str; } ``` - -## How to Develop for Interworking Between C++ and TS - -### TS Proxy and C++ Stub Development - -#### C++ Service Object - -1. Use C++ to construct an IDL file and run commands to generate interfaces, stub files, and proxy files. - -2. Create a service object, inherit the interface class defined in the C++ stub file, and implement the methods in the class. An example is as follows: - - ```cpp - class IdlTestServiceImpl : public IdlTestServiceStub { - public: - IdlTestServiceImpl() = default; - virtual ~IdlTestServiceImpl() = default; - - ErrCode TestIntTransaction(int _data, int& result) override - { - result = 256; - return ERR_OK; - } - - ErrCode TestStringTransaction(const std::string& _data) override - { - return ERR_OK; - } - }; - ``` - -#### Native APIs in C++ - -C++ provides C++ service objects to TS in the format of native APIs. For example, C++ provides a **GetNativeObject** method, which is used to create an **IdlTestServiceImpl** instance. Using the **NAPI_ohos_rpc_CreateJsRemoteObject** method, you can create a JS remote object for the TS application. - -```cpp -NativeValue* GetNativeObject(NativeEngine& engine, NativeCallbackInfo& info) -{ - sptr impl = new IdlTestServiceImpl(); - napi_value napiRemoteObject = NAPI_ohos_rpc_CreateJsRemoteObject(reinterpret_cast(&engine), impl); - NativeValue* nativeRemoteObject = reinterpret_cast(napiRemoteObject); - return nativeRemoteObject; -} -``` - -#### TS Proxy Object - -Use TS to construct an IDL file and run commands to generate interfaces, stub files, and proxy files. An example proxy file is as follows: - -```ts -import {testIntTransactionCallback} from "./i_idl_test_service"; -import {testStringTransactionCallback} from "./i_idl_test_service"; -import IIdlTestService from "./i_idl_test_service"; -import rpc from "@ohos.rpc"; - -export default class IdlTestServiceProxy implements IIdlTestService { - constructor(proxy) { - this.proxy = proxy; - } - - testIntTransaction(data: number, callback: testIntTransactionCallback): void - { - let _option = new rpc.MessageOption(); - let _data = new rpc.MessageParcel(); - let _reply = new rpc.MessageParcel(); - _data.writeInt(data); - this.proxy.sendRequest(IdlTestServiceProxy.COMMAND_TEST_INT_TRANSACTION, _data, _reply, _option).then(function(result) { - if (result.errCode == 0) { - let _errCode = result.reply.readInt(); - if (_errCode != 0) { - let _returnValue = undefined; - callback(_errCode, _returnValue); - return; - } - let _returnValue = result.reply.readInt(); - callback(_errCode, _returnValue); - } else { - console.log('sendRequest failed, errCode: ' + result.errCode); - } - }) - } - - testStringTransaction(data: string, callback: testStringTransactionCallback): void - { - let _option = new rpc.MessageOption(); - let _data = new rpc.MessageParcel(); - let _reply = new rpc.MessageParcel(); - _data.writeString(data); - this.proxy.sendRequest(IdlTestServiceProxy.COMMAND_TEST_STRING_TRANSACTION, _data, _reply, _option).then(function(result) { - if (result.errCode == 0) { - let _errCode = result.reply.readInt(); - callback(_errCode); - } else { - console.log('sendRequest failed, errCode: ' + result.errCode); - } - }) - } - - static readonly COMMAND_TEST_INT_TRANSACTION = 1; - static readonly COMMAND_TEST_STRING_TRANSACTION = 2; - private proxy -} -``` - -#### Interworking Between TS and C++ Applications - -1. The TS application invokes the native API to obtain the remote C++ service object. -2. Construct a TS proxy and transfers the remote C++ service object to it. -3. Use the TS proxy to call the method declared in the IDL file to implement the interworking between the TS proxy and C++ stub. The following is an example: - -```ts -import IdlTestServiceProxy from './idl_test_service_proxy' -import nativeMgr from 'nativeManager'; - -function testIntTransactionCallback(errCode: number, returnValue: number) -{ - console.log('errCode: ' + errCode + ' returnValue: ' + returnValue); -} - -function testStringTransactionCallback(errCode: number) -{ - console.log('errCode: ' + errCode); -} - -function jsProxyTriggerCppStub() -{ - let nativeObj = nativeMgr.GetNativeObject(); - let tsProxy = new IdlTestServiceProxy(nativeObj); - // Call testIntTransaction. - tsProxy.testIntTransaction(10, testIntTransactionCallback); - - // Call testStringTransaction. - tsProxy.testStringTransaction('test', testIntTransactionCallback); -} -``` diff --git a/en/application-dev/device/sample-server-guidelines.md b/en/application-dev/device/sample-server-guidelines.md index faf07d1e82bed9aa679901add578df1aae2444fc..369fb8cc31d3c86e96c42bb38aef2f67761eb9e4 100644 --- a/en/application-dev/device/sample-server-guidelines.md +++ b/en/application-dev/device/sample-server-guidelines.md @@ -14,6 +14,8 @@ The sample server provides a package search server for checking update packages openssl req -newkey rsa:2048 -nodes -keyout serverKey.pem -x509 -days 365 -out serverCert.cer -subj "/C=CN/ST=GD/L=GZ/O=abc/OU=defg/CN=hijk/emailAddress=test.com" ``` + + 2. Modify the **bundle.json** file. Add **sub_component** to the **build** field. @@ -173,7 +175,7 @@ The sample server provides a package search server for checking update packages "\"descriptPackageId\": \"abcdefg1234567ABCDEFG\"," "}]," "\"descriptInfo\": [{" - "\"descriptPackageId\": \"abcdefg1234567ABCDEFG\"," + "\"descriptionType\": 0," "\"content\": \"This package message is used for sampleContent\"" "}]" "}"; diff --git a/en/application-dev/device/sample-server-overview.md b/en/application-dev/device/sample-server-overview.md index 6924f8d7f2256dff9ec828cc5fb62248f68599f1..9e31fe0b50a7d7641fde28ca16c252a97aa2d646 100644 --- a/en/application-dev/device/sample-server-overview.md +++ b/en/application-dev/device/sample-server-overview.md @@ -30,7 +30,7 @@ The following is an example of the JSON response returned by the server. Note th "descriptPackageId": "abcdefg1234567ABCDEFG" }], "descriptInfo": [{ - "descriptPackageId": "abcdefg1234567ABCDEFG", + "descriptionType": 0, "content": "This package is used for update." }] } diff --git a/en/application-dev/faqs/Readme-EN.md b/en/application-dev/faqs/Readme-EN.md index 37baff507755e5862045dfb3247324c6e80dcfdf..9606b7f526c00870a7ce76e2183d4fdb3d8ce45a 100644 --- a/en/application-dev/faqs/Readme-EN.md +++ b/en/application-dev/faqs/Readme-EN.md @@ -1,17 +1,20 @@ # FAQs - [Ability Framework Development](faqs-ability.md) -- [Bundle Management Development](faqs-bundle.md) - [ArkUI (eTS) Development](faqs-ui-ets.md) - [ArkUI (JavaScript) Development](faqs-ui-js.md) +- [Bundle Management Development](faqs-bundle.md) +- [Data Management Development](faqs-data-management.md) +- [Development Board](faqs-development-board.md) +- [Device Management Development](faqs-device-management.md) +- [DFX Development](faqs-dfx.md) - [Graphics and Image Development](faqs-graphics.md) +- [hdc_std Command Usage](faqs-ide.md) +- [IDE Usage](faqs-hdc-std.md) +- [Intl Development](faqs-international.md) - [File Management Development](faqs-file-management.md) - [Media Development](faqs-media.md) - [Network and Connection Development](faqs-connectivity.md) -- [Data Management Development](faqs-data-management.md) -- [Device Management Development](faqs-device-management.md) - [Native API Usage](faqs-native.md) - [Usage of Third- and Fourth-Party Libraries](faqs-third-party-library.md) -- [hdc_std Command Usage](faqs-ide.md) -- [IDE Usage](faqs-hdc-std.md) -- [Development Board](faqs-development-board.md) + diff --git a/en/application-dev/faqs/faqs-dfx.md b/en/application-dev/faqs/faqs-dfx.md new file mode 100644 index 0000000000000000000000000000000000000000..6ab2948af18a4344fb8decc157e4ac1cb346f3ee --- /dev/null +++ b/en/application-dev/faqs/faqs-dfx.md @@ -0,0 +1,54 @@ +# DFX Development + +## How do I locate the fault when the application crashes? + +Applicable to: OpenHarmony SDK 3.2.5.5 + +1. Locate the crash-related code based on the service log. + +2. View the error information in the crash file. The crash file is located at **/data/log/faultlog/faultlogger/**. + +## Why cannot access controls in the UiTest test framework? + +Applicable to: OpenHarmony SDK 3.2.5.5 + +Check whether **persist.ace.testmode.enabled** is turned on. + +Run **hdc\_std shell param get persist.ace.testmode.enabled**. + +If the value is **0**, run the **hdc\_std shell param set persist.ace.testmode.enabled 1** to enable the test mode. + + +## Why Is Private Displayed in Logs When the Format Parameter Type of hilog in C++ Code Is %d or %s? + +When format parameters such as **%d** and **%s** are directly used, the standard system uses **private** to replace the actual data for printing by default to prevent data leakage. To print the actual data, replace **%d** with **%{public}d** or replace **%s** with **%{public}s**. + +## What should I do if the hilog.debug log cannot be printed? + +Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 + +Run **hdc_std shell hilog -b D** to turn on the debugging switch. + +## Is HiLog or console recommended for log printing? How do I set the domain if HiLog is used? + +Applicable to: OpenHarmony SDK 3.2.2.5 + +You are advised to use the [HiLog](../reference/apis/js-apis-hilog.md) for log printing. For details about how to set the **domain** parameter, see the [Development Guide](../reference/apis/js-apis-hilog.md#hilogisloggable). + +## What is the maximum length of a log record when HiLog Is used? Is it configurable? + +Applicable to: OpenHarmony SDK 3.2.2.5 + +The maximum length of a log record is 1,024 characters, and it is not changeable. + +## Can I separate multiple strings by spaces in the tag parameter of the HiLog API? + +Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9 + +No. Separating multiple strings by spaces is not allowed. + +## How do I print real data if HiLog does not contain data labeled by {public}? + +Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9 + +Run **hdc\_std shell hilog -p off** to disable logging of data labeled by {public}. diff --git a/en/application-dev/faqs/faqs-hdc-std.md b/en/application-dev/faqs/faqs-hdc-std.md index 04c0a202a57b702164b8bcb7a32299d3abd5d75c..60f93da61d7d78a4e148b65c0e30d379b1e1206d 100644 --- a/en/application-dev/faqs/faqs-hdc-std.md +++ b/en/application-dev/faqs/faqs-hdc-std.md @@ -1,17 +1,14 @@ # hdc_std Command Usage - - -## What are the commands commonly used for log management? +## Common Log Commands Applicable to: OpenHarmony SDK 3.2.2.5 -- Clearing logs: hdc_std shell hilog -r +Clearing logs: hdc_std shell hilog -r -- Increasing the buffer size to 20 MB: hdc_std shell hilog -G 20M - -- Capturing logs: hdc_std shell hilog > log.txt +Increasing the buffer size to 20 MB: hdc_std shell hilog -G 20M +Capturing logs: hdc_std shell hilog > log.txt ## What should I do to avoid log flow control? @@ -27,43 +24,64 @@ Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 After performing the preceding operations, restart the DevEco Studio. +## What should I do if the HAP installed on the development board through the IDE cannot be opened? -## Is HiLog or Console recommended for log printing? How do I set the domain if HiLog is used? +Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 -Applicable to: OpenHarmony SDK 3.2.2.5 +Check whether the SDK version is consistent with the system version on the development board. You are advised to use the SDK version and system version that are released on the same day. -[HiLog](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-hilog.md) is recommended for an application to print logs. For details about domain setting, see [Development Guide](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-hilog.md#hilogisloggable). +## How do I upload files using the hdc command? +Applicable to: OpenHarmony SDK 3.2.2.5 -## What is the maximum length of a log record when HiLog is used? Is it configurable? +Run the **hdc_std file send** command. -Applicable to: OpenHarmony SDK 3.2.2.5 +## How do I prevent the screen of the RK3568 development board from turning off? -The maximum length of a log record is 1,024 characters, and it is not changeable. +Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 +Run the **hdc_std shell "power-shell setmode 602"** command. -## What should I do if a HAP package cannot be opened after being installed on the development board using the IDE? +## How do I start an ability using the hdc command? Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 -Check whether the SDK version is consistent with the system version on the development board. You are advised to use the SDK version and system version that are released on the same day. +Run the **hdc\_std shell aa start -a AbilityName -b bundleName -m moduleName** command. +## How do I change the read and write permissions on a file directory on the development board? -## How do I upload files using an hdc command? +Applicable to: OpenHarmony SDK 3.2.5.6, stage model of API version 9 + +Run the **hdc\_std shell mount -o remount,rw /** command. + +## What should I do if the error message "Unknown file option -r" is displayed when hdc_std file recv is run? + +Applicable to: OpenHarmony SDK 3.2.5.6, stage model of API version 9 + +1. Use the the hdc tool in the device image or SDK of the same version. + +2. Remove any Chinese characters or spaces from the directory specified for the hdc tool. + +## How do I uninstall an application using the hdc command? Applicable to: OpenHarmony SDK 3.2.2.5 -Run the **hdc_std file send** command. +Run the **hdc\_std uninstall [-k] [package_name]** command. -## How do I prevent the screen of the RK3568 development board from turning off? +## How do I check whether the system is 32-bit or 64-bit? -Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 +Applicable to: OpenHarmony SDK 3.2.5.5 -Run the **hdc_std shell "power-shell setmode 602"** command. +Run the **hdc\_std shell getconf LONG_BIT** command. +If **64** is returned, the system is a 64-bit one. Otherwise, the system is a 32-bit one. -## How do I start an ability using an hdc command? +## How do I view the component tree structure? -Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 +Applicable to: OpenHarmony SDK 3.2.5.5 + +1. Run the **hdc\_std shell** command to launch the CLI. + +2. Run the **aa dump -a** command to find **abilityID**. -Run the **hdc_std shell aa start -a AbilityName -b bundleName -m moduleName** command. +3. Run the **aa dump -i [abilityID] -c -render** command to view the component tree. diff --git a/en/application-dev/faqs/faqs-international.md b/en/application-dev/faqs/faqs-international.md new file mode 100644 index 0000000000000000000000000000000000000000..546402921ce3a2cd9f9972721727a84d9a31295a --- /dev/null +++ b/en/application-dev/faqs/faqs-international.md @@ -0,0 +1,19 @@ +# Intl Development + +## How resources in AppScope, such as images and text, are referenced? + +Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 + +Resources are referenced in the **$r('app.type.name')** format. Where, **type** indicates the resource type, such as color, string, and media, and **name** indicates the resource name. + +## How do I convert the resource type to string? + +Applicable to: OpenHarmony SDK3.0, stage model of API version 9 + +If the resource type is set to **string**, the qualifier directory can be set as **this.context.resourceManager.getStringSync(\\$r('app.string.test').id)** and can be converted synchronously. The **\$r('app.string.test', 2)** mode is not supported. For more usage methods, see [Resource Manager](../reference/apis/js-apis-resource-manager.md#getstringsync9). + +## Why should I do if the constants referenced by $ in the form_config.json file does not take effect? + +Applicable to: OpenHarmony SDK 3.2.6.5, API9 Stage model + +In the **form\_config.json** file, **$** cannot be used to reference constants. diff --git a/en/application-dev/media/camera.md b/en/application-dev/media/camera.md index 25e5e573057661487895bc003c143393287b4829..8032348105eb70a3b5dbfd431de3632d6d04cb8a 100644 --- a/en/application-dev/media/camera.md +++ b/en/application-dev/media/camera.md @@ -81,6 +81,9 @@ for (let index = 0; index < cameraArray.length; index++) { // Create a camera input stream. let cameraInput = await cameraManager.createCameraInput(cameraArray[0]) +// Open camera +await cameraInput.open(); + // Obtain the output stream capabilities supported by the camera. let cameraOutputCap = await cameraManager.getSupportedOutputCapability(cameraArray[0]); if (!cameraOutputCap) { diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index 322ef9541956a428f36cb624f10f05d4df804bd6..3d7947be85a49718f2288d7c2d776853d7451bc9 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -200,6 +200,7 @@ - [@ohos.data.dataSharePredicates](js-apis-data-dataSharePredicates.md) - [@ohos.data.dataShareResultSet](js-apis-data-DataShareResultSet.md) - [@ohos.data.distributedDataObject](js-apis-data-distributedobject.md) + - [@ohos.data.distributedKVStore](js-apis-distributedKVStore.md) - [@ohos.data.preferences](js-apis-data-preferences.md) - [@ohos.data.rdb](js-apis-data-rdb.md) - [@ohos.data.ValuesBucket](js-apis-data-ValuesBucket.md) @@ -288,6 +289,7 @@ - [@ohos.runningLock](js-apis-runninglock.md) - [@ohos.sensor](js-apis-sensor.md) - [@ohos.settings](js-apis-settings.md) + - [@ohos.stationary](js-apis-stationary.md) - [@ohos.systemParameterV9](js-apis-system-parameterV9.md) - [@ohos.thermal](js-apis-thermal.md) - [@ohos.update](js-apis-update.md) @@ -342,7 +344,6 @@ - [@ohos.reminderAgent](js-apis-reminderAgent.md) - [@ohos.systemParameter](js-apis-system-parameter.md) - [@ohos.usb](js-apis-usb-deprecated.md) - - [@ohos.workScheduler](js-apis-workScheduler.md) - [@system.app](js-apis-system-app.md) - [@system.battery](js-apis-system-battery.md) - [@system.bluetooth](js-apis-system-bluetooth.md) diff --git a/en/application-dev/reference/apis/js-apis-Bundle-InnerBundleManager.md b/en/application-dev/reference/apis/js-apis-Bundle-InnerBundleManager.md index 9d023410fff66869318fca78d3cae361ff71217b..40725aefbf65838c8da46d75a13368c68118df0d 100644 --- a/en/application-dev/reference/apis/js-apis-Bundle-InnerBundleManager.md +++ b/en/application-dev/reference/apis/js-apis-Bundle-InnerBundleManager.md @@ -1,8 +1,8 @@ -# innerBundleManager(deprecated) +# @ohos.bundle.innerBundleManager The **innerBundleManager** module provides APIs for the **Home Screen** application. -> +> > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. > This module is deprecated since API version 9. You are advised to use [launcherBundleManager](js-apis-launcherBundleManager.md) and [bundleMonitor](js-apis-bundleMonitor.md) instead. @@ -41,7 +41,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------- | | bundleName | string | Yes | Bundle name of an application. | -| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0.| +| userId | number | Yes | User ID. The value must be greater than or equal to 0.| | callback | AsyncCallback\> | Yes | Callback used to return an array of the launcher ability information. | @@ -69,7 +69,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | ---------- | ------ | ---- | ----------------------------------------------------- | | bundleName | string | Yes | Bundle name of an application. | -| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0.| +| userId | number | Yes | User ID. The value must be greater than or equal to 0.| **Return value** @@ -216,7 +216,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------- | -| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0.| +| userId | number | Yes | User ID. The value must be greater than or equal to 0.| | callback | AsyncCallback\> | Yes | Callback used to return an array of the launcher ability information. | ## innerBundleManager.getAllLauncherAbilityInfos(deprecated) @@ -242,7 +242,7 @@ This is a system API and cannot be called by third-party applications. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ----------------------------------------------------- | -| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0.| +| userId | number | Yes | User ID. The value must be greater than or equal to 0.| **Return value** diff --git a/en/application-dev/reference/apis/js-apis-Bundle.md b/en/application-dev/reference/apis/js-apis-Bundle.md index 52a10b74d2346bc15d2fc17ce196b190bfbfa521..83cf9c77d2899e1c0c0969be8199c602e4374816 100644 --- a/en/application-dev/reference/apis/js-apis-Bundle.md +++ b/en/application-dev/reference/apis/js-apis-Bundle.md @@ -1,24 +1,24 @@ -# Bundle +# @ohos.bundle -The **Bundle** module provides APIs for querying the information about bundles, applications, abilities, Extension abilities, and application states. +The **bundle** module provides APIs for obtaining information about an application, including [bundle information](js-apis-bundle-BundleInfo.md), [application information](js-apis-bundle-ApplicationInfo.md), and [ability information](js-apis-bundle-AbilityInfo.md). It also provides APIs to obtain and set the application disabling state. > **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. ## Modules to Import -```js +```ts import bundle from '@ohos.bundle'; ``` ## Required Permissions -| Required Permissions | Permission Level | Description | -| ------------------------------------------ | ------------ | ------------------ | -| ohos.permission.GET_BUNDLE_INFO | normal | Permission to query information about a specified application. | -| ohos.permission.GET_BUNDLE_INFO_PRIVILEGED| system_basic | Permission to query information about all applications.| -| ohos.permission.INSTALL_BUNDLE | system_core | Permission to install or uninstall applications. | -| ohos.permission.MANAGE_DISPOSED_APP_STATUS | system_core | Permission to set and query the application disposal status. | +| Required Permissions | Permission Level | Description | +|--------------------------------------------|--------------|---------------| +| ohos.permission.GET_BUNDLE_INFO | normal | Permission to query information about a specified bundle. | +| ohos.permission.GET_BUNDLE_INFO_PRIVILEGED| system_basic | Permission to query information about all bundles. | +| ohos.permission.INSTALL_BUNDLE | system_core | Permission to install or uninstall bundles. | +| ohos.permission.MANAGE_DISPOSED_APP_STATUS | system_core | Permission to set and query the application disposal status.| For details, see [Permission Levels](../../security/accesstoken-overview.md#permission-levels). @@ -30,6 +30,8 @@ getApplicationInfo(bundleName: string, bundleFlags: number, userId?: number): Pr Obtains the application information based on a given bundle name. This API uses a promise to return the result. +No permission is required for obtaining the caller's own information. + **Required permissions** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO @@ -42,8 +44,8 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ----------- | ------ | ---- | ------------------------------------------------------------ | -| bundleName | string | Yes | Bundle name of an application. | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| +| bundleName | string | Yes | Bundle name of the application. | +| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the application information flags in [BundleFlag](#bundleflagdeprecated).| | userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | **Return value** @@ -54,7 +56,7 @@ SystemCapability.BundleManager.BundleFramework **Example** -```js +```ts let bundleName = "com.example.myapplication"; let bundleFlags = 0; let userId = 100; @@ -74,6 +76,8 @@ getApplicationInfo(bundleName: string, bundleFlags: number, userId: number, call Obtains the application information of the specified user based on a given bundle name. This API uses an asynchronous callback to return the result. +No permission is required for obtaining the caller's own information. + **Required permissions** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO @@ -86,14 +90,14 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ----------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| bundleName | string | Yes | Bundle name of an application. | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| -| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| bundleName | string | Yes | Bundle name of the application. | +| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| +| userId | number | Yes | User ID. The value must be greater than or equal to 0. | | callback | AsyncCallback\<[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)> | Yes | Callback used to return the application information. | **Example** -```js +```ts let bundleName = "com.example.myapplication"; let bundleFlags = 0; let userId = 100; @@ -115,6 +119,8 @@ getApplicationInfo(bundleName: string, bundleFlags: number, callback: AsyncCallb Obtains the application information based on a given bundle name. This API uses an asynchronous callback to return the result. +No permission is required for obtaining the caller's own information. + **Required permissions** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO @@ -127,13 +133,13 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ----------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| bundleName | string | Yes | Bundle name of an application. | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| +| bundleName | string | Yes | Bundle name of the application. | +| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| | callback | AsyncCallback\<[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)> | Yes | Callback used to return the application information. | **Example** -```js +```ts let bundleName = "com.example.myapplication"; let bundleFlags = 0; bundle.getApplicationInfo(bundleName, bundleFlags, (err, data) => { @@ -152,7 +158,7 @@ bundle.getApplicationInfo(bundleName, bundleFlags, (err, data) => { getAllBundleInfo(bundleFlag: BundleFlag, userId?: number): Promise> -Obtains the information of all available bundles of the specified user in the system. This API uses a promise to return the result. +Obtains the information of all bundles of the specified user. This API uses a promise to return the result. **Required permissions** @@ -166,7 +172,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ---------- | ---------- | ---- | ------------------------------------------------------------ | -| bundleFlag | BundleFlag | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| +| bundleFlag | BundleFlag | Yes | Type of information that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| | userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | **Return value** @@ -177,7 +183,7 @@ SystemCapability.BundleManager.BundleFramework **Example** -```js +```ts let bundleFlag = 0; let userId = 100; bundle.getAllBundleInfo(bundleFlag, userId) @@ -195,7 +201,7 @@ bundle.getAllBundleInfo(bundleFlag, userId) getAllBundleInfo(bundleFlag: BundleFlag, callback: AsyncCallback>): void -Obtains the information of all available bundles in the system. This API uses an asynchronous callback to return the result. +Obtains the information of all bundles of the current user. This API uses an asynchronous callback to return the result. **Required permissions** @@ -209,12 +215,12 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| bundleFlag | BundleFlag | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| -| callback | AsyncCallback> | Yes | Callback used to return the information of all available bundles. | +| bundleFlag | BundleFlag | Yes | Type of information that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| +| callback | AsyncCallback> | Yes | Callback used to return the information of all bundles. | **Example** -```js +```ts let bundleFlag = 0; bundle.getAllBundleInfo(bundleFlag, (err, data) => { if (err) { @@ -232,7 +238,7 @@ bundle.getAllBundleInfo(bundleFlag, (err, data) => { getAllBundleInfo(bundleFlag: BundleFlag, userId: number, callback: AsyncCallback>): void -Obtains the information of all available bundles of the specified user in the system. This API uses an asynchronous callback to return the result. +Obtains the information of all bundles of the specified user. This API uses an asynchronous callback to return the result. **Required permissions** @@ -244,15 +250,16 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| bundleFlag | BundleFlag | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| -| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | -| callback | AsyncCallback> | Yes | Callback used to return the information of all available bundles. | +| Name | Type | Mandatory | Description | +|------------|-------------------------------------------------------------------|-----|---------------------------------------------------------------------| +| bundleFlag | BundleFlag | Yes | Type of information that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| +| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| callback | AsyncCallback> | Yes | Callback used to return the information of all bundles. | +| **Example** -```js +```ts let bundleFlag = 0; let userId = 100; bundle.getAllBundleInfo(bundleFlag, userId, (err, data) => { @@ -273,6 +280,8 @@ getBundleInfo(bundleName: string, bundleFlags: number, options?: BundleOptions): Obtains the bundle information based on a given bundle name. This API uses a promise to return the result. +No permission is required for obtaining the caller's own information. + **Required permissions** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO @@ -283,11 +292,11 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ------------- | ---- | --------------------------------------- | -| bundleName | string | Yes | Bundle name of an application. | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| -| options | [BundleOptions](#bundleoptions) | No | Includes **userId**. | +| Name | Type | Mandatory | Description | +| ----------- | ------------- | ---- |---------------------------------------------------------------------| +| bundleName | string | Yes | Bundle name of the application. | +| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| +| options | [BundleOptions](#bundleoptions) | No | Options that contain the user ID. | **Return value** @@ -297,7 +306,7 @@ SystemCapability.BundleManager.BundleFramework **Example** -```js +```ts let bundleName = "com.example.myapplication"; let bundleFlags = 1; let options = { @@ -319,6 +328,8 @@ getBundleInfo(bundleName: string, bundleFlags: number, callback: AsyncCallback\< Obtains the bundle information based on a given bundle name. This API uses an asynchronous callback to return the result. +No permission is required for obtaining the caller's own information. + **Required permissions** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO @@ -329,15 +340,15 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ---------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| bundleName | string | Yes | Bundle name of an application. | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| -| callback | AsyncCallback\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Yes | Callback used to return the bundle information. | +| Name | Type | Mandatory| Description | +| ----------- | ---------------------------------------------------------- | ---- |---------------------------------------------------------------------| +| bundleName | string | Yes | Bundle name of the application. | +| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| +| callback | AsyncCallback\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Yes | Callback used to return the bundle information. | **Example** -```js +```ts let bundleName = "com.example.myapplication"; let bundleFlags = 1; bundle.getBundleInfo(bundleName, bundleFlags, (err, data) => { @@ -358,6 +369,8 @@ getBundleInfo(bundleName: string, bundleFlags: number, options: BundleOptions, c Obtains the bundle information based on a given bundle name and bundle options. This API uses an asynchronous callback to return the result. +No permission is required for obtaining the caller's own information. + **Required permissions** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO @@ -370,14 +383,14 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ----------- | ---------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| bundleName | string | Yes | Bundle name of an application. | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| +| bundleName | string | Yes | Bundle name of the application. | +| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| | options | [BundleOptions](#bundleoptions) | Yes | Includes **userId**. | | callback | AsyncCallback\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Yes | Callback used to return the bundle information. | **Example** -```js +```ts let bundleName = "com.example.myapplication"; let bundleFlags = 1; let options = { @@ -400,7 +413,7 @@ bundle.getBundleInfo(bundleName, bundleFlags, options, (err, data) => { getBundleInstaller(): Promise<BundleInstaller>; -Obtains the installation package information. This API uses a promise to return the result. +Obtains the installation package. This API uses a promise to return the result. **Required permissions** @@ -418,7 +431,17 @@ This is a system API and cannot be called by third-party applications. | Type | Description | | ------------------------------------------------------------ | -------------------------------------------- | -| Promise<[BundleInstaller](js-apis-bundle-BundleInstaller.md)> | Promise used to return the installation package information.| +| Promise<[BundleInstaller](js-apis-bundle-BundleInstaller.md)> | Promise used to return the installation package.| + +**Example** + +```ts +bundle.getBundleInstaller().then((data) => { + console.info('getBundleInstaller successfully.'); +}).catch((error) => { + console.error('getBundleInstaller failed.'); +}); +``` ## bundle.getBundleInstallerdeprecated @@ -426,7 +449,7 @@ This is a system API and cannot be called by third-party applications. getBundleInstaller(callback: AsyncCallback<BundleInstaller>): void; -Obtains the installation package information. This API uses an asynchronous callback to return the result. +Obtains the installation package. This API uses an asynchronous callback to return the result. **Required permissions** @@ -444,8 +467,19 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ---------------- | -| callback | AsyncCallback<[BundleInstaller](js-apis-bundle-BundleInstaller.md)> | Yes | Callback used to return the installation package information.| +| callback | AsyncCallback<[BundleInstaller](js-apis-bundle-BundleInstaller.md)> | Yes | Callback used to return the installation package.| + +**Example** +```ts +bundle.getBundleInstaller((err, data) => { + if (err.code == 0) { + console.error('getBundleInstaller failed.'); + } else { + console.info('getBundleInstaller successfully'); + } +}); +``` ## bundle.cleanBundleCacheFiles8+ deprecated > This API is deprecated since API version 9. You are advised to use [bundleManager.cleanBundleCacheFiles](js-apis-bundleManager.md#bundlemanagercleanbundlecachefiles) instead. @@ -470,9 +504,23 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | ---------- | ------------------- | ---- | ------------------------------------- | -| bundleName | string | Yes | Bundle name of an application.| +| bundleName | string | Yes | Bundle name of the application.| | callback | AsyncCallback\ | Yes | Callback used to return the result. | +**Example** + +```ts +let bundleName = "com.example.myapplication"; + +bundle.cleanBundleCacheFiles(bundleName, err => { + if (err) { + console.error('cleanBundleCacheFiles failed.'); + } else { + console.info('cleanBundleCacheFiles successfully.'); + } +}); +``` + ## bundle.cleanBundleCacheFiles8+ deprecated > This API is deprecated since API version 9. You are advised to use [bundleManager.cleanBundleCacheFiles](js-apis-bundleManager.md#bundlemanagercleanbundlecachefiles) instead. @@ -497,7 +545,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | ---------- | ------ | ---- | ------------------------------------- | -| bundleName | string | Yes | Bundle name of an application.| +| bundleName | string | Yes | Bundle name of the application.| **Return value** @@ -505,6 +553,18 @@ This is a system API and cannot be called by third-party applications. | ------------- | ------------------------------------ | | Promise\ | Promise that returns no value.| +**Example** + +```ts +let bundleName = "com.example.myapplication"; + +bundle.cleanBundleCacheFiles(bundleName).then(()=> { + console.info('cleanBundleCacheFiles successfully.'); +}).catch(err=> { + console.error('cleanBundleCacheFiles failed.'); +}); +``` + ## bundle.setApplicationEnabled8+ deprecated > This API is deprecated since API version 9. You are advised to use [bundleManager.setApplicationEnabled](js-apis-bundleManager.md#bundlemanagersetapplicationenabled) instead. @@ -527,11 +587,25 @@ This is a system API and cannot be called by third-party applications. **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------------------- | ---- | ----------------------------------------------- | -| bundleName | string | Yes | Bundle name of an application. | +| Name | Type | Mandatory| Description | +| ---------- | ------------------- | ---- |--------------------------------| +| bundleName | string | Yes | Bundle name of the application. | | isEnable | boolean | Yes | Whether to enable the application. The value **true** means to enable the application, and **false** means the opposite.| -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```ts +let bundleName = "com.example.myapplication"; + +bundle.setApplicationEnabled(bundleName, false, err => { + if (err) { + console.error('setApplicationEnabled failed.'); + } else { + console.info('setApplicationEnabled successfully.'); + } +}); +``` ## bundle.setApplicationEnabled8+ deprecated @@ -555,9 +629,9 @@ This is a system API and cannot be called by third-party applications. **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------- | ---- | ----------------------------------------------- | -| bundleName | string | Yes | Bundle name of an application. | +| Name | Type | Mandatory| Description | +| ---------- | ------- | ---- |------------------------------| +| bundleName | string | Yes | Bundle name of the application. | | isEnable | boolean | Yes | Whether to enable the application. The value **true** means to enable the application, and **false** means the opposite.| **Return value** @@ -566,6 +640,18 @@ This is a system API and cannot be called by third-party applications. | ------------- | ------------------------------------ | | Promise\ | Promise that returns no value.| +**Example** + +```ts +let bundleName = "com.example.myapplication"; + +bundleManager.setApplicationEnabled(bundleName, false).then(()=> { + console.info('setApplicationEnabled successfully.'); +}).catch(err=> { + console.error('setApplicationEnabled failed.'); +}); +``` + ## bundle.setAbilityEnabled8+ deprecated > This API is deprecated since API version 9. You are advised to use [bundleManager.setAbilityEnabled](js-apis-bundleManager.md#bundlemanagersetabilityenabled) instead. @@ -627,6 +713,28 @@ This is a system API and cannot be called by third-party applications. | ------------- | ------------------------------------ | | Promise\ | Promise that returns no value.| +**Example** + +```ts +let flag = bundle.BundleFlag.GET_ABILITY_INFO_WITH_PERMISSION; +let userId = 100; +let want = { + bundleName : "com.example.myapplication", + abilityName : "com.example.myapplication.MainAbility" +}; + +bundle.getAbilityInfo(want, flag, userId).then((abilityInfo) => { + console.info('getAbilityInfo successfully. Data: ' + JSON.stringify(abilityInfo)); + + bundle.setAbilityEnabled(abilityInfo, false).then(data => { + console.info('setAbilityEnabled successfully.'); + }).catch(err => { + console.error('setAbilityEnabled failed:' + JSON.stringify(err)); + }) +}).catch(error => { + console.error('getAbilityInfo failed. Cause: ' + JSON.stringify(error)); +}); +``` ## bundle.getPermissionDef8+ deprecated > This API is deprecated since API version 9. You are advised to use [bundleManager.getPermissionDef](js-apis-bundleManager.md#bundlemanagergetpermissiondef) instead. @@ -654,6 +762,19 @@ This is a system API and cannot be called by third-party applications. | permissionName | string | Yes | Name of the permission. | | callback | AsyncCallback<[PermissionDef](js-apis-bundle-PermissionDef)> | Yes | Callback used to return the permission details.| +**Example** + +```ts +let permission = "ohos.permission.GET_BUNDLE_INFO"; +bundleManager.getPermissionDef(permission, (err, data) => { + if (err) { + console.error('getPermissionDef failed:' + err.message); + } else { + console.info('getPermissionDef successfully:' + JSON.stringify(data)); + } +}); +``` + ## bundle.getPermissionDef8+ deprecated > This API is deprecated since API version 9. You are advised to use [bundleManager.getPermissionDef](js-apis-bundleManager.md#bundlemanagergetpermissiondef) instead. @@ -686,6 +807,16 @@ This is a system API and cannot be called by third-party applications. | ------------------------------------------------------ | ------------------------------------------------------ | | Promise<[PermissionDef](js-apis-bundle-PermissionDef)> | Promise used to return the permission details.| +**Example** + +```ts +let permissionName = "ohos.permission.GET_BUNDLE_INFO"; +bundle.getPermissionDef(permissionName).then((data) => { + console.info('getPermissionDef successfully. Data: ' + JSON.stringify(data)); +}).catch(error => { + console.error('getPermissionDef failed. Cause: ' + error.message); +}); +``` ## bundle.getAllApplicationInfodeprecated @@ -707,8 +838,8 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ----------- | ------ | ---- | ------------------------------------------------------------ | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| -| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| +| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | **Return value** @@ -718,7 +849,7 @@ SystemCapability.BundleManager.BundleFramework **Example** -```js +```ts let bundleFlags = 8; let userId = 100; bundle.getAllApplicationInfo(bundleFlags, userId) @@ -735,7 +866,7 @@ bundle.getAllApplicationInfo(bundleFlags, userId) getAllApplicationInfo(bundleFlags: number, userId: number, callback: AsyncCallback>): void -Obtains the information about all applications of the specified user. This API uses an asynchronous callback to return the result. +Obtains the information about all applications. This API uses an asynchronous callback to return the result. **Required permissions** @@ -749,14 +880,14 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ----------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| +| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| | userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | | callback | AsyncCallback> | Yes | Callback used to return the application information. | **Example** -```js -let bundleFlags = 8; +```ts +let bundleFlags = bundle.BundleFlag.GET_APPLICATION_INFO_WITH_PERMISSION; let userId = 100; bundle.getAllApplicationInfo(bundleFlags, userId, (err, data) => { if (err) { @@ -774,7 +905,7 @@ bundle.getAllApplicationInfo(bundleFlags, userId, (err, data) => { getAllApplicationInfo(bundleFlags: number, callback: AsyncCallback>) : void; -Obtains the information about all applications. This API uses an asynchronous callback to return the result. +Obtains the information about all applications of the current user. This API uses an asynchronous callback to return the result. **Required permissions** @@ -788,13 +919,13 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ----------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| +| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| | callback | AsyncCallback> | Yes | Callback used to return the application information. | **Example** -```js -let bundleFlags = 8; +```ts +let bundleFlags = bundle.BundleFlag.GET_APPLICATION_INFO_WITH_PERMISSION; bundle.getAllApplicationInfo(bundleFlags, (err, data) => { if (err) { console.error('Operation failed. Cause: ' + JSON.stringify(err)); @@ -820,8 +951,8 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ---------- | ------ | ---- | ------------ | -| hapFilePath | string | Yes | Path where the HAP file is stored. The path should point to the relative directory of the current application's data directory.| -| bundleFlags | number | Yes | Flags used to specify information contained in the **BundleInfo** object that will be returned. The default value is **0**. For details on the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| +| hapFilePath | string | Yes | Path where the HAP file is stored. The absolute path of the application and the data directory sandbox path are supported.| +| bundleFlags | number | Yes | Flags used to specify information contained in the **BundleInfo** object that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| **Return value** | Type | Description | @@ -830,8 +961,8 @@ SystemCapability.BundleManager.BundleFramework **Example** -```js -let hapFilePath = "/data/xxx/test.hap"; +```ts +let hapFilePath = "/data/storage/el2/base/test.hap"; let bundleFlags = 0; bundle.getBundleArchiveInfo(hapFilePath, bundleFlags) .then((data) => { @@ -857,14 +988,14 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ---------- | ------ | ---- | ------------ | -| hapFilePath | string | Yes | Path where the HAP file is stored. The path should point to the relative directory of the current application's data directory.| -| bundleFlags | number | Yes | Flags used to specify information contained in the **BundleInfo** object that will be returned. The default value is **0**. For details on the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| +| hapFilePath | string | Yes | Path where the HAP file is stored.. The absolute path of the application and the data directory sandbox path are supported.| +| bundleFlags | number | Yes | Flags used to specify information contained in the **BundleInfo** object that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| | callback| AsyncCallback\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Yes | Callback used to return the information about the bundles.| **Example** -```js -let hapFilePath = "/data/xxx/test.hap"; +```ts +let hapFilePath = "/data/storage/el2/base/test.hap"; let bundleFlags = 0; bundle.getBundleArchiveInfo(hapFilePath, bundleFlags, (err, data) => { if (err) { @@ -884,6 +1015,8 @@ getAbilityInfo(bundleName: string, abilityName: string): Promise\ Obtains the ability information based on a given bundle name and ability name. This API uses a promise to return the result. +No permission is required for obtaining the caller's own information. + **Required permissions** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO @@ -894,9 +1027,9 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ------ | ---- | ---------------- | -| bundleName | string | Yes | Bundle name of an application. | +| Name | Type | Mandatory | Description | +| ----------- | ------ | ---- |------------| +| bundleName | string | Yes | Bundle name of the application. | | abilityName | string | Yes | Ability name.| **Return value** @@ -907,7 +1040,7 @@ SystemCapability.BundleManager.BundleFramework **Example** -```js +```ts let bundleName = "com.example.myapplication"; let abilityName = "com.example.myapplication.MainAbility"; bundle.getAbilityInfo(bundleName, abilityName) @@ -926,6 +1059,8 @@ getAbilityInfo(bundleName: string, abilityName: string, callback: AsyncCallback\ Obtains the ability information based on a given bundle name and ability name. This API uses an asynchronous callback to return the result. +No permission is required for obtaining the caller's own information. + **Required permissions** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO @@ -936,15 +1071,15 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ------------ | ---- | ---------------- | -| bundleName | string | Yes | Bundle name of an application. | -| abilityName | string | Yes | Ability name.| +| Name | Type | Mandatory | Description | +| ----------- | ------------ | ---- |----------------------------| +| bundleName | string | Yes | Bundle name of the application. | +| abilityName | string | Yes | Ability name. | | callback | AsyncCallback\<[AbilityInfo](js-apis-bundle-AbilityInfo.md)> | Yes | Callback used to return the ability information.| **Example** -```js +```ts let bundleName = "com.example.myapplication"; let abilityName = "com.example.myapplication.MainAbility"; bundle.getAbilityInfo(bundleName, abilityName, (err, data) => { @@ -964,6 +1099,8 @@ getAbilityLabel(bundleName: string, abilityName: string): Promise\ Obtains the application name based on a given bundle name and ability name. This API uses a promise to return the result. +No permission is required for obtaining the caller's own information. + **Required permissions** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO @@ -974,10 +1111,10 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ------ | ---- | ---------------- | -| bundleName | string | Yes | Bundle name of an application. | -| abilityName | string | Yes | Ability name.| +| Name | Type | Mandatory | Description | +|-------------|--------|-----|------------| +| bundleName | string | Yes | Bundle name of the application. | +| abilityName | string | Yes | Ability name.| **Return value** @@ -987,7 +1124,7 @@ SystemCapability.BundleManager.BundleFramework **Example** -```js +```ts let bundleName = "com.example.myapplication"; let abilityName = "com.example.myapplication.MainAbility"; bundle.getAbilityLabel(bundleName, abilityName) @@ -1006,6 +1143,8 @@ getAbilityLabel(bundleName: string, abilityName: string, callback : AsyncCallbac Obtains the application name based on a given bundle name and ability name. This API uses an asynchronous callback to return the result. +No permission is required for obtaining the caller's own information. + **Required permissions** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO @@ -1016,15 +1155,15 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ---------------------- | ---- | ---------------- | -| bundleName | string | Yes | Bundle name of an application. | -| abilityName | string | Yes | Ability name.| -| callback | AsyncCallback\ | Yes | Callback used to return the application name. | +| Name | Type | Mandatory | Description | +|-------------|------------------------|-----|-------------------------| +| bundleName | string | Yes | Bundle name of the application. | +| abilityName | string | Yes | Ability name. | +| callback | AsyncCallback\ | Yes | Callback used to return the application name.| **Example** -```js +```ts let bundleName = "com.example.myapplication"; let abilityName = "com.example.myapplication.MainAbility"; bundle.getAbilityLabel(bundleName, abilityName, (err, data) => { @@ -1062,7 +1201,7 @@ SystemCapability.BundleManager.BundleFramework **Example** -```js +```ts let bundleName = "com.example.myapplication"; let abilityName = "com.example.myapplication.MainAbility"; bundle.getAbilityInfo(bundleName, abilityName).then((abilityInfo)=>{ @@ -1095,7 +1234,7 @@ SystemCapability.BundleManager.BundleFramework **Example** -```js +```ts let bundleName = "com.example.myapplication"; let abilityName = "com.example.myapplication.MainAbility"; bundle.getAbilityInfo(bundleName, abilityName).then((abilityInfo)=>{ @@ -1125,17 +1264,17 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ---------- | ------ | ---- | ------------------------ | -| bundleName | string | Yes | Bundle name of an application.| +| bundleName | string | Yes | Bundle name of the application.| **Return value** | Type | Description | | ----------------- | ------------------------- | -| Promise\ | Promise used to return whether the ability is enabled. If the ability is enabled, **true** will be returned; otherwise, **false** will be returned.| +| Promise\ | Promise used to return whether the application is enabled. If the application is enabled, **true** will be returned; otherwise, **false** will be returned.| **Example** -```js +```ts let bundleName = "com.example.myapplication"; bundle.isApplicationEnabled(bundleName) .then((data) => { @@ -1161,12 +1300,12 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ---------- | ----------------------- | ---- | ------------------------ | -| bundleName | string | Yes | Bundle name of an application.| -| callback | AsyncCallback\ | Yes | Callback used to return whether the ability is enabled. If the ability is enabled, **true** will be returned; otherwise, **false** will be returned. | +| bundleName | string | Yes | Bundle name of the application.| +| callback | AsyncCallback\ | Yes | Callback used to return whether the application is enabled. If the application is enabled, **true** will be returned; otherwise, **false** will be returned. | **Example** -```js +```ts let bundleName = "com.example.myapplication"; bundle.isApplicationEnabled(bundleName, (err, data) => { if (err) { @@ -1185,6 +1324,8 @@ queryAbilityByWant(want: Want, bundleFlags: number, userId?: number): Promise> | Yes | Callback used to return the ability information. | +| Name | Type | Mandatory | Description | +|-------------|---------------------------------------------------------------------|-----|-------------------------------------------------------------------------| +| want | [Want](js-apis-application-want.md) | Yes | Want that contains the bundle name. | +| bundleFlags | number | Yes | Ability information to be returned. For details about the available enumerated values, see the ability information flags in [BundleFlag](#bundleflag).| +| userId | number | Yes | User ID. The value must be greater than or equal to 0. | +| callback | AsyncCallback> | Yes | Callback used to return the ability information. | **Example** -```js +```ts let bundleFlags = 0; let userId = 100; let want = { @@ -1277,6 +1420,8 @@ queryAbilityByWant(want: Want, bundleFlags: number, callback: AsyncCallback> | Yes | Callback used to return the ability information. | +| Name | Type | Mandatory | Description | +|-------------|---------------------------------------------------------------------|-----|-------------------------------------------------------------------------| +| want | [Want](js-apis-application-want.md) | Yes | Want that contains the bundle name. | +| bundleFlags | number | Yes | Ability information to be returned. For details about the available enumerated values, see the ability information flags in [BundleFlag](#bundleflag).| +| callback | AsyncCallback> | Yes | Callback used to return the ability information. | **Example** -```js +```ts let bundleFlags = 0; let want = { bundleName : "com.example.myapplication", @@ -1332,16 +1477,16 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ---------- | ------ | ---- | ------------------------ | -| bundleName | string | Yes | Bundle name of an application.| +| bundleName | string | Yes | Bundle name of the application.| **Return value** | Type | Description | | -------------- | -------------------------------------- | -| Promise\<[Want](js-apis-application-Want.md)> | Promise used to return the **Want** object.| +| Promise\<[Want](js-apis-application-want.md)> | Promise used to return the **Want** object.| **Example** -```js +```ts let bundleName = "com.example.myapplication"; bundle.getLaunchWantForBundle(bundleName) .then((data) => { @@ -1371,12 +1516,12 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ---------- | --------------------------------------------------- | ---- | -------------------------------------------------------- | -| bundleName | string | Yes | Bundle name of an application. | -| callback | AsyncCallback\<[Want](js-apis-application-Want.md)> | Yes | Callback used to return the **Want** object.| +| bundleName | string | Yes | Bundle name of the application. | +| callback | AsyncCallback\<[Want](js-apis-application-want.md)> | Yes | Callback used to return the **Want** object.| **Example** -```js +```ts let bundleName = "com.example.myapplication"; bundle.getLaunchWantForBundle(bundleName, (err, data) => { if (err) { @@ -1413,7 +1558,7 @@ SystemCapability.BundleManager.BundleFramework **Example** -```js +```ts let uid = 20010005; bundle.getNameForUid(uid) .then((data) => { @@ -1437,14 +1582,14 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ----------------------------------------------- | -| uid | number | Yes | UID based on which the bundle name is to obtain. | +| Name | Type | Mandatory | Description | +|----------|------------------------|-----|----------------------------| +| uid | number | Yes | UID based on which the bundle name is to obtain. | | callback | AsyncCallback\ | Yes | Callback used to return the bundle name.| **Example** -```js +```ts let uid = 20010005; bundle.getNameForUid(uid, (err, data) => { if (err) { @@ -1464,6 +1609,8 @@ getAbilityIcon(bundleName: string, abilityName: string): Promise\ | Yes | Callback used to return the [pixel map](js-apis-image.md).| **Example** -```js +```ts let bundleName = "com.example.myapplication"; let abilityName = "com.example.myapplication.MainAbility"; bundle.getAbilityIcon(bundleName, abilityName, (err, data) => { @@ -1536,7 +1686,7 @@ bundle.getAbilityIcon(bundleName, abilityName, (err, data) => { ``` ## InstallErrorCodedeprecated -> This API is deprecated since API version 9. You are not advised to use it anymore. +> This API is deprecated since API version 9. You are not advised using it anymore. **System capability**: SystemCapability.BundleManager.BundleFramework @@ -1567,7 +1717,11 @@ bundle.getAbilityIcon(bundleName, abilityName, (err, data) => { > This API is deprecated since API version 9. You are advised to use [bundleManager.BundleFlag](js-apis-bundleManager.md#bundleflag) instead. -Enumerates bundle flags. +Enumerates the bundle flags, which indicate the type of bundle information to obtain. + +If an API does not match the flag, the flag is ignored. For example, using **GET_ABILITY_INFO_WITH_PERMISSION** to obtain the application information does not affect the result. + +Flags can be used together. For example, you can use the combination of **GET_APPLICATION_INFO_WITH_PERMISSION** and **GET_APPLICATION_INFO_WITH_DISABLE** to obtain the result that contains both application permission information and disabled application information. **System capability**: SystemCapability.BundleManager.BundleFramework @@ -1587,9 +1741,9 @@ Enumerates bundle flags. | GET_ALL_APPLICATION_INFO | 0xFFFF0000 | Obtains all application information. | ## BundleOptionsdeprecated -> This API is deprecated since API version 9. You are not advised to use it anymore. +> This API is deprecated since API version 9. You are not advised using it anymore. -Describes the bundle options. +Options that contain the user ID. **System capability**: SystemCapability.BundleManager.BundleFramework @@ -1601,7 +1755,7 @@ Describes the bundle options. > This API is deprecated since API version 9. You are advised to use [bundleManager.AbilityType](js-apis-bundleManager.md#abilitytype) instead. -Enumerates ability types. +Enumerates the ability types. **System capability**: SystemCapability.BundleManager.BundleFramework @@ -1630,7 +1784,7 @@ Enumerates display orientations. > This API is deprecated since API version 9. You are advised to use [bundleManager.LaunchType](js-apis-bundleManager.md#launchtype) instead. -Enumerates launch modes. +Enumerates the ability launch modes. **System capability**: SystemCapability.BundleManager.BundleFramework @@ -1640,9 +1794,9 @@ Enumerates launch modes. | STANDARD | 1 | The ability can have multiple instances. | ## AbilitySubTypedeprecated -> This API is deprecated since API version 9. You are not advised to use it anymore. +> This API is deprecated since API version 9. You are not advised using it anymore. -Enumerates ability subtypes. +Enumerates the ability subtypes. **System capability**: SystemCapability.BundleManager.BundleFramework @@ -1652,9 +1806,9 @@ Enumerates ability subtypes. | CA | 1 | Ability that has a UI.| ## ColorModedeprecated -> This API is deprecated since API version 9. You are not advised to use it anymore. +> This API is deprecated since API version 9. You are not advised using it anymore. -Enumerates color modes. +Enumerates the color modes of applications and widgets. **System capability**: SystemCapability.BundleManager.BundleFramework @@ -1669,7 +1823,7 @@ Enumerates color modes. > This API is deprecated since API version 9. You are advised to use [bundleManager.PermissionGrantState](js-apis-bundleManager.md#permissiongrantstate) instead. -Enumerates permission grant states. +Enumerates the permission grant states. **System capability**: SystemCapability.BundleManager.BundleFramework diff --git a/en/application-dev/reference/apis/js-apis-arraylist.md b/en/application-dev/reference/apis/js-apis-arraylist.md index d98422b678ea658dbe4092dc9247ca4bb551f5cc..f6334ff328c76de2d9be97b9ad430065819e53c9 100644 --- a/en/application-dev/reference/apis/js-apis-arraylist.md +++ b/en/application-dev/reference/apis/js-apis-arraylist.md @@ -1,4 +1,4 @@ -# Linear Container ArrayList +# @ohos.util.ArrayList (Linear Container ArrayList) > **NOTE** > @@ -52,11 +52,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let arrayList = new ArrayList(); -try { - let arrayList2 = ArrayList(); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -90,21 +85,16 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er **Example** - ```ts - let arrayList = new ArrayList(); - let result = arrayList.add("a"); - let result1 = arrayList.add(1); - let b = [1, 2, 3]; - let result2 = arrayList.add(b); - let c = {name: "Dylon", age: "13"}; - let result3 = arrayList.add(c); - let result4 = arrayList.add(false); - try { - arrayList.add.bind({}, "b")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. - } catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); - } - ``` +```ts +let arrayList = new ArrayList(); +let result = arrayList.add("a"); +let result1 = arrayList.add(1); +let b = [1, 2, 3]; +let result2 = arrayList.add(b); +let c = {name: "Dylon", age: "13"}; +let result3 = arrayList.add(c); +let result4 = arrayList.add(false); +``` ### insert @@ -128,7 +118,7 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er | ID| Error Message| | -------- | -------- | | 10200011 | The insert method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The parameter value is out of range. | **Example** @@ -137,21 +127,6 @@ let arrayList = new ArrayList(); arrayList.insert("A", 0); arrayList.insert(0, 1); arrayList.insert(true, 2); -try { - arrayList.insert.bind({}, 1, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - let res = arrayList.insert (8, 11); // Trigger an out-of-bounds exception. -} catch (err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - let res = arrayList.insert("a", "b"); // Trigger a type exception. -} catch (err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### has @@ -189,11 +164,6 @@ let arrayList = new ArrayList(); let result = arrayList.has("squirrel"); arrayList.add("squirrel"); let result1 = arrayList.has("squirrel"); -try { - arrayList.has.bind({}, "squirrel")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### getIndexOf @@ -236,11 +206,6 @@ arrayList.add(1); arrayList.add(2); arrayList.add(4); let result = arrayList.getIndexOf(2); -try { - arrayList.getIndexOf.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### getLastIndexOf @@ -283,11 +248,6 @@ arrayList.add(1); arrayList.add(2); arrayList.add(4); let result = arrayList.getLastIndexOf(2); -try { - arrayList.getLastIndexOf.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### removeByIndex @@ -317,7 +277,7 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er | ID| Error Message| | -------- | -------- | | 10200011 | The removeByIndex method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The parameter value is out of range. | **Example** @@ -329,21 +289,6 @@ arrayList.add(5); arrayList.add(2); arrayList.add(4); let result = arrayList.removeByIndex(2); -try { - arrayList.removeByIndex.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - arrayList.removeByIndex("a"); // Trigger a type exception. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - arrayList.removeByIndex(8); // Trigger an out-of-bounds exception. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### remove @@ -383,11 +328,6 @@ arrayList.add(4); arrayList.add(5); arrayList.add(4); let result = arrayList.remove(2); -try { - arrayList.remove.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### removeByRange @@ -412,7 +352,7 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er | ID| Error Message| | -------- | -------- | | 10200011 | The removeByRange method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The parameter value is out of range. | **Example** @@ -423,21 +363,11 @@ arrayList.add(4); arrayList.add(5); arrayList.add(4); arrayList.removeByRange(2, 4); -try { - arrayList.removeByRange.bind({}, 2, 4)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - arrayList.removeByRange(8, 4); // Trigger an out-of-bounds exception. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### replaceAllElements -replaceAllElements(callbackfn: (value: T, index?: number, arrlist?: ArrayList<T>) => T, +replaceAllElements(callbackFn: (value: T, index?: number, arrlist?: ArrayList<T>) => T, thisArg?: Object): void Replaces all elements in this container with new elements, and returns the new ones. @@ -448,7 +378,7 @@ Replaces all elements in this container with new elements, and returns the new o | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked for the replacement.| +| callbackFn | function | Yes| Callback invoked for the replacement.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -481,18 +411,11 @@ arrayList.replaceAllElements((value: number, index: number)=> { arrayList.replaceAllElements((value: number, index: number) => { return value = value - 2; }); -try { - arrayList.replaceAllElements.bind({}, (value: number, index: number)=> { - return value = 2 * value; - })(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### forEach -forEach(callbackfn: (value: T, index?: number, arrlist?: ArrayList<T>) => void, +forEach(callbackFn: (value: T, index?: number, arrlist?: ArrayList<T>) => void, thisArg?: Object): void Uses a callback to traverse the elements in this container and obtain their position indexes. @@ -503,7 +426,7 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| +| callbackFn | function | Yes| Callback invoked to traverse the elements in the container.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -533,13 +456,6 @@ arrayList.add(4); arrayList.forEach((value, index) => { console.log(`value:${value}`, index); }); -try { - arrayList.forEach.bind({}, (value, index) => { - console.log(`value:${value}`, index); - })(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### sort @@ -582,11 +498,6 @@ arrayList.add(4); arrayList.sort((a: number, b: number) => a - b); arrayList.sort((a: number, b: number) => b - a); arrayList.sort(); -try { - arrayList.sort.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### subArrayList @@ -617,7 +528,7 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er | ID| Error Message| | -------- | -------- | | 10200011 | The subArrayList method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The parameter value is out of range. | **Example** @@ -630,16 +541,6 @@ arrayList.add(4); let result1 = arrayList.subArrayList(2, 4); let result2 = arrayList.subArrayList(4, 3); let result3 = arrayList.subArrayList(2, 6); -try { - arrayList.subArrayList.bind({}, 2, 4)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - arrayList.subArrayList(6, 4); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### clear @@ -667,11 +568,6 @@ arrayList.add(4); arrayList.add(5); arrayList.add(4); arrayList.clear(); -try { - arrayList.clear.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### clone @@ -706,11 +602,6 @@ arrayList.add(4); arrayList.add(5); arrayList.add(4); let result = arrayList.clone(); -try { - arrayList.clone.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### getCapacity @@ -744,11 +635,6 @@ arrayList.add(4); arrayList.add(5); arrayList.add(4); let result = arrayList.getCapacity(); -try { - arrayList.getCapacity.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### convertToArray @@ -782,11 +668,6 @@ arrayList.add(4); arrayList.add(5); arrayList.add(4); let result = arrayList.convertToArray(); -try { - arrayList.convertToArray.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### isEmpty @@ -820,11 +701,6 @@ arrayList.add(4); arrayList.add(5); arrayList.add(4); let result = arrayList.isEmpty(); -try { - arrayList.isEmpty.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### increaseCapacityTo @@ -859,11 +735,6 @@ arrayList.add(5); arrayList.add(4); arrayList.increaseCapacityTo(2); arrayList.increaseCapacityTo(8); -try { - arrayList.increaseCapacityTo.bind({}, 5)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### trimToCurrentLength @@ -891,11 +762,6 @@ arrayList.add(4); arrayList.add(5); arrayList.add(4); arrayList.trimToCurrentLength(); -try { - arrayList.trimToCurrentLength.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### [Symbol.iterator] @@ -941,9 +807,4 @@ while(temp != undefined) { console.log(`value:${temp}`); temp = iter.next().value; } -try { - arrayList[Symbol.iterator].bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` diff --git a/en/application-dev/reference/apis/js-apis-audio.md b/en/application-dev/reference/apis/js-apis-audio.md index 8296185a2866ab0148e68ee56e52eea68e708892..48be07fbffdadd82f34eb41b6906f4a87a679e89 100644 --- a/en/application-dev/reference/apis/js-apis-audio.md +++ b/en/application-dev/reference/apis/js-apis-audio.md @@ -1,4 +1,4 @@ -# Audio Management +# @ohos.multimedia.audio (Audio Management) The **Audio** module provides basic audio management capabilities, including audio volume and audio device management, and audio data collection and rendering. @@ -9,9 +9,9 @@ This module provides the following common audio-related functions: - [AudioCapturer](#audiocapturer8): audio capture, used to record PCM audio data. - [TonePlayer](#toneplayer9): tone player, used to manage and play Dual Tone Multi Frequency (DTMF) tones, such as dial tones and ringback tones. -> **NOTE** +> **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. +> 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. ## Modules to Import @@ -23,9 +23,9 @@ import audio from '@ohos.multimedia.audio'; | Name | Type | Readable | Writable| Description | | --------------------------------------- | ----------| ---- | ---- | ------------------ | -| LOCAL_NETWORK_ID9+ | string | Yes | No | Network ID of the local device.
This is a system API.
**System capability**: SystemCapability.Multimedia.Audio.Device | -| DEFAULT_VOLUME_GROUP_ID9+ | number | Yes | No | Default volume group ID.
**System capability**: SystemCapability.Multimedia.Audio.Volume | -| DEFAULT_INTERRUPT_GROUP_ID9+ | number | Yes | No | Default audio interruption group ID.
**System capability**: SystemCapability.Multimedia.Audio.Interrupt | +| LOCAL_NETWORK_ID9+ | string | Yes | No | Network ID of the local device.
This is a system API.
**System capability**: SystemCapability.Multimedia.Audio.Device | +| DEFAULT_VOLUME_GROUP_ID9+ | number | Yes | No | Default volume group ID.
**System capability**: SystemCapability.Multimedia.Audio.Volume | +| DEFAULT_INTERRUPT_GROUP_ID9+ | number | Yes | No | Default audio interruption group ID.
**System capability**: SystemCapability.Multimedia.Audio.Interrupt | **Example** @@ -74,7 +74,10 @@ Creates an **AudioRenderer** instance. This API uses an asynchronous callback to **Example** ```js +import featureAbility from '@ohos.ability.featureAbility'; +import fileio from '@ohos.fileio'; import audio from '@ohos.multimedia.audio'; + let audioStreamInfo = { samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, channels: audio.AudioChannel.CHANNEL_1, @@ -126,6 +129,8 @@ Creates an **AudioRenderer** instance. This API uses a promise to return the res **Example** ```js +import featureAbility from '@ohos.ability.featureAbility'; +import fileio from '@ohos.fileio'; import audio from '@ohos.multimedia.audio'; let audioStreamInfo = { @@ -279,9 +284,9 @@ Creates a **TonePlayer** instance. This API uses an asynchronous callback to ret import audio from '@ohos.multimedia.audio'; let audioRendererInfo = { - "contentType": audio.ContentType.CONTENT_TYPE_MUSIC, - "streamUsage": audio.StreamUsage.STREAM_USAGE_MEDIA, - "rendererFlags": 0 + content : audio.ContentType.CONTENT_TYPE_SONIFICATION, + usage : audio.StreamUsage.STREAM_USAGE_MEDIA, + rendererFlags : 0 } let tonePlayer; @@ -322,13 +327,14 @@ Creates a **TonePlayer** instance. This API uses a promise to return the result. ```js import audio from '@ohos.multimedia.audio'; -async function createTonePlayer(){ +let tonePlayer; +async function createTonePlayerBefore(){ let audioRendererInfo = { - "contentType": audio.ContentType.CONTENT_TYPE_MUSIC, - "streamUsage": audio.StreamUsage.STREAM_USAGE_MEDIA, - "rendererFlags": 0 + content : audio.ContentType.CONTENT_TYPE_SONIFICATION, + usage : audio.StreamUsage.STREAM_USAGE_MEDIA, + rendererFlags : 0 } - let tonePlayer = await audio.createTonePlayer(audioRendererInfo); + tonePlayer = await audio.createTonePlayer(audioRendererInfo); } ``` @@ -338,7 +344,7 @@ Enumerates the audio stream types. **System capability**: SystemCapability.Multimedia.Audio.Volume -| Name | Default Value| Description | +| Name | Value | Description | | ---------------------------- | ------ | ---------- | | VOICE_CALL8+ | 0 | Audio stream for voice calls.| | RINGTONE | 2 | Audio stream for ringtones. | @@ -354,7 +360,7 @@ Enumerates the result types of audio interruption requests. **System API**: This is a system API. -| Name | Default Value| Description | +| Name | Value | Description | | ---------------------------- | ------ | ---------- | | INTERRUPT_REQUEST_GRANT | 0 | The audio interruption request is accepted.| | INTERRUPT_REQUEST_REJECT | 1 | The audio interruption request is denied. There may be a stream with a higher priority.| @@ -365,7 +371,7 @@ Enumerates the audio interruption modes. **System capability**: SystemCapability.Multimedia.Audio.Interrupt -| Name | Default Value| Description | +| Name | Value | Description | | ---------------------------- | ------ | ---------- | | SHARE_MODE | 0 | Shared mode.| | INDEPENDENT_MODE | 1 | Independent mode.| @@ -376,7 +382,7 @@ Enumerates the audio device flags. **System capability**: SystemCapability.Multimedia.Audio.Device -| Name | Default Value | Description | +| Name | Value | Description | | ------------------------------- | ------ | ------------------------------------------------- | | NONE_DEVICES_FLAG9+ | 0 | No device.
This is a system API. | | OUTPUT_DEVICES_FLAG | 1 | Output device.| @@ -392,7 +398,7 @@ Enumerates the audio device roles. **System capability**: SystemCapability.Multimedia.Audio.Device -| Name | Default Value| Description | +| Name | Value | Description | | ------------- | ------ | -------------- | | INPUT_DEVICE | 1 | Input role.| | OUTPUT_DEVICE | 2 | Output role.| @@ -403,7 +409,7 @@ Enumerates the audio device types. **System capability**: SystemCapability.Multimedia.Audio.Device -| Name | Default Value| Description | +| Name | Value | Description | | ---------------------| ------ | --------------------------------------------------------- | | INVALID | 0 | Invalid device. | | EARPIECE | 1 | Earpiece. | @@ -422,7 +428,7 @@ Enumerates the device types used for communication. **System capability**: SystemCapability.Multimedia.Audio.Communication -| Name | Default Value| Description | +| Name | Value | Description | | ------------- | ------ | -------------| | SPEAKER | 2 | Speaker. | @@ -432,7 +438,7 @@ Enumerates the ringer modes. **System capability**: SystemCapability.Multimedia.Audio.Communication -| Name | Default Value| Description | +| Name | Value | Description | | ------------------- | ------ | ---------- | | RINGER_MODE_SILENT | 0 | Silent mode.| | RINGER_MODE_VIBRATE | 1 | Vibration mode.| @@ -444,7 +450,7 @@ Enumerates the audio sample formats. **System capability**: SystemCapability.Multimedia.Audio.Core -| Name | Default Value| Description | +| Name | Value | Description | | ---------------------------------- | ------ | -------------------------- | | SAMPLE_FORMAT_INVALID | -1 | Invalid format. | | SAMPLE_FORMAT_U8 | 0 | Unsigned 8-bit integer. | @@ -459,15 +465,15 @@ Enumerates the audio error codes. **System capability**: SystemCapability.Multimedia.Audio.Core -| Error Message | Error Code | Error Description | +| Name | Value | Description | | ---------------------| --------| ----------------- | | ERROR_INVALID_PARAM | 6800101 | Invalid parameter. | | ERROR_NO_MEMORY | 6800102 | Memory allocation failure. | | ERROR_ILLEGAL_STATE | 6800103 | Unsupported state. | -| ERROR_UNSUPPORTED | 6800104 | Unsupported parameter value. | +| ERROR_UNSUPPORTED | 6800104 | Unsupported parameter value. | | ERROR_TIMEOUT | 6800105 | Processing timeout. | | ERROR_STREAM_LIMIT | 6800201 | Too many audio streams.| -| ERROR_SYSTEM | 6800301 | System error. | +| ERROR_SYSTEM | 6800301 | System error. | ## AudioChannel8+ @@ -475,18 +481,18 @@ Enumerates the audio channels. **System capability**: SystemCapability.Multimedia.Audio.Core -| Name | Default Value | Description | +| Name | Value | Description | | --------- | -------- | -------- | | CHANNEL_1 | 0x1 << 0 | Mono.| | CHANNEL_2 | 0x1 << 1 | Dual-channel.| ## AudioSamplingRate8+ -Enumerates the audio sampling rates. +Enumerates the audio sampling rates. The sampling rates supported vary according to the device in use. **System capability**: SystemCapability.Multimedia.Audio.Core -| Name | Default Value| Description | +| Name | Value | Description | | ----------------- | ------ | --------------- | | SAMPLE_RATE_8000 | 8000 | The sampling rate is 8000. | | SAMPLE_RATE_11025 | 11025 | The sampling rate is 11025.| @@ -506,7 +512,7 @@ Enumerates the audio encoding types. **System capability**: SystemCapability.Multimedia.Audio.Core -| Name | Default Value| Description | +| Name | Value | Description | | --------------------- | ------ | --------- | | ENCODING_TYPE_INVALID | -1 | Invalid. | | ENCODING_TYPE_RAW | 0 | PCM encoding.| @@ -517,7 +523,7 @@ Enumerates the audio content types. **System capability**: SystemCapability.Multimedia.Audio.Core -| Name | Default Value| Description | +| Name | Value | Description | | ---------------------------------- | ------ | ---------- | | CONTENT_TYPE_UNKNOWN | 0 | Unknown content.| | CONTENT_TYPE_SPEECH | 1 | Speech. | @@ -532,7 +538,7 @@ Enumerates the audio stream usage. **System capability**: SystemCapability.Multimedia.Audio.Core -| Name | Default Value| Description | +| Name | Value | Description | | ------------------------------------------| ------ | ---------- | | STREAM_USAGE_UNKNOWN | 0 | Unknown usage.| | STREAM_USAGE_MEDIA | 1 | Used for media. | @@ -548,7 +554,7 @@ Enumerates the audio interruption request types. **System capability**: SystemCapability.Multimedia.Audio.Interrupt -| Name | Default Value | Description | +| Name | Value | Description | | ---------------------------------- | ------ | ------------------------- | | INTERRUPT_REQUEST_TYPE_DEFAULT | 0 | Default type, which can be used to interrupt audio requests. | @@ -558,7 +564,7 @@ Enumerates the audio states. **System capability**: SystemCapability.Multimedia.Audio.Core -| Name | Default Value| Description | +| Name | Value | Description | | -------------- | ------ | ---------------- | | STATE_INVALID | -1 | Invalid state. | | STATE_NEW | 0 | Creating instance state.| @@ -574,7 +580,7 @@ Enumerates the audio renderer rates. **System capability**: SystemCapability.Multimedia.Audio.Renderer -| Name | Default Value| Description | +| Name | Value | Description | | ------------------ | ------ | ---------- | | RENDER_RATE_NORMAL | 0 | Normal rate.| | RENDER_RATE_DOUBLE | 1 | Double rate. | @@ -586,7 +592,7 @@ Enumerates the audio interruption types. **System capability**: SystemCapability.Multimedia.Audio.Renderer -| Name | Default Value| Description | +| Name | Value | Description | | -------------------- | ------ | ---------------------- | | INTERRUPT_TYPE_BEGIN | 1 | Audio interruption started.| | INTERRUPT_TYPE_END | 2 | Audio interruption ended.| @@ -597,7 +603,7 @@ Enumerates the types of force that causes audio interruption. **System capability**: SystemCapability.Multimedia.Audio.Renderer -| Name | Default Value| Description | +| Name | Value | Description | | --------------- | ------ | ------------------------------------ | | INTERRUPT_FORCE | 0 | Forced action taken by the system. | | INTERRUPT_SHARE | 1 | The application can choose to take action or ignore.| @@ -608,7 +614,7 @@ Enumerates the hints provided along with audio interruption. **System capability**: SystemCapability.Multimedia.Audio.Renderer -| Name | Default Value| Description | +| Name | Value | Description | | ---------------------------------- | ------ | -------------------------------------------- | | INTERRUPT_HINT_NONE8+ | 0 | None. | | INTERRUPT_HINT_RESUME | 1 | Resume the playback. | @@ -636,7 +642,7 @@ Describes audio renderer information. **System capability**: SystemCapability.Multimedia.Audio.Core -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory | Description | | ------------- | --------------------------- | ---- | ---------------- | | content | [ContentType](#contenttype) | Yes | Audio content type. | | usage | [StreamUsage](#streamusage) | Yes | Audio stream usage.| @@ -661,7 +667,7 @@ Describes audio renderer configurations. **System capability**: SystemCapability.Multimedia.Audio.Renderer -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory | Description | | ------------ | ---------------------------------------- | ---- | ---------------- | | streamInfo | [AudioStreamInfo](#audiostreaminfo8) | Yes | Audio stream information.| | rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | Yes | Audio renderer information.| @@ -672,7 +678,7 @@ Describes the interruption event received by the application when playback is in **System capability**: SystemCapability.Multimedia.Audio.Renderer -| Name | Type | Mandatory| Description | +| Name | Type |Mandatory | Description | | --------- | ------------------------------------------ | ---- | ------------------------------------ | | eventType | [InterruptType](#interrupttype) | Yes | Whether the interruption has started or ended. | | forceType | [InterruptForceType](#interruptforcetype9) | Yes | Whether the interruption is taken by the system or to be taken by the application.| @@ -686,7 +692,7 @@ Describes the event received by the application when the volume is changed. **System capability**: SystemCapability.Multimedia.Audio.Volume -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory | Description | | ---------- | ----------------------------------- | ---- | -------------------------------------------------------- | | volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | | volume | number | Yes | Volume to set. The value range can be obtained by calling **getMinVolume** and **getMaxVolume**.| @@ -701,7 +707,7 @@ Describes the event received by the application when the microphone mute status **System capability**: SystemCapability.Multimedia.Audio.Device | Name | Type | Mandatory| Description | -| ---------- | ----------------------------------- | ---- | -------------------------------------------------------- | +| ---------- | ----------------------------------- | ---- |-------------------------------------------------------- | | mute | boolean | Yes | Mute status of the microphone. The value **true** means that the microphone is muted, and **false** means the opposite. | ## ConnectType9+ @@ -712,7 +718,7 @@ Enumerates the types of connected devices. **System capability**: SystemCapability.Multimedia.Audio.Volume -| Name | Default Value| Description | +| Name | Value | Description | | :------------------------------ | :----- | :--------------------- | | CONNECT_TYPE_LOCAL | 1 | Local device. | | CONNECT_TYPE_DISTRIBUTED | 2 | Distributed device. | @@ -738,7 +744,7 @@ Describes the volume group information. | networkId9+ | string | Yes | No | Network ID of the device. | | groupId9+ | number | Yes | No | Group ID of the device.| | mappingId9+ | number | Yes | No | Group mapping ID.| -| groupName9+ | number | Yes | No | Group name.| +| groupName9+ | string | Yes | No | Group name.| | type9+ | [ConnectType](#connecttype9)| Yes | No | Type of the connected device.| ## DeviceChangeAction @@ -758,7 +764,7 @@ Enumerates the device connection statuses. **System capability**: SystemCapability.Multimedia.Audio.Device -| Name | Default Value| Description | +| Name | Value | Description | | :--------- | :----- | :------------- | | CONNECT | 0 | Connected. | | DISCONNECT | 1 | Disconnected.| @@ -791,7 +797,7 @@ Enumerates the audio source types. **System capability**: SystemCapability.Multimedia.Audio.Core -| Name | Default Value| Description | +| Name | Value | Description | | :------------------------------------------- | :----- | :--------------------- | | SOURCE_TYPE_INVALID | -1 | Invalid audio source. | | SOURCE_TYPE_MIC | 0 | Mic source. | @@ -804,7 +810,7 @@ Enumerates the audio scenes. **System capability**: SystemCapability.Multimedia.Audio.Communication -| Name | Default Value| Description | +| Name | Value | Description | | :--------------------- | :----- | :-------------------------------------------- | | AUDIO_SCENE_DEFAULT | 0 | Default audio scene. | | AUDIO_SCENE_RINGING | 1 | Ringing audio scene.
This is a system API.| @@ -959,7 +965,6 @@ Sets an audio scene. This API uses an asynchronous callback to return the result **Example** ```js -let audioManager = audio.getAudioManager(); audioManager.setAudioScene(audio.AudioScene.AUDIO_SCENE_PHONE_CALL, (err) => { if (err) { console.error(`Failed to set the audio scene mode.​ ${err}`); @@ -994,7 +999,6 @@ Sets an audio scene. This API uses a promise to return the result. **Example** ```js -let audioManager = audio.getAudioManager(); audioManager.setAudioScene(audio.AudioScene.AUDIO_SCENE_PHONE_CALL).then(() => { console.info('Promise returned to indicate a successful setting of the audio scene mode.'); }).catch ((err) => { @@ -1019,7 +1023,6 @@ Obtains the audio scene. This API uses an asynchronous callback to return the re **Example** ```js -let audioManager = audio.getAudioManager(); audioManager.getAudioScene((err, value) => { if (err) { console.error(`Failed to obtain the audio scene mode.​ ${err}`); @@ -1046,7 +1049,6 @@ Obtains the audio scene. This API uses a promise to return the result. **Example** ```js -let audioManager = audio.getAudioManager(); audioManager.getAudioScene().then((value) => { console.info(`Promise returned to indicate that the audio scene mode is obtained ${value}.`); }).catch ((err) => { @@ -1096,179 +1098,20 @@ Obtains an **AudioRoutingManager** instance. let audioRoutingManager = audioManager.getRoutingManager(); ``` -## AudioVolumeManager9+ - -Implements audio volume management. Before calling an API in **AudioVolumeManager**, you must use [getVolumeManager](#getvolumemanager9) to obtain an **AudioVolumeManager** instance. - -### getVolumeGroupInfos9+ - -getVolumeGroupInfos(networkId: string, callback: AsyncCallback\): void - -Obtains the volume groups. This API uses an asynchronous callback to return the result. - -**System API**: This is a system API. - -**System capability**: SystemCapability.Multimedia.Audio.Volume - -**Parameters** - -| Name | Type | Mandatory| Description | -| ---------- | ------------------------------------------------------------ | ---- | -------------------- | -| networkId | string | Yes | Network ID of the device. The network ID of the local device is **audio.LOCAL_NETWORK_ID**. | -| callback | AsyncCallback<[VolumeGroupInfos](#volumegroupinfos9)> | Yes | Callback used to return the volume group information array.| - -**Example** -```js -audioVolumeManager.getVolumeGroupInfos(audio.LOCAL_NETWORK_ID, (err, value) => { - if (err) { - console.error(`Failed to obtain the volume group infos list. ${err}`); - return; - } - console.info('Callback invoked to indicate that the volume group infos list is obtained.'); -}); -``` - -### getVolumeGroupInfos9+ - -getVolumeGroupInfos(networkId: string\): Promise - -Obtains the volume groups. This API uses a promise to return the result. - -**System API**: This is a system API. - -**System capability**: SystemCapability.Multimedia.Audio.Volume - -**Parameters** - -| Name | Type | Mandatory| Description | -| ---------- | ------------------| ---- | -------------------- | -| networkId | string | Yes | Network ID of the device. The network ID of the local device is **audio.LOCAL_NETWORK_ID**. | - -**Return value** - -| Type | Description | -| ------------------- | ----------------------------- | -| Promise<[VolumeGroupInfos](#volumegroupinfos9)> | Volume group information array.| - -**Example** - -```js -async function getVolumeGroupInfos(){ - let volumegroupinfos = await audio.getAudioManager().getVolumeManager().getVolumeGroupInfos(audio.LOCAL_NETWORK_ID); - console.info('Promise returned to indicate that the volumeGroup list is obtained.'+JSON.stringify(volumegroupinfos)) -} -``` - -### getVolumeGroupManager9+ - -getVolumeGroupManager(groupId: number, callback: AsyncCallback\): void - -Obtains the audio group manager. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Multimedia.Audio.Volume - -**Parameters** - -| Name | Type | Mandatory| Description | -| ---------- | ------------------------------------------------------------ | ---- | -------------------- | -| groupId | number | Yes | Volume group ID. | -| callback | AsyncCallback< [AudioVolumeGroupManager](#audiovolumegroupmanager9) > | Yes | Callback used to return the audio group manager.| - -**Example** - -```js -let groupid = audio.DEFAULT_VOLUME_GROUP_ID; -audioVolumeManager.getVolumeGroupManager(groupid, (err, value) => { - if (err) { - console.error(`Failed to obtain the volume group infos list. ${err}`); - return; - } - console.info('Callback invoked to indicate that the volume group infos list is obtained.'); -}); - -``` - -### getVolumeGroupManager9+ - -getVolumeGroupManager(groupId: number\): Promise - -Obtains the audio group manager. This API uses a promise to return the result. - -**System capability**: SystemCapability.Multimedia.Audio.Volume - -**Parameters** - -| Name | Type | Mandatory| Description | -| ---------- | ---------------------------------------- | ---- | ---------------- | -| groupId | number | Yes | Volume group ID. | - -**Return value** - -| Type | Description | -| ------------------- | ----------------------------- | -| Promise< [AudioVolumeGroupManager](#audiovolumegroupmanager9) > | Promise used to return the audio group manager.| - -**Example** - -```js -let groupid = audio.DEFAULT_VOLUME_GROUP_ID; -let audioVolumeGroupManager = await audioVolumeManager.getVolumeGroupManager(groupid); -console.info('Callback invoked to indicate that the volume group infos list is obtained.'); -``` - -### on('volumeChange')9+ - -on(type: 'volumeChange', callback: Callback\): void - -Subscribes to system volume change events. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Multimedia.Audio.Volume - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value **'volumeChange'** means the system volume change event, which is triggered when the system volume changes.| -| callback | Callback<[VolumeEvent](#volumeevent8)> | Yes | Callback used to return the system volume change event. | - -**Error codes** - -For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). - -| ID| Error Message| -| ------- | --------------------------------------------| -| 6800101 | if input parameter value error. | - -**Example** - -```js -audioVolumeManager.on('volumeChange', (volumeEvent) => { - console.info(`VolumeType of stream: ${volumeEvent.volumeType} `); - console.info(`Volume level: ${volumeEvent.volume} `); - console.info(`Whether to updateUI: ${volumeEvent.updateUi} `); -}); -``` - -## AudioVolumeGroupManager9+ - -Manages the volume of an audio group. Before calling any API in **AudioVolumeGroupManager**, you must use [getVolumeGroupManager](#getvolumegroupmanager9) to obtain an **AudioVolumeGroupManager** instance. - -**System API**: This is a system API. - -**System capability**: SystemCapability.Multimedia.Audio.Volume - -### setVolume9+ +### setVolume(deprecated) setVolume(volumeType: AudioVolumeType, volume: number, callback: AsyncCallback<void>): void Sets the volume for a stream. 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 [setVolume](#setvolume9) in **AudioVolumeGroupManager**. + **Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. -**System API**: This is a system API. - **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -1282,7 +1125,7 @@ This permission is required only for muting or unmuting the ringer when **volume **Example** ```js -audioVolumeGroupManager.setVolume(audio.AudioVolumeType.MEDIA, 10, (err) => { +audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10, (err) => { if (err) { console.error(`Failed to set the volume. ${err}`); return; @@ -1291,18 +1134,20 @@ audioVolumeGroupManager.setVolume(audio.AudioVolumeType.MEDIA, 10, (err) => { }); ``` -### setVolume9+ +### setVolume(deprecated) setVolume(volumeType: AudioVolumeType, volume: number): Promise<void> Sets the volume for a stream. 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 [setVolume](#setvolume9) in **AudioVolumeGroupManager**. + **Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. -**System API**: This is a system API. - **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -1321,17 +1166,21 @@ This permission is required only for muting or unmuting the ringer when **volume **Example** ```js -audioVolumeGroupManager.setVolume(audio.AudioVolumeType.MEDIA, 10).then(() => { +audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10).then(() => { console.info('Promise returned to indicate a successful volume setting.'); }); ``` -### getVolume9+ +### getVolume(deprecated) getVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void Obtains the volume of a stream. 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 [getVolume](#getvolume9) in **AudioVolumeGroupManager**. + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -1344,7 +1193,7 @@ Obtains the volume of a stream. This API uses an asynchronous callback to return **Example** ```js -audioVolumeGroupManager.getVolume(audio.AudioVolumeType.MEDIA, (err, value) => { +audioManager.getVolume(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { console.error(`Failed to obtain the volume. ${err}`); return; @@ -1353,12 +1202,16 @@ audioVolumeGroupManager.getVolume(audio.AudioVolumeType.MEDIA, (err, value) => { }); ``` -### getVolume9+ +### getVolume(deprecated) getVolume(volumeType: AudioVolumeType): Promise<number> Obtains the volume of a stream. 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 [getVolume](#getvolume9) in **AudioVolumeGroupManager**. + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -1376,17 +1229,21 @@ Obtains the volume of a stream. This API uses a promise to return the result. **Example** ```js -audioVolumeGroupManager.getVolume(audio.AudioVolumeType.MEDIA).then((value) => { - console.info(`Promise returned to indicate that the volume is obtained ${value}.`); +audioManager.getVolume(audio.AudioVolumeType.MEDIA).then((value) => { + console.info(`Promise returned to indicate that the volume is obtained ${value} .`); }); ``` -### getMinVolume9+ +### getMinVolume(deprecated) getMinVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void Obtains the minimum volume allowed for a stream. 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 [getMinVolume](#getminvolume9) in **AudioVolumeGroupManager**. + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -1399,7 +1256,7 @@ Obtains the minimum volume allowed for a stream. This API uses an asynchronous c **Example** ```js -audioVolumeGroupManager.getMinVolume(audio.AudioVolumeType.MEDIA, (err, value) => { +audioManager.getMinVolume(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { console.error(`Failed to obtain the minimum volume. ${err}`); return; @@ -1408,12 +1265,16 @@ audioVolumeGroupManager.getMinVolume(audio.AudioVolumeType.MEDIA, (err, value) = }); ``` -### getMinVolume9+ +### getMinVolume(deprecated) getMinVolume(volumeType: AudioVolumeType): Promise<number> Obtains the minimum volume allowed for a stream. 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 [getMinVolume](#getminvolume9) in **AudioVolumeGroupManager**. + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -1431,17 +1292,21 @@ Obtains the minimum volume allowed for a stream. This API uses a promise to retu **Example** ```js -audioVolumeGroupManager.getMinVolume(audio.AudioVolumeType.MEDIA).then((value) => { - console.info(`Promised returned to indicate that the minimum volume is obtained ${value}.`); +audioManager.getMinVolume(audio.AudioVolumeType.MEDIA).then((value) => { + console.info(`Promised returned to indicate that the minimum volume is obtained. ${value}`); }); ``` -### getMaxVolume9+ +### getMaxVolume(deprecated) getMaxVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void Obtains the maximum volume allowed for a stream. 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 [getMaxVolume](#getmaxvolume9) in **AudioVolumeGroupManager**. + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -1454,7 +1319,7 @@ Obtains the maximum volume allowed for a stream. This API uses an asynchronous c **Example** ```js -audioVolumeGroupManager.getMaxVolume(audio.AudioVolumeType.MEDIA, (err, value) => { +audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { console.error(`Failed to obtain the maximum volume. ${err}`); return; @@ -1463,12 +1328,16 @@ audioVolumeGroupManager.getMaxVolume(audio.AudioVolumeType.MEDIA, (err, value) = }); ``` -### getMaxVolume9+ +### getMaxVolume(deprecated) getMaxVolume(volumeType: AudioVolumeType): Promise<number> Obtains the maximum volume allowed for a stream. 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 [getMaxVolume](#getmaxvolume9) in **AudioVolumeGroupManager**. + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -1486,22 +1355,20 @@ Obtains the maximum volume allowed for a stream. This API uses a promise to retu **Example** ```js -audioVolumeGroupManager.getMaxVolume(audio.AudioVolumeType.MEDIA).then((data) => { +audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA).then((data) => { console.info('Promised returned to indicate that the maximum volume is obtained.'); }); ``` -### mute9+ +### mute(deprecated) mute(volumeType: AudioVolumeType, mute: boolean, callback: AsyncCallback<void>): void Mutes or unmutes a stream. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY - -This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. - -**System API**: This is a system API. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [mute](#mute9) in **AudioVolumeGroupManager**. **System capability**: SystemCapability.Multimedia.Audio.Volume @@ -1516,7 +1383,7 @@ This permission is required only for muting or unmuting the ringer when **volume **Example** ```js -audioVolumeGroupManager.mute(audio.AudioVolumeType.MEDIA, true, (err) => { +audioManager.mute(audio.AudioVolumeType.MEDIA, true, (err) => { if (err) { console.error(`Failed to mute the stream. ${err}`); return; @@ -1525,17 +1392,15 @@ audioVolumeGroupManager.mute(audio.AudioVolumeType.MEDIA, true, (err) => { }); ``` -### mute9+ +### mute(deprecated) mute(volumeType: AudioVolumeType, mute: boolean): Promise<void> Mutes or unmutes a stream. This API uses a promise to return the result. -**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY - -This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. - -**System API**: This is a system API. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [mute](#mute9) in **AudioVolumeGroupManager**. **System capability**: SystemCapability.Multimedia.Audio.Volume @@ -1554,18 +1419,23 @@ This permission is required only for muting or unmuting the ringer when **volume **Example** + ```js -audioVolumeGroupManager.mute(audio.AudioVolumeType.MEDIA, true).then(() => { +audioManager.mute(audio.AudioVolumeType.MEDIA, true).then(() => { console.info('Promise returned to indicate that the stream is muted.'); }); ``` -### isMute9+ +### isMute(deprecated) isMute(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void Checks whether a stream is muted. 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 [isMute](#ismute9) in **AudioVolumeGroupManager**. + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -1578,21 +1448,25 @@ Checks whether a stream is muted. This API uses an asynchronous callback to retu **Example** ```js -audioVolumeGroupManager.isMute(audio.AudioVolumeType.MEDIA, (err, value) => { +audioManager.isMute(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { console.error(`Failed to obtain the mute status. ${err}`); return; } - console.info(`Callback invoked to indicate that the mute status of the stream is obtained ${value}.`); + console.info(`Callback invoked to indicate that the mute status of the stream is obtained. ${value}`); }); ``` -### isMute9+ +### isMute(deprecated) isMute(volumeType: AudioVolumeType): Promise<boolean> Checks whether a stream is muted. 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 [isMute](#ismute9) in **AudioVolumeGroupManager**. + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -1610,24 +1484,89 @@ Checks whether a stream is muted. This API uses a promise to return the result. **Example** ```js -audioVolumeGroupManager.isMute(audio.AudioVolumeType.MEDIA).then((value) => { +audioManager.isMute(audio.AudioVolumeType.MEDIA).then((value) => { console.info(`Promise returned to indicate that the mute status of the stream is obtained ${value}.`); }); ``` -### setRingerMode9+ +### isActive(deprecated) + +isActive(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void + +Checks whether a stream is active. 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 [isActive](#isactive9) in **AudioStreamManager**. + +**System capability**: SystemCapability.Multimedia.Audio.Volume + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------------------------------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the active status of the stream. The value **true** means that the stream is active, and **false** means the opposite.| + +**Example** + +```js +audioManager.isActive(audio.AudioVolumeType.MEDIA, (err, value) => { + if (err) { + console.error(`Failed to obtain the active status of the stream. ${err}`); + return; + } + console.info(`Callback invoked to indicate that the active status of the stream is obtained ${value}.`); +}); +``` + +### isActive(deprecated) + +isActive(volumeType: AudioVolumeType): Promise<boolean> + +Checks whether a stream is active. 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 [isActive](#isactive9) in **AudioStreamManager**. + +**System capability**: SystemCapability.Multimedia.Audio.Volume + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| + +**Return value** + +| Type | Description | +| ---------------------- | -------------------------------------------------------- | +| Promise<boolean> | Promise used to return the active status of the stream. The value **true** means that the stream is active, and **false** means the opposite.| + +**Example** + +```js +audioManager.isActive(audio.AudioVolumeType.MEDIA).then((value) => { + console.info(`Promise returned to indicate that the active status of the stream is obtained ${value}.`); +}); +``` + +### setRingerMode(deprecated) setRingerMode(mode: AudioRingMode, callback: AsyncCallback<void>): void Sets the ringer mode. 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 [setRingerMode](#setringermode9) in **AudioVolumeGroupManager**. + **Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY This permission is required only for muting or unmuting the ringer. -**System API**: This is a system API. - -**System capability**: SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Communication **Parameters** @@ -1639,7 +1578,7 @@ This permission is required only for muting or unmuting the ringer. **Example** ```js -audioVolumeGroupManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL, (err) => { +audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL, (err) => { if (err) { console.error(`Failed to set the ringer mode.​ ${err}`); return; @@ -1648,19 +1587,21 @@ audioVolumeGroupManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL, (e }); ``` -### setRingerMode9+ +### setRingerMode(deprecated) setRingerMode(mode: AudioRingMode): Promise<void> Sets the ringer mode. 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 [setRingerMode](#setringermode9) in **AudioVolumeGroupManager**. + **Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY This permission is required only for muting or unmuting the ringer. -**System API**: This is a system API. - -**System capability**: SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Communication **Parameters** @@ -1677,18 +1618,22 @@ This permission is required only for muting or unmuting the ringer. **Example** ```js -audioVolumeGroupManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL).then(() => { +audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL).then(() => { console.info('Promise returned to indicate a successful setting of the ringer mode.'); }); ``` -### getRingerMode9+ +### getRingerMode(deprecated) getRingerMode(callback: AsyncCallback<AudioRingMode>): void Obtains the ringer mode. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Volume +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getRingerMode](#getringermode9) in **AudioVolumeGroupManager**. + +**System capability**: SystemCapability.Multimedia.Audio.Communication **Parameters** @@ -1699,7 +1644,7 @@ Obtains the ringer mode. This API uses an asynchronous callback to return the re **Example** ```js -audioVolumeGroupManager.getRingerMode((err, value) => { +audioManager.getRingerMode((err, value) => { if (err) { console.error(`Failed to obtain the ringer mode.​ ${err}`); return; @@ -1708,13 +1653,17 @@ audioVolumeGroupManager.getRingerMode((err, value) => { }); ``` -### getRingerMode9+ +### getRingerMode(deprecated) getRingerMode(): Promise<AudioRingMode> Obtains the ringer mode. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Volume +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getRingerMode](#getringermode9) in **AudioVolumeGroupManager**. + +**System capability**: SystemCapability.Multimedia.Audio.Communication **Return value** @@ -1725,85 +1674,123 @@ Obtains the ringer mode. This API uses a promise to return the result. **Example** ```js -audioVolumeGroupManager.getRingerMode().then((value) => { +audioManager.getRingerMode().then((value) => { console.info(`Promise returned to indicate that the ringer mode is obtained ${value}.`); }); ``` -### on('ringerModeChange')9+ +### getDevices(deprecated) -on(type: 'ringerModeChange', callback: Callback\): void +getDevices(deviceFlag: DeviceFlag, callback: AsyncCallback<AudioDeviceDescriptors>): void -Subscribes to ringer mode change events. +Obtains the audio devices with a specific flag. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Volume +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getDevices](#getdevices9) in **AudioRoutingManager**. + +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value **'ringerModeChange'** means the ringer mode change event, which is triggered when a ringer mode change is detected.| -| callback | Callback<[AudioRingMode](#audioringmode)> | Yes | Callback used to return the system volume change event. | +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | -------------------- | +| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag. | +| callback | AsyncCallback<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Yes | Callback used to return the device list.| -**Error codes** +**Example** +```js +audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (err, value) => { + if (err) { + console.error(`Failed to obtain the device list. ${err}`); + return; + } + console.info('Callback invoked to indicate that the device list is obtained.'); +}); +``` -For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). +### getDevices(deprecated) -| ID| Error Message| -| ------- | --------------------------------------------| -| 6800101 | if input parameter value error. | +getDevices(deviceFlag: DeviceFlag): Promise<AudioDeviceDescriptors> + +Obtains the audio devices with a specific flag. 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 [getDevices](#getdevices9) in **AudioRoutingManager**. + +**System capability**: SystemCapability.Multimedia.Audio.Device + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------- | ---- | ---------------- | +| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag.| + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | ------------------------- | +| Promise<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Promise used to return the device list.| **Example** ```js -audioVolumeGroupManager.on('ringerModeChange', (ringerMode) => { - console.info(`Updated ringermode: ${ringerMode}`); +audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data) => { + console.info('Promise returned to indicate that the device list is obtained.'); }); ``` -### setMicrophoneMute9+ -setMicrophoneMute(mute: boolean, callback: AsyncCallback<void>): void +### setDeviceActive(deprecated) -Mutes or unmutes the microphone. This API uses an asynchronous callback to return the result. +setDeviceActive(deviceType: ActiveDeviceType, active: boolean, callback: AsyncCallback<void>): void -**Required permissions**: ohos.permission.MANAGE_AUDIO_CONFIG +Sets a device to the active state. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Volume +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setCommunicationDevice](#setcommunicationdevice9) in **AudioRoutingManager**. + +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | --------------------------------------------- | -| mute | boolean | Yes | Mute status to set. The value **true** means to mute the microphone, and **false** means the opposite.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------- | ---- | ------------------------ | +| deviceType | [ActiveDeviceType](#activedevicetypedeprecated) | Yes | Audio device type. | +| active | boolean | Yes | Active state to set. The value **true** means to set the device to the active state, and **false** means the opposite. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** ```js -audioVolumeGroupManager.setMicrophoneMute(true, (err) => { +audioManager.setDeviceActive(audio.ActiveDeviceType.SPEAKER, true, (err) => { if (err) { - console.error(`Failed to mute the microphone. ${err}`); + console.error(`Failed to set the active status of the device. ${err}`); return; } - console.info('Callback invoked to indicate that the microphone is muted.'); + console.info('Callback invoked to indicate that the device is set to the active status.'); }); ``` -### setMicrophoneMute9+ +### setDeviceActive(deprecated) -setMicrophoneMute(mute: boolean): Promise<void> +setDeviceActive(deviceType: ActiveDeviceType, active: boolean): Promise<void> -Mutes or unmutes the microphone. This API uses a promise to return the result. +Sets a device to the active state. This API uses a promise to return the result. -**Required permissions**: ohos.permission.MANAGE_AUDIO_CONFIG +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setCommunicationDevice](#setcommunicationdevice9) in **AudioRoutingManager**. -**System capability**: SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------- | ---- | --------------------------------------------- | -| mute | boolean | Yes | Mute status to set. The value **true** means to mute the microphone, and **false** means the opposite.| +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------- | ---- | ------------------ | +| deviceType | [ActiveDeviceType](#activedevicetypedeprecated) | Yes | Audio device type.| +| active | boolean | Yes | Active state to set. The value **true** means to set the device to the active state, and **false** means the opposite. | **Return value** @@ -1813,552 +1800,539 @@ Mutes or unmutes the microphone. This API uses a promise to return the result. **Example** + ```js -audioVolumeGroupManager.setMicrophoneMute(true).then(() => { - console.info('Promise returned to indicate that the microphone is muted.'); +audioManager.setDeviceActive(audio.ActiveDeviceType.SPEAKER, true).then(() => { + console.info('Promise returned to indicate that the device is set to the active status.'); }); ``` -### isMicrophoneMute9+ +### isDeviceActive(deprecated) -isMicrophoneMute(callback: AsyncCallback<boolean>): void +isDeviceActive(deviceType: ActiveDeviceType, callback: AsyncCallback<boolean>): void -Checks whether the microphone is muted. This API uses an asynchronous callback to return the result. +Checks whether a device is active. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Volume +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isCommunicationDeviceActive](#iscommunicationdeviceactive9) in **AudioRoutingManager**. + +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------------- | ---- | ------------------------------------------------------- | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the mute status of the microphone. The value **true** means that the microphone is muted, and **false** means the opposite.| +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------- | ---- | ------------------------ | +| deviceType | [ActiveDeviceType](#activedevicetypedeprecated) | Yes | Audio device type. | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the active state of the device.| **Example** ```js -audioVolumeGroupManager.isMicrophoneMute((err, value) => { +audioManager.isDeviceActive(audio.ActiveDeviceType.SPEAKER, (err, value) => { if (err) { - console.error(`Failed to obtain the mute status of the microphone. ${err}`); + console.error(`Failed to obtain the active status of the device. ${err}`); return; } - console.info(`Callback invoked to indicate that the mute status of the microphone is obtained ${value}.`); + console.info('Callback invoked to indicate that the active status of the device is obtained.'); }); ``` -### isMicrophoneMute9+ +### isDeviceActive(deprecated) -isMicrophoneMute(): Promise<boolean> +isDeviceActive(deviceType: ActiveDeviceType): Promise<boolean> -Checks whether the microphone is muted. This API uses a promise to return the result. +Checks whether a device is active. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Volume +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isCommunicationDeviceActive](#iscommunicationdeviceactive9) in **AudioRoutingManager**. + +**System capability**: SystemCapability.Multimedia.Audio.Device + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------- | ---- | ------------------ | +| deviceType | [ActiveDeviceType](#activedevicetypedeprecated) | Yes | Audio device type.| **Return value** -| Type | Description | -| ---------------------- | ------------------------------------------------------------ | -| Promise<boolean> | Promise used to return the mute status of the microphone. The value **true** means that the microphone is muted, and **false** means the opposite.| +| Type | Description | +| ---------------------- | ------------------------------- | +| Promise<boolean> | Promise used to return the active state of the device.| **Example** ```js -audioVolumeGroupManager.isMicrophoneMute().then((value) => { - console.info(`Promise returned to indicate that the mute status of the microphone is obtained ${value}.`); +audioManager.isDeviceActive(audio.ActiveDeviceType.SPEAKER).then((value) => { + console.info(`Promise returned to indicate that the active status of the device is obtained ${value}.`); }); ``` -### on('micStateChange')9+ +### setMicrophoneMute(deprecated) -on(type: 'micStateChange', callback: Callback<MicStateChangeEvent>): void +setMicrophoneMute(mute: boolean, callback: AsyncCallback<void>): void -Subscribes to system mic state change events. +Mutes or unmutes the microphone. This API uses an asynchronous callback to return the result. -Currently, when multiple **AudioManager** instances are used in a single process, only the subscription of the last instance takes effect, and the subscription of other instances is overwritten (even if the last instance does not initiate a subscription). Therefore, you are advised to use a single **AudioManager** instance. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setMicrophoneMute](#setmicrophonemute9) in **AudioVolumeGroupManager**. -**System capability**: SystemCapability.Multimedia.Audio.Volume +**Required permissions**: ohos.permission.MICROPHONE + +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value **'micStateChange'** means the system mic state change event, which is triggered when the system mic state changes.| -| callback | Callback<[MicStateChangeEvent](#micstatechangeevent9)> | Yes | Callback used to return the changed micr state. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | --------------------------------------------- | +| mute | boolean | Yes | Mute status to set. The value **true** means to mute the microphone, and **false** means the opposite.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | -**Error codes** +**Example** -For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). +```js +audioManager.setMicrophoneMute(true, (err) => { + if (err) { + console.error(`Failed to mute the microphone. ${err}`); + return; + } + console.info('Callback invoked to indicate that the microphone is muted.'); +}); +``` -| ID| Error Message| -| ------- | --------------------------------------------| -| 6800101 | if input parameter value error. | +### setMicrophoneMute(deprecated) + +setMicrophoneMute(mute: boolean): Promise<void> + +Mutes or unmutes the microphone. 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 [setMicrophoneMute](#setmicrophonemute9) in **AudioVolumeGroupManager**. + +**Required permissions**: ohos.permission.MICROPHONE + +**System capability**: SystemCapability.Multimedia.Audio.Device + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | --------------------------------------------- | +| mute | boolean | Yes | Mute status to set. The value **true** means to mute the microphone, and **false** means the opposite.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------- | +| Promise<void> | Promise used to return the result.| **Example** ```js -audioVolumeGroupManager.on('micStateChange', (micStateChange) => { - console.info(`Current microphone status is: ${micStateChange.mute} `); +audioManager.setMicrophoneMute(true).then(() => { + console.info('Promise returned to indicate that the microphone is muted.'); }); ``` -## AudioStreamManager9+ +### isMicrophoneMute(deprecated) -Implements audio stream management. Before calling any API in **AudioStreamManager**, you must use [getStreamManager](#getstreammanager9) to obtain an **AudioStreamManager** instance. +isMicrophoneMute(callback: AsyncCallback<boolean>): void -### getCurrentAudioRendererInfoArray9+ +Checks whether the microphone is muted. This API uses an asynchronous callback to return the result. -getCurrentAudioRendererInfoArray(callback: AsyncCallback<AudioRendererChangeInfoArray>): void +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isMicrophoneMute](#ismicrophonemute9) in **AudioVolumeGroupManager**. -Obtains the information about the current audio renderer. This API uses an asynchronous callback to return the result. +**Required permissions**: ohos.permission.MICROPHONE -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ----------------------------------- | -------- | --------------------------- | -| callback | AsyncCallback<[AudioRendererChangeInfoArray](#audiorendererchangeinfoarray9)> | Yes | Callback used to return the audio renderer information.| +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ------------------------------------------------------- | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the mute status of the microphone. The value **true** means that the microphone is muted, and **false** means the opposite.| **Example** ```js -audioStreamManager.getCurrentAudioRendererInfoArray(async (err, AudioRendererChangeInfoArray) => { - console.info('getCurrentAudioRendererInfoArray **** Get Callback Called ****'); +audioManager.isMicrophoneMute((err, value) => { if (err) { - console.error(`getCurrentAudioRendererInfoArray :ERROR: ${err}`); - } else { - if (AudioRendererChangeInfoArray != null) { - for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { - let AudioRendererChangeInfo = AudioRendererChangeInfoArray[i]; - console.info(`StreamId for ${i} is: ${AudioRendererChangeInfo.streamId}`); - console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfo.clientUid}`); - console.info(`Content ${i} is: ${AudioRendererChangeInfo.rendererInfo.content}`); - console.info(`Stream ${i} is: ${AudioRendererChangeInfo.rendererInfo.usage}`); - console.info(`Flag ${i} is: ${AudioRendererChangeInfo.rendererInfo.rendererFlags}`); - console.info(`State for ${i} is: ${AudioRendererChangeInfo.rendererState}`); - for (let j = 0;j < AudioRendererChangeInfo.deviceDescriptors.length; j++) { - console.info(`Id: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].id}`); - console.info(`Type: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceType}`); - console.info(`Role: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceRole}`); - console.info(`Name: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].name}`); - console.info(`Address: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].address}`); - console.info(`SampleRates: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]}`); - console.info(`ChannelCount ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]}`); - console.info(`ChannelMask: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelMasks}`); - } - } - } + console.error(`Failed to obtain the mute status of the microphone. ${err}`); + return; } + console.info(`Callback invoked to indicate that the mute status of the microphone is obtained ${value}.`); }); ``` -### getCurrentAudioRendererInfoArray9+ +### isMicrophoneMute(deprecated) -getCurrentAudioRendererInfoArray(): Promise<AudioRendererChangeInfoArray> +isMicrophoneMute(): Promise<boolean> -Obtains the information about the current audio renderer. This API uses a promise to return the result. +Checks whether the microphone is muted. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isMicrophoneMute](#ismicrophonemute9) in **AudioVolumeGroupManager**. + +**Required permissions**: ohos.permission.MICROPHONE + +**System capability**: SystemCapability.Multimedia.Audio.Device **Return value** -| Type | Description | -| ---------------------------------------------------------------------------------| --------------------------------------- | -| Promise<[AudioRendererChangeInfoArray](#audiorendererchangeinfoarray9)> | Promise used to return the audio renderer information. | +| Type | Description | +| ---------------------- | ------------------------------------------------------------ | +| Promise<boolean> | Promise used to return the mute status of the microphone. The value **true** means that the microphone is muted, and **false** means the opposite.| **Example** ```js -async function getCurrentAudioRendererInfoArray(){ - await audioStreamManager.getCurrentAudioRendererInfoArray().then( function (AudioRendererChangeInfoArray) { - console.info(`getCurrentAudioRendererInfoArray ######### Get Promise is called ##########`); - if (AudioRendererChangeInfoArray != null) { - for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { - let AudioRendererChangeInfo = AudioRendererChangeInfoArray[i]; - console.info(`StreamId for ${i} is: ${AudioRendererChangeInfo.streamId}`); - console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfo.clientUid}`); - console.info(`Content ${i} is: ${AudioRendererChangeInfo.rendererInfo.content}`); - console.info(`Stream ${i} is: ${AudioRendererChangeInfo.rendererInfo.usage}`); - console.info(`Flag ${i} is: ${AudioRendererChangeInfo.rendererInfo.rendererFlags}`); - console.info(`State for ${i} is: ${AudioRendererChangeInfo.rendererState}`); - for (let j = 0;j < AudioRendererChangeInfo.deviceDescriptors.length; j++) { - console.info(`Id: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].id}`); - console.info(`Type: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceType}`); - console.info(`Role: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceRole}`); - console.info(`Name: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].name}`); - console.info(`Address: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].address}`); - console.info(`SampleRates: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]}`); - console.info(`ChannelCount ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]}`); - console.info(`ChannelMask: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelMasks}`); - } - } - } - }).catch((err) => { - console.error(`getCurrentAudioRendererInfoArray :ERROR: ${err}`); - }); -} +audioManager.isMicrophoneMute().then((value) => { + console.info(`Promise returned to indicate that the mute status of the microphone is obtained ${value}.`); +}); ``` -### getCurrentAudioCapturerInfoArray9+ +### on('volumeChange')(deprecated) -getCurrentAudioCapturerInfoArray(callback: AsyncCallback<AudioCapturerChangeInfoArray>): void +on(type: 'volumeChange', callback: Callback\): void -Obtains the information about the current audio capturer. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [on](#on9) in **AudioVolumeManager**. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +Subscribes to system volume change events. + +**System API**: This is a system API. + +Currently, when multiple **AudioManager** instances are used in a single process, only the subscription of the last instance takes effect, and the subscription of other instances is overwritten (even if the last instance does not initiate a subscription). Therefore, you are advised to use a single **AudioManager** instance. + +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | -------------------------------------------------------- | -| callback | AsyncCallback<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | Yes | Callback used to return the audio capturer information.| +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value **'volumeChange'** means the system volume change event, which is triggered when a system volume change is detected.| +| callback | Callback<[VolumeEvent](#volumeevent8)> | Yes | Callback used to return the system volume change event. | **Example** ```js -audioStreamManager.getCurrentAudioCapturerInfoArray(async (err, AudioCapturerChangeInfoArray) => { - console.info('getCurrentAudioCapturerInfoArray **** Get Callback Called ****'); - if (err) { - console.error(`getCurrentAudioCapturerInfoArray :ERROR: ${err}`); - } else { - if (AudioCapturerChangeInfoArray != null) { - for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { - console.info(`StreamId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`); - console.info(`ClientUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`); - console.info(`Source for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`); - console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`); - console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`); - for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { - console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`); - console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`); - console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); - console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`); - console.info(`Address: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`); - console.info(`SampleRates: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); - console.info(`ChannelCounts ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); - console.info(`ChannelMask: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); - } - } - } - } +audioManager.on('volumeChange', (volumeEvent) => { + console.info(`VolumeType of stream: ${volumeEvent.volumeType} `); + console.info(`Volume level: ${volumeEvent.volume} `); + console.info(`Whether to updateUI: ${volumeEvent.updateUi} `); }); ``` -### getCurrentAudioCapturerInfoArray9+ +### on('ringerModeChange')(deprecated) -getCurrentAudioCapturerInfoArray(): Promise<AudioCapturerChangeInfoArray> +on(type: 'ringerModeChange', callback: Callback\): void -Obtains the information about the current audio capturer. This API uses a promise to return the result. +Subscribes to ringer mode change events. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [on('ringerModeChange')](#onringermodechange9) in **AudioVolumeGroupManager**. -**Return value** +**System API**: This is a system API. -| Type | Description | -| -----------------------------------------------------------------------------| ----------------------------------- | -| Promise<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | Promise used to return the audio capturer information. | +**System capability**: SystemCapability.Multimedia.Audio.Communication + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value **'ringerModeChange'** means the ringer mode change event, which is triggered when a ringer mode change is detected.| +| callback | Callback<[AudioRingMode](#audioringmode)> | Yes | Callback used to return the ringer mode change event. | **Example** ```js -async function getCurrentAudioCapturerInfoArray(){ - await audioStreamManager.getCurrentAudioCapturerInfoArray().then( function (AudioCapturerChangeInfoArray) { - console.info('getCurrentAudioCapturerInfoArray **** Get Promise Called ****'); - if (AudioCapturerChangeInfoArray != null) { - for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { - console.info(`StreamId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`); - console.info(`ClientUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`); - console.info(`Source for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`); - console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`); - console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`); - for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { - console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`); - console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`); - console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); - console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`); - console.info(`Address: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`); - console.info(`SampleRates: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); - console.info(`ChannelCounts ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); - console.info(`ChannelMask: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); - } - } - } - }).catch((err) => { - console.error(`getCurrentAudioCapturerInfoArray :ERROR: ${err}`); - }); -} +audioManager.on('ringerModeChange', (ringerMode) => { + console.info(`Updated ringermode: ${ringerMode}`); +}); ``` -### on('audioRendererChange')9+ - -on(type: "audioRendererChange", callback: Callback<AudioRendererChangeInfoArray>): void - -Subscribes to audio renderer change events. +### on('deviceChange')(deprecated) -**System capability**: SystemCapability.Multimedia.Audio.Renderer +on(type: 'deviceChange', callback: Callback): void -**Parameters** +Subscribes to device change events. When a device is connected or disconnected, registered clients will receive the callback. -| Name | Type | Mandatory | Description | -| -------- | ---------- | --------- | ------------------------------------------------------------------------ | -| type | string | Yes | Event type. The event `'audioRendererChange'` is triggered when the audio renderer changes. | -| callback | Callback<[AudioRendererChangeInfoArray](#audiorendererchangeinfoarray9)> | Yes | Callback used to return the result. | +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [on](#on9) in **AudioRoutingManager**. -**Error codes** +**System capability**: SystemCapability.Multimedia.Audio.Device -For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). +**Parameters** -| ID| Error Message| -| ------- | --------------------------------------------| -| 6800101 | if input parameter value error. | +| Name | Type | Mandatory| Description | +| :------- | :--------------------------------------------------- | :--- | :----------------------------------------- | +| type | string | Yes | Event type. The value **'deviceChange'** means the device change event, which is triggered when a device connection status change is detected.| +| callback | Callback<[DeviceChangeAction](#devicechangeaction)\> | Yes | Callback used to return the device update details. | **Example** ```js -audioStreamManager.on('audioRendererChange', (AudioRendererChangeInfoArray) => { - for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { - let AudioRendererChangeInfo = AudioRendererChangeInfoArray[i]; - console.info(`## RendererChange on is called for ${i} ##`); - console.info(`StreamId for ${i} is: ${AudioRendererChangeInfo.streamId}`); - console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfo.clientUid}`); - console.info(`Content ${i} is: ${AudioRendererChangeInfo.rendererInfo.content}`); - console.info(`Stream ${i} is: ${AudioRendererChangeInfo.rendererInfo.usage}`); - console.info(`Flag ${i} is: ${AudioRendererChangeInfo.rendererInfo.rendererFlags}`); - console.info(`State for ${i} is: ${AudioRendererChangeInfo.rendererState}`); - for (let j = 0;j < AudioRendererChangeInfo.deviceDescriptors.length; j++) { - console.info(`Id: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].id}`); - console.info(`Type: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceType}`); - console.info(`Role: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceRole}`); - console.info(`Name: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].name}`); - console.info(`Address: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].address}`); - console.info(`SampleRates: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]}`); - console.info(`ChannelCount ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]}`); - console.info(`ChannelMask: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelMasks}`); - } - } +audioManager.on('deviceChange', (deviceChanged) => { + console.info(`device change type : ${deviceChanged.type} `); + console.info(`device descriptor size : ${deviceChanged.deviceDescriptors.length} `); + console.info(`device change descriptor : ${deviceChanged.deviceDescriptors[0].deviceRole} `); + console.info(`device change descriptor : ${deviceChanged.deviceDescriptors[0].deviceType} `); }); ``` -### off('audioRendererChange')9+ - -off(type: "audioRendererChange"): void - -Unsubscribes from audio renderer change events. +### off('deviceChange')(deprecated) -**System capability**: SystemCapability.Multimedia.Audio.Renderer +off(type: 'deviceChange', callback?: Callback): void -**Parameters** +Unsubscribes from device change events. -| Name | Type | Mandatory| Description | -| -------- | ------- | ---- | ---------------- | -| type | string | Yes | Event type. The event `'audioRendererChange'` is triggered when the audio renderer changes.| +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [off](#off9) in **AudioRoutingManager**. -**Error codes** +**System capability**: SystemCapability.Multimedia.Audio.Device -For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). +**Parameters** -| ID| Error Message| -| ------- | --------------------------------------------| -| 6800101 | if input parameter value error. | +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------- | ---- | ------------------------------------------ | +| type | string | Yes | Event type. The value **'deviceChange'** means the device change event, which is triggered when a device connection status change is detected.| +| callback | Callback<[DeviceChangeAction](#devicechangeaction)> | No | Callback used to return the device update details. | **Example** ```js -audioStreamManager.off('audioRendererChange'); -console.info('######### RendererChange Off is called #########'); +audioManager.off('deviceChange', (deviceChanged) => { + console.info('Should be no callback.'); +}); ``` -### on('audioCapturerChange')9+ +### on('interrupt')(deprecated) -on(type: "audioCapturerChange", callback: Callback<AudioCapturerChangeInfoArray>): void +on(type: 'interrupt', interrupt: AudioInterrupt, callback: Callback\): void -Subscribes to audio capturer change events. +Subscribes to audio interruption events. When the application's audio is interrupted by another playback event, the application will receive the callback. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +Same as [on('audioInterrupt')](#onaudiointerrupt9), this API is used to listen for focus changes. However, this API is used in scenarios without audio streams (no **AudioRenderer** instance is created), such as frequency modulation (FM) and voice wakeup. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. + +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------- | --------- | ----------------------------------------------------------------------- | -| type | string | Yes | Event type. The event `'audioCapturerChange'` is triggered when the audio capturer changes. | -| callback | Callback<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| --------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value **'interrupt'** means the audio interruption event, which is triggered when the audio playback of the current application is interrupted by another application.| +| interrupt | AudioInterrupt | Yes | Audio interruption event type. | +| callback | Callback<[InterruptAction](#interruptactiondeprecated)> | Yes | Callback invoked for the audio interruption event. | **Example** ```js -audioStreamManager.on('audioCapturerChange', (AudioCapturerChangeInfoArray) => { - for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { - console.info(`## CapChange on is called for element ${i} ##`); - console.info(`StreamId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`); - console.info(`ClientUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`); - console.info(`Source for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`); - console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`); - console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`); - let devDescriptor = AudioCapturerChangeInfoArray[i].deviceDescriptors; - for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { - console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`); - console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`); - console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); - console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`); - console.info(`Address: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`); - console.info(`SampleRates: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); - console.info(`ChannelCounts ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); - console.info(`ChannelMask: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); - } +let interAudioInterrupt = { + streamUsage:2, + contentType:0, + pauseWhenDucked:true +}; +audioManager.on('interrupt', interAudioInterrupt, (InterruptAction) => { + if (InterruptAction.actionType === 0) { + console.info('An event to gain the audio focus starts.'); + console.info(`Focus gain event: ${InterruptAction} `); + } + if (InterruptAction.actionType === 1) { + console.info('An audio interruption event starts.'); + console.info(`Audio interruption event: ${InterruptAction} `); } }); ``` -### off('audioCapturerChange')9+ +### off('interrupt')(deprecated) -off(type: "audioCapturerChange"): void; +off(type: 'interrupt', interrupt: AudioInterrupt, callback?: Callback\): void -Unsubscribes from audio capturer change events. +Unsubscribes from audio interruption events. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. + +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------- | --- | ------------------------------------------------------------- | -| type | string |Yes | Event type. The event `'audioCapturerChange'` is triggered when the audio capturer changes.| +| Name | Type | Mandatory| Description | +| --------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value **'interrupt'** means the audio interruption event, which is triggered when the audio playback of the current application is interrupted by another application.| +| interrupt | AudioInterrupt | Yes | Audio interruption event type. | +| callback | Callback<[InterruptAction](#interruptactiondeprecated)> | No | Callback invoked for the audio interruption event. | **Example** ```js -audioStreamManager.off('audioCapturerChange'); -console.info('######### CapturerChange Off is called #########'); - +let interAudioInterrupt = { + streamUsage:2, + contentType:0, + pauseWhenDucked:true +}; +audioManager.off('interrupt', interAudioInterrupt, (InterruptAction) => { + if (InterruptAction.actionType === 0) { + console.info('An event to release the audio focus starts.'); + console.info(`Focus release event: ${InterruptAction} `); + } +}); ``` -### isActive9+ +## AudioVolumeManager9+ -isActive(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void +Implements audio volume management. Before calling an API in **AudioVolumeManager**, you must use [getVolumeManager](#getvolumemanager9) to obtain an **AudioVolumeManager** instance. -Checks whether a stream is active. This API uses an asynchronous callback to return the result. +### getVolumeGroupInfos9+ -**System capability**: SystemCapability.Multimedia.Audio.Renderer +getVolumeGroupInfos(networkId: string, callback: AsyncCallback\): void + +Obtains the volume groups. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ----------------------------------- | ---- | ------------------------------------------------- | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the active status of the stream. The value **true** means that the stream is active, and **false** means the opposite.| +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | -------------------- | +| networkId | string | Yes | Network ID of the device. The network ID of the local device is **audio.LOCAL_NETWORK_ID**. | +| callback | AsyncCallback<[VolumeGroupInfos](#volumegroupinfos9)> | Yes | Callback used to return the volume group information array.| **Example** - ```js -audioStreamManager.isActive(audio.AudioVolumeType.MEDIA, (err, value) => { +audioVolumeManager.getVolumeGroupInfos(audio.LOCAL_NETWORK_ID, (err, value) => { if (err) { - console.error(`Failed to obtain the active status of the stream. ${err}`); + console.error(`Failed to obtain the volume group infos list. ${err}`); return; } - console.info(`Callback invoked to indicate that the active status of the stream is obtained ${value}.`); + console.info('Callback invoked to indicate that the volume group infos list is obtained.'); }); ``` -### isActive9+ +### getVolumeGroupInfos9+ -isActive(volumeType: AudioVolumeType): Promise<boolean> +getVolumeGroupInfos(networkId: string\): Promise -Checks whether a stream is active. This API uses a promise to return the result. +Obtains the volume groups. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ----------------------------------- | ---- | ------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| +| Name | Type | Mandatory| Description | +| ---------- | ------------------| ---- | -------------------- | +| networkId | string | Yes | Network ID of the device. The network ID of the local device is **audio.LOCAL_NETWORK_ID**. | **Return value** -| Type | Description | -| ---------------------- | -------------------------------------------------------- | -| Promise<boolean> | Promise used to return the active status of the stream. The value **true** means that the stream is active, and **false** means the opposite.| +| Type | Description | +| ------------------- | ----------------------------- | +| Promise<[VolumeGroupInfos](#volumegroupinfos9)> | Volume group information array.| **Example** ```js -audioStreamManager.isActive(audio.AudioVolumeType.MEDIA).then((value) => { - console.info(`Promise returned to indicate that the active status of the stream is obtained ${value}.`); -}); -``` - -## AudioRoutingManager9+ - -Implements audio routing management. Before calling any API in **AudioRoutingManager**, you must use [getRoutingManager](#getroutingmanager9) to obtain an **AudioRoutingManager** instance. +async function getVolumeGroupInfos(){ + let volumegroupinfos = await audio.getAudioManager().getVolumeManager().getVolumeGroupInfos(audio.LOCAL_NETWORK_ID); + console.info('Promise returned to indicate that the volumeGroup list is obtained.'+JSON.stringify(volumegroupinfos)) +} +``` -### getDevices9+ +### getVolumeGroupManager9+ -getDevices(deviceFlag: DeviceFlag, callback: AsyncCallback<AudioDeviceDescriptors>): void +getVolumeGroupManager(groupId: number, callback: AsyncCallback\): void -Obtains the audio devices with a specific flag. This API uses an asynchronous callback to return the result. +Obtains the audio group manager. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | -------------------- | -| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag. | -| callback | AsyncCallback<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Yes | Callback used to return the device list.| +| groupId | number | Yes | Volume group ID. | +| callback | AsyncCallback<[AudioVolumeGroupManager](#audiovolumegroupmanager9)> | Yes | Callback used to return the audio group manager.| **Example** ```js -audioRoutingManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (err, value) => { +let groupid = audio.DEFAULT_VOLUME_GROUP_ID; +audioVolumeManager.getVolumeGroupManager(groupid, (err, value) => { if (err) { - console.error(`Failed to obtain the device list. ${err}`); + console.error(`Failed to obtain the volume group infos list. ${err}`); return; } - console.info('Callback invoked to indicate that the device list is obtained.'); + console.info('Callback invoked to indicate that the volume group infos list is obtained.'); }); + ``` -### getDevices9+ +### getVolumeGroupManager9+ -getDevices(deviceFlag: DeviceFlag): Promise<AudioDeviceDescriptors> +getVolumeGroupManager(groupId: number\): Promise -Obtains the audio devices with a specific flag. This API uses a promise to return the result. +Obtains the audio group manager. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------------------------- | ---- | ---------------- | -| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag.| +| Name | Type | Mandatory| Description | +| ---------- | ---------------------------------------- | ---- | ---------------- | +| groupId | number | Yes | Volume group ID. | **Return value** -| Type | Description | -| ------------------------------------------------------------ | ------------------------- | -| Promise<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Promise used to return the device list.| +| Type | Description | +| ------------------- | ----------------------------- | +| Promise< [AudioVolumeGroupManager](#audiovolumegroupmanager9) > | Promise used to return the audio group manager.| **Example** ```js -audioRoutingManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data) => { - console.info('Promise returned to indicate that the device list is obtained.'); -}); +let groupid = audio.DEFAULT_VOLUME_GROUP_ID; +let audioVolumeGroupManager; +getVolumeGroupManager(); +async function getVolumeGroupManager(){ + audioVolumeGroupManager = await audioVolumeManager.getVolumeGroupManager(groupid); + console.info('Callback invoked to indicate that the volume group infos list is obtained.'); +} + ``` -### on9+ +### on('volumeChange')9+ -on(type: 'deviceChange', deviceFlag: DeviceFlag, callback: Callback): void +on(type: 'volumeChange', callback: Callback\): void -Subscribes to device change events. When a device is connected or disconnected, registered clients will receive the callback. +Subscribes to system volume change events. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory| Description | -| :------- | :--------------------------------------------------- | :--- | :----------------------------------------- | -| type | string | Yes | Event type. The value **'deviceChange'** means the device change event, which is triggered when a device connection status change is detected.| -| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag. | -| callback | Callback<[DeviceChangeAction](#devicechangeaction)\> | Yes | Callback used to return the device update details. | +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value **'volumeChange'** means the system volume change event, which is triggered when the system volume changes.| +| callback | Callback<[VolumeEvent](#volumeevent8)> | Yes | Callback used to return the system volume change event. | **Error codes** @@ -2366,2108 +2340,2324 @@ For details about the error codes, see [Audio Error Codes](../errorcodes/errorco | ID| Error Message| | ------- | --------------------------------------------| -| 6800101 | if input parameter value error. | +| 6800101 | if input parameter value error | **Example** ```js -audioRoutingManager.on('deviceChange', audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (deviceChanged) => { - console.info('device change type : ' + deviceChanged.type); - console.info('device descriptor size : ' + deviceChanged.deviceDescriptors.length); - console.info('device change descriptor : ' + deviceChanged.deviceDescriptors[0].deviceRole); - console.info('device change descriptor : ' + deviceChanged.deviceDescriptors[0].deviceType); +audioVolumeManager.on('volumeChange', (volumeEvent) => { + console.info(`VolumeType of stream: ${volumeEvent.volumeType} `); + console.info(`Volume level: ${volumeEvent.volume} `); + console.info(`Whether to updateUI: ${volumeEvent.updateUi} `); }); ``` -### off9+ - -off(type: 'deviceChange', callback?: Callback): void - -Unsubscribes from device change events. - -**System capability**: SystemCapability.Multimedia.Audio.Device - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | --------------------------------------------------- | ---- | ------------------------------------------ | -| type | string | Yes | Event type. The value **'deviceChange'** means the device change event, which is triggered when a device connection status change is detected.| -| callback | Callback<[DeviceChangeAction](#devicechangeaction)> | No | Callback used to return the device update details. | +## AudioVolumeGroupManager9+ -**Error codes** +Manages the volume of an audio group. Before calling any API in **AudioVolumeGroupManager**, you must use [getVolumeGroupManager](#getvolumegroupmanager9) to obtain an **AudioVolumeGroupManager** instance. -For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). +**System API**: This is a system API. -| ID| Error Message| -| ------- | --------------------------------------------| -| 6800101 | if input parameter value error. | +**System capability**: SystemCapability.Multimedia.Audio.Volume -**Example** +### setVolume9+ -```js -audioRoutingManager.off('deviceChange', (deviceChanged) => { - console.info('Should be no callback.'); -}); -``` +setVolume(volumeType: AudioVolumeType, volume: number, callback: AsyncCallback<void>): void -### selectInputDevice9+ +Sets the volume for a stream. This API uses an asynchronous callback to return the result. -selectInputDevice(inputAudioDevices: AudioDeviceDescriptors, callback: AsyncCallback<void>): void +**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY -Selects an audio input device. Currently, only one input device can be selected. This API uses an asynchronous callback to return the result. +This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. **System API**: This is a system API. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory| Description | -| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | -| inputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Input device. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | -------------------------------------------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| volume | number | Yes | Volume to set. The value range can be obtained by calling **getMinVolume** and **getMaxVolume**.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** -```js -let inputAudioDeviceDescriptor = [{ - "deviceRole":audio.DeviceRole.INPUT_DEVICE, - "networkId":audio.LOCAL_NETWORK_ID, - "interruptGroupId":1, - "volumeGroupId":1 }]; -async function selectInputDevice(){ - audioRoutingManager.selectInputDevice(inputAudioDeviceDescriptor, (err) => { - if (err) { - console.error(`Result ERROR: ${err}`); - } else { - console.info('Select input devices result callback: SUCCESS'); } - }); -} +```js +audioVolumeGroupManager.setVolume(audio.AudioVolumeType.MEDIA, 10, (err) => { + if (err) { + console.error(`Failed to set the volume. ${err}`); + return; + } + console.info('Callback invoked to indicate a successful volume setting.'); +}); ``` -### selectInputDevice9+ +### setVolume9+ -selectInputDevice(inputAudioDevices: AudioDeviceDescriptors): Promise<void> +setVolume(volumeType: AudioVolumeType, volume: number): Promise<void> -**System API**: This is a system API. +Sets the volume for a stream. This API uses a promise to return the result. -Selects an audio input device. Currently, only one input device can be selected. This API uses a promise to return the result. +**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY -**System capability**: SystemCapability.Multimedia.Audio.Device +This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory| Description | -| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | -| inputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Input device. | +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | -------------------------------------------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| volume | number | Yes | Volume to set. The value range can be obtained by calling **getMinVolume** and **getMaxVolume**.| **Return value** -| Type | Description | -| --------------------- | --------------------------- | -| Promise<void> | Promise used to return the result.| +| Type | Description | +| ------------------- | ----------------------------- | +| Promise<void> | Promise used to return the result.| **Example** ```js -let inputAudioDeviceDescriptor =[{ - "deviceRole":audio.DeviceRole.INPUT_DEVICE, - "networkId":audio.LOCAL_NETWORK_ID, - "interruptGroupId":1, - "volumeGroupId":1 }]; - -async function getRoutingManager(){ - audioRoutingManager.selectInputDevice(inputAudioDeviceDescriptor).then(() => { - console.info('Select input devices result promise: SUCCESS'); - }).catch((err) => { - console.error(`Result ERROR: ${err}`); - }); -} +audioVolumeGroupManager.setVolume(audio.AudioVolumeType.MEDIA, 10).then(() => { + console.info('Promise returned to indicate a successful volume setting.'); +}); ``` -### setCommunicationDevice9+ +### getVolume9+ -setCommunicationDevice(deviceType: CommunicationDeviceType, active: boolean, callback: AsyncCallback<void>): void +getVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void -Sets a communication device to the active state. This API uses an asynchronous callback to return the result. +Obtains the volume of a stream. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Communication +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------------------------------------- | ---- | ------------------------ | -| deviceType | [CommunicationDeviceType](#communicationdevicetype9) | Yes | Communication device type. | -| active | boolean | Yes | Active state to set. The value **true** means to set the device to the active state, and **false** means the opposite. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| callback | AsyncCallback<number> | Yes | Callback used to return the volume.| **Example** ```js -audioRoutingManager.setCommunicationDevice(audio.CommunicationDeviceType.SPEAKER, true, (err) => { +audioVolumeGroupManager.getVolume(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { - console.error(`Failed to set the active status of the device. ${err}`); + console.error(`Failed to obtain the volume. ${err}`); return; } - console.info('Callback invoked to indicate that the device is set to the active status.'); + console.info('Callback invoked to indicate that the volume is obtained.'); }); ``` -### setCommunicationDevice9+ +### getVolume9+ -setCommunicationDevice(deviceType: CommunicationDeviceType, active: boolean): Promise<void> +getVolume(volumeType: AudioVolumeType): Promise<number> -Sets a communication device to the active state. This API uses a promise to return the result. +Obtains the volume of a stream. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Communication +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ----------------------------------------------------- | ---- | ------------------ | -| deviceType | [CommunicationDeviceType](#communicationdevicetype9) | Yes | Communication device type.| -| active | boolean | Yes | Active state to set. The value **true** means to set the device to the active state, and **false** means the opposite. | +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| **Return value** -| Type | Description | -| ------------------- | ------------------------------- | -| Promise<void> | Promise used to return the result.| +| Type | Description | +| --------------------- | ------------------------- | +| Promise<number> | Promise used to return the volume.| **Example** ```js -audioRoutingManager.setCommunicationDevice(audio.CommunicationDeviceType.SPEAKER, true).then(() => { - console.info('Promise returned to indicate that the device is set to the active status.'); +audioVolumeGroupManager.getVolume(audio.AudioVolumeType.MEDIA).then((value) => { + console.info(`Promise returned to indicate that the volume is obtained ${value}.`); }); ``` -### isCommunicationDeviceActive9+ +### getMinVolume9+ -isCommunicationDeviceActive(deviceType: CommunicationDeviceType, callback: AsyncCallback<boolean>): void +getMinVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void -Checks whether a communication device is active. This API uses an asynchronous callback to return the result. +Obtains the minimum volume allowed for a stream. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Communication +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ---------------------------------------------------- | ---- | ------------------------ | -| deviceType | [CommunicationDeviceType](#communicationdevicetype9) | Yes | Communication device type. | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the active state of the device.| +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| callback | AsyncCallback<number> | Yes | Callback used to return the minimum volume.| **Example** ```js -audioRoutingManager.isCommunicationDeviceActive(audio.CommunicationDeviceType.SPEAKER, (err, value) => { +audioVolumeGroupManager.getMinVolume(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { - console.error(`Failed to obtain the active status of the device. ${err}`); + console.error(`Failed to obtain the minimum volume. ${err}`); return; } - console.info('Callback invoked to indicate that the active status of the device is obtained.'); + console.info(`Callback invoked to indicate that the minimum volume is obtained. ${value}`); }); ``` -### isCommunicationDeviceActive9+ +### getMinVolume9+ -isCommunicationDeviceActive(deviceType: CommunicationDeviceType): Promise<boolean> +getMinVolume(volumeType: AudioVolumeType): Promise<number> -Checks whether a communication device is active. This API uses a promise to return the result. +Obtains the minimum volume allowed for a stream. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Communication +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ---------------------------------------------------- | ---- | ------------------ | -| deviceType | [CommunicationDeviceType](#communicationdevicetype9) | Yes | Communication device type.| +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| **Return value** -| Type | Description | -| ---------------------- | ------------------------------- | -| Promise<boolean> | Promise used to return the active state of the device.| +| Type | Description | +| --------------------- | ------------------------- | +| Promise<number> | Promise used to return the minimum volume.| **Example** ```js -audioRoutingManager.isCommunicationDeviceActive(audio.CommunicationDeviceType.SPEAKER).then((value) => { - console.info(`Promise returned to indicate that the active status of the device is obtained ${value}.`); +audioVolumeGroupManager.getMinVolume(audio.AudioVolumeType.MEDIA).then((value) => { + console.info(`Promised returned to indicate that the minimum volume is obtained ${value}.`); }); ``` -### selectOutputDevice9+ - -selectOutputDevice(outputAudioDevices: AudioDeviceDescriptors, callback: AsyncCallback<void>): void +### getMaxVolume9+ -Selects an audio output device. Currently, only one output device can be selected. This API uses an asynchronous callback to return the result. +getMaxVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void -**System API**: This is a system API. +Obtains the maximum volume allowed for a stream. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory| Description | -| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | -| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Output device. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ---------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| callback | AsyncCallback<number> | Yes | Callback used to return the maximum volume.| **Example** + ```js -let outputAudioDeviceDescriptor = [{ - "deviceRole":audio.DeviceRole.OUTPUT_DEVICE, - "networkId":audio.LOCAL_NETWORK_ID, - "interruptGroupId":1, - "volumeGroupId":1 }]; -async function selectOutputDevice(){ - audioRoutingManager.selectOutputDevice(outputAudioDeviceDescriptor, (err) => { - if (err) { - console.error(`Result ERROR: ${err}`); - } else { - console.info('Select output devices result callback: SUCCESS'); } - }); -} +audioVolumeGroupManager.getMaxVolume(audio.AudioVolumeType.MEDIA, (err, value) => { + if (err) { + console.error(`Failed to obtain the maximum volume. ${err}`); + return; + } + console.info(`Callback invoked to indicate that the maximum volume is obtained. ${value}`); +}); ``` -### selectOutputDevice9+ - -selectOutputDevice(outputAudioDevices: AudioDeviceDescriptors): Promise<void> +### getMaxVolume9+ -**System API**: This is a system API. +getMaxVolume(volumeType: AudioVolumeType): Promise<number> -Selects an audio output device. Currently, only one output device can be selected. This API uses a promise to return the result. +Obtains the maximum volume allowed for a stream. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory| Description | -| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | -| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Output device. | +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| **Return value** -| Type | Description | -| --------------------- | --------------------------- | -| Promise<void> | Promise used to return the result.| +| Type | Description | +| --------------------- | ----------------------------- | +| Promise<number> | Promise used to return the maximum volume.| **Example** ```js -let outputAudioDeviceDescriptor =[{ - "deviceRole":audio.DeviceRole.OUTPUT_DEVICE, - "networkId":audio.LOCAL_NETWORK_ID, - "interruptGroupId":1, - "volumeGroupId":1 }]; - -async function selectOutputDevice(){ - audioRoutingManager.selectOutputDevice(outputAudioDeviceDescriptor).then(() => { - console.info('Select output devices result promise: SUCCESS'); - }).catch((err) => { - console.error(`Result ERROR: ${err}`); - }); -} +audioVolumeGroupManager.getMaxVolume(audio.AudioVolumeType.MEDIA).then((data) => { + console.info('Promised returned to indicate that the maximum volume is obtained.'); +}); ``` -### selectOutputDeviceByFilter9+ +### mute9+ -selectOutputDeviceByFilter(filter: AudioRendererFilter, outputAudioDevices: AudioDeviceDescriptors, callback: AsyncCallback<void>): void +mute(volumeType: AudioVolumeType, mute: boolean, callback: AsyncCallback<void>): void -**System API**: This is a system API. +Mutes or unmutes a stream. This API uses an asynchronous callback to return the result. -Selects an audio output device based on the filter criteria. Currently, only one output device can be selected. This API uses an asynchronous callback to return the result. +**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY -**System capability**: SystemCapability.Multimedia.Audio.Device +This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory| Description | -| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | -| filter | [AudioRendererFilter](#audiorendererfilter9) | Yes | Filter criteria. | -| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Output device. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------------------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| mute | boolean | Yes | Mute status to set. The value **true** means to mute the stream, and **false** means the opposite.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** -```js -let outputAudioRendererFilter = { - "uid":20010041, - "rendererInfo": { - "contentType":audio.ContentType.CONTENT_TYPE_MUSIC, - "streamUsage":audio.StreamUsage.STREAM_USAGE_MEDIA, - "rendererFlags":0 }, - "rendererId":0 }; -let outputAudioDeviceDescriptor = [{ - "deviceRole":audio.DeviceRole.OUTPUT_DEVICE, - "networkId":audio.LOCAL_NETWORK_ID, - "interruptGroupId":1, - "volumeGroupId":1 }]; -async function selectOutputDeviceByFilter(){ - audioRoutingManager.selectOutputDeviceByFilter(outputAudioRendererFilter, outputAudioDeviceDescriptor, (err) => { - if (err) { - console.error(`Result ERROR: ${err}`); - } else { - console.info('Select output devices by filter result callback: SUCCESS'); } - }); -} +```js +audioVolumeGroupManager.mute(audio.AudioVolumeType.MEDIA, true, (err) => { + if (err) { + console.error(`Failed to mute the stream. ${err}`); + return; + } + console.info('Callback invoked to indicate that the stream is muted.'); +}); ``` -### selectOutputDeviceByFilter9+ +### mute9+ -selectOutputDeviceByFilter(filter: AudioRendererFilter, outputAudioDevices: AudioDeviceDescriptors): Promise<void> +mute(volumeType: AudioVolumeType, mute: boolean): Promise<void> -**System API**: This is a system API. +Mutes or unmutes a stream. This API uses a promise to return the result. -Selects an audio output device based on the filter criteria. Currently, only one output device can be selected. This API uses a promise to return the result. +**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY -**System capability**: SystemCapability.Multimedia.Audio.Device +This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory| Description | -| ----------------------| ------------------------------------------------------------ | ---- | ------------------------- | -| filter | [AudioRendererFilter](#audiorendererfilter9) | Yes | Filter criteria. | -| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Output device. | +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------------------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| mute | boolean | Yes | Mute status to set. The value **true** means to mute the stream, and **false** means the opposite.| **Return value** -| Type | Description | -| --------------------- | --------------------------- | -| Promise<void> | Promise used to return the result.| +| Type | Description | +| ------------------- | ----------------------------- | +| Promise<void> | Promise used to return the result.| **Example** ```js -let outputAudioRendererFilter = { - "uid":20010041, - "rendererInfo": { - "contentType":audio.ContentType.CONTENT_TYPE_MUSIC, - "streamUsage":audio.StreamUsage.STREAM_USAGE_MEDIA, - "rendererFlags":0 }, - "rendererId":0 }; -let outputAudioDeviceDescriptor = [{ - "deviceRole":audio.DeviceRole.OUTPUT_DEVICE, - "networkId":audio.LOCAL_NETWORK_ID, - "interruptGroupId":1, - "volumeGroupId":1 }]; - -async function selectOutputDeviceByFilter(){ - audioRoutingManager.selectOutputDeviceByFilter(outputAudioRendererFilter, outputAudioDeviceDescriptor).then(() => { - console.info('Select output devices by filter result promise: SUCCESS'); - }).catch((err) => { - console.error(`Result ERROR: ${err}`); - }) -} +audioVolumeGroupManager.mute(audio.AudioVolumeType.MEDIA, true).then(() => { + console.info('Promise returned to indicate that the stream is muted.'); +}); ``` -## AudioRendererChangeInfoArray9+ - -Defines an **AudioRenderChangeInfo** array, which is read-only. +### isMute9+ -**System capability**: SystemCapability.Multimedia.Audio.Renderer +isMute(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void -## AudioRendererChangeInfo9+ +Checks whether a stream is muted. This API uses an asynchronous callback to return the result. -Describes the audio renderer change event. +**System capability**: SystemCapability.Multimedia.Audio.Volume -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**Parameters** -| Name | Type | Readable | Writable | Description | -| ------------- | ---------------------------------------- | -------- | -------- | ---------------------------------------------------------- | -| streamId | number | Yes | No | Unique ID of an audio stream. | -| clientUid | number | Yes | No | UID of the audio renderer client.
This is a system API. | -| rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | Yes | No | Audio renderer information. | -| rendererState | [AudioState](#audiostate) | Yes | No | Audio state.
This is a system API. | +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ----------------------------------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the mute status of the stream. The value **true** means that the stream is muted, and **false** means the opposite.| **Example** ```js -import audio from '@ohos.multimedia.audio'; - -let audioStreamManager; -let resultFlag = false; -let audioManager = audio.getAudioManager(); - -audioManager.getStreamManager((err, data) => { +audioVolumeGroupManager.isMute(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { - console.error(`Get AudioStream Manager : ERROR : ${err}`); - } else { - audioStreamManager = data; - console.info('Get AudioStream Manager : Success'); + console.error(`Failed to obtain the mute status. ${err}`); + return; } + console.info(`Callback invoked to indicate that the mute status of the stream is obtained ${value}.`); }); +``` -audioStreamManager.on('audioRendererChange', (AudioRendererChangeInfoArray) => { - for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { - console.info(`## RendererChange on is called for ${i} ##`); - console.info(`StreamId for ${i} is: ${AudioRendererChangeInfoArray[i].streamId}`); - console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfoArray[i].clientUid}`); - console.info(`Content for ${i} is: ${AudioRendererChangeInfoArray[i].rendererInfo.content}`); - console.info(`Stream for ${i} is: ${AudioRendererChangeInfoArray[i].rendererInfo.usage}`); - console.info(`Flag ${i} is: ${AudioRendererChangeInfoArray[i].rendererInfo.rendererFlags}`); - console.info(`State for ${i} is: ${AudioRendererChangeInfoArray[i].rendererState}`); - let devDescriptor = AudioRendererChangeInfoArray[i].deviceDescriptors; - for (let j = 0; j < AudioRendererChangeInfoArray[i].deviceDescriptors.length; j++) { - console.info(`Id: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].id}`); - console.info(`Type: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].deviceType}`); - console.info(`Role: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); - console.info(`Name: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].name}`); - console.info(`Addr: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].address}`); - console.info(`SR: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); - console.info(`C ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); - console.info(`CM: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); - } - if (AudioRendererChangeInfoArray[i].rendererState == 1 && devDescriptor != null) { - resultFlag = true; - console.info(`ResultFlag for ${i} is: ${resultFlag}`); - } - } +### isMute9+ + +isMute(volumeType: AudioVolumeType): Promise<boolean> + +Checks whether a stream is muted. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Volume + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| + +**Return value** + +| Type | Description | +| ---------------------- | ------------------------------------------------------ | +| Promise<boolean> | Promise used to return the mute status of the stream. The value **true** means that the stream is muted, and **false** means the opposite.| + +**Example** + +```js +audioVolumeGroupManager.isMute(audio.AudioVolumeType.MEDIA).then((value) => { + console.info(`Promise returned to indicate that the mute status of the stream is obtained ${value}.`); }); ``` +### setRingerMode9+ -## AudioCapturerChangeInfoArray9+ +setRingerMode(mode: AudioRingMode, callback: AsyncCallback<void>): void -Defines an **AudioCapturerChangeInfo** array, which is read-only. +Sets the ringer mode. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY -## AudioCapturerChangeInfo9+ +This permission is required only for muting or unmuting the ringer. -Describes the audio capturer change event. +**System API**: This is a system API. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Volume -| Name | Type | Readable | Writable | Description | -| ------------- | ---------------------------------------- | -------- | -------- | ---------------------------------------------------------- | -| streamId | number | Yes | No | Unique ID of an audio stream. | -| clientUid | number | Yes | No | UID of the audio capturer client.
This is a system API. | -| capturerInfo | [AudioCapturerInfo](#audiocapturerinfo8) | Yes | No | Audio capturer information. | -| capturerState | [AudioState](#audiostate) | Yes | No | Audio state.
This is a system API. | +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------- | ---- | ------------------------ | +| mode | [AudioRingMode](#audioringmode) | Yes | Ringer mode. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** ```js -import audio from '@ohos.multimedia.audio'; - -const audioManager = audio.getAudioManager(); -let audioStreamManager; -audioManager.getStreamManager((err, data) => { +audioVolumeGroupManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL, (err) => { if (err) { - console.error(`getStreamManager : Error: ${err}`); - } else { - console.info('getStreamManager : Success : SUCCESS'); - audioStreamManager = data; - } -}); - -let resultFlag = false; -audioStreamManager.on('audioCapturerChange', (AudioCapturerChangeInfoArray) => { - for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { - console.info(`## CapChange on is called for element ${i} ##`); - console.info(`StrId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`); - console.info(`CUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`); - console.info(`Src for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`); - console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`); - console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`); - let devDescriptor = AudioCapturerChangeInfoArray[i].deviceDescriptors; - for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { - console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`); - console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`); - console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); - console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`); - console.info(`Addr: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`); - console.info(`SR: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); - console.info(`C ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); - console.info(`CM ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); - } - if (AudioCapturerChangeInfoArray[i].capturerState == 1 && devDescriptor != null) { - resultFlag = true; - console.info(`ResultFlag for element ${i} is: ${resultFlag}`); - } + console.error(`Failed to set the ringer mode.​ ${err}`); + return; } + console.info('Callback invoked to indicate a successful setting of the ringer mode.'); }); ``` -## AudioDeviceDescriptors +### setRingerMode9+ -Defines an [AudioDeviceDescriptor](#audiodevicedescriptor) array, which is read-only. +setRingerMode(mode: AudioRingMode): Promise<void> -## AudioDeviceDescriptor +Sets the ringer mode. This API uses a promise to return the result. -Describes an audio device. +**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY -**System capability**: SystemCapability.Multimedia.Audio.Device +This permission is required only for muting or unmuting the ringer. -| Name | Type | Readable | Writable | Description | -| ----------------------------- | ------------------------- | -------- | -------- | ------------------------------------------------------------ | -| deviceRole | [DeviceRole](#devicerole) | Yes | No | Device role. | -| deviceType | [DeviceType](#devicetype) | Yes | No | Device type. | -| id9+ | number | Yes | No | Device ID. | -| name9+ | string | Yes | No | Device name. | -| address9+ | string | Yes | No | Device address. | -| sampleRates9+ | Array<number> | Yes | No | Supported sampling rates. | -| channelCounts9+ | Array<number> | Yes | No | Number of channels supported. | -| channelMasks9+ | Array<number> | Yes | No | Supported channel masks. | -| networkId9+ | string | Yes | No | ID of the device network.
This is a system API. | -| interruptGroupId9+ | number | Yes | No | ID of the interruption group to which the device belongs.
This is a system API. | -| volumeGroupId9+ | number | Yes | No | ID of the volume group to which the device belongs.
This is a system API. | +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.Audio.Volume + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------- | ---- | -------------- | +| mode | [AudioRingMode](#audioringmode) | Yes | Ringer mode.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------- | +| Promise<void> | Promise used to return the result.| **Example** ```js -import audio from '@ohos.multimedia.audio'; +audioVolumeGroupManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL).then(() => { + console.info('Promise returned to indicate a successful setting of the ringer mode.'); +}); +``` -function displayDeviceProp(value) { - deviceRoleValue = value.deviceRole; - deviceTypeValue = value.deviceType; -} +### getRingerMode9+ -let deviceRoleValue = null; -let deviceTypeValue = null; -const promise = audio.getAudioManager().getDevices(1); -promise.then(function (value) { - console.info('AudioFrameworkTest: Promise: getDevices OUTPUT_DEVICES_FLAG'); - value.forEach(displayDeviceProp); - if (deviceTypeValue != null && deviceRoleValue != null){ - console.info('AudioFrameworkTest: Promise: getDevices : OUTPUT_DEVICES_FLAG : PASS'); - } else { - console.error('AudioFrameworkTest: Promise: getDevices : OUTPUT_DEVICES_FLAG : FAIL'); +getRingerMode(callback: AsyncCallback<AudioRingMode>): void + +Obtains the ringer mode. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Volume + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------- | ---- | ------------------------ | +| callback | AsyncCallback<[AudioRingMode](#audioringmode)> | Yes | Callback used to return the ringer mode.| + +**Example** + +```js +audioVolumeGroupManager.getRingerMode((err, value) => { + if (err) { + console.error(`Failed to obtain the ringer mode.​ ${err}`); + return; } + console.info(`Callback invoked to indicate that the ringer mode is obtained ${value}.`); }); ``` -## AudioRendererFilter9+ +### getRingerMode9+ + +getRingerMode(): Promise<AudioRingMode> + +Obtains the ringer mode. This API uses a promise to return the result. -Implements filter criteria. Before calling **selectOutputDeviceByFilter**, you must obtain an **AudioRendererFilter** instance. +**System capability**: SystemCapability.Multimedia.Audio.Volume -**System API**: This is a system API. +**Return value** -| Name | Type | Mandatory | Description | -| ------------ | ---------------------------------------- | --------- | ------------------------------------------------------------ | -| uid | number | Yes | Application ID.
**System capability**: SystemCapability.Multimedia.Audio.Core | -| rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | No | Audio renderer information.
**System capability**: SystemCapability.Multimedia.Audio.Renderer | -| rendererId | number | No | Unique ID of an audio stream.
**System capability**: SystemCapability.Multimedia.Audio.Renderer | +| Type | Description | +| ---------------------------------------------- | ------------------------------- | +| Promise<[AudioRingMode](#audioringmode)> | Promise used to return the ringer mode.| **Example** ```js -let outputAudioRendererFilter = { - "uid":20010041, - "rendererInfo": { - "contentType":audio.ContentType.CONTENT_TYPE_MUSIC, - "streamUsage":audio.StreamUsage.STREAM_USAGE_MEDIA, - "rendererFlags":0 }, - "rendererId":0 }; +audioVolumeGroupManager.getRingerMode().then((value) => { + console.info(`Promise returned to indicate that the ringer mode is obtained ${value}.`); +}); ``` -## AudioRenderer8+ +### on('ringerModeChange')9+ -Provides APIs for audio rendering. Before calling any API in **AudioRenderer**, you must use [createAudioRenderer](#audiocreateaudiorenderer8) to create an **AudioRenderer** instance. +on(type: 'ringerModeChange', callback: Callback\): void -### Attributes +Subscribes to ringer mode change events. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Volume -| Name | Type | Readable | Writable | Description | -| ------------------ | -------------------------- | -------- | -------- | --------------------- | -| state8+ | [AudioState](#audiostate8) | Yes | No | Audio renderer state. | +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value **'ringerModeChange'** means the ringer mode change event, which is triggered when a ringer mode change is detected.| +| callback | Callback<[AudioRingMode](#audioringmode)> | Yes | Callback used to return the system volume change event. | + +**Error codes** + +For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). + +| ID| Error Message| +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error | **Example** ```js -let state = audioRenderer.state; +audioVolumeGroupManager.on('ringerModeChange', (ringerMode) => { + console.info(`Updated ringermode: ${ringerMode}`); +}); ``` +### setMicrophoneMute9+ -### getRendererInfo8+ +setMicrophoneMute(mute: boolean, callback: AsyncCallback<void>): void -getRendererInfo(callback: AsyncCallback): void +Mutes or unmutes the microphone. This API uses an asynchronous callback to return the result. -Obtains the renderer information of this **AudioRenderer** instance. This API uses an asynchronous callback to return the result. +**Required permissions**: ohos.permission.MANAGE_AUDIO_CONFIG -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :------------------------------------------------------- | :-------- | :------------------------------------------------ | -| callback | AsyncCallback<[AudioRendererInfo](#audiorendererinfo8)\> | Yes | Callback used to return the renderer information. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | --------------------------------------------- | +| mute | boolean | Yes | Mute status to set. The value **true** means to mute the microphone, and **false** means the opposite.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** ```js -audioRenderer.getRendererInfo((err, rendererInfo) => { - console.info('Renderer GetRendererInfo:'); - console.info(`Renderer content: ${rendererInfo.content}`); - console.info(`Renderer usage: ${rendererInfo.usage}`); - console.info(`Renderer flags: ${rendererInfo.rendererFlags}`); +audioVolumeGroupManager.setMicrophoneMute(true, (err) => { + if (err) { + console.error(`Failed to mute the microphone. ${err}`); + return; + } + console.info('Callback invoked to indicate that the microphone is muted.'); }); ``` -### getRendererInfo8+ +### setMicrophoneMute9+ -getRendererInfo(): Promise +setMicrophoneMute(mute: boolean): Promise<void> -Obtains the renderer information of this **AudioRenderer** instance. This API uses a promise to return the result. +Mutes or unmutes the microphone. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**Required permissions**: ohos.permission.MANAGE_AUDIO_CONFIG + +**System capability**: SystemCapability.Multimedia.Audio.Volume + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | --------------------------------------------- | +| mute | boolean | Yes | Mute status to set. The value **true** means to mute the microphone, and **false** means the opposite.| **Return value** -| Type | Description | -| -------------------------------------------------- | ------------------------------------------------ | -| Promise<[AudioRendererInfo](#audiorendererinfo8)\> | Promise used to return the renderer information. | +| Type | Description | +| ------------------- | ------------------------------- | +| Promise<void> | Promise used to return the result.| **Example** ```js -audioRenderer.getRendererInfo().then((rendererInfo) => { - console.info('Renderer GetRendererInfo:'); - console.info(`Renderer content: ${rendererInfo.content}`); - console.info(`Renderer usage: ${rendererInfo.usage}`); - console.info(`Renderer flags: ${rendererInfo.rendererFlags}`) -}).catch((err) => { - console.error(`AudioFrameworkRenderLog: RendererInfo :ERROR: ${err}`); +audioVolumeGroupManager.setMicrophoneMute(true).then(() => { + console.info('Promise returned to indicate that the microphone is muted.'); }); ``` -### getStreamInfo8+ +### isMicrophoneMute9+ -getStreamInfo(callback: AsyncCallback): void +isMicrophoneMute(callback: AsyncCallback<boolean>): void -Obtains the stream information of this **AudioRenderer** instance. This API uses an asynchronous callback to return the result. +Checks whether the microphone is muted. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :--------------------------------------------------- | :-------- | :---------------------------------------------- | -| callback | AsyncCallback<[AudioStreamInfo](#audiostreaminfo8)\> | Yes | Callback used to return the stream information. | +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ------------------------------------------------------- | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the mute status of the microphone. The value **true** means that the microphone is muted, and **false** means the opposite.| **Example** ```js -audioRenderer.getStreamInfo((err, streamInfo) => { - console.info('Renderer GetStreamInfo:'); - console.info(`Renderer sampling rate: ${streamInfo.samplingRate}`); - console.info(`Renderer channel: ${streamInfo.channels}`); - console.info(`Renderer format: ${streamInfo.sampleFormat}`); - console.info(`Renderer encoding type: ${streamInfo.encodingType}`); +audioVolumeGroupManager.isMicrophoneMute((err, value) => { + if (err) { + console.error(`Failed to obtain the mute status of the microphone. ${err}`); + return; + } + console.info(`Callback invoked to indicate that the mute status of the microphone is obtained ${value}.`); }); ``` -### getStreamInfo8+ +### isMicrophoneMute9+ -getStreamInfo(): Promise +isMicrophoneMute(): Promise<boolean> -Obtains the stream information of this **AudioRenderer** instance. This API uses a promise to return the result. +Checks whether the microphone is muted. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Volume **Return value** -| Type | Description | -| :--------------------------------------------- | :--------------------------------------------- | -| Promise<[AudioStreamInfo](#audiostreaminfo8)\> | Promise used to return the stream information. | +| Type | Description | +| ---------------------- | ------------------------------------------------------------ | +| Promise<boolean> | Promise used to return the mute status of the microphone. The value **true** means that the microphone is muted, and **false** means the opposite.| **Example** ```js -audioRenderer.getStreamInfo().then((streamInfo) => { - console.info('Renderer GetStreamInfo:'); - console.info(`Renderer sampling rate: ${streamInfo.samplingRate}`); - console.info(`Renderer channel: ${streamInfo.channels}`); - console.info(`Renderer format: ${streamInfo.sampleFormat}`); - console.info(`Renderer encoding type: ${streamInfo.encodingType}`); -}).catch((err) => { - console.error(`ERROR: ${err}`); +audioVolumeGroupManager.isMicrophoneMute().then((value) => { + console.info(`Promise returned to indicate that the mute status of the microphone is obtained ${value}.`); }); +``` + +### on('micStateChange')9+ +on(type: 'micStateChange', callback: Callback<MicStateChangeEvent>): void + +Subscribes to system microphone state change events. + +Currently, when multiple **AudioManager** instances are used in a single process, only the subscription of the last instance takes effect, and the subscription of other instances is overwritten (even if the last instance does not initiate a subscription). Therefore, you are advised to use a single **AudioManager** instance. + +**System capability**: SystemCapability.Multimedia.Audio.Volume + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value **'micStateChange'** means the system microphone state change event, which is triggered when the system microphone state changes.| +| callback | Callback<[MicStateChangeEvent](#micstatechangeevent9)> | Yes | Callback used to return the changed microphone state. | + +**Error codes** + +For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). + +| ID| Error Message| +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error | + +**Example** + +```js +audioVolumeGroupManager.on('micStateChange', (micStateChange) => { + console.info(`Current microphone status is: ${micStateChange.mute} `); +}); ``` -### getAudioStreamId9+ +## AudioStreamManager9+ -getAudioStreamId(callback: AsyncCallback): void +Implements audio stream management. Before calling any API in **AudioStreamManager**, you must use [getStreamManager](#getstreammanager9) to obtain an **AudioStreamManager** instance. -Obtains the stream ID of this **AudioRenderer** instance. This API uses an asynchronous callback to return the result. +### getCurrentAudioRendererInfoArray9+ + +getCurrentAudioRendererInfoArray(callback: AsyncCallback<AudioRendererChangeInfoArray>): void + +Obtains the information about the current audio renderer. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :--------------------- | :-------- | :------------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the stream ID. | +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------- | -------- | --------------------------- | +| callback | AsyncCallback<[AudioRendererChangeInfoArray](#audiorendererchangeinfoarray9)> | Yes | Callback used to return the audio renderer information.| **Example** ```js -audioRenderer.getAudioStreamId((err, streamid) => { - console.info(`Renderer GetStreamId: ${streamid}`); +audioStreamManager.getCurrentAudioRendererInfoArray(async (err, AudioRendererChangeInfoArray) => { + console.info('getCurrentAudioRendererInfoArray **** Get Callback Called ****'); + if (err) { + console.error(`getCurrentAudioRendererInfoArray :ERROR: ${err}`); + } else { + if (AudioRendererChangeInfoArray != null) { + for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { + let AudioRendererChangeInfo = AudioRendererChangeInfoArray[i]; + console.info(`StreamId for ${i} is: ${AudioRendererChangeInfo.streamId}`); + console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfo.clientUid}`); + console.info(`Content ${i} is: ${AudioRendererChangeInfo.rendererInfo.content}`); + console.info(`Stream ${i} is: ${AudioRendererChangeInfo.rendererInfo.usage}`); + console.info(`Flag ${i} is: ${AudioRendererChangeInfo.rendererInfo.rendererFlags}`); + console.info(`State for ${i} is: ${AudioRendererChangeInfo.rendererState}`); + for (let j = 0;j < AudioRendererChangeInfo.deviceDescriptors.length; j++) { + console.info(`Id: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].id}`); + console.info(`Type: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceType}`); + console.info(`Role: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceRole}`); + console.info(`Name: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].name}`); + console.info(`Address: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].address}`); + console.info(`SampleRates: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]}`); + console.info(`ChannelCount ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]}`); + console.info(`ChannelMask: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelMasks}`); + } + } + } + } }); - ``` -### getAudioStreamId9+ +### getCurrentAudioRendererInfoArray9+ -getAudioStreamId(): Promise +getCurrentAudioRendererInfoArray(): Promise<AudioRendererChangeInfoArray> -Obtains the stream ID of this **AudioRenderer** instance. This API uses a promise to return the result. +Obtains the information about the current audio renderer. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Audio.Renderer **Return value** -| Type | Description | -| :--------------- | :------------------------------------ | -| Promise | Promise used to return the stream ID. | +| Type | Description | +| ---------------------------------------------------------------------------------| --------------------------------------- | +| Promise<[AudioRendererChangeInfoArray](#audiorendererchangeinfoarray9)> | Promise used to return the audio renderer information. | **Example** ```js -audioRenderer.getAudioStreamId().then((streamid) => { - console.info(`Renderer getAudioStreamId: ${streamid}`); -}).catch((err) => { - console.error(`ERROR: ${err}`); -}); - +async function getCurrentAudioRendererInfoArray(){ + await audioStreamManager.getCurrentAudioRendererInfoArray().then( function (AudioRendererChangeInfoArray) { + console.info(`getCurrentAudioRendererInfoArray ######### Get Promise is called ##########`); + if (AudioRendererChangeInfoArray != null) { + for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { + let AudioRendererChangeInfo = AudioRendererChangeInfoArray[i]; + console.info(`StreamId for ${i} is: ${AudioRendererChangeInfo.streamId}`); + console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfo.clientUid}`); + console.info(`Content ${i} is: ${AudioRendererChangeInfo.rendererInfo.content}`); + console.info(`Stream ${i} is: ${AudioRendererChangeInfo.rendererInfo.usage}`); + console.info(`Flag ${i} is: ${AudioRendererChangeInfo.rendererInfo.rendererFlags}`); + console.info(`State for ${i} is: ${AudioRendererChangeInfo.rendererState}`); + for (let j = 0;j < AudioRendererChangeInfo.deviceDescriptors.length; j++) { + console.info(`Id: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].id}`); + console.info(`Type: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceType}`); + console.info(`Role: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceRole}`); + console.info(`Name: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].name}`); + console.info(`Address: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].address}`); + console.info(`SampleRates: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]}`); + console.info(`ChannelCount ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]}`); + console.info(`ChannelMask: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelMasks}`); + } + } + } + }).catch((err) => { + console.error(`getCurrentAudioRendererInfoArray :ERROR: ${err}`); + }); +} ``` -### start8+ +### getCurrentAudioCapturerInfoArray9+ -start(callback: AsyncCallback): void +getCurrentAudioCapturerInfoArray(callback: AsyncCallback<AudioCapturerChangeInfoArray>): void -Starts the renderer. This API uses an asynchronous callback to return the result. +Obtains the information about the current audio capturer. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------------------- | --------- | ----------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| ---------- | ----------------------------------- | --------- | -------------------------------------------------------- | +| callback | AsyncCallback<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | Yes | Callback used to return the audio capturer information.| **Example** ```js -audioRenderer.start((err) => { +audioStreamManager.getCurrentAudioCapturerInfoArray(async (err, AudioCapturerChangeInfoArray) => { + console.info('getCurrentAudioCapturerInfoArray **** Get Callback Called ****'); if (err) { - console.error('Renderer start failed.'); + console.error(`getCurrentAudioCapturerInfoArray :ERROR: ${err}`); } else { - console.info('Renderer start success.'); + if (AudioCapturerChangeInfoArray != null) { + for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { + console.info(`StreamId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`); + console.info(`ClientUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`); + console.info(`Source for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`); + console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`); + console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`); + for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { + console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`); + console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`); + console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); + console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`); + console.info(`Address: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`); + console.info(`SampleRates: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); + console.info(`ChannelCounts ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); + console.info(`ChannelMask: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); + } + } + } } }); - ``` -### start8+ +### getCurrentAudioCapturerInfoArray9+ -start(): Promise +getCurrentAudioCapturerInfoArray(): Promise<AudioCapturerChangeInfoArray> -Starts the renderer. This API uses a promise to return the result. +Obtains the information about the current audio capturer. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Audio.Renderer **Return value** -| Type | Description | -| -------------- | ---------------------------------- | -| Promise\ | Promise used to return the result. | +| Type | Description | +| -----------------------------------------------------------------------------| ----------------------------------- | +| Promise<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | Promise used to return the audio capturer information. | **Example** ```js -audioRenderer.start().then(() => { - console.info('Renderer started'); -}).catch((err) => { - console.error(`ERROR: ${err}`); -}); - +async function getCurrentAudioCapturerInfoArray(){ + await audioStreamManager.getCurrentAudioCapturerInfoArray().then( function (AudioCapturerChangeInfoArray) { + console.info('getCurrentAudioCapturerInfoArray **** Get Promise Called ****'); + if (AudioCapturerChangeInfoArray != null) { + for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { + console.info(`StreamId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`); + console.info(`ClientUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`); + console.info(`Source for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`); + console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`); + console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`); + for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { + console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`); + console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`); + console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); + console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`); + console.info(`Address: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`); + console.info(`SampleRates: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); + console.info(`ChannelCounts ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); + console.info(`ChannelMask: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); + } + } + } + }).catch((err) => { + console.error(`getCurrentAudioCapturerInfoArray :ERROR: ${err}`); + }); +} ``` -### pause8+ +### on('audioRendererChange')9+ -pause(callback: AsyncCallback\): void +on(type: "audioRendererChange", callback: Callback<AudioRendererChangeInfoArray>): void -Pauses rendering. This API uses an asynchronous callback to return the result. +Subscribes to audio renderer change events. **System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------------------- | --------- | ----------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ---------- | --------- | ------------------------------------------------------------------------ | +| type | string | Yes | Event type. The event `'audioRendererChange'` is triggered when the audio renderer changes. | +| callback | Callback<[AudioRendererChangeInfoArray](#audiorendererchangeinfoarray9)> | Yes | Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). + +| ID| Error Message| +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error | **Example** ```js -audioRenderer.pause((err) => { - if (err) { - console.error('Renderer pause failed'); - } else { - console.info('Renderer paused.'); +audioStreamManager.on('audioRendererChange', (AudioRendererChangeInfoArray) => { + for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { + let AudioRendererChangeInfo = AudioRendererChangeInfoArray[i]; + console.info(`## RendererChange on is called for ${i} ##`); + console.info(`StreamId for ${i} is: ${AudioRendererChangeInfo.streamId}`); + console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfo.clientUid}`); + console.info(`Content ${i} is: ${AudioRendererChangeInfo.rendererInfo.content}`); + console.info(`Stream ${i} is: ${AudioRendererChangeInfo.rendererInfo.usage}`); + console.info(`Flag ${i} is: ${AudioRendererChangeInfo.rendererInfo.rendererFlags}`); + console.info(`State for ${i} is: ${AudioRendererChangeInfo.rendererState}`); + for (let j = 0;j < AudioRendererChangeInfo.deviceDescriptors.length; j++) { + console.info(`Id: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].id}`); + console.info(`Type: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceType}`); + console.info(`Role: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceRole}`); + console.info(`Name: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].name}`); + console.info(`Address: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].address}`); + console.info(`SampleRates: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]}`); + console.info(`ChannelCount ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]}`); + console.info(`ChannelMask: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelMasks}`); + } } }); - ``` -### pause8+ +### off('audioRendererChange')9+ -pause(): Promise\ +off(type: "audioRendererChange"): void -Pauses rendering. This API uses a promise to return the result. +Unsubscribes from audio renderer change events. **System capability**: SystemCapability.Multimedia.Audio.Renderer -**Return value** +**Parameters** -| Type | Description | -| -------------- | ---------------------------------- | -| Promise\ | Promise used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | ------- | ---- | ---------------- | +| type | string | Yes | Event type. The event `'audioRendererChange'` is triggered when the audio renderer changes.| + +**Error codes** + +For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). + +| ID| Error Message| +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error | **Example** ```js -audioRenderer.pause().then(() => { - console.info('Renderer paused'); -}).catch((err) => { - console.error(`ERROR: ${err}`); -}); - +audioStreamManager.off('audioRendererChange'); +console.info('######### RendererChange Off is called #########'); ``` -### drain8+ +### on('audioCapturerChange')9+ -drain(callback: AsyncCallback\): void +on(type: "audioCapturerChange", callback: Callback<AudioCapturerChangeInfoArray>): void -Drains the playback buffer. This API uses an asynchronous callback to return the result. +Subscribes to audio capturer change events. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------------------- | --------- | ----------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------------------------------------------------------------------- | +| type | string | Yes | Event type. The event `'audioCapturerChange'` is triggered when the audio capturer changes. | +| callback | Callback<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | Yes | Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). + +| ID| Error Message| +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error | **Example** ```js -audioRenderer.drain((err) => { - if (err) { - console.error('Renderer drain failed'); - } else { - console.info('Renderer drained.'); +audioStreamManager.on('audioCapturerChange', (AudioCapturerChangeInfoArray) => { + for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { + console.info(`## CapChange on is called for element ${i} ##`); + console.info(`StreamId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`); + console.info(`ClientUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`); + console.info(`Source for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`); + console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`); + console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`); + let devDescriptor = AudioCapturerChangeInfoArray[i].deviceDescriptors; + for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { + console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`); + console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`); + console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); + console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`); + console.info(`Address: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`); + console.info(`SampleRates: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); + console.info(`ChannelCounts ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); + console.info(`ChannelMask: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); + } } }); - ``` -### drain8+ +### off('audioCapturerChange')9+ -drain(): Promise\ +off(type: "audioCapturerChange"): void; -Drains the playback buffer. This API uses a promise to return the result. +Unsubscribes from audio capturer change events. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Capturer -**Return value** +**Parameters** -| Type | Description | -| -------------- | ---------------------------------- | -| Promise\ | Promise used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | -------- | --- | ------------------------------------------------------------- | +| type | string |Yes | Event type. The event `'audioCapturerChange'` is triggered when the audio capturer changes.| + +**Error codes** + +For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). + +| ID| Error Message| +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error | **Example** ```js -audioRenderer.drain().then(() => { - console.info('Renderer drained successfully'); -}).catch((err) => { - console.error(`ERROR: ${err}`); -}); +audioStreamManager.off('audioCapturerChange'); +console.info('######### CapturerChange Off is called #########'); ``` -### stop8+ +### isActive9+ -stop(callback: AsyncCallback\): void +isActive(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void -Stops rendering. This API uses an asynchronous callback to return the result. +Checks whether a stream is active. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------------------- | --------- | ----------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------------------------------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream types. | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the active status of the stream. The value **true** means that the stream is active, and **false** means the opposite.| **Example** ```js -audioRenderer.stop((err) => { +audioStreamManager.isActive(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { - console.error('Renderer stop failed'); - } else { - console.info('Renderer stopped.'); + console.error(`Failed to obtain the active status of the stream. ${err}`); + return; } + console.info(`Callback invoked to indicate that the active status of the stream is obtained ${value}.`); }); - ``` -### stop8+ +### isActive9+ -stop(): Promise\ +isActive(volumeType: AudioVolumeType): Promise<boolean> -Stops rendering. This API uses a promise to return the result. +Checks whether a stream is active. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Audio.Renderer +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream types.| + **Return value** -| Type | Description | -| -------------- | ---------------------------------- | -| Promise\ | Promise used to return the result. | +| Type | Description | +| ---------------------- | -------------------------------------------------------- | +| Promise<boolean> | Promise used to return the active status of the stream. The value **true** means that the stream is active, and **false** means the opposite.| **Example** ```js -audioRenderer.stop().then(() => { - console.info('Renderer stopped successfully'); -}).catch((err) => { - console.error(`ERROR: ${err}`); +audioStreamManager.isActive(audio.AudioVolumeType.MEDIA).then((value) => { + console.info(`Promise returned to indicate that the active status of the stream is obtained ${value}.`); }); - ``` -### release8+ +## AudioRoutingManager9+ -release(callback: AsyncCallback\): void +Implements audio routing management. Before calling any API in **AudioRoutingManager**, you must use [getRoutingManager](#getroutingmanager9) to obtain an **AudioRoutingManager** instance. -Releases the renderer. This API uses an asynchronous callback to return the result. +### getDevices9+ -**System capability**: SystemCapability.Multimedia.Audio.Renderer +getDevices(deviceFlag: DeviceFlag, callback: AsyncCallback<AudioDeviceDescriptors>): void + +Obtains the audio devices with a specific flag. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------------------- | --------- | ----------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | -------------------- | +| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag. | +| callback | AsyncCallback<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Yes | Callback used to return the device list.| **Example** ```js -audioRenderer.release((err) => { +audioRoutingManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (err, value) => { if (err) { - console.error('Renderer release failed'); - } else { - console.info('Renderer released.'); + console.error(`Failed to obtain the device list. ${err}`); + return; } + console.info('Callback invoked to indicate that the device list is obtained.'); }); - ``` -### release8+ +### getDevices9+ -release(): Promise\ +getDevices(deviceFlag: DeviceFlag): Promise<AudioDeviceDescriptors> -Releases the renderer. This API uses a promise to return the result. +Obtains the audio devices with a specific flag. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Device + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------- | ---- | ---------------- | +| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag.| **Return value** -| Type | Description | -| -------------- | ---------------------------------- | -| Promise\ | Promise used to return the result. | +| Type | Description | +| ------------------------------------------------------------ | ------------------------- | +| Promise<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Promise used to return the device list.| **Example** ```js -audioRenderer.release().then(() => { - console.info('Renderer released successfully'); -}).catch((err) => { - console.error(`ERROR: ${err}`); +audioRoutingManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data) => { + console.info('Promise returned to indicate that the device list is obtained.'); }); - ``` -### write8+ +### on9+ -write(buffer: ArrayBuffer, callback: AsyncCallback\): void +on(type: 'deviceChange', deviceFlag: DeviceFlag, callback: Callback): void -Writes the buffer. This API uses an asynchronous callback to return the result. +Subscribes to device change events. When a device is connected or disconnected, registered clients will receive the callback. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------- | --------- | ------------------------------------------------------------ | -| buffer | ArrayBuffer | Yes | Buffer to be written. | -| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, the number of bytes written is returned; otherwise, an error code is returned. | +| Name | Type | Mandatory| Description | +| :------- | :--------------------------------------------------- | :--- | :----------------------------------------- | +| type | string | Yes | Event type. The value **'deviceChange'** means the device change event, which is triggered when a device connection status change is detected.| +| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag. | +| callback | Callback<[DeviceChangeAction](#devicechangeaction)\> | Yes | Callback used to return the device update details. | + +**Error codes** + +For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). + +| ID| Error Message| +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error | **Example** ```js -let bufferSize; -audioRenderer.getBufferSize().then((data)=> { - console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`); - bufferSize = data; - }).catch((err) => { - console.error(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`); - }); -console.info(`Buffer size: ${bufferSize}`); -let context = featureAbility.getContext(); -let path; -async function getCacheDir(){ - path = await context.getCacheDir(); -} -let filePath = path + '/StarWars10s-2C-48000-4SW.wav'; -let ss = fileio.createStreamSync(filePath, 'r'); -let buf = new ArrayBuffer(bufferSize); -ss.readSync(buf); -audioRenderer.write(buf, (err, writtenbytes) => { - if (writtenbytes < 0) { - console.error('write failed.'); - } else { - console.info(`Actual written bytes: ${writtenbytes}`); - } +audioRoutingManager.on('deviceChange', audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (deviceChanged) => { + console.info('device change type : ' + deviceChanged.type); + console.info('device descriptor size : ' + deviceChanged.deviceDescriptors.length); + console.info('device change descriptor : ' + deviceChanged.deviceDescriptors[0].deviceRole); + console.info('device change descriptor : ' + deviceChanged.deviceDescriptors[0].deviceType); }); - ``` -### write8+ +### off9+ -write(buffer: ArrayBuffer): Promise\ +off(type: 'deviceChange', callback?: Callback): void -Writes the buffer. This API uses a promise to return the result. +Unsubscribes from device change events. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Device -**Return value** +**Parameters** -| Type | Description | -| ---------------- | ------------------------------------------------------------ | -| Promise\ | Promise used to return the result. If the operation is successful, the number of bytes written is returned; otherwise, an error code is returned. | +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------- | ---- | ------------------------------------------ | +| type | string | Yes | Event type. The value **'deviceChange'** means the device change event, which is triggered when a device connection status change is detected.| +| callback | Callback<[DeviceChangeAction](#devicechangeaction)> | No | Callback used to return the device update details. | + +**Error codes** + +For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). + +| ID| Error Message| +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error | **Example** ```js -let bufferSize; -audioRenderer.getBufferSize().then((data) => { - console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`); - bufferSize = data; - }).catch((err) => { - console.info(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`); - }); -console.info(`BufferSize: ${bufferSize}`); -let context = featureAbility.getContext(); -let path; -async function getCacheDir(){ - path = await context.getCacheDir(); -} -let filePath = path + '/StarWars10s-2C-48000-4SW.wav'; -let ss = fileio.createStreamSync(filePath, 'r'); -let buf = new ArrayBuffer(bufferSize); -ss.readSync(buf); -audioRenderer.write(buf).then((writtenbytes) => { - if (writtenbytes < 0) { - console.error('write failed.'); - } else { - console.info(`Actual written bytes: ${writtenbytes}`); - } -}).catch((err) => { - console.error(`ERROR: ${err}`); +audioRoutingManager.off('deviceChange', (deviceChanged) => { + console.info('Should be no callback.'); }); - ``` -### getAudioTime8+ +### selectInputDevice9+ -getAudioTime(callback: AsyncCallback\): void +selectInputDevice(inputAudioDevices: AudioDeviceDescriptors, callback: AsyncCallback<void>): void -Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). This API uses an asynchronous callback to return the result. +Selects an audio input device. Only one input device can be selected. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------- | --------- | -------------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the timestamp. | +| Name | Type | Mandatory| Description | +| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | +| inputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Input device. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** - ```js -audioRenderer.getAudioTime((err, timestamp) => { - console.info(`Current timestamp: ${timestamp}`); -}); +let inputAudioDeviceDescriptor = [{ + deviceRole : audio.DeviceRole.INPUT_DEVICE, + deviceType : audio.DeviceType.EARPIECE, + id : 1, + name : "", + address : "", + sampleRates : [44100], + channelCounts : [2], + channelMasks : [0], + networkId : audio.LOCAL_NETWORK_ID, + interruptGroupId : 1, + volumeGroupId : 1, +}]; +async function selectInputDevice(){ + audioRoutingManager.selectInputDevice(inputAudioDeviceDescriptor, (err) => { + if (err) { + console.error(`Result ERROR: ${err}`); + } else { + console.info('Select input devices result callback: SUCCESS'); } + }); +} ``` -### getAudioTime8+ +### selectInputDevice9+ -getAudioTime(): Promise\ +selectInputDevice(inputAudioDevices: AudioDeviceDescriptors): Promise<void> -Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). This API uses a promise to return the result. +**System API**: This is a system API. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +Selects an audio input device. Only one input device can be selected. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Device + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | +| inputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Input device. | **Return value** -| Type | Description | -| ---------------- | ------------------------------------- | -| Promise\ | Promise used to return the timestamp. | +| Type | Description | +| --------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| **Example** ```js -audioRenderer.getAudioTime().then((timestamp) => { - console.info(`Current timestamp: ${timestamp}`); -}).catch((err) => { - console.error(`ERROR: ${err}`); -}); +let inputAudioDeviceDescriptor = [{ + deviceRole : audio.DeviceRole.INPUT_DEVICE, + deviceType : audio.DeviceType.EARPIECE, + id : 1, + name : "", + address : "", + sampleRates : [44100], + channelCounts : [2], + channelMasks : [0], + networkId : audio.LOCAL_NETWORK_ID, + interruptGroupId : 1, + volumeGroupId : 1, +}]; +async function getRoutingManager(){ + audioRoutingManager.selectInputDevice(inputAudioDeviceDescriptor).then(() => { + console.info('Select input devices result promise: SUCCESS'); + }).catch((err) => { + console.error(`Result ERROR: ${err}`); + }); +} ``` -### getBufferSize8+ +### setCommunicationDevice9+ -getBufferSize(callback: AsyncCallback\): void +setCommunicationDevice(deviceType: CommunicationDeviceType, active: boolean, callback: AsyncCallback<void>): void -Obtains a reasonable minimum buffer size in bytes for rendering. This API uses an asynchronous callback to return the result. +Sets a communication device to the active state. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Communication **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------- | --------- | ---------------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the buffer size. | +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------- | ---- | ------------------------ | +| deviceType | [CommunicationDeviceType](#communicationdevicetype9) | Yes | Communication device type. | +| active | boolean | Yes | Active state to set. The value **true** means to set the device to the active state, and **false** means the opposite. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** ```js -let bufferSize = audioRenderer.getBufferSize(async(err, bufferSize) => { +audioRoutingManager.setCommunicationDevice(audio.CommunicationDeviceType.SPEAKER, true, (err) => { if (err) { - console.error('getBufferSize error'); + console.error(`Failed to set the active status of the device. ${err}`); + return; } + console.info('Callback invoked to indicate that the device is set to the active status.'); }); - ``` -### getBufferSize8+ +### setCommunicationDevice9+ -getBufferSize(): Promise\ +setCommunicationDevice(deviceType: CommunicationDeviceType, active: boolean): Promise<void> -Obtains a reasonable minimum buffer size in bytes for rendering. This API uses a promise to return the result. +Sets a communication device to the active state. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Communication + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------------------------- | ---- | ------------------ | +| deviceType | [CommunicationDeviceType](#communicationdevicetype9) | Yes | Communication device type.| +| active | boolean | Yes | Active state to set. The value **true** means to set the device to the active state, and **false** means the opposite. | **Return value** -| Type | Description | -| ---------------- | --------------------------------------- | -| Promise\ | Promise used to return the buffer size. | +| Type | Description | +| ------------------- | ------------------------------- | +| Promise<void> | Promise used to return the result.| **Example** ```js -let bufferSize; -audioRenderer.getBufferSize().then((data) => { - console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`); - bufferSize = data; -}).catch((err) => { - console.error(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`); +audioRoutingManager.setCommunicationDevice(audio.CommunicationDeviceType.SPEAKER, true).then(() => { + console.info('Promise returned to indicate that the device is set to the active status.'); }); - ``` -### setRenderRate8+ +### isCommunicationDeviceActive9+ -setRenderRate(rate: AudioRendererRate, callback: AsyncCallback\): void +isCommunicationDeviceActive(deviceType: CommunicationDeviceType, callback: AsyncCallback<boolean>): void -Sets the render rate. This API uses an asynchronous callback to return the result. +Checks whether a communication device is active. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Communication **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | --------- | ----------------------------------- | -| rate | [AudioRendererRate](#audiorendererrate8) | Yes | Audio render rate. | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| ---------- | ---------------------------------------------------- | ---- | ------------------------ | +| deviceType | [CommunicationDeviceType](#communicationdevicetype9) | Yes | Communication device type. | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the active state of the device.| **Example** ```js -audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL, (err) => { +audioRoutingManager.isCommunicationDeviceActive(audio.CommunicationDeviceType.SPEAKER, (err, value) => { if (err) { - console.error('Failed to set params'); - } else { - console.info('Callback invoked to indicate a successful render rate setting.'); + console.error(`Failed to obtain the active status of the device. ${err}`); + return; } + console.info('Callback invoked to indicate that the active status of the device is obtained.'); }); - ``` -### setRenderRate8+ +### isCommunicationDeviceActive9+ -setRenderRate(rate: AudioRendererRate): Promise\ +isCommunicationDeviceActive(deviceType: CommunicationDeviceType): Promise<boolean> -Sets the render rate. This API uses a promise to return the result. +Checks whether a communication device is active. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Communication **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ---------------------------------------- | --------- | ------------------ | -| rate | [AudioRendererRate](#audiorendererrate8) | Yes | Audio render rate. | +| Name | Type | Mandatory| Description | +| ---------- | ---------------------------------------------------- | ---- | ------------------ | +| deviceType | [CommunicationDeviceType](#communicationdevicetype9) | Yes | Communication device type.| **Return value** -| Type | Description | -| -------------- | ---------------------------------- | -| Promise\ | Promise used to return the result. | +| Type | Description | +| ---------------------- | ------------------------------- | +| Promise<boolean> | Promise used to return the active state of the device.| **Example** ```js -audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL).then(() => { - console.info('setRenderRate SUCCESS'); -}).catch((err) => { - console.error(`ERROR: ${err}`); +audioRoutingManager.isCommunicationDeviceActive(audio.CommunicationDeviceType.SPEAKER).then((value) => { + console.info(`Promise returned to indicate that the active status of the device is obtained ${value}.`); }); - ``` -### getRenderRate8+ +### selectOutputDevice9+ -getRenderRate(callback: AsyncCallback\): void +selectOutputDevice(outputAudioDevices: AudioDeviceDescriptors, callback: AsyncCallback<void>): void -Obtains the current render rate. This API uses an asynchronous callback to return the result. +Selects an audio output device. Currently, only one output device can be selected. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------------------------------------- | --------- | ---------------------------------------------- | -| callback | AsyncCallback<[AudioRendererRate](#audiorendererrate8)> | Yes | Callback used to return the audio render rate. | +| Name | Type | Mandatory| Description | +| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | +| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Output device. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** - ```js -audioRenderer.getRenderRate((err, renderrate) => { - console.info(`getRenderRate: ${renderrate}`); -}); +let outputAudioDeviceDescriptor = [{ + deviceRole : audio.DeviceRole.OUTPUT_DEVICE, + deviceType : audio.DeviceType.SPEAKER, + id : 1, + name : "", + address : "", + sampleRates : [44100], + channelCounts : [2], + channelMasks : [0], + networkId : audio.LOCAL_NETWORK_ID, + interruptGroupId : 1, + volumeGroupId : 1, +}]; +async function selectOutputDevice(){ + audioRoutingManager.selectOutputDevice(outputAudioDeviceDescriptor, (err) => { + if (err) { + console.error(`Result ERROR: ${err}`); + } else { + console.info('Select output devices result callback: SUCCESS'); } + }); +} ``` -### getRenderRate8+ - -getRenderRate(): Promise\ - -Obtains the current render rate. This API uses a promise to return the result. - -**System capability**: SystemCapability.Multimedia.Audio.Renderer - -**Return value** - -| Type | Description | -| ------------------------------------------------- | --------------------------------------------- | -| Promise<[AudioRendererRate](#audiorendererrate8)> | Promise used to return the audio render rate. | - -**Example** - -```js -audioRenderer.getRenderRate().then((renderRate) => { - console.info(`getRenderRate: ${renderRate}`); -}).catch((err) => { - console.error(`ERROR: ${err}`); -}); - -``` +### selectOutputDevice9+ -### setInterruptMode9+ +selectOutputDevice(outputAudioDevices: AudioDeviceDescriptors): Promise<void> -setInterruptMode(mode: InterruptMode): Promise<void> +**System API**: This is a system API. -Sets the audio interruption mode for the application. This API uses a promise to return the result. +Selects an audio output device. Currently, only one output device can be selected. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Interrupt +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name | Type | Mandatory | Description | -| ---- | -------------------------------- | --------- | ------------------------ | -| mode | [InterruptMode](#interruptmode9) | Yes | Audio interruption mode. | +| Name | Type | Mandatory| Description | +| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | +| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Output device. | **Return value** -| Type | Description | -| ------------------- | ------------------------------------------------------------ | -| Promise<void> | Promise used to return the result. If the operation is successful, **undefined** is returned. Otherwise, **error** is returned. | +| Type | Description | +| --------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| **Example** ```js -let mode = 0; -audioRenderer.setInterruptMode(mode).then(data=>{ - console.info('setInterruptMode Success!'); -}).catch((err) => { - console.error(`setInterruptMode Fail: ${err}`); -}); +let outputAudioDeviceDescriptor = [{ + deviceRole : audio.DeviceRole.OUTPUT_DEVICE, + deviceType : audio.DeviceType.SPEAKER, + id : 1, + name : "", + address : "", + sampleRates : [44100], + channelCounts : [2], + channelMasks : [0], + networkId : audio.LOCAL_NETWORK_ID, + interruptGroupId : 1, + volumeGroupId : 1, +}]; +async function selectOutputDevice(){ + audioRoutingManager.selectOutputDevice(outputAudioDeviceDescriptor).then(() => { + console.info('Select output devices result promise: SUCCESS'); + }).catch((err) => { + console.error(`Result ERROR: ${err}`); + }); +} ``` -### setInterruptMode9+ +### selectOutputDeviceByFilter9+ -setInterruptMode(mode: InterruptMode, callback: AsyncCallback\): void +selectOutputDeviceByFilter(filter: AudioRendererFilter, outputAudioDevices: AudioDeviceDescriptors, callback: AsyncCallback<void>): void -Sets the audio interruption mode for the application. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. -**System capability**: SystemCapability.Multimedia.Audio.Interrupt +Selects an audio output device based on the filter criteria. Currently, only one output device can be selected. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------------------------------- | --------- | ----------------------------------- | -| mode | [InterruptMode](#interruptmode9) | Yes | Audio interruption mode. | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | +| filter | [AudioRendererFilter](#audiorendererfilter9) | Yes | Filter criteria. | +| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Output device. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** - ```js -let mode = 1; -audioRenderer.setInterruptMode(mode, (err, data)=>{ - if(err){ - console.error(`setInterruptMode Fail: ${err}`); - } - console.info('setInterruptMode Success!'); -}); +let outputAudioRendererFilter = { + uid : 20010041, + rendererInfo : { + content : audio.ContentType.CONTENT_TYPE_MUSIC, + usage : audio.StreamUsage.STREAM_USAGE_MEDIA, + rendererFlags : 0 }, + rendererId : 0 }; + +let outputAudioDeviceDescriptor = [{ + deviceRole : audio.DeviceRole.OUTPUT_DEVICE, + deviceType : audio.DeviceType.SPEAKER, + id : 1, + name : "", + address : "", + sampleRates : [44100], + channelCounts : [2], + channelMasks : [0], + networkId : audio.LOCAL_NETWORK_ID, + interruptGroupId : 1, + volumeGroupId : 1, +}]; +async function selectOutputDeviceByFilter(){ + audioRoutingManager.selectOutputDeviceByFilter(outputAudioRendererFilter, outputAudioDeviceDescriptor, (err) => { + if (err) { + console.error(`Result ERROR: ${err}`); + } else { + console.info('Select output devices by filter result callback: SUCCESS'); } + }); +} ``` -### setVolume9+ +### selectOutputDeviceByFilter9+ -setVolume(volume: number): Promise<void> +selectOutputDeviceByFilter(filter: AudioRendererFilter, outputAudioDevices: AudioDeviceDescriptors): Promise<void> -Sets the volume for the application. This API uses a promise to return the result. +**System API**: This is a system API. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +Selects an audio output device based on the filter criteria. Currently, only one output device can be selected. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ------ | --------- | -------------- | -| volume | number | Yes | Volume to set. | +| Name | Type | Mandatory| Description | +| ----------------------| ------------------------------------------------------------ | ---- | ------------------------- | +| filter | [AudioRendererFilter](#audiorendererfilter9) | Yes | Filter criteria. | +| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Output device. | **Return value** -| Type | Description | -| ------------------- | ------------------------------------------------------------ | -| Promise<void> | Promise used to return the result. If the operation is successful, **undefined** is returned. Otherwise, **error** is returned. | +| Type | Description | +| --------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| **Example** ```js -audioRenderer.setVolume(10).then(data=>{ - console.info('setVolume Success!'); -}).catch((err) => { - console.error(`setVolume Fail: ${err}`); -}); +let outputAudioRendererFilter = { + uid : 20010041, + rendererInfo : { + content : audio.ContentType.CONTENT_TYPE_MUSIC, + usage : audio.StreamUsage.STREAM_USAGE_MEDIA, + rendererFlags : 0 }, + rendererId : 0 }; -``` +let outputAudioDeviceDescriptor = [{ + deviceRole : audio.DeviceRole.OUTPUT_DEVICE, + deviceType : audio.DeviceType.SPEAKER, + id : 1, + name : "", + address : "", + sampleRates : [44100], + channelCounts : [2], + channelMasks : [0], + networkId : audio.LOCAL_NETWORK_ID, + interruptGroupId : 1, + volumeGroupId : 1, +}]; -### setVolume9+ +async function selectOutputDeviceByFilter(){ + audioRoutingManager.selectOutputDeviceByFilter(outputAudioRendererFilter, outputAudioDeviceDescriptor).then(() => { + console.info('Select output devices by filter result promise: SUCCESS'); + }).catch((err) => { + console.error(`Result ERROR: ${err}`); + }) +} +``` -setVolume(volume: number, callback: AsyncCallback\): void +## AudioRendererChangeInfoArray9+ -Sets the volume for the application. This API uses an asynchronous callback to return the result. +Defines an **AudioRenderChangeInfo** array, which is read-only. **System capability**: SystemCapability.Multimedia.Audio.Renderer -**Parameters** +## AudioRendererChangeInfo9+ -| Name | Type | Mandatory | Description | -| -------- | -------------------- | --------- | ----------------------------------- | -| volume | number | Yes | Volume to set. | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +Describes the audio renderer change event. + +**System capability**: SystemCapability.Multimedia.Audio.Renderer + +| Name | Type | Readable | Writable | Description | +| ------------- | ---------------------------------------- | -------- | -------- | ---------------------------------------------------------- | +| streamId | number | Yes | No | Unique ID of an audio stream. | +| clientUid | number | Yes | No | UID of the audio renderer client.
This is a system API. | +| rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | Yes | No | Audio renderer information. | +| rendererState | [AudioState](#audiostate) | Yes | No | Audio state.
This is a system API. | **Example** ```js -audioRenderer.setVolume(10, (err, data)=>{ - if(err){ - console.error(`setVolume Fail: ${err}`); +import audio from '@ohos.multimedia.audio'; + +const audioManager = audio.getAudioManager(); +let audioStreamManager = audioManager.getStreamManager(); +let resultFlag = false; + +audioStreamManager.on('audioRendererChange', (AudioRendererChangeInfoArray) => { + for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { + console.info(`## RendererChange on is called for ${i} ##`); + console.info(`StreamId for ${i} is: ${AudioRendererChangeInfoArray[i].streamId}`); + console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfoArray[i].clientUid}`); + console.info(`Content for ${i} is: ${AudioRendererChangeInfoArray[i].rendererInfo.content}`); + console.info(`Stream for ${i} is: ${AudioRendererChangeInfoArray[i].rendererInfo.usage}`); + console.info(`Flag ${i} is: ${AudioRendererChangeInfoArray[i].rendererInfo.rendererFlags}`); + console.info(`State for ${i} is: ${AudioRendererChangeInfoArray[i].rendererState}`); + let devDescriptor = AudioRendererChangeInfoArray[i].deviceDescriptors; + for (let j = 0; j < AudioRendererChangeInfoArray[i].deviceDescriptors.length; j++) { + console.info(`Id: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].id}`); + console.info(`Type: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].deviceType}`); + console.info(`Role: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); + console.info(`Name: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].name}`); + console.info(`Addr: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].address}`); + console.info(`SR: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); + console.info(`C ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); + console.info(`CM: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); + } + if (AudioRendererChangeInfoArray[i].rendererState == 1 && devDescriptor != null) { + resultFlag = true; + console.info(`ResultFlag for ${i} is: ${resultFlag}`); + } } - console.info('setVolume Success!'); }); - ``` -### on('audioInterrupt')9+ - -on(type: 'audioInterrupt', callback: Callback\): void - -Subscribes to audio interruption events. This API uses a callback to get interrupt events. -Same as [on('interrupt')](#oninterruptdeprecated), this API has obtained the focus before **start**, **pause**, or **stop** of **AudioRenderer** is called. Therefore, you do not need to request the focus. +## AudioCapturerChangeInfoArray9+ -**System capability**: SystemCapability.Multimedia.Audio.Interrupt +Defines an **AudioCapturerChangeInfo** array, which is read-only. -**Parameters** +**System capability**: SystemCapability.Multimedia.Audio.Capturer -| Name | Type | Mandatory | Description | -| -------- | -------------------------------------------- | --------- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value **'audioInterrupt'** means the audio interruption event, which is triggered when audio playback is interrupted. | -| callback | Callback<[InterruptEvent](#interruptevent9)> | Yes | Callback used to return the audio interruption event. | +## AudioCapturerChangeInfo9+ -**Error codes** +Describes the audio capturer change event. -For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). +**System capability**: SystemCapability.Multimedia.Audio.Capturer -| ID | Error Message | -| ------- | ------------------------------- | -| 6800101 | if input parameter value error. | +| Name | Type | Readable | Writable | Description | +| ------------- | ---------------------------------------- | -------- | -------- | ---------------------------------------------------------- | +| streamId | number | Yes | No | Unique ID of an audio stream. | +| clientUid | number | Yes | No | UID of the audio capturer client.
This is a system API. | +| capturerInfo | [AudioCapturerInfo](#audiocapturerinfo8) | Yes | No | Audio capturer information. | +| capturerState | [AudioState](#audiostate) | Yes | No | Audio state.
This is a system API. | **Example** ```js -let isPlay; -let started; -audioRenderer.on('audioInterrupt', async(interruptEvent) => { - if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) { - switch (interruptEvent.hintType) { - case audio.InterruptHint.INTERRUPT_HINT_PAUSE: - console.info('Force paused. Stop writing'); - isPlay = false; - break; - case audio.InterruptHint.INTERRUPT_HINT_STOP: - console.info('Force stopped. Stop writing'); - isPlay = false; - break; +import audio from '@ohos.multimedia.audio'; + +const audioManager = audio.getAudioManager(); +let audioStreamManager = audioManager.getStreamManager(); + +let resultFlag = false; +audioStreamManager.on('audioCapturerChange', (AudioCapturerChangeInfoArray) => { + for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { + console.info(`## CapChange on is called for element ${i} ##`); + console.info(`StrId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`); + console.info(`CUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`); + console.info(`Src for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`); + console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`); + console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`); + let devDescriptor = AudioCapturerChangeInfoArray[i].deviceDescriptors; + for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { + console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`); + console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`); + console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); + console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`); + console.info(`Addr: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`); + console.info(`SR: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); + console.info(`C ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); + console.info(`CM ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); } - } else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) { - switch (interruptEvent.hintType) { - case audio.InterruptHint.INTERRUPT_HINT_RESUME: - console.info('Resume force paused renderer or ignore'); - await audioRenderer.start().then(async function () { - console.info('AudioInterruptMusic: renderInstant started :SUCCESS '); - started = true; - }).catch((err) => { - console.error(`AudioInterruptMusic: renderInstant start :ERROR : ${err}`); - started = false; - }); - if (started) { - isPlay = true; - console.info(`AudioInterruptMusic Renderer started : isPlay : ${isPlay}`); - } else { - console.error('AudioInterruptMusic Renderer start failed'); - } - break; - case audio.InterruptHint.INTERRUPT_HINT_PAUSE: - console.info('Choose to pause or ignore'); - if (isPlay == true) { - isPlay == false; - console.info('AudioInterruptMusic: Media PAUSE : TRUE'); - } else { - isPlay = true; - console.info('AudioInterruptMusic: Media PLAY : TRUE'); - } - break; + if (AudioCapturerChangeInfoArray[i].capturerState == 1 && devDescriptor != null) { + resultFlag = true; + console.info(`ResultFlag for element ${i} is: ${resultFlag}`); } } }); - ``` -### on('markReach')8+ +## AudioDeviceDescriptors -on(type: "markReach", frame: number, callback: Callback<number>): void +Defines an [AudioDeviceDescriptor](#audiodevicedescriptor) array, which is read-only. -Subscribes to mark reached events. When the number of frames rendered reaches the value of the **frame** parameter, a callback is invoked. +## AudioDeviceDescriptor -**System capability**: SystemCapability.Multimedia.Audio.Renderer +Describes an audio device. -**Parameters** +**System capability**: SystemCapability.Multimedia.Audio.Device -| Name | Type | Mandatory | Description | -| :------- | :---------------- | :-------- | :----------------------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'markReach'**. | -| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | -| callback | Callback\ | Yes | Callback invoked when the event is triggered. | +| Name | Type | Readable | Writable | Description | +| ----------------------------- | ------------------------- | -------- | -------- | ------------------------------------------------------------ | +| deviceRole | [DeviceRole](#devicerole) | Yes | No | Device role. | +| deviceType | [DeviceType](#devicetype) | Yes | No | Device type. | +| id9+ | number | Yes | No | Device ID. | +| name9+ | string | Yes | No | Device name. | +| address9+ | string | Yes | No | Device address. | +| sampleRates9+ | Array<number> | Yes | No | Supported sampling rates. | +| channelCounts9+ | Array<number> | Yes | No | Number of channels supported. | +| channelMasks9+ | Array<number> | Yes | No | Supported channel masks. | +| networkId9+ | string | Yes | No | ID of the device network.
This is a system API. | +| interruptGroupId9+ | number | Yes | No | ID of the interruption group to which the device belongs.
This is a system API. | +| volumeGroupId9+ | number | Yes | No | ID of the volume group to which the device belongs.
This is a system API. | **Example** ```js -audioRenderer.on('markReach', 1000, (position) => { - if (position == 1000) { - console.info('ON Triggered successfully'); +import audio from '@ohos.multimedia.audio'; + +function displayDeviceProp(value) { + deviceRoleValue = value.deviceRole; + deviceTypeValue = value.deviceType; +} + +let deviceRoleValue = null; +let deviceTypeValue = null; +const promise = audio.getAudioManager().getDevices(1); +promise.then(function (value) { + console.info('AudioFrameworkTest: Promise: getDevices OUTPUT_DEVICES_FLAG'); + value.forEach(displayDeviceProp); + if (deviceTypeValue != null && deviceRoleValue != null){ + console.info('AudioFrameworkTest: Promise: getDevices : OUTPUT_DEVICES_FLAG : PASS'); + } else { + console.error('AudioFrameworkTest: Promise: getDevices : OUTPUT_DEVICES_FLAG : FAIL'); } }); - ``` +## AudioRendererFilter9+ -### off('markReach') 8+ +Implements filter criteria. Before calling **selectOutputDeviceByFilter**, you must obtain an **AudioRendererFilter** instance. -off(type: 'markReach'): void +**System API**: This is a system API. -Unsubscribes from mark reached events. +| Name | Type | Mandatory | Description | +| ------------ | ---------------------------------------- | --------- | ------------------------------------------------------------ | +| uid | number | Yes | Application ID.
**System capability**: SystemCapability.Multimedia.Audio.Core | +| rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | No | Audio renderer information.
**System capability**: SystemCapability.Multimedia.Audio.Renderer | +| rendererId | number | No | Unique ID of an audio stream.
**System capability**: SystemCapability.Multimedia.Audio.Renderer | -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**Example** -**Parameters** +```js +let outputAudioRendererFilter = { + "uid":20010041, + "rendererInfo": { + "contentType":audio.ContentType.CONTENT_TYPE_MUSIC, + "streamUsage":audio.StreamUsage.STREAM_USAGE_MEDIA, + "rendererFlags":0 }, + "rendererId":0 }; +``` -| Name | Type | Mandatory | Description | -| :--- | :----- | :-------- | :------------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'markReach'**. | +## AudioRenderer8+ + +Provides APIs for audio rendering. Before calling any API in **AudioRenderer**, you must use [createAudioRenderer](#audiocreateaudiorenderer8) to create an **AudioRenderer** instance. + +### Attributes + +**System capability**: SystemCapability.Multimedia.Audio.Renderer + +| Name | Type | Readable | Writable | Description | +| ------------------ | -------------------------- | -------- | -------- | --------------------- | +| state8+ | [AudioState](#audiostate8) | Yes | No | Audio renderer state. | **Example** ```js -audioRenderer.off('markReach'); - +let state = audioRenderer.state; ``` -### on('periodReach') 8+ +### getRendererInfo8+ -on(type: "periodReach", frame: number, callback: Callback<number>): void +getRendererInfo(callback: AsyncCallback): void -Subscribes to period reached events. When the number of frames rendered reaches the value of the **frame** parameter, a callback is triggered and the specified value is returned. +Obtains the renderer information of this **AudioRenderer** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :---------------- | :-------- | :----------------------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'periodReach'**. | -| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | -| callback | Callback\ | Yes | Callback invoked when the event is triggered. | +| Name | Type | Mandatory | Description | +| :------- | :------------------------------------------------------- | :-------- | :------------------------------------------------ | +| callback | AsyncCallback<[AudioRendererInfo](#audiorendererinfo8)\> | Yes | Callback used to return the renderer information. | **Example** ```js -audioRenderer.on('periodReach', 1000, (position) => { - if (position == 1000) { - console.info('ON Triggered successfully'); - } +audioRenderer.getRendererInfo((err, rendererInfo) => { + console.info('Renderer GetRendererInfo:'); + console.info(`Renderer content: ${rendererInfo.content}`); + console.info(`Renderer usage: ${rendererInfo.usage}`); + console.info(`Renderer flags: ${rendererInfo.rendererFlags}`); }); - ``` -### off('periodReach') 8+ +### getRendererInfo8+ -off(type: 'periodReach'): void +getRendererInfo(): Promise -Unsubscribes from period reached events. +Obtains the renderer information of this **AudioRenderer** instance. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Audio.Renderer -**Parameters** +**Return value** -| Name | Type | Mandatory | Description | -| :--- | :----- | :-------- | :--------------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'periodReach'**. | +| Type | Description | +| -------------------------------------------------- | ------------------------------------------------ | +| Promise<[AudioRendererInfo](#audiorendererinfo8)\> | Promise used to return the renderer information. | **Example** ```js -audioRenderer.off('periodReach') - +audioRenderer.getRendererInfo().then((rendererInfo) => { + console.info('Renderer GetRendererInfo:'); + console.info(`Renderer content: ${rendererInfo.content}`); + console.info(`Renderer usage: ${rendererInfo.usage}`); + console.info(`Renderer flags: ${rendererInfo.rendererFlags}`) +}).catch((err) => { + console.error(`AudioFrameworkRenderLog: RendererInfo :ERROR: ${err}`); +}); ``` -### on('stateChange')8+ +### getStreamInfo8+ -on(type: 'stateChange', callback: Callback): void +getStreamInfo(callback: AsyncCallback): void -Subscribes to state change events. +Obtains the stream information of this **AudioRenderer** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :------------------------- | :-------- | :----------------------------------------------------------- | -| type | string | Yes | Event type. The value **stateChange** means the state change event. | -| callback | [AudioState](#audiostate8) | Yes | Callback used to return the state change. | +| Name | Type | Mandatory | Description | +| :------- | :--------------------------------------------------- | :-------- | :---------------------------------------------- | +| callback | AsyncCallback<[AudioStreamInfo](#audiostreaminfo8)\> | Yes | Callback used to return the stream information. | **Example** ```js -audioRenderer.on('stateChange', (state) => { - if (state == 1) { - console.info('audio renderer state is: STATE_PREPARED'); - } - if (state == 2) { - console.info('audio renderer state is: STATE_RUNNING'); - } +audioRenderer.getStreamInfo((err, streamInfo) => { + console.info('Renderer GetStreamInfo:'); + console.info(`Renderer sampling rate: ${streamInfo.samplingRate}`); + console.info(`Renderer channel: ${streamInfo.channels}`); + console.info(`Renderer format: ${streamInfo.sampleFormat}`); + console.info(`Renderer encoding type: ${streamInfo.encodingType}`); }); - ``` -## AudioCapturer8+ +### getStreamInfo8+ -Provides APIs for audio capture. Before calling any API in **AudioCapturer**, you must use [createAudioCapturer](#audiocreateaudiocapturer8) to create an **AudioCapturer** instance. +getStreamInfo(): Promise -### Attributes +Obtains the stream information of this **AudioRenderer** instance. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer -| Name | Type | Readable | Writable | Description | -| :----------------- | :------------------------- | :------- | :------- | :-------------------- | -| state8+ | [AudioState](#audiostate8) | Yes | No | Audio capturer state. | +**Return value** + +| Type | Description | +| :--------------------------------------------- | :--------------------------------------------- | +| Promise<[AudioStreamInfo](#audiostreaminfo8)\> | Promise used to return the stream information. | **Example** ```js -let state = audioCapturer.state; +audioRenderer.getStreamInfo().then((streamInfo) => { + console.info('Renderer GetStreamInfo:'); + console.info(`Renderer sampling rate: ${streamInfo.samplingRate}`); + console.info(`Renderer channel: ${streamInfo.channels}`); + console.info(`Renderer format: ${streamInfo.sampleFormat}`); + console.info(`Renderer encoding type: ${streamInfo.encodingType}`); +}).catch((err) => { + console.error(`ERROR: ${err}`); +}); ``` -### getCapturerInfo8+ +### getAudioStreamId9+ -getCapturerInfo(callback: AsyncCallback): void +getAudioStreamId(callback: AsyncCallback): void -Obtains the capturer information of this **AudioCapturer** instance. This API uses an asynchronous callback to return the result. +Obtains the stream ID of this **AudioRenderer** instance. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :-------------------------------- | :-------- | :------------------------------------------------ | -| callback | AsyncCallback | Yes | Callback used to return the capturer information. | +| Name | Type | Mandatory | Description | +| :------- | :--------------------- | :-------- | :------------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the stream ID. | **Example** ```js -audioCapturer.getCapturerInfo((err, capturerInfo) => { - if (err) { - console.error('Failed to get capture info'); - } else { - console.info('Capturer getCapturerInfo:'); - console.info(`Capturer source: ${capturerInfo.source}`); - console.info(`Capturer flags: ${capturerInfo.capturerFlags}`); - } +audioRenderer.getAudioStreamId((err, streamid) => { + console.info(`Renderer GetStreamId: ${streamid}`); }); ``` +### getAudioStreamId9+ -### getCapturerInfo8+ - -getCapturerInfo(): Promise +getAudioStreamId(): Promise -Obtains the capturer information of this **AudioCapturer** instance. This API uses a promise to return the result. +Obtains the stream ID of this **AudioRenderer** instance. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Return value** -| Type | Description | -| :------------------------------------------------ | :----------------------------------------------- | -| Promise<[AudioCapturerInfo](#audiocapturerinfo)\> | Promise used to return the capturer information. | +| Type | Description | +| :--------------- | :------------------------------------ | +| Promise | Promise used to return the stream ID. | **Example** ```js -audioCapturer.getCapturerInfo().then((audioParamsGet) => { - if (audioParamsGet != undefined) { - console.info('AudioFrameworkRecLog: Capturer CapturerInfo:'); - console.info(`AudioFrameworkRecLog: Capturer SourceType: ${audioParamsGet.source}`); - console.info(`AudioFrameworkRecLog: Capturer capturerFlags: ${audioParamsGet.capturerFlags}`); - } else { - console.info(`AudioFrameworkRecLog: audioParamsGet is : ${audioParamsGet}`); - console.info('AudioFrameworkRecLog: audioParams getCapturerInfo are incorrect'); - } +audioRenderer.getAudioStreamId().then((streamid) => { + console.info(`Renderer getAudioStreamId: ${streamid}`); }).catch((err) => { - console.error(`AudioFrameworkRecLog: CapturerInfo :ERROR: ${err}`); + console.error(`ERROR: ${err}`); }); ``` -### getStreamInfo8+ +### start8+ -getStreamInfo(callback: AsyncCallback): void +start(callback: AsyncCallback): void -Obtains the stream information of this **AudioCapturer** instance. This API uses an asynchronous callback to return the result. +Starts the renderer. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :--------------------------------------------------- | :-------- | :---------------------------------------------- | -| callback | AsyncCallback<[AudioStreamInfo](#audiostreaminfo8)\> | Yes | Callback used to return the stream information. | +| Name | Type | Mandatory | Description | +| -------- | -------------------- | --------- | ----------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** ```js -audioCapturer.getStreamInfo((err, streamInfo) => { +audioRenderer.start((err) => { if (err) { - console.error('Failed to get stream info'); + console.error('Renderer start failed.'); } else { - console.info('Capturer GetStreamInfo:'); - console.info(`Capturer sampling rate: ${streamInfo.samplingRate}`); - console.info(`Capturer channel: ${streamInfo.channels}`); - console.info(`Capturer format: ${streamInfo.sampleFormat}`); - console.info(`Capturer encoding type: ${streamInfo.encodingType}`); + console.info('Renderer start success.'); } }); ``` -### getStreamInfo8+ +### start8+ -getStreamInfo(): Promise +start(): Promise -Obtains the stream information of this **AudioCapturer** instance. This API uses a promise to return the result. +Starts the renderer. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Return value** -| Type | Description | -| :--------------------------------------------- | :--------------------------------------------- | -| Promise<[AudioStreamInfo](#audiostreaminfo8)\> | Promise used to return the stream information. | +| Type | Description | +| -------------- | ---------------------------------- | +| Promise\ | Promise used to return the result. | **Example** ```js -audioCapturer.getStreamInfo().then((audioParamsGet) => { - console.info('getStreamInfo:'); - console.info(`sampleFormat: ${audioParamsGet.sampleFormat}`); - console.info(`samplingRate: ${audioParamsGet.samplingRate}`); - console.info(`channels: ${audioParamsGet.channels}`); - console.info(`encodingType: ${audioParamsGet.encodingType}`); +audioRenderer.start().then(() => { + console.info('Renderer started'); }).catch((err) => { - console.error(`getStreamInfo :ERROR: ${err}`); + console.error(`ERROR: ${err}`); }); ``` -### getAudioStreamId9+ +### pause8+ -getAudioStreamId(callback: AsyncCallback): void +pause(callback: AsyncCallback\): void -Obtains the stream ID of this **AudioCapturer** instance. This API uses an asynchronous callback to return the result. +Pauses rendering. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :--------------------- | :-------- | :------------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the stream ID. | +| Name | Type | Mandatory | Description | +| -------- | -------------------- | --------- | ----------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** ```js -audioCapturer.getAudioStreamId((err, streamid) => { - console.info(`audioCapturer GetStreamId: ${streamid}`); +audioRenderer.pause((err) => { + if (err) { + console.error('Renderer pause failed'); + } else { + console.info('Renderer paused.'); + } }); ``` -### getAudioStreamId9+ +### pause8+ -getAudioStreamId(): Promise +pause(): Promise\ -Obtains the stream ID of this **AudioCapturer** instance. This API uses a promise to return the result. +Pauses rendering. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Return value** -| Type | Description | -| :--------------- | :------------------------------------ | -| Promise | Promise used to return the stream ID. | +| Type | Description | +| -------------- | ---------------------------------- | +| Promise\ | Promise used to return the result. | **Example** ```js -audioCapturer.getAudioStreamId().then((streamid) => { - console.info(`audioCapturer getAudioStreamId: ${streamid}`); +audioRenderer.pause().then(() => { + console.info('Renderer paused'); }).catch((err) => { console.error(`ERROR: ${err}`); }); ``` -### start8+ +### drain8+ -start(callback: AsyncCallback): void +drain(callback: AsyncCallback\): void -Starts capturing. This API uses an asynchronous callback to return the result. +Drains the playback buffer. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** | Name | Type | Mandatory | Description | -| :------- | :------------------- | :-------- | :---------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result. | +| -------- | -------------------- | --------- | ----------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** ```js -audioCapturer.start((err) => { +audioRenderer.drain((err) => { if (err) { - console.error('Capturer start failed.'); + console.error('Renderer drain failed'); } else { - console.info('Capturer start success.'); + console.info('Renderer drained.'); } }); ``` +### drain8+ -### start8+ - -start(): Promise +drain(): Promise\ -Starts capturing. This API uses a promise to return the result. +Drains the playback buffer. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Return value** | Type | Description | -| :------------- | :--------------------------------- | -| Promise | Promise used to return the result. | +| -------------- | ---------------------------------- | +| Promise\ | Promise used to return the result. | **Example** ```js -audioCapturer.start().then(() => { - console.info('AudioFrameworkRecLog: ---------START---------'); - console.info('AudioFrameworkRecLog: Capturer started: SUCCESS'); - console.info(`AudioFrameworkRecLog: AudioCapturer: STATE: ${audioCapturer.state}`); - console.info('AudioFrameworkRecLog: Capturer started: SUCCESS'); - if ((audioCapturer.state == audio.AudioState.STATE_RUNNING)) { - console.info('AudioFrameworkRecLog: AudioCapturer is in Running State'); - } +audioRenderer.drain().then(() => { + console.info('Renderer drained successfully'); }).catch((err) => { - console.info(`AudioFrameworkRecLog: Capturer start :ERROR : ${err}`); + console.error(`ERROR: ${err}`); }); ``` ### stop8+ -stop(callback: AsyncCallback): void +stop(callback: AsyncCallback\): void -Stops capturing. This API uses an asynchronous callback to return the result. +Stops rendering. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** | Name | Type | Mandatory | Description | -| :------- | :------------------- | :-------- | :---------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result. | +| -------- | -------------------- | --------- | ----------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** ```js -audioCapturer.stop((err) => { +audioRenderer.stop((err) => { if (err) { - console.error('Capturer stop failed'); + console.error('Renderer stop failed'); } else { - console.info('Capturer stopped.'); + console.info('Renderer stopped.'); } }); ``` - ### stop8+ -stop(): Promise +stop(): Promise\ -Stops capturing. This API uses a promise to return the result. +Stops rendering. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Return value** | Type | Description | -| :------------- | :--------------------------------- | -| Promise | Promise used to return the result. | +| -------------- | ---------------------------------- | +| Promise\ | Promise used to return the result. | **Example** ```js -audioCapturer.stop().then(() => { - console.info('AudioFrameworkRecLog: ---------STOP RECORD---------'); - console.info('AudioFrameworkRecLog: Capturer stopped: SUCCESS'); - if ((audioCapturer.state == audio.AudioState.STATE_STOPPED)){ - console.info('AudioFrameworkRecLog: State is Stopped:'); - } +audioRenderer.stop().then(() => { + console.info('Renderer stopped successfully'); }).catch((err) => { - console.info(`AudioFrameworkRecLog: Capturer stop: ERROR: ${err}`); + console.error(`ERROR: ${err}`); }); ``` ### release8+ -release(callback: AsyncCallback): void +release(callback: AsyncCallback\): void -Releases this **AudioCapturer** instance. This API uses an asynchronous callback to return the result. +Releases the renderer. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** | Name | Type | Mandatory | Description | -| :------- | :------------------- | :-------- | :---------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result. | +| -------- | -------------------- | --------- | ----------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** ```js -audioCapturer.release((err) => { +audioRenderer.release((err) => { if (err) { - console.error('capturer release failed'); + console.error('Renderer release failed'); } else { - console.info('capturer released.'); + console.info('Renderer released.'); } }); ``` - ### release8+ -release(): Promise +release(): Promise\ -Releases this **AudioCapturer** instance. This API uses a promise to return the result. +Releases the renderer. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Return value** | Type | Description | -| :------------- | :--------------------------------- | -| Promise | Promise used to return the result. | +| -------------- | ---------------------------------- | +| Promise\ | Promise used to return the result. | **Example** ```js -let stateFlag; -audioCapturer.release().then(() => { - console.info('AudioFrameworkRecLog: ---------RELEASE RECORD---------'); - console.info('AudioFrameworkRecLog: Capturer release : SUCCESS'); - console.info(`AudioFrameworkRecLog: AudioCapturer : STATE : ${audioCapturer.state}`); - console.info(`AudioFrameworkRecLog: stateFlag : ${stateFlag}`); +audioRenderer.release().then(() => { + console.info('Renderer released successfully'); }).catch((err) => { - console.info(`AudioFrameworkRecLog: Capturer stop: ERROR: ${err}`); + console.error(`ERROR: ${err}`); }); ``` -### read8+ +### write8+ -read(size: number, isBlockingRead: boolean, callback: AsyncCallback): void +write(buffer: ArrayBuffer, callback: AsyncCallback\): void -Reads the buffer. This API uses an asynchronous callback to return the result. +Writes the buffer. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| :------------- | :-------------------------- | :-------- | :----------------------------------- | -| size | number | Yes | Number of bytes to read. | -| isBlockingRead | boolean | Yes | Whether to block the read operation. | -| callback | AsyncCallback | Yes | Callback used to return the buffer. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | --------- | ------------------------------------------------------------ | +| buffer | ArrayBuffer | Yes | Buffer to be written. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, the number of bytes written is returned; otherwise, an error code is returned. | **Example** ```js let bufferSize; -audioCapturer.getBufferSize().then((data) => { - console.info(`AudioFrameworkRecLog: getBufferSize: SUCCESS ${data}`); +audioRenderer.getBufferSize().then((data)=> { + console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`); bufferSize = data; }).catch((err) => { - console.error(`AudioFrameworkRecLog: getBufferSize: ERROR: ${err}`); + console.error(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`); }); -audioCapturer.read(bufferSize, true, async(err, buffer) => { - if (!err) { - console.info('Success in reading the buffer data'); +console.info(`Buffer size: ${bufferSize}`); +let context = featureAbility.getContext(); +let path; +async function getCacheDir(){ + path = await context.getCacheDir(); +} +let filePath = path + '/StarWars10s-2C-48000-4SW.wav'; +let ss = fileio.createStreamSync(filePath, 'r'); +let buf = new ArrayBuffer(bufferSize); +ss.readSync(buf); +audioRenderer.write(buf, (err, writtenbytes) => { + if (writtenbytes < 0) { + console.error('write failed.'); + } else { + console.info(`Actual written bytes: ${writtenbytes}`); } }); ``` -### read8+ - -read(size: number, isBlockingRead: boolean): Promise - -Reads the buffer. This API uses a promise to return the result. +### write8+ -**System capability**: SystemCapability.Multimedia.Audio.Capturer +write(buffer: ArrayBuffer): Promise\ -**Parameters** +Writes the buffer. This API uses a promise to return the result. -| Name | Type | Mandatory | Description | -| :------------- | :------ | :-------- | :----------------------------------- | -| size | number | Yes | Number of bytes to read. | -| isBlockingRead | boolean | Yes | Whether to block the read operation. | +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Return value** -| Type | Description | -| :-------------------- | :----------------------------------------------------------- | -| Promise | Promise used to return the result. If the operation is successful, the buffer data read is returned; otherwise, an error code is returned. | +| Type | Description | +| ---------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the result. If the operation is successful, the number of bytes written is returned; otherwise, an error code is returned. | **Example** ```js let bufferSize; -audioCapturer.getBufferSize().then((data) => { - console.info(`AudioFrameworkRecLog: getBufferSize: SUCCESS ${data}`); +audioRenderer.getBufferSize().then((data) => { + console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`); bufferSize = data; }).catch((err) => { - console.info(`AudioFrameworkRecLog: getBufferSize: ERROR ${err}`); + console.info(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`); }); -console.info(`Buffer size: ${bufferSize}`); -audioCapturer.read(bufferSize, true).then((buffer) => { - console.info('buffer read successfully'); +console.info(`BufferSize: ${bufferSize}`); +let context = featureAbility.getContext(); +let path; +async function getCacheDir(){ + path = await context.getCacheDir(); +} +let filePath = path + '/StarWars10s-2C-48000-4SW.wav'; +let ss = fileio.createStreamSync(filePath, 'r'); +let buf = new ArrayBuffer(bufferSize); +ss.readSync(buf); +audioRenderer.write(buf).then((writtenbytes) => { + if (writtenbytes < 0) { + console.error('write failed.'); + } else { + console.info(`Actual written bytes: ${writtenbytes}`); + } }).catch((err) => { - console.info(`ERROR : ${err}`); + console.error(`ERROR: ${err}`); }); ``` ### getAudioTime8+ -getAudioTime(callback: AsyncCallback): void +getAudioTime(callback: AsyncCallback\): void Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :--------------------- | :-------- | :---------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | --------- | -------------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the timestamp. | **Example** ```js -audioCapturer.getAudioTime((err, timestamp) => { +audioRenderer.getAudioTime((err, timestamp) => { console.info(`Current timestamp: ${timestamp}`); }); @@ -4475,54 +4665,49 @@ audioCapturer.getAudioTime((err, timestamp) => { ### getAudioTime8+ -getAudioTime(): Promise +getAudioTime(): Promise\ Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Return value** | Type | Description | -| :--------------- | :------------------------------------ | -| Promise | Promise used to return the timestamp. | +| ---------------- | ------------------------------------- | +| Promise\ | Promise used to return the timestamp. | **Example** ```js -audioCapturer.getAudioTime().then((audioTime) => { - console.info(`AudioFrameworkRecLog: AudioCapturer getAudioTime : Success ${audioTime}`); +audioRenderer.getAudioTime().then((timestamp) => { + console.info(`Current timestamp: ${timestamp}`); }).catch((err) => { - console.info(`AudioFrameworkRecLog: AudioCapturer Created : ERROR : ${err}`); + console.error(`ERROR: ${err}`); }); ``` ### getBufferSize8+ -getBufferSize(callback: AsyncCallback): void +getBufferSize(callback: AsyncCallback\): void -Obtains a reasonable minimum buffer size in bytes for capturing. This API uses an asynchronous callback to return the result. +Obtains a reasonable minimum buffer size in bytes for rendering. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** | Name | Type | Mandatory | Description | -| :------- | :--------------------- | :-------- | :--------------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the buffer size. | +| -------- | ---------------------- | --------- | ---------------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the buffer size. | **Example** ```js -audioCapturer.getBufferSize((err, bufferSize) => { - if (!err) { - console.info(`BufferSize : ${bufferSize}`); - audioCapturer.read(bufferSize, true).then((buffer) => { - console.info(`Buffer read is ${buffer}`); - }).catch((err) => { - console.error(`AudioFrameworkRecLog: AudioCapturer Created : ERROR : ${err}`); - }); +let bufferSize = audioRenderer.getBufferSize(async(err, bufferSize) => { + if (err) { + console.error('getBufferSize error'); } }); @@ -4530,1546 +4715,1425 @@ audioCapturer.getBufferSize((err, bufferSize) => { ### getBufferSize8+ -getBufferSize(): Promise +getBufferSize(): Promise\ -Obtains a reasonable minimum buffer size in bytes for capturing. This API uses a promise to return the result. +Obtains a reasonable minimum buffer size in bytes for rendering. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Return value** | Type | Description | -| :--------------- | :-------------------------------------- | -| Promise | Promise used to return the buffer size. | +| ---------------- | --------------------------------------- | +| Promise\ | Promise used to return the buffer size. | **Example** ```js let bufferSize; -audioCapturer.getBufferSize().then((data) => { - console.info(`AudioFrameworkRecLog: getBufferSize :SUCCESS ${data}`); +audioRenderer.getBufferSize().then((data) => { + console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`); bufferSize = data; }).catch((err) => { - console.info(`AudioFrameworkRecLog: getBufferSize :ERROR : ${err}`); + console.error(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`); }); ``` -### on('markReach')8+ +### setRenderRate8+ -on(type: "markReach", frame: number, callback: Callback<number>): void +setRenderRate(rate: AudioRendererRate, callback: AsyncCallback\): void -Subscribes to mark reached events. When the number of frames captured reaches the value of the **frame** parameter, a callback is invoked. +Sets the render rate. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :---------------- | :-------- | :----------------------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'markReach'**. | -| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | -| callback | Callback\ | Yes | Callback invoked when the event is triggered. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | --------- | ----------------------------------- | +| rate | [AudioRendererRate](#audiorendererrate8) | Yes | Audio render rate. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** ```js -audioCapturer.on('markReach', 1000, (position) => { - if (position == 1000) { - console.info('ON Triggered successfully'); +audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL, (err) => { + if (err) { + console.error('Failed to set params'); + } else { + console.info('Callback invoked to indicate a successful render rate setting.'); } }); ``` -### off('markReach')8+ - -off(type: 'markReach'): void - -Unsubscribes from mark reached events. - -**System capability**: SystemCapability.Multimedia.Audio.Capturer - -**Parameters** - -| Name | Type | Mandatory | Description | -| :--- | :----- | :-------- | :------------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'markReach'**. | - -**Example** - -```js -audioCapturer.off('markReach'); - -``` - -### on('periodReach')8+ +### setRenderRate8+ -on(type: "periodReach", frame: number, callback: Callback<number>): void +setRenderRate(rate: AudioRendererRate): Promise\ -Subscribes to period reached events. When the number of frames captured reaches the value of the **frame** parameter, a callback is triggered and the specified value is returned. +Sets the render rate. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :---------------- | :-------- | :----------------------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'periodReach'**. | -| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | -| callback | Callback\ | Yes | Callback invoked when the event is triggered. | +| Name | Type | Mandatory | Description | +| ---- | ---------------------------------------- | --------- | ------------------ | +| rate | [AudioRendererRate](#audiorendererrate8) | Yes | Audio render rate. | + +**Return value** + +| Type | Description | +| -------------- | ---------------------------------- | +| Promise\ | Promise used to return the result. | **Example** ```js -audioCapturer.on('periodReach', 1000, (position) => { - if (position == 1000) { - console.info('ON Triggered successfully'); - } +audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL).then(() => { + console.info('setRenderRate SUCCESS'); +}).catch((err) => { + console.error(`ERROR: ${err}`); }); ``` -### off('periodReach')8+ +### getRenderRate8+ -off(type: 'periodReach'): void +getRenderRate(callback: AsyncCallback\): void -Unsubscribes from period reached events. +Obtains the current render rate. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| :--- | :----- | :-------- | :--------------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'periodReach'**. | +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ---------------------------------------------- | +| callback | AsyncCallback<[AudioRendererRate](#audiorendererrate8)> | Yes | Callback used to return the audio render rate. | **Example** ```js -audioCapturer.off('periodReach') +audioRenderer.getRenderRate((err, renderrate) => { + console.info(`getRenderRate: ${renderrate}`); +}); ``` -### on('stateChange')8+ +### getRenderRate8+ -on(type: 'stateChange', callback: Callback): void +getRenderRate(): Promise\ -Subscribes to state change events. +Obtains the current render rate. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer -**Parameters** +**Return value** -| Name | Type | Mandatory | Description | -| :------- | :------------------------- | :-------- | :----------------------------------------------------------- | -| type | string | Yes | Event type. The value **stateChange** means the state change event. | -| callback | [AudioState](#audiostate8) | Yes | Callback used to return the state change. | +| Type | Description | +| ------------------------------------------------- | --------------------------------------------- | +| Promise<[AudioRendererRate](#audiorendererrate8)> | Promise used to return the audio render rate. | **Example** ```js -audioCapturer.on('stateChange', (state) => { - if (state == 1) { - console.info('audio capturer state is: STATE_PREPARED'); - } - if (state == 2) { - console.info('audio capturer state is: STATE_RUNNING'); - } +audioRenderer.getRenderRate().then((renderRate) => { + console.info(`getRenderRate: ${renderRate}`); +}).catch((err) => { + console.error(`ERROR: ${err}`); }); ``` -## ToneType9+ +### setInterruptMode9+ -Enumerates the tone types of the player. +setInterruptMode(mode: InterruptMode): Promise<void> -**System API**: This is a system API. +Sets the audio interruption mode for the application. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Tone +**System capability**: SystemCapability.Multimedia.Audio.Interrupt -| Name | Default Value | Description | -| :----------------------------------------------- | :------------ | :-------------------------------------------- | -| TONE_TYPE_DIAL_0 | 0 | DTMF tone of key 0. | -| TONE_TYPE_DIAL_1 | 1 | DTMF tone of key 1. | -| TONE_TYPE_DIAL_2 | 2 | DTMF tone of key 2. | -| TONE_TYPE_DIAL_3 | 3 | DTMF tone of key 3. | -| TONE_TYPE_DIAL_4 | 4 | DTMF tone of key 4. | -| TONE_TYPE_DIAL_5 | 5 | DTMF tone of key 5. | -| TONE_TYPE_DIAL_6 | 6 | DTMF tone of key 6. | -| TONE_TYPE_DIAL_7 | 7 | DTMF tone of key 7. | -| TONE_TYPE_DIAL_8 | 8 | DTMF tone of key 8. | -| TONE_TYPE_DIAL_9 | 9 | DTMF tone of key 9. | -| TONE_TYPE_DIAL_S | 10 | DTMF tone of the star key (*). | -| TONE_TYPE_DIAL_P | 11 | DTMF tone of the pound key (#). | -| TONE_TYPE_DIAL_A | 12 | DTMF tone of key A. | -| TONE_TYPE_DIAL_B | 13 | DTMF tone of key B. | -| TONE_TYPE_DIAL_C | 14 | DTMF tone of key C. | -| TONE_TYPE_DIAL_D | 15 | DTMF tone of key D. | -| TONE_TYPE_COMMON_SUPERVISORY_DIAL | 100 | Supervisory tone - dial tone. | -| TONE_TYPE_COMMON_SUPERVISORY_BUSY | 101 | Supervisory tone - busy. | -| TONE_TYPE_COMMON_SUPERVISORY_CONGESTION | 102 | Supervisory tone - congestion. | -| TONE_TYPE_COMMON_SUPERVISORY_RADIO_ACK | 103 | Supervisory tone - radio path acknowledgment. | -| TONE_TYPE_COMMON_SUPERVISORY_RADIO_NOT_AVAILABLE | 104 | Supervisory tone - radio path not available. | -| TONE_TYPE_COMMON_SUPERVISORY_CALL_WAITING | 106 | Supervisory tone - call waiting tone. | -| TONE_TYPE_COMMON_SUPERVISORY_RINGTONE | 107 | Supervisory tone - ringing tone. | -| TONE_TYPE_COMMON_PROPRIETARY_BEEP | 200 | Proprietary tone - beep tone. | -| TONE_TYPE_COMMON_PROPRIETARY_ACK | 201 | Proprietary tone - ACK. | -| TONE_TYPE_COMMON_PROPRIETARY_PROMPT | 203 | Proprietary tone - PROMPT. | -| TONE_TYPE_COMMON_PROPRIETARY_DOUBLE_BEEP | 204 | Proprietary tone - double beep tone. | +**Parameters** -## TonePlayer9+ +| Name | Type | Mandatory | Description | +| ---- | -------------------------------- | --------- | ------------------------ | +| mode | [InterruptMode](#interruptmode9) | Yes | Audio interruption mode. | -Provides APIs for playing and managing DTMF tones, such as dial tones, ringback tones, supervisory tones, and proprietary tones. +**Return value** -**System API**: This is a system API. +| Type | Description | +| ------------------- | ------------------------------------------------------------ | +| Promise<void> | Promise used to return the result. If the operation is successful, **undefined** is returned. Otherwise, **error** is returned. | -### load9+ +**Example** -load(type: ToneType, callback: AsyncCallback<void>): void +```js +let mode = 0; +audioRenderer.setInterruptMode(mode).then(data=>{ + console.info('setInterruptMode Success!'); +}).catch((err) => { + console.error(`setInterruptMode Fail: ${err}`); +}); -Loads the DTMF tone configuration. This API uses an asynchronous callback to return the result. +``` -**System capability**: SystemCapability.Multimedia.Audio.Tone +### setInterruptMode9+ + +setInterruptMode(mode: InterruptMode, callback: AsyncCallback\): void + +Sets the audio interruption mode for the application. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Interrupt **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :--------------------- | :-------- | :---------------------------------- | -| type | [ToneType](#tonetype9) | Yes | Tone type. | -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | -------------------------------- | --------- | ----------------------------------- | +| mode | [InterruptMode](#interruptmode9) | Yes | Audio interruption mode. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** ```js -tonePlayer.load(audio.ToneType.TONE_TYPE_DIAL_5, (err) => { - if (err) { - console.error(`callback call load failed error: ${err.message}`); - return; - } else { - console.info('callback call load success'); +let mode = 1; +audioRenderer.setInterruptMode(mode, (err, data)=>{ + if(err){ + console.error(`setInterruptMode Fail: ${err}`); } + console.info('setInterruptMode Success!'); }); ``` -### load9+ +### setVolume9+ -load(type: ToneType): Promise<void> +setVolume(volume: number): Promise<void> -Loads the DTMF tone configuration. This API uses a promise to return the result. +Sets the volume for the application. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Tone +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| :--- | :--------------------- | :-------- | ----------- | -| type | [ToneType](#tonetype9) | Yes | Tone type. | +| Name | Type | Mandatory | Description | +| ------ | ------ | --------- | ------------------------------------------------------------ | +| volume | number | Yes | Volume to set, which can be within the range from 0.0 to 1.0. | **Return value** -| Type | Description | -| :------------- | :--------------------------------- | -| Promise | Promise used to return the result. | +| Type | Description | +| ------------------- | ------------------------------------------------------------ | +| Promise<void> | Promise used to return the result. If the operation is successful, **undefined** is returned. Otherwise, **error** is returned. | **Example** ```js -tonePlayer.load(audio.ToneType.TONE_TYPE_DIAL_1).then(() => { - console.info('promise call load '); -}).catch(() => { - console.error('promise call load fail'); +audioRenderer.setVolume(0.5).then(data=>{ + console.info('setVolume Success!'); +}).catch((err) => { + console.error(`setVolume Fail: ${err}`); }); ``` -### start9+ +### setVolume9+ -start(callback: AsyncCallback<void>): void +setVolume(volume: number, callback: AsyncCallback\): void -Starts DTMF tone playing. This API uses an asynchronous callback to return the result. +Sets the volume for the application. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Tone +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :------------------- | :-------- | :---------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | -------------------- | --------- | ------------------------------------------------------------ | +| volume | number | Yes | Volume to set, which can be within the range from 0.0 to 1.0. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** ```js -tonePlayer.start((err) => { - if (err) { - console.error(`callback call start failed error: ${err.message}`); - return; - } else { - console.info('callback call start success'); +audioRenderer.setVolume(0.5, (err, data)=>{ + if(err){ + console.error(`setVolume Fail: ${err}`); } + console.info('setVolume Success!'); }); ``` -### start9+ +### on('audioInterrupt')9+ -start(): Promise<void> +on(type: 'audioInterrupt', callback: Callback\): void -Starts DTMF tone playing. This API uses a promise to return the result. +Subscribes to audio interruption events. This API uses a callback to get interrupt events. -**System capability**: SystemCapability.Multimedia.Audio.Tone +Same as [on('interrupt')](#oninterruptdeprecated), this API has obtained the focus before **start**, **pause**, or **stop** of **AudioRenderer** is called. Therefore, you do not need to request the focus. -**Return value** +**System capability**: SystemCapability.Multimedia.Audio.Interrupt -| Type | Description | -| :------------- | :--------------------------------- | -| Promise | Promise used to return the result. | +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value **'audioInterrupt'** means the audio interruption event, which is triggered when audio playback is interrupted. | +| callback | Callback<[InterruptEvent](#interruptevent9)> | Yes | Callback used to return the audio interruption event. | + +**Error codes** + +For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 6800101 | if input parameter value error | **Example** ```js -tonePlayer.start().then(() => { - console.info('promise call start'); -}).catch(() => { - console.error('promise call start fail'); -}); +let isPlay; +let started; +onAudioInterrupt(); + +async function onAudioInterrupt(){ + audioRenderer.on('audioInterrupt', async(interruptEvent) => { + if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) { + switch (interruptEvent.hintType) { + case audio.InterruptHint.INTERRUPT_HINT_PAUSE: + console.info('Force paused. Stop writing'); + isPlay = false; + break; + case audio.InterruptHint.INTERRUPT_HINT_STOP: + console.info('Force stopped. Stop writing'); + isPlay = false; + break; + } + } else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) { + switch (interruptEvent.hintType) { + case audio.InterruptHint.INTERRUPT_HINT_RESUME: + console.info('Resume force paused renderer or ignore'); + await audioRenderer.start().then(async function () { + console.info('AudioInterruptMusic: renderInstant started :SUCCESS '); + started = true; + }).catch((err) => { + console.error(`AudioInterruptMusic: renderInstant start :ERROR : ${err}`); + started = false; + }); + if (started) { + isPlay = true; + console.info(`AudioInterruptMusic Renderer started : isPlay : ${isPlay}`); + } else { + console.error('AudioInterruptMusic Renderer start failed'); + } + break; + case audio.InterruptHint.INTERRUPT_HINT_PAUSE: + console.info('Choose to pause or ignore'); + if (isPlay == true) { + isPlay == false; + console.info('AudioInterruptMusic: Media PAUSE : TRUE'); + } else { + isPlay = true; + console.info('AudioInterruptMusic: Media PLAY : TRUE'); + } + break; + } + } + }); +} ``` -### stop9+ +### on('markReach')8+ -stop(callback: AsyncCallback<void>): void +on(type: "markReach", frame: number, callback: Callback<number>): void -Stops the tone that is being played. This API uses an asynchronous callback to return the result. +Subscribes to mark reached events. When the number of frames rendered reaches the value of the **frame** parameter, a callback is invoked. -**System capability**: SystemCapability.Multimedia.Audio.Tone +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :------------------- | :-------- | :---------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| :------- | :---------------- | :-------- | :----------------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'markReach'**. | +| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | +| callback | Callback\ | Yes | Callback invoked when the event is triggered. | **Example** ```js -tonePlayer.stop((err) => { - if (err) { - console.error(`callback call stop error: ${err.message}`); - return; - } else { - console.error('callback call stop success '); +audioRenderer.on('markReach', 1000, (position) => { + if (position == 1000) { + console.info('ON Triggered successfully'); } }); ``` -### stop9+ -stop(): Promise<void> +### off('markReach') 8+ -Stops the tone that is being played. This API uses a promise to return the result. +off(type: 'markReach'): void -**System capability**: SystemCapability.Multimedia.Audio.Tone +Unsubscribes from mark reached events. -**Return value** +**System capability**: SystemCapability.Multimedia.Audio.Renderer -| Type | Description | -| :------------- | :--------------------------------- | -| Promise | Promise used to return the result. | +**Parameters** + +| Name | Type | Mandatory | Description | +| :--- | :----- | :-------- | :------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'markReach'**. | **Example** ```js -tonePlayer.stop().then(() => { - console.info('promise call stop finish'); -}).catch(() => { - console.error('promise call stop fail'); -}); +audioRenderer.off('markReach'); ``` -### release9+ +### on('periodReach') 8+ -release(callback: AsyncCallback<void>): void +on(type: "periodReach", frame: number, callback: Callback<number>): void -Releases the resources associated with the **TonePlayer** instance. This API uses an asynchronous callback to return the result. +Subscribes to period reached events. When the number of frames rendered reaches the value of the **frame** parameter, a callback is triggered and the specified value is returned. -**System capability**: SystemCapability.Multimedia.Audio.Tone +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :------------------- | :-------- | :---------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| :------- | :---------------- | :-------- | :----------------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'periodReach'**. | +| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | +| callback | Callback\ | Yes | Callback invoked when the event is triggered. | **Example** ```js -tonePlayer.release((err) => { - if (err) { - console.error(`callback call release failed error: ${err.message}`); - return; - } else { - console.info('callback call release success '); +audioRenderer.on('periodReach', 1000, (position) => { + if (position == 1000) { + console.info('ON Triggered successfully'); } }); ``` -### release9+ +### off('periodReach') 8+ -release(): Promise<void> +off(type: 'periodReach'): void -Releases the resources associated with the **TonePlayer** instance. This API uses a promise to return the result. +Unsubscribes from period reached events. -**System capability**: SystemCapability.Multimedia.Audio.Tone +**System capability**: SystemCapability.Multimedia.Audio.Renderer -**Return value** +**Parameters** -| Type | Description | -| :------------- | :--------------------------------- | -| Promise | Promise used to return the result. | +| Name | Type | Mandatory | Description | +| :--- | :----- | :-------- | :--------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'periodReach'**. | **Example** ```js -tonePlayer.release().then(() => { - console.info('promise call release'); -}).catch(() => { - console.error('promise call release fail'); -}); +audioRenderer.off('periodReach') ``` -## ActiveDeviceType(deprecated) - -Enumerates the active device types. - -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [CommunicationDeviceType](#communicationdevicetype9) instead. - -**System capability**: SystemCapability.Multimedia.Audio.Device - -| Name | Default Value | Description | -| ------------- | ------------- | ------------------------------------------------------------ | -| SPEAKER | 2 | Speaker. | -| BLUETOOTH_SCO | 7 | Bluetooth device using Synchronous Connection Oriented (SCO) links. | - -## InterruptActionType(deprecated) +### on('stateChange')8+ -Enumerates the returned event types for audio interruption events. +on(type: 'stateChange', callback: Callback): void -> **NOTE** -> This API is supported since API version 7 and deprecated since API version 9. +Subscribes to state change events. **System capability**: SystemCapability.Multimedia.Audio.Renderer -| Name | Default Value | Description | -| -------------- | ------------- | ------------------------- | -| TYPE_ACTIVATED | 0 | Focus gain event. | -| TYPE_INTERRUPT | 1 | Audio interruption event. | - -## AudioInterrupt(deprecated) +**Parameters** -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. +| Name | Type | Mandatory | Description | +| :------- | :------------------------------------ | :-------- | :----------------------------------------------------------- | +| type | string | Yes | Event type. The value **stateChange** means the state change event. | +| callback | Callback\<[AudioState](#audiostate8)> | Yes | Callback used to return the state change. | -Describes input parameters of audio interruption events. +**Example** -**System capability**: SystemCapability.Multimedia.Audio.Renderer +```js +audioRenderer.on('stateChange', (state) => { + if (state == 1) { + console.info('audio renderer state is: STATE_PREPARED'); + } + if (state == 2) { + console.info('audio renderer state is: STATE_RUNNING'); + } +}); -| Name | Type | Mandatory | Description | -| --------------- | --------------------------- | --------- | ------------------------------------------------------------ | -| streamUsage | [StreamUsage](#streamusage) | Yes | Audio stream usage. | -| contentType | [ContentType](#contenttype) | Yes | Audio content type. | -| pauseWhenDucked | boolean | Yes | Whether audio playback can be paused during audio interruption. The value **true** means that audio playback can be paused during audio interruption, and **false** means the opposite. | +``` -## InterruptAction(deprecated) +## AudioCapturer8+ -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. +Provides APIs for audio capture. Before calling any API in **AudioCapturer**, you must use [createAudioCapturer](#audiocreateaudiocapturer8) to create an **AudioCapturer** instance. -Describes the callback invoked for audio interruption or focus gain events. +### Attributes -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Capturer -| Name | Type | Mandatory | Description | -| ---------- | ------------------------------------------- | --------- | ------------------------------------------------------------ | -| actionType | [InterruptActionType](#interruptactiontype) | Yes | Returned event type. The value **TYPE_ACTIVATED** means the focus gain event, and **TYPE_INTERRUPT** means the audio interruption event. | -| type | [InterruptType](#interrupttype) | No | Type of the audio interruption event. | -| hint | [InterruptHint](#interrupthint) | No | Hint provided along with the audio interruption event. | -| activated | boolean | No | Whether the focus is gained or released. The value **true** means that the focus is gained or released, and **false** means that the focus fails to be gained or released. | +| Name | Type | Readable | Writable | Description | +| :----------------- | :------------------------- | :------- | :------- | :-------------------- | +| state8+ | [AudioState](#audiostate8) | Yes | No | Audio capturer state. | -### setVolume(deprecated) +**Example** -setVolume(volumeType: AudioVolumeType, volume: number, callback: AsyncCallback<void>): void +```js +let state = audioCapturer.state; -Sets the volume for a stream. 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 [setVolume](#setvolume9) in **AudioVolumeGroupManager**. +### getCapturerInfo8+ -**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY +getCapturerInfo(callback: AsyncCallback): void -This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. +Obtains the capturer information of this **AudioCapturer** instance. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ------------------------------------------------------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | -| volume | number | Yes | Volume to set. The value range can be obtained by calling **getMinVolume** and **getMaxVolume**. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| :------- | :-------------------------------- | :-------- | :------------------------------------------------ | +| callback | AsyncCallback | Yes | Callback used to return the capturer information. | **Example** ```js -audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10, (err) => { +audioCapturer.getCapturerInfo((err, capturerInfo) => { if (err) { - console.error(`Failed to set the volume. ${err}`); - return; + console.error('Failed to get capture info'); + } else { + console.info('Capturer getCapturerInfo:'); + console.info(`Capturer source: ${capturerInfo.source}`); + console.info(`Capturer flags: ${capturerInfo.capturerFlags}`); } - console.info('Callback invoked to indicate a successful volume setting.'); }); ``` -### setVolume(deprecated) - -setVolume(volumeType: AudioVolumeType, volume: number): Promise<void> - -Sets the volume for a stream. 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 [setVolume](#setvolume9) in **AudioVolumeGroupManager**. - -**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY -This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. +### getCapturerInfo8+ -**System capability**: SystemCapability.Multimedia.Audio.Volume +getCapturerInfo(): Promise -**Parameters** +Obtains the capturer information of this **AudioCapturer** instance. This API uses a promise to return the result. -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ------------------------------------------------------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | -| volume | number | Yes | Volume to set. The value range can be obtained by calling **getMinVolume** and **getMaxVolume**. | +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Return value** -| Type | Description | -| ------------------- | ---------------------------------- | -| Promise<void> | Promise used to return the result. | +| Type | Description | +| :------------------------------------------------ | :----------------------------------------------- | +| Promise<[AudioCapturerInfo](#audiocapturerinfo)\> | Promise used to return the capturer information. | **Example** ```js -audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10).then(() => { - console.info('Promise returned to indicate a successful volume setting.'); +audioCapturer.getCapturerInfo().then((audioParamsGet) => { + if (audioParamsGet != undefined) { + console.info('AudioFrameworkRecLog: Capturer CapturerInfo:'); + console.info(`AudioFrameworkRecLog: Capturer SourceType: ${audioParamsGet.source}`); + console.info(`AudioFrameworkRecLog: Capturer capturerFlags: ${audioParamsGet.capturerFlags}`); + } else { + console.info(`AudioFrameworkRecLog: audioParamsGet is : ${audioParamsGet}`); + console.info('AudioFrameworkRecLog: audioParams getCapturerInfo are incorrect'); + } +}).catch((err) => { + console.error(`AudioFrameworkRecLog: CapturerInfo :ERROR: ${err}`); }); ``` -### getVolume(deprecated) - -getVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void +### getStreamInfo8+ -Obtains the volume of a stream. This API uses an asynchronous callback to return the result. +getStreamInfo(callback: AsyncCallback): void -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getVolume](#getvolume9) in **AudioVolumeGroupManager**. +Obtains the stream information of this **AudioCapturer** instance. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ----------------------------------- | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | -| callback | AsyncCallback<number> | Yes | Callback used to return the volume. | +| Name | Type | Mandatory | Description | +| :------- | :--------------------------------------------------- | :-------- | :---------------------------------------------- | +| callback | AsyncCallback<[AudioStreamInfo](#audiostreaminfo8)\> | Yes | Callback used to return the stream information. | **Example** ```js -audioManager.getVolume(audio.AudioVolumeType.MEDIA, (err, value) => { +audioCapturer.getStreamInfo((err, streamInfo) => { if (err) { - console.error(`Failed to obtain the volume. ${err}`); - return; + console.error('Failed to get stream info'); + } else { + console.info('Capturer GetStreamInfo:'); + console.info(`Capturer sampling rate: ${streamInfo.samplingRate}`); + console.info(`Capturer channel: ${streamInfo.channels}`); + console.info(`Capturer format: ${streamInfo.sampleFormat}`); + console.info(`Capturer encoding type: ${streamInfo.encodingType}`); } - console.info('Callback invoked to indicate that the volume is obtained.'); }); ``` -### getVolume(deprecated) - -getVolume(volumeType: AudioVolumeType): Promise<number> - -Obtains the volume of a stream. 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 [getVolume](#getvolume9) in **AudioVolumeGroupManager**. +### getStreamInfo8+ -**System capability**: SystemCapability.Multimedia.Audio.Volume +getStreamInfo(): Promise -**Parameters** +Obtains the stream information of this **AudioCapturer** instance. This API uses a promise to return the result. -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ------------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Return value** -| Type | Description | -| --------------------- | ---------------------------------- | -| Promise<number> | Promise used to return the volume. | +| Type | Description | +| :--------------------------------------------- | :--------------------------------------------- | +| Promise<[AudioStreamInfo](#audiostreaminfo8)\> | Promise used to return the stream information. | **Example** ```js -audioManager.getVolume(audio.AudioVolumeType.MEDIA).then((value) => { - console.info(`Promise returned to indicate that the volume is obtained ${value} .`); +audioCapturer.getStreamInfo().then((audioParamsGet) => { + console.info('getStreamInfo:'); + console.info(`sampleFormat: ${audioParamsGet.sampleFormat}`); + console.info(`samplingRate: ${audioParamsGet.samplingRate}`); + console.info(`channels: ${audioParamsGet.channels}`); + console.info(`encodingType: ${audioParamsGet.encodingType}`); +}).catch((err) => { + console.error(`getStreamInfo :ERROR: ${err}`); }); ``` -### getMinVolume(deprecated) - -getMinVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void +### getAudioStreamId9+ -Obtains the minimum volume allowed for a stream. This API uses an asynchronous callback to return the result. +getAudioStreamId(callback: AsyncCallback): void -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getMinVolume](#getminvolume9) in **AudioVolumeGroupManager**. +Obtains the stream ID of this **AudioCapturer** instance. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ------------------------------------------- | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | -| callback | AsyncCallback<number> | Yes | Callback used to return the minimum volume. | +| Name | Type | Mandatory | Description | +| :------- | :--------------------- | :-------- | :------------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the stream ID. | **Example** ```js -audioManager.getMinVolume(audio.AudioVolumeType.MEDIA, (err, value) => { - if (err) { - console.error(`Failed to obtain the minimum volume. ${err}`); - return; - } - console.info(`Callback invoked to indicate that the minimum volume is obtained. ${value}`); +audioCapturer.getAudioStreamId((err, streamid) => { + console.info(`audioCapturer GetStreamId: ${streamid}`); }); -``` - -### getMinVolume(deprecated) - -getMinVolume(volumeType: AudioVolumeType): Promise<number> - -Obtains the minimum volume allowed for a stream. 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 [getMinVolume](#getminvolume9) in **AudioVolumeGroupManager**. +``` -**System capability**: SystemCapability.Multimedia.Audio.Volume +### getAudioStreamId9+ -**Parameters** +getAudioStreamId(): Promise + +Obtains the stream ID of this **AudioCapturer** instance. This API uses a promise to return the result. -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ------------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Return value** -| Type | Description | -| --------------------- | ------------------------------------------ | -| Promise<number> | Promise used to return the minimum volume. | +| Type | Description | +| :--------------- | :------------------------------------ | +| Promise | Promise used to return the stream ID. | **Example** ```js -audioManager.getMinVolume(audio.AudioVolumeType.MEDIA).then((value) => { - console.info(`Promised returned to indicate that the minimum volume is obtained. ${value}`); +audioCapturer.getAudioStreamId().then((streamid) => { + console.info(`audioCapturer getAudioStreamId: ${streamid}`); +}).catch((err) => { + console.error(`ERROR: ${err}`); }); ``` -### getMaxVolume(deprecated) - -getMaxVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void +### start8+ -Obtains the maximum volume allowed for a stream. This API uses an asynchronous callback to return the result. +start(callback: AsyncCallback): void -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getMaxVolume](#getmaxvolume9) in **AudioVolumeGroupManager**. +Starts capturing. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ------------------------------------------- | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | -| callback | AsyncCallback<number> | Yes | Callback used to return the maximum volume. | +| Name | Type | Mandatory | Description | +| :------- | :------------------- | :-------- | :---------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA, (err, value) => { +audioCapturer.start((err) => { if (err) { - console.error(`Failed to obtain the maximum volume. ${err}`); - return; + console.error('Capturer start failed.'); + } else { + console.info('Capturer start success.'); } - console.info(`Callback invoked to indicate that the maximum volume is obtained. ${value}`); }); ``` -### getMaxVolume(deprecated) - -getMaxVolume(volumeType: AudioVolumeType): Promise<number> - -Obtains the maximum volume allowed for a stream. 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 [getMaxVolume](#getmaxvolume9) in **AudioVolumeGroupManager**. +### start8+ -**System capability**: SystemCapability.Multimedia.Audio.Volume +start(): Promise -**Parameters** +Starts capturing. This API uses a promise to return the result. -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ------------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Return value** -| Type | Description | -| --------------------- | ------------------------------------------ | -| Promise<number> | Promise used to return the maximum volume. | +| Type | Description | +| :------------- | :--------------------------------- | +| Promise | Promise used to return the result. | **Example** ```js -audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA).then((data) => { - console.info('Promised returned to indicate that the maximum volume is obtained.'); +audioCapturer.start().then(() => { + console.info('AudioFrameworkRecLog: ---------START---------'); + console.info('AudioFrameworkRecLog: Capturer started: SUCCESS'); + console.info(`AudioFrameworkRecLog: AudioCapturer: STATE: ${audioCapturer.state}`); + console.info('AudioFrameworkRecLog: Capturer started: SUCCESS'); + if ((audioCapturer.state == audio.AudioState.STATE_RUNNING)) { + console.info('AudioFrameworkRecLog: AudioCapturer is in Running State'); + } +}).catch((err) => { + console.info(`AudioFrameworkRecLog: Capturer start :ERROR : ${err}`); }); ``` -### mute(deprecated) - -mute(volumeType: AudioVolumeType, mute: boolean, callback: AsyncCallback<void>): void - -Mutes or unmutes a stream. 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 [mute](#mute9) in **AudioVolumeGroupManager**. +### stop8+ -**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY +stop(callback: AsyncCallback): void -This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. +Stops capturing. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ------------------------------------------------------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | -| mute | boolean | Yes | Mute status to set. The value **true** means to mute the stream, and **false** means the opposite. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| :------- | :------------------- | :-------- | :---------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -audioManager.mute(audio.AudioVolumeType.MEDIA, true, (err) => { +audioCapturer.stop((err) => { if (err) { - console.error(`Failed to mute the stream. ${err}`); - return; + console.error('Capturer stop failed'); + } else { + console.info('Capturer stopped.'); } - console.info('Callback invoked to indicate that the stream is muted.'); }); ``` -### mute(deprecated) - -mute(volumeType: AudioVolumeType, mute: boolean): Promise<void> - -Mutes or unmutes a stream. 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 [mute](#mute9) in **AudioVolumeGroupManager**. - -**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY -This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. +### stop8+ -**System capability**: SystemCapability.Multimedia.Audio.Volume +stop(): Promise -**Parameters** +Stops capturing. This API uses a promise to return the result. -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ------------------------------------------------------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | -| mute | boolean | Yes | Mute status to set. The value **true** means to mute the stream, and **false** means the opposite. | +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Return value** -| Type | Description | -| ------------------- | ---------------------------------- | -| Promise<void> | Promise used to return the result. | +| Type | Description | +| :------------- | :--------------------------------- | +| Promise | Promise used to return the result. | **Example** - ```js -audioManager.mute(audio.AudioVolumeType.MEDIA, true).then(() => { - console.info('Promise returned to indicate that the stream is muted.'); +audioCapturer.stop().then(() => { + console.info('AudioFrameworkRecLog: ---------STOP RECORD---------'); + console.info('AudioFrameworkRecLog: Capturer stopped: SUCCESS'); + if ((audioCapturer.state == audio.AudioState.STATE_STOPPED)){ + console.info('AudioFrameworkRecLog: State is Stopped:'); + } +}).catch((err) => { + console.info(`AudioFrameworkRecLog: Capturer stop: ERROR: ${err}`); }); ``` -### isMute(deprecated) - -isMute(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void +### release8+ -Checks whether a stream is muted. This API uses an asynchronous callback to return the result. +release(callback: AsyncCallback): void -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isMute](#ismute9) in **AudioVolumeGroupManager**. +Releases this **AudioCapturer** instance. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ------------------------------------------------------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the mute status of the stream. The value **true** means that the stream is muted, and **false** means the opposite. | +| Name | Type | Mandatory | Description | +| :------- | :------------------- | :-------- | :---------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -audioManager.isMute(audio.AudioVolumeType.MEDIA, (err, value) => { +audioCapturer.release((err) => { if (err) { - console.error(`Failed to obtain the mute status. ${err}`); - return; + console.error('capturer release failed'); + } else { + console.info('capturer released.'); } - console.info(`Callback invoked to indicate that the mute status of the stream is obtained. ${value}`); }); ``` -### isMute(deprecated) - -isMute(volumeType: AudioVolumeType): Promise<boolean> - -Checks whether a stream is muted. 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 [isMute](#ismute9) in **AudioVolumeGroupManager**. +### release8+ -**System capability**: SystemCapability.Multimedia.Audio.Volume +release(): Promise -**Parameters** +Releases this **AudioCapturer** instance. This API uses a promise to return the result. -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ------------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Return value** -| Type | Description | -| ---------------------- | ------------------------------------------------------------ | -| Promise<boolean> | Promise used to return the mute status of the stream. The value **true** means that the stream is muted, and **false** means the opposite. | +| Type | Description | +| :------------- | :--------------------------------- | +| Promise | Promise used to return the result. | **Example** ```js -audioManager.isMute(audio.AudioVolumeType.MEDIA).then((value) => { - console.info(`Promise returned to indicate that the mute status of the stream is obtained ${value}.`); +let stateFlag; +audioCapturer.release().then(() => { + console.info('AudioFrameworkRecLog: ---------RELEASE RECORD---------'); + console.info('AudioFrameworkRecLog: Capturer release : SUCCESS'); + console.info(`AudioFrameworkRecLog: AudioCapturer : STATE : ${audioCapturer.state}`); + console.info(`AudioFrameworkRecLog: stateFlag : ${stateFlag}`); +}).catch((err) => { + console.info(`AudioFrameworkRecLog: Capturer stop: ERROR: ${err}`); }); ``` -### isActive(deprecated) - -isActive(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void +### read8+ -Checks whether a stream is active. This API uses an asynchronous callback to return the result. +read(size: number, isBlockingRead: boolean, callback: AsyncCallback): void -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isActive](#isactive9) in **AudioStreamManager**. +Reads the buffer. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ------------------------------------------------------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the active status of the stream. The value **true** means that the stream is active, and **false** means the opposite. | +| Name | Type | Mandatory | Description | +| :------------- | :-------------------------- | :-------- | :----------------------------------- | +| size | number | Yes | Number of bytes to read. | +| isBlockingRead | boolean | Yes | Whether to block the read operation. | +| callback | AsyncCallback | Yes | Callback used to return the buffer. | **Example** ```js -audioManager.isActive(audio.AudioVolumeType.MEDIA, (err, value) => { - if (err) { - console.error(`Failed to obtain the active status of the stream. ${err}`); - return; +let bufferSize; +audioCapturer.getBufferSize().then((data) => { + console.info(`AudioFrameworkRecLog: getBufferSize: SUCCESS ${data}`); + bufferSize = data; + }).catch((err) => { + console.error(`AudioFrameworkRecLog: getBufferSize: ERROR: ${err}`); + }); +audioCapturer.read(bufferSize, true, async(err, buffer) => { + if (!err) { + console.info('Success in reading the buffer data'); } - console.info(`Callback invoked to indicate that the active status of the stream is obtained ${value}.`); }); ``` -### isActive(deprecated) - -isActive(volumeType: AudioVolumeType): Promise<boolean> +### read8+ -Checks whether a stream is active. This API uses a promise to return the result. +read(size: number, isBlockingRead: boolean): Promise -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isActive](#isactive9) in **AudioStreamManager**. +Reads the buffer. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ------------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| Name | Type | Mandatory | Description | +| :------------- | :------ | :-------- | :----------------------------------- | +| size | number | Yes | Number of bytes to read. | +| isBlockingRead | boolean | Yes | Whether to block the read operation. | **Return value** -| Type | Description | -| ---------------------- | ------------------------------------------------------------ | -| Promise<boolean> | Promise used to return the active status of the stream. The value **true** means that the stream is active, and **false** means the opposite. | +| Type | Description | +| :-------------------- | :----------------------------------------------------------- | +| Promise | Promise used to return the result. If the operation is successful, the buffer data read is returned; otherwise, an error code is returned. | **Example** ```js -audioManager.isActive(audio.AudioVolumeType.MEDIA).then((value) => { - console.info(`Promise returned to indicate that the active status of the stream is obtained ${value}.`); +let bufferSize; +audioCapturer.getBufferSize().then((data) => { + console.info(`AudioFrameworkRecLog: getBufferSize: SUCCESS ${data}`); + bufferSize = data; + }).catch((err) => { + console.info(`AudioFrameworkRecLog: getBufferSize: ERROR ${err}`); + }); +console.info(`Buffer size: ${bufferSize}`); +audioCapturer.read(bufferSize, true).then((buffer) => { + console.info('buffer read successfully'); +}).catch((err) => { + console.info(`ERROR : ${err}`); }); -``` - -### setRingerMode(deprecated) - -setRingerMode(mode: AudioRingMode, callback: AsyncCallback<void>): void - -Sets the ringer mode. 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 [setRingerMode](#setringermode9) in **AudioVolumeGroupManager**. +``` -**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY +### getAudioTime8+ -This permission is required only for muting or unmuting the ringer. +getAudioTime(callback: AsyncCallback): void -**System capability**: SystemCapability.Multimedia.Audio.Communication +Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------------- | --------- | ----------------------------------- | -| mode | [AudioRingMode](#audioringmode) | Yes | Ringer mode. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| :------- | :--------------------- | :-------- | :---------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL, (err) => { - if (err) { - console.error(`Failed to set the ringer mode.​ ${err}`); - return; - } - console.info('Callback invoked to indicate a successful setting of the ringer mode.'); +audioCapturer.getAudioTime((err, timestamp) => { + console.info(`Current timestamp: ${timestamp}`); }); ``` -### setRingerMode(deprecated) - -setRingerMode(mode: AudioRingMode): Promise<void> - -Sets the ringer mode. 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 [setRingerMode](#setringermode9) in **AudioVolumeGroupManager**. - -**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY - -This permission is required only for muting or unmuting the ringer. +### getAudioTime8+ -**System capability**: SystemCapability.Multimedia.Audio.Communication +getAudioTime(): Promise -**Parameters** +Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). This API uses a promise to return the result. -| Name | Type | Mandatory | Description | -| ---- | ------------------------------- | --------- | ------------ | -| mode | [AudioRingMode](#audioringmode) | Yes | Ringer mode. | +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Return value** -| Type | Description | -| ------------------- | ---------------------------------- | -| Promise<void> | Promise used to return the result. | +| Type | Description | +| :--------------- | :------------------------------------ | +| Promise | Promise used to return the timestamp. | **Example** ```js -audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL).then(() => { - console.info('Promise returned to indicate a successful setting of the ringer mode.'); +audioCapturer.getAudioTime().then((audioTime) => { + console.info(`AudioFrameworkRecLog: AudioCapturer getAudioTime : Success ${audioTime}`); +}).catch((err) => { + console.info(`AudioFrameworkRecLog: AudioCapturer Created : ERROR : ${err}`); }); ``` -### getRingerMode(deprecated) - -getRingerMode(callback: AsyncCallback<AudioRingMode>): void +### getBufferSize8+ -Obtains the ringer mode. This API uses an asynchronous callback to return the result. +getBufferSize(callback: AsyncCallback): void -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getRingerMode](#getringermode9) in **AudioVolumeGroupManager**. +Obtains a reasonable minimum buffer size in bytes for capturing. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Communication +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------------------- | --------- | ---------------------------------------- | -| callback | AsyncCallback<[AudioRingMode](#audioringmode)> | Yes | Callback used to return the ringer mode. | +| Name | Type | Mandatory | Description | +| :------- | :--------------------- | :-------- | :--------------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the buffer size. | **Example** ```js -audioManager.getRingerMode((err, value) => { - if (err) { - console.error(`Failed to obtain the ringer mode.​ ${err}`); - return; +audioCapturer.getBufferSize((err, bufferSize) => { + if (!err) { + console.info(`BufferSize : ${bufferSize}`); + audioCapturer.read(bufferSize, true).then((buffer) => { + console.info(`Buffer read is ${buffer}`); + }).catch((err) => { + console.error(`AudioFrameworkRecLog: AudioCapturer Created : ERROR : ${err}`); + }); } - console.info(`Callback invoked to indicate that the ringer mode is obtained ${value}.`); }); ``` -### getRingerMode(deprecated) - -getRingerMode(): Promise<AudioRingMode> +### getBufferSize8+ -Obtains the ringer mode. This API uses a promise to return the result. +getBufferSize(): Promise -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getRingerMode](#getringermode9) in **AudioVolumeGroupManager**. +Obtains a reasonable minimum buffer size in bytes for capturing. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Communication +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Return value** -| Type | Description | -| ---------------------------------------------- | --------------------------------------- | -| Promise<[AudioRingMode](#audioringmode)> | Promise used to return the ringer mode. | +| Type | Description | +| :--------------- | :-------------------------------------- | +| Promise | Promise used to return the buffer size. | **Example** ```js -audioManager.getRingerMode().then((value) => { - console.info(`Promise returned to indicate that the ringer mode is obtained ${value}.`); +let bufferSize; +audioCapturer.getBufferSize().then((data) => { + console.info(`AudioFrameworkRecLog: getBufferSize :SUCCESS ${data}`); + bufferSize = data; +}).catch((err) => { + console.info(`AudioFrameworkRecLog: getBufferSize :ERROR : ${err}`); }); ``` -### getDevices(deprecated) - -getDevices(deviceFlag: DeviceFlag, callback: AsyncCallback<AudioDeviceDescriptors>): void +### on('markReach')8+ -Obtains the audio devices with a specific flag. This API uses an asynchronous callback to return the result. +on(type: "markReach", frame: number, callback: Callback<number>): void -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getDevices](#getdevices9) in **AudioRoutingManager**. +Subscribes to mark reached events. When the number of frames captured reaches the value of the **frame** parameter, a callback is invoked. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ------------------------------------------------------------ | --------- | ---------------------------------------- | -| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag. | -| callback | AsyncCallback<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Yes | Callback used to return the device list. | +| Name | Type | Mandatory | Description | +| :------- | :---------------- | :-------- | :----------------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'markReach'**. | +| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | +| callback | Callback\ | Yes | Callback invoked when the event is triggered. | **Example** ```js -audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (err, value) => { - if (err) { - console.error(`Failed to obtain the device list. ${err}`); - return; +audioCapturer.on('markReach', 1000, (position) => { + if (position == 1000) { + console.info('ON Triggered successfully'); } - console.info('Callback invoked to indicate that the device list is obtained.'); }); ``` -### getDevices(deprecated) - -getDevices(deviceFlag: DeviceFlag): Promise<AudioDeviceDescriptors> +### off('markReach')8+ -Obtains the audio devices with a specific flag. This API uses a promise to return the result. +off(type: 'markReach'): void -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getDevices](#getdevices9) in **AudioRoutingManager**. +Unsubscribes from mark reached events. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ------------------------- | --------- | ------------------ | -| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag. | - -**Return value** - -| Type | Description | -| ------------------------------------------------------------ | --------------------------------------- | -| Promise<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Promise used to return the device list. | +| Name | Type | Mandatory | Description | +| :--- | :----- | :-------- | :------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'markReach'**. | **Example** ```js -audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data) => { - console.info('Promise returned to indicate that the device list is obtained.'); -}); +audioCapturer.off('markReach'); ``` -### setDeviceActive(deprecated) - -setDeviceActive(deviceType: ActiveDeviceType, active: boolean, callback: AsyncCallback<void>): void +### on('periodReach')8+ -Sets a device to the active state. This API uses an asynchronous callback to return the result. +on(type: "periodReach", frame: number, callback: Callback<number>): void -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setCommunicationDevice](#setcommunicationdevice9) in **AudioRoutingManager**. +Subscribes to period reached events. When the number of frames captured reaches the value of the **frame** parameter, a callback is triggered and the specified value is returned. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ------------------------------------- | --------- | ------------------------------------------------------------ | -| deviceType | [ActiveDeviceType](#activedevicetype) | Yes | Audio device type. | -| active | boolean | Yes | Active state to set. The value **true** means to set the device to the active state, and **false** means the opposite. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| :------- | :---------------- | :-------- | :----------------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'periodReach'**. | +| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | +| callback | Callback\ | Yes | Callback invoked when the event is triggered. | **Example** ```js -audioManager.setDeviceActive(audio.ActiveDeviceType.SPEAKER, true, (err) => { - if (err) { - console.error(`Failed to set the active status of the device. ${err}`); - return; +audioCapturer.on('periodReach', 1000, (position) => { + if (position == 1000) { + console.info('ON Triggered successfully'); } - console.info('Callback invoked to indicate that the device is set to the active status.'); }); ``` -### setDeviceActive(deprecated) - -setDeviceActive(deviceType: ActiveDeviceType, active: boolean): Promise<void> +### off('periodReach')8+ -Sets a device to the active state. This API uses a promise to return the result. +off(type: 'periodReach'): void -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setCommunicationDevice](#setcommunicationdevice9) in **AudioRoutingManager**. +Unsubscribes from period reached events. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ------------------------------------- | --------- | ------------------------------------------------------------ | -| deviceType | [ActiveDeviceType](#activedevicetype) | Yes | Audio device type. | -| active | boolean | Yes | Active state to set. The value **true** means to set the device to the active state, and **false** means the opposite. | - -**Return value** - -| Type | Description | -| ------------------- | ---------------------------------- | -| Promise<void> | Promise used to return the result. | +| Name | Type | Mandatory | Description | +| :--- | :----- | :-------- | :--------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'periodReach'**. | **Example** - ```js -audioManager.setDeviceActive(audio.ActiveDeviceType.SPEAKER, true).then(() => { - console.info('Promise returned to indicate that the device is set to the active status.'); -}); +audioCapturer.off('periodReach') ``` -### isDeviceActive(deprecated) - -isDeviceActive(deviceType: ActiveDeviceType, callback: AsyncCallback<boolean>): void +### on('stateChange')8+ -Checks whether a device is active. This API uses an asynchronous callback to return the result. +on(type: 'stateChange', callback: Callback): void -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isCommunicationDeviceActive](#iscommunicationdeviceactive9) in **AudioRoutingManager**. +Subscribes to state change events. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ------------------------------------- | --------- | ------------------------------------------------------- | -| deviceType | [ActiveDeviceType](#activedevicetype) | Yes | Audio device type. | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the active state of the device. | +| Name | Type | Mandatory | Description | +| :------- | :------------------------------------ | :-------- | :----------------------------------------------------------- | +| type | string | Yes | Event type. The value **stateChange** means the state change event. | +| callback | Callback\<[AudioState](#audiostate8)> | Yes | Callback used to return the state change. | **Example** ```js -audioManager.isDeviceActive(audio.ActiveDeviceType.SPEAKER, (err, value) => { - if (err) { - console.error(`Failed to obtain the active status of the device. ${err}`); - return; +audioCapturer.on('stateChange', (state) => { + if (state == 1) { + console.info('audio capturer state is: STATE_PREPARED'); + } + if (state == 2) { + console.info('audio capturer state is: STATE_RUNNING'); } - console.info('Callback invoked to indicate that the active status of the device is obtained.'); }); ``` -### isDeviceActive(deprecated) - -isDeviceActive(deviceType: ActiveDeviceType): Promise<boolean> - -Checks whether a device is active. 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 [isCommunicationDeviceActive](#iscommunicationdeviceactive9) in **AudioRoutingManager**. - -**System capability**: SystemCapability.Multimedia.Audio.Device - -**Parameters** +## ToneType9+ -| Name | Type | Mandatory | Description | -| ---------- | ------------------------------------- | --------- | ------------------ | -| deviceType | [ActiveDeviceType](#activedevicetype) | Yes | Audio device type. | +Enumerates the tone types of the player. -**Return value** +**System API**: This is a system API. -| Type | Description | -| ---------------------- | ------------------------------------------------------ | -| Promise<boolean> | Promise used to return the active state of the device. | +**System capability**: SystemCapability.Multimedia.Audio.Tone -**Example** +| Name | Value | Description | +| :----------------------------------------------- | :---- | :-------------------------------------------- | +| TONE_TYPE_DIAL_0 | 0 | DTMF tone of key 0. | +| TONE_TYPE_DIAL_1 | 1 | DTMF tone of key 1. | +| TONE_TYPE_DIAL_2 | 2 | DTMF tone of key 2. | +| TONE_TYPE_DIAL_3 | 3 | DTMF tone of key 3. | +| TONE_TYPE_DIAL_4 | 4 | DTMF tone of key 4. | +| TONE_TYPE_DIAL_5 | 5 | DTMF tone of key 5. | +| TONE_TYPE_DIAL_6 | 6 | DTMF tone of key 6. | +| TONE_TYPE_DIAL_7 | 7 | DTMF tone of key 7. | +| TONE_TYPE_DIAL_8 | 8 | DTMF tone of key 8. | +| TONE_TYPE_DIAL_9 | 9 | DTMF tone of key 9. | +| TONE_TYPE_DIAL_S | 10 | DTMF tone of the star key (*). | +| TONE_TYPE_DIAL_P | 11 | DTMF tone of the pound key (#). | +| TONE_TYPE_DIAL_A | 12 | DTMF tone of key A. | +| TONE_TYPE_DIAL_B | 13 | DTMF tone of key B. | +| TONE_TYPE_DIAL_C | 14 | DTMF tone of key C. | +| TONE_TYPE_DIAL_D | 15 | DTMF tone of key D. | +| TONE_TYPE_COMMON_SUPERVISORY_DIAL | 100 | Supervisory tone - dial tone. | +| TONE_TYPE_COMMON_SUPERVISORY_BUSY | 101 | Supervisory tone - busy. | +| TONE_TYPE_COMMON_SUPERVISORY_CONGESTION | 102 | Supervisory tone - congestion. | +| TONE_TYPE_COMMON_SUPERVISORY_RADIO_ACK | 103 | Supervisory tone - radio path acknowledgment. | +| TONE_TYPE_COMMON_SUPERVISORY_RADIO_NOT_AVAILABLE | 104 | Supervisory tone - radio path not available. | +| TONE_TYPE_COMMON_SUPERVISORY_CALL_WAITING | 106 | Supervisory tone - call waiting tone. | +| TONE_TYPE_COMMON_SUPERVISORY_RINGTONE | 107 | Supervisory tone - ringing tone. | +| TONE_TYPE_COMMON_PROPRIETARY_BEEP | 200 | Proprietary tone - beep tone. | +| TONE_TYPE_COMMON_PROPRIETARY_ACK | 201 | Proprietary tone - ACK. | +| TONE_TYPE_COMMON_PROPRIETARY_PROMPT | 203 | Proprietary tone - PROMPT. | +| TONE_TYPE_COMMON_PROPRIETARY_DOUBLE_BEEP | 204 | Proprietary tone - double beep tone. | -```js -audioManager.isDeviceActive(audio.ActiveDeviceType.SPEAKER).then((value) => { - console.info(`Promise returned to indicate that the active status of the device is obtained ${value}.`); -}); +## TonePlayer9+ -``` +Provides APIs for playing and managing DTMF tones, such as dial tones, ringback tones, supervisory tones, and proprietary tones. -### setMicrophoneMute(deprecated) +**System API**: This is a system API. -setMicrophoneMute(mute: boolean, callback: AsyncCallback<void>): void +### load9+ -Mutes or unmutes the microphone. This API uses an asynchronous callback to return the result. +load(type: ToneType, callback: AsyncCallback<void>): void -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setMicrophoneMute](#setmicrophonemute9) in **AudioVolumeGroupManager**. +Loads the DTMF tone configuration. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.MICROPHONE +**System API**: This is a system API. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Tone **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------- | --------- | ------------------------------------------------------------ | -| mute | boolean | Yes | Mute status to set. The value **true** means to mute the microphone, and **false** means the opposite. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| :------- | :--------------------- | :-------- | :---------------------------------- | +| type | [ToneType](#tonetype9) | Yes | Tone type. | +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -audioManager.setMicrophoneMute(true, (err) => { +tonePlayer.load(audio.ToneType.TONE_TYPE_DIAL_5, (err) => { if (err) { - console.error(`Failed to mute the microphone. ${err}`); + console.error(`callback call load failed error: ${err.message}`); return; + } else { + console.info('callback call load success'); } - console.info('Callback invoked to indicate that the microphone is muted.'); }); ``` -### setMicrophoneMute(deprecated) - -setMicrophoneMute(mute: boolean): Promise<void> +### load9+ -Mutes or unmutes the microphone. This API uses a promise to return the result. +load(type: ToneType): Promise<void> -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setMicrophoneMute](#setmicrophonemute9) in **AudioVolumeGroupManager**. +Loads the DTMF tone configuration. This API uses a promise to return the result. -**Required permissions**: ohos.permission.MICROPHONE +**System API**: This is a system API. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Tone **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------- | --------- | ------------------------------------------------------------ | -| mute | boolean | Yes | Mute status to set. The value **true** means to mute the microphone, and **false** means the opposite. | +| Name | Type | Mandatory | Description | +| :--- | :--------------------- | :-------- | ----------- | +| type | [ToneType](#tonetype9) | Yes | Tone type. | **Return value** -| Type | Description | -| ------------------- | ---------------------------------- | -| Promise<void> | Promise used to return the result. | +| Type | Description | +| :------------- | :--------------------------------- | +| Promise | Promise used to return the result. | **Example** ```js -audioManager.setMicrophoneMute(true).then(() => { - console.info('Promise returned to indicate that the microphone is muted.'); +tonePlayer.load(audio.ToneType.TONE_TYPE_DIAL_1).then(() => { + console.info('promise call load '); +}).catch(() => { + console.error('promise call load fail'); }); ``` -### isMicrophoneMute(deprecated) - -isMicrophoneMute(callback: AsyncCallback<boolean>): void +### start9+ -Checks whether the microphone is muted. This API uses an asynchronous callback to return the result. +start(callback: AsyncCallback<void>): void -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isMicrophoneMute](#ismicrophonemute9) in **AudioVolumeGroupManager**. +Starts DTMF tone playing. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.MICROPHONE +**System API**: This is a system API. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Tone **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------- | --------- | ------------------------------------------------------------ | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the mute status of the microphone. The value **true** means that the microphone is muted, and **false** means the opposite. | +| Name | Type | Mandatory | Description | +| :------- | :------------------- | :-------- | :---------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -audioManager.isMicrophoneMute((err, value) => { +tonePlayer.start((err) => { if (err) { - console.error(`Failed to obtain the mute status of the microphone. ${err}`); + console.error(`callback call start failed error: ${err.message}`); return; + } else { + console.info('callback call start success'); } - console.info(`Callback invoked to indicate that the mute status of the microphone is obtained ${value}.`); }); ``` -### isMicrophoneMute(deprecated) - -isMicrophoneMute(): Promise<boolean> +### start9+ -Checks whether the microphone is muted. This API uses a promise to return the result. +start(): Promise<void> -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isMicrophoneMute](#ismicrophonemute9) in **AudioVolumeGroupManager**. +Starts DTMF tone playing. This API uses a promise to return the result. -**Required permissions**: ohos.permission.MICROPHONE +**System API**: This is a system API. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Tone **Return value** -| Type | Description | -| ---------------------- | ------------------------------------------------------------ | -| Promise<boolean> | Promise used to return the mute status of the microphone. The value **true** means that the microphone is muted, and **false** means the opposite. | +| Type | Description | +| :------------- | :--------------------------------- | +| Promise | Promise used to return the result. | **Example** ```js -audioManager.isMicrophoneMute().then((value) => { - console.info(`Promise returned to indicate that the mute status of the microphone is obtained ${value}.`); +tonePlayer.start().then(() => { + console.info('promise call start'); +}).catch(() => { + console.error('promise call start fail'); }); ``` -### on('volumeChange')(deprecated) - -on(type: 'volumeChange', callback: Callback\): void +### stop9+ -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [on](#on9) in **AudioVolumeManager**. +stop(callback: AsyncCallback<void>): void -Subscribes to system volume change events. +Stops the tone that is being played. This API uses an asynchronous callback to return the result. **System API**: This is a system API. -Currently, when multiple **AudioManager** instances are used in a single process, only the subscription of the last instance takes effect, and the subscription of other instances is overwritten (even if the last instance does not initiate a subscription). Therefore, you are advised to use a single **AudioManager** instance. - -**System capability**: SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Tone **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------------------------------------- | --------- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value **'volumeChange'** means the system volume change event, which is triggered when a system volume change is detected. | -| callback | Callback<[VolumeEvent](#volumeevent8)> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| :------- | :------------------- | :-------- | :---------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -audioManager.on('volumeChange', (volumeEvent) => { - console.info(`VolumeType of stream: ${volumeEvent.volumeType} `); - console.info(`Volume level: ${volumeEvent.volume} `); - console.info(`Whether to updateUI: ${volumeEvent.updateUi} `); +tonePlayer.stop((err) => { + if (err) { + console.error(`callback call stop error: ${err.message}`); + return; + } else { + console.error('callback call stop success '); + } }); ``` -### on('ringerModeChange')(deprecated) - -on(type: 'ringerModeChange', callback: Callback\): void +### stop9+ -Subscribes to ringer mode change events. +stop(): Promise<void> -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [on('ringerModeChange')](#onringermodechange9) in **AudioVolumeGroupManager**. +Stops the tone that is being played. This API uses a promise to return the result. **System API**: This is a system API. -**System capability**: SystemCapability.Multimedia.Audio.Communication +**System capability**: SystemCapability.Multimedia.Audio.Tone -**Parameters** +**Return value** -| Name | Type | Mandatory | Description | -| -------- | ----------------------------------------- | --------- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value **'ringerModeChange'** means the ringer mode change event, which is triggered when a ringer mode change is detected. | -| callback | Callback<[AudioRingMode](#audioringmode)> | Yes | Callback used to return the result. | +| Type | Description | +| :------------- | :--------------------------------- | +| Promise | Promise used to return the result. | **Example** ```js -audioManager.on('ringerModeChange', (ringerMode) => { - console.info(`Updated ringermode: ${ringerMode}`); +tonePlayer.stop().then(() => { + console.info('promise call stop finish'); +}).catch(() => { + console.error('promise call stop fail'); }); ``` -### on('deviceChange')(deprecated) +### release9+ -on(type: 'deviceChange', callback: Callback): void +release(callback: AsyncCallback<void>): void -Subscribes to device change events. When a device is connected or disconnected, registered clients will receive the callback. +Releases the resources associated with the **TonePlayer** instance. 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 [on](#on9) in **AudioRoutingManager**. +**System API**: This is a system API. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Tone **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :--------------------------------------------------- | :-------- | :----------------------------------------------------------- | -| type | string | Yes | Event type. The value **'deviceChange'** means the device change event, which is triggered when a device connection status change is detected. | -| callback | Callback<[DeviceChangeAction](#devicechangeaction)\> | Yes | Callback used to return the device update details. | +| Name | Type | Mandatory | Description | +| :------- | :------------------- | :-------- | :---------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -audioManager.on('deviceChange', (deviceChanged) => { - console.info(`device change type : ${deviceChanged.type} `); - console.info(`device descriptor size : ${deviceChanged.deviceDescriptors.length} `); - console.info(`device change descriptor : ${deviceChanged.deviceDescriptors[0].deviceRole} `); - console.info(`device change descriptor : ${deviceChanged.deviceDescriptors[0].deviceType} `); +tonePlayer.release((err) => { + if (err) { + console.error(`callback call release failed error: ${err.message}`); + return; + } else { + console.info('callback call release success '); + } }); ``` -### off('deviceChange')(deprecated) +### release9+ -off(type: 'deviceChange', callback?: Callback): void +release(): Promise<void> -Unsubscribes from device change events. +Releases the resources associated with the **TonePlayer** instance. 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 [off](#off9) in **AudioRoutingManager**. +**System API**: This is a system API. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Tone -**Parameters** +**Return value** -| Name | Type | Mandatory | Description | -| -------- | --------------------------------------------------- | --------- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value **'deviceChange'** means the device change event, which is triggered when a device connection status change is detected. | -| callback | Callback<[DeviceChangeAction](#devicechangeaction)> | No | Callback used to return the device update details. | +| Type | Description | +| :------------- | :--------------------------------- | +| Promise | Promise used to return the result. | **Example** ```js -audioManager.off('deviceChange', (deviceChanged) => { - console.info('Should be no callback.'); +tonePlayer.release().then(() => { + console.info('promise call release'); +}).catch(() => { + console.error('promise call release fail'); }); + ``` -### on('interrupt')(deprecated) +## ActiveDeviceType(deprecated) -on(type: 'interrupt', interrupt: AudioInterrupt, callback: Callback\): void +Enumerates the active device types. -Subscribes to audio interruption events. When the application's audio is interrupted by another playback event, the application will receive the callback. +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use [CommunicationDeviceType](#communicationdevicetype9) instead. -Same as [on('audioInterrupt')](#onaudiointerrupt9), this API is used to listen for focus changes. However, this API is used in scenarios without audio streams (no **AudioRenderer** instance is created), such as frequency modulation (FM) and voice wakeup. +**System capability**: SystemCapability.Multimedia.Audio.Device + +| Name | Value | Description | +| ------------- | ----- | ------------------------------------------------------------ | +| SPEAKER | 2 | Speaker. | +| BLUETOOTH_SCO | 7 | Bluetooth device using Synchronous Connection Oriented (SCO) links. | + +## InterruptActionType(deprecated) + +Enumerates the returned event types for audio interruption events. > **NOTE** > @@ -6077,40 +6141,30 @@ Same as [on('audioInterrupt')](#onaudiointerrupt9), this API is used to listen f **System capability**: SystemCapability.Multimedia.Audio.Renderer -**Parameters** +| Name | Value | Description | +| -------------- | ----- | ------------------------- | +| TYPE_ACTIVATED | 0 | Focus gain event. | +| TYPE_INTERRUPT | 1 | Audio interruption event. | -| Name | Type | Mandatory | Description | -| --------- | --------------------------------------------- | --------- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value **'interrupt'** means the audio interruption event, which is triggered when the audio playback of the current application is interrupted by another application. | -| interrupt | AudioInterrupt | Yes | Audio interruption event type. | -| callback | Callback<[InterruptAction](#interruptaction)> | Yes | Callback invoked for the audio interruption event. | +## AudioInterrupt(deprecated) -**Example** +Describes input parameters of audio interruption events. -```js -let interAudioInterrupt = { - streamUsage:2, - contentType:0, - pauseWhenDucked:true -}; -audioManager.on('interrupt', interAudioInterrupt, (InterruptAction) => { - if (InterruptAction.actionType === 0) { - console.info('An event to gain the audio focus starts.'); - console.info(`Focus gain event: ${InterruptAction} `); - } - if (InterruptAction.actionType === 1) { - console.info('An audio interruption event starts.'); - console.info(`Audio interruption event: ${InterruptAction} `); - } -}); +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. -``` +**System capability**: SystemCapability.Multimedia.Audio.Renderer -### off('interrupt')(deprecated) +| Name | Type | Mandatory | Description | +| --------------- | --------------------------- | --------- | ------------------------------------------------------------ | +| streamUsage | [StreamUsage](#streamusage) | Yes | Audio stream usage. | +| contentType | [ContentType](#contenttype) | Yes | Audio content type. | +| pauseWhenDucked | boolean | Yes | Whether audio playback can be paused during audio interruption. The value **true** means that audio playback can be paused during audio interruption, and **false** means the opposite. | -off(type: 'interrupt', interrupt: AudioInterrupt, callback?: Callback\): void +## InterruptAction(deprecated) -Unsubscribes from audio interruption events. +Describes the callback invoked for audio interruption or focus gain events. > **NOTE** > @@ -6118,26 +6172,9 @@ Unsubscribes from audio interruption events. **System capability**: SystemCapability.Multimedia.Audio.Renderer -**Parameters** - -| Name | Type | Mandatory | Description | -| --------- | --------------------------------------------- | --------- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value **'interrupt'** means the audio interruption event, which is triggered when the audio playback of the current application is interrupted by another application. | -| interrupt | AudioInterrupt | Yes | Audio interruption event type. | -| callback | Callback<[InterruptAction](#interruptaction)> | No | Callback invoked for the audio interruption event. | - -**Example** - -```js -let interAudioInterrupt = { - streamUsage:2, - contentType:0, - pauseWhenDucked:true -}; -audioManager.off('interrupt', interAudioInterrupt, (InterruptAction) => { - if (InterruptAction.actionType === 0) { - console.info('An event to release the audio focus starts.'); - console.info(`Focus release event: ${InterruptAction} `); - } -}); -``` \ No newline at end of file +| Name | Type | Mandatory | Description | +| ---------- | ----------------------------------------------------- | --------- | ------------------------------------------------------------ | +| actionType | [InterruptActionType](#interruptactiontypedeprecated) | Yes | Returned event type. The value **TYPE_ACTIVATED** means the focus gain event, and **TYPE_INTERRUPT** means the audio interruption event. | +| type | [InterruptType](#interrupttype) | No | Type of the audio interruption event. | +| hint | [InterruptHint](#interrupthint) | No | Hint provided along with the audio interruption event. | +| activated | boolean | No | Whether the focus is gained or released. The value **true** means that the focus is gained or released, and **false** means that the focus fails to be gained or released. | \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md b/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md index c03f26ef70644a43ec969a5288843838b266f883..49032dcbd7b58a404bd779635fc109a5f2336c38 100644 --- a/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md +++ b/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md @@ -1,4 +1,4 @@ -# Background Task Management +# @ohos.backgroundTaskManager (Background Task Management) The **BackgroundTaskManager** module provides APIs to manage background tasks. @@ -161,7 +161,7 @@ Requests a continuous task from the system. This API uses an asynchronous callba | Name | Type | Mandatory | Description | | --------- | ---------------------------------- | ---- | ---------------------------------------- | -| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| | bgMode | [BackgroundMode](#backgroundmode8) | Yes | Background mode requested. | | wantAgent | [WantAgent](js-apis-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. | | callback | AsyncCallback<void> | Yes | Callback used to return the result. | @@ -253,7 +253,7 @@ Requests a continuous task from the system. This API uses a promise to return th | Name | Type | Mandatory | Description | | --------- | ---------------------------------- | ---- | ---------------------------------------- | -| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| | bgMode | [BackgroundMode](#backgroundmode8) | Yes | Background mode requested. | | wantAgent | [WantAgent](js-apis-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. | @@ -339,7 +339,7 @@ Requests to cancel a continuous task. This API uses an asynchronous callback to | Name | Type | Mandatory | Description | | -------- | ------------------------- | ---- | ---------------------------------------- | -| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** @@ -395,7 +395,7 @@ Requests to cancel a continuous task. This API uses a promise to return the resu | Name | Type | Mandatory | Description | | ------- | ------- | ---- | ---------------------------------------- | -| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| **Return value** @@ -452,14 +452,14 @@ Provides the information about the suspension delay. **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask -| Name | Description | -| ----------------------- | --------------------- | -| DATA_TRANSFER | Data transfer. | -| AUDIO_PLAYBACK | Audio playback. | -| AUDIO_RECORDING | Audio recording. | -| LOCATION | Positioning and navigation. | -| BLUETOOTH_INTERACTION | Bluetooth-related task. | -| MULTI_DEVICE_CONNECTION | Multi-device connection. | -| WIFI_INTERACTION | WLAN-related (system API).| -| VOIP | Audio and video calls (system API). | -| TASK_KEEPING | Computing task (effective only for specific devices). | +| Name | Value | Description | +| ----------------------- | ---- | --------------------- | +| DATA_TRANSFER | 1 | Data transfer. | +| AUDIO_PLAYBACK | 2 | Audio playback. | +| AUDIO_RECORDING | 3 | Audio recording. | +| LOCATION | 4 | Positioning and navigation. | +| BLUETOOTH_INTERACTION | 5 | Bluetooth-related task. | +| MULTI_DEVICE_CONNECTION | 6 | Multi-device connection. | +| WIFI_INTERACTION | 7 | WLAN-related.
This is a system API.| +| VOIP | 8 | Audio and video calls.
This is a system API. | +| TASK_KEEPING | 9 | Computing task (effective only for specific devices). | diff --git a/en/application-dev/reference/apis/js-apis-bundle-AbilityInfo.md b/en/application-dev/reference/apis/js-apis-bundle-AbilityInfo.md index 7f6d5b0196b97a252564d4c29f761aefa2117db3..315e7c0f045ba3b26520ed2a69f41f242872b8e6 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-AbilityInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-AbilityInfo.md @@ -1,6 +1,6 @@ # AbilityInfo -Unless otherwise specified, ability information is obtained through **GET_BUNDLE_DEFAULT**. +The **AbilityInfo** module provides information about an ability. Unless otherwise specified, the information is obtained through [GET_BUNDLE_DEFAULT](js-apis-Bundle.md). > **NOTE** > @@ -8,13 +8,13 @@ Unless otherwise specified, ability information is obtained through **GET_BUNDLE ## AbilityInfo(deprecated) -> This API is deprecated since API version 9. You are advised to use [AbilityInfo](js-apis-bundleManager-abilityInfo.md) instead. +> This API is deprecated since API version 9. You are advised to use [bundleManager-AbilityInfo](js-apis-bundleManager-abilityInfo.md) instead. **System capability**: SystemCapability.BundleManager.BundleFramework | Name | Type | Readable| Writable| Description | | --------------------- | -------------------------------------------------------- | ---- | ---- | ----------------------------------------- | -| bundleName | string | Yes | No | Bundle name of the application. | +| bundleName | string | Yes | No | Bundle name. | | name | string | Yes | No | Ability name. | | label | string | Yes | No | Ability name visible to users. | | description | string | Yes | No | Ability description. | @@ -25,17 +25,17 @@ Unless otherwise specified, ability information is obtained through **GET_BUNDLE | process | string | Yes | No | Process in which the ability runs. If this parameter is not set, the bundle name is used.| | targetAbility | string | Yes | No | Target ability that the ability alias points to.
This attribute can be used only in the FA model.| | backgroundModes | number | Yes | No | Background service mode of the ability.
This attribute can be used only in the FA model. | -| isVisible | boolean | Yes | No | Whether the ability can be called by other applications. | +| isVisible | boolean | Yes | No | Whether the ability can be called by other bundles. | | formEnabled | boolean | Yes | No | Whether the ability provides the service widget capability.
This attribute can be used only in the FA model.| | type | AbilityType | Yes | No | Ability type.
This attribute can be used only in the FA model. | -| orientation | DisplayOrientation | Yes | No | Ability display orientation. | -| launchMode | LaunchMode | Yes | No | Ability launch mode. | +| orientation | [DisplayOrientation](js-apis-Bundle.md#displayorientationdeprecated) | Yes | No | Ability display orientation. | +| launchMode | [LaunchMode](js-apis-Bundle.md#launchmodedeprecated) | Yes | No | Ability launch mode. | | permissions | Array\ | Yes | No | Permissions required for other applications to call the ability.
The value is obtained by passing **GET_ABILITY_INFO_WITH_PERMISSION**.| | deviceTypes | Array\ | Yes | No | Device types supported by the ability. | | deviceCapabilities | Array\ | Yes | No | Device capabilities required for the ability. | | readPermission | string | Yes | No | Permission required for reading the ability data.
This attribute can be used only in the FA model.| | writePermission | string | Yes | No | Permission required for writing data to the ability.
This attribute can be used only in the FA model.| -| applicationInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application configuration information.
The value is obtained by passing **GET_ABILITY_INFO_WITH_APPLICATION**.| +| applicationInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application configuration information.
The value is obtained by passing [GET_ABILITY_INFO_WITH_APPLICATION](js-apis-Bundle.md).| | uri | string | Yes | No | URI of the ability.
This attribute can be used only in the FA model.| | labelId | number | Yes | No | Ability label ID. | | subType | AbilitySubType | Yes | No | Subtype of the template that can be used by the ability.
This attribute can be used only in the FA model.| diff --git a/en/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md b/en/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md index fb5aa288eaaf2f8eb65940f33902906c04c654c2..c1667a66eb011d24a1b7ce79061eab0f454604a3 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md @@ -1,6 +1,6 @@ # ApplicationInfo -The **ApplicationInfo** module provides application information. Unless otherwise specified, all attributes are obtained through **GET_BUNDLE_DEFAULT**. +The **ApplicationInfo** module provides application information. Unless otherwise specified, the information is obtained through [GET_BUNDLE_DEFAULT](js-apis-Bundle.md). > **NOTE** > @@ -8,30 +8,30 @@ The **ApplicationInfo** module provides application information. Unless otherwis ## ApplicationInfo(deprecated) -> This API is deprecated since API version 9. You are advised to use [ApplicationInfo](js-apis-bundleManager-applicationInfo.md) instead. +> This API is deprecated since API version 9. You are advised to use [bundleManager-ApplicationInfo](js-apis-bundleManager-applicationInfo.md) instead. **System capability**: SystemCapability.BundleManager.BundleFramework -| Name | Type | Readable| Writable| Description | -| -------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | -| name | string | Yes | No | Application name. | -| description | string | Yes | No | Application description. | -| descriptionId | number | Yes | No | Application description ID. | -| systemApp | boolean | Yes | No | Whether the application is a system application. The default value is **false**. | -| enabled | boolean | Yes | No | Whether the application is enabled. The default value is **true**. | -| label | string | Yes | No | Application label. | -| labelId(deprecated) | string | Yes | No | Application label ID.
\- **NOTE**: This attribute is deprecated from API version 9. Use **labelIndex** instead.| -| icon | string | Yes | No | Application icon. | -| iconId(deprecated) | string | Yes | No | Application icon ID.
\- **NOTE**: This attribute is deprecated from API version 9. Use **iconIndex** instead.| -| process | string | Yes | No | Process in which the application runs. If this parameter is not set, the bundle name is used. | -| supportedModes | number | Yes | No | Running modes supported by the application. | -| moduleSourceDirs | Array\ | Yes | No | Relative paths for storing application resources. | -| permissions | Array\ | Yes | No | Permissions required for accessing the application.
The value is obtained by passing **GET_APPLICATION_INFO_WITH_PERMISSION**.| -| moduleInfos | Array\<[ModuleInfo](js-apis-bundle-ModuleInfo.md)> | Yes | No | Application module information. | -| entryDir | string | Yes | No | Path for storing application files. | -| codePath8+ | string | Yes | No | Installation directory of the application. | -| metaData8+ | Map\> | Yes | No | Custom metadata of the application.
The value is obtained by passing **GET_APPLICATION_INFO_WITH_METADATA**.| -| removable8+ | boolean | Yes | No | Whether the application is removable. | -| accessTokenId8+ | number | Yes | No | Access token ID of the application. | -| uid8+ | number | Yes | No | UID of the application. | -| entityType8+ | string | Yes | No | Entity type of the application. | +| Name | Type | Readable | Writable | Description | +|----------------------------|------------------------------------------------------------------------|-----|-----|----------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| name | string | Yes | No | Application name. | +| description | string | Yes | No | Application description. | +| descriptionId | number | Yes | No | Application description ID. | +| systemApp | boolean | Yes | No | Whether the application is a system application. The default value is **false**. | +| enabled | boolean | Yes | No | Whether the application is enabled. The default value is **true**. | +| label | string | Yes | No | Application label. | +| labelId | string | Yes | No | Application label ID. | +| icon | string | Yes | No | Application icon. | +| iconId | string | Yes | No | Application icon ID. | +| process | string | Yes | No | Process in which the application runs. If this parameter is not set, the bundle name is used. | +| supportedModes | number | Yes | No | Modes supported by the application. Currently, only the **drive** mode is defined. This attribute applies only to head units. | +| moduleSourceDirs | Array\ | Yes | No | Relative paths for storing application resources. | +| permissions | Array\ | Yes | No | Permissions required for accessing the application.
The value is obtained by passing [GET_APPLICATION_INFO_WITH_PERMISSION](js-apis-Bundle.md). | +| moduleInfos | Array\<[ModuleInfo](js-apis-bundle-ModuleInfo.md)> | Yes | No | Application module information. | +| entryDir | string | Yes | No | Path for storing application files. | +| codePath8+ | string | Yes | No | Installation directory of the application. | +| metaData8+ | Map\> | Yes | No | Custom metadata of the application.
The value is obtained by passing [GET_APPLICATION_INFO_WITH_METADATA](js-apis-Bundle.md). | +| removable8+ | boolean | Yes | No | Whether the application is removable. | +| accessTokenId8+ | number | Yes | No | Access token ID of the application. | +| uid8+ | number | Yes | No | UID of the application. | +| entityType8+ | string | Yes | No | Category of the application, which can be **game**, **media**, **communication**, **news**, **travel**, **utility**, **shopping**, **education**, **kids**, **business**, and **photography**.| diff --git a/en/application-dev/reference/apis/js-apis-bundle-BundleInfo.md b/en/application-dev/reference/apis/js-apis-bundle-BundleInfo.md index f1d0240513193f217b71ccfc900acc5a211d07c3..c14419e736e1c2142fb47157826c42fb0d5cff34 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-BundleInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-BundleInfo.md @@ -1,18 +1,16 @@ # BundleInfo -The **BundleInfo** module provides bundle information. Unless otherwise specified, all attributes are obtained through **GET_BUNDLE_DEFAULT**. +The **BundleInfo** module provides bundle information. Unless otherwise specified, the information is obtained through [GET_BUNDLE_DEFAULT](js-apis-Bundle.md). > **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. - - ## BundleInfo(deprecated) -> This API is deprecated since API version 9. You are advised to use [BundleInfo](js-apis-bundleManager-bundleInfo.md) instead. +> This API is deprecated since API version 9. You are advised to use [bundleManager-BundleInfo](js-apis-bundleManager-bundleInfo.md) instead. - **System capability**: SystemCapability.BundleManager.BundleFramework +**System capability**: SystemCapability.BundleManager.BundleFramework | Name | Type | Readable| Writable| Description | | --------------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | @@ -25,7 +23,7 @@ The **BundleInfo** module provides bundle information. Unless otherwise specifie | appInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application configuration information. | | abilityInfos | Array\<[AbilityInfo](js-apis-bundle-AbilityInfo.md)> | Yes | No | Ability configuration information.
The value is obtained by passing **GET_BUNDLE_WITH_ABILITIES**.| | reqPermissions | Array\ | Yes | No | Permissions to request from the system for running the application.
The value is obtained by passing **GET_BUNDLE_WITH_REQUESTED_PERMISSION**.| -| reqPermissionDetails | Array\<[ReqPermissionDetail](#reqpermissiondetail)> | Yes | No | Detailed information of the permissions to request from the system.
The value is obtained by passing **GET_BUNDLE_WITH_REQUESTED_PERMISSION**.| +| reqPermissionDetails | Array\<[ReqPermissionDetail](#reqpermissiondetaildeprecated)> | Yes | No | Detailed information of the permissions to request from the system.
The value is obtained by passing **GET_BUNDLE_WITH_REQUESTED_PERMISSION**.| | vendor | string | Yes | No | Vendor of the bundle. | | versionCode | number | Yes | No | Version number of the bundle. | | versionName | string | Yes | No | Version description of the bundle. | @@ -38,7 +36,7 @@ The **BundleInfo** module provides bundle information. Unless otherwise specifie | isSilentInstallation | string | Yes | No | Whether the application can be installed in silent mode. | | minCompatibleVersionCode | number | Yes | No | Earliest version compatible with the bundle in the distributed scenario. | | entryInstallationFree | boolean | Yes | No | Whether installation-free is supported for the entry module. | -| reqPermissionStates8+ | Array\ | Yes | No | Permission grant state. | +| reqPermissionStates8+ | Array\ | Yes | No | Permission grant state. The value **0** means that the request is successful, and **-1** means the opposite. | @@ -54,7 +52,7 @@ Provides the detailed information of the permissions to request from the system. | --------------------- | ----------------------- | ---- | ---- | ---------------------- | | name | string | Yes | Yes | Name of the permission to request. | | reason | string | Yes | Yes | Reason for requesting the permission. | -| usedScene | [UsedScene](#usedscene) | Yes | Yes | Application scenario and timing for using the permission.| +| usedScene | [UsedScene](#usedscenedeprecated) | Yes | Yes | Application scenario and timing for using the permission.| diff --git a/en/application-dev/reference/apis/js-apis-bundle-BundleInstaller.md b/en/application-dev/reference/apis/js-apis-bundle-BundleInstaller.md index 9ab7fb823fc00cc663c909c48fca2e6cee047545..0570453b5cb9c1bfa6a1e0f0acb9dda16562005e 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-BundleInstaller.md +++ b/en/application-dev/reference/apis/js-apis-bundle-BundleInstaller.md @@ -12,7 +12,7 @@ The **BundleInstaller** module provides APIs for you to install, uninstall, and install(bundleFilePaths: Array<string>, param: InstallParam, callback: AsyncCallback<InstallStatus>): void; -Installs a bundle. This API uses an asynchronous callback to return the result. +Installs a bundle. Multiple HAP files can be installed. This API uses an asynchronous callback to return the result. **Required permissions** @@ -28,9 +28,33 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | --------------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ | -| bundleFilePaths | Array<string> | Yes | Paths where the HAP files of the bundle are stored. Each path should point to a relative directory of the current bundle's data directory.| -| param | [InstallParam](#installparam) | Yes | Parameters required for bundle installation. | -| callback | AsyncCallback<[InstallStatus](#installstatus)> | Yes | Callback used to return the installation status. | +| bundleFilePaths | Array<string> | Yes | Sandbox path where the HAP files of the bundle are stored. For details about how to obtain the sandbox path, see [Obtaining the Sandbox Path](#obtaining-the-sandbox-path).| +| param | [InstallParam](#installparamdeprecated) | Yes | Parameters required for bundle installation. | +| callback | AsyncCallback<[InstallStatus](#installstatusdeprecated)> | Yes | Callback used to return the installation status. | + +**Example** + +```ts +import bundle from '@ohos.bundle'; +let hapFilePaths = ['/data/storage/el2/base/haps/entry/files/']; +let installParam = { + userId: 100, + isKeepData: false, + installFlag: 1, +}; + +bundle.getBundleInstaller().then(installer=>{ + installer.install(hapFilePaths, installParam, err => { + if (err) { + console.error('install failed:' + JSON.stringify(err)); + } else { + console.info('install successfully.'); + } + }); +}).catch(error => { + console.error('getBundleInstaller failed. Cause: ' + error.message); +}); +``` ## BundleInstaller.uninstall(deprecated) @@ -55,16 +79,39 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ---------- | ---------------------------------------------------- | ---- | ---------------------------------------------- | | bundleName | string | Yes | Bundle name. | -| param | [InstallParam](#installparam) | Yes | Parameters required for bundle uninstall. | -| callback | AsyncCallback<[InstallStatus](#installstatus)> | Yes | Callback used to return the installation status.| - +| param | [InstallParam](#installparamdeprecated) | Yes | Parameters required for bundle uninstall. | +| callback | AsyncCallback<[InstallStatus](#installstatusdeprecated)> | Yes | Callback used to return the installation status.| + +**Example** + +```ts +import bundle from '@ohos.bundle'; +let bundleName = 'com.example.myapplication'; +let installParam = { + userId: 100, + isKeepData: false, + installFlag: 1, +}; + +bundle.getBundleInstaller().then(installer=>{ + installer.uninstall(bundleName, installParam, err => { + if (err) { + console.error('uninstall failed:' + JSON.stringify(err)); + } else { + console.info('uninstall successfully.'); + } + }); +}).catch(error => { + console.error('getBundleInstaller failed. Cause: ' + error.message); +}); +``` ## BundleInstaller.recover(deprecated) > This API is deprecated since API version 9. You are advised to use [recover](js-apis-installer.md) instead. recover(bundleName: string, param: InstallParam, callback: AsyncCallback<InstallStatus>): void; -Recovers a bundle. This API uses an asynchronous callback to return the result. +Recovers a bundle. This API uses an asynchronous callback to return the result. After a pre-installed bundle is uninstalled, you can call this API to recover it. **Required permissions** @@ -81,12 +128,37 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ---------- | ---------------------------------------------------- | ---- | ---------------------------------------------- | | bundleName | string | Yes | Bundle name. | -| param | [InstallParam](#installparam) | Yes | Parameters required for bundle recovering. | -| callback | AsyncCallback<[InstallStatus](#installstatus)> | Yes | Callback used to return the installation status.| +| param | [InstallParam](#installparamdeprecated) | Yes | Parameters required for bundle recovery. | +| callback | AsyncCallback<[InstallStatus](#installstatusdeprecated)> | Yes | Callback used to return the recovery status.| + +**Example** + +```ts +import bundle from '@ohos.bundle'; + +let bundleName = 'com.example.myapplication'; +let installParam = { + userId: 100, + isKeepData: false, + installFlag: 1, +}; + +bundle.getBundleInstaller().then(installer=>{ + installer.recover(bundleName, installParam, err => { + if (err) { + console.error('recover failed:' + JSON.stringify(err)); + } else { + console.info('recover successfully.'); + } + }); +}).catch(error => { + console.error('getBundleInstaller failed. Cause: ' + error.message); +}); +``` ## InstallParam(deprecated) -Describes the parameters required for bundle installation or uninstall. +Describes the parameters required for bundle installation, recovery, or uninstall. **System capability**: SystemCapability.BundleManager.BundleFramework @@ -100,7 +172,7 @@ Describes the parameters required for bundle installation or uninstall. ## InstallStatus(deprecated) -Describes the bundle installation status. +Describes the bundle installation or uninstall status. **System capability**: SystemCapability.BundleManager.BundleFramework @@ -110,3 +182,27 @@ Describes the bundle installation status. | ------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------ | | status | bundle.[InstallErrorCode](js-apis-Bundle.md#installerrorcode) | Yes | No | Installation or uninstall error code. | | statusMessage | string | Yes | No | Installation or uninstall status message.| + +## Obtaining the Sandbox Path +For the FA model, the sandbox path of a bundle can be obtained using the APIs in [Context](js-apis-inner-app-context.md). For the sage model, the sandbox path can be obtained using the attribute in [Context](js-apis-ability-context.md#abilitycontext). The following describes how to obtain the sandbox path. + +**Example** +``` ts +// Stage model +import Ability from '@ohos.application.Ability'; +class MainAbility extends Ability { + onWindowStageCreate(windowStage) { + let context = this.context; + let pathDir = context.filesDir; + console.info('sandbox path is ' + pathDir); + } +} + +// FA model +import featureAbility from '@ohos.ability.featureAbility'; +let context = featureAbility.getContext(); +context.getFilesDir().then((data) => { + let pathDir = data; + console.info('sandbox path is ' + pathDir); +}); +``` diff --git a/en/application-dev/reference/apis/js-apis-bundle-CustomizeData.md b/en/application-dev/reference/apis/js-apis-bundle-CustomizeData.md index 246f1420fbb328cab877fa7e83476a558530b9f9..e54a37c697a4b44df566aa8f517a4b0befd8297b 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-CustomizeData.md +++ b/en/application-dev/reference/apis/js-apis-bundle-CustomizeData.md @@ -14,6 +14,6 @@ The **CustomizeData** module provides custom metadata. | Name | Type | Readable| Writable| Description | | ------------------ | ------ | ---- | ---- | ---------------- | -| name | string | Yes | Yes | Custom metadata name.| -| value | string | Yes | Yes | Custom metadata value. | -| extra8+ | string | Yes | Yes | Custom metadata resources. | +| name | string | Yes | Yes | Key that identifies a data element.| +| value | string | Yes | Yes | Value of the data element. | +| extra8+ | string | Yes | Yes | Custom format of the data element. The value is an index to the resource that identifies the data. | diff --git a/en/application-dev/reference/apis/js-apis-bundle-ElementName.md b/en/application-dev/reference/apis/js-apis-bundle-ElementName.md index 54f43e7a56376caf4ea623d358fc27bec2d54dbc..b20de58d074a83dea5cb0992e21087ae64b990bb 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-ElementName.md +++ b/en/application-dev/reference/apis/js-apis-bundle-ElementName.md @@ -1,6 +1,6 @@ # ElementName -The **ElementName** module provides the element name information, which can be obtained through [Context.getElementName](js-apis-Context.md). +The **ElementName** module provides element name information, which can be obtained through [Context.getElementName](js-apis-inner-app-context.md). > **NOTE** > @@ -8,7 +8,9 @@ The **ElementName** module provides the element name information, which can be o ## ElementName(deprecated) -> This API is deprecated since API version 9. You are advised to use [ElementName](js-apis-bundleManager-elementName.md) instead. +> This API is deprecated since API version 9. You are advised to use [bundleManager-ElementName](js-apis-bundleManager-elementName.md) instead. + +Describes the element name information, which identifies the basic information about an ability and is obtained through [Context.getElementName](js-apis-inner-app-context.md). **System capability**: SystemCapability.BundleManager.BundleFramework diff --git a/en/application-dev/reference/apis/js-apis-bundle-HapModuleInfo.md b/en/application-dev/reference/apis/js-apis-bundle-HapModuleInfo.md index 0e252cc3fe46c45114a2d9cb9738c6ec3e0a9ffe..5540aa2bc56b9f8e34fda11d11048b8177816b95 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-HapModuleInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-HapModuleInfo.md @@ -1,6 +1,6 @@ # HapModuleInfo -The **HapModuleInfo** module provides module information. Unless otherwise specified, all attributes are obtained through **GET_BUNDLE_DEFAULT**. +The **HapModuleInfo** module provides information about an HAP module. Unless otherwise specified, the information is obtained through [GET_BUNDLE_DEFAULT](js-apis-Bundle.md). > **NOTE** > @@ -8,7 +8,7 @@ The **HapModuleInfo** module provides module information. Unless otherwise speci ## HapModuleInfo(deprecated) -> This API is deprecated since API version 9. You are advised to use [HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md) instead. +> This API is deprecated since API version 9. You are advised to use [bundleManager-HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md) instead. **System capability**: SystemCapability.BundleManager.BundleFramework diff --git a/en/application-dev/reference/apis/js-apis-bundle-ModuleInfo.md b/en/application-dev/reference/apis/js-apis-bundle-ModuleInfo.md index 781b34f89b8a954c5f0be626fcbfe0d3fc5ab3f8..18707feeb05902b5740b00544b3a23a43c09acce 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-ModuleInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-ModuleInfo.md @@ -7,10 +7,9 @@ The **ModuleInfo** module provides module information of an application. > 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. ## ModuleInfo(deprecated) -> This API is deprecated since API version 9. You are advised to use [HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md) instead. +> This API is deprecated since API version 9. You are advised to use [bundleManager-HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md) instead. **System capability**: SystemCapability.BundleManager.BundleFramework - | Name | Type | Readable| Writable| Description | | --------------- | ------ | ---- | ---- | -------- | | moduleName | string | Yes | No | Module name.| diff --git a/en/application-dev/reference/apis/js-apis-bundle-PermissionDef.md b/en/application-dev/reference/apis/js-apis-bundle-PermissionDef.md index aa7b5da045a32bb53590a8b3a5f9ec1f3dffce0e..ded02c772794179d9e8276292ab1be939a208d8f 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-PermissionDef.md +++ b/en/application-dev/reference/apis/js-apis-bundle-PermissionDef.md @@ -8,7 +8,7 @@ The **PermissionDef** module provides permission details defined in the configur ## **PermissionDef**(deprecated) -> This API is deprecated since API version 9. You are advised to use [PermissionDef](js-apis-bundleManager-permissionDef.md) instead. +> This API is deprecated since API version 9. You are advised to use [bundleManager-PermissionDef](js-apis-bundleManager-permissionDef.md) instead. **System capability**: SystemCapability.BundleManager.BundleFramework @@ -17,6 +17,6 @@ The **PermissionDef** module provides permission details defined in the configur | Name | Type | Readable| Writable| Description | | -------------- | ------ | ---- | ---- | -------------- | | permissionName | string | Yes | No | Name of the permission. | -| grantMode | number | Yes | No | Grant mode of the permission.| +| grantMode | number | Yes | No | Grant mode of the permission. The value **0** means that the system automatically grants the permission after the application installation, and **1** means that the application needs to dynamically request the permission from the user.| | labelId | number | Yes | No | Label ID of the permission. | | descriptionId | number | Yes | No | Description ID of the permission. | diff --git a/en/application-dev/reference/apis/js-apis-bundle-ShortcutInfo.md b/en/application-dev/reference/apis/js-apis-bundle-ShortcutInfo.md index adf30d8b7442dd67e822f200a0114f93957bd892..1a603da33b3403dafbac79e1bfcd31c5dde9896c 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-ShortcutInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-ShortcutInfo.md @@ -1,16 +1,14 @@ -# ShortcutInfo(deprecated) +# shortcutInfo -The **ShortcutInfo** module provides shortcut information defined in the configuration file. For details about the configuration in the FA model, see [config.json](../../quick-start/package-structure.md). For details about the configuration in the stage model, see [Internal Structure of the shortcuts Attribute](../../quick-start/stage-structure.md#internal-structure-of-the-shortcuts-attribute). +The **shortcutInfo** module defines shortcut information configured in the configuration file. For the FA model, the shortcut information is configured in the [config.json](../../quick-start/application-configuration-file-overview-fa.md) file. For the stage model, the information is configured in the configuration file under **resources/base/profile** in the development view. > **NOTE** > -> This module is deprecated since API version 9. You are advised to use [ShortcutInfo](js-apis-bundleManager-shortcutInfo.md) instead. -> > 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. ## ShortcutWant(deprecated) -> This API is deprecated since API version 9. You are advised to use [ShortcutWant](js-apis-bundleManager-shortcutInfo.md) instead. +> This API is deprecated since API version 9. You are advised to use [bundleManager-ShortcutWant](js-apis-bundleManager-shortcutInfo.md) instead. **System capability**: SystemCapability.BundleManager.BundleFramework @@ -23,7 +21,7 @@ The **ShortcutInfo** module provides shortcut information defined in the configu ## ShortcutInfo(deprecated) -> This API is deprecated since API version 9. You are advised to use [ShortcutInfo](js-apis-bundleManager-shortcutInfo.md) instead. +> This API is deprecated since API version 9. You are advised to use [bundleManager-ShortcutInfo](js-apis-bundleManager-shortcutInfo.md) instead. **System capability**: SystemCapability.BundleManager.BundleFramework @@ -35,10 +33,12 @@ The **ShortcutInfo** module provides shortcut information defined in the configu | hostAbility | string | Yes | No | Local ability information of the shortcut. | | icon | string | Yes | No | Icon of the shortcut. | | iconId8+ | number | Yes | No | Icon ID of the shortcut. | -| label | string | Yes | No | Label of the shortcut. | -| labelId8+ | number | Yes | No | Label ID of the shortcut. | +| label | string | Yes | No | Name of the shortcut. | +| labelId8+ | number | Yes | No | Name ID of the shortcut. | | disableMessage | string | Yes | No | Message displayed when the shortcut is disabled. | -| wants | Array<[ShortcutWant](#shortcutwant)> | Yes | No | Want information required for the shortcut. | +| wants | Array<[ShortcutWant](#shortcutwant)> | Yes | No | Want list for the shortcut. | | isStatic | boolean | Yes | No | Whether the shortcut is static. | | isHomeShortcut | boolean | Yes | No | Whether the shortcut is a home shortcut.| | isEnabled | boolean | Yes | No | Whether the shortcut is enabled. | + + \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-bundle-remoteAbilityInfo.md b/en/application-dev/reference/apis/js-apis-bundle-remoteAbilityInfo.md index ffde8d4356caee1dde9f47bdbb424d2dbdda57bb..f95125fb1c7228f9eade37f423b624c3289c0e34 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-remoteAbilityInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-remoteAbilityInfo.md @@ -8,7 +8,7 @@ The **RemoteAbilityInfo** module provides information about a remote ability. ## RemoteAbilityInfo(deprecated) -> This API is deprecated since API version 9. You are advised to use [RemoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md) instead. +> This API is deprecated since API version 9. You are advised to use [bundleManager-RemoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md) instead. **System capability**: SystemCapability.BundleManager.DistributedBundleFramework @@ -16,6 +16,6 @@ The **RemoteAbilityInfo** module provides information about a remote ability. | Name | Type | Readable| Writable| Description | | ----------- | -------------------------------------------- | ---- | ---- | ----------------------- | -| elementName | [ElementName](js-apis-bundle-ElementName.md) | Yes | No | Element name of the ability. | -| label | string | Yes | No | Label of the ability. | +| elementName | [ElementName](js-apis-bundle-ElementName.md) | Yes | No | Element name information of the ability. | +| label | string | Yes | No | Ability name. | | icon | string | Yes | No | Icon of the ability.| diff --git a/en/application-dev/reference/apis/js-apis-bundleManager-elementName.md b/en/application-dev/reference/apis/js-apis-bundleManager-elementName.md index 6948fac50faf7146b4bc0a8aabfb1eef2d1c719f..662f0e37640287de5e10273a45d8db327a4551da 100644 --- a/en/application-dev/reference/apis/js-apis-bundleManager-elementName.md +++ b/en/application-dev/reference/apis/js-apis-bundleManager-elementName.md @@ -1,6 +1,6 @@ # ElementName -The **ElementName** module provides information about an element name. The information can be obtained through [Context.getElementName](js-apis-Context.md). +The **ElementName** module provides element name information, which can be obtained through [Context.getElementName](js-apis-inner-app-context.md). > **NOTE** diff --git a/en/application-dev/reference/apis/js-apis-bundleManager-shortcutInfo.md b/en/application-dev/reference/apis/js-apis-bundleManager-shortcutInfo.md index 0f1d6b7e992484875d65479a3734b00484141d21..2c06d138b5bfda6383fabc14e28d3fb008af0bf0 100644 --- a/en/application-dev/reference/apis/js-apis-bundleManager-shortcutInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundleManager-shortcutInfo.md @@ -1,10 +1,12 @@ # ShortcutInfo -The **ShortcutInfo** module provides shortcut information defined in the configuration file. For details about the configuration in the FA model, see [config.json](../../quick-start/package-structure.md). For details about the configuration in the stage model, see [Internal Structure of the shortcuts Attribute](../../quick-start/stage-structure.md#internal-structure-of-the-shortcuts-attribute). +The **ShortcutInfo** module defines shortcut information configured in the configuration file. The information can be obtained through [getShortcutInfo](js-apis-launcherBundleManager.md#launcherbundlemanagergetshortcutinfo9). > **NOTE** > > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> For the FA model, the shortcut information is configured in the [config.json](../../quick-start/module-structure.md) file. For details about the shortcut information in the stage model, see [shortcuts](../../quick-start/module-configuration-file.md#shortcuts). ## ShortcutWant @@ -16,7 +18,7 @@ The **ShortcutInfo** module provides shortcut information defined in the configu | ------------------------- | ------ | ---- | ---- | -------------------- | | targetBundle | string | Yes | No | Target bundle name of the shortcut.| | targetModule | string | Yes | No | Target module name of the shortcut. | -| targetAbility | string | Yes | No | Target ability name of the shortcut.| +| targetAbility | string | Yes | No | Target ability name of the shortcut.| ## ShortcutInfo @@ -35,3 +37,5 @@ The **ShortcutInfo** module provides shortcut information defined in the configu | label | string | Yes | No | Label of the shortcut. | | labelId | number | Yes | No | Label ID of the shortcut. | | wants | Array\<[ShortcutWant](#shortcutwant)> | Yes | No | Want information required for the shortcut. | + + \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-bundleManager.md b/en/application-dev/reference/apis/js-apis-bundleManager.md index ef3ef84fab57b0ca3e10e2ea27aede219b2e4e6c..525f882052397b5d59e5d4a22c79dc013c847e6a 100644 --- a/en/application-dev/reference/apis/js-apis-bundleManager.md +++ b/en/application-dev/reference/apis/js-apis-bundleManager.md @@ -1,4 +1,4 @@ -# bundleManager +# @ohos.bundle.bundleManager The **bundleManager** module provides APIs for querying information about bundles, applications, abilities, Extension abilities, and more. @@ -96,10 +96,10 @@ Enumerates the types of Extension abilities. | Name| Value| Description| |:----------------:|:---:|-----| -| FORM | 0 | [FormExtensionAbility](../../ability/stage-formextension.md): provides APIs for widget development.| +| FORM | 0 | [FormExtensionAbility](../../application-models/widget-development-stage.md): provides APIs for widget development.| | WORK_SCHEDULER | 1 | [WorkSchedulerExtensionAbility](../../task-management/work-scheduler-dev-guide.md): enables applications to execute non-real-time tasks when the system is idle.| | INPUT_METHOD | 2 | [InputMethodExtensionAbility](js-apis-inputmethod-extension-ability.md): provides APIs for developing input method applications.| -| SERVICE | 3 | [ServiceExtensionAbility](../../ability/stage-serviceextension.md): enables applications to run in the background and provide services.| +| SERVICE | 3 | [ServiceExtensionAbility](../../application-models/serviceextensionability.md): enables applications to run in the background and provide services.| | ACCESSIBILITY | 4 | [AccessibilityExtensionAbility](js-apis-application-accessibilityExtensionAbility.md): provides accessibility for access to and operations on the UI.| | DATA_SHARE | 5 | [DataShareExtensionAbility](../../database/database-datashare-guidelines.md): enables applications to read and write data.| | FILE_SHARE | 6 | FileShareExtensionAbility: enables file sharing between applications. This ability is reserved.| @@ -2181,8 +2181,8 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 17700002 | The specified moduleName is not existed. | -| 17700003 | The specified abilityName is not existed. | +| 17700002 | The specified moduleName does not exist. | +| 17700003 | The specified abilityName does not exist. | | 17700024 | Failed to get the profile because there is no profile in the HAP. | | 17700026 | The specified bundle is disabled. | | 17700029 | The specified ability is disabled. | @@ -2236,8 +2236,8 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 17700002 | The specified moduleName is not existed. | -| 17700003 | The specified abilityName is not existed. | +| 17700002 | The specified moduleName does not exist. | +| 17700003 | The specified abilityName does not exist. | | 17700024 | Failed to get the profile because there is no profile in the HAP. | | 17700026 | The specified bundle is disabled. | | 17700029 | The specified ability is disabled. | @@ -2299,7 +2299,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 17700002 | The specified moduleName is not existed. | +| 17700002 | The specified moduleName does not exist. | | 17700003 | The specified extensionAbilityName not existed. | | 17700024 | Failed to get the profile because there is no profile in the HAP. | | 17700026 | The specified bundle is disabled. | @@ -2353,7 +2353,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 17700002 | The specified moduleName is not existed. | +| 17700002 | The specified moduleName does not exist. | | 17700003 | The specified extensionAbilityName not existed. | | 17700024 | Failed to get the profile because there is no profile in the HAP. | | 17700026 | The specified bundle is disabled. | @@ -2903,3 +2903,5 @@ try { console.error('getBundleInfoSync failed:' + err.message); } ``` + + \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-bundleMonitor.md b/en/application-dev/reference/apis/js-apis-bundleMonitor.md index ceef9d85218006916a52300887103c838d5bcd56..cf2d7aab46c5d8ea80d49fe66b61ae68e56885a0 100644 --- a/en/application-dev/reference/apis/js-apis-bundleMonitor.md +++ b/en/application-dev/reference/apis/js-apis-bundleMonitor.md @@ -1,4 +1,4 @@ -# Bundle.bundleMonitor +# @ohos.bundle.bundleMonitor The **Bundle.bundleMonitor** module provides APIs for listens for bundle installation, uninstall, and updates. @@ -18,7 +18,7 @@ import bundleMonitor from '@ohos.bundle.bundleMonitor'; | ------------------------------------ | ----------- | ------------------------------ | | ohos.permission.LISTEN_BUNDLE_CHANGE | system_core | Permission to listen for bundle installation, uninstall, and updates.| -For details, see [Permission Levels](../../security/accesstoken-overview.md#permission-levels). +For details, see [Permission Levels](../../security/accesstoken-overview.md). ## BundleChangeInfo @@ -50,10 +50,6 @@ Subscribes to bundle installation, uninstall, and update events. | BundleChangedEvent | string | Yes | Type of the event to subscribe to.| | Callback\ | callback | Yes | Callback used for the subscription.| -**Error codes** - -For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md). - **Example** ```ts @@ -87,10 +83,6 @@ Unsubscribes from bundle installation, uninstall, and update events. | BundleChangedEvent | string | Yes | Type of the event to unsubscribe from. | | Callback\ | callback | Yes | Callback used for the unsubscription. If this parameter is left empty, all callbacks of the current event are unsubscribed from.| -**Error codes** - -For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md). - **Example** ```ts diff --git a/en/application-dev/reference/apis/js-apis-commonEvent.md b/en/application-dev/reference/apis/js-apis-commonEvent.md index 5aaacbe7d104cf965d398240ff8e19468644713b..12fc260b45b0364ae5a4fc1218f45f6f2ed9df44 100644 --- a/en/application-dev/reference/apis/js-apis-commonEvent.md +++ b/en/application-dev/reference/apis/js-apis-commonEvent.md @@ -1,10 +1,10 @@ -# CommonEvent +# @ohos.commonEvent The **CommonEvent** module provides common event capabilities, including the capabilities to publish, subscribe to, and unsubscribe from common events, as well obtaining and setting the common event result code and result data. > **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. +> - The APIs provided by this module are no longer maintained since API version 9. You are advised to use [@ohos.commonEventManager](js-apis-commonEventManager.md). +> - 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. ## Modules to Import @@ -14,7 +14,7 @@ import CommonEvent from '@ohos.commonEvent'; ## Support -Provides the event types supported by the **CommonEvent** module. The name and value indicate the macro and name of a common event, respectively. +The table below lists the event types supported by the **CommonEvent** module. The name and value indicate the macro and name of a common event, respectively. **System capability**: SystemCapability.Notification.CommonEvent @@ -167,8 +167,8 @@ Provides the event types supported by the **CommonEvent** module. The name and v | COMMON_EVENT_ACCOUNT_DELETED | usual.event.data.ACCOUNT_DELETED | ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS | Indicates the common event that the account was deleted. | | COMMON_EVENT_FOUNDATION_READY | usual.event.data.FOUNDATION_READY | ohos.permission.RECEIVER_STARTUP_COMPLETED | Indicates the common event that the foundation is ready. | | COMMON_EVENT_AIRPLANE_MODE_CHANGED | usual.event.AIRPLANE_MODE | - | Indicates the common event that the airplane mode of the device has changed. | -| COMMON_EVENT_SPLIT_SCREEN8+ | usual.event.SPLIT_SCREEN | - | Indicates the common event of screen splitting. | -| COMMON_EVENT_SLOT_CHANGE9+ | usual.event.SLOT_CHANGE | ohos.permission.NOTIFICATION_CONTROLLER | Indicates the common event that the notification slot has changed. | +| COMMON_EVENT_SPLIT_SCREEN8+ | usual.event.SPLIT_SCREEN | - | Indicates the common event of screen splitting. | +| COMMON_EVENT_SLOT_CHANGE9+ | usual.event.SLOT_CHANGE | ohos.permission.NOTIFICATION_CONTROLLER | Indicates the common event that the notification slot has been updated. | | COMMON_EVENT_SPN_INFO_CHANGED 9+ | usual.event.SPN_INFO_CHANGED | - | Indicates the common event that the SPN displayed has been updated. | | COMMON_EVENT_QUICK_FIX_APPLY_RESULT 9+ | usual.event.QUICK_FIX_APPLY_RESULT | - | Indicates the common event that a quick fix is applied to the application. | @@ -192,7 +192,7 @@ Publishes a common event. This API uses an asynchronous callback to return the r ```js // Callback for common event publication -function PublishCallBack(err) { +function publishCallBack(err) { if (err.code) { console.error("publish failed " + JSON.stringify(err)); } else { @@ -201,7 +201,7 @@ function PublishCallBack(err) { } // Publish a common event. -CommonEvent.publish("event", PublishCallBack); +CommonEvent.publish("event", publishCallBack); ``` @@ -234,7 +234,7 @@ let options = { } // Callback for common event publication -function PublishCallBack(err) { +function publishCallBack(err) { if (err.code) { console.error("publish failed " + JSON.stringify(err)); } else { @@ -243,7 +243,7 @@ function PublishCallBack(err) { } // Publish a common event. -CommonEvent.publish("event", options, PublishCallBack); +CommonEvent.publish("event", options, publishCallBack); ``` @@ -270,7 +270,7 @@ Publishes a common event to a specific user. This API uses an asynchronous callb ```js // Callback for common event publication -function PublishAsUserCallBack(err) { +function publishAsUserCallBack(err) { if (err.code) { console.error("publishAsUser failed " + JSON.stringify(err)); } else { @@ -282,7 +282,7 @@ function PublishAsUserCallBack(err) { let userId = 100; // Publish a common event. -CommonEvent.publishAsUser("event", userId, PublishAsUserCallBack); +CommonEvent.publishAsUser("event", userId, publishAsUserCallBack); ``` @@ -317,7 +317,7 @@ let options = { } // Callback for common event publication -function PublishAsUserCallBack(err) { +function publishAsUserCallBack(err) { if (err.code) { console.error("publishAsUser failed " + JSON.stringify(err)); } else { @@ -329,7 +329,7 @@ function PublishAsUserCallBack(err) { let userId = 100; // Publish a common event. -CommonEvent.publishAsUser("event", userId, options, PublishAsUserCallBack); +CommonEvent.publishAsUser("event", userId, options, publishAsUserCallBack); ``` @@ -361,7 +361,7 @@ let subscribeInfo = { }; // Callback for subscriber creation. -function CreateSubscriberCallBack(err, commonEventSubscriber) { +function createSubscriberCallBack(err, commonEventSubscriber) { if (err.code) { console.error("createSubscriber failed " + JSON.stringify(err)); } else { @@ -371,7 +371,7 @@ function CreateSubscriberCallBack(err, commonEventSubscriber) { } // Create a subscriber. -CommonEvent.createSubscriber(subscribeInfo, CreateSubscriberCallBack); +CommonEvent.createSubscriber(subscribeInfo, createSubscriberCallBack); ``` @@ -442,7 +442,7 @@ let subscribeInfo = { }; // Callback for common event subscription. -function SubscribeCallBack(err, data) { +function subscribeCallBack(err, data) { if (err.code) { console.error("subscribe failed " + JSON.stringify(err)); } else { @@ -451,19 +451,19 @@ function SubscribeCallBack(err, data) { } // Callback for subscriber creation. -function CreateSubscriberCallBack(err, commonEventSubscriber) { +function createSubscriberCallBack(err, commonEventSubscriber) { if (err.code) { console.error("createSubscriber failed " + JSON.stringify(err)); } else { console.info("createSubscriber"); subscriber = commonEventSubscriber; // Subscribe to a common event. - CommonEvent.subscribe(subscriber, SubscribeCallBack); + CommonEvent.subscribe(subscriber, subscribeCallBack); } } // Create a subscriber. -CommonEvent.createSubscriber(subscribeInfo, CreateSubscriberCallBack); +CommonEvent.createSubscriber(subscribeInfo, createSubscriberCallBack); ``` @@ -494,7 +494,7 @@ let subscribeInfo = { }; // Callback for common event subscription. -function SubscribeCallBack(err, data) { +function subscribeCallBack(err, data) { if (err.code) { console.info("subscribe failed " + JSON.stringify(err)); } else { @@ -503,19 +503,19 @@ function SubscribeCallBack(err, data) { } // Callback for subscriber creation. -function CreateSubscriberCallBack(err, commonEventSubscriber) { +function createSubscriberCallBack(err, commonEventSubscriber) { if (err.code) { console.info("createSubscriber failed " + JSON.stringify(err)); } else { console.info("createSubscriber"); subscriber = commonEventSubscriber; // Subscribe to a common event. - CommonEvent.subscribe(subscriber, SubscribeCallBack); + CommonEvent.subscribe(subscriber, subscribeCallBack); } } // Callback for common event unsubscription. -function UnsubscribeCallBack(err) { +function unsubscribeCallBack(err) { if (err.code) { console.info("unsubscribe failed " + JSON.stringify(err)); } else { @@ -524,10 +524,10 @@ function UnsubscribeCallBack(err) { } // Create a subscriber. -CommonEvent.createSubscriber(subscribeInfo, CreateSubscriberCallBack); +CommonEvent.createSubscriber(subscribeInfo, createSubscriberCallBack); // Unsubscribe from the common event. -CommonEvent.unsubscribe(subscriber, UnsubscribeCallBack); +CommonEvent.unsubscribe(subscriber, unsubscribeCallBack); ``` ## CommonEventSubscriber @@ -1233,39 +1233,45 @@ subscriber.finishCommonEvent().then(() => { ## CommonEventData +Describes the common event data body. + **System capability**: SystemCapability.Notification.CommonEvent -| Name | Readable| Writable| Type | Description | -| ---------- | ---- | ---- | -------------------- | ------------------------------------------------------- | -| event | Yes | No | string | Name of the common event that is being received. | -| bundleName | Yes | No | string | Bundle name. | -| code | Yes | No | number | Result code of the common event, which is used to transfer data of the int type. | -| data | Yes | No | string | Custom result data of the common event, which is used to transfer data of the string type.| -| parameters | Yes | No | {[key: string]: any} | Additional information about the common event. | +| Name | Type | Readable| Writable| Description | +| ---------- |-------------------- | ---- | ---- | ------------------------------------------------------- | +| event | string | Yes | No | Name of the common event that is being received. | +| bundleName | string | Yes | No | Bundle name. | +| code | number | Yes | No | Result code of the common event, which is used to transfer data of the int type. | +| data | string | Yes | No | Custom result data of the common event, which is used to transfer data of the string type.| +| parameters | {[key: string]: any} | Yes | No | Additional information about the common event. | ## CommonEventPublishData +Describes the data body published by a common event, including the common event content and attributes. + **System capability**: SystemCapability.Notification.CommonEvent -| Name | Readable| Writable| Type | Description | -| --------------------- | ---- | ---- | -------------------- | ---------------------------- | -| bundleName | Yes | No | string | Bundle name. | -| code | Yes | No | number | Result code of the common event. | -| data | Yes | No | string | Custom result data of the common event.| -| subscriberPermissions | Yes | No | Array\ | Permissions required for subscribers to receive the common event. | -| isOrdered | Yes | No | boolean | Whether the common event is an ordered one. | -| isSticky | Yes | No | boolean | Whether the common event is a sticky one. | -| parameters | Yes | No | {[key: string]: any} | Additional information about the common event. | +| Name | Type | Readable| Writable| Description | +| --------------------- | -------------------- | ---- | ---- | ---------------------------- | +| bundleName | string | Yes | No | Bundle name. | +| code | number | Yes | No | Result code of the common event. | +| data | string | Yes | No | Custom result data of the common event.| +| subscriberPermissions | Array\ | Yes | No | Permissions required for subscribers to receive the common event. | +| isOrdered | boolean | Yes | No | Whether the common event is an ordered one. | +| isSticky | boolean | Yes | No | Whether the common event is a sticky one. Only system applications and system services are allowed to send sticky events.| +| parameters | {[key: string]: any} | Yes | No | Additional information about the common event. | ## CommonEventSubscribeInfo +Provides the subscriber information. + **System capability**: SystemCapability.Notification.CommonEvent -| Name | Readable| Writable| Type | Description | -| ------------------- | ---- | ---- | -------------- | ------------------------------------------------------------ | -| events | Yes | No | Array\ | Name of the common event to publish. | -| publisherPermission | Yes | No | string | Permissions required for publishers to publish the common event. | -| publisherDeviceId | Yes | No | string | Device ID. The value must be the ID of an existing device on the same network. | -| userId | Yes | No | number | User ID. The default value is the ID of the current user. If this parameter is specified, the value must be an existing user ID in the system.| -| priority | Yes | No | number | Subscriber priority. The value ranges from -100 to 1000. | +| Name | Type | Readable| Writable| Description | +| ------------------- | -------------- | ---- | ---- | ------------------------------------------------------------ | +| events | Array\ | Yes | No | Name of the common event to publish. | +| publisherPermission | string | Yes | No | Permissions required for publishers to publish the common event. | +| publisherDeviceId | string | Yes | No | Device ID. The value must be the ID of an existing device on the same network. | +| userId | number | Yes | No | User ID. The default value is the ID of the current user. If this parameter is specified, the value must be an existing user ID in the system.| +| priority | number | Yes | No | Subscriber priority. The value ranges from -100 to +1000. | diff --git a/en/application-dev/reference/apis/js-apis-commonEventManager.md b/en/application-dev/reference/apis/js-apis-commonEventManager.md new file mode 100644 index 0000000000000000000000000000000000000000..502603da539a71e465fcfbffb8e69ba696d4e6ea --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-commonEventManager.md @@ -0,0 +1,1353 @@ +# @ohos.commonEventManager + +The **CommonEventManager** module provides common event capabilities, including the capabilities to publish, subscribe to, and unsubscribe from common events, as well obtaining and setting the common event result code and result data. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```ts +import CommonEventManager from '@ohos.commonEventManager'; +``` + +## Support + +The table below lists the event types supported by the **CommonEventManager** module. The name and value indicate the macro and name of a common event, respectively. + +**System capability**: SystemCapability.Notification.CommonEvent + +| Name | Value | Subscriber Permission | Description | +| ------------ | ------------------ | ---------------------- | -------------------- | +| COMMON_EVENT_BOOT_COMPLETED | usual.event.BOOT_COMPLETED | ohos.permission.RECEIVER_STARTUP_COMPLETED | Indicates the common event that the user has finished booting and the system has been loaded. | +| COMMON_EVENT_LOCKED_BOOT_COMPLETED | usual.event.LOCKED_BOOT_COMPLETED | ohos.permission.RECEIVER_STARTUP_COMPLETED | Indicates the common event that the user has finished booting and the system has been loaded but the screen is still locked. | +| COMMON_EVENT_SHUTDOWN | usual.event.SHUTDOWN | - | Indicates the common event that the device is being shut down and the final shutdown will proceed. | +| COMMON_EVENT_BATTERY_CHANGED | usual.event.BATTERY_CHANGED | - | Indicates the common event that the charging state, level, and other information about the battery have changed. | +| COMMON_EVENT_BATTERY_LOW | usual.event.BATTERY_LOW | - | Indicates the common event that the battery level is low. | +| COMMON_EVENT_BATTERY_OKAY | usual.event.BATTERY_OKAY | - | Indicates the common event that the battery exits the low state. | +| COMMON_EVENT_POWER_CONNECTED | usual.event.POWER_CONNECTED | - | Indicates the common event that the device is connected to an external power supply. | +| COMMON_EVENT_POWER_DISCONNECTED | usual.event.POWER_DISCONNECTED | - | Indicates the common event that the device is disconnected from the external power supply. | +| COMMON_EVENT_SCREEN_OFF | usual.event.SCREEN_OFF | - | Indicates the common event that the device screen is off and the device is sleeping. | +| COMMON_EVENT_SCREEN_ON | usual.event.SCREEN_ON | - | Indicates the common event that the device screen is on and the device is in interactive state. | +| COMMON_EVENT_THERMAL_LEVEL_CHANGED | usual.event.THERMAL_LEVEL_CHANGED | - | Indicates the common event that the device's thermal level has changed. | +| COMMON_EVENT_USER_PRESENT | usual.event.USER_PRESENT | - | Indicates the common event that the user unlocks the device. | +| COMMON_EVENT_TIME_TICK | usual.event.TIME_TICK | - | Indicates the common event that the system time has changed. | +| COMMON_EVENT_TIME_CHANGED | usual.event.TIME_CHANGED | - | Indicates the common event that the system time is set. | +| COMMON_EVENT_DATE_CHANGED | usual.event.DATE_CHANGED | - | Indicates the common event that the system time has changed. | +| COMMON_EVENT_TIMEZONE_CHANGED | usual.event.TIMEZONE_CHANGED | - | Indicates the common event that the system time zone has changed. | +| COMMON_EVENT_CLOSE_SYSTEM_DIALOGS | usual.event.CLOSE_SYSTEM_DIALOGS | - | Indicates the common event that a user closes a temporary system dialog box. | +| COMMON_EVENT_PACKAGE_ADDED | usual.event.PACKAGE_ADDED | - | Indicates the common event that a new application package has been installed on the device. | +| COMMON_EVENT_PACKAGE_REPLACED | usual.event.PACKAGE_REPLACED | - | Indicates the common event that a later version of an installed application package has replaced the previous one on the device. | +| COMMON_EVENT_MY_PACKAGE_REPLACED | usual.event.MY_PACKAGE_REPLACED | - | Indicates the common event that a later version of your application package has replaced the previous one. +| COMMON_EVENT_PACKAGE_REMOVED | usual.event.PACKAGE_REMOVED | - | Indicates the common event that an installed application has been uninstalled from the device with the application data retained. | +| COMMON_EVENT_BUNDLE_REMOVED | usual.event.BUNDLE_REMOVED | - | Indicates the common event that an installed bundle has been uninstalled from the device with the application data retained. | +| COMMON_EVENT_PACKAGE_FULLY_REMOVED | usual.event.PACKAGE_FULLY_REMOVED | - | Indicates the common event that an installed application, including both the application data and code, has been completely uninstalled from the device. | +| COMMON_EVENT_PACKAGE_CHANGED | usual.event.PACKAGE_CHANGED | - | Indicates the common event that an application package has been changed (for example, a component in the package has been enabled or disabled). | +| COMMON_EVENT_PACKAGE_RESTARTED | usual.event.PACKAGE_RESTARTED | - | Indicates the common event that the user has restarted the application package and killed all its processes. | +| COMMON_EVENT_PACKAGE_DATA_CLEARED | usual.event.PACKAGE_DATA_CLEARED | - | Indicates the common event that the user has cleared the application package data. | +| COMMON_EVENT_PACKAGE_CACHE_CLEARED9+ | usual.event.PACKAGE_CACHE_CLEARED | - | Indicates the common event that the user has cleared the application package data. | +| COMMON_EVENT_PACKAGES_SUSPENDED | usual.event.PACKAGES_SUSPENDED | - | Indicates the common event that application packages have been suspended. | +| COMMON_EVENT_PACKAGES_UNSUSPENDED | usual.event.PACKAGES_UNSUSPENDED | - | Indicates the common event that application package has not been suspended. | +| COMMON_EVENT_MY_PACKAGE_SUSPENDED | usual.event.MY_PACKAGE_SUSPENDED | - | Indicates the common event that an application package has been suspended. | +| COMMON_EVENT_MY_PACKAGE_UNSUSPENDED | usual.event.MY_PACKAGE_UNSUSPENDED | - | Indicates the common event that application package has not been suspended. | +| COMMON_EVENT_UID_REMOVED | usual.event.UID_REMOVED | - | Indicates the common event that a user ID has been removed from the system. | +| COMMON_EVENT_PACKAGE_FIRST_LAUNCH | usual.event.PACKAGE_FIRST_LAUNCH | - | Indicates the common event that an installed application is started for the first time. | +| COMMON_EVENT_PACKAGE_NEEDS_VERIFICATION | usual.event.PACKAGE_NEEDS_VERIFICATION | - | Indicates the common event that an application requires system verification. | +| COMMON_EVENT_PACKAGE_VERIFIED | usual.event.PACKAGE_VERIFIED | - | Indicates the common event that an application has been verified by the system. | +| COMMON_EVENT_EXTERNAL_APPLICATIONS_AVAILABLE | usual.event.EXTERNAL_APPLICATIONS_AVAILABLE | - | Indicates the common event that applications installed on the external storage become available for the system. | +| COMMON_EVENT_EXTERNAL_APPLICATIONS_UNAVAILABLE | usual.event.EXTERNAL_APPLICATIONS_UNAVAILABLE | - | Indicates the common event that applications installed on the external storage become unavailable for the system. | +| COMMON_EVENT_CONFIGURATION_CHANGED | usual.event.CONFIGURATION_CHANGED | - | Indicates the common event that the device state (for example, orientation and locale) has changed. | +| COMMON_EVENT_LOCALE_CHANGED | usual.event.LOCALE_CHANGED | - | Indicates the common event that the device locale has changed. | +| COMMON_EVENT_MANAGE_PACKAGE_STORAGE | usual.event.MANAGE_PACKAGE_STORAGE | - | Indicates the common event that the device storage is insufficient. | +| COMMON_EVENT_DRIVE_MODE | common.event.DRIVE_MODE | - | Indicates the common event that the system is in driving mode. | +| COMMON_EVENT_HOME_MODE | common.event.HOME_MODE | - | Indicates the common event that the system is in home mode. | +| COMMON_EVENT_OFFICE_MODE | common.event.OFFICE_MODE | - | Indicates the common event that the system is in office mode. | +| COMMON_EVENT_USER_STARTED | usual.event.USER_STARTED | - | Indicates the common event that the user has been started. | +| COMMON_EVENT_USER_BACKGROUND | usual.event.USER_BACKGROUND | - | Indicates the common event that the user has been brought to the background. | +| COMMON_EVENT_USER_FOREGROUND | usual.event.USER_FOREGROUND | - | Indicates the common event that the user has been brought to the foreground. | +| COMMON_EVENT_USER_SWITCHED | usual.event.USER_SWITCHED | ohos.permission.MANAGE_LOCAL_ACCOUNTS | Indicates the common event that user switching is happening. | +| COMMON_EVENT_USER_STARTING | usual.event.USER_STARTING | ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS | Indicates the common event that the user is going to be started. | +| COMMON_EVENT_USER_UNLOCKED | usual.event.USER_UNLOCKED | - | Indicates the common event that the credential-encrypted storage has been unlocked for the current user when the device is unlocked after being restarted. | +| COMMON_EVENT_USER_STOPPING | usual.event.USER_STOPPING | ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS | Indicates the common event that the user is going to be stopped. | +| COMMON_EVENT_USER_STOPPED | usual.event.USER_STOPPED | - | Indicates the common event that the user has been stopped. | +| COMMON_EVENT_DISTRIBUTED_ACCOUNT_LOGIN | usual.event.DISTRIBUTED_ACCOUNT_LOGIN | - | Indicates the action of successful login using a distributed account. | +| COMMON_EVENT_DISTRIBUTED_ACCOUNT_LOGOUT | usual.event.DISTRIBUTED_ACCOUNT_LOGOUT | - | Indicates the action of successful logout of a distributed account. | +| COMMON_EVENT_DISTRIBUTED_ACCOUNT_TOKEN_INVALID | usual.event.DISTRIBUTED_ACCOUNT_TOKEN_INVALID | - | Indicates the action when the token of a distributed account is invalid. | +| COMMON_EVENT_DISTRIBUTED_ACCOUNT_LOGOFF | usual.event.DISTRIBUTED_ACCOUNT_LOGOFF | - | Indicates the action of deregistering a distributed account. | +| COMMON_EVENT_WIFI_POWER_STATE | usual.event.wifi.POWER_STATE | - | Indicates the common event about the Wi-Fi network state, such as enabled and disabled. | +| COMMON_EVENT_WIFI_SCAN_FINISHED | usual.event.wifi.SCAN_FINISHED | ohos.permission.LOCATION | Indicates the common event that the Wi-Fi access point has been scanned and proven to be available. | +| COMMON_EVENT_WIFI_RSSI_VALUE | usual.event.wifi.RSSI_VALUE | ohos.permission.GET_WIFI_INFO | Indicates the common event that the Wi-Fi signal strength (RSSI) has changed. | +| COMMON_EVENT_WIFI_CONN_STATE | usual.event.wifi.CONN_STATE | - | Indicates the common event that the Wi-Fi connection state has changed. | +| COMMON_EVENT_WIFI_HOTSPOT_STATE | usual.event.wifi.HOTSPOT_STATE | - | Indicates the common event about the Wi-Fi hotspot state, such as enabled or disabled. | +| COMMON_EVENT_WIFI_AP_STA_JOIN | usual.event.wifi.WIFI_HS_STA_JOIN | ohos.permission.GET_WIFI_INFO | Indicates the common event that a client has joined the Wi-Fi hotspot of the current device. | +| COMMON_EVENT_WIFI_AP_STA_LEAVE | usual.event.wifi.WIFI_HS_STA_LEAVE | ohos.permission.GET_WIFI_INFO |Indicates the common event that a client has disconnected from the Wi-Fi hotspot of the current device. | +| COMMON_EVENT_WIFI_MPLINK_STATE_CHANGE | usual.event.wifi.mplink.STATE_CHANGE | ohos.permission.MPLINK_CHANGE_STATE | Indicates the common event that the state of MPLINK (an enhanced Wi-Fi feature) has changed. | +| COMMON_EVENT_WIFI_P2P_CONN_STATE | usual.event.wifi.p2p.CONN_STATE_CHANGE | ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION | Indicates the common event that the Wi-Fi P2P connection state has changed. | +| COMMON_EVENT_WIFI_P2P_STATE_CHANGED | usual.event.wifi.p2p.STATE_CHANGE | ohos.permission.GET_WIFI_INFO | Indicates the common event about the Wi-Fi P2P state, such as enabled and disabled. | +| COMMON_EVENT_WIFI_P2P_PEERS_STATE_CHANGED | usual.event.wifi.p2p.DEVICES_CHANGE | ohos.permission.GET_WIFI_INFO | Indicates the common event about the status change of Wi-Fi P2P peer devices. | +| COMMON_EVENT_WIFI_P2P_PEERS_DISCOVERY_STATE_CHANGED | usual.event.wifi.p2p.PEER_DISCOVERY_STATE_CHANGE | ohos.permission.GET_WIFI_INFO | Indicates the common event about the Wi-Fi P2P discovery status change. | +| COMMON_EVENT_WIFI_P2P_CURRENT_DEVICE_STATE_CHANGED | usual.event.wifi.p2p.CURRENT_DEVICE_CHANGE | ohos.permission.GET_WIFI_INFO | Indicates the common event about the status change of the Wi-Fi P2P local device. | +| COMMON_EVENT_WIFI_P2P_GROUP_STATE_CHANGED | usual.event.wifi.p2p.GROUP_STATE_CHANGED | ohos.permission.GET_WIFI_INFO | Indicates the common event that the Wi-Fi P2P group information has changed. | +| COMMON_EVENT_BLUETOOTH_HANDSFREE_AG_CONNECT_STATE_UPDATE | usual.event.bluetooth.handsfree.ag.CONNECT_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event about the connection state of Bluetooth handsfree communication. | +| COMMON_EVENT_BLUETOOTH_HANDSFREE_AG_CURRENT_DEVICE_UPDATE | usual.event.bluetooth.handsfree.ag.CURRENT_DEVICE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the device connected to the Bluetooth handsfree is active. | +| COMMON_EVENT_BLUETOOTH_HANDSFREE_AG_AUDIO_STATE_UPDATE | usual.event.bluetooth.handsfree.ag.AUDIO_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the connection state of Bluetooth A2DP has changed. | +| COMMON_EVENT_BLUETOOTH_A2DPSOURCE_CONNECT_STATE_UPDATE | usual.event.bluetooth.a2dpsource.CONNECT_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event about the connection state of Bluetooth A2DP. | +| COMMON_EVENT_BLUETOOTH_A2DPSOURCE_CURRENT_DEVICE_UPDATE | usual.event.bluetooth.a2dpsource.CURRENT_DEVICE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the device connected using Bluetooth A2DP is active. | +| COMMON_EVENT_BLUETOOTH_A2DPSOURCE_PLAYING_STATE_UPDATE | usual.event.bluetooth.a2dpsource.PLAYING_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the playing state of Bluetooth A2DP has changed. | +| COMMON_EVENT_BLUETOOTH_A2DPSOURCE_AVRCP_CONNECT_STATE_UPDATE | usual.event.bluetooth.a2dpsource.AVRCP_CONNECT_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the AVRCP connection state of Bluetooth A2DP has changed. | +| COMMON_EVENT_BLUETOOTH_A2DPSOURCE_CODEC_VALUE_UPDATE | usual.event.bluetooth.a2dpsource.CODEC_VALUE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the audio codec state of Bluetooth A2DP has changed. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_DISCOVERED | usual.event.bluetooth.remotedevice.DISCOVERED | ohos.permission.LOCATION and ohos.permission.USE_BLUETOOTH | Indicates the common event that a remote Bluetooth device is discovered. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CLASS_VALUE_UPDATE | usual.event.bluetooth.remotedevice.CLASS_VALUE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the Bluetooth class of a remote Bluetooth device has changed. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_ACL_CONNECTED | usual.event.bluetooth.remotedevice.ACL_CONNECTED | ohos.permission.USE_BLUETOOTH | Indicates the common event that a low-ACL connection has been established with a remote Bluetooth device. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_ACL_DISCONNECTED | usual.event.bluetooth.remotedevice.ACL_DISCONNECTED | ohos.permission.USE_BLUETOOTH | Indicates the common event that a low-ACL connection has been disconnected from a remote Bluetooth device. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_NAME_UPDATE | usual.event.bluetooth.remotedevice.NAME_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the friendly name of a remote Bluetooth device is retrieved for the first time or is changed since the last retrieval. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIR_STATE | usual.event.bluetooth.remotedevice.PAIR_STATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the connection state of a remote Bluetooth device has changed. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_BATTERY_VALUE_UPDATE | usual.event.bluetooth.remotedevice.BATTERY_VALUE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the battery level of a remote Bluetooth device is retrieved for the first time or is changed since the last retrieval. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_SDP_RESULT | usual.event.bluetooth.remotedevice.SDP_RESULT | - | Indicates the common event about the SDP state of a remote Bluetooth device. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_UUID_VALUE | usual.event.bluetooth.remotedevice.UUID_VALUE | ohos.permission.DISCOVER_BLUETOOTH | Indicates the common event about the UUID connection state of a remote Bluetooth device. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIRING_REQ | usual.event.bluetooth.remotedevice.PAIRING_REQ | ohos.permission.DISCOVER_BLUETOOTH | Indicates the common event about the pairing request from a remote Bluetooth device. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIRING_CANCEL | usual.event.bluetooth.remotedevice.PAIRING_CANCEL | - | Indicates the common event that Bluetooth pairing is canceled. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_REQ | usual.event.bluetooth.remotedevice.CONNECT_REQ | - | Indicates the common event about the connection request from a remote Bluetooth device. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_REPLY | usual.event.bluetooth.remotedevice.CONNECT_REPLY | - | Indicates the common event about the response to the connection request from a remote Bluetooth device. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_CANCEL | usual.event.bluetooth.remotedevice.CONNECT_CANCEL | - | Indicates the common event that the connection to a remote Bluetooth device has been canceled. | +| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_CONNECT_STATE_UPDATE | usual.event.bluetooth.handsfreeunit.CONNECT_STATE_UPDATE | - | Indicates the common event that the connection state of a Bluetooth handsfree has changed. | +| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AUDIO_STATE_UPDATE | usual.event.bluetooth.handsfreeunit.AUDIO_STATE_UPDATE | - | Indicates the common event that the audio state of a Bluetooth handsfree has changed. | +| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AG_COMMON_EVENT | usual.event.bluetooth.handsfreeunit.AG_COMMON_EVENT | - | Indicates the common event that the audio gateway state of a Bluetooth handsfree has changed. | +| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AG_CALL_STATE_UPDATE | usual.event.bluetooth.handsfreeunit.AG_CALL_STATE_UPDATE | - | Indicates the common event that the calling state of a Bluetooth handsfree has changed. | +| COMMON_EVENT_BLUETOOTH_HOST_STATE_UPDATE | usual.event.bluetooth.host.STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the state of a Bluetooth adapter has been changed, for example, Bluetooth has been enabled or disabled. | +| COMMON_EVENT_BLUETOOTH_HOST_REQ_DISCOVERABLE | usual.event.bluetooth.host.REQ_DISCOVERABLE | - | Indicates the common event about the request for the user to allow Bluetooth device scanning. | +| COMMON_EVENT_BLUETOOTH_HOST_REQ_ENABLE | usual.event.bluetooth.host.REQ_ENABLE | ohos.permission.USE_BLUETOOTH | Indicates the common event about the request for the user to enable Bluetooth. | +| COMMON_EVENT_BLUETOOTH_HOST_REQ_DISABLE | usual.event.bluetooth.host.REQ_DISABLE | ohos.permission.USE_BLUETOOTH | Indicates the common event about the request for the user to disable Bluetooth. | +| COMMON_EVENT_BLUETOOTH_HOST_SCAN_MODE_UPDATE | usual.event.bluetooth.host.SCAN_MODE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the Bluetooth scanning mode of a device has changed. | +| COMMON_EVENT_BLUETOOTH_HOST_DISCOVERY_STARTED | usual.event.bluetooth.host.DISCOVERY_STARTED | ohos.permission.USE_BLUETOOTH | Indicates the common event that the Bluetooth scanning has been started on the device. | +| COMMON_EVENT_BLUETOOTH_HOST_DISCOVERY_FINISHED | usual.event.bluetooth.host.DISCOVERY_FINISHED | ohos.permission.USE_BLUETOOTH | Indicates the common event that the Bluetooth scanning is finished on the device. | +| COMMON_EVENT_BLUETOOTH_HOST_NAME_UPDATE | usual.event.bluetooth.host.NAME_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the Bluetooth adapter name of the device has changed. | +| COMMON_EVENT_BLUETOOTH_A2DPSINK_CONNECT_STATE_UPDATE | usual.event.bluetooth.a2dpsink.CONNECT_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the connection state of Bluetooth A2DP Sink has changed. | +| COMMON_EVENT_BLUETOOTH_A2DPSINK_PLAYING_STATE_UPDATE | usual.event.bluetooth.a2dpsink.PLAYING_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the playing state of Bluetooth A2DP Sink has changed. | +| COMMON_EVENT_BLUETOOTH_A2DPSINK_AUDIO_STATE_UPDATE | usual.event.bluetooth.a2dpsink.AUDIO_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the audio state of Bluetooth A2DP Sink has changed. | +| COMMON_EVENT_NFC_ACTION_ADAPTER_STATE_CHANGED | usual.event.nfc.action.ADAPTER_STATE_CHANGED | - | Indicates the common event that the state of the device's NFC adapter has changed. | +| COMMON_EVENT_NFC_ACTION_RF_FIELD_ON_DETECTED | usual.event.nfc.action.RF_FIELD_ON_DETECTED | ohos.permission.MANAGE_SECURE_SETTINGS | Indicates the action of a common event that the NFC RF field is detected to be in the enabled state. | +| COMMON_EVENT_NFC_ACTION_RF_FIELD_OFF_DETECTED | usual.event.nfc.action.RF_FIELD_OFF_DETECTED | ohos.permission.MANAGE_SECURE_SETTINGS | Indicates the common event that the NFC RF field is detected to be in the disabled state. | +| COMMON_EVENT_DISCHARGING | usual.event.DISCHARGING | - | Indicates the common event that the system stops charging the battery. | +| COMMON_EVENT_CHARGING | usual.event.CHARGING | - | Indicates the common event that the system starts charging the battery. | +| COMMON_EVENT_DEVICE_IDLE_MODE_CHANGED | usual.event.DEVICE_IDLE_MODE_CHANGED | - | Indicates the common event that the system idle mode has changed. | +| COMMON_EVENT_POWER_SAVE_MODE_CHANGED | usual.event.POWER_SAVE_MODE_CHANGED | - | Indicates the common event that the power saving mode of the system has changed. | +| COMMON_EVENT_USER_ADDED | usual.event.USER_ADDED | ohos.permission.MANAGE_LOCAL_ACCOUNTS | Indicates the common event that a user has been added to the system. | +| COMMON_EVENT_USER_REMOVED | usual.event.USER_REMOVED | ohos.permission.MANAGE_LOCAL_ACCOUNTS | Indicates the common event that a user has been removed from the system. | +| COMMON_EVENT_ABILITY_ADDED | usual.event.ABILITY_ADDED | ohos.permission.LISTEN_BUNDLE_CHANGE | Indicates the common event that an ability has been added. | +| COMMON_EVENT_ABILITY_REMOVED | usual.event.ABILITY_REMOVED | ohos.permission.LISTEN_BUNDLE_CHANGE | Indicates the common event that an ability has been removed. | +| COMMON_EVENT_ABILITY_UPDATED | usual.event.ABILITY_UPDATED | ohos.permission.LISTEN_BUNDLE_CHANGE | Indicates the common event that an ability has been updated. | +| COMMON_EVENT_LOCATION_MODE_STATE_CHANGED | usual.event.location.MODE_STATE_CHANGED | - | Indicates the common event that the location mode of the system has changed. | +| COMMON_EVENT_IVI_SLEEP | common.event.IVI_SLEEP | - | Indicates the common event that the in-vehicle infotainment (IVI) system of a vehicle is sleeping. | +| COMMON_EVENT_IVI_PAUSE | common.event.IVI_PAUSE | - | Indicates the common event that the IVI system of a vehicle has entered sleep mode and the playing application is instructed to stop playback. | +| COMMON_EVENT_IVI_STANDBY | common.event.IVI_STANDBY | - | Indicates the common event that a third-party application is instructed to pause the current work. | +| COMMON_EVENT_IVI_LASTMODE_SAVE | common.event.IVI_LASTMODE_SAVE | - | Indicates the common event that a third-party application is instructed to save its last mode. | +| COMMON_EVENT_IVI_VOLTAGE_ABNORMAL | common.event.IVI_VOLTAGE_ABNORMAL | - | Indicates the common event that the voltage of the vehicle's power system is abnormal. | +| COMMON_EVENT_IVI_HIGH_TEMPERATURE | common.event.IVI_HIGH_TEMPERATURE | - | Indicates the common event that the temperature of the IVI system is high. | +| COMMON_EVENT_IVI_EXTREME_TEMPERATURE | common.event.IVI_EXTREME_TEMPERATURE | - | Indicates the common event that the temperature of the IVI system is extremely high. | +| COMMON_EVENT_IVI_TEMPERATURE_ABNORMAL | common.event.IVI_TEMPERATURE_ABNORMAL | - | Indicates the common event that the IVI system has an extreme temperature. | +| COMMON_EVENT_IVI_VOLTAGE_RECOVERY | common.event.IVI_VOLTAGE_RECOVERY | - | Indicates the common event that the voltage of the vehicle's power system is restored to normal. | +| COMMON_EVENT_IVI_TEMPERATURE_RECOVERY | common.event.IVI_TEMPERATURE_RECOVERY | - | Indicates the common event that the temperature of the IVI system is restored to normal. | +| COMMON_EVENT_IVI_ACTIVE | common.event.IVI_ACTIVE | - | Indicates the common event that the battery service is active. | +|COMMON_EVENT_USB_STATE9+ | usual.event.hardware.usb.action.USB_STATE | - | Indicates a common event indicating that the USB device status changes. | +|COMMON_EVENT_USB_PORT_CHANGED9+ | usual.event.hardware.usb.action.USB_PORT_CHANGED | - | Indicates the public event that the USB port status of the user device changes. | +| COMMON_EVENT_USB_DEVICE_ATTACHED | usual.event.hardware.usb.action.USB_DEVICE_ATTACHED | - | Indicates the common event that a USB device has been attached when the user device functions as a USB host. | +| COMMON_EVENT_USB_DEVICE_DETACHED | usual.event.hardware.usb.action.USB_DEVICE_DETACHED | - | Indicates the common event that a USB device has been detached when the user device functions as a USB host. | +| COMMON_EVENT_USB_ACCESSORY_ATTACHED | usual.event.hardware.usb.action.USB_ACCESSORY_ATTACHED | - | Indicates the common event that a USB accessory was attached. | +| COMMON_EVENT_USB_ACCESSORY_DETACHED | usual.event.hardware.usb.action.USB_ACCESSORY_DETACHED | - | Indicates the common event that a USB accessory was detached. | +| COMMON_EVENT_DISK_REMOVED | usual.event.data.DISK_REMOVED | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was removed. | +| COMMON_EVENT_DISK_UNMOUNTED | usual.event.data.DISK_UNMOUNTED | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was unmounted. | +| COMMON_EVENT_DISK_MOUNTED | usual.event.data.DISK_MOUNTED | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was mounted. | +| COMMON_EVENT_DISK_BAD_REMOVAL | usual.event.data.DISK_BAD_REMOVAL | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was removed without being unmounted. | +| COMMON_EVENT_DISK_UNMOUNTABLE | usual.event.data.DISK_UNMOUNTABLE | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device becomes unmountable. | +| COMMON_EVENT_DISK_EJECT | usual.event.data.DISK_EJECT | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was ejected. | +| COMMON_EVENT_VOLUME_REMOVED9+ | usual.event.data.VOLUME_REMOVED | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was removed. | +| COMMON_EVENT_VOLUME_UNMOUNTED9+ | usual.event.data.VOLUME_UNMOUNTED | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was unmounted. | +| COMMON_EVENT_VOLUME_MOUNTED9+ | usual.event.data.VOLUME_MOUNTED | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was mounted. | +| COMMON_EVENT_VOLUME_BAD_REMOVAL9+ | usual.event.data.VOLUME_BAD_REMOVAL | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was removed without being unmounted. | +| COMMON_EVENT_VOLUME_EJECT9+ | usual.event.data.VOLUME_EJECT | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was ejected. | +| COMMON_EVENT_VISIBLE_ACCOUNTS_UPDATED | usual.event.data.VISIBLE_ACCOUNTS_UPDATED | ohos.permission.GET_APP_ACCOUNTS | Indicates the common event that the account visibility changed. | +| COMMON_EVENT_ACCOUNT_DELETED | usual.event.data.ACCOUNT_DELETED | ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS | Indicates the common event that the account was deleted. | +| COMMON_EVENT_FOUNDATION_READY | usual.event.data.FOUNDATION_READY | ohos.permission.RECEIVER_STARTUP_COMPLETED | Indicates the common event that the foundation is ready. | +| COMMON_EVENT_AIRPLANE_MODE_CHANGED | usual.event.AIRPLANE_MODE | - | Indicates the common event that the airplane mode of the device has changed. | +| COMMON_EVENT_SPLIT_SCREEN | usual.event.SPLIT_SCREEN | ohos.permission.RECEIVER_SPLIT_SCREEN | Indicates the common event of screen splitting. | +| COMMON_EVENT_SLOT_CHANGE9+ | usual.event.SLOT_CHANGE | ohos.permission.NOTIFICATION_CONTROLLER | Indicates the common event that the notification slot has been updated. | +| COMMON_EVENT_SPN_INFO_CHANGED 9+ | usual.event.SPN_INFO_CHANGED | - | Indicates the common event that the SPN displayed has been updated. | +| COMMON_EVENT_QUICK_FIX_APPLY_RESULT 9+ | usual.event.QUICK_FIX_APPLY_RESULT | - | Indicates the common event that a quick fix is applied to the application. | + + +## CommonEventManager.publish + +publish(event: string, callback: AsyncCallback\): void + +Publishes a common event. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------------- | +| event | string | Yes | Name of the common event to publish.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** +For details about the error codes, see [Event Error Codes](../errorcodes/errorcode-CommonEventService.md). + +|ID |Error Message | +|-----------|--------------------| +|1500004 |not System services or System app| +|1500007 |message send error| +|1500008 |CEMS error| +|1500009 |system error| + +**Example** + +```ts +// Callback for common event publication +function publishCallBack(err) { + if (err) { + console.error("publish failed " + JSON.stringify(err)); + } else { + console.info("publish"); + } +} + +// Publish a common event. +try { + CommonEventManager.publish("event", publishCallBack); +} catch(err) { + console.error('publish failed, catch error' + JSON.stringify(err)); +} +``` + +## CommonEventManager.publish + +publish(event: string, options: CommonEventPublishData, callback: AsyncCallback\): void + +Publishes a common event with given attributes. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ---------------------- | +| event | string | Yes | Name of the common event to publish. | +| options | [CommonEventPublishData](#commoneventpublishdata) | Yes | Attributes of the common event to publish.| +| callback | syncCallback\ | Yes | Callback used to return the result. | + +**Error codes** +|ID |Error Message | +|-----------|--------------------| +|1500004 |not System services or System app| +|1500007 |message send error| +|1500008 |CEMS error| +|1500009 |system error| + + +**Example** + + +```ts +// Attributes of a common event. +var options = { + code: 0, // Result code of the common event. + data: "initial data";// Result data of the common event. + isOrdered: true // The common event is an ordered one. +} + +// Callback for common event publication +function publishCallBack(err) { + if (err) { + console.error("publish failed " + JSON.stringify(err)); + } else { + console.info("publish"); + } +} + +// Publish a common event. +try { + CommonEventManager.publish("event", options, publishCallBack); +} catch (err) { + console.error('publish failed, catch error' + JSON.stringify(err)); +} +``` + + + +## CommonEventManager.publishAsUser + +publishAsUser(event: string, userId: number, callback: AsyncCallback\): void + +Publishes a common event to a specific user. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------------------------- | +| event | string | Yes | Name of the common event to publish. | +| userId | number | Yes | User ID.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Error codes** +|ID |Error Message | +|-----------|--------------------| +|1500004 |not System services or System app| +|1500007 |message send error| +|1500008 |CEMS error| +|1500009 |system error| + +**Example** + +```ts +// Callback for common event publication +function publishAsUserCallBack(err) { + if (err) { + console.error("publishAsUser failed " + JSON.stringify(err)); + } else { + console.info("publishAsUser"); + } +} + +// Specify the user to whom the common event will be published. +var userId = 100; + +// Publish a common event. +try { + CommonEventManager.publishAsUser("event", userId, publishAsUserCallBack); +} catch (err) { + console.error('publishAsUser failed, catch error' + JSON.stringify(err)); +} +``` + + + +## CommonEventManager.publishAsUser + +publishAsUser(event: string, userId: number, options: CommonEventPublishData, callback: AsyncCallback\): void + +Publishes a common event with given attributes to a specific user. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ---------------------- | +| event | string | Yes | Name of the common event to publish. | +| userId | number | Yes| User ID.| +| options | [CommonEventPublishData](#commoneventpublishdata) | Yes | Attributes of the common event to publish.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Error codes** +|ID |Error Message | +|-----------|--------------------| +|1500004 |not System services or System app| +|1500007 |message send error| +|1500008 |CEMS error| +|1500009 |system error| + +**Example** + + +```ts +// Attributes of a common event. +var options = { + code: 0, // Result code of the common event. + data: "initial data";// Result data of the common event. +} + +// Callback for common event publication +function publishAsUserCallBack(err) { + if (err) { + console.error("publishAsUser failed " + JSON.stringify(err)); + } else { + console.info("publishAsUser"); + } +} + +// Specify the user to whom the common event will be published. +var userId = 100; + +// Publish a common event. +try { + CommonEventManager.publishAsUser("event", userId, options, publishAsUserCallBack); +} catch (err) { + console.error('publishAsUser failed, catch error' + JSON.stringify(err)); +} +``` + + + +## CommonEventManager.createSubscriber + +createSubscriber(subscribeInfo: CommonEventSubscribeInfo, callback: AsyncCallback\): void + +Creates a subscriber. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | ------------------------------------------------------------ | ---- | -------------------------- | +| subscribeInfo | [CommonEventSubscribeInfo](#commoneventsubscribeinfo) | Yes | Subscriber information. | +| callback | AsyncCallback\<[CommonEventSubscriber](#commoneventsubscriber)> | Yes | Callback used to return the result.| + +**Example** + + +```ts +var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. + +// Subscriber information. +var subscribeInfo = { + events: ["event"] +}; + +// Callback for subscriber creation. +function createSubscriberCallBack(err, commonEventSubscriber) { + if(!err) { + console.info("createSubscriber"); + subscriber = commonEventSubscriber; + } else { + console.error("createSubscriber failed " + JSON.stringify(err)); + } +} + +// Create a subscriber. +try { + CommonEventManager.createSubscriber(subscribeInfo, createSubscriberCallBack); +} catch (err) { + console.error('createSubscriber failed, catch error' + JSON.stringify(err)); +} +``` + + + +## CommonEventManager.createSubscriber + +createSubscriber(subscribeInfo: CommonEventSubscribeInfo): Promise\ + +Creates a subscriber. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | ----------------------------------------------------- | ---- | -------------- | +| subscribeInfo | [CommonEventSubscribeInfo](#commoneventsubscribeinfo) | Yes | Subscriber information.| + +**Return value** +| Type | Description | +| --------------------------------------------------------- | ---------------- | +| Promise\<[CommonEventSubscriber](#commoneventsubscriber)> | Promise used to return the subscriber object.| + +**Example** + +```ts +var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. + +// Subscriber information. +var subscribeInfo = { + events: ["event"] +}; + +// Create a subscriber. +try { + CommonEventManager.createSubscriber(subscribeInfo).then((commonEventSubscriber) => { + console.info("createSubscriber"); + subscriber = commonEventSubscriber; +}).catch((err) => { + console.error("createSubscriber failed " + JSON.stringify(err)); +}); +} catch(err) { + console.error('createSubscriber failed, catch error' + JSON.stringify(err)); +} + +``` + + + +## CommonEventManager.subscribe + +subscribe(subscriber: CommonEventSubscriber, callback: AsyncCallback\): void + +Subscribes to common events. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ---------------------------------------------------- | ---- | -------------------------------- | +| subscriber | [CommonEventSubscriber](#commoneventsubscriber) | Yes | Subscriber object. | +| callback | AsyncCallback\<[CommonEventData](#commoneventdata)> | Yes | Callback used to return the result.| + +**Example** + +```ts +// Subscriber information. +var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. + +// Subscriber information. +var subscribeInfo = { + events: ["event"] +}; + +// Callback for common event subscription. +function SubscribeCallBack(err, data) { + if (err.code) { + console.error("subscribe failed " + JSON.stringify(err)); + } else { + console.info("subscribe "); + } +} + +// Callback for subscriber creation. +function createSubscriberCallBack(err, commonEventSubscriber) { + if(!err) { + console.info("createSubscriber"); + subscriber = commonEventSubscriber; + // Subscribe to a common event. + try { + CommonEventManager.subscribe(subscriber, SubscribeCallBack); + } catch (err) { + console.error("createSubscriber failed " + JSON.stringify(err)); + } + } else { + console.error("createSubscriber failed " + JSON.stringify(err)); + } +} + +// Create a subscriber. +try { + CommonEventManager.createSubscriber(subscribeInfo, createSubscriberCallBack); +} catch (err) { + console.error('createSubscriber failed, catch error' + JSON.stringify(err)); +} +``` + + + +## CommonEventManager.unsubscribe + +unsubscribe(subscriber: CommonEventSubscriber, callback?: AsyncCallback\): void + +Unsubscribes from common events. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------------------- | ---- | ------------------------ | +| subscriber | [CommonEventSubscriber](#commoneventsubscriber) | Yes | Subscriber object. | +| callback | AsyncCallback\ | No | Callback used to return the result.| + +**Example** + +```ts +var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. +// Subscriber information. +var subscribeInfo = { + events: ["event"] +}; +// Callback for common event subscription. +function subscribeCallBack(err, data) { + if (err) { + console.info("subscribe failed " + JSON.stringify(err)); + } else { + console.info("subscribe"); + } +} +// Callback for subscriber creation. +function createSubscriberCallBack(err, commonEventSubscriber) { + if (err) { + console.info("createSubscriber failed " + JSON.stringify(err)); + } else { + console.info("createSubscriber"); + subscriber = commonEventSubscriber; + // Subscribe to a common event. + try { + CommonEventManager.subscribe(subscriber, subscribeCallBack); + } catch(err) { + console.info("subscribe failed " + JSON.stringify(err)); + } + } +} +// Callback for common event unsubscription. +function unsubscribeCallBack(err) { + if (err) { + console.info("unsubscribe failed " + JSON.stringify(err)); + } else { + console.info("unsubscribe"); + } +} +// Create a subscriber. +try { + CommonEventManager.createSubscriber(subscribeInfo, createSubscriberCallBack); +} catch (err) { + console.info("createSubscriber failed " + JSON.stringify(err)); +} + +// Unsubscribe from the common event. +try { + CommonEventManager.unsubscribe(subscriber, unsubscribeCallBack); +} catch (err) { + console.info("unsubscribe failed " + JSON.stringify(err)); +} +``` + +## CommonEventSubscriber + +### getCode + +getCode(callback: AsyncCallback\): void + +Obtains the result code of this common event. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ------------------ | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +// Callback for result code obtaining of an ordered common event. +function getCodeCallback(err, Code) { + if (err.code) { + console.error("getCode failed " + JSON.stringify(err)); + } else { + console.info("getCode " + JSON.stringify(Code)); + } +} +subscriber.getCode(getCodeCallback); +``` + +### getCode + +getCode(): Promise\ + +Obtains the result code of this common event. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Return value** + +| Type | Description | +| ---------------- | -------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +subscriber.getCode().then((Code) => { + console.info("getCode " + JSON.stringify(Code)); +}).catch((err) => { + console.error("getCode failed " + JSON.stringify(err)); +}); +``` + +### setCode + +setCode(code: number, callback: AsyncCallback\): void + +Sets the result code for this common event. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------------- | +| code | number | Yes | Result code of the common event. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +// Callback for result code setting of an ordered common event. +function setCodeCallback(err) { + if (err.code) { + console.error("setCode failed " + JSON.stringify(err)); + } else { + console.info("setCode"); + } +} +subscriber.setCode(1, setCodeCallback); +``` + +### setCode + +setCode(code: number): Promise\ + +Sets the result code for this common event. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| code | number | Yes | Result code of the common event.| + +**Return value** + +| Type | Description | +| ---------------- | -------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +subscriber.setCode(1).then(() => { + console.info("setCode"); +}).catch((err) => { + console.error("setCode failed " + JSON.stringify(err)); +}); +``` + +### getData + +getData(callback: AsyncCallback\): void + +Obtains the result data of this common event. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | -------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result data.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +// Callback for result data obtaining of an ordered common event. +function getDataCallback(err, Data) { + if (err.code) { + console.error("getData failed " + JSON.stringify(err)); + } else { + console.info("getData " + JSON.stringify(Data)); + } +} +subscriber.getData(getDataCallback); +``` + +### getData + +getData(): Promise\ + +Obtains the result data of this common event. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Return value** + +| Type | Description | +| ---------------- | ------------------ | +| Promise\ | Promise used to return the result data.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +subscriber.getData().then((Data) => { + console.info("getData " + JSON.stringify(Data)); +}).catch((err) => { + console.error("getData failed " + JSON.stringify(err)); +}); +``` + +### setData + +setData(data: string, callback: AsyncCallback\): void + +Sets the result data for this common event. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | -------------------- | +| data | string | Yes | Result data of the common event. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +// Callback for result data setting of an ordered common event +function setDataCallback(err) { + if (err.code) { + console.error("setData failed " + JSON.stringify(err)); + } else { + console.info("setData"); + } +} +subscriber.setData("publish_data_changed", setDataCallback); +``` + +### setData + +setData(data: string): Promise\ + +Sets the result data for this common event. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------- | +| data | string | Yes | Result data of the common event.| + +**Return value** + +| Type | Description | +| ---------------- | -------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +subscriber.setData("publish_data_changed").then(() => { + console.info("setData"); +}).catch((err) => { + console.error("setData failed " + JSON.stringify(err)); +}); +``` + +### setCodeAndData + +setCodeAndData(code: number, data: string, callback:AsyncCallback\): void + +Sets the result code and result data for this common event. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------------- | +| code | number | Yes | Result code of the common event. | +| data | string | Yes | Result data of the common event. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +// Callback for result code and result data setting of an ordered common event. +function setCodeDataCallback(err) { + if (err.code) { + console.error("setCodeAndData failed " + JSON.stringify(err)); + } else { + console.info("setCodeDataCallback"); + } +} +subscriber.setCodeAndData(1, "publish_data_changed", setCodeDataCallback); +``` + +### setCodeAndData + +setCodeAndData(code: number, data: string): Promise\ + +Sets the result code and result data for this common event. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------- | +| code | number | Yes | Result code of the common event.| +| data | string | Yes | Result data of the common event.| + +**Return value** + +| Type | Description | +| ---------------- | -------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +subscriber.setCodeAndData(1, "publish_data_changed").then(() => { + console.info("setCodeAndData"); +}).catch((err) => { + console.info("setCodeAndData failed " + JSON.stringify(err)); +}); +``` + +### isOrderedCommonEvent + +isOrderedCommonEvent(callback: AsyncCallback\): void + +Checks whether this common event is an ordered one. This API uses an asynchronous callback to return the result. + + + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ---------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. The value **true** means that the common event is an ordered one; and **false** means the opposite.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +// Callback for checking whether the current common event is an ordered one. +function isOrderedCallback(err, isOrdered) { + if (err.code) { + console.error("isOrderedCommonEvent failed " + JSON.stringify(err)); + } else { + console.info("isOrdered " + JSON.stringify(isOrdered)); + } +} +subscriber.isOrderedCommonEvent(isOrderedCallback); +``` + +### isOrderedCommonEvent + +isOrderedCommonEvent(): Promise\ + +Checks whether this common event is an ordered one. This API uses a promise to return the result. + + + +**System capability**: SystemCapability.Notification.CommonEvent + +**Return value** + +| Type | Description | +| ----------------- | -------------------------------- | +| Promise\ | Promise used to return the result. The value **true** means that the common event is an ordered one; and **false** means the opposite.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +subscriber.isOrderedCommonEvent().then((isOrdered) => { + console.info("isOrdered " + JSON.stringify(isOrdered)); +}).catch((err) => { + console.error("isOrdered failed " + JSON.stringify(err)); +}); +``` + +### isStickyCommonEvent + +isStickyCommonEvent(callback: AsyncCallback\): void + +Checks whether this common event is a sticky one. This API uses an asynchronous callback to return the result. + + + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ---------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. The value **true** means that the common event is a sticky one; and **false** means the opposite.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +// Callback for checking whether the current common event is a sticky one. +function isStickyCallback(err, isSticky) { + if (err.code) { + console.error("isStickyCommonEvent failed " + JSON.stringify(err)); + } else { + console.info("isSticky " + JSON.stringify(isSticky)); + } +} +subscriber.isStickyCommonEvent(isStickyCallback); +``` + +### isStickyCommonEvent + +isStickyCommonEvent(): Promise\ + +Checks whether this common event is a sticky one. This API uses a promise to return the result. + + + +**System capability**: SystemCapability.Notification.CommonEvent + +**Return value** + +| Type | Description | +| ----------------- | -------------------------------- | +| Promise\ | Promise used to return the result. The value **true** means that the common event is a sticky one; and **false** means the opposite.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +subscriber.isStickyCommonEvent().then((isSticky) => { + console.info("isSticky " + JSON.stringify(isSticky)); +}).catch((err) => { + console.error("isSticky failed " + JSON.stringify(err)); +}); +``` + +### abortCommonEvent + +abortCommonEvent(callback: AsyncCallback\): void + +Aborts this common event. After the abort, the common event is not sent to the next subscriber. This API takes effect only for ordered common events. It uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | -------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +// Callback for common event aborting. +function abortCallback(err) { + if (err.code) { + console.error("abortCommonEvent failed " + JSON.stringify(err)); + } else { + console.info("abortCommonEvent"); + } +} +subscriber.abortCommonEvent(abortCallback); +``` + +### abortCommonEvent + +abortCommonEvent(): Promise\ + +Aborts this common event. After the abort, the common event is not sent to the next subscriber. This API takes effect only for ordered common events. It uses a promise to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Return value** + +| Type | Description | +| ---------------- | -------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +subscriber.abortCommonEvent().then(() => { + console.info("abortCommonEvent"); +}).catch((err) => { + console.error("abortCommonEvent failed " + JSON.stringify(err)); +}); +``` + +### clearAbortCommonEvent + +clearAbortCommonEvent(callback: AsyncCallback\): void + +Clears the aborted state of this common event. This API takes effect only for ordered common events. It uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | -------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +// Callback for clearing the aborted state of the current common event. +function clearAbortCallback(err) { + if (err.code) { + console.error("clearAbortCommonEvent failed " + JSON.stringify(err)); + } else { + console.info("clearAbortCommonEvent"); + } +} +subscriber.clearAbortCommonEvent(clearAbortCallback); +``` + +### clearAbortCommonEvent + +clearAbortCommonEvent(): Promise\ + +Clears the aborted state of this common event. This API takes effect only for ordered common events. It uses a promise to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Return value** + +| Type | Description | +| ---------------- | -------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +subscriber.clearAbortCommonEvent().then(() => { + console.info("clearAbortCommonEvent"); +}).catch((err) => { + console.error("clearAbortCommonEvent failed " + JSON.stringify(err)); +}); +``` + +### getAbortCommonEvent + +getAbortCommonEvent(callback: AsyncCallback\): void + +Checks whether this common event is in the aborted state. This API takes effect only for ordered common events. It uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ---------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. The value **true** means that the ordered common event is in the aborted state; and **false** means the opposite.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +// Callback for checking whether the current common event is in the aborted state. +function getAbortCallback(err, AbortCommonEvent) { + if (err.code) { + console.error("getAbortCommonEvent failed " + JSON.stringify(err)); + } else { + console.info("AbortCommonEvent " + AbortCommonEvent) + } +} +subscriber.getAbortCommonEvent(getAbortCallback); +``` + +### getAbortCommonEvent + +getAbortCommonEvent(): Promise\ + +Checks whether this common event is in the aborted state. This API takes effect only for ordered common events. It uses a promise to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Return value** + +| Type | Description | +| ----------------- | ---------------------------------- | +| Promise\ | Promise used to return the result. The value **true** means that the ordered common event is in the aborted state; and **false** means the opposite.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +subscriber.getAbortCommonEvent().then((AbortCommonEvent) => { + console.info("AbortCommonEvent " + JSON.stringify(AbortCommonEvent)); +}).catch((err) => { + console.error("getAbortCommonEvent failed " + JSON.stringify(err)); +}); +``` + +### getSubscribeInfo + +getSubscribeInfo(callback: AsyncCallback\): void + +Obtains the subscriber information. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ---------------------- | +| callback | AsyncCallback\<[CommonEventSubscribeInfo](#commoneventsubscribeinfo)> | Yes | Callback used to return the subscriber information.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +// Callback for subscriber information obtaining. +function getSubscribeInfoCallback(err, SubscribeInfo) { + if (err.code) { + console.error("getSubscribeInfo failed " + JSON.stringify(err)); + } else { + console.info("SubscribeInfo " + JSON.stringify(SubscribeInfo)); + } +} +subscriber.getSubscribeInfo(getSubscribeInfoCallback); +``` + +### getSubscribeInfo + +getSubscribeInfo(): Promise\ + +Obtains the subscriber information. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | ---------------------- | +| Promise\<[CommonEventSubscribeInfo](#commoneventsubscribeinfo)> | Promise used to return the subscriber information.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +subscriber.getSubscribeInfo().then((SubscribeInfo) => { + console.info("SubscribeInfo " + JSON.stringify(SubscribeInfo)); +}).catch((err) => { + console.error("getSubscribeInfo failed " + JSON.stringify(err)); +}); +``` + +### finishCommonEvent9+ + +finishCommonEvent(callback: AsyncCallback\): void + +Finishes this ordered common event. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | -------------------------------- | +| callback | AsyncCallback\ | Yes | Callback returned after the ordered common event is finished.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +// Callback for ordered common event finishing. +function finishCommonEventCallback(err) { + if (err.code) { + console.error("finishCommonEvent failed " + JSON.stringify(err)); +} else { + console.info("FinishCommonEvent"); +} +} +subscriber.finishCommonEvent(finishCommonEventCallback); +``` + +### finishCommonEvent9+ + +finishCommonEvent(): Promise\ + +Finishes this ordered common event. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Return value** + +| Type | Description | +| ---------------- | -------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +subscriber.finishCommonEvent().then(() => { + console.info("FinishCommonEvent"); +}).catch((err) => { + console.error("finishCommonEvent failed " + JSON.stringify(err)); +}); +``` + +## CommonEventData + +**System capability**: SystemCapability.Notification.CommonEvent + +| Name | Type | Readable| Writable| Description | +| ---------- |-------------------- | ---- | ---- | ------------------------------------------------------- | +| event | string | Yes | No | Name of the common event that is being received. | +| bundleName | string | Yes | No | Bundle name. | +| code | number | Yes | No | Result code of the common event, which is used to transfer data of the int type. | +| data | string | Yes | No | Custom result data of the common event, which is used to transfer data of the string type.| +| parameters | {[key: string]: any} | Yes | No | Additional information about the common event. | + + +## CommonEventPublishData + +**System capability**: SystemCapability.Notification.CommonEvent + +| Name | Type | Readable| Writable| Description | +| --------------------- | -------------------- | ---- | ---- | ---------------------------- | +| bundleName | string | Yes | No | Bundle name. | +| code | number | Yes | No | Result code of the common event. | +| data | string | Yes | No | Custom result data of the common event.| +| subscriberPermissions | Array\ | Yes | No | Permissions required for subscribers to receive the common event. | +| isOrdered | boolean | Yes | No | Whether the common event is an ordered one. | +| isSticky | boolean | Yes | No | Whether the common event is a sticky one. Only system applications and system services are allowed to send sticky events.| +| parameters | {[key: string]: any} | Yes | No | Additional information about the common event. | + +## CommonEventSubscribeInfo + +**System capability**: SystemCapability.Notification.CommonEvent + +| Name | Type | Readable| Writable| Description | +| ------------------- | -------------- | ---- | ---- | ------------------------------------------------------------ | +| events | Array\ | Yes | No | Name of the common event to publish. | +| publisherPermission | string | Yes | No | Permissions required for publishers to publish the common event. | +| publisherDeviceId | string | Yes | No | Device ID. The value must be the ID of an existing device on the same network. | +| userId | number | Yes | No | User ID. The default value is the ID of the current user. If this parameter is specified, the value must be an existing user ID in the system.| +| priority | number | Yes | No | Subscriber priority. The value ranges from -100 to +1000. | diff --git a/en/application-dev/reference/apis/js-apis-configPolicy.md b/en/application-dev/reference/apis/js-apis-configPolicy.md index 4e541cbfe0022219d9ebf57b0502e82984c84384..af8d2ba8f5fa0aa614d55205d176ce49132f9068 100644 --- a/en/application-dev/reference/apis/js-apis-configPolicy.md +++ b/en/application-dev/reference/apis/js-apis-configPolicy.md @@ -1,4 +1,4 @@ -# Configuration Policy +# @ohos.configPolicy (Configuration Policy) The **configPolicy** module provides APIs for obtaining the custom configuration directory and file path based on the predefined custom configuration level. @@ -24,6 +24,7 @@ For example, if the **config.xml** file is stored in **/system/etc/config.xml** **System capability**: SystemCapability.Customization.ConfigPolicy **Parameters** + | Name | Type | Mandatory | Description | | -------- | --------------------------- | ---- | --------------------- | | relPath | string | Yes | Name of the configuration file. | @@ -50,11 +51,13 @@ Obtains the path of a configuration file with the specified name and highest pri **System capability**: SystemCapability.Customization.ConfigPolicy **Parameters** + | Name | Type | Mandatory | Description | | ------- | ------ | ---- | ----- | | relPath | string | Yes | Name of the configuration file.| **Return value** + | Type | Description | | --------------------- | ------------ | | Promise<string> | Promise used to return the path of the configuration file.| @@ -79,6 +82,7 @@ For example, if the **config.xml** file is stored in **/system/etc/config.xml** **System capability**: SystemCapability.Customization.ConfigPolicy **Parameters** + | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ------------- | | relPath | string | Yes | Name of the configuration file. | @@ -105,11 +109,13 @@ Obtains a list of configuration files with the specified name, sorted in ascendi **System capability**: SystemCapability.Customization.ConfigPolicy **Parameters** + | Name | Type | Mandatory | Description | | ------- | ------ | ---- | ----- | | relPath | string | Yes | Name of the configuration file.| **Return value** + | Type | Description | | ---------------------------------- | ---- | | Promise<Array<string>> | Promise used to return the file list.| @@ -133,6 +139,7 @@ Obtains the list of configuration level directories. This API uses an asynchrono **System capability**: SystemCapability.Customization.ConfigPolicy **Parameters** + | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ----------------- | | callback | AsyncCallback<Array<string>> | Yes | Callback used to return the configuration level directory list.| @@ -158,6 +165,7 @@ Obtains the list of configuration level directories. This API uses a promise to **System capability**: SystemCapability.Customization.ConfigPolicy **Return value** + | Type | Description | | ---------------------------------- | -------- | | Promise<Array<string>> | Promise used to return the configuration level directory list.| diff --git a/en/application-dev/reference/apis/js-apis-defaultAppManager.md b/en/application-dev/reference/apis/js-apis-defaultAppManager.md index 28830ea0737c3243e97dd2a02256b32f54616f6d..dd19bdb98680553ff3f66b3484ab95aa97b5b52d 100644 --- a/en/application-dev/reference/apis/js-apis-defaultAppManager.md +++ b/en/application-dev/reference/apis/js-apis-defaultAppManager.md @@ -1,4 +1,4 @@ -# DefaultAppManager +# @ohos.bundle.defaultAppManager (Default Application Management) The **DefaultAppManager** module provides APIs to query whether the current application is the default application of a specific type. @@ -18,25 +18,25 @@ import defaultAppMgr from '@ohos.bundle.defaultAppManager'; | --------------------------------------- | ----------- | ---------------- | | ohos.permission.GET_DEFAULT_APPLICATION | system_core | Permission related to the default application.| -For details, see in [Permission Levels](../../security/accesstoken-overview.md#permission-levels). +For details, see [Permission Levels](../../security/accesstoken-overview.md#permission-levels). ## defaultAppMgr.ApplicationType -Enumerates the application types. +Enumerates the default application types. **System capability**: SystemCapability.BundleManager.BundleFramework.DefaultApp -| Name | Type | Value | Description | -| -------- | -------- | -------------------------------------- | -------------------------------------- | -| BROWSER | string | Web Browser | Default browser. | -| IMAGE | string | Image Gallery | Default image viewer. | -| AUDIO | string | Audio Player | Default audio player. | -| VIDEO | string | Video Player | Default video player. | -| PDF | string | PDF Viewer | Default PDF reader. | -| WORD | string | Word Viewer | Default Word viewer. | -| EXCEL | string | Excel Viewer | Default Excel viewer. | -| PPT | string | PPT Viewer | Default PowerPoint viewer. | +| Name | Value| Description | +| -------- | -------------------------------------- | -------------------------------------- | +| BROWSER | "Web Browser" | Default browser. | +| IMAGE | "Image Gallery" | Default image viewer. | +| AUDIO | "Audio Player" | Default audio player. | +| VIDEO | "Video Player" | Default video player. | +| PDF | "PDF Viewer" | Default PDF reader. | +| WORD | "Word Viewer" | Default Word viewer. | +| EXCEL | "Excel Viewer" | Default Excel viewer. | +| PPT | "PPT Viewer" | Default PowerPoint viewer. | ## defaultAppMgr.isDefaultApplication @@ -58,10 +58,6 @@ Checks whether this application is the default application of a system-defined a | ------------------------- | ------------------ | | Promise\ | Promise used to return the result. If the application is the default application, `true` is returned; otherwise, `false` is returned.| -**Error codes** - -For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md). - **Example** @@ -90,13 +86,9 @@ Checks whether this application is the default application of a system-defined a | type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#defaultappmgrapplicationtype). | | callback | AsyncCallback\ | Yes | Callback used to return the result. If the application is the default application, `true` is returned; otherwise, `false` is returned.| -**Error codes** - -For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md). - **Example** -```js +```ts import defaultAppMgr from '@ohos.bundle.defaultAppManager'; defaultAppMgr.isDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, (err, data) => { if (err) { @@ -144,7 +136,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** -```js +```ts import defaultAppMgr from '@ohos.bundle.defaultAppManager'; defaultAppMgr.getDefaultApplication(defaultAppMgr.ApplicationType.BROWSER) .then((data) => { @@ -195,7 +187,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** -```js +```ts import defaultAppMgr from '@ohos.bundle.defaultAppManager'; let userId = 100; defaultAppMgr.getDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, userId, (err, data) => { @@ -246,7 +238,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** -```js +```ts import defaultAppMgr from '@ohos.bundle.defaultAppManager'; defaultAppMgr.getDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, (err, data) => { if (err) { @@ -302,7 +294,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** -```js +```ts import defaultAppMgr from '@ohos.bundle.defaultAppManager'; defaultAppMgr.setDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, { bundleName: "com.test.app", @@ -369,7 +361,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** -```js +```ts import defaultAppMgr from '@ohos.bundle.defaultAppManager'; let userId = 100; defaultAppMgr.setDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, { @@ -486,7 +478,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** -```js +```ts import defaultAppMgr from '@ohos.bundle.defaultAppManager'; let userId = 100; defaultAppMgr.resetDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, userId) @@ -537,7 +529,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** -```js +```ts import defaultAppMgr from '@ohos.bundle.defaultAppManager'; let userId = 100; defaultAppMgr.resetDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, userId, (err, data) => { diff --git a/en/application-dev/reference/apis/js-apis-deque.md b/en/application-dev/reference/apis/js-apis-deque.md index 594984e1deb513a21c165c04d0d7d95a918a8766..e295a1cf9c72875727705c131b4342868daff54a 100644 --- a/en/application-dev/reference/apis/js-apis-deque.md +++ b/en/application-dev/reference/apis/js-apis-deque.md @@ -1,4 +1,4 @@ -# Linear Container Deque +# @ohos.util.Deque (Linear Container Deque) > **NOTE** > @@ -51,11 +51,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let deque = new Deque(); -try { - let deque2 = Deque(); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### insertFront @@ -91,11 +86,6 @@ deque.insertFront(b); let c = {name : "Dylon", age : "13"}; deque.insertFront(c); deque.insertFront(false); -try { - deque.insertFront.bind({}, "b")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### insertEnd @@ -131,11 +121,6 @@ deque.insertEnd(b); let c = {name : "Dylon", age : "13"}; deque.insertEnd(c); deque.insertEnd(false); -try { - deque.insertEnd.bind({}, "b")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### has @@ -173,11 +158,6 @@ let deque = new Deque(); let result = deque.has("squirrel"); deque.insertFront("squirrel"); let result1 = deque.has("squirrel"); -try { - deque.has.bind({}, "b")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### popFirst @@ -212,11 +192,6 @@ deque.insertEnd(5); deque.insertFront(2); deque.insertFront(4); let result = deque.popFirst(); -try { - deque.popFirst.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### popLast @@ -251,16 +226,11 @@ deque.insertFront(5); deque.insertFront(2); deque.insertFront(4); let result = deque.popLast(); -try { - deque.popLast.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### forEach -forEach(callbackfn: (value: T, index?: number, deque?: Deque<T>) => void, +forEach(callbackFn: (value: T, index?: number, deque?: Deque<T>) => void, thisArg?: Object): void Uses a callback to traverse the elements in this container and obtain their position indexes. @@ -271,7 +241,7 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| +| callbackFn | function | Yes| Callback invoked to traverse the elements in the container.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -301,13 +271,6 @@ deque.insertEnd(4); deque.forEach((value, index) => { console.log("value:" + value, index); }); -try { - deque.forEach.bind({}, (value, index) => { - console.log("value:" + value, index); - })(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### getFirst @@ -341,11 +304,6 @@ deque.insertEnd(4); deque.insertFront(5); deque.insertFront(4); let result = deque.getFirst(); -try { - deque.getFirst.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### getLast @@ -379,11 +337,6 @@ deque.insertFront(4); deque.insertFront(5); deque.insertFront(4); let result = deque.getLast(); -try { - deque.getLast.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### [Symbol.iterator] @@ -428,9 +381,4 @@ while(temp != undefined) { console.log("value:" + temp); temp = iter.next().value; } -try { - deque[Symbol.iterator].bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` diff --git a/en/application-dev/reference/apis/js-apis-distributedBundle.md b/en/application-dev/reference/apis/js-apis-distributedBundle.md index 98a15d818444aac4bd9c57e0eb270c7a3c36fbe0..2ddd4b91388067d0b301f8d7ba26bbf748eb15cb 100644 --- a/en/application-dev/reference/apis/js-apis-distributedBundle.md +++ b/en/application-dev/reference/apis/js-apis-distributedBundle.md @@ -1,4 +1,4 @@ -# distributedBundle +# @ohos.bundle.distributedBundle The **distributedBundle** module provides APIs for managing distributed bundles. diff --git a/en/application-dev/reference/apis/js-apis-emitter.md b/en/application-dev/reference/apis/js-apis-emitter.md index 0bc6f9c6a4c156cfa2d604885572fcbe4bdc41bc..a072663e8c5cf3f667860cd72d1ef50c2bb72334 100644 --- a/en/application-dev/reference/apis/js-apis-emitter.md +++ b/en/application-dev/reference/apis/js-apis-emitter.md @@ -1,4 +1,4 @@ -# Emitter +# @ohos.events.emitter The **Emitter** module provides APIs for sending and processing in-process events, including the APIs for processing events that are subscribed to in persistent or one-shot manner, unsubscribing from events, and emitting events to the event queue. diff --git a/en/application-dev/reference/apis/js-apis-freeInstall.md b/en/application-dev/reference/apis/js-apis-freeInstall.md index 44ecb706ffc98b8f7937574d3ab18812b76abece..94ab3e8ac8cad4c8a41a4820741e595535f388a3 100644 --- a/en/application-dev/reference/apis/js-apis-freeInstall.md +++ b/en/application-dev/reference/apis/js-apis-freeInstall.md @@ -1,4 +1,4 @@ -# Bundle.freeInstall +# @ohos.bundle.freeInstall The **Bundle.freeInstall** module provides APIs for setting and obtaining installation-free information and APIs for obtaining **BundlePackInfo** and **DispatchInfo**. diff --git a/en/application-dev/reference/apis/js-apis-hashmap.md b/en/application-dev/reference/apis/js-apis-hashmap.md index f3deddcc499cfa9cb3b32c5b3951664dfa3d44cb..d8da0f628f90a5090e9b2ccf0576b6ffb03ff69d 100644 --- a/en/application-dev/reference/apis/js-apis-hashmap.md +++ b/en/application-dev/reference/apis/js-apis-hashmap.md @@ -1,4 +1,4 @@ -# Nonlinear Container HashMap +# @ohos.util.HashMap (Nonlinear Container HashMap) > **NOTE** > @@ -53,11 +53,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let hashMap = new HashMap(); -try { - let hashMap2 = HashMap(); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -88,11 +83,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts const hashMap = new HashMap(); let result = hashMap.isEmpty(); -try { - hashMap.isEmpty.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -131,11 +121,6 @@ let hashMap = new HashMap(); let result = hashMap.hasKey("squirrel"); hashMap.set("squirrel", 123); let result1 = hashMap.hasKey("squirrel"); -try { - hashMap.hasKey.bind({}, "squirrel")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -174,11 +159,6 @@ let hashMap = new HashMap(); let result = hashMap.hasValue(123); hashMap.set("squirrel", 123); let result1 = hashMap.hasValue(123); -try { - hashMap.hasValue.bind({}, 123)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -217,11 +197,6 @@ let hashMap = new HashMap(); hashMap.set("squirrel", 123); hashMap.set("sparrow", 356); let result = hashMap.get("sparrow"); -try { - hashMap.get.bind({}, "sparrow")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -255,11 +230,6 @@ hashMap.set("squirrel", 123); hashMap.set("sparrow", 356); let newHashMap = new HashMap(); hashMap.setAll(newHashMap); -try { - hashMap.setAll.bind({}, newHashMap)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -297,11 +267,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let hashMap = new HashMap(); let result = hashMap.set("squirrel", 123); -try { - hashMap.set.bind({}, "squirrel", 123)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -340,11 +305,6 @@ let hashMap = new HashMap(); hashMap.set("squirrel", 123); hashMap.set("sparrow", 356); let result = hashMap.remove("sparrow"); -try { - hashMap.remove.bind({}, "sparrow")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -371,11 +331,6 @@ let hashMap = new HashMap(); hashMap.set("squirrel", 123); hashMap.set("sparrow", 356); hashMap.clear(); -try { - hashMap.clear.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -413,11 +368,6 @@ while(temp != undefined) { console.log("value:" + temp); temp = iter.next().value; } -try { - hashMap.keys.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -455,11 +405,6 @@ while(temp != undefined) { console.log("value:" + temp); temp = iter.next().value; } -try { - hashMap.values.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -498,17 +443,12 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er let hashMap = new HashMap(); hashMap.set("sparrow", 123); let result = hashMap.replace("sparrow", 357); -try { - hashMap.replace.bind({}, "sparrow", 357)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### forEach -forEach(callbackfn: (value?: V, key?: K, map?: HashMap) => void, thisArg?: Object): void +forEach(callbackFn: (value?: V, key?: K, map?: HashMap) => void, thisArg?: Object): void Uses a callback to traverse the elements in this container and obtain their position indexes. @@ -518,7 +458,7 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| +| callbackFn | function | Yes| Callback invoked to traverse the elements in the container.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -545,13 +485,6 @@ hashMap.set("gull", 357); hashMap.forEach((value, key) => { console.log("value:" + value, key); }); -try { - hashMap.forEach.bind({}, (value, key) => { - console.log("value:" + value, key); - })(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -590,11 +523,6 @@ while(temp != undefined) { console.log("value:" + temp[1]); temp = iter.next().value; } -try { - hashMap.entries.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -621,6 +549,7 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er | 10200011 | The Symbol.iterator method cannot be bound. | **Example** + ```ts let hashMap = new HashMap(); hashMap.set("squirrel", 123); @@ -640,9 +569,4 @@ while(temp != undefined) { console.log("value:" + temp[1]); temp = iter.next().value; } -try { - hashMap[Symbol.iterator].bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` diff --git a/en/application-dev/reference/apis/js-apis-hashset.md b/en/application-dev/reference/apis/js-apis-hashset.md index 09cd4c914ad0c512f65f7ad05c1552ef6b29f90a..2c52b1268a1ee4d61f3c89c26949823baa28e566 100644 --- a/en/application-dev/reference/apis/js-apis-hashset.md +++ b/en/application-dev/reference/apis/js-apis-hashset.md @@ -1,4 +1,4 @@ -# Nonlinear Container HashSet +# @ohos.util.HashSet (Nonlinear Container HashSet) > **NOTE** > @@ -61,11 +61,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let hashSet = new HashSet(); -try { - let hashSet2 = HashSet(); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -96,11 +91,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts const hashSet = new HashSet(); let result = hashSet.isEmpty(); -try { - hashSet.isEmpty.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -139,11 +129,6 @@ let hashSet = new HashSet(); let result = hashSet.has("squirrel"); hashSet.add("squirrel"); let result1 = hashSet.has("squirrel"); -try { - hashSet.has.bind({}, "squirrel")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -180,11 +165,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let hashSet = new HashSet(); let result = hashSet.add("squirrel"); -try { - hashSet.add.bind({}, "squirrel")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -223,11 +203,6 @@ let hashSet = new HashSet(); hashSet.add("squirrel"); hashSet.add("sparrow"); let result = hashSet.remove("sparrow"); -try { - hashSet.remove.bind({}, "sparrow")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -254,11 +229,6 @@ let hashSet = new HashSet(); hashSet.add("squirrel"); hashSet.add("sparrow"); hashSet.clear(); -try { - hashSet.remove.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -296,17 +266,12 @@ while(temp != undefined) { console.log("value:" + temp); temp = iter.next().value; } -try { - hashSet.values.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### forEach -forEach(callbackfn: (value?: T, key?: T, set?: HashSet<T>) => void, thisArg?: Object): void +forEach(callbackFn: (value?: T, key?: T, set?: HashSet<T>) => void, thisArg?: Object): void Uses a callback to traverse the elements in this container and obtain their position indexes. @@ -316,7 +281,7 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| +| callbackFn | function | Yes| Callback invoked to traverse the elements in the container.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -324,7 +289,7 @@ callbackfn | -------- | -------- | -------- | -------- | | value | T | No| Value of the element that is currently traversed.| | key | T | No| Key of the element that is currently traversed (same as **value**).| -| set | HashSet<T> | No| Instance that invokes the **forEach** method.| +| set | HashSet<T> | No| Instance that invokes the **forEach** API.| **Error codes** @@ -343,13 +308,6 @@ hashSet.add("squirrel"); hashSet.forEach((value, key) => { console.log("value:" + value, key); }); -try { - hashSet.forEach.bind({}, (value, key) => { - console.log("value:" + value, key); - })(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -387,11 +345,6 @@ while(temp != undefined) { console.log("value:" + temp[1]); temp = iter.next().value; } -try { - hashSet.entries.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -436,9 +389,4 @@ while(temp != undefined) { console.log("value: " + temp); temp = iter.next().value; } -try { - hashSet[Symbol.iterator].bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` diff --git a/en/application-dev/reference/apis/js-apis-installer.md b/en/application-dev/reference/apis/js-apis-installer.md index 557e655b82ab9195e2217b69ed68e8d5de0ef534..0c3651fc6add2e830f9a8e3eeb5ccabddb122e2e 100644 --- a/en/application-dev/reference/apis/js-apis-installer.md +++ b/en/application-dev/reference/apis/js-apis-installer.md @@ -1,9 +1,8 @@ -# BundleInstaller +# @ohos.bundle.installer -The **BundleInstaller** module provides APIs for you to install, uninstall, and recover bundles on devices. +The **bundle.installer** module provides APIs for you to install, uninstall, and recover bundles on devices. > **NOTE** -> > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-keycode.md b/en/application-dev/reference/apis/js-apis-keycode.md index dd4ac0b22afb7e0101579db5b6d639504f58197d..6680ea14f2ea3daa0d9144013469cf094c4904d2 100644 --- a/en/application-dev/reference/apis/js-apis-keycode.md +++ b/en/application-dev/reference/apis/js-apis-keycode.md @@ -8,7 +8,7 @@ The Keycode module provides keycodes for a key device. ## Modules to Import ```js -import {KeyCode} from '@ohos.multimodalInput.keyCode' +import {KeyCode} from '@ohos.multimodalInput.keyCode'; ``` ## KeyCode diff --git a/en/application-dev/reference/apis/js-apis-keyevent.md b/en/application-dev/reference/apis/js-apis-keyevent.md index 33d9daa72dd0c570d04d11b5eedf16f96e37dc7c..3cfb2440033aa8043801e986ade5b0bd28c475d3 100644 --- a/en/application-dev/reference/apis/js-apis-keyevent.md +++ b/en/application-dev/reference/apis/js-apis-keyevent.md @@ -1,6 +1,6 @@ # Key Event -Represents key events reported by an input device. +The Key Event module provides key events reported by an input device. > **NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-launcherBundleManager.md b/en/application-dev/reference/apis/js-apis-launcherBundleManager.md index f149c30d7a93f9adaaa68c03edea7426a8882531..505c29ae0ef6cc18404767eaa4a4b4ac88296651 100644 --- a/en/application-dev/reference/apis/js-apis-launcherBundleManager.md +++ b/en/application-dev/reference/apis/js-apis-launcherBundleManager.md @@ -1,6 +1,6 @@ -# Bundle.launcherBundleManager +# @ohos.bundle.launcherBundleManager -The **Bundle.launcherBundleManager** module providers APIs for the **Home Screen** application to obtain the launcher ability information and shortcut information. +The **bundle.launcherBundleManager** module providers APIs for the **Home Screen** application to obtain the launcher ability information and shortcut information. > **NOTE** > @@ -27,7 +27,7 @@ Obtains the launcher ability information based on the given bundle name and user **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ---------- | ------ | ---- | -------------- | | bundleName | string | Yes | Bundle name of the application.| | userId | number | Yes | User ID.| @@ -78,7 +78,7 @@ Obtains the launcher ability information based on the given bundle name and user **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ---------- | ------ | ---- | -------------- | | bundleName | string | Yes | Bundle name of the application.| | userId | number | Yes | User ID.| @@ -128,7 +128,7 @@ Obtains the launcher ability information of all applications based on the given **Parameters** -| Name| Type | Mandatory| Description | +| Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------- | | userId | number | Yes | User ID.| @@ -176,7 +176,7 @@ Obtains the launcher ability information of all applications based on the given **Parameters** -| Name| Type | Mandatory| Description | +| Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------- | | userId | number | Yes | User ID.| @@ -222,7 +222,7 @@ Obtains the shortcut information of the current user based on the given bundle n **System capability**: SystemCapability.BundleManager.BundleFramework.Launcher -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ---------- | ------ | ---- | -------------- | | bundleName | string | Yes | Bundle name of the application.| @@ -269,13 +269,13 @@ Obtains the shortcut information of the current user based on the given bundle n **System capability**: SystemCapability.BundleManager.BundleFramework.Launcher -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ---------- | ------ | ---- | -------------- | | bundleName | string | Yes | Bundle name of the application.| **Return value** -| Template | Description | +| Type | Description | | ---------------------- | ----------------------------------------------- | | Promise\> | Promise used to return the **ShortcutInfo** object obtained.| diff --git a/en/application-dev/reference/apis/js-apis-lightweightmap.md b/en/application-dev/reference/apis/js-apis-lightweightmap.md index f2ab94b72b0538f83cd21642081172cfb19b3cb1..1e966a2b659551a35649c3c087330e7d3059e182 100644 --- a/en/application-dev/reference/apis/js-apis-lightweightmap.md +++ b/en/application-dev/reference/apis/js-apis-lightweightmap.md @@ -1,4 +1,4 @@ -# Nonlinear Container LightWeightMap +# @ohos.util.LightWeightMap (Nonlinear Container LightWeightMap) > **NOTE** > @@ -54,11 +54,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let lightWeightMap = new LightWeightMap(); -try { - let lightWeightMap2 = LightWeightMap(); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -89,11 +84,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts const lightWeightMap = new LightWeightMap(); let result = lightWeightMap.isEmpty(); -try { - lightWeightMap.isEmpty.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -134,11 +124,6 @@ lightWeightMap.set("sparrow", 356); let map = new LightWeightMap(); map.set("sparrow", 356); let result = lightWeightMap.hasAll(map); -try { - lightWeightMap.hasAll.bind({}, map)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -178,11 +163,6 @@ let result = lightWeightMap.hasKey; lightWeightMap.hasKey("squirrel"); lightWeightMap.set("squirrel", 123); let result1 = lightWeightMap.hasKey("squirrel"); -try { - lightWeightMap.hasKey.bind({}, "squirrel")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -221,11 +201,6 @@ let lightWeightMap = new LightWeightMap(); let result = lightWeightMap.hasValue(123); lightWeightMap.set("squirrel", 123); let result1 = lightWeightMap.hasValue(123); -try { - lightWeightMap.hasValue.bind({}, 123)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -256,11 +231,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let lightWeightMap = new LightWeightMap(); lightWeightMap.increaseCapacityTo(10); -try { - lightWeightMap.increaseCapacityTo.bind({}, 10)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -299,11 +269,6 @@ let lightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); let result = lightWeightMap.get("sparrow"); -try { - lightWeightMap.get.bind({}, "sparrow")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -342,11 +307,6 @@ let lightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); let result = lightWeightMap.getIndexOfKey("sparrow"); -try { - lightWeightMap.getIndexOfKey.bind({}, "sparrow")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -385,11 +345,6 @@ let lightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); let result = lightWeightMap.getIndexOfValue(123); -try { - lightWeightMap.getIndexOfValue.bind({}, 123)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -420,7 +375,7 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er | ID| Error Message| | -------- | -------- | | 10200011 | The getKeyAt method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The parameter value is out of range. | **Example** @@ -429,16 +384,6 @@ let lightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); let result = lightWeightMap.getKeyAt(1); -try { - lightWeightMap.getKeyAt.bind({}, 1)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - lightWeightMap.getKeyAt(6)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -472,11 +417,6 @@ lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); let map = new LightWeightMap(); lightWeightMap.setAll(map); -try { - lightWeightMap.setAll.bind({}, map)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -513,11 +453,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let lightWeightMap = new LightWeightMap(); let result = lightWeightMap.set("squirrel", 123); -try { - lightWeightMap.set.bind({}, "squirrel", 123)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -556,11 +491,6 @@ let lightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); lightWeightMap.remove("sparrow"); -try { - lightWeightMap.remove.bind({}, "sparrow")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -599,11 +529,6 @@ let lightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); let result = lightWeightMap.removeAt(1); -try { - lightWeightMap.removeAt.bind({}, 1)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -635,7 +560,7 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er | ID| Error Message| | -------- | -------- | | 10200011 | The setValueAt method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The parameter value is out of range. | **Example** @@ -644,16 +569,6 @@ let lightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); lightWeightMap.setValueAt(1, 3546); -try { - lightWeightMap.setValueAt.bind({}, 1, 3546)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - lightWeightMap.setValueAt(6, 3546); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -684,7 +599,7 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er | ID| Error Message| | -------- | -------- | | 10200011 | The getValueAt method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The parameter value is out of range. | **Example** @@ -693,16 +608,6 @@ let lightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); let result = lightWeightMap.getValueAt(1); -try { - lightWeightMap.getValueAt.bind({}, 1)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - lightWeightMap.getValueAt(6); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -729,11 +634,6 @@ let lightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); lightWeightMap.clear(); -try { - lightWeightMap.clear.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -771,11 +671,6 @@ while(temp != undefined) { console.log("value:" + temp); temp = iter.next().value; } -try { - lightWeightMap.keys.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -813,17 +708,12 @@ while(temp != undefined) { console.log("value:" + temp); temp = iter.next().value; } -try { - lightWeightMap.values.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### forEach -forEach(callbackfn: (value?: V, key?: K, map?: LightWeightMap) => void, thisArg?: Object): void +forEach(callbackFn: (value?: V, key?: K, map?: LightWeightMap) => void, thisArg?: Object): void Uses a callback to traverse the elements in this container and obtain their position indexes. @@ -833,7 +723,7 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| +| callbackFn | function | Yes| Callback invoked to traverse the elements in the container.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -860,13 +750,6 @@ lightWeightMap.set("gull", 357); lightWeightMap.forEach((value, key) => { console.log("value:" + value, key); }); -try { - lightWeightMap.forEach.bind({}, (value, key) => { - console.log("value:" + value, key); - })(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -905,11 +788,6 @@ while(temp != undefined) { console.log("value:" + temp[1]); temp = iter.next().value; } -try { - lightWeightMap.entries.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### toString @@ -941,11 +819,6 @@ let lightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); let iter = lightWeightMap.toString(); -try { - lightWeightMap.toString.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### [Symbol.iterator] @@ -991,9 +864,4 @@ while(temp != undefined) { console.log("value:" + temp[1]); temp = iter.next().value; } -try { - lightWeightMap[Symbol.iterator].bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` diff --git a/en/application-dev/reference/apis/js-apis-lightweightset.md b/en/application-dev/reference/apis/js-apis-lightweightset.md index f5cfbde6cb11daf8884e3c5cf5818fbccc9475a6..0953c12b1a012870147f5be3481de8cd28f9edd6 100644 --- a/en/application-dev/reference/apis/js-apis-lightweightset.md +++ b/en/application-dev/reference/apis/js-apis-lightweightset.md @@ -1,4 +1,4 @@ -# Nonlinear Container LightWeightSet +# @ohos.util.LightWeightSet (Nonlinear Container LightWeightSet) > **NOTE** > @@ -23,8 +23,6 @@ This topic uses the following to identify the use of generics: import LightWeightSet from '@ohos.util.LightWeightSet'; ``` - - ## LightWeightSet ### Attributes @@ -56,11 +54,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let lightWeightSet = new LightWeightSet(); -try { - let lightWeightSet2 = LightWeightSet(); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -91,11 +84,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts const lightWeightSet = new LightWeightSet(); let result = lightWeightSet.isEmpty(); -try { - lightWeightSet.isEmpty.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### add @@ -131,11 +119,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let lightWeightSet = new LightWeightSet(); let result = lightWeightSet.add("squirrel"); -try { - lightWeightSet.add.bind({}, "squirrel")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -170,11 +153,6 @@ lightWeightSet.add("sparrow"); let set = new LightWeightSet(); set.add("gull"); let result = lightWeightSet.addAll(set); -try { - lightWeightSet.addAll.bind({}, set)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -215,11 +193,6 @@ lightWeightSet.add("sparrow"); let set = new LightWeightSet(); set.add("sparrow"); let result = lightWeightSet.hasAll(set); -try { - lightWeightSet.hasAll.bind({}, set)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -258,11 +231,6 @@ let lightWeightSet = new LightWeightSet(); let result = lightWeightSet.has(123); lightWeightSet.add(123); result = lightWeightSet.has(123); -try { - lightWeightSet.has.bind({}, 123)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -302,11 +270,6 @@ lightWeightSet.add("squirrel"); lightWeightSet.add("sparrow"); let obj = ["squirrel", "sparrow"]; let result = lightWeightSet.equal(obj); -try { - lightWeightSet.equal.bind({}, obj)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -331,23 +294,13 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er | ID| Error Message| | -------- | -------- | | 10200011 | The increaseCapacityTo method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The parameter value is out of range. | **Example** ```ts let lightWeightSet = new LightWeightSet(); lightWeightSet.increaseCapacityTo(10); -try { - lightWeightSet.increaseCapacityTo.bind({}, 10)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - lightWeightSet.increaseCapacityTo(2); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -386,11 +339,6 @@ let lightWeightSet = new LightWeightSet(); lightWeightSet.add("squirrel"); lightWeightSet.add("sparrow"); let result = lightWeightSet.getIndexOf("sparrow"); -try { - lightWeightSet.getIndexOf.bind({}, "sparrow")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -429,11 +377,6 @@ let lightWeightSet = new LightWeightSet(); lightWeightSet.add("squirrel"); lightWeightSet.add("sparrow"); let result = lightWeightSet.remove("sparrow"); -try { - lightWeightSet.remove.bind({}, "sparrow")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -472,11 +415,6 @@ let lightWeightSet = new LightWeightSet(); lightWeightSet.add("squirrel"); lightWeightSet.add("sparrow"); let result = lightWeightSet.removeAt(1); -try { - lightWeightSet.removeAt.bind({}, 1)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -515,11 +453,6 @@ let lightWeightSet = new LightWeightSet(); lightWeightSet.add("squirrel"); lightWeightSet.add("sparrow"); let result = lightWeightSet.getValueAt(1); -try { - lightWeightSet.getValueAt.bind({}, 1)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -546,11 +479,6 @@ let lightWeightSet = new LightWeightSet(); lightWeightSet.add("squirrel"); lightWeightSet.add("sparrow"); lightWeightSet.clear(); -try { - lightWeightSet.clear.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -583,11 +511,6 @@ let lightWeightSet = new LightWeightSet(); lightWeightSet.add("squirrel"); lightWeightSet.add("sparrow"); let result = lightWeightSet.toString(); -try { - lightWeightSet.toString.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -620,11 +543,6 @@ let lightWeightSet = new LightWeightSet(); lightWeightSet.add("squirrel"); lightWeightSet.add("sparrow"); let result = lightWeightSet.toArray(); -try { - lightWeightSet.toArray.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -662,17 +580,12 @@ while(index < lightWeightSet.length) { console.log(JSON.stringify(iter.next().value)); index++; } -try { - lightWeightSet.values.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### forEach -forEach(callbackfn: (value?: T, key?: T, set?: LightWeightSet<T>) => void, thisArg?: Object): void +forEach(callbackFn: (value?: T, key?: T, set?: LightWeightSet<T>) => void, thisArg?: Object): void Uses a callback to traverse the elements in this container and obtain their position indexes. @@ -682,7 +595,7 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| +| callbackFn | function | Yes| Callback invoked to traverse the elements in the container.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -709,13 +622,6 @@ lightWeightSet.add("gull"); lightWeightSet.forEach((value, key) => { console.log("value:" + value, key); }); -try { - lightWeightSet.forEach.bind({}, (value, key) => { - console.log("value:" + value, key); - })(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -753,11 +659,6 @@ while(index < lightWeightSet.length) { console.log(JSON.stringify(iter.next().value)); index++; } -try { - lightWeightSet.entries.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -802,9 +703,4 @@ while(temp != undefined) { console.log("value:" + temp); temp = iter.next().value; } -try { - lightWeightSet[Symbol.iterator].bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` diff --git a/en/application-dev/reference/apis/js-apis-linkedlist.md b/en/application-dev/reference/apis/js-apis-linkedlist.md index 81b7ee076547f3ac3acd72fb3267d8e84265e2b3..1eda96e1205a256960c8a03f28ee60080850d22c 100644 --- a/en/application-dev/reference/apis/js-apis-linkedlist.md +++ b/en/application-dev/reference/apis/js-apis-linkedlist.md @@ -1,4 +1,4 @@ -# Linear Container LinkedList +# @ohos.util.LinkedList (Linear Container LinkedList) > **NOTE** > @@ -21,9 +21,6 @@ This topic uses the following to identify the use of generics: import LinkedList from '@ohos.util.LinkedList'; ``` - - - ## LinkedList ### Attributes @@ -56,11 +53,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let linkedList = new LinkedList(); -try { - let linkedList2 = LinkedList(); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -103,11 +95,6 @@ let result2 = linkedList.add(b); let c = {name : "Dylon", age : "13"}; let result3 = linkedList.add(c); let result4 = linkedList.add(false); -try { - linkedList.add.bind({}, "b")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### addFirst @@ -143,11 +130,6 @@ linkedList.addFirst(b); let c = {name : "Dylon", age : "13"}; linkedList.addFirst(c); linkedList.addFirst(false); -try { - linkedList.addFirst.bind({}, "b")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### insert @@ -172,7 +154,7 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er | ID| Error Message| | -------- | -------- | | 10200011 | The insert method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The parameter value is out of range. | **Example** @@ -181,16 +163,6 @@ let linkedList = new LinkedList(); linkedList.insert(0, "A"); linkedList.insert(1, 0); linkedList.insert(2, true); -try { - linkedList.insert.bind({}, 3, "b")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - linkedList.insert(6, "b"); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### has @@ -228,11 +200,6 @@ let linkedList = new LinkedList(); let result1 = linkedList.has("squirrel"); linkedList.add("squirrel"); let result = linkedList.has("squirrel"); -try { - linkedList.has.bind({}, "squirrel")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### get @@ -275,11 +242,6 @@ linkedList.add(1); linkedList.add(2); linkedList.add(4); let result = linkedList.get(2); -try { - linkedList.get.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### getLastIndexOf @@ -322,11 +284,6 @@ linkedList.add(1); linkedList.add(2); linkedList.add(4); let result = linkedList.getLastIndexOf(2); -try { - linkedList.getLastIndexOf.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### getIndexOf @@ -369,11 +326,6 @@ linkedList.add(1); linkedList.add(2); linkedList.add(4); let result = linkedList.getIndexOf(2); -try { - linkedList.getIndexOf.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### removeByIndex @@ -403,7 +355,7 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er | ID| Error Message| | -------- | -------- | | 10200011 | The removeByIndex method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The parameter value is out of range. | **Example** @@ -415,16 +367,6 @@ linkedList.add(5); linkedList.add(2); linkedList.add(4); let result = linkedList.removeByIndex(2); -try { - linkedList.removeByIndex.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - linkedList.removeByIndex(8); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### removeFirst @@ -448,28 +390,18 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er | ID| Error Message| | -------- | -------- | | 10200011 | The removeFirst method cannot be bound. | -| 10200010 | Container is empty. | +| 10200010 | The container is empty. | **Example** ```ts let linkedList = new LinkedList(); -try { - linkedList.removeFirst(); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} linkedList.add(2); linkedList.add(4); linkedList.add(5); linkedList.add(2); linkedList.add(4); let result = linkedList.removeFirst(); -try { - linkedList.removeFirst.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### removeLast @@ -493,28 +425,18 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er | ID| Error Message| | -------- | -------- | | 10200011 | The removeLast method cannot be bound. | -| 10200010 | Container is empty. | +| 10200010 | The container is empty. | **Example** ```ts let linkedList = new LinkedList(); -try { - linkedList.removeLast(); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} linkedList.add(2); linkedList.add(4); linkedList.add(5); linkedList.add(2); linkedList.add(4); let result = linkedList.removeLast(); -try { - linkedList.removeLast.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### remove @@ -554,11 +476,6 @@ linkedList.add(4); linkedList.add(5); linkedList.add(4); let result = linkedList.remove(2); -try { - linkedList.remove.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### removeFirstFound @@ -588,27 +505,17 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er | ID| Error Message| | -------- | -------- | | 10200011 | The removeFirstFound method cannot be bound. | -| 10200010 | Container is empty. | +| 10200010 | The container is empty. | **Example** ```ts let linkedList = new LinkedList(); -try { - linkedList.removeFirstFound(4); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} linkedList.add(2); linkedList.add(4); linkedList.add(5); linkedList.add(4); let result = linkedList.removeFirstFound(4); -try { - linkedList.removeFirstFound.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### removeLastFound @@ -638,27 +545,17 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er | ID| Error Message| | -------- | -------- | | 10200011 | The removeLastFound method cannot be bound. | -| 10200010 | Container is empty. | +| 10200010 | The container is empty. | **Example** ```ts let linkedList = new LinkedList(); -try { - linkedList.removeLastFound(); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} linkedList.add(2); linkedList.add(4); linkedList.add(5); linkedList.add(4); let result = linkedList.removeLastFound(4); -try { - linkedList.removeLastFound.bind({}, 4)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### clone @@ -692,16 +589,11 @@ linkedList.add(4); linkedList.add(5); linkedList.add(4); let result = linkedList.clone(); -try { - linkedList.clone.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### forEach -forEach(callbackfn: (value: T, index?: number, LinkedList?: LinkedList<T>) => void, +forEach(callbackFn: (value: T, index?: number, LinkedList?: LinkedList<T>) => void, thisArg?: Object): void Uses a callback to traverse the elements in this container and obtain their position indexes. @@ -712,7 +604,7 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| +| callbackFn | function | Yes| Callback invoked to traverse the elements in the container.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -742,13 +634,6 @@ linkedList.add(4); linkedList.forEach((value, index) => { console.log("value:" + value, index); }); -try { - linkedList.forEach.bind({}, (value, index) => { - console.log("value:" + value, index); - })(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### clear @@ -776,11 +661,6 @@ linkedList.add(4); linkedList.add(5); linkedList.add(4); linkedList.clear(); -try { - linkedList.clear.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### set @@ -811,7 +691,7 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er | ID| Error Message| | -------- | -------- | | 10200011 | The set method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The parameter value is out of range. | **Example** @@ -822,16 +702,6 @@ linkedList.add(4); linkedList.add(5); linkedList.add(4); let result = linkedList.set(2, "b"); -try { - linkedList.set.bind({}, 2, "b")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - linkedList.set(8, "b"); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### convertToArray @@ -864,11 +734,6 @@ linkedList.add(4); linkedList.add(5); linkedList.add(4); let result = linkedList.convertToArray(); -try { - linkedList.convertToArray.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### getFirst @@ -902,11 +767,6 @@ linkedList.add(4); linkedList.add(5); linkedList.add(4); let result = linkedList.getFirst(); -try { - linkedList.getFirst.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### getLast @@ -940,11 +800,6 @@ linkedList.add(4); linkedList.add(5); linkedList.add(4); linkedList.getLast(); -try { - linkedList.getLast.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### [Symbol.iterator] @@ -990,9 +845,4 @@ while(temp != undefined) { console.log("value:" + temp); temp = iter.next().value; } -try { - linkedList[Symbol.iterator].bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` diff --git a/en/application-dev/reference/apis/js-apis-list.md b/en/application-dev/reference/apis/js-apis-list.md index 181febf4ebe037fe37ec061efe832bd4f9a387cd..2c657bc20289e50af9edda35a739f8fd8c3b0896 100644 --- a/en/application-dev/reference/apis/js-apis-list.md +++ b/en/application-dev/reference/apis/js-apis-list.md @@ -1,4 +1,4 @@ -# Linear Container List +# @ohos.util.List (Linear Container List) > **NOTE** > @@ -51,11 +51,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let list = new List(); -try { - let list2 = List(); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -98,11 +93,6 @@ let result3 = list.add(b); let c = {name : "Dylon", age : "13"}; let result4 = list.add(c); let result5 = list.add(false); -try { - list.add.bind({}, "b")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### insert @@ -127,7 +117,7 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er | ID| Error Message| | -------- | -------- | | 10200011 | The insert method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The parameter value is out of range. | **Example** @@ -136,16 +126,6 @@ let list = new List(); list.insert("A", 0); list.insert(0, 1); list.insert(true, 2); -try { - list.insert.bind({}, "b", 3)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - list.insert("b", 6); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### has @@ -183,11 +163,6 @@ let list = new List(); let result = list.has("squirrel"); list.add("squirrel"); let result1 = list.has("squirrel"); -try { - list.has.bind({}, "squirrel")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### get @@ -230,11 +205,6 @@ list.add(1); list.add(2); list.add(4); let result = list.get(2); -try { - list.get.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### getLastIndexOf @@ -277,11 +247,6 @@ list.add(1); list.add(2); list.add(4); let result = list.getLastIndexOf(2); -try { - list.getLastIndexOf.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### getIndexOf @@ -325,11 +290,6 @@ list.add(2); list.add(4); list.getIndexOf(2); let result = list.getIndexOf(2); -try { - list.getIndexOf.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### equal @@ -375,11 +335,6 @@ obj1.add(5); list.equal(obj1); let obj2 = {name : "Dylon", age : "13"}; let result = list.equal(obj2); -try { - list.equal.bind({}, obj2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### removeByIndex @@ -409,7 +364,7 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er | ID| Error Message| | -------- | -------- | | 10200011 | The removeByIndex method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The parameter value is out of range. | **Example** @@ -421,16 +376,6 @@ list.add(5); list.add(2); list.add(4); let result = list.removeByIndex(2); -try { - list.removeByIndex.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - list.removeByIndex(8); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### remove @@ -470,16 +415,11 @@ list.add(4); list.add(5); list.add(4); let result = list.remove(2); -try { - list.remove.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### replaceAllElements -replaceAllElements(callbackfn: (value: T, index?: number, list?: List<T>) => T, +replaceAllElements(callbackFn: (value: T, index?: number, list?: List<T>) => T, thisArg?: Object): void Replaces all elements in this container with new elements, and returns the new ones. @@ -490,7 +430,7 @@ Replaces all elements in this container with new elements, and returns the new o | Name| Value Type | Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked for the replacement.| +| callbackFn | function | Yes| Callback invoked for the replacement.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -523,18 +463,11 @@ list.replaceAllElements((value: number, index: number) => { list.replaceAllElements((value: number, index: number) => { return value = value - 2; }); -try { - list.replaceAllElements.bind({}, (value: number, index: number) => { - return value = 2 * value; - })(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### forEach -forEach(callbackfn: (value: T, index?: number, List?: List<T>) => void, +forEach(callbackFn: (value: T, index?: number, List?: List<T>) => void, thisArg?: Object): void Uses a callback to traverse the elements in this container and obtain their position indexes. @@ -545,7 +478,7 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Value Type | Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| +| callbackFn | function | Yes| Callback invoked to traverse the elements in the container.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -575,14 +508,6 @@ list.add(4); list.forEach((value, index) => { console.log("value: " + value, index); }); -try { - list.forEach.bind({}, (value, index) => { - console.log("value: " + value, index); - })(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} - ``` ### sort @@ -624,11 +549,6 @@ list.add(5); list.add(4); list.sort((a: number, b: number) => a - b); list.sort((a: number, b: number) => b - a); -try { - list.sort.bind({}, (a: number, b: number) => b - a)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### getSubList @@ -659,7 +579,7 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er | ID| Error Message| | -------- | -------- | | 10200011 | The getSubList method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The parameter value is out of range. | **Example** @@ -672,16 +592,6 @@ list.add(4); let result = list.getSubList(2, 4); let result1 = list.getSubList(4, 3); let result2 = list.getSubList(2, 6); -try { - list.getSubList.bind({}, 2, 4)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - list.getSubList(2, 10); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### clear @@ -709,11 +619,6 @@ list.add(4); list.add(5); list.add(4); list.clear(); -try { - list.clear.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### set @@ -744,7 +649,7 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er | ID| Error Message| | -------- | -------- | | 10200011 | The set method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The parameter value is out of range. | **Example** @@ -755,16 +660,6 @@ list.add(4); list.add(5); list.add(4); list.set(2, "b"); -try { - list.set.bind({}, 3, "b")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - list.set(8, "b"); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### convertToArray @@ -798,11 +693,6 @@ list.add(4); list.add(5); list.add(4); let result = list.convertToArray(); -try { - list.convertToArray.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### isEmpty @@ -836,11 +726,6 @@ list.add(4); list.add(5); list.add(4); let result = list.isEmpty(); -try { - list.isEmpty.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### getFirst @@ -874,11 +759,6 @@ list.add(4); list.add(5); list.add(4); let result = list.getFirst(); -try { - list.getFirst.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### getLast @@ -912,11 +792,6 @@ list.add(4); list.add(5); list.add(4); let result = list.getLast(); -try { - list.getLast.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### [Symbol.iterator] @@ -962,9 +837,4 @@ while(temp != undefined) { console.log("value: " + temp); temp = iter.next().value; } -try { - list[Symbol.iterator].bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` diff --git a/en/application-dev/reference/apis/js-apis-notification.md b/en/application-dev/reference/apis/js-apis-notification.md index ff80fc8564758868ec979ff6bf033b7084fea561..99dd6551d098ddf0d6f58a69bde92191e38d083d 100644 --- a/en/application-dev/reference/apis/js-apis-notification.md +++ b/en/application-dev/reference/apis/js-apis-notification.md @@ -1,4 +1,4 @@ -# Notification +# @ohos.notification The **Notification** module provides notification management capabilities, covering notifications, notification slots, notification subscription, notification enabled status, and notification badge status. @@ -852,11 +852,7 @@ Subscribes to a notification with the subscription information specified. This A ```js function onConsumeCallback(data) { - if (err.code) { - console.info("subscribe failed " + JSON.stringify(err)); - } else { - console.info("subscribe success"); - } + console.info("Consume callback: " + JSON.stringify(data)); } var subscriber = { onConsume: onConsumeCallback @@ -1621,7 +1617,7 @@ Removes a notification for a specified bundle. This API uses an asynchronous cal | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | -------------------- | | hashCode | string | Yes | Unique notification ID. | -| reason | [RemoveReason](#removereason9) | Yes | Reason for removing the notification. | +| reason | [RemoveReason](#removereason9) | Yes | Indicates the reason for deleting a notification. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -1659,7 +1655,7 @@ Removes a notification for a specified bundle. This API uses a promise to return | Name | Type | Mandatory| Description | | -------- | ---------- | ---- | ---------- | | hashCode | string | Yes | Unique notification ID.| -| reason | [RemoveReason](#removereason9) | Yes | Reason for removing the notification. | +| reason | [RemoveReason](#removereason9) | Yes | Reason for deleting the notification. | **Example** @@ -2567,11 +2563,11 @@ Requests notification to be enabled for this application. This API uses an async **Example** ```javascript -function requestEnableNotificationCallback() { +function requestEnableNotificationCallback(err) { if (err.code) { console.info("requestEnableNotification failed " + JSON.stringify(err)); } else { - console.info("requestEnableNotification success"); + } }; @@ -2620,7 +2616,7 @@ Sets whether this device supports distributed notifications. This API uses an as **Example** ```javascript -function enabledNotificationCallback() { +function enabledNotificationCallback(err) { if (err.code) { console.info("enableDistributed failed " + JSON.stringify(err)); } else { @@ -2682,11 +2678,11 @@ Obtains whether this device supports distributed notifications. This API uses an **Example** ```javascript -function isDistributedEnabledCallback() { +function isDistributedEnabledCallback(err, data) { if (err.code) { console.info("isDistributedEnabled failed " + JSON.stringify(err)); } else { - console.info("isDistributedEnabled success"); + console.info("isDistributedEnabled success " + JSON.stringify(data)); } }; @@ -2742,7 +2738,7 @@ Sets whether an application supports distributed notifications based on the bund **Example** ```javascript -function enableDistributedByBundleCallback() { +function enableDistributedByBundleCallback(err) { if (err.code) { console.info("enableDistributedByBundle failed " + JSON.stringify(err)); } else { @@ -2817,11 +2813,11 @@ Obtains whether an application supports distributed notifications based on the b **Example** ```javascript -function isDistributedEnabledByBundleCallback(data) { +function isDistributedEnabledByBundleCallback(err, data) { if (err.code) { console.info("isDistributedEnabledByBundle failed " + JSON.stringify(err)); } else { - console.info("isDistributedEnabledByBundle success"); + console.info("isDistributedEnabledByBundle success" + JSON.stringify(data)); } }; @@ -2893,7 +2889,7 @@ Obtains the notification reminder type. This API uses an asynchronous callback t **Example** ```javascript -function getDeviceRemindTypeCallback(data) { +function getDeviceRemindTypeCallback(err,data) { if (err.code) { console.info("getDeviceRemindType failed " + JSON.stringify(err)); } else { @@ -3414,6 +3410,8 @@ Notification.getSyncNotificationEnabledWithoutApp(userId) ## NotificationSubscriber +Provides callbacks for receiving or removing notifications. + **System API**: This is a system API and cannot be called by third-party applications. ### onConsume @@ -3430,7 +3428,7 @@ Callback for receiving notifications. | Name| Type| Mandatory| Description| | ------------ | ------------------------ | ---- | -------------------------- | -| data | AsyncCallback\<[SubscribeCallbackData](#subscribecallbackdata)\> | Yes| Notification information returned.| +| data | [SubscribeCallbackData](#subscribecallbackdata) | Yes| Notification information returned.| **Example** @@ -3447,15 +3445,6 @@ function onConsumeCallback(data) { console.info('===> onConsume in test'); let req = data.request; console.info('===> onConsume callback req.id:' + req.id); - let wantAgent = data.wantAgent; - wantAgent .getWant(wantAgent) - .then((data1) => { - console.info('===> getWant success want:' + JSON.stringify(data1)); - }) - .catch((err) => { - console.error('===> getWant failed because' + JSON.stringify(err)); - }); - console.info('===> onConsume callback req.wantAgent:' + JSON.stringify(req.wantAgent)); }; var subscriber = { @@ -3479,7 +3468,7 @@ Callback for removing notifications. | Name| Type| Mandatory| Description| | ------------ | ------------------------ | ---- | -------------------------- | -| data | AsyncCallback\<[SubscribeCallbackData](#subscribecallbackdata)\> | Yes| Notification information returned.| +| data | [SubscribeCallbackData](#subscribecallbackdata) | Yes| Notification information returned.| **Example** @@ -3723,13 +3712,13 @@ Notification.subscribe(subscriber, subscribeCallback); **System API**: This is a system API and cannot be called by third-party applications. -| Name | Readable| Writable| Type | Description | -| --------------- | ---- | --- | ------------------------------------------------- | -------- | -| request | Yes | No | [NotificationRequest](#notificationrequest) | Notification content.| -| sortingMap | Yes | No | [NotificationSortingMap](#notificationsortingmap) | Notification sorting information.| -| reason | Yes | No | number | Reason for deletion.| -| sound | Yes | No | string | Sound used for notification.| -| vibrationValues | Yes | No | Array\ | Vibration used for notification.| +| Name | Type | Readable| Writable| Description | +| --------------- | ------------------------------------------------- | ---- | --- | -------- | +| request | [NotificationRequest](#notificationrequest) | Yes | No | Notification content.| +| sortingMap | [NotificationSortingMap](#notificationsortingmap) | Yes | No | Notification sorting information.| +| reason | number | Yes | No | Reason for deletion.| +| sound | string | Yes | No | Sound used for notification.| +| vibrationValues | Array\ | Yes | No | Vibration used for notification.| ## EnabledNotificationCallbackData8+ @@ -3738,11 +3727,11 @@ Notification.subscribe(subscriber, subscribeCallback); **System API**: This is a system API and cannot be called by third-party applications. -| Name | Readable| Writable| Type | Description | -| ------ | ---- | --- | ------- | ---------------- | -| bundle | Yes | No | string | Bundle name of the application. | -| uid | Yes | No | number | UID of the application. | -| enable | Yes | No | boolean | Notification enabled status of the application.| +| Name | Type | Readable| Writable| Description | +| ------ | ------- | ---- | --- | ---------------- | +| bundle | string | Yes | No | Bundle name of the application. | +| uid | number | Yes | No | UID of the application. | +| enable | boolean | Yes | No | Notification enabled status of the application.| ## DoNotDisturbDate8+ @@ -3751,11 +3740,11 @@ Notification.subscribe(subscriber, subscribeCallback); **System API**: This is a system API and cannot be called by third-party applications. -| Name | Readable| Writable| Type | Description | -| ----- | ---- | --- | ------------------------------------- | ------------------------ | -| type | Yes | No | [DoNotDisturbType](#donotdisturbtype8) | DND time type.| -| begin | Yes | No | Date | DND start time.| -| end | Yes | No | Date | DND end time.| +| Name | Type | Readable| Writable| Description | +| ----- ------------------------------------- || ---- | --- | ------------------------ | +| type | [DoNotDisturbType](#donotdisturbtype8) | Yes | No | DND time type.| +| begin | Date | Yes | No | DND start time.| +| end | Date | Yes | No | DND end time.| @@ -3802,10 +3791,10 @@ Notification.subscribe(subscriber, subscribeCallback); **System capability**: SystemCapability.Notification.Notification -| Name | Readable| Writable| Type | Description | -| ------ | ---- | --- | ------ | ------ | -| bundle | Yes | Yes | string | Bundle name. | -| uid | Yes | Yes | number | User ID.| +| Name | Type | Readable| Writable| Description | +| ------ | ------ |---- | --- | ------ | +| bundle | string | Yes | Yes | Bundle name. | +| uid | number | Yes | Yes | User ID.| @@ -3813,10 +3802,10 @@ Notification.subscribe(subscriber, subscribeCallback); **System capability**: SystemCapability.Notification.Notification -| Name | Readable| Writable| Type | Description | -| ----- | ---- | --- | ------ | -------- | -| id | Yes | Yes | number | Notification ID. | -| label | Yes | Yes | string | Notification label.| +| Name | Type | Readable| Writable| Description | +| ----- | ------ | ---- | --- | -------- | +| id | number | Yes | Yes | Notification ID. | +| label | string | Yes | Yes | Notification label.| ## SlotType @@ -3834,84 +3823,98 @@ Notification.subscribe(subscriber, subscribeCallback); ## NotificationActionButton +Enumerates the buttons in the notification. + **System capability**: SystemCapability.Notification.Notification -| Name | Readable| Writable| Type | Description | -| --------- | --- | ---- | ----------------------------------------------- | ------------------------- | -| title | Yes | Yes | string | Button title. | -| wantAgent | Yes | Yes | WantAgent | **WantAgent** of the button.| -| extras | Yes | Yes | { [key: string]: any } | Extra information of the button. | -| userInput8+ | Yes | Yes | [NotificationUserInput](#notificationuserinput8) | User input object. | +| Name | Type | Readable| Writable| Description | +| --------- | ----------------------------------------------- | --- | ---- | ------------------------- | +| title | string | Yes | Yes | Button title. | +| wantAgent | WantAgent | Yes | Yes | **WantAgent** of the button.| +| extras | { [key: string]: any } | Yes | Yes | Extra information of the button. | +| userInput8+ | [NotificationUserInput](#notificationuserinput8) | Yes | Yes | User input object. | ## NotificationBasicContent +Describes the normal text notification. + **System capability**: SystemCapability.Notification.Notification -| Name | Readable| Writable| Type | Description | -| -------------- | ---- | ---- | ------ | ---------------------------------- | -| title | Yes | Yes | string | Notification title. | -| text | Yes | Yes | string | Notification content. | -| additionalText | Yes | Yes | string | Additional information of the notification.| +| Name | Type | Readable| Writable| Description | +| -------------- | ------ | ---- | ---- | ---------------------------------- | +| title | string | Yes | Yes | Notification title. | +| text | string | Yes | Yes | Notification content. | +| additionalText | string | Yes | Yes | Additional information of the notification.| ## NotificationLongTextContent +Describes the long text notification. + **System capability**: SystemCapability.Notification.Notification -| Name | Readable| Writable| Type | Description | -| -------------- | ---- | --- | ------ | -------------------------------- | -| title | Yes | Yes | string | Notification title. | -| text | Yes | Yes | string | Notification content. | -| additionalText | Yes | Yes | string | Additional information of the notification.| -| longText | Yes | Yes | string | Long text of the notification. | -| briefText | Yes | Yes | string | Brief text of the notification.| -| expandedTitle | Yes | Yes | string | Title of the notification in the expanded state. | +| Name | Type | Readable| Writable| Description | +| -------------- | ------ | ---- | --- | -------------------------------- | +| title | string | Yes | Yes | Notification title. | +| text | string | Yes | Yes | Notification content. | +| additionalText | string | Yes | Yes | Additional information of the notification.| +| longText | string | Yes | Yes | Long text of the notification. | +| briefText | string | Yes | Yes | Brief text of the notification.| +| expandedTitle | string | Yes | Yes | Title of the notification in the expanded state. | ## NotificationMultiLineContent +Describes the multi-line text notification. + **System capability**: SystemCapability.Notification.Notification -| Name | Readable| Writable| Type | Description | -| -------------- | --- | --- | --------------- | -------------------------------- | -| title | Yes | Yes | string | Notification title. | -| text | Yes | Yes | string | Notification content. | -| additionalText | Yes | Yes | string | Additional information of the notification.| -| briefText | Yes | Yes | string | Brief text of the notification.| -| longTitle | Yes | Yes | string | Title of the notification in the expanded state. | -| lines | Yes | Yes | Array\ | Multi-line text of the notification. | +| Name | Type | Readable| Writable| Description | +| -------------- | --------------- | --- | --- | -------------------------------- | +| title | string | Yes | Yes | Notification title. | +| text | string | Yes | Yes | Notification content. | +| additionalText | string | Yes | Yes | Additional information of the notification.| +| briefText | string | Yes | Yes | Brief text of the notification.| +| longTitle | string | Yes | Yes | Title of the notification in the expanded state. | +| lines | Array\ | Yes | Yes | Multi-line text of the notification. | ## NotificationPictureContent +Describes the picture-attached notification. + **System capability**: SystemCapability.Notification.Notification -| Name | Readable| Writable| Type | Description | -| -------------- | ---- | --- | -------------- | -------------------------------- | -| title | Yes | Yes | string | Notification title. | -| text | Yes | Yes | string | Notification content. | -| additionalText | Yes | Yes | string | Additional information of the notification.| -| briefText | Yes | Yes | string | Brief text of the notification.| -| expandedTitle | Yes | Yes | string | Title of the notification in the expanded state. | -| picture | Yes | Yes | image.PixelMap | Picture attached to the notification. | +| Name | Type | Readable| Writable| Description | +| -------------- | -------------- | ---- | --- | -------------------------------- | +| title | string | Yes | Yes | Notification title. | +| text | string | Yes | Yes | Notification content. | +| additionalText | string | Yes | Yes | Additional information of the notification.| +| briefText | string | Yes | Yes | Brief text of the notification.| +| expandedTitle | string | Yes | Yes | Title of the notification in the expanded state. | +| picture | image.PixelMap | Yes | Yes | Picture attached to the notification. | ## NotificationContent +Describes the notification content. + **System capability**: SystemCapability.Notification.Notification -| Name | Readable| Writable| Type | Description | -| ----------- | ---- | --- | ------------------------------------------------------------ | ------------------ | -| contentType | Yes | Yes | [ContentType](#contenttype) | Notification content type. | -| normal | Yes | Yes | [NotificationBasicContent](#notificationbasiccontent) | Normal text. | -| longText | Yes | Yes | [NotificationLongTextContent](#notificationlongtextcontent) | Long text.| -| multiLine | Yes | Yes | [NotificationMultiLineContent](#notificationmultilinecontent) | Multi-line text. | -| picture | Yes | Yes | [NotificationPictureContent](#notificationpicturecontent) | Picture-attached. | +| Name | Type | Readable| Writable| Description | +| ----------- | ------------------------------------------------------------ | ---- | --- | ------------------ | +| contentType | [ContentType](#contenttype) | Yes | Yes | Notification content type. | +| normal | [NotificationBasicContent](#notificationbasiccontent) | Yes | Yes | Normal text. | +| longText | [NotificationLongTextContent](#notificationlongtextcontent) | Yes | Yes | Long text.| +| multiLine | [NotificationMultiLineContent](#notificationmultilinecontent) | Yes | Yes | Multi-line text. | +| picture | [NotificationPictureContent](#notificationpicturecontent) | Yes | Yes | Picture-attached. | ## NotificationFlagStatus8+ +Describes the notification flag status. + **System capability**: SystemCapability.Notification.Notification **System API**: This is a system API and cannot be called by third-party applications. @@ -3925,133 +3928,149 @@ Notification.subscribe(subscriber, subscribeCallback); ## NotificationFlags8+ +Enumerates notification flags. + **System capability**: SystemCapability.Notification.Notification -| Name | Readable| Writable| Type | Description | -| ---------------- | ---- | ---- | ---------------------- | --------------------------------- | -| soundEnabled | Yes | No | NotificationFlagStatus | Whether to enable the sound alert for the notification. | -| vibrationEnabled | Yes | No | NotificationFlagStatus | Whether to enable vibration for the notification. | +| Name | Type | Readable| Writable| Description | +| ---------------- | ---------------------- | ---- | ---- | --------------------------------- | +| soundEnabled | NotificationFlagStatus | Yes | No | Whether to enable the sound alert for the notification. | +| vibrationEnabled | NotificationFlagStatus | Yes | No | Whether to enable vibration for the notification. | ## NotificationRequest -**System capability**: SystemCapability.Notification.Notification - -| Name | Readable| Writable| Type | Description | -| --------------------- | ---- | --- | --------------------------------------------- | -------------------------- | -| content | Yes | Yes | [NotificationContent](#notificationcontent) | Notification content. | -| id | Yes | Yes | number | Notification ID. | -| slotType | Yes | Yes | [SlotType](#slottype) | Slot type. | -| isOngoing | Yes | Yes | boolean | Whether the notification is an ongoing notification. | -| isUnremovable | Yes | Yes | boolean | Whether the notification can be removed. | -| deliveryTime | Yes | Yes | number | Time when the notification is sent. | -| tapDismissed | Yes | Yes | boolean | Whether the notification is automatically cleared. | -| autoDeletedTime | Yes | Yes | number | Time when the notification is automatically cleared. | -| wantAgent | Yes | Yes | WantAgent | **WantAgent** instance to which the notification will be redirected after being clicked. | -| extraInfo | Yes | Yes | {[key: string]: any} | Extended parameters. | -| color | Yes | Yes | number | Background color of the notification. | -| colorEnabled | Yes | Yes | boolean | Whether the notification background color is enabled. | -| isAlertOnce | Yes | Yes | boolean | Whether the notification triggers an alert only once.| -| isStopwatch | Yes | Yes | boolean | Whether to display the stopwatch. | -| isCountDown | Yes | Yes | boolean | Whether to display the countdown time. | -| isFloatingIcon | Yes | Yes | boolean | Whether the notification is displayed as a floating icon. | -| label | Yes | Yes | string | Notification label. | -| badgeIconStyle | Yes | Yes | number | Notification badge type. | -| showDeliveryTime | Yes | Yes | boolean | Whether to display the time when the notification is delivered. | -| actionButtons | Yes | Yes | Array\<[NotificationActionButton](#notificationactionbutton)\> | Buttons in the notification. Up to two buttons are allowed. | -| smallIcon | Yes | Yes | PixelMap | Small notification icon. | -| largeIcon | Yes | Yes | PixelMap | Large notification icon. | -| creatorBundleName | Yes | No | string | Name of the bundle that creates the notification. | -| creatorUid | Yes | No | number | UID used for creating the notification. | -| creatorPid | Yes | No | number | PID used for creating the notification. | -| creatorUserId8+| Yes | No | number | ID of the user who creates the notification. | -| hashCode | Yes | No | string | Unique ID of the notification. | -| classification | Yes | Yes | string | Notification category.
**System API**: This is a system API and cannot be called by third-party applications. | -| groupName8+| Yes | Yes | string | Group notification name. | -| template8+ | Yes | Yes | [NotificationTemplate](#notificationtemplate8) | Notification template. | -| isRemoveAllowed8+ | Yes | No | boolean | Whether the notification can be removed.
**System API**: This is a system API and cannot be called by third-party applications. | -| source8+ | Yes | No | number | Notification source.
**System API**: This is a system API and cannot be called by third-party applications. | -| distributedOption8+ | Yes | Yes | [DistributedOptions](#distributedoptions8) | Option of distributed notification. | -| deviceId8+ | Yes | No | string | Device ID of the notification source.
**System API**: This is a system API and cannot be called by third-party applications. | -| notificationFlags8+ | Yes | No | [NotificationFlags](#notificationflags8) | Notification flags. | -| removalWantAgent9+ | Yes | Yes | WantAgent | **WantAgent** instance to which the notification will be redirected when it is removed. | -| badgeNumber9+ | Yes | Yes | number | Number of notifications displayed on the application icon. | +Describes the notification request. + +**System capability**: SystemCapability.Notification.Notification + +| Name | Type | Readable| Writable| Description | +| --------------------- | --------------------------------------------- | ---- | --- | -------------------------- | +| content | [NotificationContent](#notificationcontent) | Yes | Yes | Notification content. | +| id | number | Yes | Yes | Notification ID. | +| slotType | [SlotType](#slottype) | Yes | Yes | Slot type. | +| isOngoing | boolean | Yes | Yes | Whether the notification is an ongoing notification. | +| isUnremovable | boolean | Yes | Yes | Whether the notification can be removed. | +| deliveryTime | number | Yes | Yes | Time when the notification is sent. | +| tapDismissed | boolean | Yes | Yes | Whether the notification is automatically cleared. | +| autoDeletedTime | number | Yes | Yes | Time when the notification is automatically cleared. | +| wantAgent | WantAgent | Yes | Yes | **WantAgent** instance to which the notification will be redirected after being clicked. | +| extraInfo | {[key: string]: any} | Yes | Yes | Extended parameters. | +| color | number | Yes | Yes | Background color of the notification. Not supported currently. | +| colorEnabled | boolean | Yes | Yes | Whether the notification background color is enabled. Not supported currently. | +| isAlertOnce | boolean | Yes | Yes | Whether the notification triggers an alert only once.| +| isStopwatch | boolean | Yes | Yes | Whether to display the stopwatch. | +| isCountDown | boolean | Yes | Yes | Whether to display the countdown time. | +| isFloatingIcon | boolean | Yes | Yes | Whether the notification is displayed as a floating icon. | +| label | string | Yes | Yes | Notification label. | +| badgeIconStyle | number | Yes | Yes | Notification badge type. | +| showDeliveryTime | boolean | Yes | Yes | Whether to display the time when the notification is delivered. | +| actionButtons | Array\<[NotificationActionButton](#notificationactionbutton)\> | Yes | Yes | Buttons in the notification. Up to two buttons are allowed. | +| smallIcon | PixelMap | Yes | Yes | Small notification icon. | +| largeIcon | PixelMap | Yes | Yes | Large notification icon. | +| creatorBundleName | string | Yes | No | Name of the bundle that creates the notification. | +| creatorUid | number | Yes | No | UID used for creating the notification. | +| creatorPid | number | Yes | No | PID used for creating the notification. | +| creatorUserId8+| number | Yes | No | ID of the user who creates the notification. | +| hashCode | string | Yes | No | Unique ID of the notification. | +| classification | string | Yes | Yes | Notification category.
**System API**: This is a system API and cannot be called by third-party applications. | +| groupName8+| string | Yes | Yes | Group notification name. | +| template8+ | [NotificationTemplate](#notificationtemplate8) | Yes | Yes | Notification template. | +| isRemoveAllowed8+ | boolean | Yes | No | Whether the notification can be removed.
**System API**: This is a system API and cannot be called by third-party applications. | +| source8+ | number | Yes | No | Notification source.
**System API**: This is a system API and cannot be called by third-party applications. | +| distributedOption8+ | [DistributedOptions](#distributedoptions8) | Yes | Yes | Option of distributed notification. | +| deviceId8+ | string | Yes | No | Device ID of the notification source.
**System API**: This is a system API and cannot be called by third-party applications. | +| notificationFlags8+ | [NotificationFlags](#notificationflags8) | Yes | No | Notification flags. | +| removalWantAgent9+ | WantAgent | Yes | Yes | **WantAgent** instance to which the notification will be redirected when it is removed. | +| badgeNumber9+ | number | Yes | Yes | Number of notifications displayed on the application icon. | ## DistributedOptions8+ +Describes distributed options. + **System capability**: SystemCapability.Notification.Notification -| Name | Readable| Writable| Type | Description | -| ---------------------- | ---- | ---- | -------------- | ---------------------------------- | -| isDistributed | Yes | Yes | boolean | Whether the notification is a distributed notification. | -| supportDisplayDevices | Yes | Yes | Array\ | Types of the devices to which the notification can be synchronized. | -| supportOperateDevices | Yes | Yes | Array\ | Devices on which notification can be enabled. | -| remindType | Yes | No | number | Notification reminder type.
**System API**: This is a system API and cannot be called by third-party applications. | +| Name | Type | Readable| Writable| Description | +| ---------------------- | -------------- | ---- | ---- | ---------------------------------- | +| isDistributed | boolean | Yes | Yes | Whether the notification is a distributed notification. | +| supportDisplayDevices | Array\ | Yes | Yes | Types of the devices to which the notification can be synchronized. | +| supportOperateDevices | Array\ | Yes | Yes | Devices on which notification can be enabled. | +| remindType | number | Yes | No | Notification reminder type.
**System API**: This is a system API and cannot be called by third-party applications. | ## NotificationSlot +Describes the notification slot. + **System capability**: SystemCapability.Notification.Notification -| Name | Readable| Writable| Type | Description | -| -------------------- | ---- | --- | --------------------- | ------------------------------------------ | -| type | Yes | Yes | [SlotType](#slottype) | Slot type. | -| level | Yes | Yes | number | Notification level. If this parameter is not set, the default value is used based on the notification slot type.| -| desc | Yes | Yes | string | Notification slot description. | -| badgeFlag | Yes | Yes | boolean | Whether to display the badge. | -| bypassDnd | Yes | Yes | boolean | Whether to bypass the DND mode in the system. | -| lockscreenVisibility | Yes | Yes | number | Mode for displaying the notification on the lock screen. | -| vibrationEnabled | Yes | Yes | boolean | Whether vibration is supported for the notification. | -| sound | Yes | Yes | string | Notification alert tone. | -| lightEnabled | Yes | Yes | boolean | Whether the indicator blinks for the notification. | -| lightColor | Yes | Yes | number | Indicator color of the notification. | -| vibrationValues | Yes | Yes | Array\ | Vibration mode of the notification. | -| enabled9+ | Yes | No | boolean | Enabled status of the notification slot. | +| Name | Type | Readable| Writable| Description | +| -------------------- | --------------------- | ---- | --- | ------------------------------------------ | +| type | [SlotType](#slottype) | Yes | Yes | Slot type. | +| level | number | Yes | Yes | Notification level. If this parameter is not set, the default value is used based on the notification slot type.| +| desc | string | Yes | Yes | Notification slot description. | +| badgeFlag | boolean | Yes | Yes | Whether to display the badge. | +| bypassDnd | boolean | Yes | Yes | Whether to bypass the DND mode in the system. | +| lockscreenVisibility | number | Yes | Yes | Mode for displaying the notification on the lock screen. | +| vibrationEnabled | boolean | Yes | Yes | Whether vibration is supported for the notification. | +| sound | string | Yes | Yes | Notification alert tone. | +| lightEnabled | boolean | Yes | Yes | Whether the indicator blinks for the notification. | +| lightColor | number | Yes | Yes | Indicator color of the notification. | +| vibrationValues | Array\ | Yes | Yes | Vibration mode of the notification. | +| enabled9+ | boolean | Yes | No | Enabled status of the notification slot. | ## NotificationSorting +Provides sorting information of active notifications. + **System capability**: SystemCapability.Notification.Notification **System API**: This is a system API and cannot be called by third-party applications. -| Name | Readable| Writable| Type | Description | -| -------- | ---- | --- | ------------------------------------- | ------------ | -| slot | Yes | No | [NotificationSlot](#notificationslot) | Notification slot content.| -| hashCode | Yes | No | string | Unique ID of the notification.| -| ranking | Yes | No | number | Notification sequence number.| +| Name | Type | Readable| Writable| Description | +| -------- | ------------------------------------- | ---- | --- | ------------ | +| slot | [NotificationSlot](#notificationslot) | Yes | No | Notification slot content.| +| hashCode | string | Yes | No | Unique ID of the notification.| +| ranking | number | Yes | No | Notification sequence number.| ## NotificationSortingMap +Provides sorting information of active notifications in all subscribed notifications. + **System capability**: SystemCapability.Notification.Notification **System API**: This is a system API and cannot be called by third-party applications. -| Name | Readable| Writable| Type | Description | -| -------------- | ---- | --- | ------------------------------------------------------------ | ---------------- | -| sortings | Yes | No | {[key: string]: [NotificationSorting](#notificationsorting)} | Array of notification sorting information.| -| sortedHashCode | Yes | No | Array\ | Array of unique notification IDs.| +| Name | Type | Readable| Writable| Description | +| -------------- | ------------------------------------------------------------ | ---- | --- | ---------------- | +| sortings | {[key: string]: [NotificationSorting](#notificationsorting)} | Yes | No | Array of notification sorting information.| +| sortedHashCode | Array\ | Yes | No | Array of unique notification IDs.| ## NotificationSubscribeInfo +Provides the information about the publisher for notification subscription. + **System capability**: SystemCapability.Notification.Notification **System API**: This is a system API and cannot be called by third-party applications. -| Name | Readable| Writable| Type | Description | -| ----------- | --- | ---- | --------------- | ------------------------------- | -| bundleNames | Yes | Yes | Array\ | Bundle names of the applications whose notifications are to be subscribed to.| -| userId | Yes | Yes | number | User whose notifications are to be subscribed to. | +| Name | Type | Readable| Writable| Description | +| ----------- | --------------- | --- | ---- | ------------------------------- | +| bundleNames | Array\ | Yes | Yes | Bundle names of the applications whose notifications are to be subscribed to.| +| userId | number | Yes | Yes | User whose notifications are to be subscribed to. | ## NotificationTemplate8+ +Notification template. + **System capability**: SystemCapability.Notification.Notification -| Name| Type | Readable| Writable| Description | +| Name| Type | Readable| Writable| Description | | ---- | ---------------------- | ---- | ---- | ---------- | | name | string | Yes | Yes | Template name.| | data | {[key:string]: Object} | Yes | Yes | Template data.| @@ -4059,11 +4078,13 @@ Notification.subscribe(subscriber, subscribeCallback); ## NotificationUserInput8+ +Provides the notification user input. + **System capability**: SystemCapability.Notification.Notification -| Name | Readable| Writable| Type | Description | -| -------- | --- | ---- | ------ | ----------------------------- | -| inputKey | Yes | Yes | string | Key to identify the user input.| +| Name | Type | Readable| Writable| Description | +| -------- | ------ | --- | ---- | ----------------------------- | +| inputKey | string | Yes | Yes | Key to identify the user input.| ## DeviceRemindType8+ diff --git a/en/application-dev/reference/apis/js-apis-plainarray.md b/en/application-dev/reference/apis/js-apis-plainarray.md index 79ede0ce7a1aac37d64fe0a848e4bb5948cd877b..dfc05166987a87d07bc1499fbcb980b45f08f2e8 100644 --- a/en/application-dev/reference/apis/js-apis-plainarray.md +++ b/en/application-dev/reference/apis/js-apis-plainarray.md @@ -1,4 +1,4 @@ -# Nonlinear Container PlainArray +# @ohos.util.PlainArray (Nonlinear Container PlainArray) > **NOTE** > @@ -21,8 +21,6 @@ This topic uses the following to identify the use of generics: import PlainArray from '@ohos.util.PlainArray'; ``` - - ## PlainArray ### Attributes @@ -54,11 +52,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let plainArray = new PlainArray(); -try { - let plainArray2 = PlainArray(); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -89,11 +82,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts const plainArray = new PlainArray(); let result = plainArray.isEmpty(); -try { - plainArray.isEmpty.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -132,11 +120,6 @@ let plainArray = new PlainArray(); plainArray.has(1); plainArray.add(1, "squirrel"); let result1 = plainArray.has(1); -try { - plainArray.has.bind({}, 1)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -175,11 +158,6 @@ let plainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let result = plainArray.get(1); -try { - plainArray.get.bind({}, 1)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -218,11 +196,6 @@ let plainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let result = plainArray.getIndexOfKey(2); -try { - plainArray.getIndexOfKey.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -261,11 +234,6 @@ let plainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let result = plainArray.getIndexOfValue("squirrel"); -try { - plainArray.getIndexOfValue.bind({}, "squirrel")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -304,11 +272,6 @@ let plainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let result = plainArray.getKeyAt(1); -try { - plainArray.getKeyAt.bind({}, 1)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### getValueAt @@ -338,7 +301,7 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er | ID| Error Message| | -------- | -------- | | 10200011 | The getValueAt method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The parameter value is out of range. | **Example** @@ -347,16 +310,6 @@ let plainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let result = plainArray.getValueAt(1); -try { - plainArray.getValueAt.bind({}, 1)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - plainArray.getValueAt(10); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### clone @@ -388,11 +341,6 @@ let plainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let newPlainArray = plainArray.clone(); -try { - plainArray.clone.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -424,11 +372,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let plainArray = new PlainArray(); plainArray.add(1, "squirrel"); -try { - plainArray.add.bind({}, "squirrel")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -467,11 +410,6 @@ let plainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let result = plainArray.remove(2); -try { - plainArray.remove.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -510,11 +448,6 @@ let plainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let result = plainArray.removeAt(1); -try { - plainArray.removeAt.bind({}, 1)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -546,7 +479,7 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er | ID| Error Message| | -------- | -------- | | 10200011 | The removeRangeFrom method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The parameter value is out of range. | **Example** @@ -555,16 +488,6 @@ let plainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let result = plainArray.removeRangeFrom(1, 3); -try { - plainArray.removeRangeFrom.bind({}, 1, 3)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - plainArray.removeRangeFrom(10, 3); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -590,7 +513,7 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er | ID| Error Message| | -------- | -------- | | 10200011 | The setValueAt method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The parameter value is out of range. | **Example** @@ -599,16 +522,6 @@ let plainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); plainArray.setValueAt(1, 3546); -try { - plainArray.setValueAt.bind({}, 1, 3546)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - plainArray.setValueAt(10, 3); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -641,11 +554,6 @@ let plainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let result = plainArray.toString(); -try { - plainArray.toString.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -672,17 +580,12 @@ let plainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); plainArray.clear(); -try { - plainArray.clear.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### forEach -forEach(callbackfn: (value: T, index?: number, PlainArray?: PlainArray<T>) => void, thisArg?: Object): void +forEach(callbackFn: (value: T, index?: number, PlainArray?: PlainArray<T>) => void, thisArg?: Object): void Uses a callback to traverse the elements in this container and obtain their position indexes. @@ -692,7 +595,7 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type | Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| +| callbackFn | function | Yes| Callback invoked to traverse the elements in the container.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -719,13 +622,6 @@ plainArray.add(2, "sparrow"); plainArray.forEach((value, index) => { console.log("value:" + value, index); }); -try { - plainArray.forEach.bind({}, (value, index) => { - console.log("value:" + value, index); - })(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -772,9 +668,4 @@ while(temp != undefined) { console.log("value:" + temp[1]); temp = iter.next().value; } -try { - plainArray[Symbol.iterator].bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` diff --git a/en/application-dev/reference/apis/js-apis-queue.md b/en/application-dev/reference/apis/js-apis-queue.md index 11ca91994e98310961e657db1a4c5e2554798c99..57ce3f7b301c42167b6af3830e39949afd76f719 100644 --- a/en/application-dev/reference/apis/js-apis-queue.md +++ b/en/application-dev/reference/apis/js-apis-queue.md @@ -1,4 +1,4 @@ -# Linear Container Queue +# @ohos.util.Queue (Linear Container Queue) > **NOTE** > @@ -51,11 +51,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let queue = new Queue(); -try { - let queue2 = Queue(); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -97,11 +92,6 @@ let b = [1, 2, 3]; let result2 = queue.add(b); let c = {name : "Dylon", age : "13"}; let result3 = queue.add(c); -try { - queue.add.bind({}, "b")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### pop @@ -136,11 +126,6 @@ queue.add(5); queue.add(2); queue.add(4); let result = queue.pop(); -try { - queue.pop.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### getFirst @@ -151,7 +136,7 @@ Obtains the first element of this container. **System capability**: SystemCapability.Utils.Lang -**Parameters** +**Return value** | Type| Description| | -------- | -------- | @@ -174,16 +159,11 @@ queue.add(4); queue.add(5); queue.add(2); let result = queue.getFirst(); -try { - queue.getFirst.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### forEach -forEach(callbackfn: (value: T, index?: number, Queue?: Queue<T>) => void, +forEach(callbackFn: (value: T, index?: number, Queue?: Queue<T>) => void, thisArg?: Object): void Uses a callback to traverse the elements in this container and obtain their position indexes. @@ -194,7 +174,7 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| +| callbackFn | function | Yes| Callback invoked to traverse the elements in the container.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -224,13 +204,6 @@ queue.add(4); queue.forEach((value, index) => { console.log("value:" + value, index); }); -try { - queue.forEach.bind({}, (value, index) => { - console.log("value:" + value, index); - })(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### [Symbol.iterator] @@ -275,9 +248,4 @@ while(temp != undefined) { console.log("value:" + temp); temp = iter.next().value; } -try { - queue[Symbol.iterator].bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` diff --git a/en/application-dev/reference/apis/js-apis-request.md b/en/application-dev/reference/apis/js-apis-request.md index 65e8c2708c98748ba55a734e8095228233d90b9a..2220b4bbc02bd9a68fa900138869b6d3f6620675 100644 --- a/en/application-dev/reference/apis/js-apis-request.md +++ b/en/application-dev/reference/apis/js-apis-request.md @@ -1,9 +1,9 @@ -# Upload and Download +# @ohos.request The **request** module provides applications with basic upload, download, and background transmission agent capabilities. > **NOTE** -> +> > The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -34,8 +34,9 @@ var config = { The **cleartextTraffic** attribute is not involved during application development in the stage model. -The download server must support the HTTP HEAD method so that the size of the data to download can be obtained through **content-length**. Otherwise, the download task fails. If this is the case, you can check the failure cause through [on('fail')7+)](#onfail7). +The download server must support the HTTP HEAD method so that the size of the data to download can be obtained through **Content-length**. Otherwise, the download task fails. If this is the case, you can check the failure cause through [on('fail')7+](#onfail7). +Only HTTP requests are supported. HTTPS requests are not supported. ## Constants @@ -69,86 +70,93 @@ The download server must support the HTTP HEAD method so that the size of the da | SESSION_SUCCESSFUL7+ | number | Yes| No| Successful download.| -## request.upload +## request.uploadFile9+ -upload(config: UploadConfig): Promise<UploadTask> +uploadFile(context: BaseContext, config: UploadConfig): Promise<UploadTask> Uploads files. This API uses a promise to return the result. -This API can be used only in the FA model. - -> **NOTE**
This API is deprecated since API version 9. You are advised to use [request.uploadFile9+](#requestuploadfile9). - **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Upload **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.| +| config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.| + **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[UploadTask](#uploadtask)> | Promise used to return the **UploadTask** object.| +| Type| Description| +| -------- | -------- | +| Promise<[UploadTask](#uploadtask)> | Promise used to return the **UploadTask** object.| + +**Error codes** +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID| Error Message| +| -------- | -------- | +| 13400002 | Bad file path. | **Example** - + ```js let uploadTask; let uploadConfig = { - url: 'https://patch', + url: 'http://patch', header: { key1: "value1", key2: "value2" }, method: "POST", files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }], data: [{ name: "name123", value: "123" }], }; - request.upload(uploadConfig).then((data) => { + request.uploadFile(globalThis.abilityContext, uploadConfig).then((data) => { uploadTask = data; }).catch((err) => { console.error('Failed to request the upload. Cause: ' + JSON.stringify(err)); - }) + }); ``` -## request.upload +## request.uploadFile9+ -upload(config: UploadConfig, callback: AsyncCallback<UploadTask>): void +uploadFile(context: BaseContext, config: UploadConfig, callback: AsyncCallback<UploadTask>): void Uploads files. This API uses an asynchronous callback to return the result. -This API can be used only in the FA model. - -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [request.uploadFile9+](#requestuploadfile9-1). - **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Upload **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.| - | callback | AsyncCallback<[UploadTask](#uploadtask)> | Yes| Callback used to return the **UploadTask** object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.| +| config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.| +| callback | AsyncCallback<[UploadTask](#uploadtask)> | Yes| Callback used to return the **UploadTask** object.| + +**Error codes** +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID| Error Message| +| -------- | -------- | +| 13400002 | Bad file path. | **Example** - + ```js let uploadTask; let uploadConfig = { - url: 'https://patch', + url: 'http://patch', header: { key1: "value1", key2: "value2" }, method: "POST", files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }], data: [{ name: "name123", value: "123" }], }; - request.upload(uploadConfig, (err, data) => { + request.uploadFile(globalThis.abilityContext, uploadConfig, (err, data) => { if (err) { console.error('Failed to request the upload. Cause: ' + JSON.stringify(err)); return; @@ -156,15 +164,18 @@ This API can be used only in the FA model. uploadTask = data; }); ``` -## request.upload9+ -upload(context: BaseContext, config: UploadConfig): Promise<UploadTask> +## request.upload(deprecated) + +upload(config: UploadConfig): Promise<UploadTask> Uploads files. This API uses a promise to return the result. -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [request.uploadFile9+](#requestuploadfile9). +**Model restriction**: This API can be used only in the FA model. + +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use [request.uploadFile9+](#requestuploadfile9). **Required permissions**: ohos.permission.INTERNET @@ -172,46 +183,46 @@ Uploads files. This API uses a promise to return the result. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | context | BaseContext | Yes| Application-based context.| - | config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.| - +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[UploadTask](#uploadtask)> | Promise used to return the **UploadTask** object.| +| Type| Description| +| -------- | -------- | +| Promise<[UploadTask](#uploadtask)> | Promise used to return the **UploadTask** object.| **Example** - + ```js let uploadTask; let uploadConfig = { - url: 'https://patch', + url: 'http://patch', header: { key1: "value1", key2: "value2" }, method: "POST", files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }], data: [{ name: "name123", value: "123" }], }; - request.upload(globalThis.abilityContext, uploadConfig).then((data) => { + request.upload(uploadConfig).then((data) => { uploadTask = data; }).catch((err) => { console.error('Failed to request the upload. Cause: ' + JSON.stringify(err)); - }); + }) ``` -## request.upload9+ +## request.upload(deprecated) -upload(context: BaseContext, config: UploadConfig, callback: AsyncCallback<UploadTask>): void +upload(config: UploadConfig, callback: AsyncCallback<UploadTask>): void Uploads files. This API uses an asynchronous callback to return the result. -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [request.uploadFile9+](#requestuploadfile9-1). +**Model restriction**: This API can be used only in the FA model. + +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use [request.uploadFile9+](#requestuploadfile9-1). **Required permissions**: ohos.permission.INTERNET @@ -219,24 +230,23 @@ Uploads files. This API uses an asynchronous callback to return the result. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | context | BaseContext | Yes| Application-based context.| - | config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.| - | callback | AsyncCallback<[UploadTask](#uploadtask)> | Yes| Callback used to return the **UploadTask** object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.| +| callback | AsyncCallback<[UploadTask](#uploadtask)> | Yes| Callback used to return the **UploadTask** object.| **Example** - + ```js let uploadTask; let uploadConfig = { - url: 'https://patch', + url: 'http://patch', header: { key1: "value1", key2: "value2" }, method: "POST", files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }], data: [{ name: "name123", value: "123" }], }; - request.upload(globalThis.abilityContext, uploadConfig, (err, data) => { + request.upload(uploadConfig, (err, data) => { if (err) { console.error('Failed to request the upload. Cause: ' + JSON.stringify(err)); return; @@ -245,13 +255,16 @@ Uploads files. This API uses an asynchronous callback to return the result. }); ``` +## request.upload(deprecated) -## request.uploadFile9+ - -uploadFile(context: BaseContext, config: UploadConfig): Promise<UploadTask> +upload(context: BaseContext, config: UploadConfig): Promise<UploadTask> Uploads files. This API uses a promise to return the result. +> **NOTE** +> +> This API is supported since API version 9 and is deprecated since API version 9. You are advised to use [request.uploadFile9+](#requestuploadfile9). + **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Upload @@ -259,36 +272,29 @@ Uploads files. This API uses a promise to return the result. **Parameters** | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | -| context | BaseContext | Yes| Application-based context.| +| -------- | -------- | -------- | -------- | +| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.| | config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.| **Return value** | Type| Description| - | -------- | -------- | -| Promise<[UploadTask](#uploadtask)> | Promise used to return the **UploadTask** object.| - -**Error codes** -For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). - -| ID| Error Message| | -------- | -------- | -| 13400002 | Bad file path. | +| Promise<[UploadTask](#uploadtask)> | Promise used to return the **UploadTask** object.| **Example** ```js let uploadTask; let uploadConfig = { - url: 'https://patch', + url: 'http://patch', header: { key1: "value1", key2: "value2" }, method: "POST", files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }], data: [{ name: "name123", value: "123" }], }; - request.uploadFile(globalThis.abilityContext, uploadConfig).then((data) => { + request.upload(globalThis.abilityContext, uploadConfig).then((data) => { uploadTask = data; }).catch((err) => { console.error('Failed to request the upload. Cause: ' + JSON.stringify(err)); @@ -296,12 +302,16 @@ For details about the error codes, see [Upload and Download Error Codes](../erro ``` -## request.uploadFile9+ +## request.upload(deprecated) -uploadFile(context: BaseContext, config: UploadConfig, callback: AsyncCallback<UploadTask>): void +upload(context: BaseContext, config: UploadConfig, callback: AsyncCallback<UploadTask>): void Uploads files. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use [request.uploadFile9+](#requestuploadfile9-1). + **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Upload @@ -309,30 +319,23 @@ Uploads files. This API uses an asynchronous callback to return the result. **Parameters** | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | -| context | BaseContext | Yes| Application-based context.| +| -------- | -------- | -------- | -------- | +| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.| | config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.| | callback | AsyncCallback<[UploadTask](#uploadtask)> | Yes| Callback used to return the **UploadTask** object.| -**Error codes** -For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). - -| ID| Error Message| -| -------- | -------- | -| 13400002 | Bad file path. | - **Example** ```js let uploadTask; let uploadConfig = { - url: 'https://patch', + url: 'http://patch', header: { key1: "value1", key2: "value2" }, method: "POST", files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }], data: [{ name: "name123", value: "123" }], }; - request.uploadFile(globalThis.abilityContext, uploadConfig, (err, data) => { + request.upload(globalThis.abilityContext, uploadConfig, (err, data) => { if (err) { console.error('Failed to request the upload. Cause: ' + JSON.stringify(err)); return; @@ -341,10 +344,10 @@ For details about the error codes, see [Upload and Download Error Codes](../erro }); ``` - ## UploadTask -Implements file uploads. Before using any APIs of this class, you must obtain an **UploadTask** object. +Implements file uploads. Before using any APIs of this class, you must obtain an **UploadTask** object through [request.uploadFile9+](#requestuploadfile9) in promise mode or [request.uploadFile9+](#requestuploadfile9-1) in callback mode. + ### on('progress') @@ -359,10 +362,10 @@ Subscribes to an upload event. This API uses an asynchronous callback to return **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to subscribe to. The value is **'progress'** (upload progress).| - | callback | function | Yes| Callback for the upload progress event.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to subscribe to. The value is **'progress'** (upload progress).| +| callback | function | Yes| Callback for the upload progress event.| Parameters of the callback function @@ -372,9 +375,8 @@ Subscribes to an upload event. This API uses an asynchronous callback to return | totalSize | number | Yes| Total size of the files to upload, in KB.| **Example** - + ```js - let uploadTask; uploadTask.on('progress', function callback(uploadedSize, totalSize) { console.info("upload totalSize:" + totalSize + " uploadedSize:" + uploadedSize); } @@ -394,10 +396,10 @@ Subscribes to an upload event. This API uses an asynchronous callback to return **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to subscribe to. The value is **'headerReceive'** (response header).| - | callback | function | Yes| Callback for the HTTP Response Header event.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to subscribe to. The value is **'headerReceive'** (response header).| +| callback | function | Yes| Callback for the HTTP Response Header event.| Parameters of the callback function @@ -406,9 +408,8 @@ Subscribes to an upload event. This API uses an asynchronous callback to return | header | object | Yes| HTTP Response Header.| **Example** - + ```js - let uploadTask; uploadTask.on('headerReceive', function callback(headers){ console.info("upOnHeader headers:" + JSON.stringify(headers)); } @@ -428,10 +429,10 @@ Subscribes to an upload event. This API uses an asynchronous callback to return **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to subscribe to. The value **'complete'** means the upload completion event, and **'fail'** means the upload failure event.| - | callback | Callback<Array<TaskState>> | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to subscribe to. The value **'complete'** means the upload completion event, and **'fail'** means the upload failure event.| +| callback | Callback<Array<TaskState>> | Yes| Callback used to return the result.| Parameters of the callback function @@ -440,9 +441,8 @@ Subscribes to an upload event. This API uses an asynchronous callback to return | taskstates | Array<[TaskState](#taskstate9)> | Yes| Upload result.| **Example** - + ```js - let uploadTask; uploadTask.on('complete', function callback(taskStates) { for (let i = 0; i < taskStates.length; i++ ) { console.info("upOnComplete taskState:" + JSON.stringify(taskStates[i])); @@ -471,10 +471,10 @@ Unsubscribes from an upload event. This API uses an asynchronous callback to ret **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to unsubscribe from. The value is **'progress'** (upload progress).| - | callback | function | No| Callback for the upload progress event.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to unsubscribe from. The value is **'progress'** (upload progress).| +| callback | function | No| Callback for the upload progress event.| Parameters of the callback function @@ -484,9 +484,8 @@ Unsubscribes from an upload event. This API uses an asynchronous callback to ret | totalSize | number | Yes| Total size of the files to upload, in KB.| **Example** - + ```js - let uploadTask; uploadTask.off('progress', function callback(uploadedSize, totalSize) { console.info('uploadedSize: ' + uploadedSize, 'totalSize: ' + totalSize); } @@ -506,10 +505,10 @@ Unsubscribes from an upload event. This API uses an asynchronous callback to ret **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to unsubscribe from. The value is **'headerReceive'** (response header).| - | callback | function | No| Callback for the HTTP Response Header event.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to unsubscribe from. The value is **'headerReceive'** (response header).| +| callback | function | No| Callback for the HTTP Response Header event.| Parameters of the callback function @@ -518,9 +517,8 @@ Unsubscribes from an upload event. This API uses an asynchronous callback to ret | header | object | Yes| HTTP Response Header.| **Example** - + ```js - let uploadTask; uploadTask.off('headerReceive', function callback(headers) { console.info("upOnHeader headers:" + JSON.stringify(headers)); } @@ -539,10 +537,10 @@ Unsubscribes from an upload event. This API uses an asynchronous callback to ret **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to subscribe to. The value **'complete'** means the upload completion event, and **'fail'** means the upload failure event.| - | callback | Callback<Array<TaskState>> | No| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to subscribe to. The value **'complete'** means the upload completion event, and **'fail'** means the upload failure event.| +| callback | Callback<Array<TaskState>> | No| Callback used to return the result.| Parameters of the callback function @@ -551,9 +549,8 @@ Unsubscribes from an upload event. This API uses an asynchronous callback to ret | taskstates | Array<[TaskState](#taskstate9)> | Yes| Upload result.| **Example** - + ```js - let uploadTask; uploadTask.off('complete', function callback(taskStates) { for (let i = 0; i < taskStates.length; i++ ) { console.info("upOnComplete taskState:" + JSON.stringify(taskStates[i])); @@ -569,16 +566,10 @@ Unsubscribes from an upload event. This API uses an asynchronous callback to ret ); ``` +### delete9+ +delete(): Promise<boolean> -### remove - -remove(): Promise<boolean> - -Removes this upload task. This API uses a promise to return the result. - -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [delete9+](#delete9). +Deletes this upload task. This API uses a promise to return the result. **Required permissions**: ohos.permission.INTERNET @@ -586,15 +577,14 @@ Removes this upload task. This API uses a promise to return the result. **Return value** - | Type| Description| - | -------- | -------- | - | Promise<boolean> | Promise used to return the result. It returns **true** if the operation is successful and returns **false** otherwise.| +| Type| Description| +| -------- | -------- | +| Promise<boolean> | Promise used to return the task removal result. It returns **true** if the operation is successful and returns **false** otherwise.| **Example** - + ```js - let uploadTask; - uploadTask.remove().then((result) => { + uploadTask.delete().then((result) => { if (result) { console.info('Upload task removed successfully. '); } else { @@ -606,31 +596,26 @@ Removes this upload task. This API uses a promise to return the result. ``` -### remove +### delete9+ -remove(callback: AsyncCallback<boolean>): void +delete(callback: AsyncCallback<boolean>): void Removes this upload task. This API uses an asynchronous callback to return the result. -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [delete9+](#delete9-1). - **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Upload **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<boolean> | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<boolean> | Yes| Callback used to return the result.| **Example** - + ```js - let uploadTask; - uploadTask.remove((err, result) => { + uploadTask.delete((err, result) => { if (err) { console.error('Failed to remove the upload task. Cause: ' + JSON.stringify(err)); return; @@ -644,11 +629,15 @@ Removes this upload task. This API uses an asynchronous callback to return the r ``` -### delete9+ +### remove(deprecated) -delete(): Promise<boolean> +remove(): Promise<boolean> -Deletes this upload task. This API uses a promise to return the result. +Removes this upload task. This API uses a promise to return the result. + +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use [delete9+](#delete9). **Required permissions**: ohos.permission.INTERNET @@ -657,14 +646,13 @@ Deletes this upload task. This API uses a promise to return the result. **Return value** | Type| Description| - | -------- | -------- | -| Promise<boolean> | Promise used to return the task deletion result. It returns **true** if the operation is successful and returns **false** otherwise.| +| -------- | -------- | +| Promise<boolean> | Promise used to return the task removal result. It returns **true** if the operation is successful and returns **false** otherwise.| **Example** ```js - let uploadTask; - uploadTask.delete().then((result) => { + uploadTask.remove().then((result) => { if (result) { console.info('Upload task removed successfully. '); } else { @@ -676,11 +664,15 @@ Deletes this upload task. This API uses a promise to return the result. ``` -### delete9+ +### remove(deprecated) -delete(callback: AsyncCallback<boolean>): void +remove(callback: AsyncCallback<boolean>): void + +Removes this upload task. This API uses an asynchronous callback to return the result. -Deletes this upload task. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use [delete9+](#delete9-1). **Required permissions**: ohos.permission.INTERNET @@ -689,14 +681,13 @@ Deletes this upload task. This API uses an asynchronous callback to return the r **Parameters** | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | +| -------- | -------- | -------- | -------- | | callback | AsyncCallback<boolean> | Yes| Callback used to return the result.| **Example** ```js - let uploadTask; - uploadTask.delete((err, result) => { + uploadTask.remove((err, result) => { if (err) { console.error('Failed to remove the upload task. Cause: ' + JSON.stringify(err)); return; @@ -709,7 +700,6 @@ Deletes this upload task. This API uses an asynchronous callback to return the r }); ``` - ## UploadConfig **Required permissions**: ohos.permission.INTERNET @@ -746,7 +736,7 @@ Deletes this upload task. This API uses an asynchronous callback to return the r | -------- | -------- | -------- | -------- | | filename | string | Yes| File name in the header when **multipart** is used.| | name | string | Yes| Name of a form item when **multipart** is used. The default value is **file**.| -| uri | string | Yes| Local path for storing files.
The **dataability** and **internal** protocol types are supported. However, the **internal** protocol type supports only temporary directories. Below are examples:
dataability:///com.domainname.dataability.persondata/person/10/file.txt
internal://cache/path/to/file.txt | +| uri | string | Yes| Local path for storing files.
The **dataability** and **internal** protocol types are supported. However, the **internal** protocol type supports only temporary directories. Below are examples:
dataability:///com.domainname.dataability.persondata/person/10/file.txt

internal://cache/path/to/file.txt | | type | string | Yes| Type of the file content. By default, the type is obtained based on the extension of the file name or URI.| @@ -761,40 +751,43 @@ Deletes this upload task. This API uses an asynchronous callback to return the r | name | string | Yes| Name of a form element.| | value | string | Yes| Value of a form element.| +## request.downloadFile9+ -## request.download - -download(config: DownloadConfig): Promise<DownloadTask> +downloadFile(context: BaseContext, config: DownloadConfig): Promise<DownloadTask> Downloads files. This API uses a promise to return the result. -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [request.downloadFile9+](#requestdownloadfile9). - -This API can be used only in the FA model. - **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.| +| config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[DownloadTask](#downloadtask)> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<[DownloadTask](#downloadtask)> | Promise used to return the result.| + +**Error codes** +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID| Error Message| +| -------- | -------- | +| 13400001 | File operation error. | +| 13400002 | Bad file path. | +| 13400003 | Task manager service error. | **Example** - + ```js let downloadTask; - request.download({ url: 'https://xxxx/xxxx.hap' }).then((data) => { + request.downloadFile(globalThis.abilityContext, { url: 'https://xxxx/xxxx.hap' }).then((data) => { downloadTask = data; }).catch((err) => { console.error('Failed to request the download. Cause: ' + JSON.stringify(err)); @@ -802,34 +795,38 @@ This API can be used only in the FA model. ``` -## request.download +## request.downloadFile9+ -download(config: DownloadConfig, callback: AsyncCallback<DownloadTask>): void +downloadFile(context: BaseContext, config: DownloadConfig, callback: AsyncCallback<DownloadTask>): void; Downloads files. This API uses an asynchronous callback to return the result. -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [request.downloadFile9+](#requestdownloadfile9-1). - -This API can be used only in the FA model. - **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.| - | callback | AsyncCallback<[DownloadTask](#downloadtask)> | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.| +| config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.| +| callback | AsyncCallback<[DownloadTask](#downloadtask)> | Yes| Callback used to return the result.| + +**Error codes** +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID| Error Message| +| -------- | -------- | +| 13400001 | File operation error. | +| 13400002 | Bad file path. | +| 13400003 | Task manager service error. | **Example** - + ```js let downloadTask; - request.download({ url: 'https://xxxx/xxxxx.hap', + request.downloadFile(globalThis.abilityContext, { url: 'https://xxxx/xxxxx.hap', filePath: 'xxx/xxxxx.hap'}, (err, data) => { if (err) { console.error('Failed to request the download. Cause: ' + JSON.stringify(err)); @@ -839,15 +836,17 @@ This API can be used only in the FA model. }); ``` -## request.download9+ +## request.download(deprecated) -download(context: BaseContext, config: DownloadConfig): Promise<DownloadTask> +download(config: DownloadConfig): Promise<DownloadTask> Downloads files. This API uses a promise to return the result. -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [request.downloadFile9+](#requestdownloadfile9). +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use [request.downloadFile9+](#requestdownloadfile9). + +**Model restriction**: This API can be used only in the FA model. **Required permissions**: ohos.permission.INTERNET @@ -855,22 +854,21 @@ Downloads files. This API uses a promise to return the result. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | context | BaseContext | Yes| Application-based context.| - | config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[DownloadTask](#downloadtask)> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<[DownloadTask](#downloadtask)> | Promise used to return the result.| **Example** - + ```js let downloadTask; - request.download(globalThis.abilityContext, { url: 'https://xxxx/xxxx.hap' }).then((data) => { + request.download({ url: 'https://xxxx/xxxx.hap' }).then((data) => { downloadTask = data; }).catch((err) => { console.error('Failed to request the download. Cause: ' + JSON.stringify(err)); @@ -878,15 +876,17 @@ Downloads files. This API uses a promise to return the result. ``` -## request.download9+ +## request.download(deprecated) -download(context: BaseContext, config: DownloadConfig, callback: AsyncCallback<DownloadTask>): void; +download(config: DownloadConfig, callback: AsyncCallback<DownloadTask>): void Downloads files. This API uses an asynchronous callback to return the result. -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [request.downloadFile9+](#requestdownloadfile9-1). +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use [request.downloadFile9+](#requestdownloadfile9-1). + +**Model restriction**: This API can be used only in the FA model. **Required permissions**: ohos.permission.INTERNET @@ -894,17 +894,16 @@ Downloads files. This API uses an asynchronous callback to return the result. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | context | BaseContext | Yes| Application-based context.| - | config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.| - | callback | AsyncCallback<[DownloadTask](#downloadtask)> | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.| +| callback | AsyncCallback<[DownloadTask](#downloadtask)> | Yes| Callback used to return the result.| **Example** - + ```js let downloadTask; - request.download(globalThis.abilityContext, { url: 'https://xxxx/xxxxx.hap', + request.download({ url: 'https://xxxx/xxxxx.hap', filePath: 'xxx/xxxxx.hap'}, (err, data) => { if (err) { console.error('Failed to request the download. Cause: ' + JSON.stringify(err)); @@ -914,13 +913,16 @@ Downloads files. This API uses an asynchronous callback to return the result. }); ``` +## request.download(deprecated) -## request.downloadFile9+ - -downloadFile(context: BaseContext, config: DownloadConfig): Promise<DownloadTask> +download(context: BaseContext, config: DownloadConfig): Promise<DownloadTask> Downloads files. This API uses a promise to return the result. +> **NOTE** +> +> This API is supported since API version 9 and is deprecated since API version 9. You are advised to use [request.downloadFile9+](#requestdownloadfile9). + **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -928,30 +930,21 @@ Downloads files. This API uses a promise to return the result. **Parameters** | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | -| context | BaseContext | Yes| Application-based context.| +| -------- | -------- | -------- | -------- | +| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.| | config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.| **Return value** | Type| Description| - | -------- | -------- | -| Promise<[DownloadTask](#downloadtask)> | Promise used to return the result.| - -**Error codes** -For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). - -| ID| Error Message| | -------- | -------- | -| 13400001 | File operation error. | -| 13400002 | Bad file path. | -| 13400003 | Task manager service error. | +| Promise<[DownloadTask](#downloadtask)> | Promise used to return the result.| **Example** ```js let downloadTask; - request.downloadFile(globalThis.abilityContext, { url: 'https://xxxx/xxxx.hap' }).then((data) => { + request.download(globalThis.abilityContext, { url: 'https://xxxx/xxxx.hap' }).then((data) => { downloadTask = data; }).catch((err) => { console.error('Failed to request the download. Cause: ' + JSON.stringify(err)); @@ -959,12 +952,16 @@ For details about the error codes, see [Upload and Download Error Codes](../erro ``` -## request.downloadFile9+ +## request.download(deprecated) -downloadFile(context: BaseContext, config: DownloadConfig, callback: AsyncCallback<DownloadTask>): void; +download(context: BaseContext, config: DownloadConfig, callback: AsyncCallback<DownloadTask>): void; Downloads files. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use [request.downloadFile9+](#requestdownloadfile9-1). + **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -972,25 +969,16 @@ Downloads files. This API uses an asynchronous callback to return the result. **Parameters** | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | -| context | BaseContext | Yes| Application-based context.| +| -------- | -------- | -------- | -------- | +| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.| | config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.| | callback | AsyncCallback<[DownloadTask](#downloadtask)> | Yes| Callback used to return the result.| -**Error codes** -For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). - -| ID| Error Message| -| -------- | -------- | -| 13400001 | File operation error. | -| 13400002 | Bad file path. | -| 13400003 | Task manager service error. | - **Example** ```js let downloadTask; - request.downloadFile(globalThis.abilityContext, { url: 'https://xxxx/xxxxx.hap', + request.download(globalThis.abilityContext, { url: 'https://xxxx/xxxxx.hap', filePath: 'xxx/xxxxx.hap'}, (err, data) => { if (err) { console.error('Failed to request the download. Cause: ' + JSON.stringify(err)); @@ -1003,7 +991,7 @@ For details about the error codes, see [Upload and Download Error Codes](../erro ## DownloadTask -Implements file downloads. +Implements file downloads. Before using any APIs of this class, you must obtain a **DownloadTask** object through [request.downloadFile9+](#requestdownloadfile9) in promise mode or [request.downloadFile9+](#requestdownloadfile9-1) in callback mode. ### on('progress') @@ -1018,10 +1006,10 @@ Subscribes to a download event. This API uses an asynchronous callback to return **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to subscribe to. The value is **'progress'** (download progress).| - | callback | function | Yes| Callback for the download progress event.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to subscribe to. The value is **'progress'** (download progress).| +| callback | function | Yes| Callback for the download progress event.| Parameters of the callback function @@ -1031,9 +1019,8 @@ Subscribes to a download event. This API uses an asynchronous callback to return | totalSize | number | Yes| Total size of the files to download, in KB.| **Example** - + ```js - let downloadTask; downloadTask.on('progress', function download_callback(receivedSize, totalSize) { console.info("download receivedSize:" + receivedSize + " totalSize:" + totalSize); } @@ -1053,10 +1040,10 @@ Unsubscribes from a download event. This API uses an asynchronous callback to re **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to unsubscribe from. The value is **'progress'** (download progress).| - | callback | function | No| Callback for the download progress event.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to unsubscribe from. The value is **'progress'** (download progress).| +| callback | function | No| Callback for the download progress event.| Parameters of the callback function @@ -1066,7 +1053,7 @@ Unsubscribes from a download event. This API uses an asynchronous callback to re | totalSize | number | Yes| Total size of the files to download.| **Example** - + ```js downloadTask .off('progress', function download_callback(receivedSize, totalSize) { console.info("download receivedSize:" + receivedSize + " totalSize:" + totalSize); @@ -1087,15 +1074,14 @@ Subscribes to a download event. This API uses an asynchronous callback to return **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to subscribe to.
- **'complete'**: download task completion event.
- **'pause'**: download task pause event.
- **'remove'**: download task removal event.| - | callback | function | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to subscribe to.
- **'complete'**: download task completion event.
- **'pause'**: download task pause event.
- **'remove'**: download task removal event.| +| callback | function | Yes| Callback used to return the result.| **Example** - + ```js - let downloadTask; downloadTask.on('complete', function callback() { console.info('Download task completed.'); } @@ -1115,15 +1101,14 @@ Unsubscribes from a download event. This API uses an asynchronous callback to re **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to unsubscribe from.
- **'complete'**: download task completion event.
- **'pause'**: download task pause event.
- **'remove'**: download task removal event.| - | callback | function | No| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to unsubscribe from.
- **'complete'**: download task completion event.
- **'pause'**: download task pause event.
- **'remove'**: download task removal event.| +| callback | function | No| Callback used to return the result.| **Example** - + ```js - let downloadTask; downloadTask.off('complete', function callback() { console.info('Download task completed.'); } @@ -1143,10 +1128,10 @@ Subscribes to the download task failure event. This API uses an asynchronous cal **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to subscribe to. The value is **'fail'** (download failure).| - | callback | function | Yes| Callback for the download task failure event.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to subscribe to. The value is **'fail'** (download failure).| +| callback | function | Yes| Callback for the download task failure event.| Parameters of the callback function @@ -1155,9 +1140,8 @@ Subscribes to the download task failure event. This API uses an asynchronous cal | err | number | Yes| Error code of the download failure. For details about the error codes, see [ERROR_*](#constants).| **Example** - + ```js - let downloadTask; downloadTask.on('fail', function callBack(err) { console.info('Download task failed. Cause:' + err); } @@ -1177,10 +1161,10 @@ Unsubscribes from the download task failure event. This API uses an asynchronous **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to unsubscribe from. The value is **'fail'** (download failure).| - | callback | function | No| Callback for the download task failure event.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to unsubscribe from. The value is **'fail'** (download failure).| +| callback | function | No| Callback for the download task failure event.| Parameters of the callback function @@ -1189,41 +1173,34 @@ Unsubscribes from the download task failure event. This API uses an asynchronous | err | number | Yes| Error code of the download failure. For details about the error codes, see [ERROR_*](#constants).| **Example** - + ```js - let downloadTask; downloadTask.off('fail', function callBack(err) { console.info('Download task failed. Cause:' + err); } ); ``` + ### delete9+ -### remove - -remove(): Promise<boolean> +delete(): Promise<boolean> Removes this download task. This API uses a promise to return the result. -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [delete9+](#delete9-2). - **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download **Return value** - | Type| Description| - | -------- | -------- | - | Promise<boolean> | Promise used to return the task removal result.| +| Type| Description| +| -------- | -------- | +| Promise<boolean> | Promise used to return the task removal result.| **Example** - + ```js - let downloadTask; - downloadTask.remove().then((result) => { + downloadTask.delete().then((result) => { if (result) { console.info('Download task removed.'); } else { @@ -1235,31 +1212,26 @@ Removes this download task. This API uses a promise to return the result. ``` -### remove +### delete9+ -remove(callback: AsyncCallback<boolean>): void +delete(callback: AsyncCallback<boolean>): void Removes this download task. This API uses an asynchronous callback to return the result. -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [delete9+](#delete9-3). - **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<boolean> | Yes| Callback used to return the task removal result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<boolean> | Yes| Callback used to return the task removal result.| **Example** - + ```js - let downloadTask; - downloadTask.remove((err, result)=>{ + downloadTask.delete((err, result)=>{ if(err) { console.error('Failed to remove the download task.'); return; @@ -1273,31 +1245,26 @@ Removes this download task. This API uses an asynchronous callback to return the ``` -### query7+ +### getTaskInfo9+ -query(): Promise<DownloadInfo> +getTaskInfo(): Promise<DownloadInfo> Queries this download task. This API uses a promise to return the result. -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [getTaskInfo9+](#gettaskinfo9). - **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[DownloadInfo](#downloadinfo7)> | Promise used to return the download task information.| +| Type| Description| +| -------- | -------- | +| Promise<[DownloadInfo](#downloadinfo7)> | Promise used to return the download task information.| **Example** - + ```js - let downloadTask; - downloadTask.query().then((downloadInfo) => { + downloadTask.getTaskInfo().then((downloadInfo) => { console.info('Download task queried. Data:' + JSON.stringify(downloadInfo)) }) .catch((err) => { console.error('Failed to query the download task. Cause:' + err) @@ -1305,31 +1272,26 @@ Queries this download task. This API uses a promise to return the result. ``` -### query7+ +### getTaskInfo9+ -query(callback: AsyncCallback<DownloadInfo>): void +getTaskInfo(callback: AsyncCallback<DownloadInfo>): void Queries this download task. This API uses an asynchronous callback to return the result. -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [getTaskInfo9+](#gettaskinfo9-1). - **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[DownloadInfo](#downloadinfo7)> | Yes| Callback used to return the download task information.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<[DownloadInfo](#downloadinfo7)> | Yes| Callback used to return the download task information.| **Example** - + ```js - let downloadTask; - downloadTask.query((err, downloadInfo)=>{ + downloadTask.getTaskInfo((err, downloadInfo)=>{ if(err) { console.error('Failed to query the download mimeType. Cause:' + JSON.stringify(err)); } else { @@ -1339,15 +1301,11 @@ Queries this download task. This API uses an asynchronous callback to return the ``` -### queryMimeType7+ - -queryMimeType(): Promise<string> +### getTaskMimeType9+ -Queries the **MimeType** of this download task. This API uses a promise to return the result. +getTaskMimeType(): Promise<string> -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [getTaskMimeType9+](#gettaskmimetype9). +Obtains the **MimeType** of this download task. This API uses a promise to return the result. **Required permissions**: ohos.permission.INTERNET @@ -1355,15 +1313,14 @@ Queries the **MimeType** of this download task. This API uses a promise to retur **Return value** - | Type| Description| - | -------- | -------- | - | Promise<string> | Promise used to return the **MimeType** of the download task.| +| Type| Description| +| -------- | -------- | +| Promise<string> | Promise used to return the **MimeType** of the download task.| **Example** - + ```js - let downloadTask; - downloadTask.queryMimeType().then((data) => { + downloadTask.getTaskMimeType().then((data) => { console.info('Download task queried. Data:' + JSON.stringify(data)); }).catch((err) => { console.error('Failed to query the download MimeType. Cause:' + JSON.stringify(err)) @@ -1371,15 +1328,11 @@ Queries the **MimeType** of this download task. This API uses a promise to retur ``` -### queryMimeType7+ - -queryMimeType(callback: AsyncCallback<string>): void; +### getTaskMimeType9+ -Queries the **MimeType** of this download task. This API uses an asynchronous callback to return the result. +getTaskMimeType(callback: AsyncCallback<string>): void; -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [getTaskMimeType9+](#gettaskmimetype9-1). +Obtains the **MimeType** of this download task. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.INTERNET @@ -1387,15 +1340,14 @@ Queries the **MimeType** of this download task. This API uses an asynchronous ca **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<string> | Yes| Callback used to return the **MimeType** of the download task.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<string> | Yes| Callback used to return the **MimeType** of the download task.| **Example** - + ```js - let downloadTask; - downloadTask.queryMimeType((err, data)=>{ + downloadTask.getTaskMimeType((err, data)=>{ if(err) { console.error('Failed to query the download mimeType. Cause:' + JSON.stringify(err)); } else { @@ -1405,31 +1357,26 @@ Queries the **MimeType** of this download task. This API uses an asynchronous ca ``` -### pause7+ +### suspend9+ -pause(): Promise<void> +suspend(): Promise<boolean> Pauses this download task. This API uses a promise to return the result. -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [suspend9+](#suspend9). - **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the download task pause result.| +| Type| Description| +| -------- | -------- | +| Promise<boolean> | Promise used to return the download task pause result.| **Example** - + ```js - let downloadTask; - downloadTask.pause().then((result) => { + downloadTask.suspend().then((result) => { if (result) { console.info('Download task paused. '); } else { @@ -1441,13 +1388,9 @@ Pauses this download task. This API uses a promise to return the result. ``` -### pause7+ - -pause(callback: AsyncCallback<void>): void +### suspend9+ -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [suspend9+](#suspend9-1). +suspend(callback: AsyncCallback<boolean>): void Pauses this download task. This API uses an asynchronous callback to return the result. @@ -1457,15 +1400,14 @@ Pauses this download task. This API uses an asynchronous callback to return the **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<boolean> | Yes| Callback used to return the result.| **Example** - + ```js - let downloadTask; - downloadTask.pause((err, result)=>{ + downloadTask.suspend((err, result)=>{ if(err) { console.error('Failed to pause the download task. Cause:' + JSON.stringify(err)); return; @@ -1479,31 +1421,26 @@ Pauses this download task. This API uses an asynchronous callback to return the ``` -### resume7+ +### restore9+ -resume(): Promise<void> +restore(): Promise<boolean> Resumes this download task. This API uses a promise to return the result. -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [restore9+](#restore9). - **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<boolean> | Promise used to return the result.| **Example** - + ```js - let downloadTask; - downloadTask.resume().then((result) => { + downloadTask.restore().then((result) => { if (result) { console.info('Download task resumed.') } else { @@ -1516,13 +1453,9 @@ Resumes this download task. This API uses a promise to return the result. ``` -### resume7+ - -resume(callback: AsyncCallback<void>): void +### restore9+ -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [restore9+](#restore9-1). +restore(callback: AsyncCallback<boolean>): void Resumes this download task. This API uses an asynchronous callback to return the result. @@ -1532,15 +1465,14 @@ Resumes this download task. This API uses an asynchronous callback to return the **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<boolean> | Yes| Callback used to return the result.| **Example** - + ```js - let downloadTask; - downloadTask.resume((err, result)=>{ + downloadTask.restore((err, result)=>{ if (err) { console.error('Failed to resume the download task. Cause:' + err); return; @@ -1554,11 +1486,16 @@ Resumes this download task. This API uses an asynchronous callback to return the ``` -### delete9+ -delete(): Promise<boolean> +### remove(deprecated) -Deletes this download task. This API uses a promise to return the result. +remove(): Promise<boolean> + +Removes this download task. This API uses a promise to return the result. + +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use [delete9+](#delete9-2). **Required permissions**: ohos.permission.INTERNET @@ -1567,14 +1504,13 @@ Deletes this download task. This API uses a promise to return the result. **Return value** | Type| Description| - | -------- | -------- | -| Promise<boolean> | Promise used to return the result.| +| -------- | -------- | +| Promise<boolean> | Promise used to return the task removal result.| **Example** ```js - let downloadTask; - downloadTask.delete().then((result) => { + downloadTask.remove().then((result) => { if (result) { console.info('Download task removed.'); } else { @@ -1586,11 +1522,15 @@ Deletes this download task. This API uses a promise to return the result. ``` -### delete9+ +### remove(deprecated) -delete(callback: AsyncCallback<boolean>): void +remove(callback: AsyncCallback<boolean>): void -Deletes this download task. This API uses an asynchronous callback to return the result. +Removes this download task. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use [delete9+](#delete9-3). **Required permissions**: ohos.permission.INTERNET @@ -1599,14 +1539,13 @@ Deletes this download task. This API uses an asynchronous callback to return the **Parameters** | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<boolean> | Yes| Callback used to return the result.| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<boolean> | Yes| Callback used to return the task removal result.| **Example** ```js - let downloadTask; - downloadTask.delete((err, result)=>{ + downloadTask.remove((err, result)=>{ if(err) { console.error('Failed to remove the download task.'); return; @@ -1620,12 +1559,16 @@ Deletes this download task. This API uses an asynchronous callback to return the ``` -### getTaskInfo9+ +### query(deprecated) -getTaskInfo(): Promise<DownloadInfo> +query(): Promise<DownloadInfo> Queries this download task. This API uses a promise to return the result. +> **NOTE** +> +> This API is supported since API version 7 and is deprecated since API version 9. You are advised to use [getTaskInfo9+](#gettaskinfo9). + **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -1639,8 +1582,7 @@ Queries this download task. This API uses a promise to return the result. **Example** ```js - let downloadTask; - downloadTask.getTaskInfo().then((downloadInfo) => { + downloadTask.query().then((downloadInfo) => { console.info('Download task queried. Data:' + JSON.stringify(downloadInfo)) }) .catch((err) => { console.error('Failed to query the download task. Cause:' + err) @@ -1648,12 +1590,16 @@ Queries this download task. This API uses a promise to return the result. ``` -### getTaskInfo9+ +### query(deprecated) query(callback: AsyncCallback<DownloadInfo>): void Queries this download task. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is supported since API version 7 and is deprecated since API version 9. You are advised to use [getTaskInfo9+](#gettaskinfo9-1). + **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -1661,14 +1607,13 @@ Queries this download task. This API uses an asynchronous callback to return the **Parameters** | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | +| -------- | -------- | -------- | -------- | | callback | AsyncCallback<[DownloadInfo](#downloadinfo7)> | Yes| Callback used to return the download task information.| **Example** ```js - let downloadTask; - downloadTask.getTaskInfo((err, downloadInfo)=>{ + downloadTask.query((err, downloadInfo)=>{ if(err) { console.error('Failed to query the download mimeType. Cause:' + JSON.stringify(err)); } else { @@ -1678,11 +1623,15 @@ Queries this download task. This API uses an asynchronous callback to return the ``` -### getTaskMimeType9+ +### queryMimeType(deprecated) -getTaskMimeType(): Promise<string> +queryMimeType(): Promise<string> -Obtains the **MimeType** of this download task. This API uses a promise to return the result. +Queries the **MimeType** of this download task. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and is deprecated since API version 9. You are advised to use [getTaskMimeType9+](#gettaskmimetype9). **Required permissions**: ohos.permission.INTERNET @@ -1691,14 +1640,13 @@ Obtains the **MimeType** of this download task. This API uses a promise to retur **Return value** | Type| Description| - | -------- | -------- | +| -------- | -------- | | Promise<string> | Promise used to return the **MimeType** of the download task.| **Example** ```js - let downloadTask; - downloadTask.getTaskMimeType().then((data) => { + downloadTask.queryMimeType().then((data) => { console.info('Download task queried. Data:' + JSON.stringify(data)); }).catch((err) => { console.error('Failed to query the download MimeType. Cause:' + JSON.stringify(err)) @@ -1706,11 +1654,15 @@ Obtains the **MimeType** of this download task. This API uses a promise to retur ``` -### getTaskMimeType9+ +### queryMimeType(deprecated) -getTaskMimeType(callback: AsyncCallback<string>): void; +queryMimeType(callback: AsyncCallback<string>): void; -Obtains the **MimeType** of this download task. This API uses an asynchronous callback to return the result. +Queries the **MimeType** of this download task. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and is deprecated since API version 9. You are advised to use [getTaskMimeType9+](#gettaskmimetype9-1). **Required permissions**: ohos.permission.INTERNET @@ -1719,14 +1671,13 @@ Obtains the **MimeType** of this download task. This API uses an asynchronous ca **Parameters** | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | +| -------- | -------- | -------- | -------- | | callback | AsyncCallback<string> | Yes| Callback used to return the **MimeType** of the download task.| **Example** ```js - let downloadTask; - downloadTask.getTaskMimeType((err, data)=>{ + downloadTask.queryMimeType((err, data)=>{ if(err) { console.error('Failed to query the download mimeType. Cause:' + JSON.stringify(err)); } else { @@ -1736,12 +1687,16 @@ Obtains the **MimeType** of this download task. This API uses an asynchronous ca ``` -### suspend9+ +### pause(deprecated) -suspend(): Promise<boolean> +pause(): Promise<void> Pauses this download task. This API uses a promise to return the result. +> **NOTE** +> +> This API is supported since API version 7 and is deprecated since API version 9. You are advised to use [suspend9+](#suspend9). + **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -1749,14 +1704,13 @@ Pauses this download task. This API uses a promise to return the result. **Return value** | Type| Description| - | -------- | -------- | -| Promise<boolean> | Promise used to return the download task pause result.| +| -------- | -------- | +| Promise<void> | Promise used to return the download task pause result.| **Example** ```js - let downloadTask; - downloadTask.suspend().then((result) => { + downloadTask.pause().then((result) => { if (result) { console.info('Download task paused. '); } else { @@ -1768,9 +1722,13 @@ Pauses this download task. This API uses a promise to return the result. ``` -### suspend9+ +### pause(deprecated) -suspend(callback: AsyncCallback<boolean>): void +pause(callback: AsyncCallback<void>): void + +> **NOTE** +> +> This API is supported since API version 7 and is deprecated since API version 9. You are advised to use [suspend9+](#suspend9-1). Pauses this download task. This API uses an asynchronous callback to return the result. @@ -1781,14 +1739,13 @@ Pauses this download task. This API uses an asynchronous callback to return the **Parameters** | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<boolean> | Yes| Callback used to return the result.| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** ```js - let downloadTask; - downloadTask.suspend((err, result)=>{ + downloadTask.pause((err, result)=>{ if(err) { console.error('Failed to pause the download task. Cause:' + JSON.stringify(err)); return; @@ -1802,12 +1759,16 @@ Pauses this download task. This API uses an asynchronous callback to return the ``` -### restore9+ +### resume(deprecated) -restore(): Promise<boolean> +resume(): Promise<void> Resumes this download task. This API uses a promise to return the result. +> **NOTE** +> +> This API is supported since API version 7 and is deprecated since API version 9. You are advised to use [restore9+](#restore9). + **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -1815,14 +1776,13 @@ Resumes this download task. This API uses a promise to return the result. **Return value** | Type| Description| - | -------- | -------- | -| Promise<boolean> | Promise used to return the result.| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| **Example** ```js - let downloadTask; - downloadTask.restore().then((result) => { + downloadTask.resume().then((result) => { if (result) { console.info('Download task resumed.') } else { @@ -1835,9 +1795,13 @@ Resumes this download task. This API uses a promise to return the result. ``` -### restore9+ +### resume(deprecated) -restore(callback: AsyncCallback<boolean>): void +resume(callback: AsyncCallback<void>): void + +> **NOTE** +> +> This API is supported since API version 7 and is deprecated since API version 9. You are advised to use [restore9+](#restore9-1). Resumes this download task. This API uses an asynchronous callback to return the result. @@ -1848,14 +1812,13 @@ Resumes this download task. This API uses an asynchronous callback to return the **Parameters** | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<boolean> | Yes| Callback used to return the result.| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** ```js - let downloadTask; - downloadTask.restore((err, result)=>{ + downloadTask.resume((err, result)=>{ if (err) { console.error('Failed to resume the download task. Cause:' + err); return; diff --git a/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md b/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md index 8944052b4fed8899733d3cf924479ddc4359fc7e..03645ac62b8ec51c616fbfd6e923aef203a52ad6 100644 --- a/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md +++ b/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md @@ -1,4 +1,4 @@ -# Background Task Management +# @ohos.resourceschedule.backgroundTaskManager (Background Task Management) The **BackgroundTaskManager** module provides APIs to manage background tasks. @@ -234,7 +234,7 @@ Requests a continuous task from the system. This API uses an asynchronous callba | Name | Type | Mandatory | Description | | --------- | ---------------------------------- | ---- | ---------------------------------------- | -| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| | bgMode | [BackgroundMode](#backgroundmode) | Yes | Background mode requested. | | wantAgent | [WantAgent](js-apis-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. | | callback | AsyncCallback<void> | Yes | Callback used to return the result. | @@ -308,7 +308,7 @@ Requests a continuous task from the system. This API uses a promise to return th | Name | Type | Mandatory | Description | | --------- | ---------------------------------- | ---- | ---------------------------------------- | -| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| | bgMode | [BackgroundMode](#backgroundmode) | Yes | Background mode requested. | | wantAgent | [WantAgent](js-apis-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. | @@ -381,7 +381,7 @@ Requests to cancel a continuous task. This API uses an asynchronous callback to | Name | Type | Mandatory | Description | | -------- | ------------------------- | ---- | ---------------------------------------- | -| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Error codes** @@ -437,7 +437,7 @@ Requests to cancel a continuous task. This API uses a promise to return the resu | Name | Type | Mandatory | Description | | ------- | ------- | ---- | ---------------------------------------- | -| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| **Return value** @@ -618,12 +618,12 @@ Enumerates the efficiency resource types. **System API**: This is a system API. -| Name | Description | -| ----------------------- | --------------------- | -| CPU | CPU resources, which prevent the application from being suspended. | -| COMMON_EVENT | A type of software resources, which prevent common events from being proxied when the application is suspended. | -| TIMER | A type of software resources, which prevent timers from being proxied when the application is suspended. | -| WORK_SCHEDULER | WORK_SCHEDULER resources, which ensure that the application has more time to execute the task. | -| BLUETOOTH | A type of hardware resources, which prevent Bluetooth resources from being proxied when the application is suspended. | -| GPS | A type of hardware resources, which prevent GPS resources from being proxied when the application is suspended. | -| AUDIO | A type of hardware resources, which prevent audio resources from being proxied when the application is suspended.| +| Name | Value | Description | +| ----------------------- | ---- | --------------------- | +| CPU | 1 | CPU resources, which prevent the application from being suspended. | +| COMMON_EVENT | 2 | A type of software resources, which prevent common events from being proxied when the application is suspended. | +| TIMER | 4 | A type of software resources, which prevent timers from being proxied when the application is suspended. | +| WORK_SCHEDULER | 8 | WORK_SCHEDULER resources, which ensure that the application has more time to execute the task. | +| BLUETOOTH | 16 | A type of hardware resources, which prevent Bluetooth resources from being proxied when the application is suspended. | +| GPS | 32 | A type of hardware resources, which prevent GPS resources from being proxied when the application is suspended. | +| AUDIO | 64 | A type of hardware resources, which prevent audio resources from being proxied when the application is suspended.| diff --git a/en/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md b/en/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md index e62f6ca72f897772a8c98f21d14aaf18e398f575..77638dbfe38acf986f1b632349253c9ceb9496ed 100644 --- a/en/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md +++ b/en/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md @@ -1,4 +1,4 @@ -# Work Scheduler +# @ohos.resourceschedule.workScheduler The **workScheduler** module provides the APIs for registering, canceling, and querying Work Scheduler tasks, which do not have real-time constraints. @@ -437,45 +437,45 @@ Enumerates the network types that can trigger the task. **System capability**: SystemCapability.ResourceSchedule.WorkScheduler -| Name | Description | -| ---------------------- | ----------------------- | -| NETWORK_TYPE_ANY | Any network type. | -| NETWORK_TYPE_MOBILE | Mobile network. | -| NETWORK_TYPE_WIFI | Wi-Fi network. | -| NETWORK_TYPE_BLUETOOTH | Bluetooth network.| -| NETWORK_TYPE_WIFI_P2P | Wi-Fi P2P network. | -| NETWORK_TYPE_ETHERNET | Ethernet. | +| Name | Value | Description | +| ---------------------- | ---- | ----------------------- | +| NETWORK_TYPE_ANY | 0 | Any network type. | +| NETWORK_TYPE_MOBILE | 1 | Mobile network. | +| NETWORK_TYPE_WIFI | 2 | Wi-Fi network. | +| NETWORK_TYPE_BLUETOOTH | 3 | Bluetooth network.| +| NETWORK_TYPE_WIFI_P2P | 4 | Wi-Fi P2P network. | +| NETWORK_TYPE_ETHERNET | 5 | Ethernet. | ## ChargingType Enumerates the charging types that can trigger the task. **System capability**: SystemCapability.ResourceSchedule.WorkScheduler -| Name | Description | -| ------------------------- | -------------------- | -| CHARGING_PLUGGED_ANY | Any charging type.| -| CHARGING_PLUGGED_AC | DC charging. | -| CHARGING_PLUGGED_USB | USB charging. | -| CHARGING_PLUGGED_WIRELESS | Wireless charging. | +| Name | Value | Description | +| ------------------------- | ---- | -------------------- | +| CHARGING_PLUGGED_ANY | 0 | Any charging type.| +| CHARGING_PLUGGED_AC | 1 | DC charging. | +| CHARGING_PLUGGED_USB | 2 | USB charging. | +| CHARGING_PLUGGED_WIRELESS | 3 | Wireless charging. | ## BatteryStatus Enumerates the battery states that can trigger the task. **System capability**: SystemCapability.ResourceSchedule.WorkScheduler -| Name | Description | -| -------------------------- | -------------------------- | -| BATTERY_STATUS_LOW | A low battery alert is displayed. | -| BATTERY_STATUS_OKAY | The battery level is restored from low to normal. | -| BATTERY_STATUS_LOW_OR_OKAY | The battery level is restored from low to normal, or a low battery alert is displayed.| +| Name | Value | Description | +| -------------------------- | ---- | -------------------------- | +| BATTERY_STATUS_LOW | 0 | A low battery alert is displayed. | +| BATTERY_STATUS_OKAY | 1 | The battery level is restored from low to normal. | +| BATTERY_STATUS_LOW_OR_OKAY | 2 | The battery level is restored from low to normal, or a low battery alert is displayed.| ## StorageRequest Enumerates the storage states that can trigger the task. **System capability**: SystemCapability.ResourceSchedule.WorkScheduler -| Name | Description | -| ------------------------- | ------------------------------ | -| STORAGE_LEVEL_LOW | The storage space is insufficient. | -| STORAGE_LEVEL_OKAY | The storage space is restored from insufficient to normal. | -| STORAGE_LEVEL_LOW_OR_OKAY | The storage space is restored from insufficient to normal, or the storage space is insufficient.| +| Name | Value | Description | +| ------------------------- | ---- | ------------------------------ | +| STORAGE_LEVEL_LOW | 0 | The storage space is insufficient. | +| STORAGE_LEVEL_OKAY | 1 | The storage space is restored from insufficient to normal. | +| STORAGE_LEVEL_LOW_OR_OKAY | 2 | The storage space is restored from insufficient to normal, or the storage space is insufficient.| diff --git a/en/application-dev/reference/apis/js-apis-settings.md b/en/application-dev/reference/apis/js-apis-settings.md index 9474b7a298b40546ae1b5fe1a7c639efb1195de3..5972e0cd9a278dcc49b634b6d05e8d76f3fa0a1d 100644 --- a/en/application-dev/reference/apis/js-apis-settings.md +++ b/en/application-dev/reference/apis/js-apis-settings.md @@ -1,4 +1,4 @@ -# Settings +# @ohos.settings The **settings** module provides APIs for setting data items. @@ -24,8 +24,8 @@ Provides data items for setting the time and date formats. | ------------------- | ------ | ---- | ---- | ------------------------------------------------------------ | | 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.
**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; and **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; and **false** means the opposite.| +| 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; and **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; and **false** means the opposite. | ## display @@ -39,7 +39,7 @@ Provides data items for setting the display effects. | ----------------------------- | ------ | ---- | ---- | ------------------------------------------------------------ | | FONT_SCALE | string | Yes | Yes | Scale factor of the font. The value is a floating point number. | | SCREEN_BRIGHTNESS_STATUS | string | Yes | Yes | Screen brightness. The value ranges 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 | 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). | @@ -47,7 +47,7 @@ Provides data items for setting the display effects. | ANIMATOR_DURATION_SCALE | string | Yes | Yes | Scale factor for the animation duration. This 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.| +| 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 @@ -248,7 +248,7 @@ Obtains the value of a data item in the database. This API uses an asynchronous | Name | Type | Mandatory| Description | | ----------------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ | -| dataAbilityHelper | [DataAbilityHelper](js-apis-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. | +| dataAbilityHelper | [DataAbilityHelper](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. | @@ -280,7 +280,7 @@ Obtains the value of a data item in the database. This API uses a promise to ret | Name | Type | Mandatory| Description | | ----------------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ | -| dataAbilityHelper | [DataAbilityHelper](js-apis-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. | +| dataAbilityHelper | [DataAbilityHelper](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** @@ -315,7 +315,7 @@ Sets the value for a data item. This API uses an asynchronous callback to return | Name | Type | Mandatory| Description | | ----------------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ | -| dataAbilityHelper | [DataAbilityHelper](js-apis-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. | +| dataAbilityHelper | [DataAbilityHelper](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 | object | 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. | @@ -347,7 +347,7 @@ Sets the value for a data item. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ----------------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ | -| dataAbilityHelper | [DataAbilityHelper](js-apis-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. | +| dataAbilityHelper | [DataAbilityHelper](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 | object | Yes | Value of the data item. The value range varies by service. | @@ -512,9 +512,9 @@ Obtains the value of a data item. Unlike **getValue**, this API returns the resu | Name | Type | Mandatory| Description | | ----------------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ | -| dataAbilityHelper | [DataAbilityHelper](js-apis-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. | +| dataAbilityHelper | [DataAbilityHelper](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 attribute 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** @@ -541,7 +541,7 @@ Sets the value for a data item. Unlike **setValue**, this API returns the result If the specified data item exists in the database, the **setValueSync** method updates the value of the data item. If the data item does not exist in the database, the **setValueSync** method inserts the data item into the database. -**Required permissions**: ohos.permission.MANAGE_SECUER_SETTINGS (available only to system applications) +**Required permissions**: ohos.permission.MANAGE_SECURE_SETTINGS (available only to system applications) **System capability**: SystemCapability.Applications.settings.Core @@ -549,7 +549,7 @@ If the specified data item exists in the database, the **setValueSync** method u | Name | Type | Mandatory| Description | | ----------------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ | -| dataAbilityHelper | [DataAbilityHelper](js-apis-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. | +| dataAbilityHelper | [DataAbilityHelper](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. | diff --git a/en/application-dev/reference/apis/js-apis-stack.md b/en/application-dev/reference/apis/js-apis-stack.md index 479550783c54d87accf6436cf6556e1b33a12ccc..d7c5dcb66c511aa8ade7ad6e4fa94041162f2380 100644 --- a/en/application-dev/reference/apis/js-apis-stack.md +++ b/en/application-dev/reference/apis/js-apis-stack.md @@ -1,4 +1,4 @@ -# Linear Container Stack +# @ohos.util.Stack (Linear Container Stack) > **NOTE** > @@ -19,9 +19,6 @@ This topic uses the following to identify the use of generics: import Stack from '@ohos.util.Stack'; ``` - - - ## Stack ### Attributes @@ -53,11 +50,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let stack = new Stack(); -try { - let stack2 = Stack(); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -99,11 +91,6 @@ let b = [1, 2, 3]; let result2 = stack.push(b); let c = {name : "Dylon", age : "13"}; let result3 = stack.push(c); -try { - stack.push.bind({}, "b")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### pop @@ -138,11 +125,6 @@ stack.push(5); stack.push(2); stack.push(4); let result = stack.pop(); -try { - stack.pop.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### peek @@ -176,11 +158,6 @@ stack.push(4); stack.push(5); stack.push(2); let result = stack.peek(); -try { - stack.peek.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### locate @@ -220,16 +197,11 @@ stack.push(4); stack.push(5); stack.push(2); let result = stack.locate(2); -try { - stack.locate.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### forEach -forEach(callbackfn: (value: T, index?: number, stack?: Stack<T>) => void, +forEach(callbackFn: (value: T, index?: number, stack?: Stack<T>) => void, thisArg?: Object): void Uses a callback to traverse the elements in this container and obtain their position indexes. @@ -240,7 +212,7 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| +| callbackFn | function | Yes| Callback invoked to traverse the elements in the container.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -270,13 +242,6 @@ stack.push(4); stack.forEach((value, index) => { console.log("value:" + value, index); }); -try { - stack.forEach.bind({}, (value, index) => { - console.log("value:" + value, index); - })(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### isEmpty @@ -310,11 +275,6 @@ stack.push(4); stack.push(5); stack.push(4); let result = stack.isEmpty(); -try { - stack.isEmpty.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### [Symbol.iterator] @@ -359,9 +319,4 @@ while(temp != undefined) { console.log("value:" + temp); temp = iter.next().value; } -try { - stack[Symbol.iterator].bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` diff --git a/en/application-dev/reference/apis/js-apis-stationary.md b/en/application-dev/reference/apis/js-apis-stationary.md new file mode 100644 index 0000000000000000000000000000000000000000..ceae25ac4c711e8dd3664520290fda7b897c9ae9 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-stationary.md @@ -0,0 +1,130 @@ +# @ohos.stationary (Device Status Awareness Framework) + +The **stationary** module provides APIs to report the device status, including absolute still and relative still. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```js +import stationary from '@ohos.stationary' +``` + +## ActivityResponse + +Defines the response interface to receive the device status. + +**System capability**: SystemCapability.Msdp.DeviceStatus.Stationary + +### Attributes + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| state | [ActivityState](#activitystate) | Yes| No| New device status.| + +## ActivityType + +Enumerates the device status types. + +**System capability**: SystemCapability.Msdp.DeviceStatus.Stationary + +| Name| Description| +| -------- | -------- | +| still | Absolutely still.| +| relativeStill | Relatively still.| + +## ActivityEvent + +Enumerates the device status events. + +**System capability**: SystemCapability.Msdp.DeviceStatus.Stationary + +| Name | Value | Description | +| ------------------------------ | ---- | ---------------------------------------- | +| ENTER | 1 | Event indicating entering device status. | +| EXIT | 2 | Event indicating exiting device status.| +| ENTER_EXIT | 3 | Event indicating entering and exiting device status.| + +## ActivityState + +Enumerates the device statuses. + +**System capability**: SystemCapability.Msdp.DeviceStatus.Stationary + +| Name | Value | Description | +| ------------------------------ | ---- | ---------------------------------------- | +| ENTER | 1 | Entering device status. | +| EXIT | 2 | Exiting device status.| + +## stationary.on('still' | 'relativeStill') + +on(activity: ActivityType, event: ActivityEvent, reportLatencyNs: number, callback: Callback<ActivityResponse>): void + +Subscribes to the device status. + +**System capability**: SystemCapability.Msdp.DeviceStatus.Stationary + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------------- | -------------------------------------------------- | ---- | ---------------------------- | +| activity | [ActivityType](#activitytype) | Yes | Device status type. | +| event | [ActivityEvent](#activityevent) | Yes | Event type. | +| reportLatencyNs | number | Yes | Event reporting period. | +| callback | Callback<[ActivityResponse](#activityresponse)\> | Yes | Callback used to receive reported data. | + +**Example** + +```js +var reportLatencyNs = 100; +stationary.on('still', stationary.ActivityEvent.ENTER, reportLatencyNs, (data) => { + console.log('data='+ JSON.stringify(data)); +}) +``` + +## stationary.once('still' | 'relativeStill') + +once(activity: ActivityType, callback: Callback<ActivityResponse>): void + +Obtains the device status. + +**System capability**: SystemCapability.Msdp.DeviceStatus.Stationary + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------------- | -------------------------------------------------- | ---- | ---------------------------- | +| activity | [ActivityType](#activitytype) | Yes | Device status type. | +| callback | Callback<[ActivityResponse](#activityresponse)\> | Yes | Callback used to receive reported data. | + +**Example** + +```js +stationary.once('still', (data) => { + console.log("data="+ JSON.stringify(data)); +}) +``` + +## stationary.off('still' | 'relativeStill') + +off(activity: ActivityType, event: ActivityEvent, callback?: Callback<ActivityResponse>): void + +Unsubscribes from the device status. + +**System capability**: SystemCapability.Msdp.DeviceStatus.Stationary + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------------- | -------------------------------------------------- | ---- | ---------------------------- | +| activity | [ActivityType](#activitytype) | Yes | Device status type. | +| event | [ActivityEvent](#activityevent) | Yes | Event type. | +| callback | Callback<[ActivityResponse](#activityresponse)\> | No | Callback used to receive reported data. | + +**Example** + +```js +stationary.off('still', stationary.ActivityEvent.ENTER); +``` diff --git a/en/application-dev/reference/apis/js-apis-system-device.md b/en/application-dev/reference/apis/js-apis-system-device.md index c5b92831958ea79cb7b868fbf549974cdf39a669..6da9ae481fe8ef4aeb440090f478fb1069596882 100644 --- a/en/application-dev/reference/apis/js-apis-system-device.md +++ b/en/application-dev/reference/apis/js-apis-system-device.md @@ -1,61 +1,61 @@ -# Device Information +# @system.device -> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** -> - The APIs of this module are no longer maintained since API version 6. It is recommended that you use [`@ohos.deviceInfo`](js-apis-device-info.md) instead. +The **device** module provides APIs for checking information about the current device. + +> **NOTE** +> - The APIs of this module are no longer maintained since API version 6. It is recommended that you use [@ohos.deviceInfo](js-apis-device-info.md) instead. > > - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. - ## Modules to Import - ``` import device from '@system.device'; ``` - ## device.getInfo getInfo(Object): void Obtains the device information. -> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> **NOTE** +> > Do not call **device.getInfo** before the **onShow** event of the home page. -**System capability**: SystemCapability.Startup.SysInfo +**System capability**: SystemCapability.Startup.SystemInfo **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| success | Function | No | Called when the device information is obtained | -| fail | Function | No | Called when the device information fails to be obtained | -| complete | Function | No | Called when the execution is complete | +| success | Function | No| Called when API call is successful.| +| fail | Function | No| Called when API call has failed.| +| complete | Function | No| Called when API call is complete.| -The following values will be returned when the device information is obtained. +**Return value of success()** -| Name | Type | Description | +| Name| Type| Description| | -------- | -------- | -------- | -| brand | string | Brand | -| manufacturer | string | Manufacturer | -| model | string | Model | -| product | string | Product number | -| language4+ | string | System language | -| region4+ | string | System region | -| windowWidth | number | Window width | -| windowHeight | number | Window height | -| screenDensity4+ | number | Screen density | -| screenShape4+ | string | Screen shape. The options are as follows:
- rect: rectangle screen
- circle: circle screen | -| apiVersion4+ | number | API version | -| releaseType4+ | string | Release type. The value includes both the release type and the API version, for example, Beta1.
Available release types are as follows:
- **Canary**: For the same API version, different canary releases are compatible with each other, but not compatible with those of the **beta** and **release** type.
- **Beta**: For the same API version, different beta releases are compatible with each other, but not compatible with those of the **release** type.
- **Release**: Releases of this type are compatible with the latest five API versions. | -| deviceType4+ | string | Device type | - -The following error code will be returned if the device information fails to be obtained. - -| Error Code | Description | +| brand | string | Brand.| +| manufacturer | string | Manufacturer.| +| model | string | Model. | +| product | string | Product number.| +| language4+ | string | System language.| +| region4+ | string | System region.| +| windowWidth | number | Window width.| +| windowHeight | number | Window height.| +| screenDensity4+ | number | Screen density.| +| screenShape4+ | string | Screen shape. The options are as follows:
- **rect**: rectangle screen
- **circle**: circle screen| +| apiVersion4+ | number | API version.| +| releaseType4+ | string | Release type. The value includes both the release type and the API version, for example, Beta1.
Available release types are as follows:
- **Canary**: For the same API version, different canary releases are compatible with each other, but not compatible with those of the **beta** and **release** type.
- **Beta**: For the same API version, different beta releases are compatible with each other, but not compatible with those of the **release** type.
- **Release**: Releases of this type are compatible with the latest five API versions.| +| deviceType4+ | string | Device type.| + +**Return value of fail()** + +| Error Code| Description| | -------- | -------- | -| 200 | The returned result contains information that cannot be obtained. | +| 200 | The returned result contains information that cannot be obtained.| **Example** @@ -72,4 +72,4 @@ export default { }); }, } -``` \ No newline at end of file +``` diff --git a/en/application-dev/reference/apis/js-apis-system-location.md b/en/application-dev/reference/apis/js-apis-system-location.md index ab53fb2d188b7b929c591a67c33cec12984e063c..b0648efc475396e317d6f8da4891ecb66e6164df 100644 --- a/en/application-dev/reference/apis/js-apis-system-location.md +++ b/en/application-dev/reference/apis/js-apis-system-location.md @@ -1,6 +1,6 @@ # Geographic Location -> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> **Note:** > - The APIs of this module are no longer maintained since API version 7. It is recommended that you use [`@ohos.geolocation`](js-apis-geolocation.md) instead. > > - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. diff --git a/en/application-dev/reference/apis/js-apis-system-package.md b/en/application-dev/reference/apis/js-apis-system-package.md index c6453ec28f1dca4749d8f8c91414a609af161466..3dec0fa1e2fd325479ac688443e67500d60f570b 100644 --- a/en/application-dev/reference/apis/js-apis-system-package.md +++ b/en/application-dev/reference/apis/js-apis-system-package.md @@ -1,9 +1,9 @@ -# Application Management +# @system.package (Bundle Management) -> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> **NOTE** > -> - The APIs of this module are no longer maintained since API version 7. It is recommended that you use [`@ohos.bundle`](js-apis-Bundle.md) instead. +> - This module is deprecated since API version 9. You are advised to use [@ohos.bundle.bundleManager](js-apis-bundleManager.md) instead. > > - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -12,11 +12,12 @@ ``` -import pkg from '@system.package'; +import package from '@system.package'; ``` -## package.hasInstalled +## package.hasInstalled(deprecated) +> This API is deprecated since API version 9. You are advised to use [@ohos.bundle.bundleManager](js-apis-bundleManager.md) instead. hasInstalled(Object): void @@ -26,35 +27,57 @@ Checks whether an application exists, or whether a native application has been i **System capability**: SystemCapability.BundleManager.BundleFramework -**Parameter** +**Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| bundleName | string | Yes | Application bundle name | -| success | Function | No | Called when the check result is obtained | -| fail | Function | No | Called when the check result fails to be obtained | -| complete | Function | No | Called when the execution is complete | +|options | [CheckPackageHasInstalledOptions](#checkpackagehasinstalledoptions) | Yes| Options.| -The following value will be returned when the check result is obtained. +**Return value** -| Name | Type | Description | +| Name| Type| Description| | -------- | -------- | -------- | -| result | boolean | Whether the application exists, or whether the native application has been installed | +| result | boolean | The value **true** means that the application exists or the native application has been installed, and **false** means the opposite.| **Example** -``` -export default { - hasInstalled() { - pkg.hasInstalled({ - bundleName: 'com.example.bundlename', - success: function(data) { - console.log('package has installed: ' + data); - }, - fail: function(data, code) { - console.log('query package fail, code: ' + code + ', data: ' + data); - }, - }); +``` ts +export default { + hasInstalled() { + package.hasInstalled({ + bundleName: 'com.example.bundlename', + success: function(data) { + console.log('package has installed: ' + data); + }, + fail: function(data, code) { + console.log('query package fail, code: ' + code + ', data: ' + data); + }, + }); }, } -``` \ No newline at end of file +``` + +## CheckPackageHasInstalledResponse + +> This API is deprecated since API version 9. + +Checks whether a bundle has been installed. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name| Type| Description| +| --- | --- | ---- | +| result | boolean | The value **true** means that the bundle has been installed, and **false** means the opposite.| + +## CheckPackageHasInstalledOptions + +> This API is deprecated since API version 9. + +Defines the options used for checking whether a bundle has been installed. + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| bundleName | string | Yes| Bundle name.| +| success | Function | No| Called when API call is successful.| +| fail | Function | No| Called when API call has failed.| +| complete | Function | No| Called when API call is complete.| diff --git a/en/application-dev/reference/apis/js-apis-system-parameter.md b/en/application-dev/reference/apis/js-apis-system-parameter.md index 6ccbc31664329e94861a503f1995682f104c6d79..ab3ae31887d1a2c55eb94c0164573834321e96c0 100644 --- a/en/application-dev/reference/apis/js-apis-system-parameter.md +++ b/en/application-dev/reference/apis/js-apis-system-parameter.md @@ -1,11 +1,10 @@ -# SystemParameter +# @ohos.systemParameter -The **SystemParameter** module provides system services with easy access to key-value pairs. You can use the APIs of 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 getters and modify the values through setters. +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 getters and modify the values through setters. For details about the system parameter design principles and definitions, see [Service Management](../../../device-dev/subsystems/subsys-boot-init-sysparam.md). > **NOTE** -> > - The APIs of this module are no longer maintained since API version 9. It is recommended that you use [@ohos.systemParameterV9](js-apis-system-parameterV9.md) instead. > - The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. > - The APIs provided by this module are system APIs. @@ -54,7 +53,7 @@ try { get(key: string, callback: AsyncCallback<string>): void -Obtains the value of the system parameter with the specified key. This API uses an asynchronous callback to return the result. +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 @@ -164,9 +163,9 @@ Sets a value for the system parameter with the specified key. | value | string | Yes| Value of the system parameter to set.| > **NOTE** -> > - This API can be used only for setting parameters of system applications. -> - SELinux and DAC rules must be configured for authorized system applications. For details, see [Service Management](../../../device-dev/subsystems/subsys-boot-init-sysparam.md). +> - SELinux and Discretionary Access Control (DAC) rules must be configured for authorized system applications. For details about how to configure SELinux and DAC rules, see [Parameter Management](../../../device-dev/subsystems/subsys-boot-init-sysparam.md). + **Example** @@ -195,9 +194,8 @@ Sets a value for the system parameter with the specified key. This API uses an a | callback | AsyncCallback<void> | Yes| Callback used to return the result.| > **NOTE** -> > - This API can be used only for setting parameters of system applications. -> - SELinux and discretionary access control (DAC) rules must be configured for authorized system applications. For details, see [Service Management](../../../device-dev/subsystems/subsys-boot-init-sysparam.md). +> - SELinux and Discretionary Access Control (DAC) rules must be configured for authorized system applications. For details about how to configure SELinux and DAC rules, see [Parameter Management](../../../device-dev/subsystems/subsys-boot-init-sysparam.md). **Example** @@ -236,9 +234,8 @@ Sets a value for the system parameter with the specified key. This API uses a pr | Promise<void> | Promise used to return the execution result.| > **NOTE** -> > - This API can be used only for setting parameters of system applications. -> - SELinux and discretionary access control (DAC) rules must be configured for authorized system applications. For details, see [Service Management](../../../device-dev/subsystems/subsys-boot-init-sysparam.md). +> - SELinux and Discretionary Access Control (DAC) rules must be configured for authorized system applications. For details about how to configure SELinux and DAC rules, see [Parameter Management](../../../device-dev/subsystems/subsys-boot-init-sysparam.md). **Example** diff --git a/en/application-dev/reference/apis/js-apis-treemap.md b/en/application-dev/reference/apis/js-apis-treemap.md index e2a41d26819c96d3ef4321bfaf9a0e9f058300c9..573732b5474552added2d9918986e2add3982b01 100644 --- a/en/application-dev/reference/apis/js-apis-treemap.md +++ b/en/application-dev/reference/apis/js-apis-treemap.md @@ -1,4 +1,4 @@ -# Nonlinear Container TreeMap +# @ohos.util.TreeMap (Nonlinear Container TreeMap) > **NOTE** > @@ -59,11 +59,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let treeMap = new TreeMap(); -try { - let treeMap2 = TreeMap(); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -94,11 +89,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts const treeMap = new TreeMap(); let result = treeMap.isEmpty(); -try { - treeMap.isEmpty.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -137,11 +127,6 @@ let treeMap = new TreeMap(); let result = treeMap.hasKey("squirrel"); treeMap.set("squirrel", 123); let result1 = treeMap.hasKey("squirrel"); -try { - treeMap.hasKey.bind({}, "squirrel")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -180,11 +165,6 @@ let treeMap = new TreeMap(); let result = treeMap.hasValue(123); treeMap.set("squirrel", 123); let result1 = treeMap.hasValue(123); -try { - treeMap.hasValue.bind({}, 123)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -223,11 +203,6 @@ let treeMap = new TreeMap(); treeMap.set("squirrel", 123); treeMap.set("sparrow", 356); let result = treeMap.get("sparrow"); -try { - treeMap.get.bind({}, "sparrow")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -260,11 +235,6 @@ let treeMap = new TreeMap(); treeMap.set("squirrel", 123); treeMap.set("sparrow", 356); let result = treeMap.getFirstKey(); -try { - treeMap.getFirstKey.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -297,11 +267,6 @@ let treeMap = new TreeMap(); treeMap.set("squirrel", 123); treeMap.set("sparrow", 356); let result = treeMap.getLastKey(); -try { - treeMap.getLastKey.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -335,11 +300,6 @@ treeMap.set("squirrel", 123); treeMap.set("sparrow", 356); let map = new TreeMap(); treeMap.setAll(map); -try { - treeMap.setAll.bind({}, map)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -377,11 +337,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let treeMap = new TreeMap(); treeMap.set("squirrel", 123); -try { - treeMap.set.bind({}, "squirrel", 123)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -420,11 +375,6 @@ let treeMap = new TreeMap(); treeMap.set("squirrel", 123); treeMap.set("sparrow", 356); treeMap.remove("sparrow"); -try { - treeMap.remove.bind({}, "sparrow")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -464,11 +414,6 @@ treeMap.set("squirrel", 123); treeMap.set("sparrow", 356); treeMap.set("gander", 356); let result = treeMap.getLowerKey("sparrow"); -try { - treeMap.getLowerKey.bind({}, "sparrow")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -508,11 +453,6 @@ treeMap.set("squirrel", 123); treeMap.set("sparrow", 356); treeMap.set("gander", 356); let result = treeMap.getHigherKey("sparrow"); -try { - treeMap.getHigherKey.bind({}, "sparrow")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### replace @@ -550,11 +490,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er let treeMap = new TreeMap(); treeMap.set("sparrow", 123); let result = treeMap.replace("sparrow", 357); -try { - treeMap.replace.bind({}, "sparrow", 357)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -581,11 +516,6 @@ let treeMap = new TreeMap(); treeMap.set("squirrel", 123); treeMap.set("sparrow", 356); treeMap.clear(); -try { - treeMap.clear.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -623,11 +553,6 @@ while(temp != undefined) { console.log("value:" + temp); temp = iter.next().value; } -try { - treeMap.keys.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -665,17 +590,12 @@ while(temp != undefined) { console.log("value:" + temp); temp = iter.next().value; } -try { - treeMap.values.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### forEach -forEach(callbackfn: (value?: V, key?: K, map?: TreeMap) => void, thisArg?: Object): void +forEach(callbackFn: (value?: V, key?: K, map?: TreeMap) => void, thisArg?: Object): void Uses a callback to traverse the elements in this container and obtain their position indexes. @@ -685,7 +605,7 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| +| callbackFn | function | Yes| Callback invoked to traverse the elements in the container.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -712,13 +632,6 @@ treeMap.set("gull", 357); treeMap.forEach((value, key) => { console.log("value:" + value, key); }); -try { - treeMap.forEach.bind({}, (value, key) => { - console.log("value:" + value, key); - })(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -757,11 +670,6 @@ while(temp != undefined) { console.log("value:" + temp[1]); temp = iter.next().value; } -try { - treeMap.entries.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -807,9 +715,4 @@ while(temp != undefined) { console.log("value:" + temp[1]); temp = iter.next().value; } -try { - treeMap[Symbol.iterator].bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` diff --git a/en/application-dev/reference/apis/js-apis-treeset.md b/en/application-dev/reference/apis/js-apis-treeset.md index ef10035349bf185462f803ad967270e79b8cc93d..bc6f1272452fd35d0458b6232f7c03a1bd19ce9b 100644 --- a/en/application-dev/reference/apis/js-apis-treeset.md +++ b/en/application-dev/reference/apis/js-apis-treeset.md @@ -1,4 +1,4 @@ -# Nonlinear Container TreeSet +# @ohos.util.TreeSet (Nonlinear Container TreeSet) > **NOTE** > @@ -56,11 +56,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let treeSet = new TreeSet(); -try { - let treeSet2 = TreeSet(); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -91,11 +86,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts const treeSet = new TreeSet(); let result = treeSet.isEmpty(); -try { - treeSet.isEmpty.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -134,11 +124,6 @@ let treeSet = new TreeSet(); treeSet.has(123); treeSet.add(123); let result1 = treeSet.has(123); -try { - treeSet.has.bind({}, 123)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -171,11 +156,6 @@ let treeSet = new TreeSet(); treeSet.add("squirrel"); treeSet.add("sparrow"); let result = treeSet.getFirstValue(); -try { - treeSet.getFirstValue.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -208,11 +188,6 @@ let treeSet = new TreeSet(); treeSet.add("squirrel"); treeSet.add("sparrow"); let result = treeSet.getLastValue(); -try { - treeSet.getLastValue.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -249,11 +224,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let treeSet = new TreeSet(); let result = treeSet.add("squirrel"); -try { - treeSet.add.bind({}, "squirrel")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -292,11 +262,6 @@ let treeSet = new TreeSet(); treeSet.add("squirrel"); treeSet.add("sparrow"); let result = treeSet.remove("sparrow"); -try { - treeSet.remove.bind({}, "sparrow")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -336,11 +301,6 @@ treeSet.add("squirrel"); treeSet.add("sparrow"); treeSet.add("gander"); let result = treeSet.getLowerValue("sparrow"); -try { - treeSet.getLowerValue.bind({}, "sparrow")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -380,11 +340,6 @@ treeSet.add("squirrel"); treeSet.add("sparrow"); treeSet.add("gander"); let result = treeSet.getHigherValue("sparrow"); -try { - treeSet.getHigherValue.bind({}, "sparrow")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -417,11 +372,6 @@ let treeSet = new TreeSet(); treeSet.add("squirrel"); treeSet.add("sparrow"); let result = treeSet.popFirst(); -try { - treeSet.popFirst.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -454,11 +404,6 @@ let treeSet = new TreeSet(); treeSet.add("squirrel"); treeSet.add("sparrow"); let result = treeSet.popLast(); -try { - treeSet.popLast.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -485,11 +430,6 @@ let treeSet = new TreeSet(); treeSet.add("squirrel"); treeSet.add("sparrow"); treeSet.clear(); -try { - treeSet.clear.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -527,17 +467,12 @@ while(temp != undefined) { console.log("value:" + temp); temp = iter.next().value; } -try { - treeSet.values.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### forEach -forEach(callbackfn: (value?: T, key?: T, set?: TreeSet<T>) => void, thisArg?: Object): void +forEach(callbackFn: (value?: T, key?: T, set?: TreeSet<T>) => void, thisArg?: Object): void Uses a callback to traverse the elements in this container and obtain their position indexes. @@ -547,7 +482,7 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| +| callbackFn | function | Yes| Callback invoked to traverse the elements in the container.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -574,13 +509,6 @@ treeSet.add("gull"); treeSet.forEach((value, key) => { console.log("value:" + value, key) }); -try { - treeSet.forEach.bind({}, (value, key) => { - console.log("value:" + value, key) - })(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -619,11 +547,6 @@ while(temp != undefined) { console.log("value:" + temp[1]); temp = iter.next().value; } -try { - treeSet.entries.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -668,9 +591,4 @@ while(temp != undefined) { console.log("value:" + temp); temp = iter.next().value; } -try { - treeSet[Symbol.iterator].bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` diff --git a/en/application-dev/reference/apis/js-apis-uri.md b/en/application-dev/reference/apis/js-apis-uri.md index d058b555c87be4fe5f9601ef4b9f9c7198964463..6bad7dde783939b10243f10824e98ef991235499 100644 --- a/en/application-dev/reference/apis/js-apis-uri.md +++ b/en/application-dev/reference/apis/js-apis-uri.md @@ -1,4 +1,4 @@ -# URI String Parsing +# @ohos.uri (URI String Parsing) > **NOTE** > @@ -40,18 +40,18 @@ A constructor used to create a URI instance. **Parameters** -| Name| Type.| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| uri | string | Yes| Yes| Input object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| uri | string | Yes| Input object.| **Example** ```js -let mm = 'http://username:password@host:8080/directory/file?foo=1&bar=2#fragment'; -new uri.URI(mm); // Output 'http://username:password@host:8080/directory/file?foo=1&bar=2#fragment'; +let mm = 'https://username:password@host:8080/directory/file?foo=1&bar=2#fragment'; +new uri.URI(mm); // Output 'https://username:password@host:8080/directory/file?foo=1&bar=2#fragment'; ``` ```js -new uri.URI('http://username:password@host:8080'); // Output 'http://username:password@host:8080'; +new uri.URI('https://username:password@host:8080'); // Output 'https://username:password@host:8080'; ``` @@ -65,22 +65,23 @@ Obtains the query string applicable to this URI. **Return value** -| Type.| Description| +| Type| Description| | -------- | -------- | | string | Website address in a serialized string.| **Example** ```js -const result = new uri.URI('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); +const result = new uri.URI('https://username:password@host:8080/directory/file?query=pppppp#qwer=da'); result.toString() ``` ### equals(deprecated) + > **NOTE** > -> This API is deprecated since API version 9. You are advised to use [equalsTo9+](#equalsto9) instead. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [equalsTo9+](#equalsto9) instead. equals(other: URI): boolean @@ -90,21 +91,21 @@ Checks whether this URI is the same as another URI object. **Parameters** -| Name| Type.| Mandatory| Description| +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | other | [URI](#uri) | Yes| URI object to compare.| **Return value** -| Type.| Description| +| Type| Description| | -------- | -------- | | boolean | Returns **true** if the two URIs are the same; returns **false** otherwise.| **Example** ```js -const uriInstance = new uri.URI('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); -const uriInstance1 = new uri.URI('http://username:password@host:8080/directory/file?query=pppppp#qwer=da#fragment'); +const uriInstance = new uri.URI('https://username:password@host:8080/directory/file?query=pppppp#qwer=da'); +const uriInstance1 = new uri.URI('https://username:password@host:8080/directory/file?query=pppppp#qwer=da#fragment'); uriInstance.equals(uriInstance1); ``` ### equalsTo9+ @@ -117,21 +118,21 @@ Checks whether this URI is the same as another URI object. **Parameters** -| Name| Type.| Mandatory| Description| +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | other | [URI](#uri) | Yes| URI object to compare.| **Return value** -| Type.| Description| +| Type| Description| | -------- | -------- | | boolean | Returns **true** if the two URIs are the same; returns **false** otherwise.| **Example** ```js -const uriInstance = new uri.URI('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); -const uriInstance1 = new uri.URI('http://username:password@host:8080/directory/file?query=pppppp#qwer=da#fragment'); +const uriInstance = new uri.URI('https://username:password@host:8080/directory/file?query=pppppp#qwer=da'); +const uriInstance1 = new uri.URI('https://username:password@host:8080/directory/file?query=pppppp#qwer=da#fragment'); uriInstance.equalsTo(uriInstance1); ``` @@ -145,14 +146,14 @@ Checks whether this URI is an absolute URI (whether the scheme component is defi **Return value** -| Type.| Description| +| Type| Description| | -------- | -------- | | boolean | Returns **true** if the URI is an absolute URI; returns **false** otherwise.| **Example** ```js -const uriInstance = new uri.URI('http://username:password@www.qwer.com:8080?query=pppppp'); +const uriInstance = new uri.URI('https://username:password@www.qwer.com:8080?query=pppppp'); uriInstance.checkIsAbsolute(); ``` @@ -167,13 +168,14 @@ Normalizes the path of this URI. **Return value** -| Type.| Description| +| Type| Description| | -------- | -------- | | URI | URI with the normalized path.| **Example** + ```js -const uriInstance = new uri.URI('http://username:password@www.qwer.com:8080/path/path1/../path2/./path3?query=pppppp'); +const uriInstance = new uri.URI('https://username:password@www.qwer.com:8080/path/path1/../path2/./path3?query=pppppp'); let uriInstance1 = uriInstance.normalize(); uriInstance1.path; ``` diff --git a/en/application-dev/reference/apis/js-apis-util.md b/en/application-dev/reference/apis/js-apis-util.md index 226f7686f490b2d3fd28e8263d7226eb02091c09..8897b51f07b4e00feae752e792820e6b9b32370f 100755 --- a/en/application-dev/reference/apis/js-apis-util.md +++ b/en/application-dev/reference/apis/js-apis-util.md @@ -1,17 +1,15 @@ -# util +# @ohos.util +This module provides common utility functions, such as **TextEncoder** and **TextDecoder** for string encoding and decoding, **RationalNumber** for rational number operations, **LruBuffer** for buffer management, **Scope** for range determination, **Base64** for Base64 encoding and decoding, and **Types** for checks of built-in object types. > **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. -This module provides common utility functions, such as **TextEncoder** and **TextDecoder** for string encoding and decoding, **RationalNumber** for rational number operations, **LruBuffer** for buffer management, **Scope** for range determination, **Base64** for Base64 encoding and decoding, and **Types** for checks of built-in object types. - - ## Modules to Import -``` +```js import util from '@ohos.util'; ``` @@ -45,14 +43,14 @@ console.log(res); ## util.printf(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [util.format9+](#utilformat9) instead. - printf(format: string, ...args: Object[]): string Formats the specified values and inserts them into the string by replacing the wildcard in the string. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [util.format9+](#utilformat9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -60,7 +58,7 @@ Formats the specified values and inserts them into the string by replacing the w | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | format | string | Yes| String.| -| ...args | Object[] | No| Values to format. The formatted values will be replaced the wildcard in the string. | +| ...args | Object[] | No| Values to format. The formatted values will be replaced the wildcard in the string.| **Return value** @@ -69,6 +67,7 @@ Formats the specified values and inserts them into the string by replacing the w | string | String containing the formatted values.| **Example** + ```js let res = util.printf("%s", "hello world!"); console.log(res); @@ -96,22 +95,22 @@ Obtains detailed information about a system error code. **Example** - ```js +```js let errnum = 10; // 10 is a system error code. let result = util.errnoToString(errnum); console.log("result = " + result); - ``` +``` ## util.getErrorString(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [util.errnoToString9+](#utilerrnotostring9) instead. - getErrorString(errno: number): string Obtains detailed information about a system error code. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [util.errnoToString9+](#utilerrnotostring9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -127,6 +126,7 @@ Obtains detailed information about a system error code. | string | Detailed information about the error code.| **Example** + ```js let errnum = 10; // 10 is a system error code. let result = util.getErrorString(errnum); @@ -154,6 +154,7 @@ Calls back an asynchronous function. In the callback, the first parameter indica | Function | Callback, in which the first parameter indicates the cause of the rejection (the value is **null** if the promise has been resolved) and the second parameter indicates the resolved value.| **Example** + ```js async function promiseFn() { return Promise.reject('value'); @@ -187,6 +188,7 @@ Processes an asynchronous function and returns a promise. | Function | Function in the error-first style (that is, **(err, value) =>...** is called as the last parameter) and the promise.| **Example** + ```js function aysnFun(str1, str2) { if (typeof str1 === 'object' && typeof str2 === 'object') { @@ -205,11 +207,11 @@ Processes an asynchronous function and returns a promise. promiseWrapper(original: (err: Object, value: Object) => void): Object +Processes an asynchronous function and returns a promise. + > **NOTE** > -> This API is deprecated since API version 9. You are advised to use **[util.promisify9+](#utilpromisify9)** instead. - -Processes an asynchronous function and returns a promise. +> This API is unavailable. You are advised to use [util.promisify9+](#utilpromisify9) instead. **System capability**: SystemCapability.Utils.Lang @@ -246,6 +248,7 @@ Uses a secure random number generator to generate a random universally unique id | string | A string representing the UUID generated.| **Example** + ```js let uuid = util.randomUUID(true); console.log("RFC 4122 Version 4 UUID:" + uuid); @@ -274,6 +277,7 @@ Uses a secure random number generator to generate a random binary UUID of RFC 41 | Uint8Array | A Uint8Array value representing the UUID generated.| **Example** + ```js let uuid = util.randomBinaryUUID(true); console.log(JSON.stringify(uuid)); @@ -302,6 +306,7 @@ Parses a UUID from a string, as described in RFC 4122 version 4. | Uint8Array | A Uint8Array value representing the UUID parsed. If the parsing fails, **SyntaxError** is thrown.| **Example** + ```js let uuid = util.parseUUID("84bdf796-66cc-4655-9b89-d6218d100f9c"); console.log(JSON.stringify(uuid)); @@ -335,6 +340,8 @@ create(encoding?: string,options?: { fatal?: boolean; ignoreBOM?: boolean },): T Creates a **TextDecoder** object. It provides the same function as the deprecated argument constructor. +**System capability**: SystemCapability.Utils.Lang + **Parameters** | Name | Type | Mandatory| Description | @@ -342,7 +349,7 @@ Creates a **TextDecoder** object. It provides the same function as the deprecate | encoding | string | No | Encoding format. | | options | Object | No | Encoding-related options, which include **fatal** and **ignoreBOM**.| - **Table 1.1** options +**Table 1.1** options | Name | Type| Mandatory| Description | | --------- | -------- | ---- | ------------------ | @@ -351,21 +358,21 @@ Creates a **TextDecoder** object. It provides the same function as the deprecate **Example** - ```js +```js let textDecoder = new util.TextDecoder() textDecoder.create('utf-8', { ignoreBOM : true }); - ``` +``` ### constructor(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [constructor9+](#constructor9) instead. - constructor(encoding?: string, options?: { fatal?: boolean; ignoreBOM?: boolean },) A constructor used to create a **TextDecoder** object. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [constructor9+](#constructor9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -383,6 +390,7 @@ A constructor used to create a **TextDecoder** object. | ignoreBOM | boolean | No| Whether to ignore the BOM.| **Example** + ```js let textDecoder = new util.TextDecoder("utf-8",{ignoreBOM: true}); ``` @@ -402,7 +410,7 @@ Decodes the input content. | input | Uint8Array | Yes| Uint8Array to decode.| | options | Object | No| Options related to decoding.| - **Table 2** options +**Table 2** options | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | @@ -415,6 +423,7 @@ Decodes the input content. | string | Data decoded.| **Example** + ```js let textDecoder = new util.TextDecoder("utf-8",{ignoreBOM: true}); let result = new Uint8Array(6); @@ -445,7 +454,7 @@ Decodes the input content. | input | Uint8Array | Yes| Uint8Array to decode.| | options | Object | No| Options related to decoding.| - **Table 2** options +**Table 2** options | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | @@ -458,6 +467,7 @@ Decodes the input content. | string | Data decoded.| **Example** + ```js let textDecoder = new util.TextDecoder("utf-8",{ignoreBOM: true}); let result = new Uint8Array(6); @@ -493,6 +503,7 @@ A constructor used to create a **TextEncoder** object. **System capability**: SystemCapability.Utils.Lang **Example** + ```js let textEncoder = new util.TextEncoder(); ``` @@ -509,7 +520,7 @@ Encodes the input content. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------ | -| input | string | Yes | String to encode.| +| input | string | No | String to encode.| **Return value** @@ -528,21 +539,21 @@ result = textEncoder.encodeInto("\uD800¥¥"); ### encode(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [encodeInto9+](#encodeinto9) instead. - encode(input?: string): Uint8Array Encodes the input content. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [encodeInto9+](#encodeinto9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| input | string | Yes| String to encode.| +| input | string | No| String to encode.| **Return value** @@ -591,14 +602,14 @@ result = that.encodeInto('abcd', dest) ### encodeInto(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [encodeIntoUint8Array9+](#encodeintouint8array9) instead. - encodeInto(input: string, dest: Uint8Array, ): { read: number; written: number } Stores the UTF-8 encoded text. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [encodeIntoUint8Array9+](#encodeintouint8array9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -635,13 +646,13 @@ A constructor used to create a **RationalNumber** object. **Example** - ```js +```js let rationalNumber = new util.RationalNumber(); - ``` +``` ### parseRationalNumber9+ -parseRationalNumber(numerator: number,denominator: number) +parseRationalNumber(numerator: number,denominator: number): RationalNumber Parses a rational number. Previously, this processing is an internal action of the deprecated constructor. @@ -656,21 +667,20 @@ Parses a rational number. Previously, this processing is an internal action of t **Example** - ```js -let rationalNumber = new util.RationalNumber(); -rationalNumber.parseRationalNumber(1,2) - ``` +```js +let rationalNumber = util.RationalNumber.parseRationalNumber(1,2) +``` ### constructor(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [constructor9+](#constructor9) instead. - constructor(numerator: number,denominator: number) A constructor used to create a **RationalNumber** object. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [constructor9+](#constructor9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -682,9 +692,9 @@ A constructor used to create a **RationalNumber** object. **Example** - ```js - let rationalNumber = new util.RationalNumber(1,2); - ``` +```js +let rationalNumber = new util.RationalNumber(1,2); +``` ### createRationalFromString8+ @@ -707,10 +717,11 @@ Creates a **RationalNumber** object based on the given string. | object | **RationalNumber** object created.| **Example** - ```js - let rationalNumber = new util.RationalNumber(1,2); - let rational = util.RationalNumber.createRationalFromString("3/4"); - ``` + +```js +let rationalNumber = new util.RationalNumber(1,2); +let rational = util.RationalNumber.createRationalFromString("3/4"); +``` ### compare9+ @@ -740,16 +751,16 @@ let rational = util.RationalNumber.createRationalFromString("3/4"); let result = rationalNumber.compare(rational); ``` -### compareTo8+(deprecated) - -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [compare9+](#compare9) instead. +### compareTo(deprecated) compareTo​(another: RationalNumber): number​ Compares this **RationalNumber** object with a given object. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [compare9+](#compare9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -765,11 +776,12 @@ Compares this **RationalNumber** object with a given object. | number | Returns **0** if the two objects are equal; returns **1** if the given object is less than this object; return **-1** if the given object is greater than this object.| **Example** - ```js - let rationalNumber = new util.RationalNumber(1,2); - let rational = util.RationalNumber.createRationalFromString("3/4"); - let result = rationalNumber.compareTo(rational); - ``` + +```js +let rationalNumber = new util.RationalNumber(1,2); +let rational = util.RationalNumber.createRationalFromString("3/4"); +let result = rationalNumber.compareTo(rational); +``` ### valueOf8+ @@ -786,10 +798,11 @@ Obtains the value of this **RationalNumber** object as an integer or a floating- | number | An integer or a floating-point number.| **Example** - ```js - let rationalNumber = new util.RationalNumber(1,2); - let result = rationalNumber.valueOf(); - ``` + +```js +let rationalNumber = new util.RationalNumber(1,2); +let result = rationalNumber.valueOf(); +``` ### equals8+ @@ -812,11 +825,12 @@ Checks whether this **RationalNumber** object equals the given object. | boolean | Returns **true** if the two objects are equal; returns **false** otherwise.| **Example** - ```js - let rationalNumber = new util.RationalNumber(1,2); - let rational = util.RationalNumber.createRationalFromString("3/4"); - let result = rationalNumber.equals(rational); - ``` + +```js +let rationalNumber = new util.RationalNumber(1,2); +let rational = util.RationalNumber.createRationalFromString("3/4"); +let result = rationalNumber.equals(rational); +``` ### getCommonFactor9+ @@ -841,20 +855,21 @@ Obtains the greatest common divisor of two specified integers. **Example** - ```js +```js let rationalNumber = new util.RationalNumber(1,2); let result = util.RationalNumber.getCommonFactor(4,6); - ``` +``` ### getCommonDivisor(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [getCommonFactor9+](#getcommonfactor9) instead. static getCommonDivisor​(number1: number,number2: number): number Obtains the greatest common divisor of two specified integers. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getCommonFactor9+](#getcommonfactor9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -871,10 +886,11 @@ Obtains the greatest common divisor of two specified integers. | number | Greatest common divisor obtained.| **Example** - ```js - let rationalNumber = new util.RationalNumber(1,2); - let result = util.RationalNumber.getCommonDivisor(4,6); - ``` + +```js +let rationalNumber = new util.RationalNumber(1,2); +let result = util.RationalNumber.getCommonDivisor(4,6); +``` ### getNumerator8+ @@ -891,10 +907,11 @@ Obtains the numerator of this **RationalNumber** object. | number | Numerator of this **RationalNumber** object.| **Example** - ```js - let rationalNumber = new util.RationalNumber(1,2); - let result = rationalNumber.getNumerator(); - ``` + +```js +let rationalNumber = new util.RationalNumber(1,2); +let result = rationalNumber.getNumerator(); +``` ### getDenominator8+ @@ -911,10 +928,11 @@ Obtains the denominator of this **RationalNumber** object. | number | Denominator of this **RationalNumber** object.| **Example** - ```js - let rationalNumber = new util.RationalNumber(1,2); - let result = rationalNumber.getDenominator(); - ``` + +```js +let rationalNumber = new util.RationalNumber(1,2); +let result = rationalNumber.getDenominator(); +``` ### isZero8+ @@ -931,10 +949,11 @@ Checks whether this **RationalNumber** object is **0**. | boolean | Returns **true** if the value of this **RationalNumber** object is **0**; returns **false** otherwise.| **Example** - ```js - let rationalNumber = new util.RationalNumber(1,2); - let result = rationalNumber.isZero(); - ``` + +```js +let rationalNumber = new util.RationalNumber(1,2); +let result = rationalNumber.isZero(); +``` ### isNaN8+ @@ -951,10 +970,11 @@ Checks whether this **RationalNumber** object is a Not a Number (NaN). | boolean | Returns **true** if this **RationalNumber** object is a NaN (the denominator and numerator are both **0**); returns **false** otherwise.| **Example** - ```js - let rationalNumber = new util.RationalNumber(1,2); - let result = rationalNumber.isNaN(); - ``` + +```js +let rationalNumber = new util.RationalNumber(1,2); +let result = rationalNumber.isNaN(); +``` ### isFinite8+ @@ -971,10 +991,11 @@ Checks whether this **RationalNumber** object represents a finite value. | boolean | Returns **true** if this **RationalNumber** object represents a finite value (the denominator is not **0**); returns **false** otherwise.| **Example** - ```js - let rationalNumber = new util.RationalNumber(1,2); - let result = rationalNumber.isFinite(); - ``` + +```js +let rationalNumber = new util.RationalNumber(1,2); +let result = rationalNumber.isFinite(); +``` ### toString8+ @@ -991,10 +1012,11 @@ Obtains the string representation of this **RationalNumber** object. | string | Returns **NaN** if the numerator and denominator of this object are both **0**; returns a string in Numerator/Denominator format otherwise, for example, **3/5**.| **Example** - ```js - let rationalNumber = new util.RationalNumber(1,2); - let result = rationalNumber.toString(); - ``` + +```js +let rationalNumber = new util.RationalNumber(1,2); +let result = rationalNumber.toString(); +``` ## LRUCache9+ @@ -1005,22 +1027,22 @@ Obtains the string representation of this **RationalNumber** object. | Name | Type | Readable| Writable| Description | | ------ | ------ | ---- | ---- | ---------------------- | -| length | number | Yes | No | Total number of values in this buffer. | +| length | number | Yes | No | Total number of values in this cache.| **Example** - ```js +```js let pro = new util.LRUCache(); pro.put(2,10); pro.put(1,8); let result = pro.length; - ``` +``` ### constructor9+ constructor(capacity?: number) -A constructor used to create a **LruBuffer** instance. The default capacity of the buffer is 64. +A constructor used to create a **LruCache** instance. The default capacity of the cache is 64. **System capability**: SystemCapability.Utils.Lang @@ -1028,20 +1050,20 @@ A constructor used to create a **LruBuffer** instance. The default capacity of t | Name | Type | Mandatory| Description | | -------- | ------ | ---- | ---------------------------- | -| capacity | number | No | Capacity of the **LruBuffer** to create.| +| capacity | number | No | Capacity of the **LruCache** to create.| **Example** - ```js +```js let lrubuffer= new util.LRUCache(); - ``` +``` ### updateCapacity9+ updateCapacity(newCapacity: number): void -Changes the **LruBuffer** capacity. If the new capacity is less than or equal to **0**, an exception will be thrown. +Changes the **LruCache** capacity. If the new capacity is less than or equal to **0**, an exception will be thrown. **System capability**: SystemCapability.Utils.Lang @@ -1049,21 +1071,21 @@ Changes the **LruBuffer** capacity. If the new capacity is less than or equal to | Name | Type | Mandatory| Description | | ----------- | ------ | ---- | ---------------------------- | -| newCapacity | number | Yes | New capacity of the **LruBuffer**.| +| newCapacity | number | Yes | New capacity of the **LruCache**.| **Example** - ```js +```js let pro = new util.LRUCache(); let result = pro.updateCapacity(100); - ``` +``` ### toString9+ toString(): string -Obtains the string representation of this **LruBuffer** object. +Obtains the string representation of this **LruCache** object. **System capability**: SystemCapability.Utils.Lang @@ -1071,24 +1093,24 @@ Obtains the string representation of this **LruBuffer** object. | Type | Description | | ------ | -------------------------- | -| string | String representation of this **LruBuffer** object.| +| string | String representation of this **LruCache** object.| **Example** - ```js +```js let pro = new util.LRUCache(); pro.put(2,10); pro.get(2); pro.remove(20); let result = pro.toString(); - ``` +``` ### getCapacity9+ getCapacity(): number -Obtains the capacity of this buffer. +Obtains the capacity of this cache. **System capability**: SystemCapability.Utils.Lang @@ -1096,7 +1118,7 @@ Obtains the capacity of this buffer. | Type | Description | | ------ | ---------------------- | -| number | Capacity of this buffer.| +| number | Capacity of this cache.| **Example** @@ -1110,7 +1132,7 @@ let result = pro.getCapacity(); clear(): void -Clears key-value pairs from this buffer. The **afterRemoval()** method will be called to perform subsequent operations. +Clears key-value pairs from this cache. The **afterRemoval()** method will be called to perform subsequent operations. **System capability**: SystemCapability.Utils.Lang @@ -1175,7 +1197,7 @@ let result = pro.getMissCount(); getRemovalCount(): number -Obtains the number of removals from this buffer. +Obtains the number of removals from this cache. **System capability**: SystemCapability.Utils.Lang @@ -1183,7 +1205,7 @@ Obtains the number of removals from this buffer. | Type | Description | | ------ | -------------------------- | -| number | Number of removals from the buffer.| +| number | Number of removals from the cache.| **Example** @@ -1224,7 +1246,7 @@ let result = pro.getMatchCount(); getPutCount(): number -Obtains the number of additions to this buffer. +Obtains the number of additions to this cache. **System capability**: SystemCapability.Utils.Lang @@ -1232,7 +1254,7 @@ Obtains the number of additions to this buffer. | Type | Description | | ------ | ---------------------------- | -| number | Number of additions to the buffer.| +| number | Number of additions to the cache.| **Example** @@ -1247,7 +1269,7 @@ let result = pro.getPutCount(); isEmpty(): boolean -Checks whether this buffer is empty. +Checks whether this cache is empty. **System capability**: SystemCapability.Utils.Lang @@ -1255,7 +1277,7 @@ Checks whether this buffer is empty. | Type | Description | | ------- | ---------------------------------------- | -| boolean | Returns **true** if the buffer does not contain any value.| +| boolean | Returns **true** if the cache does not contain any value.| **Example** @@ -1284,7 +1306,7 @@ Obtains the value of the specified key. | Type | Description | | ------------------------ | ------------------------------------------------------------ | -| V \| undefined | Returns the value of the key if a match is found in the buffer; returns **undefined** otherwise.| +| V \| undefined | Returns the value of the key if a match is found in the cache; returns **undefined** otherwise.| **Example** @@ -1299,7 +1321,7 @@ let result = pro.get(2); put(key: K,value: V): V -Adds a key-value pair to this buffer. +Adds a key-value pair to this cache. **System capability**: SystemCapability.Utils.Lang @@ -1327,7 +1349,7 @@ let result = pro.put(2,10); values(): V[] -Obtains all values in this buffer, listed from the most to the least recently accessed. +Obtains all values in this cache, listed from the most to the least recently accessed. **System capability**: SystemCapability.Utils.Lang @@ -1335,7 +1357,7 @@ Obtains all values in this buffer, listed from the most to the least recently ac | Type | Description | | --------- | ------------------------------------------------------------ | -| V [] | All values in the buffer, listed from the most to the least recently accessed.| +| V [] | All values in the cache, listed from the most to the least recently accessed.| **Example** @@ -1352,7 +1374,7 @@ let result = pro.values(); keys(): K[] -Obtains all keys in this buffer, listed from the most to the least recently accessed. +Obtains all keys in this cache, listed from the most to the least recently accessed. **System capability**: SystemCapability.Utils.Lang @@ -1360,7 +1382,7 @@ Obtains all keys in this buffer, listed from the most to the least recently acce | Type | Description | | --------- | ------------------------------------------------------------ | -| K [] | All keys in the buffer, listed from the most to the least recently accessed.| +| K [] | All keys in the cache, listed from the most to the least recently accessed.| **Example** @@ -1375,7 +1397,7 @@ let result = pro.keys(); remove(key: K): V | undefined -Removes the specified key and its value from this buffer. +Removes the specified key and its value from this cache. **System capability**: SystemCapability.Utils.Lang @@ -1389,7 +1411,7 @@ Removes the specified key and its value from this buffer. | Type | Description | | ------------------------ | ------------------------------------------------------------ | -| V \| undefined | Returns an **Optional** object containing the removed key-value pair if the key exists in the buffer; returns an empty **Optional** object otherwise. If the key is null, an exception will be thrown.| +| V \| undefined | Returns an **Optional** object containing the removed key-value pair if the key exists in the cache; returns an empty **Optional** object otherwise. If the key is null, an exception will be thrown.| **Example** @@ -1412,10 +1434,10 @@ Performs subsequent operations after a value is removed. | Name | Type | Mandatory| Description | | -------- | ------- | ---- | ------------------------------------------------------------ | -| isEvict | boolean | No | Whether the buffer capacity is insufficient. If the value is **true**, this method is called due to insufficient capacity. | +| isEvict | boolean | Yes | Whether the cache capacity is insufficient. If the value is **true**, this method is called due to insufficient capacity. | | key | K | Yes | Key removed. | | value | V | Yes | Value removed. | -| newValue | V | No | New value for the key if the **put()** method is called and the key to be added already exists. In other cases, this parameter is left blank.| +| newValue | V | Yes | New value for the key if the **put()** method is called and the key to be added already exists. In other cases, this parameter is left blank.| **Example** @@ -1442,30 +1464,31 @@ lru.afterRemoval(false,10,30,null); ### contains9+ -contains(key: K): boolean +contains(key: object): boolean -Checks whether this buffer contains the specified key. +Checks whether this cache contains the specified key. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type| Mandatory| Description | -| ------ | ---- | ---- | ---------------- | -| key | K | Yes | Key to check.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------- | +| key | object | Yes | Key to check.| **Return value** | Type | Description | | ------- | ------------------------------------------ | -| boolean | Returns **true** if the buffer contains the specified key; returns **false** otherwise.| +| boolean | Returns **true** if the cache contains the specified key; returns **false** otherwise.| **Example** ```js let pro = new util.LRUCache(); pro.put(2,10); -let result = pro.contains(20); +let obj = {1:"key"}; +let result = pro.contains(obj); ``` @@ -1545,7 +1568,7 @@ let result = pro[Symbol.iterator](); > **NOTE** > -> This API is deprecated since API version 9. You are advised to use [LRUCache9+](#lrucache9) instead. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [LRUCache9+](#lrucache9) instead. ### Attributes @@ -1556,6 +1579,7 @@ let result = pro[Symbol.iterator](); | length | number | Yes| No| Total number of values in this buffer.| **Example** + ```js let pro = new util.LruBuffer(); pro.put(2,10); @@ -1565,14 +1589,14 @@ let result = pro[Symbol.iterator](); ### constructor(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [constructor9+](#constructor9) instead. - constructor(capacity?: number) A constructor used to create a **LruBuffer** instance. The default capacity of the buffer is 64. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [constructor9+](#constructor9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -1582,20 +1606,21 @@ A constructor used to create a **LruBuffer** instance. The default capacity of t | capacity | number | No| Capacity of the **LruBuffer** to create.| **Example** + ```js let lrubuffer= new util.LruBuffer(); ``` ### updateCapacity(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [updateCapacity9+](#updatecapacity9) instead. - updateCapacity(newCapacity: number): void Changes the **LruBuffer** capacity. If the new capacity is less than or equal to **0**, an exception will be thrown. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [updateCapacity9+](#updatecapacity9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -1605,6 +1630,7 @@ Changes the **LruBuffer** capacity. If the new capacity is less than or equal to | newCapacity | number | Yes| New capacity of the **LruBuffer**.| **Example** + ```js let pro = new util.LruBuffer(); let result = pro.updateCapacity(100); @@ -1612,14 +1638,14 @@ Changes the **LruBuffer** capacity. If the new capacity is less than or equal to ### toString(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [toString9+](#tostring9) instead. - toString(): string Obtains the string representation of this **LruBuffer** object. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [toString9+](#tostring9) instead. + **System capability**: SystemCapability.Utils.Lang **Return value** @@ -1629,6 +1655,7 @@ Obtains the string representation of this **LruBuffer** object. | string | String representation of this **LruBuffer** object.| **Example** + ```js let pro = new util.LruBuffer(); pro.put(2,10); @@ -1639,14 +1666,14 @@ Obtains the string representation of this **LruBuffer** object. ### getCapacity(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [getCapacity9+](#getcapacity9) instead. - getCapacity(): number Obtains the capacity of this buffer. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getCapacity9+](#getcapacity9) instead. + **System capability**: SystemCapability.Utils.Lang **Return value** @@ -1663,17 +1690,18 @@ Obtains the capacity of this buffer. ### clear(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [clear9+](#clear9) instead. - clear(): void Clears key-value pairs from this buffer. The **afterRemoval()** method will be called to perform subsequent operations. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [clear9+](#clear9) instead. + **System capability**: SystemCapability.Utils.Lang **Example** + ```js let pro = new util.LruBuffer(); pro.put(2,10); @@ -1683,14 +1711,14 @@ Clears key-value pairs from this buffer. The **afterRemoval()** method will be c ### getCreateCount(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [getCreateCount9+](#getcreatecount9) instead. - getCreateCount(): number Obtains the number of return values for **createDefault()**. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getCreateCount9+](#getcreatecount9) instead. + **System capability**: SystemCapability.Utils.Lang **Return value** @@ -1700,6 +1728,7 @@ Obtains the number of return values for **createDefault()**. | number | Number of return values for **createDefault()**.| **Example** + ```js let pro = new util.LruBuffer(); pro.put(1,8); @@ -1708,14 +1737,14 @@ Obtains the number of return values for **createDefault()**. ### getMissCount(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [getMissCount9+](#getmisscount9) instead. - getMissCount(): number Obtains the number of times that the queried values are mismatched. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getMissCount9+](#getmisscount9) instead. + **System capability**: SystemCapability.Utils.Lang **Return value** @@ -1725,6 +1754,7 @@ Obtains the number of times that the queried values are mismatched. | number | Number of times that the queried values are mismatched.| **Example** + ```js let pro = new util.LruBuffer(); pro.put(2,10); @@ -1734,14 +1764,14 @@ Obtains the number of times that the queried values are mismatched. ### getRemovalCount(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [getRemovalCount9+](#getremovalcount9) instead. - getRemovalCount(): number Obtains the number of removals from this buffer. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getRemovalCount9+](#getremovalcount9) instead. + **System capability**: SystemCapability.Utils.Lang **Return value** @@ -1751,6 +1781,7 @@ Obtains the number of removals from this buffer. | number | Number of removals from the buffer.| **Example** + ```js let pro = new util.LruBuffer(); pro.put(2,10); @@ -1761,14 +1792,14 @@ Obtains the number of removals from this buffer. ### getMatchCount(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [getMatchCount9+](#getmatchcount9) instead. - getMatchCount(): number Obtains the number of times that the queried values are matched. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getMatchCount9+](#getmatchcount9) instead. + **System capability**: SystemCapability.Utils.Lang **Return value** @@ -1778,6 +1809,7 @@ Obtains the number of times that the queried values are matched. | number | Number of times that the queried values are matched.| **Example** + ```js let pro = new util.LruBuffer(); pro.put(2,10); @@ -1787,14 +1819,14 @@ Obtains the number of times that the queried values are matched. ### getPutCount(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [getPutCount9+](#getputcount9) instead. - getPutCount(): number Obtains the number of additions to this buffer. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getPutCount9+](#getputcount9) instead. + **System capability**: SystemCapability.Utils.Lang **Return value** @@ -1804,6 +1836,7 @@ Obtains the number of additions to this buffer. | number | Number of additions to the buffer.| **Example** + ```js let pro = new util.LruBuffer(); pro.put(2,10); @@ -1812,14 +1845,14 @@ Obtains the number of additions to this buffer. ### isEmpty(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [isEmpty9+](#isempty9) instead. - isEmpty(): boolean Checks whether this buffer is empty. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [isEmpty9+](#isempty9) instead. + **System capability**: SystemCapability.Utils.Lang **Return value** @@ -1829,6 +1862,7 @@ Checks whether this buffer is empty. | boolean | Returns **true** if the buffer does not contain any value.| **Example** + ```js let pro = new util.LruBuffer(); pro.put(2,10); @@ -1837,14 +1871,14 @@ Checks whether this buffer is empty. ### get(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [get9+](#get9) instead. - get(key: K): V | undefined Obtains the value of the specified key. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [get9+](#get9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -1860,6 +1894,7 @@ Obtains the value of the specified key. | V \| undefined | Returns the value of the key if a match is found in the buffer; returns **undefined** otherwise.| **Example** + ```js let pro = new util.LruBuffer(); pro.put(2,10); @@ -1868,14 +1903,14 @@ Obtains the value of the specified key. ### put(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [put9+](#put9) instead. - put(key: K,value: V): V Adds a key-value pair to this buffer. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [put9+](#put9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -1892,6 +1927,7 @@ Adds a key-value pair to this buffer. | V | Returns the existing value if the key already exists; returns the value added otherwise. If the key or value is null, an exception will be thrown. | **Example** + ```js let pro = new util.LruBuffer(); let result = pro.put(2,10); @@ -1899,14 +1935,14 @@ Adds a key-value pair to this buffer. ### values(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [values9+](#values9) instead. - values(): V[] Obtains all values in this buffer, listed from the most to the least recently accessed. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [values9+](#values9) instead. + **System capability**: SystemCapability.Utils.Lang **Return value** @@ -1916,6 +1952,7 @@ Obtains all values in this buffer, listed from the most to the least recently ac | V [] | All values in the buffer, listed from the most to the least recently accessed.| **Example** + ```js let pro = new util.LruBuffer(); pro.put(2,10); @@ -1926,14 +1963,14 @@ Obtains all values in this buffer, listed from the most to the least recently ac ### keys(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [keys9+](#keys9) instead. - keys(): K[] Obtains all keys in this buffer, listed from the most to the least recently accessed. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [keys9+](#keys9) instead. + **System capability**: SystemCapability.Utils.Lang **Return value** @@ -1951,14 +1988,14 @@ Obtains all keys in this buffer, listed from the most to the least recently acce ### remove(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [remove9+](#remove9) instead. - remove(key: K): V | undefined Removes the specified key and its value from this buffer. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [remove9+](#remove9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -1982,26 +2019,27 @@ Removes the specified key and its value from this buffer. ### afterRemoval(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [afterRemoval9+](#afterremoval9) instead. - afterRemoval(isEvict: boolean,key: K,value: V,newValue: V): void Performs subsequent operations after a value is removed. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [afterRemoval9+](#afterremoval9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| isEvict | boolean | No| Whether the buffer capacity is insufficient. If the value is **true**, this method is called due to insufficient capacity.| +| isEvict | boolean | Yes| Whether the buffer capacity is insufficient. If the value is **true**, this method is called due to insufficient capacity.| | key | K | Yes| Key removed.| | value | V | Yes| Value removed.| -| newValue | V | No| New value for the key if the **put()** method is called and the key to be added already exists. In other cases, this parameter is left blank.| +| newValue | V | Yes| New value for the key if the **put()** method is called and the key to be added already exists. In other cases, this parameter is left blank.| **Example** + ```js let arr = []; class ChildLruBuffer extends util.LruBuffer @@ -2024,14 +2062,15 @@ Performs subsequent operations after a value is removed. ### contains(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [contains9+](#contains9) instead. - contains(key: K): boolean Checks whether this buffer contains the specified key. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [contains9+](#contains9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -2047,6 +2086,7 @@ Checks whether this buffer contains the specified key. | boolean | Returns **true** if the buffer contains the specified key; returns **false** otherwise.| **Example** + ```js let pro = new util.LruBuffer(); pro.put(2,10); @@ -2055,14 +2095,14 @@ Checks whether this buffer contains the specified key. ### createDefault(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [createDefault9+](#createdefault9) instead. - createDefault(key: K): V Creates a value if the value of the specified key is not available. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [createDefault9+](#createdefault9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -2078,6 +2118,7 @@ Creates a value if the value of the specified key is not available. | V | Value of the key.| **Example** + ```js let pro = new util.LruBuffer(); let result = pro.createDefault(50); @@ -2085,14 +2126,14 @@ Creates a value if the value of the specified key is not available. ### entries(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [entries9+](#entries9) instead. - entries(): IterableIterator<[K,V]> Obtains a new iterator object that contains all key-value pairs in this object. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [entries9+](#entries9) instead. + **System capability**: SystemCapability.Utils.Lang **Return value** @@ -2102,6 +2143,7 @@ Obtains a new iterator object that contains all key-value pairs in this object. | [K, V] | Iterable array.| **Example** + ```js let pro = new util.LruBuffer(); pro.put(2,10); @@ -2110,14 +2152,14 @@ Obtains a new iterator object that contains all key-value pairs in this object. ### [Symbol.iterator](deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [Symbol.iterator9+](#symboliterator9) instead. - [Symbol.iterator]\(): IterableIterator<[K, V]> Obtains a two-dimensional array in key-value pairs. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [Symbol.iterator9+](#symboliterator9) instead. + **System capability**: SystemCapability.Utils.Lang **Return value** @@ -2127,6 +2169,7 @@ Obtains a two-dimensional array in key-value pairs. | [K, V] | Two-dimensional array in key-value pairs.| **Example** + ```js let pro = new util.LruBuffer(); pro.put(2,10); @@ -2138,6 +2181,7 @@ Obtains a two-dimensional array in key-value pairs. Defines the type of values in a **Scope** object. The value type can be **ScopeComparable** or **number**. The values of the **ScopeComparable** type are used to implement the **compareTo** method. Therefore, ensure that the input parameters are comparable. + ```js interface ScopeComparable{ compareTo(other: ScopeComparable): boolean; @@ -2229,9 +2273,9 @@ Obtains the intersection of this **Scope** and the given **Scope**. **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------------------------------ | ---- | ------------------ | -| range | [ScopeHelper9+](#scopehelper9) | Yes | **Scope** specified.| +| Name| Type | Mandatory| Description | +| ------ | ---------------------------- | ---- | ------------------ | +| range | [ScopeHelper](#scopehelper9) | Yes | **Scope** specified.| **Return value** @@ -2269,9 +2313,9 @@ Obtains the intersection of this **Scope** and the given lower and upper limits. **Return value** -| Type | Description | -| ------------------------------ | ---------------------------------------- | -| [ScopeHelper9+](#scopehelper9) | Intersection of this **Scope** and the given lower and upper limits.| +| Type | Description | +| ---------------------------- | ---------------------------------------- | +| [ScopeHelper](#scopehelper9) | Intersection of this **Scope** and the given lower and upper limits.| **Example** @@ -2350,9 +2394,9 @@ Obtains the union set of this **Scope** and the given lower and upper limits. **Return value** -| Type | Description | -| ------------------------------ | ------------------------------------ | -| [ScopeHelper9+](#scopehelper9) | Union set of this **Scope** and the given lower and upper limits.| +| Type | Description | +| ---------------------------- | ------------------------------------ | +| [ScopeHelper](#scopehelper9) | Union set of this **Scope** and the given lower and upper limits.| **Example** @@ -2376,15 +2420,15 @@ Obtains the union set of this **Scope** and the given **Scope**. **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------------------------------ | ---- | ------------------ | -| range | [ScopeHelper9+](#scopehelper9) | Yes | **Scope** specified.| +| Name| Type | Mandatory| Description | +| ------ | ---------------------------- | ---- | ------------------ | +| range | [ScopeHelper](#scopehelper9) | Yes | **Scope** specified.| **Return value** -| Type | Description | -| ------------------------------ | ---------------------------------- | -| [ScopeHelper9+](#scopehelper9) | Union set of this **Scope** and the given **Scope**.| +| Type | Description | +| ---------------------------- | ---------------------------------- | +| [ScopeHelper](#scopehelper9) | Union set of this **Scope** and the given **Scope**.| **Example** @@ -2415,9 +2459,9 @@ Obtains the union set of this **Scope** and the given value. **Return value** -| Type | Description | -| ------------------------------ | -------------------------------- | -| [ScopeHelper9+](#scopehelper9) | Union set of this **Scope** and the given value.| +| Type | Description | +| ---------------------------- | -------------------------------- | +| [ScopeHelper](#scopehelper9) | Union set of this **Scope** and the given value.| **Example** @@ -2471,9 +2515,9 @@ Checks whether a range is within this **Scope**. **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------------------------------ | ---- | ------------------ | -| range | [ScopeHelper9+](#scopehelper9) | Yes | **Scope** specified.| +| Name| Type | Mandatory| Description | +| ------ | ---------------------------- | ---- | ------------------ | +| range | [ScopeHelper](#scopehelper9) | Yes | **Scope** specified.| **Return value** @@ -2528,18 +2572,19 @@ let result = range.clamp(tempMiDF); > **NOTE** > -> This class is deprecated since API version 9. You are advised to use [ScopeHelper9+](#scopehelper9) instead. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [ScopeHelper9+](#scopehelper9) instead. ### constructor(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [constructor9+](#constructor9) instead. - constructor(lowerObj: ScopeType, upperObj: ScopeType) A constructor used to create a **Scope** object with the specified upper and lower limits. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [constructor9+](#constructor9) instead. + + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -2558,14 +2603,14 @@ A constructor used to create a **Scope** object with the specified upper and low ### toString(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [toString9+](#tostring9) instead. - toString(): string Obtains a string representation that contains this **Scope**. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [toString9+](#tostring9) instead. + **System capability**: SystemCapability.Utils.Lang **Return value** @@ -2575,6 +2620,7 @@ Obtains a string representation that contains this **Scope**. | string | String representation containing the **Scope**.| **Example** + ```js let tempLower = new Temperature(30); let tempUpper = new Temperature(40); @@ -2584,14 +2630,14 @@ Obtains a string representation that contains this **Scope**. ### intersect(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [intersect9+](#intersect9) instead. - intersect(range: Scope): Scope Obtains the intersection of this **Scope** and the given **Scope**. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [intersect9+](#intersect9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -2620,14 +2666,14 @@ Obtains the intersection of this **Scope** and the given **Scope**. ### intersect(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [intersect9+](#intersect9) instead. - intersect(lowerObj:ScopeType,upperObj:ScopeType):Scope Obtains the intersection of this **Scope** and the given lower and upper limits. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [intersect9+](#intersect9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -2644,6 +2690,7 @@ Obtains the intersection of this **Scope** and the given lower and upper limits. | [Scope](#scopedeprecated) | Intersection of this **Scope** and the given lower and upper limits.| **Example** + ```js let tempLower = new Temperature(30); let tempUpper = new Temperature(40); @@ -2655,14 +2702,14 @@ Obtains the intersection of this **Scope** and the given lower and upper limits. ### getUpper(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [getUpper9+](#getupper9) instead. - getUpper(): ScopeType Obtains the upper limit of this **Scope**. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getUpper9+](#getupper9) instead. + **System capability**: SystemCapability.Utils.Lang **Return value** @@ -2672,6 +2719,7 @@ Obtains the upper limit of this **Scope**. | [ScopeType](#scopetype8) | Upper limit of this **Scope**.| **Example** + ```js let tempLower = new Temperature(30); let tempUpper = new Temperature(40); @@ -2681,14 +2729,14 @@ Obtains the upper limit of this **Scope**. ### getLower(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [getLower9+](#getlower9) instead. - getLower(): ScopeType Obtains the lower limit of this **Scope**. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getLower9+](#getlower9) instead. + **System capability**: SystemCapability.Utils.Lang **Return value** @@ -2698,6 +2746,7 @@ Obtains the lower limit of this **Scope**. | [ScopeType](#scopetype8) | Lower limit of this **Scope**.| **Example** + ```js let tempLower = new Temperature(30); let tempUpper = new Temperature(40); @@ -2707,14 +2756,14 @@ Obtains the lower limit of this **Scope**. ### expand(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [expand9+](#expand9) instead. - expand(lowerObj: ScopeType,upperObj: ScopeType): Scope Obtains the union set of this **Scope** and the given lower and upper limits. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [expand9+](#expand9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -2743,14 +2792,14 @@ Obtains the union set of this **Scope** and the given lower and upper limits. ### expand(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [expand9+](#expand9) instead. - expand(range: Scope): Scope Obtains the union set of this **Scope** and the given **Scope**. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [expand9+](#expand9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -2766,6 +2815,7 @@ Obtains the union set of this **Scope** and the given **Scope**. | [Scope](#scopedeprecated) | Union set of this **Scope** and the given **Scope**.| **Example** + ```js let tempLower = new Temperature(30); let tempUpper = new Temperature(40); @@ -2778,14 +2828,14 @@ Obtains the union set of this **Scope** and the given **Scope**. ### expand(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [expand9+](#expand9) instead. - expand(value: ScopeType): Scope Obtains the union set of this **Scope** and the given value. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [expand9+](#expand9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -2801,6 +2851,7 @@ Obtains the union set of this **Scope** and the given value. | [Scope](#scopedeprecated) | Union set of this **Scope** and the given value.| **Example** + ```js let tempLower = new Temperature(30); let tempUpper = new Temperature(40); @@ -2811,14 +2862,14 @@ Obtains the union set of this **Scope** and the given value. ### contains(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [contains9+](#contains9) instead. - contains(value: ScopeType): boolean Checks whether a value is within this **Scope**. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [contains9+](#contains9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -2834,6 +2885,7 @@ Checks whether a value is within this **Scope**. | boolean | Returns **true** if the value is within this **Scope**; returns **false** otherwise.| **Example** + ```js let tempLower = new Temperature(30); let tempUpper = new Temperature(40); @@ -2844,14 +2896,14 @@ Checks whether a value is within this **Scope**. ### contains(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [contains9+](#contains9) instead. - contains(range: Scope): boolean Checks whether a range is within this **Scope**. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [contains9+](#contains9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -2880,14 +2932,15 @@ Checks whether a range is within this **Scope**. ### clamp(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [clamp9+](#clamp9) instead. clamp(value: ScopeType): ScopeType Limits a value to this **Scope**. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [clamp9+](#clamp9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -2903,6 +2956,7 @@ Limits a value to this **Scope**. | [ScopeType](#scopetype8) | Returns **lowerObj** if the specified value is less than the lower limit; returns **upperObj** if the specified value is greater than the upper limit; returns the specified value if it is within this **Scope**.| **Example** + ```js let tempLower = new Temperature(30); let tempUpper = new Temperature(40); @@ -3117,35 +3171,36 @@ that.decode(array).then(val=>{ > **NOTE** > -> This class is deprecated since API version 9. You are advised to use [Base64Helper9+](#base64helper9) instead. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [Base64Helper9+](#base64helper9) instead. ### constructor(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [constructor9+](#constructor9) instead. - constructor() A constructor used to create a **Base64** object. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [constructor9+](#constructor9) instead. + **System capability**: SystemCapability.Utils.Lang **Example** + ```js let base64 = new util.Base64(); ``` ### encodeSync(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [encodeSync9+](#encodesync9) instead. - encodeSync(src: Uint8Array): Uint8Array Encodes the input content. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [encodeSync9+](#encodesync9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -3170,14 +3225,14 @@ Encodes the input content. ### encodeToStringSync(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [encodeToStringSync9+](#encodetostringsync9) instead. - encodeToStringSync(src: Uint8Array): string Encodes the input content. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [encodeToStringSync9+](#encodetostringsync9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -3193,6 +3248,7 @@ Encodes the input content. | string | String encoded from the Uint8Array.| **Example** + ```js let that = new util.Base64(); let array = new Uint8Array([115,49,51]); @@ -3201,14 +3257,14 @@ Encodes the input content. ### decodeSync(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [decodeSync9+](#decodesync9) instead. - decodeSync(src: Uint8Array | string): Uint8Array Decodes the input content. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [decodeSync9+](#decodesync9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -3224,6 +3280,7 @@ Decodes the input content. | Uint8Array | Uint8Array decoded.| **Example** + ```js let that = new util.Base64(); let buff = 'czEz'; @@ -3232,14 +3289,14 @@ Decodes the input content. ### encode(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [encode9+](#encode9) instead. - encode(src: Uint8Array): Promise<Uint8Array> Encodes the input content asynchronously. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [encode9+](#encode9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -3255,6 +3312,7 @@ Encodes the input content asynchronously. | Promise<Uint8Array> | Uint8Array obtained after asynchronous encoding.| **Example** + ```js let that = new util.Base64(); let array = new Uint8Array([115,49,51]); @@ -3268,14 +3326,14 @@ Encodes the input content asynchronously. ### encodeToString(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [encodeToString9+](#encodetostring9) instead. - encodeToString(src: Uint8Array): Promise<string> Encodes the input content asynchronously. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [encodeToString9+](#encodetostring9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -3291,6 +3349,7 @@ Encodes the input content asynchronously. | Promise<string> | String obtained after asynchronous encoding.| **Example** + ```js let that = new util.Base64(); let array = new Uint8Array([115,49,51]); @@ -3301,14 +3360,15 @@ Encodes the input content asynchronously. ### decode(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [decode9+](#decode9) instead. decode(src: Uint8Array | string): Promise<Uint8Array> Decodes the input content asynchronously. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [decode9+](#decode9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -3324,6 +3384,7 @@ Decodes the input content asynchronously. | Promise<Uint8Array> | Uint8Array obtained after asynchronous decoding.| **Example** + ```js let that = new util.Base64(); let array = new Uint8Array([99,122,69,122]); @@ -3347,6 +3408,7 @@ A constructor used to create a **Types** object. **System capability**: SystemCapability.Utils.Lang **Example** + ```js let type = new util.types(); ``` @@ -3373,6 +3435,7 @@ Checks whether the input value is of the **ArrayBuffer** type. | boolean | Returns **true** if the input value is of the **ArrayBuffer** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isAnyArrayBuffer(new ArrayBuffer(0)); @@ -3402,6 +3465,7 @@ Checks whether the input value is of the **ArrayBufferView** type. | boolean | Returns **true** if the input value is of the **ArrayBufferView** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isArrayBufferView(new Int8Array([])); @@ -3429,6 +3493,7 @@ Checks whether the input value is of the **arguments** type. | boolean | Returns **true** if the input value is of the **arguments** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); function foo() { @@ -3459,6 +3524,7 @@ Checks whether the input value is of the **ArrayBuffer** type. | boolean | Returns **true** if the input value is of the **ArrayBuffer** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isArrayBuffer(new ArrayBuffer(0)); @@ -3486,6 +3552,7 @@ Checks whether the input value is an asynchronous function. | boolean | Returns **true** if the input value is an asynchronous function; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isAsyncFunction(async function foo() {}); @@ -3513,6 +3580,7 @@ Checks whether the input value is of the **Boolean** type. | boolean | Returns **true** if the input value is of the **Boolean** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isBooleanObject(new Boolean(true)); @@ -3540,6 +3608,7 @@ Checks whether the input value is of the **Boolean**, **Number**, **String**, or | boolean | Returns **true** if the input value is of the **Boolean**, **Number**, **String**, or **Symbol** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isBoxedPrimitive(new Boolean(false)); @@ -3567,6 +3636,7 @@ Checks whether the input value is of the **DataView** type. | boolean | Returns **true** if the input value is of the **DataView** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); const ab = new ArrayBuffer(20); @@ -3595,6 +3665,7 @@ Checks whether the input value is of the **Date** type. | boolean | Returns **true** if the input value is of the **Date** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isDate(new Date()); @@ -3622,6 +3693,7 @@ Checks whether the input value is of the **native external** type. | boolean | Returns **true** if the input value is of the **native external** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isExternal(true); @@ -3649,6 +3721,7 @@ Checks whether the input value is of the **Float32Array** type. | boolean | Returns **true** if the input value is of the **Float32Array** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isFloat32Array(new Float32Array()); @@ -3676,6 +3749,7 @@ Checks whether the input value is of the **Float64Array** type. | boolean | Returns **true** if the input value is of the **Float64Array** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isFloat64Array(new Float64Array()); @@ -3703,6 +3777,7 @@ Checks whether the input value is a generator function. | boolean | Returns **true** if the input value is a generator function; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isGeneratorFunction(function* foo() {}); @@ -3730,6 +3805,7 @@ Checks whether the input value is a generator object. | boolean | Returns **true** if the input value is a generator object; returns **false** otherwise.| **Example** + ```js let that = new util.types(); function* foo() {} @@ -3759,6 +3835,7 @@ Checks whether the input value is of the **Int8Array** type. | boolean | Returns **true** if the input value is of the **Int8Array** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isInt8Array(new Int8Array([])); @@ -3786,6 +3863,7 @@ Checks whether the input value is of the **Int16Array** type. | boolean | Returns **true** if the input value is of the **Int16Array** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isInt16Array(new Int16Array([])); @@ -3813,6 +3891,7 @@ Checks whether the input value is of the **Int32Array** type. | boolean | Returns **true** if the input value is of the **Int32Array** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isInt32Array(new Int32Array([])); @@ -3840,6 +3919,7 @@ Checks whether the input value is of the **Map** type. | boolean | Returns **true** if the input value is of the **Map** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isMap(new Map()); @@ -3856,6 +3936,7 @@ Checks whether the input value is of the **MapIterator** type. **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| @@ -3867,6 +3948,7 @@ Checks whether the input value is of the **MapIterator** type. | boolean | Returns **true** if the input value is of the **MapIterator** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); const map = new Map(); @@ -3895,6 +3977,7 @@ Checks whether the input value is of the **Error** type. | boolean | Returns **true** if the input value is of the **Error** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isNativeError(new TypeError()); @@ -3922,6 +4005,7 @@ Checks whether the input value is a number object. | boolean | Returns **true** if the input value is a number object; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isNumberObject(new Number(0)); @@ -3949,6 +4033,7 @@ Checks whether the input value is a promise. | boolean | Returns **true** if the input value is a promise; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isPromise(Promise.resolve(1)); @@ -3976,6 +4061,7 @@ Checks whether the input value is a proxy. | boolean | Returns **true** if the input value is a proxy; returns **false** otherwise.| **Example** + ```js let that = new util.types(); const target = {}; @@ -4005,6 +4091,7 @@ Checks whether the input value is of the **RegExp** type. | boolean | Returns **true** if the input value is of the **RegExp** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isRegExp(new RegExp('abc')); @@ -4032,6 +4119,7 @@ Checks whether the input value is of the **Set** type. | boolean | Returns **true** if the input value is of the **Set** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isSet(new Set()); @@ -4059,6 +4147,7 @@ Checks whether the input value is of the **SetIterator** type. | boolean | Returns **true** if the input value is of the **SetIterator** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); const set = new Set(); @@ -4087,6 +4176,7 @@ Checks whether the input value is a string object. | boolean | Returns **true** if the input value is a string object; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isStringObject(new String('foo')); @@ -4114,6 +4204,7 @@ Checks whether the input value is a symbol object. | boolean | Returns **true** if the input value is a symbol object; returns **false** otherwise.| **Example** + ```js let that = new util.types(); const symbols = Symbol('foo'); @@ -4144,6 +4235,7 @@ Checks whether the input value is of the **TypedArray** type. | boolean | Returns **true** if the input value is of the **TypedArray** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isTypedArray(new Float64Array([])); @@ -4171,6 +4263,7 @@ Checks whether the input value is of the **Uint8Array** type. | boolean | Returns **true** if the input value is of the **Uint8Array** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isUint8Array(new Uint8Array([])); @@ -4198,6 +4291,7 @@ Checks whether the input value is of the **Uint8ClampedArray** type. | boolean | Returns **true** if the input value is of the **Uint8ClampedArray** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isUint8ClampedArray(new Uint8ClampedArray([])); @@ -4225,6 +4319,7 @@ Checks whether the input value is of the **Uint16Array** type. | boolean | Returns **true** if the input value is of the **Uint16Array** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isUint16Array(new Uint16Array([])); @@ -4252,6 +4347,7 @@ Checks whether the input value is of the **Uint32Array** type. | boolean | Returns **true** if the input value is of the **Uint32Array** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isUint32Array(new Uint32Array([])); @@ -4279,6 +4375,7 @@ Checks whether the input value is of the **WeakMap** type. | boolean | Returns **true** if the input value is of the **WeakMap** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isWeakMap(new WeakMap()); @@ -4306,6 +4403,7 @@ Checks whether the input value is of the **WeakSet** type. | boolean | Returns **true** if the input value is of the **WeakSet** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isWeakSet(new WeakSet()); @@ -4333,6 +4431,7 @@ Checks whether the input value is of the **BigInt64Array** type. | boolean | Returns **true** if the input value is of the **BigInt64Array** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isBigInt64Array(new BigInt64Array([])); @@ -4360,6 +4459,7 @@ Checks whether the input value is of the **BigUint64Array** type. | boolean | Returns **true** if the input value is of the **BigUint64Array** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isBigUint64Array(new BigUint64Array([])); @@ -4387,6 +4487,7 @@ Checks whether the input value is a module namespace object. | boolean | Returns **true** if the input value is a module namespace object; returns **false** otherwise.| **Example** + ```js import url from '@ohos.url' let that = new util.types(); @@ -4415,6 +4516,7 @@ Checks whether the input value is of the **SharedArrayBuffer** type. | boolean | Returns **true** if the input value is of the **SharedArrayBuffer** type; returns **false** otherwise.| **Example** + ```js let that = new util.types(); let result = that.isSharedArrayBuffer(new SharedArrayBuffer(0)); diff --git a/en/application-dev/reference/apis/js-apis-vector.md b/en/application-dev/reference/apis/js-apis-vector.md index 57b38f31c7e609fb59e1ff5266713e59d588c247..302b8223c0b720390c82cb28afa921b439fef7fd 100644 --- a/en/application-dev/reference/apis/js-apis-vector.md +++ b/en/application-dev/reference/apis/js-apis-vector.md @@ -1,4 +1,4 @@ -# Linear Container Vector +# @ohos.util.Vector (Linear Container Vector) > **NOTE** > @@ -290,7 +290,7 @@ vector.removeByRange(2,4); ### replaceAllElements -replaceAllElements(callbackfn: (value: T, index?: number, vector?: Vector<T>) => T, +replaceAllElements(callbackFn: (value: T, index?: number, vector?: Vector<T>) => T, thisArg?: Object): void Replaces all elements in this container with new elements, and returns the new ones. @@ -301,7 +301,7 @@ Replaces all elements in this container with new elements, and returns the new o | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked for replacement.| +| callbackFn | function | Yes| Callback invoked for replacement.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -330,7 +330,7 @@ vector.replaceAllElements((value: number, index: number) => { ### forEach -forEach(callbackfn: (value: T, index?: number, vector?: Vector<T>) => void, +forEach(callbackFn: (value: T, index?: number, vector?: Vector<T>) => void, thisArg?: Object): void Uses a callback to traverse the elements in this container and obtain their position indexes. @@ -341,7 +341,7 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked for replacement.| +| callbackFn | function | Yes| Callback invoked for replacement.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn diff --git a/en/application-dev/reference/apis/js-apis-wallpaper.md b/en/application-dev/reference/apis/js-apis-wallpaper.md index b7a9bad454b15ce99e38ff407df3aa4dc5e7b653..371e69dd03b0e5886456a189f9aceeb4444610c0 100644 --- a/en/application-dev/reference/apis/js-apis-wallpaper.md +++ b/en/application-dev/reference/apis/js-apis-wallpaper.md @@ -1,20 +1,19 @@ -# Wallpaper +# @ohos.wallpaper The **wallpaper** module is part of the theme framework and provides the system-level wallpaper management service in OpenHarmony. You can use the APIs of this module to show, set, and switch between wallpapers. > **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. ## Modules to Import -``` +```js import wallpaper from '@ohos.wallpaper'; ``` - ## WallpaperType Enumerates the wallpaper types. @@ -27,15 +26,25 @@ Enumerates the wallpaper types. | WALLPAPER_LOCKSCREEN | 1 |Lock screen wallpaper.| -## wallpaper.getColors +## RgbaColor -getColors(wallpaperType: WallpaperType, callback: AsyncCallback<Array<RgbaColor>>): void +Defines the RGBA color space for the wallpaper. -Obtains the main color information of the wallpaper of the specified type. This API uses an asynchronous callback to return the result. +**System capability**: SystemCapability.MiscServices.Wallpaper -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getColorsSync9+](#wallpapergetcolorssync9) instead. +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| red | number | Yes| Yes| Red color. The value ranges from 0 to 255.| +| green | number | Yes| Yes| Green color. The value ranges from 0 to 255.| +| blue | number | Yes| Yes| Blue color. The value ranges from 0 to 255.| +| alpha | number | Yes| Yes| Alpha value. The value ranges from 0 to 255.| + + +## wallpaper.getColorsSync9+ + +getColorsSync(wallpaperType: WallpaperType): Array<RgbaColor> + +Obtains the main color information of the wallpaper of the specified type. **System capability**: SystemCapability.MiscServices.Wallpaper @@ -44,30 +53,24 @@ Obtains the main color information of the wallpaper of the specified type. This | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| -| callback | AsyncCallback<Array<[RgbaColor](#rgbacolor)>> | Yes| Callback used to return the main color information of the wallpaper.| -**Example** +**Return value** - ```js - wallpaper.getColors(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { - if (error) { - console.error(`failed to getColors because: ` + JSON.stringify(error)); - return; - } - console.log(`success to getColors.`); - }); - ``` +| Type| Description| +| -------- | -------- | +| Array<[RgbaColor](#rgbacolor)> | Promise used to return the main color information of the wallpaper.| +**Example** -## wallpaper.getColors +```js +let colors = wallpaper.getColorsSync(wallpaper.WallpaperType.WALLPAPER_SYSTEM); +``` -getColors(wallpaperType: WallpaperType): Promise<Array<RgbaColor>> +## wallpaper.getIdSync9+ -Obtains the main color information of the wallpaper of the specified type. This API uses a promise to return the result. +getIdSync(wallpaperType: WallpaperType): number -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getColorsSync9+](#wallpapergetcolorssync9) instead. +Obtains the ID of the wallpaper of the specified type. **System capability**: SystemCapability.MiscServices.Wallpaper @@ -81,24 +84,130 @@ Obtains the main color information of the wallpaper of the specified type. This | Type| Description| | -------- | -------- | -| Promise<Array<[RgbaColor](#rgbacolor)>> | Promise used to return the main color information of the wallpaper.| +| number | ID of the wallpaper. If this type of wallpaper is configured, a number greater than or equal to **0** is returned. Otherwise, **-1** is returned. The value ranges from -1 to 2^31-1.| **Example** - ```js - wallpaper.getColors(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { - console.log(`success to getColors.`); - }).catch((error) => { - console.error(`failed to getColors because: ` + JSON.stringify(error)); - }); - ``` +```js +let id = wallpaper.getIdSync(wallpaper.WallpaperType.WALLPAPER_SYSTEM); +``` +## wallpaper.getMinHeightSync9+ -## wallpaper.getColorsSync9+ +getMinHeightSync(): number -getColorsSync(wallpaperType: WallpaperType): Array<RgbaColor> +Obtains the minimum height of this wallpaper. -Obtains the main color information of the wallpaper of the specified type. This API uses an asynchronous callback to return the result. +**System capability**: SystemCapability.MiscServices.Wallpaper + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Promise used to return the minimum wallpaper height, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default height should be used instead.| + +**Example** + +```js +let minHeight = wallpaper.getMinHeightSync(); +``` + +## wallpaper.getMinWidthSync9+ + +getMinWidthSync(): number + +Obtains the minimum width of this wallpaper. + +**System capability**: SystemCapability.MiscServices.Wallpaper + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Promise used to return the minimum wallpaper width, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default width should be used instead.| + +**Example** + +```js +let minWidth = wallpaper.getMinWidthSync(); +``` + +## wallpaper.isChangeAllowed9+ + +isChangeAllowed(): boolean + +Checks whether to allow the application to change the wallpaper for the current user. + +**System capability**: SystemCapability.MiscServices.Wallpaper + +**Return value** + +| Type| Description| +| -------- | -------- | +| boolean | Whether to allow the application to change the wallpaper for the current user. The value **true** means that the operation is allowed, and **false** means the opposite.| + +**Example** + +```js +let isChangeAllowed = wallpaper.isChangeAllowed(); +``` + +## wallpaper.isUserChangeAllowed9+ + +isUserChangeAllowed(): boolean + +Checks whether the user is allowed to set wallpapers. + +**System capability**: SystemCapability.MiscServices.Wallpaper + +**Return value** + +| Type| Description| +| -------- | -------- | +| boolean | Whether the user is allowed to set wallpapers. The value **true** means that the operation is allowed, and **false** means the opposite.| + +**Example** + +```js +let isUserChangeAllowed = wallpaper.isUserChangeAllowed(); +``` + +## wallpaper.restore9+ + +restore(wallpaperType: WallpaperType, callback: AsyncCallback<void>): void + +Resets the wallpaper of the specified type to the default wallpaper. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.SET_WALLPAPER + +**System capability**: SystemCapability.MiscServices.Wallpaper + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is error information.| + +**Example** + +```js +wallpaper.restore(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error) => { + if (error) { + console.error(`failed to restore because: ${JSON.stringify(error)}`); + return; + } + console.log(`success to restore.`); +}); +``` + +## wallpaper.restore9+ + +restore(wallpaperType: WallpaperType): Promise<void> + +Resets the wallpaper of the specified type to the default wallpaper. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.SET_WALLPAPER **System capability**: SystemCapability.MiscServices.Wallpaper @@ -112,24 +221,25 @@ Obtains the main color information of the wallpaper of the specified type. This | Type| Description| | -------- | -------- | -| Array<[RgbaColor](#rgbacolor)> | Promise used to return the main color information of the wallpaper.| +| Promise<void> | Promise that returns no value.| **Example** - ```js - var colors = wallpaper.getColorsSync(wallpaper.WallpaperType.WALLPAPER_SYSTEM); - ``` - +```js +wallpaper.restore(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then(() => { + console.log(`success to restore.`); + }).catch((error) => { + console.error(`failed to restore because: ${JSON.stringify(error)}`); +}); +``` -## wallpaper.getId +## wallpaper.setImage9+ -getId(wallpaperType: WallpaperType, callback: AsyncCallback<number>): void +setImage(source: string | image.PixelMap, wallpaperType: WallpaperType, callback: AsyncCallback<void>): void -Obtains the ID of the wallpaper of the specified type. This API uses an asynchronous callback to return the result. +Sets a specified source as the wallpaper of a specified type. 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 [wallpaper.getIdSync9+](#wallpapergetidsync9) instead. +**Required permissions**: ohos.permission.SET_WALLPAPER **System capability**: SystemCapability.MiscServices.Wallpaper @@ -137,31 +247,52 @@ Obtains the ID of the wallpaper of the specified type. This API uses an asynchro | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | +| source | string \| [image.PixelMap](js-apis-image.md#pixelmap7) | Yes| URI of a JPEG or PNG file, or bitmap of a PNG file.| | wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| -| callback | AsyncCallback<number> | Yes| Callback used to return the wallpaper ID. If the wallpaper of the specified type is configured, a number greater than or equal to **0** is returned. Otherwise, **-1** is returned. The value ranges from -1 to 2^31-1.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is error information.| **Example** - ```js - wallpaper.getId(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { - if (error) { - console.error(`failed to getId because: ` + JSON.stringify(error)); - return; - } - console.log(`success to getId: ` + JSON.stringify(data)); - }); - ``` - +```js +//The source type is string. +let wallpaperPath = "/data/data/ohos.acts.aafwk.plrdtest.form/files/Cup_ic.jpg"; +wallpaper.setImage(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error) => { + if (error) { + console.error(`failed to setImage because: ${JSON.stringify(error)}`); + return; + } + console.log(`success to setImage.`); +}); + +// The source type is image.PixelMap. +import image from '@ohos.multimedia.image'; +let imageSource = image.createImageSource("file://" + wallpaperPath); +let opts = { + "desiredSize": { + "height": 3648, + "width": 2736 + } +}; +imageSource.createPixelMap(opts).then((pixelMap) => { + wallpaper.setImage(pixelMap, wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error) => { + if (error) { + console.error(`failed to setImage because: ${JSON.stringify(error)}`); + return; + } + console.log(`success to setImage.`); + }); +}).catch((error) => { + console.error(`failed to createPixelMap because: ${JSON.stringify(error)}`); +}); +``` -## wallpaper.getId +## wallpaper.setImage9+ -getId(wallpaperType: WallpaperType): Promise<number> +setImage(source: string | image.PixelMap, wallpaperType: WallpaperType): Promise<void> -Obtains the ID of the wallpaper of the specified type. This API uses a promise to return the result. +Sets a specified source as the wallpaper of a specified type. 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 [wallpaper.getIdSync9+](#wallpapergetidsync9) instead. +**Required permissions**: ohos.permission.SET_WALLPAPER **System capability**: SystemCapability.MiscServices.Wallpaper @@ -169,30 +300,53 @@ Obtains the ID of the wallpaper of the specified type. This API uses a promise t | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | +| source | string \| [image.PixelMap](js-apis-image.md#pixelmap7) | Yes| URI of a JPEG or PNG file, or bitmap of a PNG file.| | wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| **Return value** | Type| Description| | -------- | -------- | -| Promise<number> | Promise used to return the wallpaper ID. If this type of wallpaper is configured, a number greater than or equal to **0** is returned. Otherwise, **-1** is returned. The value ranges from -1 to 2^31-1.| +| Promise<void> | Promise that returns no value.| **Example** - ```js - wallpaper.getId(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { - console.log(`success to getId: ` + JSON.stringify(data)); - }).catch((error) => { - console.error(`failed to getId because: ` + JSON.stringify(error)); - }); - ``` +```js +//The source type is string. +let wallpaperPath = "/data/data/ohos.acts.aafwk.plrdtest.form/files/Cup_ic.jpg"; +wallpaper.setImage(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM).then(() => { + console.log(`success to setImage.`); +}).catch((error) => { + console.error(`failed to setImage because: ${JSON.stringify(error)}`); +}); + +// The source type is image.PixelMap. +import image from '@ohos.multimedia.image'; +let imageSource = image.createImageSource("file://" + wallpaperPath); +let opts = { + "desiredSize": { + "height": 3648, + "width": 2736 + } +}; +imageSource.createPixelMap(opts).then((pixelMap) => { + wallpaper.setImage(pixelMap, wallpaper.WallpaperType.WALLPAPER_SYSTEM).then(() => { + console.log(`success to setImage.`); + }).catch((error) => { + console.error(`failed to setImage because: ${JSON.stringify(error)}`); + }); +}).catch((error) => { + console.error(`failed to createPixelMap because: ${JSON.stringify(error)}`); +}); +``` +## wallpaper.getFileSync9+ -## wallpaper.getIdSync9+ +getFileSync(wallpaperType: WallpaperType): number; -getIdSync(wallpaperType: WallpaperType): number +Obtains the wallpaper of the specified type. -Obtains the ID of the wallpaper of the specified type. This API uses an asynchronous callback to return the result. +**Required permissions**: ohos.permission.GET_WALLPAPER **System capability**: SystemCapability.MiscServices.Wallpaper @@ -206,105 +360,109 @@ Obtains the ID of the wallpaper of the specified type. This API uses an asynchro | Type| Description| | -------- | -------- | -| number | ID of the wallpaper. If this type of wallpaper is configured, a number greater than or equal to **0** is returned. Otherwise, **-1** is returned. The value ranges from -1 to 2^31-1.| +| number | Promise used to return the result. If the operation is successful, the file descriptor ID to the wallpaper is returned. Otherwise, error information is returned.| **Example** - ```js - var id = wallpaper.getIdSync(wallpaper.WallpaperType.WALLPAPER_SYSTEM); - ``` - +```js +let file = wallpaper.getFileSync(wallpaper.WallpaperType.WALLPAPER_SYSTEM); +``` -## wallpaper.getMinHeight +## wallpaper.getImage9+ -getMinHeight(callback: AsyncCallback<number>): void +getImage(wallpaperType: WallpaperType, callback: AsyncCallback<image.PixelMap>): void; -Obtains the minimum height of this wallpaper. This API uses an asynchronous callback to return the result. +Obtains the pixel map for the wallpaper of the specified type. 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 [wallpaper.getMinHeightSync9+](#wallpapergetminheightsync9) instead. +**Required permissions**: ohos.permission.GET_WALLPAPER **System capability**: SystemCapability.MiscServices.Wallpaper +**System API**: This is a system API. + **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<number> | Yes| Callback used to return the minimum wallpaper height, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default height should be used instead.| +| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| +| callback | AsyncCallback<[image.PixelMap](js-apis-image.md#pixelmap7)> | Yes| Callback used to return the result. Returns the pixel map size of the wallpaper if the operation is successful; returns an error message otherwise.| **Example** - ```js - wallpaper.getMinHeight((error, data) => { - if (error) { - console.error(`failed to getMinHeight because: ` + JSON.stringify(error)); - return; - } - console.log(`success to getMinHeight: ` + JSON.stringify(data)); - }); - ``` +```js +wallpaper.getImage(wallpaper.WallpaperType.WALLPAPER_SYSTEM, function (error, data) { + if (error) { + console.error(`failed to getImage because: ${JSON.stringify(error)}`); + return; + } + console.log(`success to getImage: ${JSON.stringify(data)}`); +}); +``` -## wallpaper.getMinHeight +## wallpaper.getImage9+ -getMinHeight(): Promise<number> +getImage(wallpaperType: WallpaperType): Promise<image.PixelMap> -Obtains the minimum height of this wallpaper. This API uses a promise to return the result. +Obtains the pixel map for the wallpaper of the specified type. 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 [wallpaper.getMinHeightSync9+](#wallpapergetminheightsync9) instead. +**Required permissions**: ohos.permission.GET_WALLPAPER **System capability**: SystemCapability.MiscServices.Wallpaper +**System API**: This is a system API. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| + **Return value** | Type| Description| | -------- | -------- | -| Promise<number> | Promise used to return the minimum wallpaper height, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default height should be used instead.| +| Promise<[image.PixelMap](js-apis-image.md#pixelmap7)> | Promise used to return the result. Returns the pixel map size of the wallpaper if the operation is successful; returns an error message otherwise.| **Example** - ```js - wallpaper.getMinHeight().then((data) => { - console.log(`success to getMinHeight: ` + JSON.stringify(data)); +```js +wallpaper.getImage(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { + console.log(`success to getImage: ${JSON.stringify(data)}`); }).catch((error) => { - console.error(`failed to getMinHeight because: ` + JSON.stringify(error)); - }); - ``` - + console.error(`failed to getImage because: ${JSON.stringify(error)}`); +}); +``` -## wallpaper.getMinHeightSync9+ +## wallpaper.on('colorChange')9+ -getMinHeightSync(): number +on(type: 'colorChange', callback: (colors: Array<RgbaColor>, wallpaperType: WallpaperType) => void): void -Obtains the minimum height of this wallpaper. This API uses an asynchronous callback to return the result. +Subscribes to the wallpaper color change event. **System capability**: SystemCapability.MiscServices.Wallpaper -**Return value** +**Parameters** -| Type| Description| -| -------- | -------- | -| number | Promise used to return the minimum wallpaper height, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default height should be used instead.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to subscribe to. The value **'colorChange'** indicates subscribing to the wallpaper color change event.| +| callback | function | Yes| Callback triggered when the wallpaper color changes. The wallpaper type and main colors are returned.
- colors
Main color information of the wallpaper. For details, see [RgbaColor](#rgbacolor).
- wallpaperType
Wallpaper type.| **Example** - ```js - var minHeight = wallpaper.getMinHeightSync(); - ``` - - -## wallpaper.getMinWidth +```js +let listener = (colors, wallpaperType) => { + console.log(`wallpaper color changed.`); +}; +wallpaper.on('colorChange', listener); +``` -getMinWidth(callback: AsyncCallback<number>): void +## wallpaper.off('colorChange')9+ -Obtains the minimum width of this wallpaper. This API uses an asynchronous callback to return the result. +off(type: 'colorChange', callback?: (colors: Array<RgbaColor>, wallpaperType: WallpaperType) => void): void -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getMinWidthSync9+](#wallpapergetminwidthsync9) instead. +Unsubscribes from the wallpaper color change event. **System capability**: SystemCapability.MiscServices.Wallpaper @@ -312,80 +470,96 @@ Obtains the minimum width of this wallpaper. This API uses an asynchronous callb | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<number> | Yes| Callback used to return the minimum wallpaper width, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default width should be used instead.| +| type | string | Yes| Type of the event to unsubscribe from. The value **'colorChange'** indicates unsubscribing from the wallpaper color change event.| +| callback | function | No| Callback for the wallpaper color change event. If this parameter is not set, this API unsubscribes from all callbacks corresponding to **type**.
- colors
Main color information of the wallpaper. For details, see [RgbaColor](#rgbacolor).
- wallpaperType
Wallpaper type.| **Example** - ```js - wallpaper.getMinWidth((error, data) => { - if (error) { - console.error(`failed to getMinWidth because: ` + JSON.stringify(error)); - return; - } - console.log(`success to getMinWidth: ` + JSON.stringify(data)); - }); - ``` - +```js +let listener = (colors, wallpaperType) => { + console.log(`wallpaper color changed.`); +}; +wallpaper.on('colorChange', listener); +// Unsubscribe from the listener. +wallpaper.off('colorChange', listener); +// Unsubscribe from all subscriptions of the colorChange type. +wallpaper.off('colorChange'); +``` -## wallpaper.getMinWidth +## wallpaper.getColors(deprecated) -getMinWidth(): Promise<number> +getColors(wallpaperType: WallpaperType, callback: AsyncCallback<Array<RgbaColor>>): void -Obtains the minimum width of this wallpaper. This API uses a promise to return the result. +Obtains the main color information of the wallpaper of the specified type. 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 [wallpaper.getMinWidthSync9+](#wallpapergetminwidthsync9) instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getColorsSync9+](#wallpapergetcolorssync9) instead. **System capability**: SystemCapability.MiscServices.Wallpaper -**Return value** +**Parameters** -| Type| Description| -| -------- | -------- | -| Promise<number> | Promise used to return the minimum wallpaper width, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default width should be used instead.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| +| callback | AsyncCallback<Array<[RgbaColor](#rgbacolor)>> | Yes| Callback used to return the main color information of the wallpaper.| **Example** - ```js - wallpaper.getMinWidth().then((data) => { - console.log(`success to getMinWidth: ` + JSON.stringify(data)); - }).catch((error) => { - console.error(`failed to getMinWidth because: ` + JSON.stringify(error)); - }); - ``` +```js +wallpaper.getColors(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { + if (error) { + console.error(`failed to getColors because: ${JSON.stringify(error)}`); + return; + } + console.log(`success to getColors: ${JSON.stringify(data)}`); +}); +``` +## wallpaper.getColors(deprecated) -## wallpaper.getMinWidthSync9+ +getColors(wallpaperType: WallpaperType): Promise<Array<RgbaColor>> -getMinWidthSync(): number +Obtains the main color information of the wallpaper of the specified type. This API uses a promise to return the result. -Obtains the minimum width of this wallpaper. 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 [wallpaper.getColorsSync9+](#wallpapergetcolorssync9) instead. **System capability**: SystemCapability.MiscServices.Wallpaper +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| + **Return value** | Type| Description| | -------- | -------- | -| number | Promise used to return the minimum wallpaper width, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default width should be used instead.| +| Promise<Array<[RgbaColor](#rgbacolor)>> | Promise used to return the main color information of the wallpaper.| **Example** - ```js - var minWidth = wallpaper.getMinWidthSync(); - ``` - +```js +wallpaper.getColors(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { + console.log(`success to getColors: ${JSON.stringify(data)}`); + }).catch((error) => { + console.error(`failed to getColors because: ${JSON.stringify(error)}`); +}); +``` -## wallpaper.isChangePermitted +## wallpaper.getId(deprecated) -isChangePermitted(callback: AsyncCallback<boolean>): void +getId(wallpaperType: WallpaperType, callback: AsyncCallback<number>): void -Checks whether to allow the application to change the wallpaper for the current user. This API uses an asynchronous callback to return the result. +Obtains the ID of the wallpaper of the specified type. 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 [wallpaper.isChangeAllowed9+](#wallpaperischangeallowed9) instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getIdSync9+](#wallpapergetidsync9) instead. **System capability**: SystemCapability.MiscServices.Wallpaper @@ -393,136 +567,152 @@ Checks whether to allow the application to change the wallpaper for the current | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<boolean> | Yes| Callback used to return whether to allow the application to change the wallpaper for the current user. The value **true** means that the operation is allowed, and **false** means the opposite.| +| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| +| callback | AsyncCallback<number> | Yes| Callback used to return the wallpaper ID. If the wallpaper of the specified type is configured, a number greater than or equal to **0** is returned. Otherwise, **-1** is returned. The value ranges from -1 to 2^31-1.| **Example** - ```js - wallpaper.isChangePermitted((error, data) => { - if (error) { - console.error(`failed to isChangePermitted because: ` + JSON.stringify(error)); - return; - } - console.log(`success to isChangePermitted: ` + JSON.stringify(data)); - }); - ``` - +```js +wallpaper.getId(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { + if (error) { + console.error(`failed to getId because: ${JSON.stringify(error)}`); + return; + } + console.log(`success to getId: ${JSON.stringify(data)}`); +}); +``` -## wallpaper.isChangePermitted +## wallpaper.getId(deprecated) -isChangePermitted(): Promise<boolean> +getId(wallpaperType: WallpaperType): Promise<number> -Checks whether to allow the application to change the wallpaper for the current user. This API uses a promise to return the result. +Obtains the ID of the wallpaper of the specified type. 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 [wallpaper.isChangeAllowed9+](#wallpaperischangeallowed9) instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getIdSync9+](#wallpapergetidsync9) instead. **System capability**: SystemCapability.MiscServices.Wallpaper +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| + **Return value** | Type| Description| | -------- | -------- | -| Promise<boolean> | Promise used to return whether to allow the application to change the wallpaper for the current user. The value **true** means that the operation is allowed, and **false** means the opposite.| +| Promise<number> | Promise used to return the wallpaper ID. If this type of wallpaper is configured, a number greater than or equal to **0** is returned. Otherwise, **-1** is returned. The value ranges from -1 to 2^31-1.| **Example** - ```js - wallpaper.isChangePermitted().then((data) => { - console.log(`success to isChangePermitted: ` + JSON.stringify(data)); +```js +wallpaper.getId(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { + console.log(`success to getId: ${JSON.stringify(data)}`); }).catch((error) => { - console.error(`failed to isChangePermitted because: ` + JSON.stringify(error)); - }); - ``` + console.error(`failed to getId because: ${JSON.stringify(error)}`); +}); +``` +## wallpaper.getMinHeight(deprecated) -## wallpaper.isChangeAllowed9+ +getMinHeight(callback: AsyncCallback<number>): void -isChangeAllowed(): boolean +Obtains the minimum height of this wallpaper. This API uses an asynchronous callback to return the result. -Checks whether to allow the application to change the wallpaper for the current user. 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 [wallpaper.getMinHeightSync9+](#wallpapergetminheightsync9) instead. **System capability**: SystemCapability.MiscServices.Wallpaper -**Return value** +**Parameters** -| Type| Description| -| -------- | -------- | -| boolean | Whether to allow the application to change the wallpaper for the current user. The value **true** means that the operation is allowed, and **false** means the opposite.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<number> | Yes| Callback used to return the minimum wallpaper height, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default height should be used instead.| **Example** - ```js - var isChangeAllowed = wallpaper.isChangeAllowed(); - ``` - +```js +wallpaper.getMinHeight((error, data) => { + if (error) { + console.error(`failed to getMinHeight because: ${JSON.stringify(error)}`); + return; + } + console.log(`success to getMinHeight: ${JSON.stringify(data)}`); +}); +``` -## wallpaper.isOperationAllowed +## wallpaper.getMinHeight(deprecated) -isOperationAllowed(callback: AsyncCallback<boolean>): void +getMinHeight(): Promise<number> -Checks whether the user is allowed to set wallpapers. This API uses an asynchronous callback to return the result. +Obtains the minimum height of this wallpaper. 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 [wallpaper.isUserChangeAllowed9+](#wallpaperisuserchangeallowed9) instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getMinHeightSync9+](#wallpapergetminheightsync9) instead. **System capability**: SystemCapability.MiscServices.Wallpaper -**Parameters** +**Return value** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<boolean> | Yes| Callback used to return whether the user is allowed to set wallpapers. The value **true** means that the operation is allowed, and **false** means the opposite.| +| Type| Description| +| -------- | -------- | +| Promise<number> | Promise used to return the minimum wallpaper height, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default height should be used instead.| **Example** - ```js - wallpaper.isOperationAllowed((error, data) => { - if (error) { - console.error(`failed to isOperationAllowed because: ` + JSON.stringify(error)); - return; - } - console.log(`success to isOperationAllowed: ` + JSON.stringify(data)); - }); - ``` - +```js +wallpaper.getMinHeight().then((data) => { + console.log(`success to getMinHeight: ${JSON.stringify(data)}`); +}).catch((error) => { + console.error(`failed to getMinHeight because: ${JSON.stringify(error)}`); +}); +``` -## wallpaper.isOperationAllowed +## wallpaper.getMinWidth(deprecated) -isOperationAllowed(): Promise<boolean> +getMinWidth(callback: AsyncCallback<number>): void -Checks whether the user is allowed to set wallpapers. This API uses a promise to return the result. +Obtains the minimum width of this wallpaper. 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 [wallpaper.isUserChangeAllowed9+](#wallpaperisuserchangeallowed9) instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getMinWidthSync9+](#wallpapergetminwidthsync9) instead. **System capability**: SystemCapability.MiscServices.Wallpaper -**Return value** +**Parameters** -| Type| Description| -| -------- | -------- | -| Promise<boolean> | Promise used to return whether the user is allowed to set wallpapers. The value **true** means that the operation is allowed, and **false** means the opposite.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<number> | Yes| Callback used to return the minimum wallpaper width, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default width should be used instead.| **Example** - ```js - wallpaper.isOperationAllowed().then((data) => { - console.log(`success to isOperationAllowed: ` + JSON.stringify(data)); - }).catch((error) => { - console.error(`failed to isOperationAllowed because: ` + JSON.stringify(error)); - }); - ``` +```js +wallpaper.getMinWidth((error, data) => { + if (error) { + console.error(`failed to getMinWidth because: ${JSON.stringify(error)}`); + return; + } + console.log(`success to getMinWidth: ${JSON.stringify(data)}`); +}); +``` +## wallpaper.getMinWidth(deprecated) -## wallpaper.isUserChangeAllowed9+ +getMinWidth(): Promise<number> -isUserChangeAllowed(): boolean +Obtains the minimum width of this wallpaper. This API uses a promise to return the result. -Checks whether the user is allowed to set wallpapers. 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 [wallpaper.getMinWidthSync9+](#wallpapergetminwidthsync9) instead. **System capability**: SystemCapability.MiscServices.Wallpaper @@ -530,26 +720,27 @@ Checks whether the user is allowed to set wallpapers. This API uses an asynchron | Type| Description| | -------- | -------- | -| boolean | Whether the user is allowed to set wallpapers. The value **true** means that the operation is allowed, and **false** means the opposite.| +| Promise<number> | Promise used to return the minimum wallpaper width, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default width should be used instead.| **Example** - ```js - var isUserChangeAllowed = wallpaper.isUserChangeAllowed(); - ``` - +```js +wallpaper.getMinWidth().then((data) => { + console.log(`success to getMinWidth: ${JSON.stringify(data)}`); + }).catch((error) => { + console.error(`failed to getMinWidth because: ${JSON.stringify(error)}`); +}); +``` -## wallpaper.reset +## wallpaper.isChangePermitted(deprecated) -reset(wallpaperType: WallpaperType, callback: AsyncCallback<void>): void +isChangePermitted(callback: AsyncCallback<boolean>): void -Resets the wallpaper of the specified type to the default wallpaper. This API uses an asynchronous callback to return the result. +Checks whether to allow the application to change the wallpaper for the current user. 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 [wallpaper.restore9+](#wallpaperrestore9) instead. - -**Required permissions**: ohos.permission.SET_WALLPAPER +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.isChangeAllowed9+](#wallpaperischangeallowed9) instead. **System capability**: SystemCapability.MiscServices.Wallpaper @@ -557,66 +748,57 @@ Resets the wallpaper of the specified type to the default wallpaper. This API us | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, the result of removal is returned. Otherwise, error information is returned.| +| callback | AsyncCallback<boolean> | Yes| Callback used to return whether to allow the application to change the wallpaper for the current user. The value **true** means that the operation is allowed, and **false** means the opposite.| **Example** - ```js - wallpaper.reset(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { - if (error) { - console.error(`failed to reset because: ` + JSON.stringify(error)); - return; - } - console.log(`success to reset.`); - }); - ``` - +```js +wallpaper.isChangePermitted((error, data) => { + if (error) { + console.error(`failed to isChangePermitted because: ${JSON.stringify(error)}`); + return; + } + console.log(`success to isChangePermitted: ${JSON.stringify(data)}`); +}); +``` -## wallpaper.reset +## wallpaper.isChangePermitted(deprecated) -reset(wallpaperType: WallpaperType): Promise<void> +isChangePermitted(): Promise<boolean> -Resets the wallpaper of the specified type to the default wallpaper. This API uses a promise to return the result. +Checks whether to allow the application to change the wallpaper for the current user. 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 [wallpaper.restore9+](#wallpaperrestore9) instead. - -**Required permissions**: ohos.permission.SET_WALLPAPER +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.isChangeAllowed9+](#wallpaperischangeallowed9) instead. **System capability**: SystemCapability.MiscServices.Wallpaper -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| - **Return value** | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result. If the operation is successful, the result is returned. Otherwise, error information is returned.| +| Promise<boolean> | Promise used to return whether to allow the application to change the wallpaper for the current user. The value **true** means that the operation is allowed, and **false** means the opposite.| **Example** - ```js - wallpaper.reset(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { - console.log(`success to reset.`); - }).catch((error) => { - console.error(`failed to reset because: ` + JSON.stringify(error)); - }); - ``` - +```js +wallpaper.isChangePermitted().then((data) => { + console.log(`success to isChangePermitted: ${JSON.stringify(data)}`); +}).catch((error) => { + console.error(`failed to isChangePermitted because: ${JSON.stringify(error)}`); +}); +``` -## wallpaper.restore9+ +## wallpaper.isOperationAllowed(deprecated) -restore(wallpaperType: WallpaperType, callback: AsyncCallback<void>): void +isOperationAllowed(callback: AsyncCallback<boolean>): void -Resets the wallpaper of the specified type to the default wallpaper. This API uses an asynchronous callback to return the result. +Checks whether the user is allowed to set wallpapers. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.SET_WALLPAPER +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.isUserChangeAllowed9+](#wallpaperisuserchangeallowed9) instead. **System capability**: SystemCapability.MiscServices.Wallpaper @@ -624,64 +806,57 @@ Resets the wallpaper of the specified type to the default wallpaper. This API us | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, the result of removal is returned. Otherwise, error information is returned.| +| callback | AsyncCallback<boolean> | Yes| Callback used to return whether the user is allowed to set wallpapers. The value **true** means that the operation is allowed, and **false** means the opposite.| **Example** - ```js - wallpaper.restore(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { - if (error) { - console.error(`failed to restore because: ` + JSON.stringify(error)); - return; - } - console.log(`success to restore.`); - }); - ``` - +```js +wallpaper.isOperationAllowed((error, data) => { + if (error) { + console.error(`failed to isOperationAllowed because: ${JSON.stringify(error)}`); + return; + } + console.log(`success to isOperationAllowed: ${JSON.stringify(data)}`); +}); +``` -## wallpaper.restore9+ +## wallpaper.isOperationAllowed(deprecated) -restore(wallpaperType: WallpaperType): Promise<void> +isOperationAllowed(): Promise<boolean> -Resets the wallpaper of the specified type to the default wallpaper. This API uses an asynchronous callback to return the result. +Checks whether the user is allowed to set wallpapers. This API uses a promise to return the result. -**Required permissions**: ohos.permission.SET_WALLPAPER +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.isUserChangeAllowed9+](#wallpaperisuserchangeallowed9) instead. **System capability**: SystemCapability.MiscServices.Wallpaper -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| - **Return value** | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result. If the operation is successful, the result is returned. Otherwise, error information is returned.| +| Promise<boolean> | Promise used to return whether the user is allowed to set wallpapers. The value **true** means that the operation is allowed, and **false** means the opposite.| **Example** - ```js - wallpaper.restore(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { - console.log(`success to restore.`); +```js +wallpaper.isOperationAllowed().then((data) => { + console.log(`success to isOperationAllowed: ${JSON.stringify(data)}`); }).catch((error) => { - console.error(`failed to restore because: ` + JSON.stringify(error)); - }); - ``` - + console.error(`failed to isOperationAllowed because: ${JSON.stringify(error)}`); +}); +``` -## wallpaper.setWallpaper +## wallpaper.reset(deprecated) -setWallpaper(source: string | image.PixelMap, wallpaperType: WallpaperType, callback: AsyncCallback<void>): void +reset(wallpaperType: WallpaperType, callback: AsyncCallback<void>): void -Sets a specified source as the wallpaper of a specified type. This API uses an asynchronous callback to return the result. +Resets the wallpaper of the specified type to the default wallpaper. 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 [wallpaper.setImage9+](#wallpapersetimage9) instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.restore9+](#wallpaperrestore9) instead. **Required permissions**: ohos.permission.SET_WALLPAPER @@ -691,55 +866,30 @@ Sets a specified source as the wallpaper of a specified type. This API uses an a | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| source | string \|[image.PixelMap](js-apis-image.md#pixelmap7) | Yes| URI of a JPEG or PNG file, or bitmap of a PNG file.| | wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, the setting result is returned. Otherwise, error information is returned.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is error information.| **Example** - ```js - //The source type is string. - let wallpaperPath = "/data/data/ohos.acts.aafwk.plrdtest.form/files/Cup_ic.jpg"; - wallpaper.setWallpaper(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { - if (error) { - console.error(`failed to setWallpaper because: ` + JSON.stringify(error)); - return; - } - console.log(`success to setWallpaper.`); - }); - - // The source type is image.PixelMap. - import image from '@ohos.multimedia.image'; - let imageSource = image.createImageSource("file://" + wallpaperPath); - let opts = { - "desiredSize": { - "height": 3648, - "width": 2736 - } - }; - imageSource.createPixelMap(opts).then((pixelMap) => { - wallpaper.setWallpaper(pixelMap, wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { - if (error) { - console.error(`failed to setWallpaper because: ` + JSON.stringify(error)); - return; - } - console.log(`success to setWallpaper.`); - }); - }).catch((error) => { - console.error(`failed to createPixelMap because: ` + JSON.stringify(error)); - }); - ``` - +```js +wallpaper.reset(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error) => { + if (error) { + console.error(`failed to reset because: ${JSON.stringify(error)}`); + return; + } + console.log(`success to reset.`); +}); +``` -## wallpaper.setWallpaper +## wallpaper.reset(deprecated) -setWallpaper(source: string | image.PixelMap, wallpaperType: WallpaperType): Promise<void> +reset(wallpaperType: WallpaperType): Promise<void> -Sets a specified source as the wallpaper of a specified type. This API uses a promise to return the result. +Resets the wallpaper of the specified type to the default wallpaper. 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 [wallpaper.setImage9+](#wallpapersetimage9) instead. +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.restore9+](#wallpaperrestore9) instead. **Required permissions**: ohos.permission.SET_WALLPAPER @@ -749,53 +899,34 @@ Sets a specified source as the wallpaper of a specified type. This API uses a pr | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| source | string \|[image.PixelMap](js-apis-image.md#pixelmap7) | Yes| URI of a JPEG or PNG file, or bitmap of a PNG file.| | wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| **Return value** | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result. If the operation is successful, the setting result is returned. Otherwise, error information is returned.| +| Promise<void> | Promise that returns no value.| **Example** - ```js - //The source type is string. - let wallpaperPath = "/data/data/ohos.acts.aafwk.plrdtest.form/files/Cup_ic.jpg"; - wallpaper.setWallpaper(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { - console.log(`success to setWallpaper.`); - }).catch((error) => { - console.error(`failed to setWallpaper because: ` + JSON.stringify(error)); - }); - - // The source type is image.PixelMap. - import image from '@ohos.multimedia.image'; - let imageSource = image.createImageSource("file://" + wallpaperPath); - let opts = { - "desiredSize": { - "height": 3648, - "width": 2736 - } - }; - imageSource.createPixelMap(opts).then((pixelMap) => { - wallpaper.setWallpaper(pixelMap, wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { - console.log(`success to setWallpaper.`); - }).catch((error) => { - console.error(`failed to setWallpaper because: ` + JSON.stringify(error)); - }); - }).catch((error) => { - console.error(`failed to createPixelMap because: ` + JSON.stringify(error)); - }); - ``` - +```js +wallpaper.reset(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then(() => { + console.log(`success to reset.`); +}).catch((error) => { + console.error(`failed to reset because: ${JSON.stringify(error)}`); +}); +``` -## wallpaper.setImage9+ +## wallpaper.setWallpaper(deprecated) -setImage(source: string | image.PixelMap, wallpaperType: WallpaperType, callback: AsyncCallback<void>): void +setWallpaper(source: string | image.PixelMap, wallpaperType: WallpaperType, callback: AsyncCallback<void>): void Sets a specified source as the wallpaper of a specified type. 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 [wallpaper.setImage9+](#wallpapersetimage9) instead. + **Required permissions**: ohos.permission.SET_WALLPAPER **System capability**: SystemCapability.MiscServices.Wallpaper @@ -804,51 +935,54 @@ Sets a specified source as the wallpaper of a specified type. This API uses an a | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| source | string \|[image.PixelMap](js-apis-image.md#pixelmap7) | Yes| URI of a JPEG or PNG file, or bitmap of a PNG file.| +| source | string \| [image.PixelMap](js-apis-image.md#pixelmap7) | Yes| URI of a JPEG or PNG file, or bitmap of a PNG file.| | wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, the setting result is returned. Otherwise, error information is returned.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is error information.| **Example** - ```js - //The source type is string. - let wallpaperPath = "/data/data/ohos.acts.aafwk.plrdtest.form/files/Cup_ic.jpg"; - wallpaper.setImage(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { - if (error) { - console.error(`failed to setImage because: ` + JSON.stringify(error)); - return; - } - console.log(`success to setImage.`); - }); - - // The source type is image.PixelMap. - import image from '@ohos.multimedia.image'; - let imageSource = image.createImageSource("file://" + wallpaperPath); - let opts = { - "desiredSize": { - "height": 3648, - "width": 2736 - } - }; - imageSource.createPixelMap(opts).then((pixelMap) => { - wallpaper.setImage(pixelMap, wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { - if (error) { - console.error(`failed to setImage because: ` + JSON.stringify(error)); - return; - } - console.log(`success to setImage.`); - }); - }).catch((error) => { - console.error(`failed to createPixelMap because: ` + JSON.stringify(error)); - }); - ``` +```js +//The source type is string. +let wallpaperPath = "/data/data/ohos.acts.aafwk.plrdtest.form/files/Cup_ic.jpg"; +wallpaper.setWallpaper(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error) => { + if (error) { + console.error(`failed to setWallpaper because: ${JSON.stringify(error)}`); + return; + } + console.log(`success to setWallpaper.`); +}); + +// The source type is image.PixelMap. +import image from '@ohos.multimedia.image'; +let imageSource = image.createImageSource("file://" + wallpaperPath); +let opts = { + "desiredSize": { + "height": 3648, + "width": 2736 + } +}; +imageSource.createPixelMap(opts).then((pixelMap) => { + wallpaper.setWallpaper(pixelMap, wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error) => { + if (error) { + console.error(`failed to setWallpaper because: ${JSON.stringify(error)}`); + return; + } + console.log(`success to setWallpaper.`); + }); +}).catch((error) => { + console.error(`failed to createPixelMap because: ${JSON.stringify(error)}`); +}); +``` +## wallpaper.setWallpaper(deprecated) -## wallpaper.setImage9+ +setWallpaper(source: string | image.PixelMap, wallpaperType: WallpaperType): Promise<void> -setImage(source: string | image.PixelMap, wallpaperType: WallpaperType): Promise<void> +Sets a specified source as the wallpaper of a specified type. This API uses a promise to return the result. -Sets a specified source as the wallpaper of a specified type. 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 [wallpaper.setImage9+](#wallpapersetimage9) instead. **Required permissions**: ohos.permission.SET_WALLPAPER @@ -858,48 +992,48 @@ Sets a specified source as the wallpaper of a specified type. This API uses an a | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| source | string \|[image.PixelMap](js-apis-image.md#pixelmap7) | Yes| URI of a JPEG or PNG file, or bitmap of a PNG file.| +| source | string \| [image.PixelMap](js-apis-image.md#pixelmap7) | Yes| URI of a JPEG or PNG file, or bitmap of a PNG file.| | wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| **Return value** | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result. If the operation is successful, the setting result is returned. Otherwise, error information is returned.| +| Promise<void> | Promise that returns no value.| **Example** - ```js - //The source type is string. - let wallpaperPath = "/data/data/ohos.acts.aafwk.plrdtest.form/files/Cup_ic.jpg"; - wallpaper.setImage(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { - console.log(`success to setImage.`); +```js +//The source type is string. +let wallpaperPath = "/data/data/ohos.acts.aafwk.plrdtest.form/files/Cup_ic.jpg"; +wallpaper.setWallpaper(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM).then(() => { + console.log(`success to setWallpaper.`); }).catch((error) => { - console.error(`failed to setImage because: ` + JSON.stringify(error)); - }); + console.error(`failed to setWallpaper because: ${JSON.stringify(error)}`); +}); - // The source type is image.PixelMap. - import image from '@ohos.multimedia.image'; - let imageSource = image.createImageSource("file://" + wallpaperPath); - let opts = { - "desiredSize": { - "height": 3648, - "width": 2736 - } - }; - imageSource.createPixelMap(opts).then((pixelMap) => { - wallpaper.setImage(pixelMap, wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { - console.log(`success to setImage.`); - }).catch((error) => { - console.error(`failed to setImage because: ` + JSON.stringify(error)); - }); - }).catch((error) => { - console.error(`failed to createPixelMap because: ` + JSON.stringify(error)); - }); - ``` +// The source type is image.PixelMap. +import image from '@ohos.multimedia.image'; +let imageSource = image.createImageSource("file://" + wallpaperPath); +let opts = { + "desiredSize": { + "height": 3648, + "width": 2736 + } +}; +imageSource.createPixelMap(opts).then((pixelMap) => { + wallpaper.setWallpaper(pixelMap, wallpaper.WallpaperType.WALLPAPER_SYSTEM).then(() => { + console.log(`success to setWallpaper.`); + }).catch((error) => { + console.error(`failed to setWallpaper because: ${JSON.stringify(error)}`); + }); + }).catch((error) => { + console.error(`failed to createPixelMap because: ${JSON.stringify(error)}`); +}); +``` -## wallpaper.getFile8+ +## wallpaper.getFile(deprecated) getFile(wallpaperType: WallpaperType, callback: AsyncCallback<number>): void @@ -922,17 +1056,17 @@ Obtains the wallpaper of the specified type. This API uses an asynchronous callb **Example** - ```js - wallpaper.getFile(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { - if (error) { - console.error(`failed to getFile because: ` + JSON.stringify(error)); - return; - } - console.log(`success to getFile: ` + JSON.stringify(data)); - }); - ``` +```js +wallpaper.getFile(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { + if (error) { + console.error(`failed to getFile because: ${JSON.stringify(error)}`); + return; + } + console.log(`success to getFile: ${JSON.stringify(data)}`); +}); +``` -## wallpaper.getFile8+ +## wallpaper.getFile(deprecated) getFile(wallpaperType: WallpaperType): Promise<number> @@ -960,45 +1094,15 @@ Obtains the wallpaper of the specified type. This API uses a promise to return t **Example** - ```js - wallpaper.getFile(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { - console.log(`success to getFile: ` + JSON.stringify(data)); +```js +wallpaper.getFile(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { + console.log(`success to getFile: ${JSON.stringify(data)}`); }).catch((error) => { - console.error(`failed to getFile because: ` + JSON.stringify(error)); - }); - ``` - - -## wallpaper.getFileSync9+ - -getFileSync(wallpaperType: WallpaperType): number; - -Obtains the wallpaper of the specified type. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.GET_WALLPAPER - -**System capability**: SystemCapability.MiscServices.Wallpaper - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| number | Promise used to return the result. If the operation is successful, the file descriptor ID to the wallpaper is returned. Otherwise, error information is returned.| - -**Example** - - ```js - var file = wallpaper.getFileSync(wallpaper.WallpaperType.WALLPAPER_SYSTEM); - ``` - + console.error(`failed to getFile because: ${JSON.stringify(error)}`); +}); +``` -## wallpaper.getPixelMap +## wallpaper.getPixelMap(deprecated) getPixelMap(wallpaperType: WallpaperType, callback: AsyncCallback<image.PixelMap>): void; @@ -1012,7 +1116,7 @@ Obtains the pixel map for the wallpaper of the specified type. This API uses an **System capability**: SystemCapability.MiscServices.Wallpaper -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -1023,15 +1127,17 @@ Obtains the pixel map for the wallpaper of the specified type. This API uses an **Example** - ```js - wallpaper.getPixelMap(wallpaper.WallpaperType.WALLPAPER_SYSTEM, function (err, data) { - console.info('wallpaperXTS ===> testGetPixelMapCallbackSystem err : ' + JSON.stringify(err)); - console.info('wallpaperXTS ===> testGetPixelMapCallbackSystem data : ' + JSON.stringify(data)); +```js +wallpaper.getPixelMap(wallpaper.WallpaperType.WALLPAPER_SYSTEM, function (error, data) { + if (error) { + console.error(`failed to getPixelMap because: ${JSON.stringify(error)}`); + return; + } + console.log(`success to getPixelMap : ${JSON.stringify(data)}`); }); - ``` - +``` -## wallpaper.getPixelMap +## wallpaper.getPixelMap(deprecated) getPixelMap(wallpaperType: WallpaperType): Promise<image.PixelMap> @@ -1045,7 +1151,7 @@ Obtains the pixel map for the wallpaper of the specified type. This API uses a p **System capability**: SystemCapability.MiscServices.Wallpaper -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -1061,144 +1167,10 @@ Obtains the pixel map for the wallpaper of the specified type. This API uses a p **Example** - ```js - wallpaper.getPixelMap(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { - console.info('wallpaperXTS ===> testGetPixelMapPromiseSystem data : ' + data); - console.info('wallpaperXTS ===> testGetPixelMapPromiseSystem data : ' + JSON.stringify(data)); - }).catch((err) => { - console.info('wallpaperXTS ===> testGetPixelMapPromiseSystem err : ' + err); - console.info('wallpaperXTS ===> testGetPixelMapPromiseSystem err : ' + JSON.stringify(err)); - }); - ``` - - -## wallpaper.getImage9+ - -getImage(wallpaperType: WallpaperType, callback: AsyncCallback<image.PixelMap>): void; - -Obtains the pixel map for the wallpaper of the specified type. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.GET_WALLPAPER - -**System capability**: SystemCapability.MiscServices.Wallpaper - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| -| callback | AsyncCallback<[image.PixelMap](js-apis-image.md#pixelmap7)> | Yes| Callback used to return the result. Returns the pixel map size of the wallpaper if the operation is successful; returns an error message otherwise.| - -**Example** - - ```js - wallpaper.getImage(wallpaper.WallpaperType.WALLPAPER_SYSTEM, function (err, data) { - console.info('wallpaperXTS ===> testgetImageCallbackSystem err : ' + JSON.stringify(err)); - console.info('wallpaperXTS ===> testgetImageCallbackSystem data : ' + JSON.stringify(data)); - }); - ``` - - -## wallpaper.getImage9+ - -getImage(wallpaperType: WallpaperType): Promise<image.PixelMap> - -Obtains the pixel map for the wallpaper of the specified type. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.GET_WALLPAPER - -**System capability**: SystemCapability.MiscServices.Wallpaper - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise<[image.PixelMap](js-apis-image.md#pixelmap7)> | Promise used to return the result. Returns the pixel map size of the wallpaper if the operation is successful; returns an error message otherwise.| - -**Example** - - ```js - wallpaper.getImage(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { - console.info('wallpaperXTS ===> testgetImagePromiseSystem data : ' + data); - console.info('wallpaperXTS ===> testgetImagePromiseSystem data : ' + JSON.stringify(data)); - }).catch((err) => { - console.info('wallpaperXTS ===> testgetImagePromiseSystem err : ' + err); - console.info('wallpaperXTS ===> testgetImagePromiseSystem err : ' + JSON.stringify(err)); - }); - ``` - - -## wallpaper.on('colorChange')9+ - -on(type: 'colorChange', callback: (colors: Array<RgbaColor>, wallpaperType: WallpaperType) => void): void - -Subscribes to the wallpaper color change event. - -**System capability**: SystemCapability.MiscServices.Wallpaper - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Type of the event to subscribe to. The value **'colorChange'** indicates subscribing to the wallpaper color change event.| -| callback | function | Yes| Callback triggered when the wallpaper color changes. The wallpaper type and main colors are returned.
- colors
Main color information of the wallpaper. For details, see [RgbaColor](#rgbacolor).
- wallpaperType
Wallpaper type.| - -**Example** - - ```js - let listener = (colors, wallpaperType) => { - console.log(`wallpaper color changed.`); - }; - wallpaper.on('colorChange', listener); - ``` - - -## wallpaper.off('colorChange')9+ - -off(type: 'colorChange', callback?: (colors: Array<RgbaColor>, wallpaperType: WallpaperType) => void): void - -Unsubscribes from the wallpaper color change event. - -**System capability**: SystemCapability.MiscServices.Wallpaper - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Type of the event to unsubscribe from. The value **colorChange** indicates unsubscribing from the wallpaper color change event.| -| callback | function | No| Callback for the wallpaper color change event. If this parameter is not specified, all callbacks corresponding to the wallpaper color change event are invoked.
- colors
Main color information of the wallpaper. For details, see [RgbaColor](#rgbacolor).
- wallpaperType
Wallpaper type.| - -**Example** - - ```js - let listener = (colors, wallpaperType) => { - console.log(`wallpaper color changed.`); - }; - wallpaper.on('colorChange', listener); - // Unsubscribe from the listener. - wallpaper.off('colorChange', listener); - // Unsubscribe from all subscriptions of the colorChange type. - wallpaper.off('colorChange'); - ``` - - -## RgbaColor - -**System capability**: SystemCapability.MiscServices.Wallpaper - -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| red | number | Yes| Yes| Red color. The value ranges from 0 to 255.| -| green | number | Yes| Yes| Green color. The value ranges from 0 to 255.| -| blue | number | Yes| Yes| Blue color. The value ranges from 0 to 255.| -| alpha | number | Yes| Yes| Alpha value. The value ranges from 0 to 255.| +```js +wallpaper.getPixelMap(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { + console.log(`success to getPixelMap : ${JSON.stringify(data)}`); + }).catch((error) => { + console.error(`failed to getPixelMap because: ${JSON.stringify(error)}`); +}); +``` diff --git a/en/application-dev/reference/apis/js-apis-workScheduler.md b/en/application-dev/reference/apis/js-apis-workScheduler.md deleted file mode 100644 index d897bc91717348ee8addd00751741f83cc77c345..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-workScheduler.md +++ /dev/null @@ -1,361 +0,0 @@ -# Work Scheduler - -The **workScheduler** module provides the APIs for registering, canceling, and querying Work Scheduler tasks, which do not have real-time constraints. - -The system executes Work Scheduler tasks at an appropriate time, subject to the storage space, power consumption, temperature, and more. - -> **NOTE** -> -> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> - The APIs of this module can be used only in the stage model. -> - For details about the constraints on the Work Scheduler usage, see [Work Scheduler Overview](../../task-management/work-scheduler-overview.md). - - -## Modules to Import - -```js -import workScheduler from '@ohos.workScheduler'; -``` - -## workScheduler.startWork -startWork(work: WorkInfo): boolean - -Instructs the **WorkSchedulerService** to add the specified task to the execution queue. - -**System capability**: SystemCapability.ResourceSchedule.WorkScheduler - -**Parameters** - -| Name | Type | Mandatory | Description | -| ---- | --------------------- | ---- | -------------- | -| work | [WorkInfo](#workinfo) | Yes | Task to be added to the execution queue.| - -**Return value** - -| Type | Description | -| ------- | -------------------------------- | -| boolean | Returns **true** if the task is added to the execution queue; returns **false** otherwise.| - -**Example** - -```js - let workInfo = { - workId: 1, - batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW, - isRepeat: false, - isPersisted: true, - bundleName: "com.example.myapplication", - abilityName: "MyExtension", - parameters: { - mykey0: 1, - mykey1: "string value", - mykey2: true, - mykey3: 1.5 - } - } - var res = workScheduler.startWork(workInfo); - console.info(`workschedulerLog res: ${res}`); -``` - -## workScheduler.stopWork -stopWork(work: WorkInfo, needCancel?: boolean): boolean - -Instructs the **WorkSchedulerService** to stop the specified task. - -**System capability**: SystemCapability.ResourceSchedule.WorkScheduler - -**Parameters** - -| Name | Type | Mandatory | Description | -| ---------- | --------------------- | ---- | ---------- | -| work | [WorkInfo](#workinfo) | Yes | Task to stop. | -| needCancel | boolean | Yes | Whether to cancel the task.| - -**Return value** - -| Type | Description | -| ------- | ----------------------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - -**Example** - -```js - let workInfo = { - workId: 1, - batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW, - isRepeat: false, - isPersisted: true, - bundleName: "com.example.myapplication", - abilityName: "MyExtension", - parameters: { - mykey0: 1, - mykey1: "string value", - mykey2: true, - mykey3: 1.5 - } - } - var res = workScheduler.stopWork(workInfo, false); - console.info(`workschedulerLog res: ${res}`); -``` - -## workScheduler.getWorkStatus -getWorkStatus(workId: number, callback : AsyncCallback\): void - -Obtains the latest task status. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.ResourceSchedule.WorkScheduler - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | ------------------------------------- | ---- | ---------------------------------------- | -| workId | number | Yes | Task ID. | -| callback | AsyncCallback\<[WorkInfo](#workinfo)> | Yes | Callback used to return the result. Returns the task status obtained from the **WorkSchedulerService** if the specified task ID is valid; returns **null** otherwise.| - -**Example** - -```js - workScheduler.getWorkStatus(50, (err, res) => { - if (err) { - console.info(`workschedulerLog getWorkStatus failed, because: ${err.code}`); - } else { - for (let item in res) { - console.info(`workschedulerLog getWorkStatus success, ${item} is: ${res[item]}`); - } - } - }); -``` - -## workScheduler.getWorkStatus -getWorkStatus(workId: number): Promise\ - -Obtains the latest task status. This API uses a promise to return the result. - -**System capability**: SystemCapability.ResourceSchedule.WorkScheduler - -**Parameters** - -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | -------- | -| workId | number | Yes | Task ID.| - -**Return value** - -| Type | Description | -| ------------------------------- | ---------------------------------------- | -| Promise\<[WorkInfo](#workinfo)> | Promise used to return the result. Returns the task status obtained from the **WorkSchedulerService** if the specified task ID is valid; returns **null** otherwise.| - -**Example** - -```js - workScheduler.getWorkStatus(50).then((res) => { - for (let item in res) { - console.info(`workschedulerLog getWorkStatus success, ${item} is: ${res[item]}`); - } - }).catch((err) => { - console.info(`workschedulerLog getWorkStatus failed, because: ${err.code}`); - }) -``` - -## workScheduler.obtainAllWorks -obtainAllWorks(callback : AsyncCallback\): Array\ - -Obtains all tasks associated with this application. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.ResourceSchedule.WorkScheduler - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | -------------------- | ---- | ------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return all tasks associated with the current application. | - -**Return value** - -| Type | Description | -| ----------------------------- | --------------- | -| Array\<[WorkInfo](#workinfo)> | All tasks associated with the current application.| - -**Example** - -```js - workScheduler.obtainAllWorks((err, res) =>{ - if (err) { - console.info(`workschedulerLog obtainAllWorks failed, because: ${err.code}`); - } else { - console.info(`workschedulerLog obtainAllWorks success, data is: ${JSON.stringify(res)}`); - } - }); -``` - -## workScheduler.obtainAllWorks -obtainAllWorks(): Promise> - -Obtains all tasks associated with this application. This API uses a promise to return the result. - -**System capability**: SystemCapability.ResourceSchedule.WorkScheduler - -**Return value** - -| Type | Description | -| -------------------------------------- | ------------------------------ | -| Promise> | Promise used to return all tasks associated with the current application. | - -**Example** - -```js - workScheduler.obtainAllWorks().then((res) => { - console.info(`workschedulerLog obtainAllWorks success, data is: ${JSON.stringify(res)}`); - }).catch((err) => { - console.info(`workschedulerLog obtainAllWorks failed, because: ${err.code}`); - }) -``` - -## workScheduler.stopAndClearWorks -stopAndClearWorks(): boolean - -Stops and cancels all tasks associated with the current application. - -**System capability**: SystemCapability.ResourceSchedule.WorkScheduler - -**Example** - -```js - let res = workScheduler.stopAndClearWorks(); - console.info(`workschedulerLog res: ${res}`); -``` - -## workScheduler.isLastWorkTimeOut -isLastWorkTimeOut(workId: number, callback : AsyncCallback\): boolean - -Checks whether the last execution of the specified task timed out. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.ResourceSchedule.WorkScheduler - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | -------------------- | ---- | ---------------------------------------- | -| workId | number | Yes | Task ID. | -| callback | AsyncCallback\ | Yes | Callback used to return the result. Returns **true** if the last execution of the specified task timed out; returns **false** otherwise.| - -**Return value** - -| Type | Description | -| ------- | ---------------------------------------- | -| boolean | Callback used to return the result. Returns **true** if the last execution of the specified task timed out; returns **false** otherwise.| - -**Example** - -```js - workScheduler.isLastWorkTimeOut(500, (err, res) =>{ - if (err) { - console.info(`workschedulerLog isLastWorkTimeOut failed, because: ${err.code}`); - } else { - console.info(`workschedulerLog isLastWorkTimeOut success, data is: ${res}`); - } - }); -``` - -## workScheduler.isLastWorkTimeOut -isLastWorkTimeOut(workId: number): Promise\ - -Checks whether the last execution of the specified task timed out. This API uses a promise to return the result. - -**System capability**: SystemCapability.ResourceSchedule.WorkScheduler - -**Parameters** - -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | -------- | -| workId | number | Yes | Task ID.| - -**Return value** - -| Type | Description | -| ----------------- | ---------------------------------------- | -| Promise\ | Promise used to return the result. Returns **true** if the last execution of the specified task timed out; returns **false** otherwise.| - -**Example** - -```js - workScheduler.isLastWorkTimeOut(500) - .then(res => { - console.info(`workschedulerLog isLastWorkTimeOut success, data is: ${res}`); - }) - .catch(err => { - console.info(`workschedulerLog isLastWorkTimeOut failed, because: ${err.code}`); - }); -``` - -## WorkInfo -Provides detailed information about the task. For details about the constraints on configuring **WorkInfo**, see [Work Scheduler Overview](../../task-management/work-scheduler-overview.md). - -**System capability**: SystemCapability.ResourceSchedule.WorkScheduler - -| Name | Type | Mandatory | Description | -| --------------- | --------------------------------- | ---- | ---------------- | -| workId | number | Yes | Task ID. | -| bundleName | string | Yes | Name of the Work Scheduler task bundle. | -| abilityName | string | Yes | Name of the component to be notified by a Work Scheduler callback.| -| networkType | [NetworkType](#networktype) | No | Network type. | -| isCharging | boolean | No | Whether the device is charging. | -| chargerType | [ChargingType](#chargingtype) | No | Charging type. | -| batteryLevel | number | No | Battery level. | -| batteryStatus | [BatteryStatus](#batterystatus) | No | Battery status. | -| storageRequest | [StorageRequest](#storagerequest) | No | Storage status. | -| isRepeat | boolean | No | Whether the task is repeated. | -| repeatCycleTime | number | No | Repeat interval. | -| repeatCount | number | No | Number of repeat times. | -| isPersisted | boolean | No | Whether to enable persistent storage for the task. | -| isDeepIdle | boolean | No | Whether the device needs to enter the idle state. | -| idleWaitTime | number | No | Time to wait in the idle state. | -| parameters | {[key: string]: any} | No | Carried parameters. | - -## NetworkType -Enumerates the network types that can trigger the task. - -**System capability**: SystemCapability.ResourceSchedule.WorkScheduler - -| Name | Default Value | Description | -| ---------------------- | ---- | ----------------------- | -| NETWORK_TYPE_ANY | 0 | Any network type. | -| NETWORK_TYPE_MOBILE | 1 | Mobile network. | -| NETWORK_TYPE_WIFI | 2 | Wi-Fi network. | -| NETWORK_TYPE_BLUETOOTH | 3 | Bluetooth network.| -| NETWORK_TYPE_WIFI_P2P | 4 | Wi-Fi P2P network. | -| NETWORK_TYPE_ETHERNET | 5 | Ethernet. | - -## ChargingType -Enumerates the charging types that can trigger the task. - -**System capability**: SystemCapability.ResourceSchedule.WorkScheduler - -| Name | Default Value | Description | -| ------------------------- | ---- | -------------------- | -| CHARGING_PLUGGED_ANY | 0 | Any charging type.| -| CHARGING_PLUGGED_AC | 1 | DC charging. | -| CHARGING_PLUGGED_USB | 2 | USB charging. | -| CHARGING_PLUGGED_WIRELESS | 3 | Wireless charging. | - -## BatteryStatus -Enumerates the battery states that can trigger the task. - -**System capability**: SystemCapability.ResourceSchedule.WorkScheduler - -| Name | Default Value | Description | -| -------------------------- | ---- | -------------------------- | -| BATTERY_STATUS_LOW | 0 | A low battery alert is displayed. | -| BATTERY_STATUS_OKAY | 1 | The battery level is restored from low to normal. | -| BATTERY_STATUS_LOW_OR_OKAY | 2 | The battery level is restored from low to normal, or a low battery alert is displayed.| - -## StorageRequest -Enumerates the storage states that can trigger the task. - -**System capability**: SystemCapability.ResourceSchedule.WorkScheduler - -| Name | Default Value | Description | -| ------------------------- | ---- | ------------------------------ | -| STORAGE_LEVEL_LOW | 0 | The storage space is insufficient. | -| STORAGE_LEVEL_OKAY | 1 | The storage space is restored from insufficient to normal. | -| STORAGE_LEVEL_LOW_OR_OKAY | 2 | The storage space is restored from insufficient to normal, or the storage space is insufficient.| diff --git a/en/application-dev/reference/apis/js-apis-worker.md b/en/application-dev/reference/apis/js-apis-worker.md index a9bb769b0eccd89631f4747bcce6deba03c4533a..1b269ea33508c427b9480641ee08210b7906eddc 100644 --- a/en/application-dev/reference/apis/js-apis-worker.md +++ b/en/application-dev/reference/apis/js-apis-worker.md @@ -1,11 +1,13 @@ -# Worker Startup +# @ohos.worker + +The worker thread is an independent thread running in parallel with the main thread. The thread that creates the worker thread is referred to as the host thread. The URL file passed in during worker creation is executed in the worker thread. The worker thread can process time-consuming operations, but cannot directly operate the UI. + +With the **Worker** module, you can provide a multithreading environment for an application, so that the application can perform a time-consuming operation in a background thread. This greatly prevents a computing-intensive or high-latency task from blocking the running of the main thread. A **Worker** instance will not be proactively destroyed once it is created. It consumes resources to keep running. Therefore, you should call the API to terminate it in a timely manner. > **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. -The worker thread is an independent thread running in parallel with the main thread. The thread that creates the worker thread is referred to as the host thread. The URL file passed in during worker creation is executed in the worker thread. The worker thread can process time-consuming operations, but cannot directly operate the UI. - ## Modules to Import ```js @@ -17,10 +19,10 @@ import worker from '@ohos.worker'; **System capability**: SystemCapability.Utils.Lang -| Name | Type | Readable| Writable| Description | +| Name | Type | Readable| Writable| Description | | --------------------------------- | --------------------------------------------------------- | ---- | ---- | ------------------------------------------------------------ | | workerPort9+ | [ThreadWorkerGlobalScope](#threadworkerglobalscope9) | Yes | Yes | Object of the worker thread used to communicate with the host thread. | -| parentPort(deprecated) | [DedicatedWorkerGlobalScope](#dedicatedworkerglobalscope) | Yes | Yes | Object of the worker thread used to communicate with the host thread.
This attribute is deprecated since API version 9. You are advised to use **workerPort9+** instead.| +| parentPort(deprecated) | [DedicatedWorkerGlobalScope](#dedicatedworkerglobalscope) | Yes | Yes | Object of the worker thread used to communicate with the host thread.
This attribute is supported since API version 7 and deprecated since API version 9.
You are advised to use **workerPort9+** instead.| ## WorkerOptions @@ -31,7 +33,9 @@ Provides options that can be set for the **Worker** instance to create. | Name| Type| Readable| Writable| Description | | ---- | -------- | ---- | ---- | -------------- | +| type | "classic" \| "module" | Yes | Yes | Mode in which the **Worker** instance executes the script. The default value is **classic**. The module **type** is not supported yet.| | name | string | Yes | Yes | Name of the worker thread.| +| shared | boolean | Yes | Yes | Sharing of the **Worker** instance is not supported yet.| ## ThreadWorker9+ @@ -166,7 +170,7 @@ workerInstance.postMessage(buffer, [buffer]); on(type: string, listener: WorkerEventListener): void -Adds an event listener for the worker thread. +Adds an event listener for the worker thread. This API provides the same functionality as [addEventListener9+](#addeventlistener9). **System capability**: SystemCapability.Utils.Lang @@ -216,7 +220,7 @@ workerInstance.once("alert", (e)=>{ off(type: string, listener?: WorkerEventListener): void -Removes an event listener for the worker thread. +Removes an event listener for the worker thread. This API provides the same functionality as [removeEventListener9+](#removeeventlistener9). **System capability**: SystemCapability.Utils.Lang @@ -231,6 +235,7 @@ Removes an event listener for the worker thread. ```js const workerInstance = new worker.ThreadWorker("workers/worker.js"); +// Use on, once, or addEventListener to add a listener for the "alert" event, and use off to remove the listener. workerInstance.off("alert"); ``` @@ -263,7 +268,7 @@ Defines the event handler to be called when the worker thread exits. The handler | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------ | -| code | number | No | Code indicating the worker thread exit state.| +| code | number | Yes | Code indicating the worker thread exit state.| **Example** @@ -272,6 +277,13 @@ const workerInstance = new worker.ThreadWorker("workers/worker.js"); workerInstance.onexit = function(e) { console.log("onexit"); } + +// onexit is executed in either of the following ways: +// Main thread: +workerInstance.terminate(); + +// Worker thread: +//parentPort.close() ``` @@ -287,7 +299,7 @@ Defines the event handler to be called when an exception occurs during worker ex | Name| Type | Mandatory| Description | | ------ | ------------------------- | ---- | ---------- | -| err | [ErrorEvent](#errorevent) | No | Error data.| +| err | [ErrorEvent](#errorevent) | Yes | Error data.| **Example** @@ -301,7 +313,7 @@ workerInstance.onerror = function(e) { ### onmessage9+ -onmessage?: (event: MessageEvent\) => void +onmessage?: (event: MessageEvents) => void Defines the event handler to be called when the host thread receives a message sent by the worker thread through **parentPort.postMessage**. The event handler is executed in the host thread. @@ -309,16 +321,16 @@ Defines the event handler to be called when the host thread receives a message s **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ----------------------------- | ---- | ---------------------- | -| event | [MessageEvent](#messageevent) | No | Message received.| +| Name| Type | Mandatory| Description | +| ------ | -------------------------------- | ---- | ---------------------- | +| event | [MessageEvents](#messageevents9) | Yes | Message received.| **Example** ```js const workerInstance = new worker.ThreadWorker("workers/worker.js"); workerInstance.onmessage = function(e) { - // e: MessageEvent. The usage is as follows: + // e: MessageEvents. The usage is as follows: // let data = e.data; console.log("onmessage"); } @@ -327,7 +339,7 @@ workerInstance.onmessage = function(e) { ### onmessageerror9+ -onmessageerror?: (event: MessageEvent\) => void +onmessageerror?: (event: MessageEvents) => void Defines the event handler to be called when the worker thread receives a message that cannot be serialized. The event handler is executed in the host thread. @@ -335,9 +347,9 @@ Defines the event handler to be called when the worker thread receives a message **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ----------------------------- | ---- | ---------- | -| event | [MessageEvent](#messageevent) | No | Error data.| +| Name| Type | Mandatory| Description | +| ------ | -------------------------------- | ---- | ---------- | +| event | [MessageEvents](#messageevents9) | Yes | Error data.| **Example** @@ -355,7 +367,7 @@ workerInstance.onmessageerror= function(e) { addEventListener(type: string, listener: WorkerEventListener): void -Adds an event listener for the worker thread. +Adds an event listener for the worker thread. This API provides the same functionality as [on9+](#on9). **System capability**: SystemCapability.Utils.Lang @@ -380,7 +392,7 @@ workerInstance.addEventListener("alert", (e)=>{ removeEventListener(type: string, callback?: WorkerEventListener): void -Removes an event listener for the worker thread. +Removes an event listener for the worker thread. This API provides the same functionality as [off9+](#off9). **System capability**: SystemCapability.Utils.Lang @@ -395,6 +407,9 @@ Removes an event listener for the worker thread. ```js const workerInstance = new worker.ThreadWorker("workers/worker.js"); +workerInstance.addEventListener("alert", (e)=>{ + console.log("alert listener callback"); +}) workerInstance.removeEventListener("alert"); ``` @@ -423,7 +438,41 @@ Dispatches the event defined for the worker thread. ```js const workerInstance = new worker.ThreadWorker("workers/worker.js"); -workerInstance.dispatchEvent({type:"alert"}); +// Usage 1: +workerInstance.on("alert_on", (e)=>{ + console.log("alert listener callback"); +}) +workerInstance.once("alert_once", (e)=>{ + console.log("alert listener callback"); +}) +workerInstance.addEventListener("alert_add", (e)=>{ + console.log("alert listener callback"); +}) + +// The event listener created by once is removed after being executed once. +workerInstance.dispatchEvent({type:"alert_once", timeStamp:0}); +// The event listener created by on will be always valid and will not be proactively deleted. +workerInstance.dispatchEvent({type:"alert_on", timeStamp:0}); +workerInstance.dispatchEvent({type:"alert_on", timeStamp:0}); +// The event listener created by addEventListener will be always valid and will not be proactively deleted. +workerInstance.dispatchEvent({type:"alert_add", timeStamp:0}); +workerInstance.dispatchEvent({type:"alert_add", timeStamp:0}); + +// Usage 2: +// The event type can be customized, and the special types "message", "messageerror", and "error" exist. +// When type = "message", the event handler defined by onmessage will also be executed. +// When type = "messageerror", the event handler defined by onmessageerror will also be executed. +// When type = "error", the event handler defined by onerror will also be executed. +// removeEventListener or off can be used to remove an event listener that is created by addEventListener, on, or once. + +workerInstance.addEventListener("message", (e)=>{ + console.log("message listener callback"); +}) +workerInstance.onmessage = function(e) { + console.log("onmessage : message listener callback"); +} +// When dispatchEvent is called to distribute the "message" event, the callback passed in addEventListener and onmessage will be invoked. +workerInstance.dispatchEvent({type:"message", timeStamp:0}); ``` @@ -439,13 +488,16 @@ Removes all event listeners for the worker thread. ```js const workerInstance = new worker.ThreadWorker("workers/worker.js"); +workerInstance.addEventListener("alert", (e)=>{ + console.log("alert listener callback"); +}) workerInstance.removeAllListener(); ``` ## ThreadWorkerGlobalScope9+ -Implements communication between the worker thread and the host thread. The **postMessage** API is used to send messages to the host thread, and the **close** API is used to terminate the worker thread. The **DedicatedWorkerGlobalScope** class inherits from [GlobalScope9+](#globalscope9). +Implements communication between the worker thread and the host thread. The **postMessage** API is used to send messages to the host thread, and the **close** API is used to terminate the worker thread. The **ThreadWorkerGlobalScope** class inherits from [GlobalScope9+](#globalscope9). ### postMessage9+ @@ -515,7 +567,7 @@ parentPort.onmessage = function(e) { ### onmessage9+ -onmessage?: (event: MessageEvent\) => void +onmessage?: (this: ThreadWorkerGlobalScope, event: MessageEvents) => void Defines the event handler to be called when the worker thread receives a message sent by the host thread through **postMessage**. The event handler is executed in the worker thread. @@ -523,9 +575,10 @@ Defines the event handler to be called when the worker thread receives a message **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ----------------------------- | ---- | ------------------------ | -| event | [MessageEvent](#messageevent) | No | Message received.| +| Name| Type | Mandatory| Description | +| ------ | ---------------------------------------------------- | ---- | ------------------------ | +| this | [ThreadWorkerGlobalScope](#threadworkerglobalscope9) | Yes | Caller. | +| event | [MessageEvents](#messageevents9) | Yes | Message received.| **Example** @@ -548,7 +601,7 @@ parentPort.onmessage = function(e) { ### onmessageerror9+ -onmessageerror?: (event: MessageEvent\) => void +onmessageerror?: (this: ThreadWorkerGlobalScope, event: MessageEvents) => void Defines the event handler to be called when the worker thread receives a message that cannot be deserialized. The event handler is executed in the worker thread. @@ -556,9 +609,10 @@ Defines the event handler to be called when the worker thread receives a message **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ----------------------------- | ---- | ---------- | -| event | [MessageEvent](#messageevent) | No | Error data.| +| Name| Type | Mandatory| Description | +| ------ | -------------------------------- | ---- | ---------- | +| this | [ThreadWorkerGlobalScope](#threadworkerglobalscope9) | Yes | Caller. | +| event | [MessageEvents](#messageevents9) | Yes | Error data.| **Example** @@ -572,7 +626,7 @@ const workerInstance = new worker.ThreadWorker("workers/worker.js"); // worker.js import worker from '@ohos.worker'; const parentPort = worker.workerPort; -parentPort.onmessageerror= function(e) { +parentPort.onmessageerror = function(e) { console.log("worker.js onmessageerror") } ``` @@ -610,13 +664,13 @@ workerInstance.addEventListener("alert", (e)=>{ ## GlobalScope9+ -Implements the running environment of the worker thread. The **WorkerGlobalScope** class inherits from [WorkerEventTarget](#workereventtarget9). +Implements the running environment of the worker thread. The **GlobalScope** class inherits from [WorkerEventTarget](#workereventtarget9). ### Attributes **System capability**: SystemCapability.Utils.Lang -| Name| Type | Readable| Writable| Description | +| Name| Type | Readable| Writable| Description | | ---- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------- | | name | string | Yes | No | **Worker** instance specified when there is a new **Worker** instance.| | self | [GlobalScope](#globalscope9) & typeof globalThis | Yes | No | **GlobalScope** itself. | @@ -634,7 +688,7 @@ Defines the event handler to be called when an exception occurs during worker ex | Name| Type | Mandatory| Description | | ------ | ------------------------- | ---- | ---------- | -| ev | [ErrorEvent](#errorevent) | No | Error data.| +| ev | [ErrorEvent](#errorevent) | Yes | Error data.| **Example** @@ -653,22 +707,33 @@ parentPort.onerror = function(e){ } ``` +## MessageEvents9+ + +Holds the data transferred between worker threads. + +**System capability**: SystemCapability.Utils.Lang + +| Name| Type| Readable| Writable| Description | +| ---- | ---- | ---- | ---- | ------------------ | +| data | any | Yes | No | Data transferred between threads.| ## Worker(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [ThreadWorker9+](#threadworker9) instead. Before using the following APIs, you must create a **Worker** instance. The **Worker** class inherits from [EventTarget](#eventtarget). -### constructor(deprecated) > **NOTE**
-> This API is deprecated since API version 9. You are advised to use [ThreadWorker.constructor9+](#constructor9) instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker9+](#threadworker9) instead. + +### constructor(deprecated) constructor(scriptURL: string, options?: WorkerOptions) A constructor used to create a **Worker** instance. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.constructor9+](#constructor9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -753,13 +818,13 @@ In the stage model: ``` ### postMessage(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [ThreadWorker.postMessage9+](#postmessage9) instead. - postMessage(message: Object, options?: PostMessageOptions): void Sends a message to the worker thread. The data type of the message must be sequenceable. For details about the sequenceable data types, see [More Information](#more-information). +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.postMessage9+](#postmessage9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -783,12 +848,12 @@ workerInstance.postMessage(buffer, [buffer]); ### on(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [ThreadWorker.on9+](#on9) instead. - on(type: string, listener: EventListener): void -Adds an event listener for the worker thread. +Adds an event listener for the worker thread. This API provides the same functionality as [addEventListener(deprecated)](#addeventlistenerdeprecated). + +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.on9+](#on9) instead. **System capability**: SystemCapability.Utils.Lang @@ -811,13 +876,13 @@ workerInstance.on("alert", (e)=>{ ### once(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [ThreadWorker.once9+](#once9) instead. - once(type: string, listener: EventListener): void Adds an event listener for the worker thread and removes the event listener after it is invoked once. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.once9+](#once9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -839,12 +904,12 @@ workerInstance.once("alert", (e)=>{ ### off(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [ThreadWorker.off9+](#off9) instead. - off(type: string, listener?: EventListener): void -Removes an event listener for the worker thread. +Removes an event listener for the worker thread. This API provides the same functionality as [removeEventListener(deprecated)](#removeeventlistenerdeprecated). + +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.off9+](#off9) instead. **System capability**: SystemCapability.Utils.Lang @@ -859,19 +924,20 @@ Removes an event listener for the worker thread. ```js const workerInstance = new worker.Worker("workers/worker.js"); +// Use on, once, or addEventListener to add a listener for the "alert" event, and use off to remove the listener. workerInstance.off("alert"); ``` ### terminate(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [ThreadWorker.terminate9+](#terminate9) instead. - terminate(): void Terminates the worker thread to stop it from receiving messages. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.terminate9+](#terminate9) instead. + **System capability**: SystemCapability.Utils.Lang **Example** @@ -884,20 +950,20 @@ workerInstance.terminate(); ### onexit(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [ThreadWorker.onexit9+](#onexit9) instead. - onexit?: (code: number) => void Defines the event handler to be called when the worker thread exits. The handler is executed in the host thread. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.onexit9+](#onexit9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------ | -| code | number | No | Code indicating the worker thread exit state.| +| code | number | Yes | Code indicating the worker thread exit state.| **Example** @@ -906,25 +972,32 @@ const workerInstance = new worker.Worker("workers/worker.js"); workerInstance.onexit = function(e) { console.log("onexit"); } + +// onexit is executed in either of the following ways: +// Main thread: +workerInstance.terminate(); + +// Worker thread: +//parentPort.close() ``` ### onerror(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [ThreadWorker.onerror9+](#onerror9) instead. - onerror?: (err: ErrorEvent) => void Defines the event handler to be called when an exception occurs during worker execution. The event handler is executed in the host thread. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.onerror9+](#onerror9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type | Mandatory| Description | | ------ | ------------------------- | ---- | ---------- | -| err | [ErrorEvent](#errorevent) | No | Error data.| +| err | [ErrorEvent](#errorevent) | Yes | Error data.| **Example** @@ -938,27 +1011,27 @@ workerInstance.onerror = function(e) { ### onmessage(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [ThreadWorker.onmessage9+](#onmessage9) instead. - -onmessage?: (event: MessageEvent\) => void +onmessage?: (event: MessageEvent) => void Defines the event handler to be called when the host thread receives a message sent by the worker thread through **parentPort.postMessage**. The event handler is executed in the host thread. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.onmessage9+](#onmessage9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ----------------------------- | ---- | ---------------------- | -| event | [MessageEvent](#messageevent) | No | Message received.| +| Name| Type | Mandatory| Description | +| ------ | ------------------------------ | ---- | ---------------------- | +| event | [MessageEvent](#messageeventt) | Yes | Message received.| **Example** ```js const workerInstance = new worker.Worker("workers/worker.js"); workerInstance.onmessage = function(e) { - // e: MessageEvent. The usage is as follows: + // e: MessageEvent. The usage is as follows: // let data = e.data; console.log("onmessage"); } @@ -967,20 +1040,20 @@ workerInstance.onmessage = function(e) { ### onmessageerror(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [ThreadWorker.onmessageerror9+](#onmessageerror9) instead. - -onmessageerror?: (event: MessageEvent\) => void +onmessageerror?: (event: MessageEvent) => void Defines the event handler to be called when the worker thread receives a message that cannot be serialized. The event handler is executed in the host thread. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.onmessageerror9+](#onmessageerror9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ----------------------------- | ---- | ---------- | -| event | [MessageEvent](#messageevent) | No | Error data.| +| Name| Type | Mandatory| Description | +| ------ | ------------------------------ | ---- | ---------- | +| event | [MessageEvent](#messageeventt) | Yes | Error data.| **Example** @@ -994,16 +1067,16 @@ workerInstance.onmessageerror= function(e) { ## EventTarget(deprecated) > **NOTE**
-> This API is deprecated since API version 9. You are advised to use [WorkerEventTarget9+](#workereventtarget9) instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [WorkerEventTarget9+](#workereventtarget9) instead. ### addEventListener(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [addEventListener9+](#addeventlistener9) instead. - addEventListener(type: string, listener: EventListener): void -Adds an event listener for the worker thread. +Adds an event listener for the worker thread. This API provides the same functionality as [on(deprecated)](#ondeprecated). + +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [addEventListener9+](#addeventlistener9) instead. **System capability**: SystemCapability.Utils.Lang @@ -1026,12 +1099,12 @@ workerInstance.addEventListener("alert", (e)=>{ ### removeEventListener(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [removeEventListener9+](#removeeventlistener9) instead. - removeEventListener(type: string, callback?: EventListener): void -Removes an event listener for the worker thread. +Removes an event listener for the worker thread. This API provides the same functionality as [off(deprecated)](#offdeprecated). + +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [removeEventListener9+](#removeeventlistener9) instead. **System capability**: SystemCapability.Utils.Lang @@ -1046,19 +1119,22 @@ Removes an event listener for the worker thread. ```js const workerInstance = new worker.Worker("workers/worker.js"); +workerInstance.addEventListener("alert", (e)=>{ + console.log("alert listener callback"); +}) workerInstance.removeEventListener("alert"); ``` ### dispatchEvent(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [dispatchEvent9+](#dispatchevent9) instead. - dispatchEvent(event: Event): boolean Dispatches the event defined for the worker thread. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [dispatchEvent9+](#dispatchevent9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -1077,46 +1153,81 @@ Dispatches the event defined for the worker thread. ```js const workerInstance = new worker.Worker("workers/worker.js"); -workerInstance.dispatchEvent({type:"alert"}); -``` +// Usage 1: +workerInstance.on("alert_on", (e)=>{ + console.log("alert listener callback"); +}) +workerInstance.once("alert_once", (e)=>{ + console.log("alert listener callback"); +}) +workerInstance.addEventListener("alert_add", (e)=>{ + console.log("alert listener callback"); +}) +// The event listener created by once is removed after being executed once. +workerInstance.dispatchEvent({type:"alert_once", timeStamp:0}); +// The event listener created by on will not be proactively deleted. +workerInstance.dispatchEvent({type:"alert_on", timeStamp:0}); +workerInstance.dispatchEvent({type:"alert_on", timeStamp:0}); +// The event listener created by addEventListener will not be proactively deleted. +workerInstance.dispatchEvent({type:"alert_add", timeStamp:0}); +workerInstance.dispatchEvent({type:"alert_add", timeStamp:0}); + +// Usage 2: +// The event type can be customized, and the special types "message", "messageerror", and "error" exist. +// When type = "message", the event handler defined by onmessage will also be executed. +// When type = "messageerror", the event handler defined by onmessageerror will also be executed. +// When type = "error", the event handler defined by onerror will also be executed. +// removeEventListener or off can be used to remove an event listener that is created by addEventListener, on, or once. + +workerInstance.addEventListener("message", (e)=>{ + console.log("message listener callback"); +}) +workerInstance.onmessage = function(e) { + console.log("onmessage : message listener callback"); +} +// When dispatchEvent is called to distribute the "message" event, the callback passed in addEventListener and onmessage will be invoked. +workerInstance.dispatchEvent({type:"message", timeStamp:0}); +``` ### removeAllListener(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [removeAllListener9+](#removealllistener9) instead. - removeAllListener(): void Removes all event listeners for the worker thread. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [removeAllListener9+](#removealllistener9) instead. + **System capability**: SystemCapability.Utils.Lang **Example** ```js const workerInstance = new worker.Worker("workers/worker.js"); +workerInstance.addEventListener("alert", (e)=>{ + console.log("alert listener callback"); +}) workerInstance.removeAllListener(); ``` ## DedicatedWorkerGlobalScope(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+](#threadworkerglobalscope9) instead. - Implements communication between the worker thread and the host thread. The **postMessage** API is used to send messages to the host thread, and the **close** API is used to terminate the worker thread. This class inherits from [WorkerGlobalScope](#workerglobalscope). +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+](#threadworkerglobalscope9) instead. ### postMessage(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+](#threadworkerglobalscope9).postMessage9+ instead. - postMessage(messageObject: Object, options?: PostMessageOptions): void Sends a message to the host thread from the worker thread. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+](#threadworkerglobalscope9).postMessage9+ instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -1151,13 +1262,13 @@ parentPort.onmessage = function(e){ ### close(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+](#threadworkerglobalscope9).close9+ instead. - close(): void Terminates the worker thread to stop it from receiving messages. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+](#threadworkerglobalscope9).close9+ instead. + **System capability**: SystemCapability.Utils.Lang **Example** @@ -1179,20 +1290,21 @@ parentPort.onmessage = function(e) { ### onmessage(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+](#threadworkerglobalscope9).onmessage9+ instead. - -onmessage?: (event: MessageEvent\) => void +onmessage?: (this: DedicatedWorkerGlobalScope, event: MessageEvent) => void Defines the event handler to be called when the worker thread receives a message sent by the host thread through **postMessage**. The event handler is executed in the worker thread. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+](#threadworkerglobalscope9).onmessage9+ instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ----------------------------- | ---- | ------------------------ | -| event | [MessageEvent](#messageevent) | No | Message received.| +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------------------------ | ---- | ------------------------ | +| this | [DedicatedWorkerGlobalScope](#dedicatedworkerglobalscopedeprecated) | Yes | Caller. | +| event | [MessageEvent](#messageeventt) | Yes | Message received.| **Example** @@ -1214,20 +1326,21 @@ parentPort.onmessage = function(e) { ### onmessageerror(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+](#threadworkerglobalscope9).onmessageerror9+ instead. - -onmessageerror?: (event: MessageEvent\) => void +onmessageerror?: (this: DedicatedWorkerGlobalScope, event: MessageEvent) => void Defines the event handler to be called when the worker thread receives a message that cannot be deserialized. The event handler is executed in the worker thread. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+](#threadworkerglobalscope9).onmessageerror9+ instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ----------------------------- | ---- | ---------- | -| event | [MessageEvent](#messageevent) | No | Error data.| +| Name| Type | Mandatory| Description | +| ------ | ------------------------------ | ---- | ---------- | +| this | [DedicatedWorkerGlobalScope](#dedicatedworkerglobalscopedeprecated) | Yes | Caller.| +| event | [MessageEvent](#messageeventt) | Yes | Error data.| **Example** @@ -1240,7 +1353,7 @@ const workerInstance = new worker.Worker("workers/worker.js"); // worker.js import worker from '@ohos.worker'; const parentPort = worker.parentPort; -parentPort.onmessageerror= function(e) { +parentPort.onmessageerror = function(e) { console.log("worker.js onmessageerror") } ``` @@ -1252,7 +1365,7 @@ Specifies the object whose ownership needs to be transferred during data transfe **System capability**: SystemCapability.Utils.Lang -| Name | Type| Readable| Writable| Description | +| Name | Type | Readable| Writable| Description | | -------- | -------- | ---- | ---- | --------------------------------- | | transfer | Object[] | Yes | Yes | **ArrayBuffer** array used to transfer the ownership.| @@ -1263,21 +1376,21 @@ Defines the event. **System capability**: SystemCapability.Utils.Lang -| Name | Type| Readable| Writable| Description | -| --------- | -------- | ---- | ---- | ---------------------------------- | -| type | string | Yes | No | Type of the event. | -| timeStamp | number | Yes | No | Timestamp (accurate to millisecond) when the event is created.| +| Name | Type | Readable| Writable| Description | +| --------- | ------ | ---- | ---- | ---------------------------------- | +| type | string | Yes | No | Type of the event. | +| timeStamp | number | Yes | No | Timestamp (accurate to millisecond) when the event is created.| ## EventListener(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [WorkerEventListener9+](#workereventlistener9) instead. - (evt: Event): void | Promise<void> Implements event listening. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [WorkerEventListener9+](#workereventlistener9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -1308,38 +1421,38 @@ Provides detailed information about the exception that occurs during worker exec **System capability**: SystemCapability.Utils.Lang -| Name | Type| Readable| Writable| Description | -| -------- | -------- | ---- | ---- | -------------------- | -| message | string | Yes | No | Information about the exception.| -| filename | string | Yes | No | File where the exception is located.| -| lineno | number | Yes | No | Serial number of the line where the exception is located. | -| colno | number | Yes | No | Serial number of the column where the exception is located. | -| error | Object | Yes | No | Type of the exception. | +| Name | Type | Readable| Writable| Description | +| -------- | ------ | ---- | ---- | -------------------- | +| message | string | Yes | No | Information about the exception.| +| filename | string | Yes | No | File where the exception is located.| +| lineno | number | Yes | No | Serial number of the line where the exception is located. | +| colno | number | Yes | No | Serial number of the column where the exception is located. | +| error | Object | Yes | No | Type of the exception. | -## MessageEvent +## MessageEvent\ Holds the data transferred between worker threads. **System capability**: SystemCapability.Utils.Lang | Name| Type| Readable| Writable| Description | -| ---- | -------- | ---- | ---- | ------------------ | -| data | T | Yes | No | Data transferred between threads.| +| ---- | ---- | ---- | ---- | ------------------ | +| data | T | Yes | No | Data transferred between threads.| ## WorkerGlobalScope(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [GlobalScope9+](#globalscope9) instead. - Implements the running environment of the worker thread. The **WorkerGlobalScope** class inherits from [EventTarget](#eventtarget). +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [GlobalScope9+](#globalscope9) instead. + ### Attributes **System capability**: SystemCapability.Utils.Lang -| Name| Type | Readable| Writable| Description | +| Name| Type | Readable| Writable| Description | | ---- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------- | | name | string | Yes | No | **Worker** instance specified when there is a new **Worker** instance.| | self | [WorkerGlobalScope](#workerglobalscope) & typeof globalThis | Yes | No | **WorkerGlobalScope**. | @@ -1347,20 +1460,20 @@ Implements the running environment of the worker thread. The **WorkerGlobalScope ### onerror(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [GlobalScope9+](#globalscope9).onerror instead. - onerror?: (ev: ErrorEvent) => void Defines the event handler to be called when an exception occurs during worker execution. The event handler is executed in the worker thread. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [GlobalScope9+](#globalscope9).onerror instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type | Mandatory| Description | | ------ | ------------------------- | ---- | ---------- | -| ev | [ErrorEvent](#errorevent) | No | Error data.| +| ev | [ErrorEvent](#errorevent) | Yes | Error data.| **Example** @@ -1402,7 +1515,7 @@ Exception: When an object created through a custom class is passed, no serializa ```js // main.js import worker from '@ohos.worker'; -const workerInstance = new worker.Thread("workers/worker.js"); +const workerInstance = new worker.ThreadWorker("workers/worker.js"); workerInstance.postMessage("message from main to worker"); workerInstance.onmessage = function(d) { // When the worker thread passes obj2, data contains obj2, excluding the Init or SetName method. @@ -1414,12 +1527,9 @@ workerInstance.onmessage = function(d) { import worker from '@ohos.worker'; const parentPort = worker.workerPort; class MyModel { + name = "undefined" Init() { - this.name = "wzy" - this.age = 18 - } - SetName() { - this.name = "WZY" + this.name = "MyModel" } } parentPort.onmessage = function(d) { @@ -1460,6 +1570,7 @@ Each actor concurrently processes tasks of the main thread. For each actor, ther - To proactively destroy a worker thread, you can call **terminate()** or **parentPort.close()** of the newly created **Worker** instance. - Since API version 9, if a **Worker** instance in a non-running state (such as destroyed or being destroyed) calls an API, a business error is thrown. - Creating and terminating worker threads consume performance. Therefore, you are advised to manage available workers and reuse them. +- Do not use both **new worker.Worker** and **new worker.ThreadWorker** to create a **Worker** project. Otherwise, **Worker** functions abnormally. Since API version 9, you are advised to use [new worker.ThreadWorker](#constructor9). In API version 8 and earlier versions, you are advised to use [new worker.Worker](#constructordeprecated). ## Sample Code > **NOTE**
@@ -1589,3 +1700,4 @@ Configuration of the **build-profile.json5** file: } } ``` + diff --git a/en/application-dev/reference/apis/js-apis-xml.md b/en/application-dev/reference/apis/js-apis-xml.md index 945c5219bedb22f5efdd6f53b5d55d4cdd97f260..ec3549a4051ea6784a56be33c902fc167e1311a1 100644 --- a/en/application-dev/reference/apis/js-apis-xml.md +++ b/en/application-dev/reference/apis/js-apis-xml.md @@ -1,4 +1,4 @@ -# XML Parsing and Generation +# @ohos.xml (XML Parsing and Generation) > **NOTE** > @@ -24,10 +24,10 @@ A constructor used to create an **XmlSerializer** instance. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| buffer | ArrayBuffer \| DataView | Yes| **ArrayBuffer** or **DataView** for storing the XML information to write.| -| encoding | string | No| Encoding format.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------- | ---- | ------------------------------------------------ | +| buffer | ArrayBuffer \| DataView | Yes | **ArrayBuffer** or **DataView** for storing the XML information to write.| +| encoding | string | No | Encoding format. | **Example** @@ -48,10 +48,10 @@ Sets an attribute. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| name | string | Yes| Key of the attribute.| -| value | string | Yes| Value of the attribute.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | --------------- | +| name | string | Yes | Key of the attribute. | +| value | string | Yes | Value of the attribute.| **Example** @@ -60,8 +60,8 @@ let arrayBuffer = new ArrayBuffer(1024); let bufView = new DataView(arrayBuffer); let thatSer = new xml.XmlSerializer(bufView); thatSer.startElement("note"); -thatSer.setAttributes("importance", "high"); -thatSer.endElement(); +thatSer.setAttributes("importance", "high"); +thatSer.endElement(); ``` @@ -75,9 +75,9 @@ Adds an empty element. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| name | string | Yes| Name of the empty element to add.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| name | string | Yes | Name of the empty element to add.| **Example** @@ -117,9 +117,9 @@ Writes the start tag based on the given element name. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| name | string | Yes| Name of the element.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| name | string | Yes | Name of the element.| **Example** @@ -145,11 +145,11 @@ Writes the end tag of the element. let arrayBuffer = new ArrayBuffer(1024); let bufView = new DataView(arrayBuffer); let thatSer = new xml.XmlSerializer(bufView); -thatSer.setNamespace("h", "http://www.w3.org/TR/html4/"); +thatSer.setNamespace("h", "https://www.w3.org/TR/html4/"); thatSer.startElement("table"); thatSer.setAttributes("importance", "high"); thatSer.setText("Happy"); -thatSer.endElement(); // => Happy +thatSer.endElement(); // => Happy ``` @@ -163,10 +163,10 @@ Sets the namespace for an element tag. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| prefix | string | Yes| Prefix of the element and its child elements.| -| namespace | string | Yes| Namespace to set.| +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | ------------------------------ | +| prefix | string | Yes | Prefix of the element and its child elements. | +| namespace | string | Yes | Namespace to set.| **Example** @@ -174,9 +174,9 @@ Sets the namespace for an element tag. let arrayBuffer = new ArrayBuffer(1024); let thatSer = new xml.XmlSerializer(arrayBuffer); thatSer.setDeclaration(); -thatSer.setNamespace("h", "http://www.w3.org/TR/html4/"); +thatSer.setNamespace("h", "https://www.w3.org/TR/html4/"); thatSer.startElement("note"); -thatSer.endElement();// = >'\r\n'; +thatSer.endElement();// = >'\r\n'; ``` ### setComment @@ -189,9 +189,9 @@ Sets the comment. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| text | string | Yes| Comment to set.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------- | +| text | string | Yes | Comment to set.| **Example** @@ -214,9 +214,9 @@ Sets CDATA attributes. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| text | string | Yes| CDATA attribute to set.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ----------------- | +| text | string | Yes | CDATA attribute to set.| **Example** @@ -237,9 +237,9 @@ Sets **Text**. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| text | string | Yes| Content of the **Text** to set.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------- | +| text | string | Yes | Content of the **Text** to set.| **Example** @@ -263,9 +263,9 @@ Sets **DocType**. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| text | string | Yes| Content of **DocType** to set.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------- | +| text | string | Yes | Content of **DocType** to set.| **Example** @@ -289,10 +289,10 @@ Creates and returns an **XmlPullParser** object. The **XmlPullParser** object pa **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| buffer | ArrayBuffer \| DataView | Yes| **ArrayBuffer** or **DataView** that contains XML text information.| -| encoding | string | No| Encoding format. Only UTF-8 is supported.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------- | ---- | ------------------------------------------ | +| buffer | ArrayBuffer \| DataView | Yes | **ArrayBuffer** or **DataView** that contains XML text information.| +| encoding | string | No | Encoding format. Only UTF-8 is supported. | **Example** @@ -324,9 +324,9 @@ Parses XML information. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| option | [ParseOptions](#parseoptions) | Yes| Options for controlling and obtaining the parsed information.| +| Name| Type | Mandatory| Description | +| ------ | ----------------------------- | ---- | -------------------------------- | +| option | [ParseOptions](#parseoptions) | Yes | Options for controlling and obtaining the parsed information.| **Example** @@ -372,13 +372,13 @@ Defines the XML parsing options. **System capability**: SystemCapability.Utils.Lang -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| supportDoctype | boolean | No| Whether to ignore **Doctype**. The default value is **false**.| -| ignoreNameSpace | boolean | No| Whether to ignore **Namespace**. The default value is **false**.| -| tagValueCallbackFunction | (name: string, value: string)=> boolean | No| Callback used to return **tagValue**.| -| attributeValueCallbackFunction | (name: string, value: string)=> boolean | No| Callback used to return **attributeValue**.| -| tokenValueCallbackFunction | (eventType: [EventType](#eventtype), value: [ParseInfo](#parseinfo))=> boolean | No| Callback used to return **tokenValue**.| +| Name | Type | Mandatory| Description | +| ------------------------------ | ------------------------------------------------------------ | ---- | --------------------------------------- | +| supportDoctype | boolean | No | Whether to ignore **Doctype**. The default value is **false**.| +| ignoreNameSpace | boolean | No | Whether to ignore **Namespace**. The default value is **false**. | +| tagValueCallbackFunction | (name: string, value: string) => boolean | No | Callback used to return **tagValue**. | +| attributeValueCallbackFunction | (name: string, value: string) => boolean | No | Callback used to return **attributeValue**. | +| tokenValueCallbackFunction | (eventType: [EventType](#eventtype), value: [ParseInfo](#parseinfo)) => boolean | No | Callback used to return **tokenValue**. | ## ParseInfo @@ -395,8 +395,8 @@ Obtains the column line number, starting from 1. **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------ | -------------- | | number | Column number obtained.| @@ -410,8 +410,8 @@ Obtains the depth of this element. **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------ | -------------------- | | number | Depth obtained.| @@ -425,8 +425,8 @@ Obtains the current line number, starting from 1. **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------ | -------------- | | number | Line number obtained.| @@ -440,8 +440,8 @@ Obtains the name of this element. **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------ | ------------------ | | string | Element name obtained.| @@ -455,8 +455,8 @@ Obtains the namespace of this element. **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------ | ------------------------ | | string | Namespace obtained.| @@ -470,8 +470,8 @@ Obtains the prefix of this element. **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------ | ------------------ | | string | Element prefix obtained.| @@ -485,8 +485,8 @@ Obtains the text of the current event. **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------ | ------------------------ | | string | Text content obtained.| @@ -500,8 +500,8 @@ Checks whether the current element is empty. **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------- | ---------------------------- | | boolean | Returns **true** if the element is empty; returns **false** otherwise.| @@ -515,8 +515,8 @@ Checks whether the current text event contains only whitespace characters. **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------- | -------------------------------------- | | boolean | Returns **true** if the text event contains only whitespace characters; returns **false** otherwise.| @@ -529,8 +529,8 @@ Obtains the number of attributes for the current start tag. **System capability**: SystemCapability.Utils.Lang **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------ | ---------------------- | | number | Number of attributes obtained.| @@ -540,16 +540,16 @@ Enumerates the events. **System capability**: SystemCapability.Utils.Lang -| Name| Value| Description| -| -------- | -------- | -------- | -| START_DOCUMENT | 0 | Indicates a start document event.| -| END_DOCUMENT | 1 | Indicates an end document event.| -| START_TAG | 2 | Indicates a start tag event.| -| END_TAG | 3 | Indicates an end tag event.| -| TEXT | 4 | Indicates a text event.| -| CDSECT | 5 | Indicates a CDATA section event.| -| COMMENT | 6 | Indicates an XML comment event.| -| DOCDECL | 7 | Indicates an XML document type declaration event.| -| INSTRUCTION | 8 | Indicates an XML processing instruction event.| -| ENTITY_REFERENCE | 9 | Indicates an entity reference event.| -| WHITESPACE | 10 | Indicates a whitespace character event.| +| Name | Value | Description | +| ---------------- | ---- | --------------------- | +| START_DOCUMENT | 0 | Indicates a start document event. | +| END_DOCUMENT | 1 | Indicates an end document event. | +| START_TAG | 2 | Indicates a start tag event. | +| END_TAG | 3 | Indicates an end tag event. | +| TEXT | 4 | Indicates a text event. | +| CDSECT | 5 | Indicates a CDATA section event. | +| COMMENT | 6 | Indicates an XML comment event. | +| DOCDECL | 7 | Indicates an XML document type declaration event.| +| INSTRUCTION | 8 | Indicates an XML processing instruction event.| +| ENTITY_REFERENCE | 9 | Indicates an entity reference event. | +| WHITESPACE | 10 | Indicates a whitespace character event. | diff --git a/en/application-dev/reference/apis/js-apis-zlib.md b/en/application-dev/reference/apis/js-apis-zlib.md index bc2a9504185453888cf8ba53416f38a44519c5a2..aa7d700534b09bb582ca96d61740fdd6ff9681b9 100644 --- a/en/application-dev/reference/apis/js-apis-zlib.md +++ b/en/application-dev/reference/apis/js-apis-zlib.md @@ -1,4 +1,4 @@ -# zlib +# @ohos.zlib The **zlib** module provides APIs for file compression and decompression. @@ -25,7 +25,7 @@ Zips a file. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ------- | ------------------- | ---- | ------------------------------------------------------------ | -| inFile | string | Yes | Path of the folder or file to zip. For details about the path, see [FA Model](js-apis-Context.md) or [Stage Model](js-apis-application-context.md).| +| inFile | string | Yes | Path of the folder or file to zip. For details about the path, see [FA Model](js-apis-inner-app-context.md) or [Stage Model](js-apis-application-context.md).| | outFile | string | Yes | Path of the zipped file. The file name extension is .zip. | | options | [Options](#options) | Yes | Optional parameters for the zip operation. | @@ -89,7 +89,7 @@ Unzips a file. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ------- | ------------------- | ---- | ------------------------------------------------------------ | -| inFile | string | Yes | Path of the folder or file to unzip. For details about the path, see [FA Model](js-apis-Context.md) or [Stage Model](js-apis-application-context.md).| +| inFile | string | Yes | Path of the folder or file to unzip. For details about the path, see [FA Model](js-apis-inner-app-context.md) or [Stage Model](js-apis-application-context.md).| | outFile | string | Yes | Path of the unzipped file. | | options | [Options](#options) | Yes | Optional parameters for the unzip operation. | @@ -131,7 +131,7 @@ Compresses a file. This API uses an asynchronous callback to return the result. | Name | Type | Mandatory| Description | | ----------------------- | ------------------- | ---- | ------------------------------------------------------------ | -| inFile | string | Yes | Path of the folder or file to compress. For details about the path, see [FA Model](js-apis-Context.md) or [Stage Model](js-apis-application-context.md).| +| inFile | string | Yes | Path of the folder or file to compress. For details about the path, see [FA Model](js-apis-inner-app-context.md) or [Stage Model](js-apis-application-context.md).| | outFile | string | Yes | Path of the compressed file. | | options | [Options](#options) | Yes | Compression parameters. | | AsyncCallback<**void**> | callback | No | Callback used to return the result. If the operation is successful, **null** is returned; otherwise, a specific error code is returned. | @@ -179,7 +179,7 @@ Compresses a file. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ------- | ------------------- | ---- | ------------------------------------------------------------ | -| inFile | string | Yes | Path of the folder or file to compress. For details about the path, see [FA Model](js-apis-Context.md) or [Stage Model](js-apis-application-context.md).| +| inFile | string | Yes | Path of the folder or file to compress. For details about the path, see [FA Model](js-apis-inner-app-context.md) or [Stage Model](js-apis-application-context.md).| | outFile | string | Yes | Path of the compressed file. | | options | [Options](#options) | Yes | Compression parameters. | @@ -229,7 +229,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. For details about the path, see [FA Model](js-apis-Context.md) or [Stage Model](js-apis-application-context.md).| +| inFile | string | Yes | Path of the file to decompress. For details about the path, see [FA Model](js-apis-inner-app-context.md) or [Stage Model](js-apis-application-context.md).| | outFile | string | Yes | Path of the decompressed file. | | options | [Options](#options) | Yes | Decompression parameters. | | AsyncCallback<**void**> | callback | No | Callback used to return the result. If the operation is successful, **null** is returned; otherwise, a specific error code is returned. | @@ -278,7 +278,7 @@ Decompress a file. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ------- | ------------------- | ---- | ------------------------------------------------------------ | -| inFile | string | Yes | Path of the file to decompress. For details about the path, see [FA Model](js-apis-Context.md) or [Stage Model](js-apis-application-context.md).| +| inFile | string | Yes | Path of the file to decompress. For details about the path, see [FA Model](js-apis-inner-app-context.md) or [Stage Model](js-apis-application-context.md).| | outFile | string | Yes | Path of the decompressed file. | | options | [Options](#options) | Yes | Decompression parameters. | diff --git a/en/application-dev/reference/arkui-js/figures/2.png b/en/application-dev/reference/arkui-js/figures/2.png deleted file mode 100644 index e506fd8f37b0e522d5925b509def595e5db653c3..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/2.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/3.png b/en/application-dev/reference/arkui-js/figures/3.png deleted file mode 100644 index 495f967777f91ce6e654c278683807ef6560809c..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/3.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125114.gif b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125114.gif deleted file mode 100644 index f4d097a34aef9e583651d11133dff575345f0272..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125114.gif and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001152610806.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001152610806.png index b3a47a84d8086ca0806bc958f745f29821c47cc2..30ab31575654579e9a00a64d3d67f7420662f203 100644 Binary files a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001152610806.png and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001152610806.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001152862510.gif b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001152862510.gif deleted file mode 100644 index 6641ac7b1a0108d46bed16e64d65369c3515e8fb..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001152862510.gif and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001176075554.gif b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001176075554.gif new file mode 100644 index 0000000000000000000000000000000000000000..16e7ff213bd5caf5a9802001d3ced2996c66e0bc Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001176075554.gif differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001214619417.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001214619417.png index 5da42e3e14d601745274cb62d914c6600620bb25..4f6c19892155444ecf63dab3ca80575a8046cc1b 100644 Binary files a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001214619417.png and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001214619417.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001214704759.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001214704759.png index 6afdd1b39e4bcb3664c7664a55b47b8537f4aeaa..0b4837fc44abc0e1005de3d1259ed924f2969806 100644 Binary files a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001214704759.png and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001214704759.png differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001214811029.png b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001214811029.png index 1d71cee4618f1f2822cea1031c9b0e5d602e0a9b..447e5b819bdddc57b98ccf7629d612eb499aec8b 100644 Binary files a/en/application-dev/reference/arkui-js/figures/en-us_image_0000001214811029.png and b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001214811029.png differ diff --git a/en/application-dev/reference/arkui-js/figures/pickerview1.gif b/en/application-dev/reference/arkui-js/figures/pickerview1.gif new file mode 100644 index 0000000000000000000000000000000000000000..e255be05356073aa2cd2a8cf1fe9080da0cce7bf Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/pickerview1.gif differ diff --git a/en/application-dev/reference/arkui-js/figures/pickerview2.gif b/en/application-dev/reference/arkui-js/figures/pickerview2.gif new file mode 100644 index 0000000000000000000000000000000000000000..ab30fdac7ab76ea4759a61c52cb326b53396d1dc Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/pickerview2.gif differ diff --git a/en/application-dev/reference/arkui-js/figures/pickerview5.gif b/en/application-dev/reference/arkui-js/figures/pickerview5.gif new file mode 100644 index 0000000000000000000000000000000000000000..fd3a65d962df54eca02bd0a30c06bc1254c11df7 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/pickerview5.gif differ diff --git a/en/application-dev/reference/arkui-js/figures/rainbow.gif b/en/application-dev/reference/arkui-js/figures/rainbow.gif new file mode 100644 index 0000000000000000000000000000000000000000..2dd14c106005c014e3daa8b6132f610280d06516 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/rainbow.gif differ diff --git a/en/application-dev/reference/arkui-js/figures/slider.png b/en/application-dev/reference/arkui-js/figures/slider.png index d0167fe6773371fa70d8bf32c3a3953ed1e1455b..be1ee572a931ec2f06614e5f17c5616eba462e85 100644 Binary files a/en/application-dev/reference/arkui-js/figures/slider.png and b/en/application-dev/reference/arkui-js/figures/slider.png differ diff --git a/en/application-dev/reference/arkui-js/figures/stepper.gif b/en/application-dev/reference/arkui-js/figures/stepper.gif new file mode 100644 index 0000000000000000000000000000000000000000..cfaa06512dacaa75acbc26a65f040c1b1caf32ff Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/stepper.gif differ diff --git a/en/application-dev/reference/arkui-js/figures/switch.gif b/en/application-dev/reference/arkui-js/figures/switch.gif new file mode 100644 index 0000000000000000000000000000000000000000..1ba8e3e6401faf9c70fe97e4a2eac2181eeec974 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/switch.gif differ diff --git a/en/application-dev/reference/arkui-js/figures/text.png b/en/application-dev/reference/arkui-js/figures/text.png new file mode 100644 index 0000000000000000000000000000000000000000..65f36bddf4015f870e67edf7a96d1457014d1b3c Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/text.png differ diff --git a/en/application-dev/reference/arkui-js/js-components-basic-button.md b/en/application-dev/reference/arkui-js/js-components-basic-button.md index 29061668cc3ddd2c59a2b057a97bb09970807693..bec475bb4689aea314bb6e251e3d270da78000f2 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-button.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-button.md @@ -18,7 +18,7 @@ In addition to the [universal attributes](../arkui-js/js-components-common-attri | Name | Type | Default Value | Mandatory | Description | | ---------------------- | ------- | ----- | ---- | ---------------------------------------- | -| type | string | - | No | Button type. The value cannot be dynamically updated. If this attribute is not set, a capsule-like button is displayed. Unlike the capsule button, the capsule-like button allows its corners to be configured using **border-radius**. Available button types are as follows:
- **capsule**: capsule button with fillets, background color, and text.
- **circle**: circle button that can accommodate icons.
- **text**: text button, which displays only text.
- **arc**: arc button. This value is applicable to wearables only.
- **download**: download button, with an extra download progress bar.| +| type | string | - | No | Button type. The value cannot be dynamically updated. By default, a capsule-like button is displayed. Unlike the capsule button, the capsule-like button allows its corners to be configured using **border-radius**. The options are as follows:
- **capsule**: capsule button with fillets, background color, and text.
- **circle**: circle button that can accommodate icons.
- **text**: text button, which displays only text.
- **arc**: arc button. This value is applicable to wearables only.
- **download**: download button, with an extra download progress bar.| | value | string | - | No | Text value of the button. | | icon | string | - | No | Path of the button icon. The supported icon formats are JPG, PNG, and SVG. | | placement5+ | string | end | No | Position of the button icon in text. This attribute is valid only when **type** is not set. Available values are as follows:
- **start**: The button icon is at the beginning of the text.
- **end**: The button icon is at the end of the text.
- **top**: The button icon is at the top of the text.
- **bottom**: The button icon is at the bottom of the text.| @@ -39,7 +39,7 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md | allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings.
If the **config-changes** tag of **fontSize** is configured for abilities in the **config.json** file, the setting takes effect without application restart.| | font-style | string | normal | No | Font style of the button. | | font-weight | number \| string | normal | No | Font weight of the button. For details, see **font-weight** of the [**\** component](../arkui-js/js-components-basic-text.md#styles).| -| font-family | <string> | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text. | +| font-family | <string> | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text.| | icon-width | <length> | - | No | Width of the internal icon of a circle button. The entire circle button is filled by default.
This style must be set when the icon uses the SVG image.| | icon-height | <length> | - | No | Height of the internal icon of a circle button. The entire circle button is filled by default.
This style must be set when the icon uses the SVG image.| | radius | <length> | - | No | Corner radius of the button. For a circle button, this style takes precedence over **width** and **height** in the universal styles.| @@ -55,8 +55,8 @@ In addition to the **background-color**, **opacity**, **display**, **visibility* | font-size | <length> | 37.5px | No | Font size of the arc button. | | allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings. | | font-style | string | normal | No | Font style of the arc button. | -| font-weight | number \| string | normal | No | Font weight of the arc button. For details, see **font-weight** of the [**\** component](../arkui-js/js-components-basic-text.md#styles).| -| font-family | <string> | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text. | +| font-weight | number \| string | normal | No | Font weight of the arc button. For details, see **font-weight** of the [**\**](../arkui-js/js-components-basic-text.md#styles) component. | +| font-family | <string> | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text.| ## Events diff --git a/en/application-dev/reference/arkui-js/js-components-basic-chart.md b/en/application-dev/reference/arkui-js/js-components-basic-chart.md index 26ac1ef03d97536474103465f8f61cc5108ab126..a11c5aaabf8fa65f15399d5e8b13d9e040e77397 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-chart.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-chart.md @@ -22,7 +22,7 @@ In addition to the [universal attributes](../arkui-js/js-components-common-attri | Name | Type | Default Value | Mandatory | Description | | ------------------------------ | ---------------------------------------- | ---- | ---- | ---------------------------------------- | -| type | string | line | No | Chart type. Dynamic modification is not supported. Available values include:
- **bar**: bar chart.
- **line**: line chart.
- **gauge**: gauge chart.
- **progress**5+: circle chart of progresses.
- **loading**5+: circle chart of loading processes.
- **rainbow**5+: circle chart of proportions.| +| type | string | line | No | Chart type. Dynamic modification is not supported. Available values include:
- **bar**: bar chart
- **line**: line chart
- **gauge**: gauge chart
- **progress**5+: circle chart of progresses
- **loading**5+: circle chart of loading processes
- **rainbow**5+: circle chart of proportions| | options | ChartOptions | - | No | Chart parameters. You must set parameters for bar charts and line charts. Parameter settings for gauge charts do not take effect. You can set the minimum value, maximum value, scale, and line width of the x-axis or y-axis, whether to display the x-axis and y-axis, and whether the line is smooth. Dynamic modification is not supported.| | datasets | Array<ChartDataset> | - | No | Data sets. You must set data sets for bar charts and line charts. Data sets for a gauge chart do not take effect. You can set multiple datasets and their background colors.| | segments5+ | DataSegment \| Array<DataSegment> | - | No | Data structures used by **progress**, **loading**, and **rainbow** charts.
**DataSegment** is available for **progress** and **loading** charts.
**Array<DataSegment>** is available for **rainbow** charts. A maximum of nine **DataSegment**s are supported in the array.| @@ -99,7 +99,7 @@ In addition to the [universal attributes](../arkui-js/js-components-common-attri | description | string | - | No | Description text of the point. | | textLocation | string | - | No | Position of the description text relative to the point. Available values are as follows: **top**: above the point
**bottom**: below the point
**none**: not displayed| | textColor | <color> | \#000000 | No | Color of the description text. | -| lineDash | string | solid | No | Dashed line pattern. You can set the dash length and space length between the dashes. For example, **"dashed, 5, 5"** indicates a dashed line with each dash in 5 px and a 5 px space between each two dashes. Default value **"solid"** indicates a solid line.| +| lineDash | string | solid | No | Dashed line pattern. You can set the dash length and space length between the dashes. - **"dashed, 5, 5"**: dashed line with each dash in 5 px and a 5 px space between each two dashes. Default value **"solid"** indicates a solid line.| | lineColor | <color> | \#000000 | No | Line color. If this attribute is not set, the value of **strokeColor** is used. | **Table 9** DataSegment5+ @@ -144,7 +144,7 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md | center-x | <length> | - | No | Center of the scale bar of the gauge component. This style is supported by the gauge chart only. This style takes precedence over the **position** style in the common styles, and must be used together with **center-y** and **radius**. This style is supported by the gauge chart only.| | center-y | <length> | - | No | Center of the scale bar of the gauge component. This style is supported by the gauge chart only. This style takes precedence over the **position** style in the common styles, and must be used together with **center-x** and **radius**. This style is supported by the gauge chart only.| | radius | <length> | - | No | Radius of the scale bar of the gauge component. This style is supported by the gauge chart only. This style takes precedence over the **width** and **height** in the common styles, and must be used together with **center-x** and **center-y**. This style is supported by the gauge chart only.| -| colors | Array | - | No | Color of each section for the scale bar of the gauge component.
For example, **colors: \#ff0000, #00ff00**. This style is supported by the gauge chart only.| +| colors | Array | - | No | Color of each section for the scale bar of the gauge component.
For example, **colors: \#ff0000, \#00ff00**. This style is supported by the gauge chart only.| | weights | Array | - | No | Weight of each section for the scale bar of the gauge component.
For example, **weights: 2, 2**. This style is supported by the gauge chart only.| | font-family5+ | Array | - | No | Font style of the description text. You can use a [custom font](../arkui-js/js-components-common-customizing-font.md).| | font-size5+ | <length> | - | No | Font size of the description text. | @@ -161,7 +161,7 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods. | Name | Parameter | Description | | ------ | ---------------------------------------- | ---------------------------------------- | -| append | {
serial: number, // Set the data subscript of the line chart to be updated.
data: Array<number>, // Set the new data.
} | Data is dynamically added to an existing data sequence. The target sequence is specified based on **serial**, which is the subscript of the datasets array and starts from 0. **datasets[index].data** is not updated. Only line charts support this attribute. The value is incremented by 1 based on the horizontal coordinate and is related to the **xAxis min/max** setting.| +| append | {
serial: number,
data: Array<number>,
} | Data is dynamically added to an existing data sequence. The target sequence is specified based on **serial**, which is the subscript of the datasets array and starts from 0. For example, if the value of **serial** is **index**, use **data** to update **datasets[index].data**. Only line charts support this attribute. The value is incremented by 1 based on the horizontal coordinate and is related to the **xAxis min/max** setting.| ## Example @@ -212,24 +212,24 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods. strokeColor: '#0081ff', fillColor: '#cce5ff', data: [763, 550, 551, 554, 731, 654, 525, 696, 595, 628, 791, 505, 613, 575, 475, 553, 491, 680, 657, 716], - gradient: true, + gradient: true } ], lineOps: { xAxis: { min: 0, max: 20, - display: false, + display: false }, yAxis: { min: 0, max: 1000, - display: false, + display: false }, series: { lineStyle: { width: "5px", - smooth: true, + smooth: true }, headPoint: { shape: "circle", @@ -237,14 +237,14 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods. strokeWidth: 5, fillColor: '#ffffff', strokeColor: '#007aff', - display: true, + display: true }, loop: { margin: 2, - gradient: true, + gradient: true } } - }, + } }, addData() { this.$refs.linechart.append({ @@ -295,15 +295,15 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods. barData: [ { fillColor: '#f07826', - data: [763, 550, 551, 554, 731, 654, 525, 696, 595, 628], + data: [763, 550, 551, 554, 731, 654, 525, 696, 595, 628] }, { fillColor: '#cce5ff', - data: [535, 776, 615, 444, 694, 785, 677, 609, 562, 410], + data: [535, 776, 615, 444, 694, 785, 677, 609, 562, 410] }, { fillColor: '#ff88bb', - data: [673, 500, 574, 483, 702, 583, 437, 506, 693, 657], + data: [673, 500, 574, 483, 702, 583, 437, 506, 693, 657] }, ], barOps: { @@ -311,14 +311,14 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods. min: 0, max: 20, display: false, - axisTick: 10, + axisTick: 10 }, yAxis: { min: 0, max: 1000, - display: false, - }, - }, + display: false + } + } } } ``` @@ -353,3 +353,76 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods. ``` ![en-us_image_0000001127125264](figures/en-us_image_0000001127125264.png) + +4. Circle chart of progresses, loading progresses, or proportions + ```html + +
+ progress Example + + + + loading Example + + + + rainbow Example + + + +
+ ``` + ```css + /* xxx.css */ + .container { + flex-direction: column; + justify-content: center; + align-items: center; + } + .chart-region { + height: 400px; + width: 700px; + margin-top: 10px; + } + .text { + margin-top: 30px; + } + ``` + ```js + // xxx.js + export default { + data: { + progressdata: { + value: 50, + name: 'progress' + }, + loadingdata: { + startColor: "#ffc0cb", + endColor: "#00bfff", + }, + rainbowdata: [ + { + value: 50, + name: 'item1' + }, + { + value: 10, + name: 'item2' + }, + { + value: 20, + name: 'item3' + }, + { + value: 10, + name: 'item4' + }, + { + value: 10, + name: 'item5' + } + ] + } + } + ``` + ![rainbow](figures/rainbow.gif) diff --git a/en/application-dev/reference/arkui-js/js-components-basic-image.md b/en/application-dev/reference/arkui-js/js-components-basic-image.md index 53b335e34c30317f99f789bd22358bad5d8ad279..89643b3aaa104e4f15b91db6098e74611c1aa42d 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-image.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-image.md @@ -31,7 +31,7 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md | object-fit | string | cover | No | Image scale type. This style is not supported for SVG images. For details about available values, see **object-fit**.| | match-text-direction | boolean | false | No | Whether image orientation changes with the text direction. This style is not supported for SVG images. | | fit-original-size | boolean | false | No | Whether the **\** component adapts to the image source size when its width and height are not set. If this style is set to **true**, **object-fit** will not take effect. This style is not supported for SVG images.| -| object-position7+ | string | 0px 0px | No | Position of an image in the component.
The options are as follows:
1. Pixels. For example, **15px 15px** indicates the moving position along the x-axis or y-axis.
2. Characters. Optional values are as follows:
- **left**: The image is displayed on the left of the component.
- **top** The image is displayed on the top of the component.
- **right** The image is displayed on the right of the component.
- **bottom** The image is displayed at the bottom of the component.| +| object-position7+ | string | 0px 0px | No | Position of the image in the component.
The options are as follows:
1. Pixels, in px. For example, **15px 15px** indicates the position to move along the x-axis or y-axis.
2. Characters. Optional values are as follows:
- **left**: The image is displayed on the left of the component.<
- **top**: The image is displayed on the top of the component.
- **right**: The image is displayed on the right of the component.
- **bottom**: The image is displayed at the bottom of the component.| **Table 1** object-fit @@ -56,16 +56,18 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md > 1. If the **\** component is too small to afford the SVG image, the SVG image is cropped and only its upper left part is displayed in the component. > > 2. If the **\** component is big enough to afford the SVG image, this SVG image is displayed in the upper left corner of the component. +> +> - For SVG images, only the following tags are included in the supported list: **svg**, **rect**, **circle**, **ellipse**, **path**, **line**, **polyline**, **polygon**, **animate**, **animateMotion**, and **animateTransform**. ## Events In addition to the [universal events](../arkui-js/js-components-common-events.md), the following events are supported. -| Name | Parameter | Description | -| -------------- | ---------------------------------------- | ------------------------- | -| complete(Rich) | {
width: width,
height: height
} | Triggered when an image is successfully loaded. The loaded image size is returned.| -| error(Rich) | {
width: width,
height: height
} | Triggered when an exception occurs during image loading. In this case, the width and height are **0**. | +| Name | Parameter | Description | +| -------- | ---------------------------------------- | ------------------------- | +| complete | {
width: width,
height: height
} | Triggered when an image is successfully loaded. The loaded image size is returned.| +| error | {
width: width,
height: height
} | Triggered when an exception occurs during image loading. In this case, the width and height are **0**. | ## Methods diff --git a/en/application-dev/reference/arkui-js/js-components-basic-input.md b/en/application-dev/reference/arkui-js/js-components-basic-input.md index 2ce4c7d3b07a6e8dbdcd47c4d3143ec8e4b285df..13c42c2f80fe31b010cf38829a6d3a388bb19629 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-input.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-input.md @@ -20,44 +20,44 @@ Not supported In addition to the [universal attributes](../arkui-js/js-components-common-attributes.md), the following attributes are supported. -| Name | Type | Default Value | Mandatory | Description | -| -------------------------------- | ----------------------- | ------------- | --------- | ---------------------------------------- | -| type | string | text
| No | Type of the input component. Available values include **text**, **email**, **date**, **time**, **number**, **password**, **button**, **checkbox**, and **radio**.
The **text**, **email**, **date**, **time**, **number**, and **password** types can be dynamically switched and modified.
The **button**, **checkbox**, and **radio** types cannot be dynamically modified.
- **button**: a button that can be clicked.
- **checkbox**: a check box.
- **radio**: a radio button that allows users to select one from multiple others with the same name.
- **text**: a single-line text field.
- **email**: a field used for an email address.
- **date**: date component, including the year, month, and day, but excluding time.
- **time**: time component, without the time zone.
- **number**: field for entering digits.
- **password**: password field, in which characters will be shielded. | -| checked | boolean | false | No | Whether the **\** component is selected. This attribute is valid only when **type** is set to **checkbox** or **radio**. | -| name | string | - | No | Name of the **\** component.
This attribute is mandatory when **type** is set to **radio**. | -| value | string | - | No | Value of the **\** component. When **type** is **radio**, this attribute is mandatory and the value must be unique for radio buttons with the same name. | -| placeholder | string | - | No | Content of the hint text. This attribute is available only when the component type is set to **text** \|email\|date\|time\|number\|**password**. | -| maxlength | number | - | No | Maximum number of characters that can be entered in the input box. The empty value indicates no limit. | -| enterkeytype | string | default | No | Type of the **Enter** key on the soft keyboard. The value cannot be dynamically updated.
Available values include:
- default
- next
- go
- done
- send
- search
Except for the **next** type, clicking the Enter key hides the soft keyboard. | -| headericon | string | - | No | Icon resource path before text input. This icon does not support click events and is unavailable for **button**, **checkbox**, and **radio** types. The supported icon image formats are JPG, PNG, and SVG. | -| showcounter5+ | boolean | false | No | Whether to display the character counter for an input box. This attribute takes effect only when **maxlength** is set. | -| menuoptions5+ | Array<MenuOption> | - | No | Menu options displayed after users click the **More** button. | -| autofocus6+ | boolean | false | No | Whether to automatically obtain focus.
This attribute setting does not take effect on the application home page. You can enable a text box on the home page to automatically obtain focus, by delaying the **focus** method call (for about 100–500 ms) in **onActive**. | -| selectedstart6+ | number | -1 | No | Start position for text selection. | -| selectedend6+ | number | -1 | No | End position for text selection. | -| softkeyboardenabled6+ | boolean | true | No | Whether to display the soft keyboard during editing. | -| showpasswordicon6+ | boolean | true | No | Whether to display the icon at the end of the password text box. This attribute is available only when **type** is set to **password**. | +| Name | Type | Default Value | Mandatory | Description | +| -------------------------------- | ----------------------- | --------- | ---- | ---------------------------------------- | +| type | string | text
| No | Type of the input component. Available values include **text**, **email**, **date**, **time**, **number**, **password**, **button**, **checkbox**, and **radio**.
The **text**, **email**, **date**, **time**, **number**, and **password** types can be dynamically switched and modified.
The **button**, **checkbox**, and **radio** types cannot be dynamically modified.
- **button**: a button that can be clicked.
- **checkbox**: a check box.
- **radio**: a radio button that allows users to select one from multiple others with the same name.
- **text**: a single-line text field.
- **email**: a field used for an email address.
- **date**: date component, including the year, month, and day, but excluding time.
- **time**: time component, without the time zone.
- **number**: field for entering digits.
- **password**: password field, in which characters will be shielded.| +| checked | boolean | false | No | Whether the **\** component is selected. This attribute is valid only when **type** is set to **checkbox** or **radio**. | +| name | string | - | No | Name of the **\** component.
This attribute is mandatory when **type** is set to **radio**. | +| value | string | - | No | Value of the **\** component. When **type** is **radio**, this attribute is mandatory and the value must be unique for radio buttons with the same name.| +| placeholder | string | - | No | Content of the hint text. This attribute is available only when the component type is set to **text** \|email\|date\|time\|number\|**password**.| +| maxlength | number | - | No | Maximum number of characters that can be entered in the input box. The empty value indicates no limit. | +| enterkeytype | string | default | No | Type of the **Enter** key on the soft keyboard. The value cannot be dynamically updated.
Available values include:
- default
- next
- go
- done
- send
- search
Except for the **next** type, clicking the Enter key hides the soft keyboard.| +| headericon | string | - | No | Icon resource path before text input. This icon does not support click events and is unavailable for **button**, **checkbox**, and **radio** types. The supported icon image formats are JPG, PNG, and SVG.| +| showcounter5+ | boolean | false | No | Whether to display the character counter for an input box. This attribute takes effect only when **maxlength** is set. | +| menuoptions5+ | Array<MenuOption> | - | No | Menu options displayed after users click the **More** button. | +| autofocus6+ | boolean | false | No | Whether to automatically obtain focus.
This attribute setting does not take effect on the application home page. You can enable a text box on the home page to automatically obtain focus, by delaying the **focus** method call (for about 100–500 ms) in **onActive**.| +| selectedstart6+ | number | -1 | No | Start position for text selection. | +| selectedend6+ | number | -1 | No | End position for text selection. | +| softkeyboardenabled6+ | boolean | true | No | Whether to display the soft keyboard during editing. | +| showpasswordicon6+ | boolean | true | No | Whether to display the icon at the end of the password text box. This attribute is available only when **type** is set to **password**. | **Table 1** MenuOption5+ -| Name | Type | Description | -| ------- | ------ | ----------------------------------- | -| icon | string | Path of the icon for a menu option. | -| content | string | Text content of a menu option. | +| Name | Type | Description | +| ------- | ------ | ----------- | +| icon | string | Path of the icon for a menu option.| +| content | string | Text content of a menu option.| ## Styles In addition to the [universal styles](../arkui-js/js-components-common-styles.md), the following styles are supported. -| Name | Type | Default Value | Mandatory | Description | -| ------------------------ | ---------------- | ------------- | --------- | ---------------------------------------- | -| color | <color> | \#e6000000 | No | Font color of the single-line text box or button. | -| font-size | <length> | 16px | No | Font size of the single-line text box or button. | -| allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings.
If the **config-changes** tag of **fontSize** is configured for abilities in the **config.json** file, the setting takes effect without application restart. | -| placeholder-color | <color> | \#99000000 | No | Color of the hint text in the single-line text box. This attribute is available only when **type** is set to **text**, **email**, **date**, **time**, **number**, or **password**. | -| font-weight | number \| string | normal | No | Font weight of the single-line text box or button. For details, see **font-weight** of the [**\**](../arkui-js/js-components-basic-text.md) component. | -| caret-color6+ | <color> | - | No | Color of the caret. | +| Name | Type | Default Value | Mandatory | Description | +| ------------------------ | -------------------------- | ---------- | ---- | ---------------------------------------- | +| color | <color> | \#e6000000 | No | Font color of the single-line text box or button. | +| font-size | <length> | 16px | No | Font size of the single-line text box or button. | +| allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings.
If the **config-changes** tag of **fontSize** is configured for abilities in the **config.json** file, the setting takes effect without application restart.| +| placeholder-color | <color> | \#99000000 | No | Color of the hint text in the single-line text box. This attribute is available only when the component type is set to **text**, **email**, **date**, **time**, **number**, or **password**. | +| font-weight | number \| string | normal | No | Font weight of the single-line text box or button. For details, see **font-weight** of the [**\**](../arkui-js/js-components-basic-text.md) component. | +| caret-color6+ | <color> | - | No | Color of the caret. | ## Events @@ -66,27 +66,27 @@ In addition to the [universal events](../arkui-js/js-components-common-events.md - When **type** is set to **text**, **email**, **date**, **time**, **number**, or **password**, the following events are supported. - | Name | Parameter | Description | + | Name | Parameter | Description | | ------------------------- | ---------------------------------------- | ---------------------------------------- | - | change | {
value: inputValue
} | Triggered when the content entered in the input box changes. The most recent content entered by the user is returned.
If you change the **value** attribute directly, this event will not be triggered. | - | enterkeyclick | {
value: enterKey
} | Triggered when the **Enter** key on the soft keyboard is clicked. The type of the **Enter** key is returned, which is of the number type. Available values are as follows:
- **2**: returned if **enterkeytype** is **go**.
- **3**: returned if **enterkeytype** is **search**.
- **4**: returned if **enterkeytype** is **send**.
- **5**: returned if **enterkeytype** is **next**.
- **6**: returned if **enterkeytype** is **default**, **done**, or is not set. | - | translate5+ | {
value: selectedText
} | Triggered when users click the translate button in the menu displayed after they select a text segment. The selected text content is returned. | - | share5+ | {
value: selectedText
} | Triggered when users click the share button in the menu displayed after they select a text segment. The selected text content is returned. | - | search5+ | {
value: selectedText
} | Triggered when users click the search button in the menu displayed after they select a text segment. The selected text content is returned. | - | optionselect5+ | {
index: optionIndex,
value: selectedText
} | Triggered when users click a menu option in the menu displayed after they select a text segment. This event is valid only when the **menuoptions** attribute is set. The option index and selected text content are returned. | - | selectchange6+ | {
start: number,
end: number
} | Triggered when the text selection changes. | + | change | {
value: inputValue
} | Triggered when the content entered in the input box changes. The most recent content entered by the user is returned.
If you change the **value** attribute directly, this event will not be triggered.| + | enterkeyclick | {
value: enterKey
} | Triggered when the **Enter** key on the soft keyboard is clicked. The type of the **Enter** key is returned, which is of the number type. Available values are as follows:
- **2**: returned if **enterkeytype** is **go**.
- **3**: returned if **enterkeytype** is **search**.
- **4**: returned if **enterkeytype** is **send**.
- **5**: returned if **enterkeytype** is **next**.
- **6**: returned if **enterkeytype** is **default**, **done**, or is not set.| + | translate5+ | {
value: selectedText
} | Triggered when users click the translate button in the menu displayed after they select a text segment. The selected text content is returned.| + | share5+ | {
value: selectedText
} | Triggered when users click the share button in the menu displayed after they select a text segment. The selected text content is returned.| + | search5+ | {
value: selectedText
} | Triggered when users click the search button in the menu displayed after they select a text segment. The selected text content is returned.| + | optionselect5+ | {
index: optionIndex,
value: selectedText
} | Triggered when users click a menu option in the menu displayed after they select a text segment. This event is valid only when the **menuoptions** attribute is set. The option index and selected text content are returned.| + | selectchange6+ | {
start: number,
end: number
} | Triggered when the text selection changes. | - When **type** is set to **checkbox** or **radio**, the following events are supported. - | Name | Parameter | Description | - | ------ | --------------------------------- | ---------------------------------------- | - | change | {
checked:true \| false
} | Triggered when the checked status of the **checkbox** or **radio** button changes. | + | Name | Parameter | Description | + | ------ | ---------------------------------------- | ---------------------------------------- | + | change | {
checked:true \| false
} | Triggered when the checked status of the **checkbox** or **radio** button changes.| ## Methods In addition to the [universal methods](../arkui-js/js-components-common-methods.md), the following methods are supported. -| Name | Parameter | Description | +| Name | Parameter | Description | | ------------------- | ---------------------------------------- | ---------------------------------------- | | focus | {
focus: true\|false
}:
If **focus** is not passed, the default value **true** is used. | Obtains or loses focus. When **type** is set to **text**, **email**, **date**, **time**, **number**, or **password**, the input method can be displayed or collapsed. | | showError | {
error: string
} | Displays the error message. This method is available when **type** is set to **text**, **email**, **date**, **time**, **number**, or **password**. | @@ -102,38 +102,40 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods. headericon="/common/search.svg" placeholder="Please input text" onchange="change" onenterkeyclick="enterkeyClick"> - + ``` ```css /* xxx.css */ .content { - width: 60%; + width: 100%; flex-direction: column; align-items: center; } .input { + width: 60%; placeholder-color: gray; } .button { + width: 60%; background-color: gray; margin-top: 20px; - } + } ``` - + ```js // xxx.js - import prompt from '@system.prompt' + import promptAction from '@ohos.promptAction' export default { change(e){ - prompt.showToast({ + promptAction.showToast({ message: "value: " + e.value, duration: 3000, }); }, enterkeyClick(e){ - prompt.showToast({ + promptAction.showToast({ message: "enterkey clicked", duration: 3000, }); @@ -143,11 +145,11 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods. error: 'error text' }); }, - } + } ``` ![1-2](figures/1-2.png) - + 2. Common button ```html @@ -190,10 +192,10 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods. ```js // xxx.js - import prompt from '@system.prompt' + import promptAction from '@ohos.promptAction' export default { checkboxOnChange(e) { - prompt.showToast({ + promptAction.showToast({ message:'checked: ' + e.checked, duration: 3000, }); @@ -225,11 +227,11 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods. ```js // xxx.js - import prompt from '@system.prompt' + import promptAction from '@ohos.promptAction' export default { onRadioChange(inputValue, e) { if (inputValue === e.value) { - prompt.showToast({ + promptAction.showToast({ message: 'The chosen radio is ' + e.value, duration: 3000, }); diff --git a/en/application-dev/reference/arkui-js/js-components-basic-label.md b/en/application-dev/reference/arkui-js/js-components-basic-label.md index 3adcd954efec63b002f90f923cd8fe5b5dfdd500..9a45521ecb6ed4d614ab43abafdcd6317c31530a 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-label.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-label.md @@ -35,8 +35,8 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md | font-size | <length> | 30px | No | Font size. | | allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings.
For details about how to make the configuration take effect dynamically, see the **config-changes** attribute in the **config.json** file.| | letter-spacing | <length> | 0px | No | Character spacing (px). | -| font-style | string | normal | No | Font style. Available values are as follows:
- **normal**: standard font style
- **italic**: italic font style| -| font-weight | number \| string | normal | No | Font width. For the number type, the value ranges from 100 to 900. The default value is 400. A larger value indicates a larger font width.
The value of the number type must be an integer multiple of 100.
The value of the string type can be **lighter**, **normal**, **bold**, or **bolder**.| +| font-style | string | normal | No | Font style. Available values are as follows:
- **normal**: standard font style.
- **italic**: italic font style.| +| font-weight | number \| string | normal | No | Font weight. For the number type, the value ranges from 100 to 900. The default value is 400. A larger value indicates a heavier font weight.
The value of the number type must be an integer multiple of 100.
The value of the string type can be **lighter**, **normal**, **bold**, or **bolder**.| | text-decoration | string | none | No | Text decoration. Available values are as follows:
- **underline**: An underline is used.
- **line-through**: A strikethrough is used.
- **none**: The standard text is used.| | text-align | string | start
| No | Text alignment mode. Available values are as follows:
- **left**: The text is left-aligned.
- **center**: The text is center-aligned.
- **right**: The text is right-aligned.
- **start**: The text is aligned with the direction in which the text is written.
- **end**: The text is aligned with the opposite direction in which the text is written.
If the text width is not specified, the alignment effect may not be obvious when the text width is the same as the width of the parent container.| | line-height | <length> | 0px | No | Text line height. When this parameter is set to **0px**, the text line height is not limited and the font size is adaptive. | @@ -46,7 +46,7 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md | min-font-size | <length> | - | No | Minimum font size in the text. This style must be used together with **max-font-size**. The font size can be changed dynamically. After the maximum and minimum font sizes are set, **font-size** does not take effect.| | max-font-size | <length> | - | No | Maximum font size in the text. This style must be used together with **min-font-size**. The font size can be changed dynamically. After the maximum and minimum font sizes are set, **font-size** does not take effect.| | font-size-step | <length> | 1px | No | Step for dynamically adjusting the font size in the text. The minimum and maximum font sizes must be set. | -| prefer-font-sizes | <array> | - | No | Preset preferred font sizes. For dynamic font size adjustment, the preset sizes are used to match the maximum number of lines in the text. If the preferred font sizes were not set, the font size will be adjusted based on the maximum and minimum font sizes and the step you have set. If the maximum number of lines in the text cannot be met, **text-overflow** is used to truncate the text. If this parameter is set, **font-size**, **max-font-size**, **min-font-size**, and **font-size-step** do not take effect.
Example values: **12px,14px,16px**| +| prefer-font-sizes | <array> | - | No | Preset preferred font sizes. For dynamic font size adjustment, the preset sizes are used to match the maximum number of lines in the text. If the preferred font sizes were not set, the font size will be adjusted based on the maximum and minimum font sizes and the step you have set. If the maximum number of lines in the text cannot be met, **text-overflow** is used to truncate the text. If this parameter is set, **font-size**, **max-font-size**, **min-font-size**, and **font-size-step** do not take effect.
Example: prefer-font-sizes: 12px,14px,16px| ## Events @@ -83,7 +83,7 @@ Not supported /*xxx.css */ .container { flex-direction: column; - align-items: center; + margin-left: 20px; } .row { flex-direction: row; diff --git a/en/application-dev/reference/arkui-js/js-components-basic-marquee.md b/en/application-dev/reference/arkui-js/js-components-basic-marquee.md index 9f13895436ce5f1104994f9d6956deba5e04a928..a1072111daa65e9eab0e528e086b8955efa66e09 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-marquee.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-marquee.md @@ -37,7 +37,7 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md | color | <color> | \#e5000000 | No | Font color of the scrolling text. | | font-size | <length> | 37.5 | No | Font size of the scrolling text. | | allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings.
If the **config-changes** tag of **fontSize** is configured for abilities in the **config.json** file, the setting takes effect without application restart.| -| font-weight | number \| string | normal | No | Font weight of the scrolling text. For details, see **font-weight** of the **[\ component](../arkui-js/js-components-basic-text.md#styles)**.| +| font-weight | number \| string | normal | No | Font weight of the scrolling text. For details, see **font-weight** of the **[\ component](../arkui-js/js-components-basic-text.md#styles)**.| | font-family | string | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text.| @@ -45,17 +45,17 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md In addition to the [universal events](../arkui-js/js-components-common-events.md), the following events are supported. -| Name | Parameter | Description | -| ------------ | ---- | ---------------------------------------- | -| bounce(Rich) | - | Triggered when the marquee scrolls to the end. | -| finish(Rich) | - | Triggered when the marquee finishes the specified number of scrollings (value of the **loop** attribute). It can be triggered only when the **loop** attribute is set to a number greater than 0.| -| start(Rich) | - | Triggered when the marquee starts to scroll. | +| Name | Parameter | Description | +| ------ | ---- | ---------------------------------------- | +| bounce | - | Triggered when the marquee scrolls to the end. | +| finish | - | Triggered when the marquee finishes the specified number of scrollings (value of the **loop** attribute). It can be triggered only when the **loop** attribute is set to a number greater than 0.| +| start | - | Triggered when the marquee starts to scroll. | ## Methods In addition to the [universal methods](../arkui-js/js-components-common-methods.md), the following methods are supported. -| Name | Parameter | Description | +| Name | Parameter | Description | | ----- | ---- | ----- | | start | - | Starts scrolling.| | stop | - | Stops scrolling.| @@ -65,72 +65,75 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods. ```html -
- {{marqueeCustomData}} -
- - +
+
+ + Life is a journey, not the destination. + +
+
+ +
``` ```css /* xxx.css */ -.container { +.tutorial-page { + width: 750px; + height: 100%; flex-direction: column; - justify-content: center; align-items: center; - background-color: #ffffff; + justify-content: center; } -.customMarquee { - width: 100%; - height: 80px; - padding: 10px; - margin: 20px; - border: 4px solid #ff8888; - border-radius: 20px; - font-size: 40px; - color: #ff8888; - font-weight: bolder; - font-family: serif; - background-color: #ffdddd; +.marqueetext { + font-size: 37px; } -.content { - flex-direction: row; +.mymarquee { + margin-top: 20px; + width:100%; + height: 100px; + margin-left: 50px; + margin-right: 50px; + border: 1px solid #dc0f27; + border-radius: 15px; + align-items: center; } -.controlButton { - flex-grow: 1; - background-color: #F2F2F2; - text-color: #0D81F2; +button{ + width: 200px; + height: 80px; + margin-top: 100px; } ``` ```js // xxx.js export default { - data: { - scrollAmount: 30, - loop: 3, - marqueeDir: 'left', - marqueeCustomData: 'Custom marquee', - }, - onMarqueeBounce: function() { - console.log("onMarqueeBounce"); + private: { + loopval: 1, + scroll: 8, + color1: 'red' }, - onMarqueeStart: function() { - console.log("onMarqueeStart"); + onInit(){ }, - onMarqueeFinish: function() { - console.log("onMarqueeFinish"); + setfinish(e) { + this.loopval= this.loopval + 1, + this.r = Math.floor(Math.random()*255), + this.g = Math.floor(Math.random()*255), + this.b = Math.floor(Math.random()*255), + this.color1 = 'rgba('+ this.r +','+ this.g +','+ this.b +',0.8)', + this.$element('testmarquee').start(), + this.loopval= this.loopval - 1 }, - onStartClick (evt) { - this.$element('customMarquee').start(); + makestart(e) { + this.$element('testmarquee').start() }, - onStopClick (evt) { - this.$element('customMarquee').stop(); + makestop(e) { + this.$element('testmarquee').stop() } } ``` -![lite_bar](figures/lite_bar.gif) +![zh-cn_image_0000001176075554](figures/zh-cn_image_0000001176075554.gif) diff --git a/en/application-dev/reference/arkui-js/js-components-basic-picker-view.md b/en/application-dev/reference/arkui-js/js-components-basic-picker-view.md index 426e227f9009c06b9e6c82f3344719c9d988e948..3f1ac6a278adeaea3059c930e3e5098fa8392374 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-picker-view.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-picker-view.md @@ -20,7 +20,7 @@ In addition to the [universal attributes](../arkui-js/js-components-common-attri | ---- | ------ | ---- | ---- | ---------------------------------------- | | type | string | text | No | Type of the scrollable selector, which cannot be changed dynamically. Available values are as follows:
- **text**: text selector.
- **time**: time selector.
- **date**: date selector.
- **datetime**: date and time selector.
- **multi-text**: multi-column text selector.| -Text selector (**type** is **text**) +### Text Selector | Name | Type | Default Value | Mandatory | Description | | --------------- | ------ | ---- | ---- | ---------------------------------------- | @@ -29,15 +29,15 @@ Text selector (**type** is **text**) | indicatorprefix | string | - | No | Prefix field added when a value is specified for the text selector. | | indicatorsuffix | string | - | No | Suffix field added when a value is specified for the text selector. | -Time selector (**type** is **time**) +### Time Selector | Name | Type | Default Value | Mandatory | Description | | ------------- | ------- | ----------------------------------- | ---- | ---------------------------------------- | | containsecond | boolean | false | No | Whether seconds are contained. | | selected | string | Current time | No | Default value of the time selector, in the format of HH:mm.
If seconds are contained, the format is HH:mm:ss.| -| hours | number | 241-4 | No | Time format used by the time selector. Available values are as follows:
- **12**: displayed in 12-hour format and distinguished by a.m. and p.m.
- **24**: displayed in 24-hour format.
Since API version 5, the default value is the most commonly-used hour format in the current locale.| +| hours | number | 241-4
-5+ | No | Time format used by the time selector. Available values are as follows:
- **12**: displayed in 12-hour format and distinguished by a.m. and p.m.
- **24**: displayed in 24-hour format.
Since API version 5, the default value is the most commonly-used hour format in the current locale.| -Date selector (**type** is **date**) +### Date Selector | Name | Type | Default Value | Mandatory | Description | | ------------------ | ------------ | ---------- | ---- | ---------------------------------------- | @@ -47,16 +47,16 @@ Date selector (**type** is **date**) | lunar5+ | boolean | false | No | Whether the pop-up window displays the lunar calendar. | | lunarswitch | boolean | false | No | Whether to display the lunar calendar switch in the date selector. When this switch is displayed, the user can switch between the lunar calendar and Gregorian calendar. Turn on the switch to display the lunar calendar, and turn off the switch to hide the lunar calendar.| -Date and time selector (**type** is **datetime**) +### Date and Time Selector | Name | Type | Default Value | Mandatory | Description | | ------------------ | ------- | ----------------------------------- | ---- | ---------------------------------------- | | selected | string | Current date and time | No | Default value of the date and time selector. The value can be in the format of MM-DD-HH-mm or YYYY-MM-DD-HH-mm. If the year is not set, the current year is used by default. The value you set is the date selected by default in the pop-up window.| -| hours | number | 241-4 | No | Time format used by the date and time selector. Available values are as follows:
- **12**: displayed in 12-hour format and distinguished by a.m. and p.m.
- **24**: displayed in 24-hour format.
Since API version 5, the default value is the most commonly-used hour format in the current locale.| +| hours | number | 241-4
-5+ | No | Time format used by the date and time selector. Available values are as follows:
- **12**: displayed in 12-hour format and distinguished by a.m. and p.m.
- **24**: displayed in 24-hour format.
Since API version 5, the default value is the most commonly-used hour format in the current locale.| | lunar5+ | boolean | false | No | Whether the pop-up window displays the lunar calendar. | | lunarswitch | boolean | false | No | Whether to display the lunar calendar switch in the date and time selector. When this switch is displayed, the user can switch between the lunar calendar and Gregorian calendar. Turn on the switch to display the lunar calendar, and turn off the switch to hide the lunar calendar.| -Multi-column text selector (**type** is **multi-text**) +### Multi-Column Text Selector | Name | Type | Default Value | Mandatory | Description | | -------- | ------- | --------- | ---- | ---------------------------------------- | @@ -77,42 +77,42 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md | selected-font-size | <length> | 20px | No | Font size of the selected item. The value is of the length type, in pixels. | | disappear-color5+ | <color> | \#ffffff | No | Font color of the items that gradually disappear. Disappearing items are the top option and bottom option of a column containing five options in total. | | disappear-font-size5+ | <length> | 14px | No | Font size of the items that gradually disappear. Disappearing items are the top option and bottom option of a column containing five options in total. | -| font-family | string | sans-serif | No | Font family of the selector, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text.| +| font-family | string | sans-serif | No | Font family of the selector, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text. | ## Events The following events are supported. -Text selector (**type** is **text**) +### Text Selector | Name | Parameter | Description | | ------ | ---------------------------------------- | --------------- | -| change | { newValue: newValue, newSelected: newSelected } | Triggered when a value is specified for the text selector.| +| change | { newValue: newValue, newSelected: newSelected } | Triggered when a value is specified for the text selector.| -Time selector (**type** is **time**) +### Time Selector | Name | Parameter | Description | | ------ | ---------------------------------------- | ------------------------------- | -| change | { hour: hour, minute: minute, [second:second]} | Triggered when a value is specified for the time selector.
If seconds are contained, the value contains hour, minute, and second.| +| change | { hour: hour, minute: minute, [second:second]} | Triggered when a value is specified for the time selector.
If seconds are contained, the value contains hour, minute, and second.| -Date selector (**type** is **date**) +### Date Selector | Name | Parameter | Description | | ------ | ---------------------------------------- | --------------- | -| change | { year:year, month:month, day:day } | Triggered when a value is specified for the date selector.| +| change | { year:year, month:month, day:day } | Triggered when a value is specified for the date selector.| -Date and time selector (**type** is **datetime**) +### Date and Time Selector | Name | Parameter | Description | | ------ | ---------------------------------------- | ----------------- | -| change | { year:year, month:month, day:day,  hour:hour, minute:minute } | Triggered when a value is specified for the date and time selector.| +| change | { year:year, month:month, day:day, hour:hour, minute:minute } | Triggered when a value is specified for the date and time selector.| -Multi-text selector (**type** is **multi-text**) +### Multi-Column Text Selector | Name | Parameter | Description | | ------------ | ---------------------------------------- | ---------------------------------------- | -| columnchange | { column:column, newValue:newValue, newSelected:newSelected } | Triggered when the value of a column in the multi-column selector changes.
**column**: column whose value has changed.
**newValue**: selected value.
**newSelected**: index of the selected value.| +| columnchange | { column:column, newValue:newValue, newSelected:newSelected } | Triggered when the value of a column in the multi-column selector changes.
**column**: column whose value has changed.
**newValue**: selected value.
**newSelected**: index of the selected value.| ## Methods @@ -121,67 +121,252 @@ Not supported ## Example - -```html - -
- - Selected: {{time}} - - -
-``` - -```css -/* xxx.css */ -.container { - flex-direction: column; - justify-content: center; - align-items: center; - left: 0px; - top: 0px; - width: 454px; - height: 454px; -} -.title { - font-size: 30px; - text-align: center; -} -.time-picker { - width: 500px; - height: 400px; - margin-top: 20px; -} -``` - -```js -/* xxx.js */ -export default { - data: { - defaultTime: "", - time: "", - }, - onInit() { - this.defaultTime = this.now(); - }, - handleChange(data) { - this.time = this.concat(data.hour, data.minute); - }, - now() { - const date = new Date(); - const hours = date.getHours(); - const minutes = date.getMinutes(); - return this.concat(hours, minutes); - }, - - fill(value) { - return (value > 9 ? "" : "0") + value; - }, - - concat(hours, minutes) { - return `${this.fill(hours)}:${this.fill(minutes)}`; - }, -} -``` - -![lite_bar-4](figures/lite_bar-4.png) +1. Text Selector + ```html + +
+ + Selected value: {{value}} Selected index: {{index}} + + +
+ ``` + + ```css + /* xxx.css */ + .container { + flex-direction: column; + justify-content: center; + align-items: center; + left: 0px; + top: 0px; + width: 454px; + height: 454px; + } + .title { + font-size: 30px; + text-align: center; + margin-top: 20px; + } + ``` + + ```js + /* xxx.js */ + export default { + data: { + options: ['Option 1','Option 2','Option 3'], + value: "Option 1", + index: 0 + }, + handleChange(data) { + this.value = data.newValue; + this.index = data.newSelected; + }, + } + ``` + ![](figures/pickerview1.gif) + +2. Time Selector + ```html + +
+ + Selected: {{time}} + + +
+ ``` + + ```css + /* xxx.css */ + .container { + flex-direction: column; + justify-content: center; + align-items: center; + left: 0px; + top: 0px; + width: 454px; + height: 454px; + } + .title { + font-size: 30px; + text-align: center; + } + .time-picker { + width: 500px; + height: 400px; + margin-top: 20px; + } + ``` + + ```js + /* xxx.js */ + export default { + data: { + defaultTime: "", + time: "", + }, + onInit() { + this.defaultTime = this.now(); + }, + handleChange(data) { + this.time = this.concat(data.hour, data.minute); + }, + now() { + const date = new Date(); + const hours = date.getHours(); + const minutes = date.getMinutes(); + return this.concat(hours, minutes); + }, + fill(value) { + return (value > 9 ? "" : "0") + value; + }, + concat(hours, minutes) { + return `${this.fill(hours)}:${this.fill(minutes)}`; + }, + } + ``` + + ![](figures/pickerview2.gif) + +3. Date Selector + ```html + +
+ + Selected: {{time}} + + +
+ ``` + + ```css + /* xxx.css */ + .container { + flex-direction: column; + justify-content: center; + align-items: center; + left: 0px; + top: 0px; + width: 454px; + height: 454px; + } + .title { + font-size: 30px; + text-align: center; + margin-top: 20px; + } + .date-picker { + width: 500px; + height: 400px; + margin-top: 50px; + } + ``` + + ```js + /* xxx.js */ + export default { + data: { + date: "", + }, + handleChange(data) { + this.date = data.year + "" + data.month + "" + data.day + ""; + }, + } + ``` + + +4. Date and Time Selector + ```html + +
+ + Selected: {{datetime}} + + +
+ ``` + + ```css + /* xxx.css */ + .container { + flex-direction: column; + justify-content: center; + align-items: center; + left: 0px; + top: 0px; + width: 500px; + height: 454px; + } + .title { + font-size: 30px; + text-align: center; + margin-top: 20px; + } + .date-picker { + width: 500px; + height: 400px; + margin-top: 50px; + } + ``` + + ```js + /* xxx.js */ + export default { + data: { + datetime: "", + }, + handleChange(data) { + this.datetime = data.year + "" + data.month + "" + data.day + "" + data.hour + "" + data.minute + ""; + }, + } + ``` + + +5. Multi-Column Text Selector + + ```html + +
+ + Selected: {{ value }} + + +
+ ``` + + ```css + /* xxx.css */ + .container { + flex-direction: column; + justify-content: center; + align-items: center; + left: 0px; + top: 0px; + width: 500px; + height: 454px; + } + .title { + font-size: 30px; + text-align: center; + margin-top: 20px; + } + ``` + + ```js + /* xxx.js */ + export default { + data: { + multitext: [ + [1, 2, 3], + [4, 5, 6], + [7, 8, 9], + ], + value: "" + }, + handleChange(data) { + this.value = "Column: " + data.column + "," + "Value: " + data.newValue + ", Index:" + data.newSelected; + }, + } + ``` + ![](figures/pickerview5.gif) diff --git a/en/application-dev/reference/arkui-js/js-components-basic-picker.md b/en/application-dev/reference/arkui-js/js-components-basic-picker.md index f6425d937129086d130562d8454da03bcaef3c87..5a9ace889f60ae6f6c0c891e8d0a8d55b3dadfd1 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-picker.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-picker.md @@ -58,7 +58,7 @@ When **type** is set to **time**, a time selector is used. | Name | Type | Default Value | Mandatory | Description | | ------------- | ------- | ----------------------------------- | ---- | ---------------------------------------- | | containsecond | boolean | false | No | Whether seconds are contained. | -| selected | string | Current time | No | Default value of the time selector, in format of HH:mm. If seconds are contained, the format is HH:mm:ss. | +| selected | string | Current time | No | Default value of the time selector, in format of HH:mm. If seconds are contained, the format is HH:mm:ss.
| | value | string | - | No | Value of the time selector. | | hours | number | 241-4
-5+ | No | Time format used by the time selector. Available values are as follows:
- **12**: displayed in 12-hour format and distinguished by a.m. and p.m.
- **24**: displayed in 24-hour format.
Since API version 5, the default value is the most commonly-used hour format in the current locale.| @@ -166,52 +166,59 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods. ```html
- - - - - - - - - - - + + + + + + + + + +
``` ```css /* xxx.css */ -.container { - flex-direction: column; - justify-content: center; - align-items: center; +.container { + flex-direction: column; + justify-content: center; + align-items: center; } - picker{ - width:60%; - height:80px; - border-radius:20px; - text-color:white; - font-size:15px; - background-color:#4747e3; - margin-left:20%; + +picker { + width: 60%; + height: 80px; + border-radius: 20px; + text-color: white; + font-size: 15px; + background-color: #4747e3; + margin-left: 20%; } - select{ - background-color: #efecec; - height: 50px; - width: 60%; - margin-left: 20%; - margin-top: 300px; - margin-bottom: 50px; - font-size: 22px; + +select { + background-color: #efecec; + height: 50px; + width: 60%; + margin-left: 20%; + margin-top: 300px; + margin-bottom: 50px; + font-size: 22px; } ``` @@ -219,72 +226,96 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods. // xxx.js import router from '@system.router'; import prompt from '@system.prompt'; + export default { - data: { - selectList:["text","data","time","datetime","multitext"], - rangetext:['15', "20", "25"], - multitext:[["a", "b", "c"], ["e", "f", "g"], ["h", "i"], ["k", "l", "m"]], - textvalue:'default textvalue', - datevalue:'default datevalue', - timevalue:'default timevalue', - datetimevalue:'default datetimevalue', - multitextvalue:'default multitextvalue', - containsecond:true, - multitextselect:[1,2,0], - datetimeselect:'2012-5-6-11-25', - timeselect:'11:22:30', - dateselect:'2021-3-2', - textselect:'2' - }, - selectChange(e){ - for(let i = 0;i** component is used to generate and display a QR code. - > **NOTE** > > This component is supported since API version 5. Updates will be marked with a superscript to indicate their earliest API version. +The **\** component is used to generate and display a QR code. ## Required Permissions @@ -24,7 +23,7 @@ In addition to the [universal attributes](../arkui-js/js-components-common-attri | Name | Type | Default Value | Mandatory | Description | | ----- | ------ | ---- | ---- | ---------------------------------------- | | value | string | - | Yes | Content used to generate the QR code. | -| type | string | rect | No | QR code type. Available values are as follows:
- **rect**: rectangular QR code
- **circle**: round QR code| +| type | string | rect | No | QR code type. Available values are as follows:
- **rect**: rectangular QR code.
- **circle**: round QR code.| ## Styles @@ -60,8 +59,6 @@ The [universal methods](../arkui-js/js-components-common-methods.md) are support
- Value - 123 Type Color @@ -98,7 +95,6 @@ select{ /* index.js */ export default { data: { - qr_value:'', qr_type: 'rect', qr_size: '300px', qr_col: '#87ceeb', @@ -113,9 +109,6 @@ export default { this.qr_type = 'circle' } }, - setvalue(e) { - this.qr_value = e.newValue - }, setcol(e) { this.qr_col = e.newValue }, diff --git a/en/application-dev/reference/arkui-js/js-components-basic-search.md b/en/application-dev/reference/arkui-js/js-components-basic-search.md index 94cfa99cc29d81d779dbd1b901d8a09b71b86369..adf32950c2889e99e88d67e28da1b6bfb110f4ee 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-search.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-search.md @@ -1,10 +1,9 @@ # search > **NOTE** -> > This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. -The **\** component provides an input area for users to search. +The **\** component provides an input area for users to search. ## Child Components @@ -42,7 +41,7 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md | font-size | <length> | 16px | No | Font size of the search box. | | allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings.
If the **config-changes** tag of **fontSize** is configured for abilities in the **config.json** file, the setting takes effect without application restart.| | placeholder-color | <color> | \#99000000
| No | Color of the hint text. | -| font-weight | number \| string | normal | No | Font weight. For details, see **font-weight** of the **[\](../arkui-js/js-components-basic-text.md#styles)** component.| +| font-weight | number \| string | normal | No | Font weight. For details, see [font-weight](../arkui-js/js-components-basic-text.md#styles) of the **\** component.| | font-family | string | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text.| | caret-color6+ | <color> | - | No | Color of the caret. | diff --git a/en/application-dev/reference/arkui-js/js-components-basic-slider.md b/en/application-dev/reference/arkui-js/js-components-basic-slider.md index 08099a0bf8999752bba1fec21d227b5c710bbae0..e4351b95ac820b6acbeb624e83abe60d4fc113fe 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-slider.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-slider.md @@ -2,9 +2,9 @@ > **NOTE** > -> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. +> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. -The **\** component is used to quickly adjust settings, such as the volume and brightness. +The **\** component is used to quickly adjust settings, such as the volume and brightness. ## Child Components @@ -22,7 +22,7 @@ In addition to the [universal attributes](../arkui-js/js-components-common-attri | max | number | 100 | No| Maximum value of the slider.| | step | number | 1 | No| Step of each slide.| | value | number | 0 | No| Initial value of the slider.| -| mode5+ | string | outset | No| Slider style. Available values are as follows:
- **outset**: The slider is on the sliding bar.
- **inset**: The slider is inside the sliding bar.| +| mode5+ | string | outset | No| Slider style. Available values are as follows:
- **outset**: The slider is on the slider track.
- **inset**: The slider is in the slider track.| | showsteps5+ | boolean | false | No| Whether to display slider scales.| | showtips5+ | boolean | false | No| Whether a tooltip is displayed to show the percentage value on the slider.| @@ -51,7 +51,7 @@ In addition to the [universal events](../arkui-js/js-components-common-events.md | Attribute| Type| Description| | -------- | -------- | -------- | | value5+ | number | Current value of the slider.| -| mode5+ | string | Type of the change event. Available values are as follows:
- **start**: The **value** starts to change.
- **move**: The **value** is changing with users' dragging.
- **end**: The **value** stops changing.| +| mode5+ | string | Type of the change event. Available values are as follows:
- **start**: The **value** starts to change.
- **move**: The **value** is changing with users' dragging.
- **end**: The **value** stops changing.
- **click**: The **value** changes upon a touch on the slider.| ## Example @@ -59,48 +59,23 @@ In addition to the [universal events](../arkui-js/js-components-common-events.md ```html
- slider start value is {{startValue}} - slider current value is {{currentValue}} - slider end value is {{endValue}} - + + +
``` ```css /* xxx.css */ .container { - flex-direction: column; - justify-content: center; - align-items: center; - + flex-direction: column; + justify-content: center; + align-items: center; } -``` - -```js -// xxx.js -export default { - data: { - value: 0, - startValue: 0, - currentValue: 0, - endValue: 0, - }, - setvalue(e) { - if (e.mode == "start") { - this.value = e.value; - this.startValue = e.value; - } else if (e.mode == "move") { - this.value = e.value; - this.currentValue = e.value; - } else if (e.mode == "end") { - this.value = e.value; - this.endValue = e.value; - } else if (e.mode == "click) { - this.value = e.value; - this.currentValue = e.value; - } - } +slider{ + margin-top: 100px; } ``` + ![slider](figures/slider.png) diff --git a/en/application-dev/reference/arkui-js/js-components-basic-switch.md b/en/application-dev/reference/arkui-js/js-components-basic-switch.md index f7cc8ddd86f2762c8b6a7e5e250e95f22e5c74ed..d58e16b10b6357537684c09f519caa537a469f5c 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-switch.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-switch.md @@ -30,18 +30,20 @@ In addition to the [universal attributes](../arkui-js/js-components-common-attri ## Styles + + In addition to the [universal styles](../arkui-js/js-components-common-styles.md), the following styles are supported. -| Name | Type | Default Value | Mandatory | Description | -| ------------------- | -------------------------- | ---------- | ---- | ---------------------------------------- | -| texton-color(Rich) | <color> | \#000000 | No | Text color displayed when the component is checked. | -| textoff-color(Rich) | <color> | \#000000 | No | Text color displayed when the component is not checked. | -| text-padding(Rich) | number | 0px | No | Distance between the two sides of the longest text in **texton** and **textoff** and the border of the slider. | -| font-size(Rich) | <length> | - | No | Font size. This attribute is available only when **texton** and **textoff** are set. | -| allow-scale(Rich) | boolean | true | No | Whether the font size changes with the system's font size settings.
If the **config-changes** tag of **fontSize** is configured for abilities in the **config.json** file, the setting takes effect without application restart.| -| font-style(Rich) | string | normal | No | Font style. This attribute is available only when **texton** and **textoff** are set. For details, see **font-style** of the [**\**](../arkui-js/js-components-basic-text.md#styles) component.| -| font-weight(Rich) | number \| string | normal | No | Font weight. This attribute is available only when **texton** and **textoff** are set. For details, see **font-weight** of the [**\**](../arkui-js/js-components-basic-text.md#styles) component.| -| font-family(Rich) | string | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text. This attribute is available only when **texton** and **textoff** are set.| +| Name | Type | Default Value | Mandatory | Description | +| ------------- | -------------------------- | ---------- | ---- | ---------------------------------------- | +| texton-color | <color> | \#000000 | No | Text color displayed when the component is checked. This attribute is available only when **texton** and **textoff** are set. | +| textoff-color | <color> | \#000000 | No | Text color displayed when the component is not checked. This attribute is available only when **texton** and **textoff** are set. | +| text-padding | number | 0px | No | Distance between the two sides of the longest text in **texton** and **textoff** and the border of the slider. | +| font-size | <length> | - | No | Font size. This attribute is available only when **texton** and **textoff** are set. | +| allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings.
If the **config-changes** tag of **fontSize** is configured for abilities in the **config.json** file, the setting takes effect without application restart.| +| font-style | string | normal | No | Font style. This attribute is available only when **texton** and **textoff** are set. For details, see [font-style](../arkui-js/js-components-basic-text.md#styles) of the **\** component.| +| font-weight | number \| string | normal | No | Font weight. This attribute is available only when **texton** and **textoff** are set. For details, see [font-weight](../arkui-js/js-components-basic-text.md#styles) of the **\** component.| +| font-family | string | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text. This attribute is available only when **texton** and **textoff** are set.| ## Events @@ -61,45 +63,63 @@ The [universal methods](../arkui-js/js-components-common-methods.md) are support ```html
- - + + + + + +
``` ```css /* xxx.css */ .container { - display: flex; - justify-content: center; - align-items: center; + display: flex; + justify-content: center; + align-items: center; +} +.switch { + texton-color: red; + textoff-color: forestgreen; } -switch{ - texton-color:#002aff; - textoff-color:silver; - text-padding:20px; +.text { + text-padding: 20px; + font-size: 30px; + font-weight: 700; } ``` ```js // xxx.js -import prompt from '@system.prompt'; +import promptAction from '@ohos.promptAction'; export default { - data: { - title: 'World' - }, - switchChange(e){ - console.log(e.checked); - if(e.checked){ - prompt.showToast({ - message: "Switch on." - }); - }else{ - prompt.showToast({ - message: "Switch off." - }); + data: { + title: 'World' + }, + switchChange(e) { + if (e.checked) { + promptAction.showToast({ + message: "Switch on." + }); + } else { + promptAction.showToast({ + message: "Switch off." + }); + } + }, + normalswitchChange(e) { + if (e.checked) { + promptAction.showToast({ + message: "switch on" + }); + } else { + promptAction.showToast({ + message: "switch off" + }); + } } - } } ``` -![en-us_image_0000001152862510](figures/en-us_image_0000001152862510.gif) +![en-us_image_0000001152862510](figures/switch.gif) diff --git a/en/application-dev/reference/arkui-js/js-components-basic-text.md b/en/application-dev/reference/arkui-js/js-components-basic-text.md index c9f0227a6b0f5c684557206d36b84ed722c22c2e..2509a3a6bcc556e19d1393ed80acad3d28c91fb4 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-text.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-text.md @@ -15,7 +15,7 @@ None ## Child Components -Only the **[\](../arkui-js/js-components-basic-span.md)** component is supported. +The **[\](../arkui-js/js-components-basic-span.md)** child component is supported. ## Attributes @@ -34,19 +34,19 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md | allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings.
For details about how to make the configuration take effect dynamically, see the **config-changes** attribute in the **config.json** file.| | letter-spacing | <length> | 0px | No | Character spacing (px). | | word-spacing7+ | <length> \| <percentage> \| string | normal | No | Spacing between texts. If the input is a string, the options are as follows:
**normal**: default spacing.| -| font-style | string | normal | No | Font style. Available values are as follows:
- **normal**: standard font style
- **italic**: italic font style| -| font-weight | number \| string | normal | No | Font width. For the number type, the value ranges from 100 to 900. The default value is 400. A larger value indicates a larger font width. The value of the number type must be an integer multiple of 100.
The value of the string type can be **lighter**, **normal**, **bold**, or **bolder**.| +| font-style | string | normal | No | Font style. Available values are as follows:
- **normal**: standard font style.
- **italic**: italic font style.| +| font-weight | number \| string | normal | No | Font weight. For the number type, the value ranges from 100 to 900. The default value is 400. A larger value indicates a heavier font weight. The value of the number type must be an integer multiple of 100.
The value of the string type can be **lighter**, **normal**, **bold**, or **bolder**.| | text-decoration | string | none | No | Text decoration. Available values are as follows:
- **underline**: An underline is used.
- **line-through**: A strikethrough is used.
- **none**: The standard text is used.| | text-decoration-color7+ | <color> | - | No | Color of the text decoration. | | text-align | string | start
| No | Text alignment mode. Available values are as follows:
- **left**: The text is left-aligned.
- **center**: The text is center-aligned.
- **right**: The text is right-aligned.
- **start**: The text is aligned with the direction in which the text is written.
- **end**: The text is aligned with the opposite direction in which the text is written.
If the text width is not specified, the alignment effect may not be obvious when the text width is the same as the width of the parent container.| -| line-height | <length> \| <percentage>7+ \| string7+ | 0px1-6
normal7+ | No | Text line height. When this parameter is set to **0px**, the text line height is not limited and the font size is adaptive. The value of the string type is as follows:
**normal**7+: default line height | +| line-height | <length> \| <percentage>7+ \| string7+ | 0px1-6
normal7+ | No | Text line height. When this parameter is set to **0px**, the text line height is not limited and the font size is adaptive. The value of the string type is as follows:
**normal**7+: default line height| | text-overflow | string | clip | No | Display mode when the text is too long. This style takes effect when the maximum number of lines is specified. Available values are as follows:
- **clip**: The text is clipped and displayed based on the size of the parent container.
- **ellipsis**: The text is displayed based on the size of the parent container. The text that cannot be displayed is replaced with ellipsis. This style must be used together with **max-lines**.| | font-family | string | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text.| -| max-lines | number \| string7+ | - | No | Maximum number of text lines. The value of the string type is as follows:
- **auto**7+: The number of text lines adapts to the container height. | +| max-lines | number \| string7+ | - | No | Maximum number of text lines. The value of the string type is as follows:
- **auto**7+: The number of text lines adapts to the container height.| | min-font-size | <length> | - | No | Minimum font size in the text. This style must be used together with **max-font-size**. The font size can be changed dynamically. After the maximum and minimum font sizes are set, **font-size** does not take effect.| | max-font-size | <length> | - | No | Maximum font size in the text. This style must be used together with **min-font-size**. The font size can be changed dynamically. After the maximum and minimum font sizes are set, **font-size** does not take effect.| | font-size-step | <length> | 1px | No | Step for dynamically adjusting the font size in the text. The minimum and maximum font sizes must be set. | -| prefer-font-sizes | <array> | - | No | Preset preferred font sizes. For dynamic font size adjustment, the preset sizes are used to match the maximum number of lines in the text. If the preferred font sizes were not set, the font size will be adjusted based on the maximum and minimum font sizes and the step you have set. If the maximum number of lines in the text cannot be met, **text-overflow** is used to truncate the text. If this parameter is set, **font-size**, **max-font-size**, **min-font-size**, and **font-size-step** do not take effect.
Example values: **12px,14px,16px**| +| prefer-font-sizes | <array> | - | No | Preset preferred font sizes. For dynamic font size adjustment, the preset sizes are used to match the maximum number of lines in the text. If the preferred font sizes were not set, the font size will be adjusted based on the maximum and minimum font sizes and the step you have set. If the maximum number of lines in the text cannot be met, **text-overflow** is used to truncate the text. If this parameter is set, **font-size**, **max-font-size**, **min-font-size**, and **font-size-step** do not take effect.
Example: prefer-font-sizes: 12px,14px,16px| | word-break6+ | string | normal | No | Text line breaking mode. The options are as follows:
- **normal**: Allows text line breaks between words as appropriate to the relevant language writing systems. This is the default mode.
- **break-all**: Allows text line breaks between any characters for writing systems other than Chinese, Japanese, and Korean.
- **break-word**: Works in the same way as **break-all**, except that it does not break unbreakable words.| | text-indent7+ | <length> | - | No | Indentation of the first line. | | white-space7+ | string | pre | No | Mode for processing blanks in the component. The options are as follows:
- **normal**: All spaces, carriage returns, and tabs are combined into one space, and the text is automatically wrapped.
- **nowrap**: All spaces, carriage returns, and tabs are combined into one space, and the text is not wrapped.
- **pre**: All contents are output as-is.
- **pre-wrap**: All contents are output as-is with line breaks.
- **pre-line**: All spaces and tabs are combined into one space, the carriage return remains unchanged, and the text is wrapped.| @@ -76,84 +76,65 @@ The [universal methods](../arkui-js/js-components-common-methods.md) are support ## Example - +1. ```html
-
- - Hello {{ title }} - -
+ default text + hello world with color + hello world with font-size + hello world with letter-spacing + hello world with word-spacing + hello world with italic + hello world with font-weight + hello world with underline + hello world with line-through + hello world with text-align:right
``` ```css /* xxx.css */ .container { - display: flex; - justify-content: center; - align-items: center; -} -.content{ - width: 400px; - height: 400px; - border: 20px; + display: flex; + justify-content: center; + align-items: center; + flex-direction: column; } .title { - font-size: 80px; - text-align: center; - width: 400px; - height: 400px; + text-align: center; + width: 800px; + height: 60px; } -``` - -```js -// xxx.js -export default { - data: { - title: 'World' - } +.textcolor { + color: indianred; } -``` - -![3](figures/3.png) - -```html - -
- - This is a passage - - - This is a passage - -
-``` - -```css -/* xxx.css */ -.container { - flex-direction: column; - align-items: center; - background-color: #F1F3F5; - justify-content: center; +.textsize { + font-size: 40px; +} +.textletterspacing { + letter-spacing: -3px; } -.text1{ - word-spacing: 10px; - adapt-height: true; +.textwordspacing { + word-spacing: 20px; } -.text2{ - width: 200px; - max-lines: 1; - text-overflow: ellipsis; - text-valign: middle; - line-height: 40px; - text-decoration: underline; - text-decoration-color: red; - text-indent: 20px; - white-space: pre; +.textstyle { + font-style: italic; +} +.textweight { + font-weight: 700; +} +.textdecoration1 { + text-decoration: underline; +} +.textdecoration2 { + text-decoration: line-through; + text-decoration-color: red; +} +.textalign { + text-align: right; } ``` -![2](figures/2.png) + +![en-us_image_0000001167823076](figures/text.png) diff --git a/en/application-dev/reference/arkui-js/js-components-basic-xcomponent.md b/en/application-dev/reference/arkui-js/js-components-basic-xcomponent.md index bb5389d410eb12c80575d55d0ea74dd4b33efa05..639f9f1d575f6d5f1aa183ad74f6d1d2a666dc27 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-xcomponent.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-xcomponent.md @@ -1,18 +1,18 @@ # xcomponent - > **NOTE** - > - > This component is supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version. +> **NOTE** +> +> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. - The **\** displays the components to which the EGL/OpenGLES or media data is written. +The **\** displays the components to which the EGL/OpenGLES or media data is written. ## Required Permissions - None +None ## Child Components - Not supported +Not supported ## Attributes diff --git a/en/application-dev/reference/arkui-js/js-components-canvas-canvas.md b/en/application-dev/reference/arkui-js/js-components-canvas-canvas.md index edf0d3afa3412cb67b3d97f38036218f46e1de33..ca3a9125a0dba2956d12d15fe7c82322730f40bb 100644 --- a/en/application-dev/reference/arkui-js/js-components-canvas-canvas.md +++ b/en/application-dev/reference/arkui-js/js-components-canvas-canvas.md @@ -11,7 +11,7 @@ The **\** component is used for customizing drawings. None -## Child Component +## Child Components Not supported @@ -38,7 +38,7 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods. ### getContext -getContext(type: '2d', options?: ContextAttrOptions): CanvasRendering2dContext +getContext(type: '2d', options?: ContextAttrOptions): CanvasRenderingContext2D Obtains the canvas drawing context. This API cannot be called in **onInit** or **onReady**. @@ -49,7 +49,7 @@ Obtains the canvas drawing context. This API cannot be called in **onInit** or * | type | string | Yes | Object type. The value is set to **'2d'**, indicating that a 2D drawing object is returned. This object can be used to draw rectangles, texts, and images on the canvas component.| | options6+ | ContextAttrOptions | No | Whether to enable anti-aliasing. By default, anti-aliasing is disabled. | -**Table 1** ContextAttrOptions + **Table 1** ContextAttrOptions | Name | Type | Description | | --------- | ------- | ------------------- | @@ -59,7 +59,7 @@ Obtains the canvas drawing context. This API cannot be called in **onInit** or * | Type | Description | | ---------------------------------------- | -------------------- | -| [CanvasRenderingContext2D](../arkui-js/js-components-canvas-canvasrenderingcontext2d.md) | 2D drawing object, which can be used to draw rectangles, images, and texts, on the canvas component. | +| [CanvasRenderingContext2D](../arkui-js/js-components-canvas-canvasrenderingcontext2d.md) | 2D drawing object, which can be used to draw rectangles, images, and texts on the canvas component.| ### toDataURL6+ diff --git a/en/application-dev/reference/arkui-js/js-components-canvas-canvasgradient.md b/en/application-dev/reference/arkui-js/js-components-canvas-canvasgradient.md index 9bc724d26a7610fa4b7fdbd48b21811a2f472cf2..125067139d62be03f2a19995e9181df6010a1f77 100644 --- a/en/application-dev/reference/arkui-js/js-components-canvas-canvasgradient.md +++ b/en/application-dev/reference/arkui-js/js-components-canvas-canvasgradient.md @@ -25,19 +25,21 @@ Adds a color stop for the **CanvasGradient** object based on the specified offse
-
``` ```js // xxx.js export default { - handleClick() { + onShow() { const el =this.$refs.canvas; - const ctx =el.getContext('2d'); - const gradient = ctx.createLinearGradient(0,0,100,0); - gradient.addColorStop(0,'#00ffff'); - gradient.addColorStop(1,'#ffff00'); + const ctx = el.getContext('2d'); + const gradient = ctx.createLinearGradient(50,0,300,100); + gradient.addColorStop(0.0, 'red') + gradient.addColorStop(0.5, 'white') + gradient.addColorStop(1.0, 'green') + ctx.fillStyle = gradient + ctx.fillRect(0, 0, 300, 300) } } ``` diff --git a/en/application-dev/reference/arkui-js/js-components-canvas-canvasrenderingcontext2d.md b/en/application-dev/reference/arkui-js/js-components-canvas-canvasrenderingcontext2d.md index 4100f9429985f1df7dd1e52087c842f128496226..0ebefab7d190de7f8ca8bd76b570444c0a2aa70b 100644 --- a/en/application-dev/reference/arkui-js/js-components-canvas-canvasrenderingcontext2d.md +++ b/en/application-dev/reference/arkui-js/js-components-canvas-canvasrenderingcontext2d.md @@ -2,7 +2,7 @@ > **NOTE** > -> Supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. +> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. **CanvasRenderingContext2D** allows you to draw rectangles, text, images, and other objects on a canvas. @@ -426,9 +426,9 @@ export default { } ``` -![en-us_image_0000001213192781](figures/en-us_image_0000001213192781.png) + ![en-us_image_0000001213192781](figures/en-us_image_0000001213192781.png) -In the above example, the blue rectangle represents the new drawing, and the red rectangle represents the existing drawing. + In the above example, the blue rectangle represents the new drawing, and the red rectangle represents the existing drawing. ### shadowBlur @@ -585,7 +585,7 @@ Fills a rectangle on the canvas. ```html
- +
``` @@ -621,7 +621,7 @@ Clears the content in a rectangle on the canvas. ```html
- +
``` @@ -984,7 +984,7 @@ Creates a pattern for image filling based on a specified source image and repeti ```html
- +
``` @@ -998,7 +998,7 @@ Creates a pattern for image filling based on a specified source image and repeti img.src = 'common/images/example.jpg'; var pat = ctx.createPattern(img, 'repeat'); ctx.fillStyle = pat; - ctx.fillRect(0, 0, 20, 20); + ctx.fillRect(0, 0, 500, 500); } } ``` @@ -1429,7 +1429,7 @@ Defines a transformation matrix. To transform a graph, you only need to set para setTransform(scaleX: number, skewX: number, skewY: number, scale: number, translateX: number, translateY: number): void -Resets the existing transformation matrix and creates a new transformation matrix by using the same parameters as the **transform()** function. +Resets the existing transformation matrix and creates a new transformation matrix by using the same parameters as the **transform()** API. **Parameters** @@ -1574,7 +1574,7 @@ Draws an image on the canvas. ```html
- +
``` @@ -1582,11 +1582,11 @@ Draws an image on the canvas. //xxx.js export default { onShow() { - var test = this.$element('drawImage'); + var test = this.$refs.canvas; var ctx = test.getContext('2d'); var img = new Image(); img.src = 'common/image/test.jpg'; - ctx.drawImage(img, 50, 80, 80, 80); + ctx.drawImage(img, 0, 0, 200, 200, 10, 10, 200, 200); } } ``` diff --git a/en/application-dev/reference/arkui-js/js-components-canvas-path2d.md b/en/application-dev/reference/arkui-js/js-components-canvas-path2d.md index f5f4179442862246d1c3171dde95879efbe4c532..c2ca3f82172d1b3a7c7b6a5a2d5423d9ecc3aabd 100644 --- a/en/application-dev/reference/arkui-js/js-components-canvas-path2d.md +++ b/en/application-dev/reference/arkui-js/js-components-canvas-path2d.md @@ -65,7 +65,7 @@ Sets the path transformation matrix. ```html
- +
``` @@ -95,7 +95,7 @@ Moves the current point of the path back to the start point of the path, and dra ```html
- +
``` @@ -223,7 +223,7 @@ Draws a cubic bezier curve on the canvas. ```html
- +
``` @@ -264,7 +264,7 @@ Draws a quadratic curve on the canvas. ```html
- +
``` @@ -307,7 +307,7 @@ Draws an arc on the canvas. ```html
- +
``` @@ -348,7 +348,7 @@ Draws an arc based on the radius and points on the arc. ```html
- +
``` diff --git a/en/application-dev/reference/arkui-js/js-components-common-transition.md b/en/application-dev/reference/arkui-js/js-components-common-transition.md index 19e54ce8bb7cbbf8f417fb3623a0fbe6635f8f67..d75160229929e2cb565ec65604164c89539e8182 100644 --- a/en/application-dev/reference/arkui-js/js-components-common-transition.md +++ b/en/application-dev/reference/arkui-js/js-components-common-transition.md @@ -11,14 +11,14 @@ | Name | Type | Default Value | Description | | ------- | ------ | ---- | ---------------------------------------- | -| shareid | string | - | Used for the transition of shared elements, which takes effect only when this attribute is set. **\**, **\**, **\**, **\
@@ -60,12 +60,12 @@ In the example below, where **PageA** jumps to **PageB**, the shared element is ```js // xxx.js -import router from '@system.router'; +import router from '@ohos.router'; export default { jump() { router.push({ // The path must be the same as that in the config.json file. - uri: 'pages/detailpage', + url: 'pages/detailpage', }); }, } @@ -93,7 +93,7 @@ export default { ```js // xxx.js -import router from '@system.router'; +import router from '@ohos.router'; export default { jumpBack() { router.back(); @@ -117,7 +117,6 @@ export default { ## Widget Transition > **NOTE** -> > Widget transitions are not available when other transitions (including shared element transitions and custom transitions) are used. @@ -125,7 +124,7 @@ export default { | Name | Type | Default Value | Description | | ----------------- | ------ | ---- | ---------------------------------------- | -| transition-effect | string | - | Whether a component on the current page displays the transition effect during a widget transition. Available values are as follows:
- **unfold**: The component will move upwards by one widget height if the component is located above the widget tapped by the user, or move downwards by one widget height if the component is located below the widget.
- **none**: No transition effect is displayed. | +| transition-effect | string | - | Whether a component on the current page displays the transition effect during a widget transition. Available values are as follows:
- **unfold**: The component will move upwards by one widget height if the component is located above the widget tapped by the user, or move downwards by one widget height if the component is located below the widget.
- **none**: No transition effect is displayed.| ### Example @@ -140,7 +139,7 @@ The **source_page** has a title area on the top and a widget list. Users can tap MAIN TITLE
- + {{$item.title}} @@ -149,19 +148,19 @@ The **source_page** has a title area on the top and a widget list. Users can tap ```js // xxx.js -import router from '@system.router' +import router from '@ohos.router' export default { data: { list: [] }, onInit() { for(var i = 0; i < 10; i++) { - var item = { uri: "pages/card_transition/target_page/index", + var item = { url: "pages/card_transition/target_page/index", title: "this is title" + i, id: "item_" + i } this.list.push(item); } }, - jumpPage(id, uri) { + jumpPage(id, url) { var cardId = this.$element(id).ref; - router.push({ uri: uri, params : { ref : cardId } }); + router.push({ url: url, params : { ref : cardId } }); } } ``` @@ -169,6 +168,8 @@ export default { ```css /* xxx.css */ .container { + width: 100%; + height: 100%; flex-direction: column; align-items: center; background-color: #ABDAFF; @@ -199,6 +200,8 @@ export default { ```css /* xxx.css */ .container { + width: 100%; + height: 100%; flex-direction: column; align-items: center; background-color: #EBFFD7; @@ -223,7 +226,7 @@ export default { | -------------------------- | ------ | ------------- | ---------------------------------------- | | transition-enter | string | - | Works with **@keyframes** and supports transform and opacity animations. For details, see [Attributes available for the @keyframes rule](../arkui-js/js-components-common-animation.md).| | transition-exit | string | - | Works with **@keyframes** and supports transform and opacity animations. For details, see [Attributes available for the @keyframes rule](../arkui-js/js-components-common-animation.md).| -| transition-duration | string | Follows the default page transition time of the device | The unit can be s or ms. The default unit is ms. If no value is specified, the default value is used. | +| transition-duration | string | Follows the default page transition time of the device| The unit can be s|or ms. The default unit is ms. If no value is specified, the default value is used.| | transition-timing-function | string | friction | Speed curve of the transition animation, which makes the animation more fluent. For details, see the description of **animation-timing-function **in [Animation Styles](../arkui-js/js-components-common-animation.md).| @@ -255,16 +258,16 @@ export default {
``` - ```css + ```js // xxx.js - import router from '@system.router'; + import router from '@ohos.router'; export default { data: { - + }, jump() { router.push({ - uri:'pages/transition2/transition2' + url:'pages/transition2/transition2' }) } } @@ -288,13 +291,13 @@ export default { transition-duration: 5s; transition-timing-function: friction; } - + @keyframes go_page { from { opacity: 0; transform: translate(0px) rotate(60deg) scale(1.0); } - + to { opacity: 1; transform: translate(100px) rotate(360deg) scale(1.0); @@ -305,7 +308,7 @@ export default { opacity: 1; transform: translate(200px) rotate(60deg) scale(2); } - + to { opacity: 0; transform: translate(200px) rotate(360deg) scale(2); @@ -321,15 +324,15 @@ export default {
transition
-
``` ```js // xxx.js - import router from '@system.router'; + import router from '@ohos.router'; export default { data: { - + }, jumpBack() { router.back() @@ -346,7 +349,7 @@ export default { width: 100%; height: 100%; } - + .move_page { width: 100px; height: 100px; @@ -356,7 +359,7 @@ export default { transition-duration: 5s; transition-timing-function: ease; } - + @keyframes go_page { from { opacity: 0; @@ -367,7 +370,7 @@ export default { transform:translate(100px) rotate(180deg) scale(2.0); } } - + @keyframes exit_page { from { opacity: 1; diff --git a/en/application-dev/reference/arkui-js/js-components-container-list.md b/en/application-dev/reference/arkui-js/js-components-container-list.md index 640c6c420ce81d299b7d12a1b67cca42b543ea1b..793e037c599b70a09ef595d9ee969823f137917e 100644 --- a/en/application-dev/reference/arkui-js/js-components-container-list.md +++ b/en/application-dev/reference/arkui-js/js-components-container-list.md @@ -72,7 +72,7 @@ In addition to the [universal events](../arkui-js/js-components-common-events.md | scrollend | - | Triggered when the list stops scrolling. | | scrolltouchup | - | Triggered when the list continues scrolling after the user lifts their fingers. | | requestitem | - | Triggered for a request to create a list-item.
This event is triggered when the number of cached list-items outside the visible area is less than the value of **cachedcount** during long list loading with delay.| -| rotate7+ | { rotateValue: number } | Triggered to indicate the incremental value of the rotation angle of the watch crown. This parameter is only supported by wearables. | +| rotation7+ | { rotateValue: number } | Triggered to indicate the incremental value of the rotation angle of the watch crown. This parameter is only supported by wearables. | ## Methods @@ -112,22 +112,6 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods. ``` - -```js -// index.js -export default { - data: { - todolist: [{ - title: 'Prepare for the interview', - date: '2021-12-31 10:00:00', - }, { - title: 'Watch the movie', - date: '2021-12-31 20:00:00', - }], - }, -} -``` - ```css /* index.css */ .container { @@ -153,4 +137,21 @@ export default { } ``` +```js +// index.js +export default { + data: { + todolist: [{ + title: 'Prepare for the interview', + date: '2021-12-31 10:00:00' + }, { + title: 'Watch the movie', + date: '2021-12-31 20:00:00' + }], + }, +} +``` + + + ![en-us_image_0000001185033226](figures/en-us_image_0000001185033226.png) diff --git a/en/application-dev/reference/arkui-js/js-components-container-panel.md b/en/application-dev/reference/arkui-js/js-components-container-panel.md index 89e23df188c5250d071bfdcf38b30c6af09e1863..9dd11f5afc549a7cd9a0fde7cdc926af5b433292 100644 --- a/en/application-dev/reference/arkui-js/js-components-container-panel.md +++ b/en/application-dev/reference/arkui-js/js-components-container-panel.md @@ -86,58 +86,63 @@ The following methods are supported. ```html
-
- -
- -
-
- Simple panel in {{modeFlag}} mode -
-
- -
+
+
- + +
+
+ Simple panel in {{ modeFlag }} mode +
+
+ +
+
+
``` ```css /* xxx.css */ .doc-page { - flex-direction: column; - justify-content: center; - align-items: center; + flex-direction: column; + justify-content: center; + align-items: center; } + .btn-div { - width: 100%; - height: 200px; - flex-direction: column; - align-items: center; - justify-content: center; + width: 100%; + height: 200px; + flex-direction: column; + align-items: center; + justify-content: center; } + .txt { - color: #000000; - font-weight: bold; - font-size: 39px; + color: #000000; + font-weight: bold; + font-size: 39px; } + .panel-div { - width: 100%; - flex-direction: column; - align-items: center; + width: 100%; + flex-direction: column; + align-items: center; } + .inner-txt { - width: 100%; - height: 160px; - flex-direction: column; - align-items: center; - justify-content: center; + width: 100%; + height: 160px; + flex-direction: column; + align-items: center; + justify-content: center; } + .inner-btn { - width: 100%; - height: 120px; - justify-content: center; - align-items: center; + width: 100%; + height: 120px; + justify-content: center; + align-items: center; } ``` diff --git a/en/application-dev/reference/arkui-js/js-components-container-popup.md b/en/application-dev/reference/arkui-js/js-components-container-popup.md index ef1cf3c658d395c64808eb9a1743c8d67b76bd81..46d661972f887b2ed6601523198618d7a831d380 100644 --- a/en/application-dev/reference/arkui-js/js-components-container-popup.md +++ b/en/application-dev/reference/arkui-js/js-components-container-popup.md @@ -4,7 +4,7 @@ > > This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. -Bubble indication. The **\** component is used to display a pop-up to offer instructions after a user clicks a bound control. +The **\** component is used to display a pop-up to offer instructions after a user clicks a bound component. ## Required Permissions @@ -116,7 +116,7 @@ export default { visibilitychange(e) { prompt.showToast({ message: 'visibility change visibility: ' + e.visibility, - duration: 3000, + duration: 3000 }); }, showpopup() { @@ -124,7 +124,7 @@ export default { }, hidepopup() { this.$element("popup").hide(); - }, + } } ``` diff --git a/en/application-dev/reference/arkui-js/js-components-container-refresh.md b/en/application-dev/reference/arkui-js/js-components-container-refresh.md index 8c3d8c5f42dfeb9721e0c00b1b7a7dbb31187241..fb9bf04be32e5c4612afd0a955810bfec050ae8d 100644 --- a/en/application-dev/reference/arkui-js/js-components-container-refresh.md +++ b/en/application-dev/reference/arkui-js/js-components-container-refresh.md @@ -4,7 +4,7 @@ > > This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. -The **** component is used to refresh a page through a pull-down gesture. +The **** component is used to refresh a page through a pull-down gesture. ## Required Permissions @@ -22,7 +22,7 @@ In addition to the [universal attributes](../arkui-js/js-components-common-attri | Name| Type| Default Value| Mandatory| Description| | -------- | -------- | -------- | -------- | -------- | -| offset | <length> | - | No| Distance to the top of the parent component from the **** component that comes to rest after a successful pull-down gesture.| +| offset | <length> | - | No| Distance to the top of the parent component from the **** component that comes to rest after a successful pull-down gesture.| | refreshing | boolean | false | No| Whether the **\** component is being used for refreshing.| | type | string | auto | No| Dynamic effect when the component is refreshed. Two options are available and cannot be modified dynamically.
- **auto**: default effect. When the list is pulled to the top, the list does not move. When the list is pulled to the bottom, a circle is displayed.
- **pulldown**: When the list is pulled to the top, users can continue to pull down to trigger a refresh. The rebound effect will appear after the refresh. If the child component contains a list, set **scrolleffect** of the list to **no** to prevent drop-down effect conflicts.| | lasttime | boolean | false | No| Whether to display the last update time. The character string format is **last update time: XXXX**, where **XXXX** is displayed based on the certain time and date formats and cannot be dynamically modified. (It is recommended that this attribute be used when **type** is set to **pulldown**. The fixed distance is at the bottom of the content drop-down area. Pay attention to the **offset** attribute setting to prevent overlapping.)| @@ -36,8 +36,8 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md | Name| Type| Default Value| Mandatory| Description| | -------- | -------- | -------- | -------- | -------- | -| background-color | <color> | white | No| Background color of the **\** component.| -| progress-color | <color> | black | No| Loading color of the **\** component.| +| background-color | <color> | white
| No| Background color of the **\** component.| +| progress-color | <color> | black
| No| Color of the loading icon of the **\** component.| ## Events @@ -107,7 +107,7 @@ The [universal methods](../arkui-js/js-components-common-methods.md) are not sup ```js // xxx.js -import prompt from '@system.prompt'; +import promptAction from '@ohos.promptAction'; export default { data: { list:[], @@ -121,7 +121,7 @@ export default { } }, refresh: function (e) { - prompt.showToast({ + promptAction.showToast({ message: 'Refreshing...' }) var that = this; @@ -130,7 +130,7 @@ export default { that.fresh = false; var addItem ='Refresh element'; that.list.unshift(addItem); - prompt.showToast({ + promptAction.showToast({ message: 'Refreshed.' }) }, 2000) diff --git a/en/application-dev/reference/arkui-js/js-components-container-stepper.md b/en/application-dev/reference/arkui-js/js-components-container-stepper.md index 6a666a454cd424e1b3daf67fcae1c4a4e08f67a6..09bd2f3fce15f326b1d8f06832d3ea0c4319e234 100644 --- a/en/application-dev/reference/arkui-js/js-components-container-stepper.md +++ b/en/application-dev/reference/arkui-js/js-components-container-stepper.md @@ -27,7 +27,7 @@ In addition to the [universal attributes](../arkui-js/js-components-common-attri | Name | Type | Default Value | Description | | ----- | ------ | ---- | ------------------------------ | -| index | number | - | Index of the **\** child component that is currently displayed.| +| index | number | 0 | Index of the **\** child component to display. By default, the first one is displayed.| ## Styles @@ -46,10 +46,10 @@ In addition to the [universal events](../arkui-js/js-components-common-events.md | Name | Parameter | Description | | ------ | ---------------------------------------- | ---------------------------------------- | | finish | - | Triggered when the last step on the navigator is complete. | -| skip | - | Triggered when users click the skip button, which works only if you have called **setNextButtonStatus** method to allow users to skip all steps.| +| skip | - | Triggered when users click the skip button to skip steps.| | change | { prevIndex: prevIndex, index: index} | Triggered when users click the left or right (text) button of the step navigator to switch between steps. **prevIndex** indicates the index of the previous step, and **index** indicates that of the current step.| -| next | { index: index, pendingIndex: pendingIndex } | Triggered when users click the next (text) button. **index** indicates the index of the current step, and **pendingIndex** indicates that of the step to go. The return value is in **{pendingIndex:*** pendingIndex***}** format. You can use **pendingIndex** to specify a **\** child component as the next step to go.| -| back | { index: index, pendingIndex: pendingIndex } | Triggered when users click the previous (text) button. **index** indicates the index of the current step, and **pendingIndex** indicates that of the step to go. The return value is in Object:{ **{pendingIndex:*** pendingIndex***}** format. You can use **pendingIndex** to specify a **\** child component as the previous step.| +| next | { index: index, pendingIndex: pendingIndex } | Triggered when users click the next (text) button. **index** indicates the index of the current step, and **pendingIndex** indicates that of the step to go. The return value is in **{pendingIndex:*** pendingIndex***}** format. You can use **pendingIndex** to specify a **** child component as the next step to go.| +| back | { index: index, pendingIndex: pendingIndex } | Triggered when users click the previous (text) button. **index** indicates the index of the current step, and **pendingIndex** indicates that of the step to go. The return value is in Object:{ **{pendingIndex:*** pendingIndex***}** format. You can use **pendingIndex** to specify a **** child component as the previous step.| ## Methods @@ -58,101 +58,137 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods. | Name | Parameter | Description | | ------------------- | ---------------------------------------- | ---------------------------------------- | -| setNextButtonStatus | { status: string, label: label } | Sets the status of the next (text) button in this step navigator. Available **status** values are as follows:
- **normal**: The next button is displayed normally and can navigate users to the next step when it is clicked.
- **disabled**: The next button is grayed out and unavailable.
- **waiting**: The next button is not displayed, and a process bar is displayed instead.
- **skip**: The skip button is displayed to allow users to skip all remaining steps.| +| setNextButtonStatus | { status: string, label: label } | Sets the text and status of the next button in the step navigator. **label** indicates the button text, and **status** indicates the button status. Available **status** values are as follows:
- **normal**: The next button is displayed normally and can navigate users to the next step when it is clicked.
- **disabled**: The next button is grayed out and unavailable.
- **waiting**: The next button is not displayed, and a process bar is displayed instead.
- **skip**: The skip button is displayed to allow users to skip all remaining steps.| ## Example ```html -
- - -
- First screen -
- -
- -
- Second screen -
- -
- -
- Third screen -
- -
-
+
+ + +
+ Page One + +
+
+ +
+ Page Two + +
+
+ +
+ Page Three + +
+
+
``` ```css /* xxx.css */ .container { - margin-top: 20px; - flex-direction: column; - align-items: center; - height: 300px; + flex-direction: column; + align-items: center; + height: 100%; + width: 100%; + background-color: #f7f7f7; } -.stepperItem { - width: 100%; - flex-direction: column; - align-items: center; +.stepper{ + width: 100%; + height: 100%; } -.stepperItemContent { - color: #0000ff; - font-size: 50px; - justify-content: center; +.stepper-item { + width: 100%; + height: 100%; + flex-direction: column; + align-items: center; +} +.item{ + width: 90%; + height: 86%; + margin-top: 80px; + background-color: white; + border-radius: 60px; + flex-direction: column; + align-items: center; + padding-top: 160px; +} +text { + font-size: 78px; + color: #182431; + opacity: 0.4; } .button { - width: 60%; - margin-top: 30px; - justify-content: center; + width: 40%; + margin-top: 100px; + justify-content: center; } ``` ```js // xxx.js +import prompt from '@system.prompt'; + export default { - data: { - label_1: - { - prevLabel: 'BACK', - nextLabel: 'NEXT', - status: 'normal' - }, - label_2: - { - prevLabel: 'BACK', - nextLabel: 'NEXT', - status: 'normal' - }, - label_3: - { - prevLabel: 'BACK', - nextLabel: 'NEXT', - status: 'normal' - }, - }, - setRightButton(e) { - this.$element('mystepper').setNextButtonStatus({status: 'skip', label: 'SKIP'}); - }, - nextclick(e) { - var index = { - pendingIndex: e.pendingIndex - } - return index; - }, - backclick(e) { - var index = { - pendingIndex: e.pendingIndex + data: { + label_1: + { + prevLabel: 'BACK', + nextLabel: 'NEXT', + status: 'normal' + }, + label_2: + { + prevLabel: 'BACK', + nextLabel: 'NEXT', + status: 'normal' + }, + label_3: + { + prevLabel: 'BACK', + nextLabel: 'NEXT', + status: 'normal' + } + }, + setRightButton(e) { + this.$element('mystepper').setNextButtonStatus({ + status: 'waiting', label: 'SKIP' + }); + }, + nextclick(e) { + var index = { + pendingIndex: e.pendingIndex + } + return index; + }, + backclick(e) { + var index = { + pendingIndex: e.pendingIndex + } + return index; + }, + statuschange(e) { + prompt.showToast({ + message: 'Previous step index' + e.prevIndex + 'Current step index' + e.index + }) + }, + finish() { + prompt.showToast({ + message:'Finished.' + }) + }, + skip() { + prompt.showToast({ + message: 'Skip triggered' + }) } - return index; - }, } ``` -![en-us_image_0000001127125114](figures/en-us_image_0000001127125114.gif) +![](figures/stepper.gif) diff --git a/en/application-dev/reference/arkui-js/js-components-container-swiper.md b/en/application-dev/reference/arkui-js/js-components-container-swiper.md index e0edf4c40ffba747e84e1dc84e8999993bca675e..f607139653a52a1e1edbca359ca60d7224ebcc30 100644 --- a/en/application-dev/reference/arkui-js/js-components-container-swiper.md +++ b/en/application-dev/reference/arkui-js/js-components-container-swiper.md @@ -4,7 +4,7 @@ > > This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. -The **\** component provides a container that allows users to switch among child components using swipe gestures. +The **\** component provides a container that allows users to switch among child components using swipe gestures. ## Required Permissions diff --git a/en/application-dev/reference/arkui-js/js-components-media-video.md b/en/application-dev/reference/arkui-js/js-components-media-video.md index c024cbe0058093b754c98f04f579b1cd7dac620f..0141e4818d35042cdef8f77362a95bb3d641b4d8 100644 --- a/en/application-dev/reference/arkui-js/js-components-media-video.md +++ b/en/application-dev/reference/arkui-js/js-components-media-video.md @@ -3,17 +3,7 @@ > **NOTE** > -> - This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. -> -> - Set **configChanges** under **abilities** in the **config.json** file to **orientation**. -> ``` -> "abilities": [ -> { -> "configChanges": ["orientation"], -> ... -> } -> ] -> ``` +> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. The **\