提交 8284f25e 编写于 作者: D donglin 提交者: Gitee

Merge branch 'master' of gitee.com:openharmony/docs into master

Signed-off-by: Ndonglin <donglin9@huawei.com>
...@@ -133,7 +133,7 @@ zh-cn/device-dev/subsystems/subsys-xts-guide.md @Austin23 ...@@ -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/ability/ @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen
zh-cn/application-dev/IDL/ @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/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/notification/ @RayShih @jayleehw @li-weifeng2 @currydavids
zh-cn/application-dev/windowmanager/ @ge-yafang @zhangqiang183 @zhouyaoying @zxg-gitee zh-cn/application-dev/windowmanager/ @ge-yafang @zhangqiang183 @zhouyaoying @zxg-gitee
zh-cn/application-dev/webgl/ @zengyawen @zhangqiang183 @wind_zj @zxg-gitee zh-cn/application-dev/webgl/ @zengyawen @zhangqiang183 @wind_zj @zxg-gitee
...@@ -369,10 +369,10 @@ zh-cn/application-dev/reference/apis/js-apis-inputconsumer.md @mayunteng_1 @ning ...@@ -369,10 +369,10 @@ zh-cn/application-dev/reference/apis/js-apis-inputconsumer.md @mayunteng_1 @ning
zh-cn/application-dev/reference/apis/js-apis-inputdevice.md @mayunteng_1 @ningningW @cococoler @alien0208 zh-cn/application-dev/reference/apis/js-apis-inputdevice.md @mayunteng_1 @ningningW @cococoler @alien0208
zh-cn/application-dev/reference/apis/js-apis-inputevent.md @mayunteng_1 @ningningW @cococoler @alien0208 zh-cn/application-dev/reference/apis/js-apis-inputevent.md @mayunteng_1 @ningningW @cococoler @alien0208
zh-cn/application-dev/reference/apis/js-apis-inputeventclient.md @mayunteng_1 @ningningW @cococoler @alien0208 zh-cn/application-dev/reference/apis/js-apis-inputeventclient.md @mayunteng_1 @ningningW @cococoler @alien0208
zh-cn/application-dev/reference/apis/js-apis-inputmethod-extension-ability.md @feng-aiwen @ge-yafang @SuperShrimp @murphy1984 zh-cn/application-dev/reference/apis/js-apis-inputmethod-extension-ability.md @feng-aiwen @ningningW @SuperShrimp @murphy1984
zh-cn/application-dev/reference/apis/js-apis-inputmethod-extension-context.md @feng-aiwen @ge-yafang @SuperShrimp @murphy1984 zh-cn/application-dev/reference/apis/js-apis-inputmethod-extension-context.md @feng-aiwen @ningningW @SuperShrimp @murphy1984
zh-cn/application-dev/reference/apis/js-apis-inputmethod.md @feng-aiwen @ge-yafang @SuperShrimp @murphy1984 zh-cn/application-dev/reference/apis/js-apis-inputmethod.md @feng-aiwen @ningningW @SuperShrimp @murphy1984
zh-cn/application-dev/reference/apis/js-apis-inputmethodengine.md @feng-aiwen @ge-yafang @SuperShrimp @murphy1984 zh-cn/application-dev/reference/apis/js-apis-inputmethodengine.md @feng-aiwen @ningningW @SuperShrimp @murphy1984
zh-cn/application-dev/reference/apis/js-apis-inputmonitor.md @mayunteng_1 @ningningW @cococoler @alien0208 zh-cn/application-dev/reference/apis/js-apis-inputmonitor.md @mayunteng_1 @ningningW @cococoler @alien0208
zh-cn/application-dev/reference/apis/js-apis-intl.md @Buda-Liu @ningningW @budda-wang @yangqing3 zh-cn/application-dev/reference/apis/js-apis-intl.md @Buda-Liu @ningningW @budda-wang @yangqing3
zh-cn/application-dev/reference/apis/js-apis-keycode.md @mayunteng_1 @ningningW @cococoler @alien0208 zh-cn/application-dev/reference/apis/js-apis-keycode.md @mayunteng_1 @ningningW @cococoler @alien0208
...@@ -407,12 +407,12 @@ zh-cn/application-dev/reference/apis/js-apis-prompt.md @huaweimaxuchu @HelloCrea ...@@ -407,12 +407,12 @@ zh-cn/application-dev/reference/apis/js-apis-prompt.md @huaweimaxuchu @HelloCrea
zh-cn/application-dev/reference/apis/js-apis-queue.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-queue.md @gongjunsong @ge-yafang @flyingwolf @BlackStone
zh-cn/application-dev/reference/apis/js-apis-radio.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785 zh-cn/application-dev/reference/apis/js-apis-radio.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785
zh-cn/application-dev/reference/apis/js-apis-reminderAgent.md @jayleehw @RayShih @li-weifeng2 @currydavids zh-cn/application-dev/reference/apis/js-apis-reminderAgent.md @jayleehw @RayShih @li-weifeng2 @currydavids
zh-cn/application-dev/reference/apis/js-apis-request.md @feng-aiwen @zengyawen @nagexiucai @murphy1984 zh-cn/application-dev/reference/apis/js-apis-request.md @feng-aiwen @ningningW @nagexiucai @murphy1984
zh-cn/application-dev/reference/apis/js-apis-resource-manager.md @Buda-Liu @ningningW @budda-wang @yangqing3 zh-cn/application-dev/reference/apis/js-apis-resource-manager.md @Buda-Liu @ningningW @budda-wang @yangqing3
zh-cn/application-dev/reference/apis/js-apis-router.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy zh-cn/application-dev/reference/apis/js-apis-router.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy
zh-cn/application-dev/reference/apis/js-apis-rpc.md @xuepianpian @RayShih @zhaopeng_gitee @vagrant_world zh-cn/application-dev/reference/apis/js-apis-rpc.md @xuepianpian @RayShih @zhaopeng_gitee @vagrant_world
zh-cn/application-dev/reference/apis/js-apis-runninglock.md @aqxyjay @zengyawen @aqxyjay @alien0208 zh-cn/application-dev/reference/apis/js-apis-runninglock.md @aqxyjay @zengyawen @aqxyjay @alien0208
zh-cn/application-dev/reference/apis/js-apis-screen-lock.md @feng-aiwen @ge-yafang @wangzhangjun @murphy1984 zh-cn/application-dev/reference/apis/js-apis-screen-lock.md @feng-aiwen @ningningW @wangzhangjun @murphy1984
zh-cn/application-dev/reference/apis/js-apis-screen.md @zhangqiang183 @ge-yafang @zhouyaoying @zxg-gitee zh-cn/application-dev/reference/apis/js-apis-screen.md @zhangqiang183 @ge-yafang @zhouyaoying @zxg-gitee
zh-cn/application-dev/reference/apis/js-apis-screenshot.md @zhangqiang183 @ge-yafang @zhouyaoying @zxg-gitee zh-cn/application-dev/reference/apis/js-apis-screenshot.md @zhangqiang183 @ge-yafang @zhouyaoying @zxg-gitee
zh-cn/application-dev/reference/apis/js-apis-securityLabel.md @panqinxu @zengyawen @bubble_mao @jinhaihw zh-cn/application-dev/reference/apis/js-apis-securityLabel.md @panqinxu @zengyawen @bubble_mao @jinhaihw
...@@ -446,8 +446,8 @@ zh-cn/application-dev/reference/apis/js-apis-system-request.md @zhang-hai-feng @ ...@@ -446,8 +446,8 @@ zh-cn/application-dev/reference/apis/js-apis-system-request.md @zhang-hai-feng @
zh-cn/application-dev/reference/apis/js-apis-system-router.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy zh-cn/application-dev/reference/apis/js-apis-system-router.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy
zh-cn/application-dev/reference/apis/js-apis-system-sensor.md @hellohyh001 @ningningW @butterls @star-wind-snow-and-rain zh-cn/application-dev/reference/apis/js-apis-system-sensor.md @hellohyh001 @ningningW @butterls @star-wind-snow-and-rain
zh-cn/application-dev/reference/apis/js-apis-system-storage.md @feng-aiwen @ge-yafang @gong-a-shi @logic42 zh-cn/application-dev/reference/apis/js-apis-system-storage.md @feng-aiwen @ge-yafang @gong-a-shi @logic42
zh-cn/application-dev/reference/apis/js-apis-system-time.md @feng-aiwen @ge-yafang @illybyy @murphy1984 zh-cn/application-dev/reference/apis/js-apis-system-time.md @feng-aiwen @ningningW @illybyy @murphy1984
zh-cn/application-dev/reference/apis/js-apis-system-timer.md @feng-aiwen @ge-yafang @illybyy @murphy1984 zh-cn/application-dev/reference/apis/js-apis-system-timer.md @feng-aiwen @ningningW @illybyy @murphy1984
zh-cn/application-dev/reference/apis/js-apis-system-vibrate.md @hellohyh001 @ningningW @butterls @star-wind-snow-and-rain zh-cn/application-dev/reference/apis/js-apis-system-vibrate.md @hellohyh001 @ningningW @butterls @star-wind-snow-and-rain
zh-cn/application-dev/reference/apis/js-apis-telephony-data.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785 zh-cn/application-dev/reference/apis/js-apis-telephony-data.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785
zh-cn/application-dev/reference/apis/js-apis-testRunner.md @inter515 @littlejerry1 @RayShih @inter515 @jiyong zh-cn/application-dev/reference/apis/js-apis-testRunner.md @inter515 @littlejerry1 @RayShih @inter515 @jiyong
...@@ -466,7 +466,7 @@ zh-cn/application-dev/reference/apis/js-apis-util.md @gongjunsong @ge-yafang @fl ...@@ -466,7 +466,7 @@ zh-cn/application-dev/reference/apis/js-apis-util.md @gongjunsong @ge-yafang @fl
zh-cn/application-dev/reference/apis/js-apis-vector.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-vector.md @gongjunsong @ge-yafang @flyingwolf @BlackStone
zh-cn/application-dev/reference/apis/js-apis-vibrator.md @hellohyh001 @ningningW @butterls @star-wind-snow-and-rain zh-cn/application-dev/reference/apis/js-apis-vibrator.md @hellohyh001 @ningningW @butterls @star-wind-snow-and-rain
zh-cn/application-dev/reference/apis/js-apis-volumemanager.md @panqinxu @zengyawen @bubble_mao @jinhaihw zh-cn/application-dev/reference/apis/js-apis-volumemanager.md @panqinxu @zengyawen @bubble_mao @jinhaihw
zh-cn/application-dev/reference/apis/js-apis-wallpaper.md @feng-aiwen @ge-yafang @wangzhangjun @murphy1984 zh-cn/application-dev/reference/apis/js-apis-wallpaper.md @feng-aiwen @ningningW @wangzhangjun @murphy1984
zh-cn/application-dev/reference/apis/js-apis-wantAgent.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-wantAgent.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen
zh-cn/application-dev/reference/apis/js-apis-webgl.md @zhangqiang183 @ge-yafang @wind_zj @zxg-gitee zh-cn/application-dev/reference/apis/js-apis-webgl.md @zhangqiang183 @ge-yafang @wind_zj @zxg-gitee
zh-cn/application-dev/reference/apis/js-apis-webgl2.md @zhangqiang183 @ge-yafang @wind_zj @zxg-gitee zh-cn/application-dev/reference/apis/js-apis-webgl2.md @zhangqiang183 @ge-yafang @wind_zj @zxg-gitee
...@@ -527,7 +527,7 @@ zh-cn/application-dev/reference/apis/js-apis-fileExtensionInfo.md @panqinxu @zen ...@@ -527,7 +527,7 @@ zh-cn/application-dev/reference/apis/js-apis-fileExtensionInfo.md @panqinxu @zen
zh-cn/application-dev/reference/apis/js-apis-freeInstall.md @shuaytao @RayShih @wangzhen107 @inter515 zh-cn/application-dev/reference/apis/js-apis-freeInstall.md @shuaytao @RayShih @wangzhen107 @inter515
zh-cn/application-dev/reference/apis/js-apis-geoLocationManager.md @cheng_guohong @RayShih @cheng_guohong @xiangkejin123 zh-cn/application-dev/reference/apis/js-apis-geoLocationManager.md @cheng_guohong @RayShih @cheng_guohong @xiangkejin123
zh-cn/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md @stone2050 @zengyawen @stesen @elsen-liu zh-cn/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md @stone2050 @zengyawen @stesen @elsen-liu
zh-cn/application-dev/reference/apis/js-apis-inputmethod-subtype.md @feng-aiwen @ge-yafang @SuperShrimp @murphy1984 zh-cn/application-dev/reference/apis/js-apis-inputmethod-subtype.md @feng-aiwen @ningningW @SuperShrimp @murphy1984
zh-cn/application-dev/reference/apis/js-apis-installer.md @shuaytao @RayShih @wangzhen107 @inter515 zh-cn/application-dev/reference/apis/js-apis-installer.md @shuaytao @RayShih @wangzhen107 @inter515
zh-cn/application-dev/reference/apis/js-apis-launcherBundleManager.md @shuaytao @RayShih @wangzhen107 @inter515 zh-cn/application-dev/reference/apis/js-apis-launcherBundleManager.md @shuaytao @RayShih @wangzhen107 @inter515
zh-cn/application-dev/reference/apis/js-apis-matrix4.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy zh-cn/application-dev/reference/apis/js-apis-matrix4.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy
...@@ -581,7 +581,7 @@ zh-cn/application-dev/reference/errorcodes/errorcode-hisysevent.md @zengyawen ...@@ -581,7 +581,7 @@ zh-cn/application-dev/reference/errorcodes/errorcode-hisysevent.md @zengyawen
zh-cn/application-dev/reference/errorcodes/errorcode-hiviewdfx-hidebug.md @zengyawen zh-cn/application-dev/reference/errorcodes/errorcode-hiviewdfx-hidebug.md @zengyawen
zh-cn/application-dev/reference/errorcodes/errorcode-huks.md @zengyawen zh-cn/application-dev/reference/errorcodes/errorcode-huks.md @zengyawen
zh-cn/application-dev/reference/errorcodes/errorcode-i18n.md @ningningW zh-cn/application-dev/reference/errorcodes/errorcode-i18n.md @ningningW
zh-cn/application-dev/reference/errorcodes/errorcode-inputmethod-framework.md @ge-yafang zh-cn/application-dev/reference/errorcodes/errorcode-inputmethod-framework.md @ningningW
zh-cn/application-dev/reference/errorcodes/errorcode-multimodalinput.md @ningningW zh-cn/application-dev/reference/errorcodes/errorcode-multimodalinput.md @ningningW
zh-cn/application-dev/reference/errorcodes/errorcode-nfc.md @RayShih zh-cn/application-dev/reference/errorcodes/errorcode-nfc.md @RayShih
zh-cn/application-dev/reference/errorcodes/errorcode-pasteboard.md @ge-yafang zh-cn/application-dev/reference/errorcodes/errorcode-pasteboard.md @ge-yafang
...@@ -589,7 +589,7 @@ zh-cn/application-dev/reference/errorcodes/errorcode-power.md @zengyawen ...@@ -589,7 +589,7 @@ zh-cn/application-dev/reference/errorcodes/errorcode-power.md @zengyawen
zh-cn/application-dev/reference/errorcodes/errorcode-preferences.md @ge-yafang zh-cn/application-dev/reference/errorcodes/errorcode-preferences.md @ge-yafang
zh-cn/application-dev/reference/errorcodes/errorcode-promptAction.md @HelloCrease zh-cn/application-dev/reference/errorcodes/errorcode-promptAction.md @HelloCrease
zh-cn/application-dev/reference/errorcodes/errorcode-reminderAgentManager.md @ningningW zh-cn/application-dev/reference/errorcodes/errorcode-reminderAgentManager.md @ningningW
zh-cn/application-dev/reference/errorcodes/errorcode-request.md @zengyawen zh-cn/application-dev/reference/errorcodes/errorcode-request.md @ningningW
zh-cn/application-dev/reference/errorcodes/errorcode-resource-manager.md @ningningW zh-cn/application-dev/reference/errorcodes/errorcode-resource-manager.md @ningningW
zh-cn/application-dev/reference/errorcodes/errorcode-router.md @HelloCrease zh-cn/application-dev/reference/errorcodes/errorcode-router.md @HelloCrease
zh-cn/application-dev/reference/errorcodes/errorcode-rpc.md @RayShih zh-cn/application-dev/reference/errorcodes/errorcode-rpc.md @RayShih
......
...@@ -149,198 +149,53 @@ The value of <*formal_param_attr*> can be **in**, **out**, or **inout**, indicat ...@@ -149,198 +149,53 @@ The value of <*formal_param_attr*> can be **in**, **out**, or **inout**, indicat
## How to Develop ## 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 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.
You can use C++ to create IDL files. An example IDL file is as follows:
```cpp > **NOTE**: Use the SDK of the latest version. The use of an earlier version may cause errors in some statements.
interface OHOS.IIdlTestService {
int TestIntTransaction([in] int data);
void TestStringTransaction([in] String data);
}
```
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 ### Development Using TS
#ifndef OHOS_IDLTESTSERVICESTUB_H
#define OHOS_IDLTESTSERVICESTUB_H
#include <iremote_stub.h>
#include "iidl_test_service.h"
namespace OHOS {
class IdlTestServiceStub : public IRemoteStub<IIdlTestService> {
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
```
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 You can use TS to create IDL files.
#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
```
The sample code for registering a service is as follows: For example, create a file named **IIdlTestService.idl** with the following content:
```cpp ```cpp
#include "test_service.h" interface OHOS.IIdlTestService {
int TestIntTransaction([in] int data);
#include <string_ex.h> void TestStringTransaction([in] String data);
}
#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<IRemoteObject> 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
``` ```
#### Calling Methods from the Client for IPC Run the **idl -gen-ts -d *dir* -c dir/IIdlTestService.idl** command in the folder where the executable file is located.
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:
```cpp -*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.
#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;
}
sptr<IRemoteObject> object = saMgr->GetSystemAbility(IPC_TEST_SERVICE); > **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 (object != nullptr) {
ZLOGE(LABEL, "Got test Service object");
testService_ = (new (std::nothrow) IdlTestServiceProxy(object));
}
if (testService_ == nullptr) { For example, for an .idl file named **IIdlTestService.idl** and target output directory named **IIdlTestServiceTs**, the directory structure is similar to the following:
ZLOGE(LABEL, "Could not find Test Service!");
return -1;
}
return 0;
}
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
``` ```
├── IIdlTestServiceTs # IDL code output folder
### Development Using TS │ ├── i_idl_test_service.ts # File generated
│ ├── idl_test_service_proxy.ts # File generated
#### Creating an IDL File │ ├── idl_test_service_stub.ts # File generated
│ └── IIdlTestService.idl # Constructed .idl file
You can use TS to create IDL files. An example IDL file is as follows: └── idl.exe # Executable file of IDL
```ts
interface OHOS.IIdlTestService {
int TestIntTransaction([in] int data);
void TestStringTransaction([in] String data);
}
``` ```
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 #### 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. 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 ...@@ -356,8 +211,8 @@ export default class IdlTestServiceStub extends rpc.RemoteObject implements IIdl
super(des); super(des);
} }
onRemoteRequest(code: number, data, reply, option): boolean { async onRemoteRequestEx(code: number, data, reply, option): Promise<boolean> {
console.log("onRemoteRequest called, code = " + code); console.log("onRemoteRequestEx called, code = " + code);
switch(code) { switch(code) {
case IdlTestServiceStub.COMMAND_TEST_INT_TRANSACTION: { case IdlTestServiceStub.COMMAND_TEST_INT_TRANSACTION: {
let _data = data.readInt(); let _data = data.readInt();
...@@ -529,137 +384,3 @@ export default class MySequenceable { ...@@ -529,137 +384,3 @@ export default class MySequenceable {
private str; 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<IdlTestServiceImpl> impl = new IdlTestServiceImpl();
napi_value napiRemoteObject = NAPI_ohos_rpc_CreateJsRemoteObject(reinterpret_cast<napi_env>(&engine), impl);
NativeValue* nativeRemoteObject = reinterpret_cast<NativeValue*>(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);
}
```
# Ability Development # Ability Development
> **NOTE**<br/>
> This folder is deprecated. Read [Application Models](../application-models/Readme-EN.md) instead.
- [Ability Framework Overview](ability-brief.md) - [Ability Framework Overview](ability-brief.md)
- [Context Usage](context-userguide.md) - [Context Usage](context-userguide.md)
- FA Model - FA Model
......
...@@ -73,10 +73,10 @@ The ability assistant enables you to start applications, atomic services, and te ...@@ -73,10 +73,10 @@ The ability assistant enables you to start applications, atomic services, and te
| -a/--all | - | Prints ability information in all missions. | | -a/--all | - | Prints ability information in all missions. |
| -l/--mission-list | type (All logs are printed if this parameter is left unspecified.)| Prints mission stack information.<br>The following values are available for **type**:<br>- NORMAL <br>- DEFAULT_STANDARD<br>- DEFAULT_SINGLE<br>- LAUNCHER | | -l/--mission-list | type (All logs are printed if this parameter is left unspecified.)| Prints mission stack information.<br>The following values are available for **type**:<br>- NORMAL <br>- DEFAULT_STANDARD<br>- DEFAULT_SINGLE<br>- LAUNCHER |
| -e/--extension | elementName | Prints extended component information. | | -e/--extension | elementName | Prints extended component information. |
| -u/--userId | UserId | Prints stack information of a specified user ID. This parameter must be used together with other parameters. <br/>Example commands: aa **dump -a -u 100** and **aa dump -d -u 100**. | | -u/--userId | UserId | Prints stack information of a specified user ID. This parameter must be used together with other parameters. <br/>Example commands: aa **dump -a -u 100** and **aa dump -d -u 100**.|
| -d/--data | - | Prints Data ability information. | | -d/--data | - | Prints Data ability information. |
| -i/--ability | AbilityRecord ID | Prints detailed information about a specified ability. | | -i/--ability | AbilityRecord ID | Prints detailed information about a specified ability. |
| -c/--client | - | Prints detailed ability information. This parameter must be used together with other parameters. <br/>Example commands: **aa dump -a -c** and **aa dump -i 21 -c**. | | -c/--client | - | Prints detailed ability information. This parameter must be used together with other parameters. <br/>Example commands: **aa dump -a -c** and **aa dump -i 21 -c**.|
**Method** **Method**
......
...@@ -46,19 +46,19 @@ For details about how to use DevEco Studio to start the test framework, see [Ope ...@@ -46,19 +46,19 @@ For details about how to use DevEco Studio to start the test framework, see [Ope
## Introduction to TestRunner ## Introduction to TestRunner
**TestRunner** is the entry class of the test framework test process. When the test process is started, the system calls related APIs in **TestRunner**. You need to inherit this class and override the **onPrepare** and **onRun** APIs. When creating an application template, DevEco Studio initializes the default **TestRunner** and starts the default **TestAbility** in the **onRun** API. You can modify the test code of **TestAbility** or override **onPrepare** and **onRun** in **TestRunner** to implement your own test code. For details, see [TestRunner](../reference/apis/js-apis-testRunner.md). **TestRunner** is the entry class of the test framework test process. When the test process is started, the system calls related APIs in **TestRunner**. You need to inherit this class and override the **onPrepare** and **onRun** APIs. When creating an application template, DevEco Studio initializes the default **TestRunner** and starts the default **TestAbility** in the **onRun** API. You can modify the test code of **TestAbility** or override **onPrepare** and **onRun** in **TestRunner** to implement your own test code. For details, see [TestRunner](../reference/apis/js-apis-application-testRunner.md).
## Introduction to AbilityDelegatorRegistry ## Introduction to AbilityDelegatorRegistry
**AbilityDelegatorRegistry** is the **AbilityDelegator** repository class provided by the test framework. You can use **AbilityDelegatorRegistry** to obtain an **AbilityDelegator** instance and the input and generated parameters **AbilityDelegatorArgs** during the test. You can use **AbilityDelegator** to invoke the function set provided by the test framework for testing and verification. For details, see [AbilityDelegatorRegistry](../reference/apis/js-apis-abilityDelegatorRegistry.md). **AbilityDelegatorRegistry** is the **AbilityDelegator** repository class provided by the test framework. You can use **AbilityDelegatorRegistry** to obtain an **AbilityDelegator** instance and the input and generated parameters **AbilityDelegatorArgs** during the test. You can use **AbilityDelegator** to invoke the function set provided by the test framework for testing and verification. For details, see [AbilityDelegatorRegistry](../reference/apis/js-apis-application-abilityDelegatorRegistry.md).
## Introduction to AbilityDelegatorArgs ## Introduction to AbilityDelegatorArgs
**AbilityDelegatorArgs** is a test parameter class provided by the test framework. You can use **AbilityDelegatorArgs** to obtain the parameters passed and generated during the test. For details, see [AbilityDelegatorArgs](../reference/apis/js-apis-application-abilityDelegatorArgs.md). **AbilityDelegatorArgs** is a test parameter class provided by the test framework. You can use **AbilityDelegatorArgs** to obtain the parameters passed and generated during the test. For details, see [AbilityDelegatorArgs](../reference/apis/js-apis-inner-application-abilityDelegatorArgs.md).
## Introduction to AbilityMonitor ## Introduction to AbilityMonitor
**AbilityMonitor** is provided by the test framework for binding to and listening for abilities. You can use **AbilityMonitor** to bind to an **Ability** instance and add **AbilityMonitor** to the listening list. When **AbilityMonitor** is bound to an ability, the creation and lifecycle changes of the ability will trigger the related callback in **AbilityMonitor**. You can test and verify the ability in these callbacks. For details, see [AbilityMonitor](../reference/apis/js-apis-application-abilityMonitor.md). **AbilityMonitor** is provided by the test framework for binding to and listening for abilities. You can use **AbilityMonitor** to bind to an **Ability** instance and add **AbilityMonitor** to the listening list. When **AbilityMonitor** is bound to an ability, the creation and lifecycle changes of the ability will trigger the related callback in **AbilityMonitor**. You can test and verify the ability in these callbacks. For details, see [AbilityMonitor](../reference/apis/js-apis-inner-application-abilityMonitor.md).
**Example** **Example**
...@@ -131,7 +131,7 @@ abilityDelegator.startAbility(want, (err, data) => { ...@@ -131,7 +131,7 @@ abilityDelegator.startAbility(want, (err, data) => {
### Scheduling the Ability Lifecycle ### Scheduling the Ability Lifecycle
**AbilityDelegator** provides APIs to display and schedule the ability lifecycle and supports the foreground and background. It works with **AbilityMonitor** to listen for the ability lifecycle. For details, see [AbilityDelegator](../reference/apis/js-apis-application-abilityDelegator.md). **AbilityDelegator** provides APIs to display and schedule the ability lifecycle and supports the foreground and background. It works with **AbilityMonitor** to listen for the ability lifecycle. For details, see [AbilityDelegator](../reference/apis/js-apis-inner-application-abilityDelegator.md).
### Running a Shell Command ### Running a Shell Command
......
...@@ -4,12 +4,12 @@ ...@@ -4,12 +4,12 @@
**Context** provides the capability of obtaining contextual information of an application. **Context** provides the capability of obtaining contextual information of an application.
The OpenHarmony application framework has two models: Feature Ability (FA) model and stage model. Correspondingly, there are two sets of context mechanisms. **application/BaseContext** is a common context base class. It uses the **stageMode** attribute to specify whether the context is used for the stage model. The OpenHarmony application framework has two models: Feature Ability (FA) model and stage model. Correspondingly, there are two sets of context mechanisms. **application/BaseContext** is a common context base class. It uses the **stageMode** attribute to specify whether the context is used for the stage model.
- FA model
Only the methods in **app/Context** can be used for the context in the FA model. Both the application-level context and ability-level context are instances of this type. If an ability-level method is invoked in the application-level context, an error occurs. Therefore, you must pay attention to the actual meaning of the **Context** instance.
- FA model
Only the methods in **app/Context** can be used for the context in the FA model. Both the application-level context and ability-level context are instances of this type. If an ability-level method is invoked in the application-level context, an error occurs. Therefore, you must pay attention to the actual meaning of the **Context** instance.
- Stage model - Stage model
The stage model has the following types of contexts: **application/Context**, **application/ApplicationContext**, **application/AbilityStageContext**, **application/ExtensionContext**, **application/AbilityContext**, and **application/FormExtensionContext**. For details about these contexts and how to use them, see [Context in the Stage Model](#context-in-the-stage-model). The stage model has the following types of contexts: **application/Context**, **application/ApplicationContext**, **application/AbilityStageContext**, **application/ExtensionContext**, **application/AbilityContext**, and **application/FormExtensionContext**. For details about these contexts and how to use them, see [Context in the Stage Model](#context-in-the-stage-model).
...@@ -239,7 +239,7 @@ export default class MainAbility extends Ability { ...@@ -239,7 +239,7 @@ export default class MainAbility extends Ability {
### application/FormExtensionContext ### application/FormExtensionContext
For details, see [FormExtensionContext](../reference/apis/js-apis-formextensioncontext.md). For details, see [FormExtensionContext](../reference/apis/js-apis-inner-application-formExtensionContext.md).
### Obtaining the Context on an ArkTS Page ### Obtaining the Context on an ArkTS Page
......
...@@ -188,7 +188,7 @@ As the entry of the ability continuation capability, **continuationManager** is ...@@ -188,7 +188,7 @@ As the entry of the ability continuation capability, **continuationManager** is
} }
``` ```
The preceding multi-device collaboration operation is performed across devices in the stage model. For details about this operation in the FA model, see [Page Ability Development](https://gitee.com/openharmony/docs/blob/master/en/application-dev/ability/fa-pageability.md). The preceding multi-device collaboration operation is performed across devices in the stage model. For details about this operation in the FA model, see [Page Ability Development](fa-pageability.md).
You can also instruct the device selection module to update the device connection state. The sample code is as follows: You can also instruct the device selection module to update the device connection state. The sample code is as follows:
......
...@@ -38,4 +38,6 @@ When an ability is started, an application process as well as a thread for this ...@@ -38,4 +38,6 @@ When an ability is started, an application process as well as a thread for this
For details about the project directory structure of the FA model, see [OpenHarmony Project Overview](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-project-overview-0000001218440650#section4154183910141). For details about the project directory structure of the FA model, see [OpenHarmony Project Overview](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-project-overview-0000001218440650#section4154183910141).
For details about how to configure the application package structure of the FA model, see [Application Package Structure Configuration File](../quick-start/package-structure.md). For details about how to configure the application package structure of the FA model, see [Application Package Structure Configuration File](../quick-start/application-configuration-file-overview-fa.md).
<!--no_check-->
\ No newline at end of file
...@@ -148,7 +148,7 @@ The basic dependency packages include: ...@@ -148,7 +148,7 @@ The basic dependency packages include:
1. Create a Data ability helper. 1. Create a Data ability helper.
For details about the APIs provided by **DataAbilityHelper**, see [DataAbilityHelper Module](../reference/apis/js-apis-dataAbilityHelper.md). For details about the APIs provided by **DataAbilityHelper**, see [DataAbilityHelper Module](../reference/apis/js-apis-inner-ability-dataAbilityHelper.md).
```js ```js
// Different from the URI defined in the config.json file, the URI passed in the parameter has an extra slash (/), because there is a DeviceID parameter between the second and the third slash (/). // Different from the URI defined in the config.json file, the URI passed in the parameter has an extra slash (/), because there is a DeviceID parameter between the second and the third slash (/).
import featureAbility from '@ohos.ability.featureAbility' import featureAbility from '@ohos.ability.featureAbility'
......
...@@ -43,7 +43,7 @@ The table below describes the **LifecycleForm** APIs, which represent the lifecy ...@@ -43,7 +43,7 @@ The table below describes the **LifecycleForm** APIs, which represent the lifecy
| onDestroy(formId: string): void | Called to notify the widget provider that a widget has been destroyed. | | onDestroy(formId: string): void | Called to notify the widget provider that a widget has been destroyed. |
| onAcquireFormState?(want: Want): formInfo.FormState | Called to instruct the widget provider to receive the status query result of a widget. | | onAcquireFormState?(want: Want): formInfo.FormState | Called to instruct the widget provider to receive the status query result of a widget. |
The table below describes the **FormProvider** APIs. For details, see [FormProvider](../reference/apis/js-apis-formprovider.md). The table below describes the **FormProvider** APIs. For details, see [FormProvider](../reference/apis/js-apis-application-formProvider.md).
**Table 2** FormProvider APIs **Table 2** FormProvider APIs
......
...@@ -61,7 +61,7 @@ By default, **singleton** is used. ...@@ -61,7 +61,7 @@ By default, **singleton** is used.
| API | Description | | API | Description |
| --------------------------------------------------- | --------------- | | --------------------------------------------------- | --------------- |
| void startAbility(parameter: StartAbilityParameter) | Starts an ability. | | void startAbility(parameter: StartAbilityParameter) | Starts an ability. |
| Context getContext(): | Obtains the application context.| | Context getContext(): | Obtains the application context.|
| void terminateSelf() | Terminates the ability. | | void terminateSelf() | Terminates the ability. |
| bool hasWindowFocus() | Checks whether the ability has focus. | | bool hasWindowFocus() | Checks whether the ability has focus. |
......
...@@ -22,7 +22,9 @@ The differences between **onCommand()** and **onConnect()** are as follows: ...@@ -22,7 +22,9 @@ The differences between **onCommand()** and **onConnect()** are as follows:
### Creating and Registering a Service Ability ### Creating and Registering a Service Ability
1. Override the Service ability-related lifecycle callbacks to implement your own logic for processing interaction requests. 1. Override the Service ability-related lifecycle callbacks to implement your own logic for processing interaction requests.
```ts ```ts
export default { export default {
...@@ -45,7 +47,7 @@ The differences between **onCommand()** and **onConnect()** are as follows: ...@@ -45,7 +47,7 @@ The differences between **onCommand()** and **onConnect()** are as follows:
} }
} }
``` ```
2. Register a Service ability. 2. Register a Service ability.
Declare the Service ability in the **config.json** file by setting its **type** attribute to **service**. Declare the Service ability in the **config.json** file by setting its **type** attribute to **service**.
......
...@@ -301,11 +301,13 @@ In the ability continuation scenario, the distributed data object is used to syn ...@@ -301,11 +301,13 @@ In the ability continuation scenario, the distributed data object is used to syn
### Restrictions ### Restrictions
1. The continuation must be performed between the same ability, which means the same bundle name, module name, and ability name. For details, see [Application Package Structure Configuration File](../quick-start/stage-structure.md). 1. The continuation must be performed between the same ability, which means the same bundle name, module name, and ability name. For details, see [Application Package Structure Configuration File](../quick-start/module-configuration-file.md).
2. Currently, the application can only implement the continuation capability. The continuation action must be initiated by the system. 2. Currently, the application can only implement the continuation capability. The continuation action must be initiated by the system.
### Best Practice ### Best Practice
For better user experience, you are advised to use the **wantParam** parameter to transmit data smaller than 100 KB and use distributed objects to transmit data larger than 100 KB. For better user experience, you are advised to use the **wantParam** parameter to transmit data smaller than 100 KB and use distributed objects to transmit data larger than 100 KB.
<!--no_check-->
\ No newline at end of file
# Ability Development # Ability Development
## When to Use ## When to Use
Ability development in the [stage model](stage-brief.md) is significantly different from that in the FA model. The stage model requires you to declare the application package structure in the **module.json5** and **app.json5** files during application development. For details about the configuration file, see [Application Package Structure Configuration File](../quick-start/stage-structure.md). To develop an ability based on the stage model, implement the following logic: Ability development in the [stage model](stage-brief.md) is significantly different from that in the FA model. The stage model requires you to declare the application package structure in the **module.json5** and **app.json5** files during application development. For details about the configuration file, see [Application Package Structure Configuration File](../quick-start/application-package-structure-stage.md). To develop an ability based on the stage model, implement the following logic:
- Create an ability that supports screen viewing and human-machine interaction. You must implement the following scenarios: ability lifecycle callbacks, obtaining ability configuration, requesting permissions, and notifying environment changes. - Create an ability that supports screen viewing and human-machine interaction. You must implement the following scenarios: ability lifecycle callbacks, obtaining ability configuration, requesting permissions, and notifying environment changes.
- Start an ability. You need to implement ability startup on the same device, on a remote device, or with a specified UI page. - Start an ability. You need to implement ability startup on the same device, on a remote device, or with a specified UI page.
- Call abilities. For details, see [Call Development](stage-call.md). - Call abilities. For details, see [Call Development](stage-call.md).
...@@ -30,7 +30,7 @@ By default, the singleton mode is used. The following is an example of the **mod ...@@ -30,7 +30,7 @@ By default, the singleton mode is used. The following is an example of the **mod
``` ```
## Creating an Ability ## Creating an Ability
### Available APIs ### Available APIs
The table below describes the APIs provided by the **AbilityStage** class, which has the **context** attribute. For details about the APIs, see [AbilityStage](../reference/apis/js-apis-application-abilitystage.md). The table below describes the APIs provided by the **AbilityStage** class, which has the **context** attribute. For details about the APIs, see [AbilityStage](../reference/apis/js-apis-app-ability-abilityStage.md).
**Table 1** AbilityStage APIs **Table 1** AbilityStage APIs
|API|Description| |API|Description|
...@@ -321,3 +321,5 @@ struct Index { ...@@ -321,3 +321,5 @@ struct Index {
} }
} }
``` ```
<!--no_check-->
\ No newline at end of file
...@@ -12,15 +12,15 @@ The stage model is designed based on the following considerations: ...@@ -12,15 +12,15 @@ The stage model is designed based on the following considerations:
- Efficient management of application processes - Efficient management of application processes
As the device memory becomes larger, the number of processes concurrently running in the system increases. If the number of concurrent processes reaches several hundreds, the overall power consumption and performance of the system will be adversely affected without effective management measures. To restrict the behavior of background processes, the stage model uses four measures: transient task, continuous task, agent task, and Work Scheduler task. With these measures, foreground processes will obtain guaranteed resources, thereby delivering a better user experience. As the device memory becomes larger, the number of processes concurrently running in the system increases. If the number of concurrent processes reaches several hundreds, the overall power consumption and performance of the system will be adversely affected without effective management measures. To restrict the behavior of background processes, the stage model uses four measures: transient task, continuous task, agent task, and Work Scheduler task. With these measures, foreground processes will obtain guaranteed resources, thereby delivering a better user experience.
- Native support for cross-device migration and multi-device collaboration - Native support for cross-device migration and multi-device collaboration
OpenHarmony is a native distributed OS. Its application framework must be designed for easier component migration and collaboration across devices. The stage model achieves this design objective by providing features such as separation between ability and UI as well as integration of UI display and service capabilities. OpenHarmony is a native distributed OS. Its application framework must be designed for easier component migration and collaboration across devices. The stage model achieves this design objective by providing features such as separation between ability and UI as well as integration of UI display and service capabilities.
- Different window forms for various device types - Different window forms for various device types
The stage model redefines the ability lifecycle. In terms of architecture, the component manager and window manager are decoupled. This facilitates adaptation between window forms and device types. The stage model redefines the ability lifecycle. In terms of architecture, the component manager and window manager are decoupled. This facilitates adaptation between window forms and device types.
## Basic Concepts ## Basic Concepts
...@@ -103,8 +103,12 @@ The processes of an application can be classified into three types: ...@@ -103,8 +103,12 @@ The processes of an application can be classified into three types:
![stageprocessmodel](figures/stageprocessmodel.png) ![stageprocessmodel](figures/stageprocessmodel.png)
## Application Package Structure ## Application Package Structure
For details about the project directory structure of the stage model, see [OpenHarmony Project Overview](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-project-overview-0000001218440650#section56487581904). For details about the project directory structure of the stage model, see [OpenHarmony Project Overview](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-project-overview-0000001218440650#section56487581904).
For details about how to configure the application package structure of the stage model, see [Application Package Structure Configuration File (Stage Model)](../quick-start/stage-structure.md). For details about how to configure the application package structure of the stage model, see [Application Package Structure Configuration File](../quick-start/application-configuration-file-overview-stage.md).
<!--no_check-->
\ No newline at end of file
...@@ -34,7 +34,7 @@ The table below describes the ability call APIs. For details, see [Ability](../r ...@@ -34,7 +34,7 @@ The table below describes the ability call APIs. For details, see [Ability](../r
**Table 2** Ability call APIs **Table 2** Ability call APIs
|API|Description| |API|Description|
|:------|:------| |:------|:------|
|startAbilityByCall(want: Want): Promise\<Caller>|Starts an ability in the foreground (through the **want** configuration) or background (default) and obtains the **Caller** object for communication with the ability. For details, see [AbilityContext](../reference/apis/js-apis-ability-context.md#abilitycontextstartabilitybycall) or [ServiceExtensionContext](../reference/apis/js-apis-service-extension-context.md#serviceextensioncontextstartabilitybycall).| |startAbilityByCall(want: Want): Promise\<Caller>|Starts an ability in the foreground (through the **want** configuration) or background (default) and obtains the **Caller** object for communication with the ability. For details, see [AbilityContext](../reference/apis/js-apis-ability-context.md#abilitycontextstartabilitybycall) or [ServiceExtensionContext](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextstartabilitybycall).|
|on(method: string, callback: CalleeCallBack): void|Callback invoked when the callee ability registers a method.| |on(method: string, callback: CalleeCallBack): void|Callback invoked when the callee ability registers a method.|
|off(method: string): void|Callback invoked when the callee ability deregisters a method.| |off(method: string): void|Callback invoked when the callee ability deregisters a method.|
|call(method: string, data: rpc.Sequenceable): Promise\<void>|Sends agreed sequenceable data to the callee ability.| |call(method: string, data: rpc.Sequenceable): Promise\<void>|Sends agreed sequenceable data to the callee ability.|
......
...@@ -31,7 +31,7 @@ Stage widget development refers to the development conducted by the widget provi ...@@ -31,7 +31,7 @@ Stage widget development refers to the development conducted by the widget provi
## Available APIs ## Available APIs
The **FormExtension** class has the following APIs. For details, see [FormExtension](../reference/apis/js-apis-formextension.md). The **FormExtension** class has the following APIs. For details, see [FormExtension](../reference/apis/js-apis-app-form-formExtensionAbility.md).
**Table 1** FormExtension APIs **Table 1** FormExtension APIs
...@@ -45,7 +45,7 @@ The **FormExtension** class has the following APIs. For details, see [FormExtens ...@@ -45,7 +45,7 @@ The **FormExtension** class has the following APIs. For details, see [FormExtens
| onDestroy(formId: string): void | Called to notify the widget provider that a **Form** instance (widget) has been destroyed. | | onDestroy(formId: string): void | Called to notify the widget provider that a **Form** instance (widget) has been destroyed. |
| onConfigurationUpdated(config: Configuration): void; | Called when the configuration of the environment where the widget is running is updated. | | onConfigurationUpdated(config: Configuration): void; | Called when the configuration of the environment where the widget is running is updated. |
The **FormExtension** class also has a member context, that is, the **FormExtensionContext** class. For details, see [FormExtensionContext](../reference/apis/js-apis-formextensioncontext.md). The **FormExtension** class also has a member context, that is, the **FormExtensionContext** class. For details, see [FormExtensionContext](../reference/apis/js-apis-inner-application-formExtensionContext.md).
**Table 2** FormExtensionContext APIs **Table 2** FormExtensionContext APIs
...@@ -54,7 +54,7 @@ The **FormExtension** class also has a member context, that is, the **FormExtens ...@@ -54,7 +54,7 @@ The **FormExtension** class also has a member context, that is, the **FormExtens
| startAbility(want: Want, callback: AsyncCallback&lt;void&gt;): void | Starts an ability. This API uses an asynchronous callback to return the result. (This is a system API and cannot be called by third-party applications.)| | startAbility(want: Want, callback: AsyncCallback&lt;void&gt;): void | Starts an ability. This API uses an asynchronous callback to return the result. (This is a system API and cannot be called by third-party applications.)|
| startAbility(want: Want): Promise&lt;void&gt; | Starts an ability. This API uses a promise to return the result. (This is a system API and cannot be called by third-party applications.)| | startAbility(want: Want): Promise&lt;void&gt; | Starts an ability. This API uses a promise to return the result. (This is a system API and cannot be called by third-party applications.)|
For details about the **FormProvider** APIs, see [FormProvider](../reference/apis/js-apis-formprovider.md). For details, see [FormProvider](../reference/apis/js-apis-application-formProvider.md).
**Table 3** FormProvider APIs **Table 3** FormProvider APIs
...@@ -412,4 +412,4 @@ The following is an example: ...@@ -412,4 +412,4 @@ The following is an example:
} }
} }
} }
``` ```
\ No newline at end of file
...@@ -71,4 +71,5 @@ OpenHarmony does not support creation of a Service Extension ability for third-p ...@@ -71,4 +71,5 @@ OpenHarmony does not support creation of a Service Extension ability for third-p
console.log('onDestroy'); console.log('onDestroy');
} }
} }
``` ```
\ No newline at end of file
...@@ -2,8 +2,6 @@ ...@@ -2,8 +2,6 @@
## When to Use ## When to Use
The **WantAgent** class encapsulates want information that specifies a particular action, which can be starting an ability or publishing a common event. You can either call **wantAgent.trigger** to trigger a **WantAgent** directly or add a **WantAgent** to a notification so that it will be triggered when users tap the notification. The **WantAgent** class encapsulates want information that specifies a particular action, which can be starting an ability or publishing a common event. You can either call **wantAgent.trigger** to trigger a **WantAgent** directly or add a **WantAgent** to a notification so that it will be triggered when users tap the notification.
## Available APIs ## Available APIs
| API | Description| | API | Description|
| ---------------------------------------------------------------------------------------------- | ----------- | | ---------------------------------------------------------------------------------------------- | ----------- |
......
# Application Test
- [arkXtest User Guide](arkxtest-guidelines.md)
- [SmartPerf User Guide](smartperf-guidelines.md)
- [wukong User Guide](wukong-guidelines.md)
# arkXtest User Guide
## Overview
To accelerate test automation of OpenHarmony, arkXtest — an automated test framework that supports both the JavaScript (JS) and TypeScript (TS) programming languages — is provided.
In this document you will learn about the key functions of arkXtest and how to use it to perform unit testing on application or system APIs and to write UI automated test scripts.
### Introduction
arkXtest is part of the OpenHarmony toolkit and provides basic capabilities of writing and running OpenHarmony automated test scripts. In terms of test script writing, arkXtest offers a wide range of APIs, including basic process APIs, assertion APIs, and APIs related to UI operations. In terms of test script running, arkXtest offers such features as identifying, scheduling, and executing test scripts, as well as summarizing test script execution results.
### Principles
arkXtest is divided into two parts: unit test framework and UI test framework.
- Unit Test Framework
As the backbone of arkXtest, the unit test framework offers such features as identifying, scheduling, and executing test scripts, as well as summarizing test script execution results. The figure below shows the main functions of the unit test framework.
![](figures/UnitTest.PNG)
The following figure shows the basic unit test process. To start the unit test framework, run the **aa test** command.
![](figures/TestFlow.PNG)
- UI Testing Framework
The UI test framework provides [UiTest APIs](../reference/apis/js-apis-uitest.md) for you to call in different test scenarios. The test scripts are executed on top of the unit test framework mentioned above.
The figure below shows the main functions of the UI test framework.
![](figures/Uitest.PNG)
### Limitations and Constraints
- The features of the UI test framework are available only in OpenHarmony 3.1 and later versions.
- The feature availability of the unit test framework varies by version. For details about the mappings between the features and versions, see [arkXtest](https://gitee.com/openharmony/testfwk_arkxtest/blob/master/README_en.md).
## Environment preparations
### Environment Requirements
Software for writing test scripts: DevEco Studio 3.0 or later
Hardware for running test scripts: PC connected to a OpenHarmony device, such as the RK3568 development board
### Setting Up the Environment
[Download DevEco Studio](https://developer.harmonyos.com/cn/develop/deveco-studio#download) and set it up as instructed on the official website.
## Creating a Test Script
1. Open DevEco Studio and create a project, where the **ohos** directory is where the test script is located.
2. Open the .ets file of the module to be tested in the project directory. Move the cursor to any position in the code, and then right-click and choose **Show Context Actions** > **Create Ohos Test** or press **Alt+Enter** and choose **Create Ohos Test** to create a test class.
## Writing a Unit Test Script
```TS
import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium'
import abilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry'
const delegator = abilityDelegatorRegistry.getAbilityDelegator()
export default function abilityTest() {
describe('ActsAbilityTest', function () {
it('testUiExample',0, async function (done) {
console.info("uitest: TestUiExample begin");
//start tested ability
await delegator.executeShellCommand('aa start -b com.ohos.uitest -a MainAbility').then(result =>{
console.info('Uitest, start ability finished:' + result)
}).catch(err => {
console.info('Uitest, start ability failed: ' + err)
})
await sleep(1000);
//check top display ability
await delegator.getCurrentTopAbility().then((Ability)=>{
console.info("get top ability");
expect(Ability.context.abilityInfo.name).assertEqual('MainAbility');
})
done();
})
function sleep(time) {
return new Promise((resolve) => setTimeout(resolve, time));
}
})
}
```
The unit test script must contain the following basic elements:
1. Import of the dependency package so that the dependent test APIs can be used.
2. Test code, mainly about the related logic, such as API invoking.
3. Invoking of the assertion APIs and setting of checkpoints. If there is no checkpoint, the test script is considered as incomplete.
## Writing a UI Test Script
You write a UI test script based on the unit test framework, adding the invoking of APIs provided by the UI test framework to implement the corresponding test logic.
In this example, the UI test script is written based on the preceding unit test script. First, add the dependency package, as shown below:
```js
import {UiDriver,BY,UiComponent,MatchPattern} from '@ohos.uitest'
```
Then, write specific test code. Specifically, implement the click action on the started application page and add checkpoint check cases.
```js
export default function abilityTest() {
describe('ActsAbilityTest', function () {
it('testUiExample',0, async function (done) {
console.info("uitest: TestUiExample begin");
//start tested ability
await delegator.executeShellCommand('aa start -b com.ohos.uitest -a MainAbility').then(result =>{
console.info('Uitest, start ability finished:' + result)
}).catch(err => {
console.info('Uitest, start ability failed: ' + err)
})
await sleep(1000);
//check top display ability
await delegator.getCurrentTopAbility().then((Ability)=>{
console.info("get top ability");
expect(Ability.context.abilityInfo.name).assertEqual('MainAbility');
})
//ui test code
//init uidriver
var driver = await UiDriver.create();
await driver.delayMs(1000);
//find button by text 'Next'
var button = await driver.findComponent(BY.text('Next'));
//click button
await button.click();
await driver.delayMs(1000);
//check text
await driver.assertComponentExist(BY.text('after click'));
await driver.pressBack();
done();
})
function sleep(time) {
return new Promise((resolve) => setTimeout(resolve, time));
}
})
}
```
## Running the Test Script
You can run a test script in DevEco Studio in any of the following modes:
- Test package level: All test cases in the test package are executed.
- Test suite level: All test cases defined in the **describe** method are executed.
- Test method level: The specified **it** method, that is, a single test case, is executed.
![](figures/Execute.PNG)
## Viewing the Test Result
After the test is complete, you can view the test result in DevEco Studio, as shown in the following figure.
![](figures/TestResult.PNG)
## FAQs
### FAQs About Unit Test Cases
#### The logs in the test case are printed after the test case result
**Problem**
The logs added to the test case are displayed after the test case execution, rather than during the test case execution.
**Possible Causes**
More than one asynchronous interface is called in the test case.<br>In principle, logs in the test case are printed before the test case execution is complete.
**Solution**
If more than one asynchronous interface is called, you are advised to encapsulate the interface invoking into the promise mode
#### Error "fail to start ability" is reported during test case execution
**Problem**
When a test case is executed, the console returns the error message "fail to start ability".
**Possible Causes**
An error occurs during the packaging of the test package, and the test framework dependency file is not included in the test package.
**Solution**
Check whether the test package contains the **OpenHarmonyTestRunner.abc** file. If the file does not exist, rebuild and pack the file and perform the test again.
#### Test case execution timeout
**Problem**
After the test case execution is complete, the console displays the error message "execute time XXms", indicating that the case execution times out.
**Possible Causes**
1. The test case is executed through an asynchronous interface, but the **done** function is not executed during the execution. As a result, the test case execution does not end until it times out.
2. The time taken for API invocation is longer than the timeout interval set for test case execution.
**Solution**
1. Check the code logic of the test case to ensure that the **done** function is executed even if the assertion fails.
2. Modify the case execution timeout settings under **Run/Debug Configurations** in DevEco Studio.
### FAQs About UI Test Cases
#### The failure log contains "Get windows failed/GetRootByWindow failed"
**Problem**
The UI test case fails to be executed. The HiLog file contains the error message "Get windows failed/GetRootByWindow failed".
**Possible Causes**
The ArkUI feature is disabled. As a result, the control tree information on the test page is not generated.
**Solution**
Run the following command, restart the device, and execute the test case again:
```shell
hdc shell param set persist.ace.testmode.enabled 1
```
#### The failure log contains "uitest-api dose not allow calling concurrently"
**Problem**
The UI test case fails to be executed. The HiLog file contains the error message "uitest-api dose not allow calling concurrently".
**Possible Causes**
1. In the test case, the **await** operator is not added to the asynchronous interface provided by the UI test framework.
2. The UI test case is executed in multiple processes. As a result, multiple UI test processes are started. The framework does not support multi-process invoking.
**Solution**
1. Check the case implementation and add the **await** operator to the asynchronous interface invoking.
2. Do not execute UI test cases in multiple processes.
#### The failure log contains "dose not exist on current UI! Check if the UI has changed after you got the widget object"
**Problem**
The UI test case fails to be executed. The HiLog file contains the error message "dose not exist on current UI! Check if the UI has changed after you got the widget object".
**Possible Causes**
After the target component is found in the code of the test case, the device UI changes. As a result, the found component is lost and the emulation operation cannot be performed.
**Solution**
Run the UI test case again.
# SmartPerf User Guide
## Overview
Performance testing helps developers detect the performance bottlenecks and deliver quality applications that meet user expectations. For this reason, SmartPerf, a performance testing tool specially designed for OpenHarmony developers, is provided.
## Introduction
SmartPerf is a reliable, easy-to-use performance and power consumption test tool built for the OpenHarmony system. It provides KPIs with test value details that help you measure the performance and power consumption of your application, such as FPS, CPU, GPU, and Ftrace.
You can use SmartPerf in two modes: visualized operation mode (SmartPerf-Device) and command-line shell mode (SmartPerf-Daemon). SmartPerf-Device supports visualized operations and floating window based operations (such as data collection control and real-time data display). SmartPerf-Daemon is applicable to devices without screens and devices with high tolerance regarding performance, for example, Hi3568.
## Principles
SmartPerf come with SmartPerf-Device and SmartPerf-Daemon. SmartPerf-Device sends data requests for KPIs (such as FPS, RAM, and Trace) through messages to SmartPerf-Daemon, which then collects and sends back data as requested, and displays the received data. SmartPerf-Daemon also allows on-demand data collection through hell commands. The figure below demonstrates the main functions of SmartPerf.
![SmartPerf](figures/SmartPerfStru.png)
## Constraints
- SmartPerf-Device and SmartPerf-Daemon are pre-installed in version 3.2 and later versions.
- SmartPerf-Device requires a screen to work correctly.
## Environment Preparations
To run SmartPerf-Daemon, you must connect the PC to an OpenHarmony device, such as the RK3568 development board.
## Performing Performance Testing
**Using SmartPerf-Device**
In the screenshots below, the RK3568 development board is used as an example.
1. Set the application for which you want to collect data.
Start SmartPerf-Device. On the home screen, select the test application and test indicators, and touch **Start Test**.
2. Control the data collection process from the floating window.
To start collection, touch **Start** in the floating window. To pause, touch the timer in the floating window to pause data collection. To resume, touch the timer again. To view the collected data in real time, double-touch the timer. To stop, touch and hold the timer. You can drag the floating window to anywhere you like.
3. View the report.
Touch **Report** to view the test report list. Touch **Report List** to view details about test indicators.
**Using SmartPerf-Daemon**
1. Access the shell and run the following command to view the help information:
```
:# SP_daemon --help
```
2. Run the collection commands.
```
:# SP_daemon -N 2 -PKG com.ohos.contacts -c -g -t -p -r
```
**Collection Commands**
| Command | Function |Mandatory|
| :-----| :--------------------- |:-----|
| -N | Set the number of collection times. |Yes|
| -PKG | Set the package name. | No|
| -PID | Sets the PID of a process (applicable to RAM).|No|
| -c | Set whether to collect CPU data. | No|
| -g | Set whether to collect GPU data. |No|
| -f | Set whether to collect FPS data. |No|
| -t | Set whether to collect temperature data. |No|
| -p | Set whether to collect current data. |No|
| -r | Set whether to collect memory data. |No|
The default output path of the test result is as follows:
```
/data/local/tmp/data.csv
```
# wukong User Guide
## Overview
Stability testing is important in that it demonstrates how an application performs under stress. For this reason, wukong, a stability testing tool specially designed for OpenHarmony developers, is provided.
In this document you will learn about the key functions of wukong and how to use it to perform stability testing.
## Introduction
wukong is part of the OpenHarmony toolkit and implements basic application stability test capabilities such as random event injection, component injection, exception capture, report generation, and data traversal of abilities.
## Principles
wukong mainly provides two types of tests: random test and special test.
- Random test
The random test is the staple service of wukong. It provides the basic startup, running, and result summary features, as shown below.
![](figures/wukongRandomTest.png)
The following figure shows the basic running process of the random test, which depends on the **hdc** command.
![](figures/wukongRandomTestFlow.png)
- Special test
The special test provides a wide range of features: traversing the components of an application in sequence, recording and playback, and sleeping and waking up.
The following figure shows the main features of the special test.
![](figures/wukongSpecialTest.png)
For details about the test commands, see [wukong](https://gitee.com/openharmony/ostest_wukong/blob/master/README.md).
## Constraints
1. wukong is pre-installed in version 3.2 and later versions.
2. In versions earlier than 3.2, you must build wukong separately and push it to the tested OpenHarmony device. The procedure is as follows:
How to build:
```
./build.sh --product-name rk3568 --build-target wukong
```
How to push:
```
hdc_std shell mount -o rw,remount /
hdc_std file send wukong /
hdc_std shell chmod a+x /wukong
hdc_std shell mv /wukong /bin/
```
## Environment Preparations
To run commands, connect the PC to an OpenHarmony device, such as the RK3568 development board.
## Performing Stability Testing
**Using wukong exec for Random Test**
Access the shell and run the following random test command:
```
# wukong exec -s 10 -i 1000 -a 0.28 -t 0.72 -c 100
```
Random test commands
| Command | Value | Description |
| -------------- | -------------- | ---------------------------------------------- |
| wukong exec | - | Works as the main command. |
| -s | 10 | Sets the random seed. The value 10 is the seed value. |
| -i | 1000 | Sets the application startup interval to 1000 ms.|
| -a | 0.28 | Sets the proportion of the random application startup test to 28%. |
| -t | 0.72 | Sets the proportion of the random touch test to 72%. |
| -c | 100 | Sets the number of execution times to 100. |
**Using wukong special for Special Test**
Access the shell and run the following commands to perform the sequential traversal test:
```bash
# wukong special -C [bundlename] -p
```
Special test commands
| Command | Value | Description |
| -------------- |-------------- | ---------------------------------------------- |
| wukong special | - | Works as the main command. |
| -C [bundlename] |[bundlename] | Sets the bundle name of the application for the sequential traversal test. |
| -p | - | Indicates a screenshot. |
## Viewing the Test Result
After the test commands are executed, the test result is automatically generated.
You can obtain the test result in the following directory:
```
Before 2022/9/22: /data/local/wukong/report/xxxxxxxx_xxxxxx/
Since 2022/9/22: /data/local/tmp/wukong/report/xxxxxxxx_xxxxxx/
```
>**NOTE**
>
>The folder for test reports is automatically generated.
Content of the folder is described in the table below.
| Folder/File | Description |
| ------------------------------------ | ------------------ |
| exception/ | Stores exception files generated during the test.|
| screenshot/ | Stores screenshots of the sequential traversal test. |
| wukong_report.csv | Stores the test report summary. |
You can view the wukong execution log in the path below:
```
reports/xxxxxxxx_xxxxxx/wukong.log
```
...@@ -10,8 +10,10 @@ ...@@ -10,8 +10,10 @@
- [Network and Connection Development](faqs-connectivity.md) - [Network and Connection Development](faqs-connectivity.md)
- [Data Management Development](faqs-data-management.md) - [Data Management Development](faqs-data-management.md)
- [Device Management Development](faqs-device-management.md) - [Device Management Development](faqs-device-management.md)
- [DFX Development](faqs-dfx.md)
- [Intl Development](faqs-international.md)
- [Native API Usage](faqs-native.md) - [Native API Usage](faqs-native.md)
- [Usage of Third- and Fourth-Party Libraries](faqs-third-party-library.md) - [Usage of Third- and Fourth-Party Libraries](faqs-third-party-library.md)
- [hdc_std Command Usage](faqs-ide.md) - [IDE Usage](faqs-ide.md)
- [IDE Usage](faqs-hdc-std.md) - [hdc_std Command Usage](faqs-hdc-std.md)
- [Development Board](faqs-development-board.md) - [Development Board](faqs-development-board.md)
\ No newline at end of file
...@@ -21,7 +21,7 @@ Applicable to: OpenHarmony SDK 3.2.2.5, stage model of API version 9 ...@@ -21,7 +21,7 @@ Applicable to: OpenHarmony SDK 3.2.2.5, stage model of API version 9
Error code 28 refers to **CURLE_OPERATION_TIMEDOUT**, which means a cURL operation timeout. For details, see any HTTP status code description available. Error code 28 refers to **CURLE_OPERATION_TIMEDOUT**, which means a cURL operation timeout. For details, see any HTTP status code description available.
Reference: [Development Guide](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-http.md#httpresponse) and [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html) Reference: [Response Codes](../reference/apis/js-apis-http.md#responsecode) and [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html)
## What does error code 6 mean for the response of \@ohos.net.http.d.ts? ## What does error code 6 mean for the response of \@ohos.net.http.d.ts?
...@@ -30,4 +30,4 @@ Applicable to: OpenHarmony SDK 3.2.3.5 ...@@ -30,4 +30,4 @@ Applicable to: OpenHarmony SDK 3.2.3.5
Error code 6 indicates a failure to resolve the host in the address. You can ping the URL carried in the request to check whether the host is accessible. Error code 6 indicates a failure to resolve the host in the address. You can ping the URL carried in the request to check whether the host is accessible.
Reference: [Development Guide](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-http.md#httpresponse) and [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html) Reference: [Response Codes](../reference/apis/js-apis-http.md#responsecode) and [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html)
# Data Management Development # Data Management Development
## How Do I Save PixelMap Data to a Database?
## How Do I Save PixelMap data to a database?
Applicable to: OpenHarmony SDK 3.2.3.5 Applicable to: OpenHarmony SDK 3.2.3.5
You can convert a **PixelMap** into a **ArrayBuffer** and save the **ArrayBuffer** to your database. You can convert a **PixelMap** into an **ArrayBuffer** and save the **ArrayBuffer** to your database.
Reference: [readPixelsToBuffer](../reference/apis/js-apis-image.md#readpixelstobuffer7-1) Reference: [readPixelsToBuffer](../reference/apis/js-apis-image.md#readpixelstobuffer7-1)
...@@ -14,11 +12,65 @@ Reference: [readPixelsToBuffer](../reference/apis/js-apis-image.md#readpixelstob ...@@ -14,11 +12,65 @@ Reference: [readPixelsToBuffer](../reference/apis/js-apis-image.md#readpixelstob
Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9
Run the hdc_std command to copy the .db, .db-shm, and .db-wal files from **/data/app/el2/100/database/Bundle name/entry/db/**, and then use the SQLite tool to open the files. Run the hdc_std command to copy the .db, .db-shm, and .db-wal files in **/data/app/el2/100/database/*bundleName*/entry/db/**, and then use the SQLite tool to open the files.
Example: Example:
``` ```
hdc_std file recv /data/app/el2/100/database/com.xxxx.xxxx/entry/db/test.db ./test.db hdc_std file recv /data/app/el2/100/database/com.xxxx.xxxx/entry/db/test.db ./test.db
``` ```
## Does the Database Has a Lock Mechanism?
Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9
The distributed data service (DDS), relational database (RDB) store, and preferences provided OpenHarmony have a lock mechanism. You do not need to bother with the lock mechanism during the development.
## What Is a Transaction in an RDB Store?
Applicable to: all versions
When a large number of operations are performed in an RDB store, an unexpected exception may cause a failure of some data operations and loss of certain data. As a result, the application may become abnormal or even crash.
A transaction is a group of tasks serving as a single logical unit. It eliminates the failure of some of the operations and loss of associated data.
## What Data Types Does an RDB Store Support?
Applicable to: OpenHarmony SDK 3.0 or later, stage model of API version 9
An RDB store supports data of the number, string, and Boolean types. The number array supports data of the Double, Long, Float, Int, or Int64 type, with a maximum precision of 17 decimal digits.
## How Do I View Database db Files?
Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9
1. Run the **hdc_std shell** command.
2. Obtain the absolute path or sandbox path of the database.
The absolute path is **/data/app/el2/<userId>/database/<bundleName>**. The default **<userId>** is **100**.
To obtain the sandbox path, run the **ps -ef | grep hapName** command to obtain the process ID of the application.
The database sandbox path is **/proc/<Application process ID>/root/data/storage/el2/database/**.
3. Run the **find ./ -name "\*.db"** command in the absolute path or sandbox path of the database.
## How Do I Store Long Text Data?
Applicable to: OpenHarmony SDK 3.2.5.5, API version 9
- Preferences support a string of up to 8192 bytes.
- The KV store supports a value of up to 4 MB.
Reference: [Preference Overview](../database/database-preference-overview.md) and [Distributed Data Service Overview](../database/database-mdds-overview.md)
## How Do I Develop DataShare on the Stage Model
Applicable to: OpenHarmony SDK 3.2.5.5, API version 9
The DataShare on the stage model cannot be used with the **DataAbility** for the FA model. The connected server application must be implemented by using **DataShareExtensionAbility**.
Reference: [DataShare Development](../database/database-datashare-guidelines.md)
# 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}.
# File Management Development # File Management Development
## Does fileio.rmdir Delete Files Recursively?
Applicable to: OpenHarmony SDK 3.2.6.3, stage model of API version 9
## What If There is No Return Value or Error Captured After getAlbums Is Called? Yes. **fileio.rmdir** deletes files recursively.
## How Do I Create a File That Does Not Exist?
Applicable to: OpenHarmony SDK 3.2.6.3, stage model of API version 9
You can use **fileio.open(filePath, 0o100, 0o666)**. The second parameter **0o100** means to create a file if it does not exist. The third parameter **mode** must also be specified.
## What If "call fail callback fail, code: 202, data: json arguments illegal" Is Displayed?
Applicable to: OpenHarmony SDK 3.2.6.3, stage model of API version 9
When the **fileio** module is used to copy files, the file path cannot start with "file:///".
## How Do I Read Files Outside the App Sandbox?
Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9
If the input parameter of the **fileio** API is **path**, only the sandbox directory of the current app obtained from the context can be accessed. To access data in other directories such as the user data, images, and videos, open the file as the data owner and operate with the file descriptor (FD) returned.
For example, to read or write a file in Media Library, perform the following steps:
1. Use **getFileAssets()** to obtain the **fileAsset** object.
2. Use **fileAsset.open()** to obtain the FD.
3. Use the obtained FD as the **fileIo** API parameter to read and write the file.
## What If the File Contains Garbled Characters?
Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9
Read the file content from the buffer, and decode the file content using **util.TextDecoder**.
Example:
```
import util from '@ohos.util'
async function readFile(path) {
let stream = fileio.createStreamSync(path, "r+");
let readOut = await stream.read(new ArrayBuffer(4096));
let textDecoder = new util.TextDecoder("utf-8", { ignoreBOM: true });
let buffer = new Uint8Array(readOut.buffer)
let readString = textDecoder.decode(buffer, { stream: false });
console.log ("[Demo] File content read: "+ readString);
}
```
## What Should I Do If There Is No Return Value or Error Captured After getAlbums Is Called?
Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9
The **ohos.permission.READ_MEDIA** permission is required for calling **getAlbums**, and this permission needs user authorization. For details, see OpenHarmony [Application Permission List](../security/permission-list.md). The **ohos.permission.READ_MEDIA** is required for using **getAlbums()**. In addition, this permission needs user authorization. For details, see [OpenHarmony Permission List](../security/permission-list.md).
1. Configure the required permission in the **module.json5** file. 1. Configure the required permission in the **module.json5** file.
``` ```
"requestPermissions": [ "requestPermissions": [
{ {
...@@ -19,7 +69,7 @@ The **ohos.permission.READ_MEDIA** permission is required for calling **getAlbum ...@@ -19,7 +69,7 @@ The **ohos.permission.READ_MEDIA** permission is required for calling **getAlbum
``` ```
2. Add the code for user authorization before the **MainAbility.ts -> onWindowStageCreate** page is loaded. 2. Add the code for user authorization before the **MainAbility.ts -> onWindowStageCreate** page is loaded.
``` ```
private requestPermissions() { private requestPermissions() {
let permissionList: Array<string> = [ let permissionList: Array<string> = [
...@@ -34,3 +84,21 @@ The **ohos.permission.READ_MEDIA** permission is required for calling **getAlbum ...@@ -34,3 +84,21 @@ The **ohos.permission.READ_MEDIA** permission is required for calling **getAlbum
}) })
} }
``` ```
## What Do I Do If the App Crashes When FetchFileResult() Is Called Multiple Times?
Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9
Each time after the **FetchFileResult** object is called, call **FetchFileResult.close()** to release and invalidate the **FetchFileResult** object .
## What If An Error Is Reported by IDE When mediaLibrary.getMediaLibrary() Is Called in the Stage Model?
Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9
In the stage model, use **mediaLibrary.getMediaLibrary(context: Context)** to obtain the media library instance.
## How Do I Sort the Data Returned by mediaLibrary.getFileAssets()?
Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9
Use the **order** attribute in **[MediaFetchOptions](../reference/apis/js-apis-medialibrary.md#mediafetchoptions7)** to sort the data returned.
# hdc_std Command Usage # hdc_std Command Usage
## Common Log Commands
## What are the commands commonly used for log management?
Applicable to: OpenHarmony SDK 3.2.2.5 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 Increasing the buffer size to 20 MB: hdc_std shell hilog -G 20M
- Capturing logs: hdc_std shell hilog &gt; log.txt
Capturing logs: hdc_std shell hilog &gt; log.txt
## What should I do to avoid log flow control? ## 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 ...@@ -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. 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 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 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.
# 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.
...@@ -24,7 +24,7 @@ APIs involved in MindSpore Lite model inference are categorized into context API ...@@ -24,7 +24,7 @@ APIs involved in MindSpore Lite model inference are categorized into context API
| ------------------ | ----------------- | | ------------------ | ----------------- |
|OH_AI_ContextHandle OH_AI_ContextCreate()|Creates a context object.| |OH_AI_ContextHandle OH_AI_ContextCreate()|Creates a context object.|
|void OH_AI_ContextSetThreadNum(OH_AI_ContextHandle context, int32_t thread_num)|Sets the number of runtime threads.| |void OH_AI_ContextSetThreadNum(OH_AI_ContextHandle context, int32_t thread_num)|Sets the number of runtime threads.|
| void OH_AI_ContextSetThreadAffinityMode(OH_AI_ContextHandle context, int mode)|Sets the affinity mode for binding runtime threads to CPU cores, which are categorized into little cores and big cores depending on the CPU frequency.| | void OH_AI_ContextSetThreadAffinityMode(OH_AI_ContextHandle context, int mode)|Sets the affinity mode for binding runtime threads to CPU cores, which are classified into large, medium, and small cores based on the CPU frequency. You only need to bind the large or medium cores, but not small cores.|
|OH_AI_DeviceInfoHandle OH_AI_DeviceInfoCreate(OH_AI_DeviceType device_type)|Creates a runtime device information object.| |OH_AI_DeviceInfoHandle OH_AI_DeviceInfoCreate(OH_AI_DeviceType device_type)|Creates a runtime device information object.|
|void OH_AI_ContextDestroy(OH_AI_ContextHandle *context)|Destroys a context object.| |void OH_AI_ContextDestroy(OH_AI_ContextHandle *context)|Destroys a context object.|
|void OH_AI_DeviceInfoSetEnableFP16(OH_AI_DeviceInfoHandle device_info, bool is_fp16)|Sets whether to enable float16 inference. This function is available only for CPU and GPU devices.| |void OH_AI_DeviceInfoSetEnableFP16(OH_AI_DeviceInfoHandle device_info, bool is_fp16)|Sets whether to enable float16 inference. This function is available only for CPU and GPU devices.|
......
...@@ -200,17 +200,19 @@ ...@@ -200,17 +200,19 @@
- [@ohos.data.dataSharePredicates](js-apis-data-dataSharePredicates.md) - [@ohos.data.dataSharePredicates](js-apis-data-dataSharePredicates.md)
- [@ohos.data.dataShareResultSet](js-apis-data-DataShareResultSet.md) - [@ohos.data.dataShareResultSet](js-apis-data-DataShareResultSet.md)
- [@ohos.data.distributedDataObject](js-apis-data-distributedobject.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.preferences](js-apis-data-preferences.md)
- [@ohos.data.rdb](js-apis-data-rdb.md) - [@ohos.data.rdb](js-apis-data-rdb.md)
- [@ohos.data.ValuesBucket](js-apis-data-ValuesBucket.md) - [@ohos.data.ValuesBucket](js-apis-data-valuesBucket.md)
- data/rdb/[resultSet](js-apis-data-resultset.md) - data/rdb
- [resultSet](js-apis-data-resultset.md)
- File Management - File Management
- [@ohos.document](js-apis-document.md) - [@ohos.document](js-apis-document.md)
- [@ohos.environment](js-apis-environment.md) - [@ohos.environment](js-apis-environment.md)
- [@ohos.data.fileAccess](js-apis-fileAccess.md) - [@ohos.data.fileAccess](js-apis-fileAccess.md)
- [@ohos.fileExtensionInfo](js-apis-fileExtensionInfo.md) - [@ohos.fileExtensionInfo](js-apis-fileExtensionInfo.md)
- [@ohos.fileio](js-apis-fileio.md) - [@ohos.fileio](js-apis-fileio.md)
- [@ohos.filemanagement.userfile_manager](js-apis-userfilemanager.md) - [@ohos.filemanagement.userFileManager](js-apis-userfilemanager.md)
- [@ohos.multimedia.medialibrary](js-apis-medialibrary.md) - [@ohos.multimedia.medialibrary](js-apis-medialibrary.md)
- [@ohos.securityLabel](js-apis-securityLabel.md) - [@ohos.securityLabel](js-apis-securityLabel.md)
- [@ohos.statfs](js-apis-statfs.md) - [@ohos.statfs](js-apis-statfs.md)
...@@ -239,10 +241,13 @@ ...@@ -239,10 +241,13 @@
- [@ohos.nfc.controller](js-apis-nfcController.md) - [@ohos.nfc.controller](js-apis-nfcController.md)
- [@ohos.nfc.tag](js-apis-nfcTag.md) - [@ohos.nfc.tag](js-apis-nfcTag.md)
- [@ohos.rpc](js-apis-rpc.md) - [@ohos.rpc](js-apis-rpc.md)
- [@ohos.wifiManager (WLAN)](js-apis-wifiManager.md)
- [@ohos.wifiManagerExt](js-apis-wifiManagerExt.md)
- [@ohos.wifi](js-apis-wifi.md) - [@ohos.wifi](js-apis-wifi.md)
- [@ohos.wifiext](js-apis-wifiext.md) - [@ohos.wifiext](js-apis-wifiext.md)
- tag/[nfctech](js-apis-nfctech.md) - tag
- tag/[tagSession](js-apis-tagSession.md) - [nfctech](js-apis-nfctech.md)
- [tagSession](js-apis-tagSession.md)
- Basic Features - Basic Features
- [@ohos.accessibility](js-apis-accessibility.md) - [@ohos.accessibility](js-apis-accessibility.md)
- [@ohos.accessibility.config](js-apis-accessibility-config.md) - [@ohos.accessibility.config](js-apis-accessibility-config.md)
...@@ -288,6 +293,7 @@ ...@@ -288,6 +293,7 @@
- [@ohos.runningLock](js-apis-runninglock.md) - [@ohos.runningLock](js-apis-runninglock.md)
- [@ohos.sensor](js-apis-sensor.md) - [@ohos.sensor](js-apis-sensor.md)
- [@ohos.settings](js-apis-settings.md) - [@ohos.settings](js-apis-settings.md)
- [@ohos.stationary](js-apis-stationary.md)
- [@ohos.systemParameterV9](js-apis-system-parameterV9.md) - [@ohos.systemParameterV9](js-apis-system-parameterV9.md)
- [@ohos.thermal](js-apis-thermal.md) - [@ohos.thermal](js-apis-thermal.md)
- [@ohos.update](js-apis-update.md) - [@ohos.update](js-apis-update.md)
...@@ -342,7 +348,6 @@ ...@@ -342,7 +348,6 @@
- [@ohos.reminderAgent](js-apis-reminderAgent.md) - [@ohos.reminderAgent](js-apis-reminderAgent.md)
- [@ohos.systemParameter](js-apis-system-parameter.md) - [@ohos.systemParameter](js-apis-system-parameter.md)
- [@ohos.usb](js-apis-usb-deprecated.md) - [@ohos.usb](js-apis-usb-deprecated.md)
- [@ohos.workScheduler](js-apis-workScheduler.md)
- [@system.app](js-apis-system-app.md) - [@system.app](js-apis-system-app.md)
- [@system.battery](js-apis-system-battery.md) - [@system.battery](js-apis-system-battery.md)
- [@system.bluetooth](js-apis-system-bluetooth.md) - [@system.bluetooth](js-apis-system-bluetooth.md)
......
# innerBundleManager<sup>(deprecated)</sup> # @ohos.bundle.innerBundleManager
The **innerBundleManager** module provides APIs for the **Home Screen** application. 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. > 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. > 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. ...@@ -41,7 +41,7 @@ This is a system API and cannot be called by third-party applications.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------- | | ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------- |
| bundleName | string | Yes | Bundle name of an application. | | 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\<Array<[LauncherAbilityInfo](js-apis-bundle-LauncherAbilityInfo.md)>> | Yes | Callback used to return an array of the launcher ability information. | | callback | AsyncCallback\<Array<[LauncherAbilityInfo](js-apis-bundle-LauncherAbilityInfo.md)>> | 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. ...@@ -69,7 +69,7 @@ This is a system API and cannot be called by third-party applications.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ---------- | ------ | ---- | ----------------------------------------------------- | | ---------- | ------ | ---- | ----------------------------------------------------- |
| bundleName | string | Yes | Bundle name of an application. | | 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** **Return value**
...@@ -216,7 +216,7 @@ This is a system API and cannot be called by third-party applications. ...@@ -216,7 +216,7 @@ This is a system API and cannot be called by third-party applications.
| Name | Type | Mandatory| Description | | 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\<Array<[LauncherAbilityInfo](js-apis-bundle-LauncherAbilityInfo.md)>> | Yes | Callback used to return an array of the launcher ability information. | | callback | AsyncCallback\<Array<[LauncherAbilityInfo](js-apis-bundle-LauncherAbilityInfo.md)>> | Yes | Callback used to return an array of the launcher ability information. |
## innerBundleManager.getAllLauncherAbilityInfos<sup>(deprecated)</sup> ## innerBundleManager.getAllLauncherAbilityInfos<sup>(deprecated)</sup>
...@@ -242,7 +242,7 @@ This is a system API and cannot be called by third-party applications. ...@@ -242,7 +242,7 @@ This is a system API and cannot be called by third-party applications.
| Name| Type | Mandatory| Description | | 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** **Return value**
......
# @ohos.accessibility.GesturePath
The **GesturePath** module provides APIs for creating gesture path information required for an accessibility application to inject gestures.
> **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 GesturePath from '@ohos.accessibility.GesturePath';
```
## GesturePath
Defines a gesture path.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
### Attributes
| Name | Type | Readable | Writable | Description |
| ------------ | ---------------------------------------- | ---- | ---- | ------ |
| points | Array&lt;[GesturePoint](js-apis-accessibility-GesturePoint.md#gesturepoint)&gt; | Yes | Yes | Gesture touch point. |
| durationTime | number | Yes | Yes | Total gesture duration, in milliseconds.|
### constructor
constructor(durationTime: number);
Constructor used to create a **GesturePath** object.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| durationTime | number | Yes| Total gesture duration, in milliseconds.|
**Example**
```ts
let gesturePath = new GesturePath.GesturePath(20);
```
# @ohos.accessibility.GesturePoint
The **GesturePoint** module provides APIs for creating gesture touch point information required for an accessibility application to inject gestures.
> **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 GesturePoint from '@ohos.accessibility.GesturePoint';
```
## GesturePoint
Defines a gesture touch point.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
### Attributes
| Name | Type | Readable | Writable | Description |
| --------- | ------ | ---- | ---- | ------- |
| positionX | number | Yes | Yes | X coordinate of the touch point.|
| positionY | number | Yes | Yes | Y coordinate of the touch point.|
### constructor
constructor(positionX: number, positionY: number);
Constructor used to create a **GesturePoint** object.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| positionX | number | Yes| X coordinate of the touch point.|
| positionY | number | Yes | Y coordinate of the touch point.|
**Example**
```ts
let gesturePoint = new GesturePoint.GesturePoint(1, 2);
```
# App Account Management # @ohos.account.appAccount
The **appAccount** module provides APIs for adding, deleting, modifying, and querying app account information, and supports inter-app authentication and distributed data synchronization. The **appAccount** module provides APIs for adding, deleting, modifying, and querying app account information, and supports inter-app authentication and distributed data synchronization.
...@@ -3173,7 +3173,7 @@ Set credentials for an app account. This API uses an asynchronous callback to re ...@@ -3173,7 +3173,7 @@ Set credentials for an app account. This API uses an asynchronous callback to re
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------------- | ------------------------- | ---- | ------------- | | -------------- | ------------------------- | ---- | ------------- |
| name | string | Yes | Name of the target app account. | | name | string | Yes | Name of the target app account. |
| credentialType | string | Yes | Type of the credential to delete. | | credentialType | string | Yes | Type of the credential to set. |
| credential | string | Yes | Credential value. | | credential | string | Yes | Credential value. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.| | callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.|
...@@ -3203,7 +3203,7 @@ Set credentials for an app account. This API uses a promise to return the result ...@@ -3203,7 +3203,7 @@ Set credentials for an app account. This API uses a promise to return the result
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------------- | ------ | ---- | ---------- | | -------------- | ------ | ---- | ---------- |
| name | string | Yes | Name of the target app account. | | name | string | Yes | Name of the target app account. |
| credentialType | string | Yes | Type of the credential to delete.| | credentialType | string | Yes | Type of the credential to set.|
| credential | string | Yes | Credential value.| | credential | string | Yes | Credential value.|
**Return value** **Return value**
...@@ -3576,7 +3576,7 @@ Obtains the credential of an app account. This API uses an asynchronous callback ...@@ -3576,7 +3576,7 @@ Obtains the credential of an app account. This API uses an asynchronous callback
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------------- | --------------------------- | ---- | -------------- | | -------------- | --------------------------- | ---- | -------------- |
| name | string | Yes | Name of the target app account. | | name | string | Yes | Name of the target app account. |
| credentialType | string | Yes | Type of the credential to delete.| | credentialType | string | Yes | Type of the credential to obtain.|
| callback | AsyncCallback&lt;string&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the credential obtained. Otherwise, **err** is an error object.| | callback | AsyncCallback&lt;string&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the credential obtained. Otherwise, **err** is an error object.|
**Example** **Example**
...@@ -3606,7 +3606,7 @@ Obtains the credential of an app account. This API uses a promise to return the ...@@ -3606,7 +3606,7 @@ Obtains the credential of an app account. This API uses a promise to return the
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------------- | ------ | ---- | ---------- | | -------------- | ------ | ---- | ---------- |
| name | string | Yes | Name of the target app account. | | name | string | Yes | Name of the target app account. |
| credentialType | string | Yes | Type of the credential to delete.| | credentialType | string | Yes | Type of the credential to obtain.|
**Return value** **Return value**
......
# Accessibility Extension Ability # @ohos.application.AccessibilityExtensionAbility
The **AccessibilityExtensionAbility** module is based on the ExtensionAbility framework and provides the **AccessibilityExtensionAbility**. The **AccessibilityExtensionAbility** module provides accessibility extension capabilities based on the ExtensionAbility framework.
>**NOTE** > **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 initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>
>The APIs of this module can be used only in the stage model.
## Modules to Import ## Modules to Import
...@@ -18,9 +16,9 @@ import AccessibilityExtensionAbility from '@ohos.application.AccessibilityExtens ...@@ -18,9 +16,9 @@ import AccessibilityExtensionAbility from '@ohos.application.AccessibilityExtens
**System capability**: SystemCapability.BarrierFree.Accessibility.Core **System capability**: SystemCapability.BarrierFree.Accessibility.Core
| Name | Type | Readable | Writable | Description | | Name | Type| Readable| Writable| Description |
| --------- | -------- | ---- | ---- | ------------------------- | | --------- | -------- | ---- | ---- | ------------------------- |
| context | [AccessibilityExtensionContext](js-apis-accessibility-extension-context.md) | Yes | No | Context of the accessibility extension ability. | | context | [AccessibilityExtensionContext](js-apis-inner-application-accessibilityExtensionContext.md) | Yes| No| Context of the accessibility extension ability.|
## AccessibilityEvent ## AccessibilityEvent
...@@ -32,36 +30,10 @@ Defines an accessibility event. ...@@ -32,36 +30,10 @@ Defines an accessibility event.
| Name | Type | Readable | Writable | Description | | Name | Type | Readable | Writable | Description |
| --------- | ---------------------------------------- | ---- | ---- | ---------- | | --------- | ---------------------------------------- | ---- | ---- | ---------- |
| eventType | [EventType](js-apis-accessibility.md#eventtype) \| [WindowUpdateType](js-apis-accessibility.md#windowupdatetype) \| [TouchGuideType](#touchguidetype) \| [GestureType](#gesturetype) \| [PageUpdateType](#pageupdatetype) | Yes | No | Event type. | | eventType | [accessibility.EventType](js-apis-accessibility.md#EventType) \| [accessibility.WindowUpdateType](js-apis-accessibility.md#WindowUpdateType) \| [TouchGuideType](#touchguidetype) \| [GestureType](#gesturetype) \| [PageUpdateType](#pageupdatetype) | Yes | No | Event type. |
| target | AccessibilityElement | Yes | No | Target component where the event occurs.| | target | AccessibilityElement | Yes | No | Target component where the event occurs.|
| timeStamp | number | Yes | No | Timestamp of the event. | | timeStamp | number | Yes | No | Timestamp of the event. |
## GesturePath
Defines a gesture path.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
### Attributes
| Name | Type | Readable | Writable | Description |
| ------------ | ---------------------------------------- | ---- | ---- | ------ |
| points | Array&lt;[GesturePoint](gesturepoint)&gt; | Yes | Yes | An array of gesture touch points. |
| durationTime | number | Yes | Yes | Total time consumed by the gesture.|
## GesturePoint
Defines a gesture touch point.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
### Attributes
| Name | Type | Readable | Writable | Description |
| --------- | ------ | ---- | ---- | ------- |
| positionX | number | Yes | Yes | X-coordinate of the touch point.|
| positionY | number | Yes | Yes | Y-coordinate of the touch point.|
## GestureType ## GestureType
Enumerates gesture types. Enumerates gesture types.
...@@ -89,7 +61,7 @@ Enumerates gesture types. ...@@ -89,7 +61,7 @@ Enumerates gesture types.
## PageUpdateType ## PageUpdateType
Enumerates the page refresh types. Enumerates the page update types.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core **System capability**: SystemCapability.BarrierFree.Accessibility.Core
...@@ -106,27 +78,25 @@ Enumerates the touch guide event types. ...@@ -106,27 +78,25 @@ Enumerates the touch guide event types.
| Name | Description | | Name | Description |
| ---------- | ------------ | | ---------- | ------------ |
| touchBegin | A touch starts in touch guide mode.| | touchBegin | Start of touch in touch guide mode. |
| touchEnd | A touch ends in touch guide mode.| | touchEnd | End of touch in touch guide mode. |
## AccessibilityExtensionAbility.onConnect ## AccessibilityExtensionAbility.onConnect
onConnect(): void; onConnect(): void;
Called when the **AccessibilityExtensionAbility** is enabled and connected to the system service. In this API, you can initialize service logic. This API can be overridden as required. Called when the **AccessibilityExtensionAbility** is enabled and connected to the system service. In this API, you can have the service logic initialized. This API can be overridden as required.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core **System capability**: SystemCapability.BarrierFree.Accessibility.Core
**Parameters**
None
**Example** **Example**
```ts ```ts
onConnect(): void { class MyAccessibilityExtensionAbility extends AccessibilityExtensionAbility {
console.log("AxExtensionAbility onConnect"); onConnect() {
} console.log('AxExtensionAbility onConnect');
}
};
``` ```
## AccessibilityExtensionAbility.onDisconnect ## AccessibilityExtensionAbility.onDisconnect
...@@ -137,16 +107,14 @@ Called when the **AccessibilityExtensionAbility** is disabled and disconnected f ...@@ -137,16 +107,14 @@ Called when the **AccessibilityExtensionAbility** is disabled and disconnected f
**System capability**: SystemCapability.BarrierFree.Accessibility.Core **System capability**: SystemCapability.BarrierFree.Accessibility.Core
**Parameters**
None
**Example** **Example**
```ts ```ts
onDisconnect(): void { class MyAccessibilityExtensionAbility extends AccessibilityExtensionAbility {
console.log("AxExtensionAbility onDisconnect"); onDisconnect() {
} console.log('AxExtensionAbility onDisconnect');
}
};
``` ```
## AccessibilityExtensionAbility.onAccessibilityEvent ## AccessibilityExtensionAbility.onAccessibilityEvent
...@@ -166,19 +134,21 @@ Called when an event that matches the specified bundle and event type occurs. In ...@@ -166,19 +134,21 @@ Called when an event that matches the specified bundle and event type occurs. In
**Example** **Example**
```ts ```ts
onAccessibilityEvent(event: AccessibilityEvent): void { class MyAccessibilityExtensionAbility extends AccessibilityExtensionAbility {
console.log("AxExtensionAbility onAccessibilityEvent"); onAccessibilityEvent(event) {
if (event.eventType == 'click') { console.log('AxExtensionAbility onAccessibilityEvent');
console.log("AxExtensionAbility onAccessibilityEvent: click"); if (event.eventType == 'click') {
console.log('AxExtensionAbility onAccessibilityEvent: click');
}
} }
} };
``` ```
## AccessibilityExtensionAbility.onKeyEvent ## AccessibilityExtensionAbility.onKeyEvent
onKeyEvent(keyEvent: inputEventClient.KeyEvent): boolean; onKeyEvent(keyEvent: KeyEvent): boolean;
Called when a physical key is pressed. In this API, you can determine whether to intercept the key event based on the service. Called when a physical key is pressed. In this API, you can determine whether to intercept an event based on the service.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core **System capability**: SystemCapability.BarrierFree.Accessibility.Core
...@@ -191,12 +161,14 @@ Called when a physical key is pressed. In this API, you can determine whether to ...@@ -191,12 +161,14 @@ Called when a physical key is pressed. In this API, you can determine whether to
**Example** **Example**
```ts ```ts
onKeyEvent(keyEvent: inputEventClient.KeyEvent): boolean { class MyAccessibilityExtensionAbility extends AccessibilityExtensionAbility {
console.log("AxExtensionAbility onKeyEvent"); onKeyEvent(keyEvent) {
if (keyEvent.keyCode == 22) { console.log('AxExtensionAbility onKeyEvent');
console.log("AxExtensionAbility onKeyEvent: intercept 22"); if (keyEvent.keyCode == 22) {
return true; console.log('AxExtensionAbility onKeyEvent: intercept 22');
return true;
}
return false;
} }
return false; };
}
``` ```
# Linear Container ArrayList # @ohos.util.ArrayList (Linear Container ArrayList)
> **NOTE** > **NOTE**
> >
...@@ -52,11 +52,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ...@@ -52,11 +52,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er
```ts ```ts
let arrayList = new ArrayList(); 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 ...@@ -90,21 +85,16 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er
**Example** **Example**
```ts ```ts
let arrayList = new ArrayList(); let arrayList = new ArrayList();
let result = arrayList.add("a"); let result = arrayList.add("a");
let result1 = arrayList.add(1); let result1 = arrayList.add(1);
let b = [1, 2, 3]; let b = [1, 2, 3];
let result2 = arrayList.add(b); let result2 = arrayList.add(b);
let c = {name: "Dylon", age: "13"}; let c = {name: "Dylon", age: "13"};
let result3 = arrayList.add(c); let result3 = arrayList.add(c);
let result4 = arrayList.add(false); 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}`);
}
```
### insert ### insert
...@@ -128,7 +118,7 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ...@@ -128,7 +118,7 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er
| ID| Error Message| | ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 10200011 | The insert method cannot be bound. | | 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** **Example**
...@@ -137,21 +127,6 @@ let arrayList = new ArrayList(); ...@@ -137,21 +127,6 @@ let arrayList = new ArrayList();
arrayList.insert("A", 0); arrayList.insert("A", 0);
arrayList.insert(0, 1); arrayList.insert(0, 1);
arrayList.insert(true, 2); 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 ### has
...@@ -189,11 +164,6 @@ let arrayList = new ArrayList(); ...@@ -189,11 +164,6 @@ let arrayList = new ArrayList();
let result = arrayList.has("squirrel"); let result = arrayList.has("squirrel");
arrayList.add("squirrel"); arrayList.add("squirrel");
let result1 = arrayList.has("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 ### getIndexOf
...@@ -236,11 +206,6 @@ arrayList.add(1); ...@@ -236,11 +206,6 @@ arrayList.add(1);
arrayList.add(2); arrayList.add(2);
arrayList.add(4); arrayList.add(4);
let result = arrayList.getIndexOf(2); 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 ### getLastIndexOf
...@@ -283,11 +248,6 @@ arrayList.add(1); ...@@ -283,11 +248,6 @@ arrayList.add(1);
arrayList.add(2); arrayList.add(2);
arrayList.add(4); arrayList.add(4);
let result = arrayList.getLastIndexOf(2); 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 ### removeByIndex
...@@ -317,7 +277,7 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ...@@ -317,7 +277,7 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er
| ID| Error Message| | ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 10200011 | The removeByIndex method cannot be bound. | | 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** **Example**
...@@ -329,21 +289,6 @@ arrayList.add(5); ...@@ -329,21 +289,6 @@ arrayList.add(5);
arrayList.add(2); arrayList.add(2);
arrayList.add(4); arrayList.add(4);
let result = arrayList.removeByIndex(2); 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 ### remove
...@@ -383,11 +328,6 @@ arrayList.add(4); ...@@ -383,11 +328,6 @@ arrayList.add(4);
arrayList.add(5); arrayList.add(5);
arrayList.add(4); arrayList.add(4);
let result = arrayList.remove(2); 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 ### removeByRange
...@@ -412,7 +352,7 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ...@@ -412,7 +352,7 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er
| ID| Error Message| | ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 10200011 | The removeByRange method cannot be bound. | | 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** **Example**
...@@ -423,21 +363,11 @@ arrayList.add(4); ...@@ -423,21 +363,11 @@ arrayList.add(4);
arrayList.add(5); arrayList.add(5);
arrayList.add(4); arrayList.add(4);
arrayList.removeByRange(2, 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
replaceAllElements(callbackfn: (value: T, index?: number, arrlist?: ArrayList&lt;T&gt;) => T, replaceAllElements(callbackFn: (value: T, index?: number, arrlist?: ArrayList&lt;T&gt;) => T,
thisArg?: Object): void thisArg?: Object): void
Replaces all elements in this container with new elements, and returns the new ones. 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 ...@@ -448,7 +378,7 @@ Replaces all elements in this container with new elements, and returns the new o
| Name| Type| Mandatory| Description| | 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.| | thisArg | Object | No| Value to use when the callback is invoked.|
callbackfn callbackfn
...@@ -481,18 +411,11 @@ arrayList.replaceAllElements((value: number, index: number)=> { ...@@ -481,18 +411,11 @@ arrayList.replaceAllElements((value: number, index: number)=> {
arrayList.replaceAllElements((value: number, index: number) => { arrayList.replaceAllElements((value: number, index: number) => {
return value = value - 2; 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
forEach(callbackfn: (value: T, index?: number, arrlist?: ArrayList&lt;T&gt;) => void, forEach(callbackFn: (value: T, index?: number, arrlist?: ArrayList&lt;T&gt;) => void,
thisArg?: Object): void thisArg?: Object): void
Uses a callback to traverse the elements in this container and obtain their position indexes. 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 ...@@ -503,7 +426,7 @@ Uses a callback to traverse the elements in this container and obtain their posi
| Name| Type| Mandatory| Description| | 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.| | thisArg | Object | No| Value to use when the callback is invoked.|
callbackfn callbackfn
...@@ -533,13 +456,6 @@ arrayList.add(4); ...@@ -533,13 +456,6 @@ arrayList.add(4);
arrayList.forEach((value, index) => { arrayList.forEach((value, index) => {
console.log(`value:${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 ### sort
...@@ -582,11 +498,6 @@ arrayList.add(4); ...@@ -582,11 +498,6 @@ arrayList.add(4);
arrayList.sort((a: number, b: number) => a - b); arrayList.sort((a: number, b: number) => a - b);
arrayList.sort((a: number, b: number) => b - a); arrayList.sort((a: number, b: number) => b - a);
arrayList.sort(); 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 ### subArrayList
...@@ -617,7 +528,7 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ...@@ -617,7 +528,7 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er
| ID| Error Message| | ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 10200011 | The subArrayList method cannot be bound. | | 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** **Example**
...@@ -630,16 +541,6 @@ arrayList.add(4); ...@@ -630,16 +541,6 @@ arrayList.add(4);
let result1 = arrayList.subArrayList(2, 4); let result1 = arrayList.subArrayList(2, 4);
let result2 = arrayList.subArrayList(4, 3); let result2 = arrayList.subArrayList(4, 3);
let result3 = arrayList.subArrayList(2, 6); 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 ### clear
...@@ -667,11 +568,6 @@ arrayList.add(4); ...@@ -667,11 +568,6 @@ arrayList.add(4);
arrayList.add(5); arrayList.add(5);
arrayList.add(4); arrayList.add(4);
arrayList.clear(); 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 ### clone
...@@ -706,11 +602,6 @@ arrayList.add(4); ...@@ -706,11 +602,6 @@ arrayList.add(4);
arrayList.add(5); arrayList.add(5);
arrayList.add(4); arrayList.add(4);
let result = arrayList.clone(); 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 ### getCapacity
...@@ -744,11 +635,6 @@ arrayList.add(4); ...@@ -744,11 +635,6 @@ arrayList.add(4);
arrayList.add(5); arrayList.add(5);
arrayList.add(4); arrayList.add(4);
let result = arrayList.getCapacity(); 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 ### convertToArray
...@@ -782,11 +668,6 @@ arrayList.add(4); ...@@ -782,11 +668,6 @@ arrayList.add(4);
arrayList.add(5); arrayList.add(5);
arrayList.add(4); arrayList.add(4);
let result = arrayList.convertToArray(); 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 ### isEmpty
...@@ -820,11 +701,6 @@ arrayList.add(4); ...@@ -820,11 +701,6 @@ arrayList.add(4);
arrayList.add(5); arrayList.add(5);
arrayList.add(4); arrayList.add(4);
let result = arrayList.isEmpty(); 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 ### increaseCapacityTo
...@@ -859,11 +735,6 @@ arrayList.add(5); ...@@ -859,11 +735,6 @@ arrayList.add(5);
arrayList.add(4); arrayList.add(4);
arrayList.increaseCapacityTo(2); arrayList.increaseCapacityTo(2);
arrayList.increaseCapacityTo(8); 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 ### trimToCurrentLength
...@@ -891,11 +762,6 @@ arrayList.add(4); ...@@ -891,11 +762,6 @@ arrayList.add(4);
arrayList.add(5); arrayList.add(5);
arrayList.add(4); arrayList.add(4);
arrayList.trimToCurrentLength(); 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] ### [Symbol.iterator]
...@@ -941,9 +807,4 @@ while(temp != undefined) { ...@@ -941,9 +807,4 @@ while(temp != undefined) {
console.log(`value:${temp}`); console.log(`value:${temp}`);
temp = iter.next().value; 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}`);
}
``` ```
# Background Task Management # @ohos.backgroundTaskManager (Background Task Management)
The **BackgroundTaskManager** module provides APIs to manage background tasks. 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 ...@@ -161,7 +161,7 @@ Requests a continuous task from the system. This API uses an asynchronous callba
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| --------- | ---------------------------------- | ---- | ---------------------------------------- | | --------- | ---------------------------------- | ---- | ---------------------------------------- |
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-Context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md).| | context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-ability-context.md).|
| bgMode | [BackgroundMode](#backgroundmode8) | Yes | Background mode requested. | | 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. | | 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&lt;void&gt; | Yes | Callback used to return the result. | | callback | AsyncCallback&lt;void&gt; | 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 ...@@ -253,7 +253,7 @@ Requests a continuous task from the system. This API uses a promise to return th
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| --------- | ---------------------------------- | ---- | ---------------------------------------- | | --------- | ---------------------------------- | ---- | ---------------------------------------- |
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-Context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md).| | context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-ability-context.md).|
| bgMode | [BackgroundMode](#backgroundmode8) | Yes | Background mode requested. | | 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. | | 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 ...@@ -339,7 +339,7 @@ Requests to cancel a continuous task. This API uses an asynchronous callback to
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ------------------------- | ---- | ---------------------------------------- | | -------- | ------------------------- | ---- | ---------------------------------------- |
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-Context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md).| | context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-ability-context.md).|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result. | | callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result. |
**Example** **Example**
...@@ -395,7 +395,7 @@ Requests to cancel a continuous task. This API uses a promise to return the resu ...@@ -395,7 +395,7 @@ Requests to cancel a continuous task. This API uses a promise to return the resu
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------- | ------- | ---- | ---------------------------------------- | | ------- | ------- | ---- | ---------------------------------------- |
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-Context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md).| | context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-ability-context.md).|
**Return value** **Return value**
...@@ -452,14 +452,14 @@ Provides the information about the suspension delay. ...@@ -452,14 +452,14 @@ Provides the information about the suspension delay.
**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask
| Name | Description | | Name | Value | Description |
| ----------------------- | --------------------- | | ----------------------- | ---- | --------------------- |
| DATA_TRANSFER | Data transfer. | | DATA_TRANSFER | 1 | Data transfer. |
| AUDIO_PLAYBACK | Audio playback. | | AUDIO_PLAYBACK | 2 | Audio playback. |
| AUDIO_RECORDING | Audio recording. | | AUDIO_RECORDING | 3 | Audio recording. |
| LOCATION | Positioning and navigation. | | LOCATION | 4 | Positioning and navigation. |
| BLUETOOTH_INTERACTION | Bluetooth-related task. | | BLUETOOTH_INTERACTION | 5 | Bluetooth-related task. |
| MULTI_DEVICE_CONNECTION | Multi-device connection. | | MULTI_DEVICE_CONNECTION | 6 | Multi-device connection. |
| WIFI_INTERACTION | WLAN-related (system API).| | WIFI_INTERACTION | 7 | WLAN-related.<br>This is a system API.|
| VOIP | Audio and video calls (system API). | | VOIP | 8 | Audio and video calls.<br>This is a system API. |
| TASK_KEEPING | Computing task (effective only for specific devices). | | TASK_KEEPING | 9 | Computing task (effective only for specific devices). |
# Brightness # Screen Brightness
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/>
> 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 Brightness module provides an API for setting the screen brightness. The Brightness module provides an API for setting the screen brightness.
> **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 system APIs.
## Modules to Import ## Modules to Import
...@@ -18,18 +20,30 @@ setValue(value: number): void ...@@ -18,18 +20,30 @@ setValue(value: number): void
Sets the screen brightness. Sets the screen brightness.
This is a system API and cannot be called by third-party applications. **System API**: This is a system API.
**System capability:** SystemCapability.PowerManager.DisplayPowerManager **System capability**: SystemCapability.PowerManager.DisplayPowerManager
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name| Type | Mandatory| Description |
| ----- | ------ | ---- | ----------- | | ------ | ------ | ---- | ----------------------- |
| value | number | Yes | Brightness value, ranging from **0** to **255**.| | value | number | Yes | Brightness value. The value ranges from 0 to 255.|
**Error codes**
For details about the error codes, see [Screen Brightness Error Codes](../errorcodes/errorcode-brightness.md).
| Code | Error Message |
|---------|---------|
| 4700101 | Operation failed. Cannot connect to service.|
**Example** **Example**
```js ```js
brightness.setValue(128); try {
brightness.setValue(128);
} catch(err) {
console.error('set brightness failed, err: ' + err);
}
``` ```
...@@ -14,6 +14,6 @@ The **CustomizeData** module provides custom metadata. ...@@ -14,6 +14,6 @@ The **CustomizeData** module provides custom metadata.
| Name | Type | Readable| Writable| Description | | Name | Type | Readable| Writable| Description |
| ------------------ | ------ | ---- | ---- | ---------------- | | ------------------ | ------ | ---- | ---- | ---------------- |
| name | string | Yes | Yes | Custom metadata name.| | name | string | Yes | Yes | Key that identifies a data element.|
| value | string | Yes | Yes | Custom metadata value. | | value | string | Yes | Yes | Value of the data element. |
| extra<sup>8+</sup> | string | Yes | Yes | Custom metadata resources. | | extra<sup>8+</sup> | string | Yes | Yes | Custom format of the data element. The value is an index to the resource that identifies the data. |
# ElementName # 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** > **NOTE**
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册