提交 ff9f26de 编写于 作者: L lijialang 提交者: Gitee

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

Signed-off-by: Nlijialang <lijialang2@huawei-partners.com>

要显示的变更太多。

To preserve performance only 1000 of 1000+ files are displayed.
此差异已折叠。
...@@ -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: > **NOTE**: Use the SDK of the latest version. The use of an earlier version may cause errors in some statements.
```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.
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**. For details about how to replace the SDK package, see [Guide to Switching to Full SDK](../quick-start/full-sdk-switch-guide.md).
#### Exposing Interfaces on the Server After obtaining the executable file, perform subsequent development steps based on your scenario.
The stub class generated by IDL is an abstract implementation of the interface class and declares all methods in the IDL file. ### Development Using TS
```cpp #### Creating an IDL File
#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. You can use TS to create IDL files.
```cpp For example, create a file named **IIdlTestService.idl** with the following content:
#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:
```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
#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);
if (object != nullptr) {
ZLOGE(LABEL, "Got test Service object");
testService_ = (new (std::nothrow) IdlTestServiceProxy(object));
}
if (testService_ == nullptr) { -*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.
ZLOGE(LABEL, "Could not find Test Service!");
return -1;
}
return 0; > **NOTE**: The generated interface class file name must be the same as that of the .idl file. Otherwise, an error occurs during code generation.
}
void TestClient::StartIntTransaction() For example, for an .idl file named **IIdlTestService.idl** and target output directory named **IIdlTestServiceTs**, the directory structure is similar to the following:
{
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,11 +4,11 @@ ...@@ -4,11 +4,11 @@
**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 - 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. 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
...@@ -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
......
# Service Ability Development
## When to Use
A Service ability is used to run tasks in the background, such as playing music or downloading files. It does not provide a UI for user interaction. Service abilities can be started by other applications or abilities and can keep running in the background even after the user switches to another application.
## Lifecycle APIs
**Table 1** Service ability lifecycle APIs
|API|Description|
|:------|:------|
|onStart?(): void|Called to initialize a Service ability when the Service ability is being created. This callback is invoked only once in the entire lifecycle of a Service ability.|
|onCommand?(want: Want, startId: number): void|Called every time a Service ability is created on the client. You can collect calling statistics and perform initialization operations in this callback.|
|onConnect?(want: Want): rpc.RemoteObject|Called when another ability is connected to the Service ability.|
|onDisconnect?(want: Want): void|Called when another ability is disconnected from the Service ability.|
|onStop?(): void|Called when the Service ability is being destroyed. You should override this callback for your Service ability to clear its resources, such as threads and registered listeners.|
The differences between **onCommand()** and **onConnect()** are as follows:
- The **onCommand()** callback is triggered each time the client starts the Service ability by calling **startAbility** or **startAbilityForResult**.
- The **onConnect()** callback is triggered each time the client establishes a new connection with the Service ability by calling **connectAbility**.
## How to Develop
### Creating and Registering a Service Ability
1. Override the Service ability-related lifecycle callbacks to implement your own logic for processing interaction requests.
```ts
export default {
onStart() {
console.log('ServiceAbility onStart');
},
onCommand(want, startId) {
console.log('ServiceAbility onCommand');
},
onConnect(want) {
console.log('ServiceAbility OnConnect');
// Below lists the implementation of ServiceAbilityStub.
return new ServiceAbilityStub('test');
},
onDisconnect(want) {
console.log('ServiceAbility OnDisConnect');
},
onStop() {
console.log('ServiceAbility onStop');
}
}
```
2. Register a Service ability.
Declare the Service ability in the **config.json** file by setting its **type** attribute to **service**.
```json
{
"module": {
"abilities": [
{
"name": ".ServiceAbility",
"type": "service",
"visible": true
...
}
]
...
}
...
}
```
### Starting a Service Ability
The **Ability** class provides the **startAbility()** API for you to start another Service ability by passing a **Want** object.
To set information about the target Service ability, you can first construct a **Want** object with the **bundleName** and **abilityName** parameters specified.
- **bundleName** specifies the bundle name of the target application.
- **abilityName** specifies the target ability name.
The following code snippet shows how to start a Service ability running on the local device:
```ts
import featureAbility from '@ohos.ability.featureAbility'
featureAbility.startAbility(
{
want:
{
bundleName: "com.jstest.service",
abilityName: "com.jstest.service.ServiceAbility"
}
}
).then((err) => {
console.log("startService success");
}).catch (err => {
console.log("startService FAILED");
});
```
In the preceding code, the **startAbility()** API is used to start the Service ability.
- If the Service ability is not running, the system initializes the Service ability, and calls **onStart()** and **onCommand()** on the Service ability in sequence.
- If the Service ability is running, the system directly calls **onCommand()** on the Service ability.
The following code snippet shows how to start a Service ability running on the remote device. For details, see [Connecting to a Remote Service Ability](#connecting-to-a-remote-service-ability).
```ts
import featureAbility from '@ohos.ability.featureAbility'
featureAbility.startAbility(
{
want:
{
deviceId: remoteDeviceId, // Remote device ID.
bundleName: "com.jstest.service",
abilityName: "com.jstest.service.ServiceAbility"
}
}
).then((err) => {
console.log("startService success");
}).catch (err => {
console.log("startService FAILED");
});
```
### Stopping a Service Ability
In normal cases, a Service ability can be stopped by itself or by the system.
- The Service ability can call **particleAbility.terminateSelf()** to stop itself.
- If the application process where the Service ability is located exits, the Service ability is reclaimed along with the process.
- If the Service ability is only accessed through **connectAbility()** (the **onCommand()** callback has never been triggered), the system stops the Service ability when the last connection to the Service ability is disconnected.
### Connecting to a Local Service Ability
If a Service ability wants to interact with a Page ability or a Service ability in another application, you must first create a connection. A Service ability allows other abilities to connect to it through **connectAbility()**.
You can use either of the following methods to connect to a Service ability:
1. Using the IDL to automatically generate code
Use OpenHarmony Interface Definition Language (IDL) to automatically generate the corresponding client, server, and **IRemoteObject** code. For details, see [Development Using TS](../IDL/idl-guidelines.md#development-using-ts).
2. Writing code in the corresponding file
When using **connectAbility()**, pass the **Want** and **ConnectOptions** objects of the target Service ability, where **ConnectOptions** encapsulates the following three callbacks that need to be implemented.
- **onConnect()**: callback used for processing when the Service ability is connected.
- **onDisconnect()**: callback used for processing when the Service ability is disconnected.
- **onFailed()**: callback used for processing when the connection to the Service ability fails.
The following code snippet shows how to implement the callbacks:
```ts
import prompt from '@system.prompt'
var option = {
onConnect: function onConnectCallback(element, proxy) {
console.log(`onConnectLocalService onConnectDone`);
if (proxy === null) {
prompt.showToast({
message: "Connect service failed"
});
return;
}
// After obtaining the proxy of the Service ability, the calling ability can communicate with the Service ability.
let data = rpc.MessageParcel.create();
let reply = rpc.MessageParcel.create();
let option = new rpc.MessageOption();
data.writeString("InuptString");
proxy.sendRequest(0, data, reply, option);
prompt.showToast({
message: "Connect service success"
});
},
onDisconnect: function onDisconnectCallback(element) {
console.log(`onConnectLocalService onDisconnectDone element:${element}`);
prompt.showToast({
message: "Disconnect service success"
});
},
onFailed: function onFailedCallback(code) {
console.log(`onConnectLocalService onFailed errCode:${code}`);
prompt.showToast({
message: "Connect local service onFailed"
});
}
};
```
The following code snippet shows how to connect to a local Service ability:
```ts
import featureAbility from '@ohos.ability.featureAbility'
let want = {
bundleName: "com.jstest.service",
abilityName: "com.jstest.service.ServiceAbility"
};
let connectId = featureAbility.connectAbility(want, option);
```
When a Service ability is connected, the **onConnect()** callback is invoked and returns an **IRemoteObject** defining the proxy used for communicating with the Service ability. OpenHarmony provides the default implementation of **IRemoteObject**. You can inherit **rpc.RemoteObject** to create a custom implementation class for interaction with the Service ability. For details, see the [RPC API Reference](..\reference\apis\js-apis-rpc.md).
The following code snippet shows how the Service ability returns itself to the calling ability:
```ts
import rpc from "@ohos.rpc"
class ServiceAbilityStub extends rpc.RemoteObject {
constructor(des: any) {
if (typeof des === 'string') {
super(des);
} else {
console.log("Error, the input param is not string");
return;
}
}
onRemoteRequest(code: number, data: any, reply: any, option: any) {
console.log("onRemoteRequest called");
// Execute the service logic.
if (code === 1) {
// Sort the input strings.
let string = data.readString();
console.log(`Input string = ${string}`);
let result = Array.from(string).sort().join('');
console.log(`Output result = ${result}`);
reply.writeString(result);
} else {
console.log(`Unknown request code`);
}
return true;
}
}
export default {
onStart() {
console.log('ServiceAbility onStart');
},
onCommand(want, startId) {
console.log('ServiceAbility onCommand');
},
onConnect(want) {
console.log('ServiceAbility OnConnect');
return new ServiceAbilityStub('ServiceAbilityRemoteObject');
},
onDisconnect(want) {
console.log('ServiceAbility OnDisConnect');
},
onStop() {
console.log('ServiceAbility onStop');
}
}
```
### Connecting to a Remote Service Ability
This feature applies only to system applications. The method of creating a **ConnectOptions** object for connecting to a remote Service ability is similar to that for connecting to a local Service ability. The differences are as follows:
- The application must apply for the data synchronization permission from the user.
- **Want** of the target Service ability must contain the remote device ID.
> **NOTE**
>
> The **getTrustedDeviceList** API of **DeviceManager** is open only to system applications. Currently, only system applications can connect to a remote Service ability.
>
> For details about the API definition, see [Device Management](..\reference\apis\js-apis-device-manager.md).
The data synchronization permission is required in the cross-device scenario. Configure the permission in the **config.json** file.
```json
{
...
"module": {
...
"reqPermissions": [{
"name": "ohos.permission.DISTRIBUTED_DATASYNC"
}]
}
}
```
The **DISTRIBUTED_DATASYNC** permission is user granted. Therefore, your application, when being started, must display a dialog box to request the permission. The sample code is as follows:
```ts
import abilityAccessCtrl from "@ohos.abilityAccessCtrl"
import bundle from '@ohos.bundle'
async function RequestPermission() {
console.info('RequestPermission begin');
let array: Array<string> = ["ohos.permission.DISTRIBUTED_DATASYNC"];
let bundleFlag = 0;
let tokenID = undefined;
let userID = 100;
let appInfo = await bundle.getApplicationInfo('ohos.samples.etsDemo', bundleFlag, userID);
tokenID = appInfo.accessTokenId;
let atManager = abilityAccessCtrl.createAtManager();
let requestPermissions: Array<string> = [];
for (let i = 0;i < array.length; i++) {
let result = await atManager.verifyAccessToken(tokenID, array[i]);
console.info("verifyAccessToken result:" + JSON.stringify(result));
if (result != abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
requestPermissions.push(array[i]);
}
}
console.info("requestPermissions:" + JSON.stringify(requestPermissions));
if (requestPermissions.length == 0 || requestPermissions == []) {
return;
}
let context = featureAbility.getContext();
context.requestPermissionsFromUser(requestPermissions, 1, (data)=>{
console.info("data:" + JSON.stringify(data));
});
console.info('RequestPermission end');
}
```
To obtain the device ID, import the **@ohos.distributedHardware.deviceManager** module, which provides **getTrustedDeviceList** to obtain the remote device ID. For details about how to use the API, see [Device Management](..\reference\apis\js-apis-device-manager.md).
To connect to a remote Service ability, you only need to define **deviceId** in **Want**. The sample code is as follows:
```ts
import featureAbility from '@ohos.ability.featureAbility'
let want = {
deviceId: remoteDeviceId,
bundleName: "com.jstest.service",
abilityName: "com.jstest.service.ServiceAbility"
};
let connectId = featureAbility.connectAbility(want, option);
```
The other implementations are the same as those for the connection to a local Service ability. For details, see the sample code provided under [Connecting to a Local Service Ability](#connecting-to-a-local-service-ability).
...@@ -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
......
...@@ -72,3 +72,4 @@ OpenHarmony does not support creation of a Service Extension ability for third-p ...@@ -72,3 +72,4 @@ OpenHarmony does not support creation of a Service Extension ability for third-p
} }
} }
``` ```
...@@ -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|
| ---------------------------------------------------------------------------------------------- | ----------- | | ---------------------------------------------------------------------------------------------- | ----------- |
......
# Service Ability Development
## When to Use
A Service ability is used to run tasks in the background, such as playing music or downloading files. It does not provide a UI for user interaction. Service abilities can be started by other applications or abilities and can remain running in the background even after the user switches to another application.
## Available APIs
**Table 1** Service ability lifecycle APIs
|API|Description|
|:------|:------|
|onStart?(): void|Called to initialize a Service ability being created. This callback is invoked only once in the entire lifecycle of a Service ability. The **Want** object passed to this callback must be null.|
|onCommand?(want: Want, startId: number): void|Called every time a Service ability is created on a client. You can collect calling statistics and perform initialization operations in this callback.|
|onConnect?(want: Want): rpc.RemoteObject|Called when another ability is connected to the Service ability.|
|onDisconnect?(want: Want): void|Called when another ability is disconnected from the Service ability.|
|onStop?(): void|Called when the Service ability is being destroyed. You should override this callback for your Service ability to clear its resources, such as threads and registered listeners.|
## How to Develop
### Creating and Registering a Service Ability
1. Override the Service ability-related lifecycle callbacks to implement your own logic for processing interaction requests.
```javascript
export default {
onStart() {
console.log('ServiceAbility onStart');
},
onCommand(want, startId) {
console.log('ServiceAbility onCommand');
},
onConnect(want) {
console.log('ServiceAbility OnConnect');
return new FirstServiceAbilityStub('test');
},
onDisconnect(want) {
console.log('ServiceAbility OnDisConnect');
},
onStop() {
console.log('ServiceAbility onStop');
},
}
```
2. Register a Service ability.
Declare the Service ability in the **config.json** file by setting its **type** attribute to **service**.
```javascript
{
"module": {
"abilities": [
{
"name": ".ServiceAbility",
"type": "service",
"visible": true
...
}
]
...
}
...
}
```
### Starting a Service Ability
The **Ability** class provides the **startAbility()** API for you to start another Service ability by passing a **Want** object.
To set information about the target Service ability, you can first construct a **Want** object with the **bundleName** and **abilityName** parameters specified. The meanings of the parameters are as follows:
- **bundleName** indicates the name of the bundle to which the target ability belongs.
- **abilityName** indicates the target ability name.
The following code snippet shows how to start a Service ability running on the local device:
```javascript
import featureAbility from '@ohos.ability.featureAbility';
let promise = featureAbility.startAbility(
{
want:
{
bundleName: "com.jstest.service",
abilityName: "com.jstest.service.ServiceAbility",
},
}
);
```
After the preceding code is executed, the **startAbility()** API is called to start the Service ability.
- If the Service ability is not running, the system calls **onStart()** to initialize the Service ability, and then calls **onCommand()** on the Service ability.
- If the Service ability is running, the system directly calls **onCommand()** on the Service ability.
The following code snippet shows how to start a Service ability running on the remote device. For details about **getRemoteDeviceId()**, see [Connecting to a Remote Service Ability](#connecting-to-a-remote-service-ability).
```javascript
import featureAbility from '@ohos.ability.featureAbility';
let promise = featureAbility.startAbility(
{
want:
{
deviceId: getRemoteDeviceId(), // Remote device ID
bundleName: "com.jstest.service",
abilityName: "com.jstest.service.ServiceAbility",
},
}
);
```
### Stopping a Service Ability
Once created, the Service ability keeps running in the background. The system does not stop or destroy it unless memory resources must be reclaimed.
### Connecting to a Local Service Ability
If you need to connect a Service ability to a Page ability or to a Service ability in another application, you must first implement the **IAbilityConnection** API for the connection. A Service ability allows other abilities to connect to it through **connectAbility()**.
You can use either of the following methods to connect to a Service ability:
1. Using the IDL to automatically generate code
Use OpenHarmony Interface Definition Language (IDL) to automatically generate the corresponding client, server, and **IRemoteObject** code. For details, see “Development Using TS" in [OpenHarmony IDL Specifications and User Guide](../IDL/idl-guidelines.md).
2. Writing code in the corresponding file
When calling **connectAbility()**, you should pass a **Want** object containing information about the target Service ability and an **IAbilityConnection** object to the API. **IAbilityConnection** provides the following callbacks that you should implement: **onConnect()**, **onDisconnect()**, and **onFailed()**. The **onConnect()** callback is invoked when a Service ability is connected, **onDisconnect()** is invoked when a Service ability is unexpectedly disconnected, and **onFailed()** is invoked when a connection to a Service ability fails.
The following code snippet shows how to implement the callbacks:
```javascript
import prompt from '@system.prompt'
var option = {
onConnect: function onConnectCallback(element, proxy) {
console.log(`onConnectLocalService onConnectDone`)
if (proxy === null) {
prompt.showToast({
message: "Connect service failed"
})
return
}
let data = rpc.MessageParcel.create()
let reply = rpc.MessageParcel.create()
let option = new rpc.MessageOption()
data.writeInterfaceToken("connect.test.token")
proxy.sendRequest(0, data, reply, option)
prompt.showToast({
message: "Connect service success"
})
},
onDisconnect: function onDisconnectCallback(element) {
console.log(`onConnectLocalService onDisconnectDone element:${element}`)
prompt.showToast({
message: "Disconnect service success"
})
},
onFailed: function onFailedCallback(code) {
console.log(`onConnectLocalService onFailed errCode:${code}`)
prompt.showToast({
message: "Connect local service onFailed"
})
}
}
```
The following code snippet shows how to connect to a local Service ability:
```javascript
import featureAbility from '@ohos.ability.featureAbility';
let connId = featureAbility.connectAbility(
{
bundleName: "com.jstest.service",
abilityName: "com.jstest.service.ServiceAbility",
},
{
onConnect: onConnectCallback,
onDisconnect: onDisconnectCallback,
onFailed: onFailedCallback,
},
);
```
When a Service ability is connected, the **onConnect()** callback is invoked and returns an **IRemoteObject** defining the proxy used for communicating with the Service ability. OpenHarmony provides a default implementation of **IRemoteObject**. You can extend **rpc.RemoteObject** to implement your own class of **IRemoteObject**.
The following code snippet shows how the Service ability instance returns itself to the calling ability:
```javascript
import rpc from "@ohos.rpc";
class FirstServiceAbilityStub extends rpc.RemoteObject {
constructor(des: any) {
if (typeof des === 'string') {
super(des)
} else {
return
}
}
onRemoteRequest(code: number, data: any, reply: any, option: any) {
console.log(printLog + ` onRemoteRequest called`)
if (code === 1) {
let string = data.readString()
console.log(printLog + ` string=${string}`)
let result = Array.from(string).sort().join('')
console.log(printLog + ` result=${result}`)
reply.writeString(result)
} else {
console.log(printLog + ` unknown request code`)
}
return true;
}
```
### Connecting to a Remote Service Ability
>**NOTE**
>
>This feature applies only to system applications, since the **getTrustedDeviceListSync** API of the **DeviceManager** class is open only to system applications.
If you need to connect a Service ability to a Page ability or another Service ability on a remote device, you must first implement the **IAbilityConnection** interface for the connection. A Service ability allows abilities on another device to connect to it through **connectAbility()**.
When calling **connectAbility()**, you should pass a **Want** object containing information about the target Service ability and an **IAbilityConnection** object to the API. **IAbilityConnection** provides the following callbacks that you should implement: **onConnect()**, **onDisconnect()**, and **onFailed()**. The **onConnect()** callback is invoked when a Service ability is connected, **onDisconnect()** is invoked when a Service ability is unexpectedly disconnected, and **onFailed()** is invoked when a connection to a Service ability fails.
The following code snippet shows how to implement the callbacks:
```ts
import prompt from '@system.prompt'
var option = {
onConnect: function onConnectCallback(element, proxy) {
console.log(`onConnectRemoteService onConnectDone`)
if (proxy === null) {
prompt.showToast({
message: "Connect service failed"
})
return
}
let data = rpc.MessageParcel.create()
let reply = rpc.MessageParcel.create()
let option = new rpc.MessageOption()
data.writeInterfaceToken("connect.test.token")
proxy.sendRequest(0, data, reply, option)
prompt.showToast({
message: "Connect service success"
})
},
onDisconnect: function onDisconnectCallback(element) {
console.log(`onConnectRemoteService onDisconnectDone element:${element}`)
prompt.showToast({
message: "Disconnect service success"
})
},
onFailed: function onFailedCallback(code) {
console.log(`onConnectRemoteService onFailed errCode:${code}`)
prompt.showToast({
message: "Connect local service onFailed"
})
}
}
```
The **Want** of the target Service ability must contain the remote **deviceId**, which can be obtained from **DeviceManager**. The sample code is as follows:
```ts
import deviceManager from '@ohos.distributedHardware.deviceManager';
// For details about the implementation of dmClass, see the implementation in Distributed Demo in Samples.
let dmClass;
function getRemoteDeviceId() {
if (typeof dmClass === 'object' && dmClass != null) {
let list = dmClass.getTrustedDeviceListSync();
if (typeof (list) == 'undefined' || typeof (list.length) == 'undefined') {
console.log("MainAbility onButtonClick getRemoteDeviceId err: list is null");
return;
}
console.log("MainAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId);
return list[0].deviceId;
} else {
console.log("MainAbility onButtonClick getRemoteDeviceId err: dmClass is null");
}
}
```
The following code snippet shows how to connect to a remote Service ability:
```ts
import featureAbility from '@ohos.ability.featureAbility';
let connId = featureAbility.connectAbility(
{
deviceId: getRemoteDeviceId(),
bundleName: "ohos.samples.etsDemo",
abilityName: "ohos.samples.etsDemo.ServiceAbility",
},
{
onConnect: onConnectCallback,
onDisconnect: onDisconnectCallback,
onFailed: onFailedCallback,
},
);
```
In the cross-device scenario, the application must also apply for the data synchronization permission from end users. The sample code is as follows:
```ts
import abilityAccessCtrl from "@ohos.abilityAccessCtrl";
import bundle from '@ohos.bundle';
async function RequestPermission() {
console.info('RequestPermission begin');
let array: Array<string> = ["ohos.permission.DISTRIBUTED_DATASYNC"];
let bundleFlag = 0;
let tokenID = undefined;
let userID = 100;
let appInfo = await bundle.getApplicationInfo('ohos.samples.etsDemo', bundleFlag, userID);
tokenID = appInfo.accessTokenId;
let atManager = abilityAccessCtrl.createAtManager();
let requestPermissions: Array<string> = [];
for (let i = 0;i < array.length; i++) {
let result = await atManager.verifyAccessToken(tokenID, array[i]);
console.info("verifyAccessToken result:" + JSON.stringify(result));
if (result == abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
} else {
requestPermissions.push(array[i]);
}
}
console.info("requestPermissions:" + JSON.stringify(requestPermissions));
if (requestPermissions.length == 0 || requestPermissions == []) {
return;
}
let context = featureAbility.getContext();
context.requestPermissionsFromUser(requestPermissions, 1, (data)=>{
console.info("data:" + JSON.stringify(data));
});
console.info('RequestPermission end');
}
```
When a Service ability is connected, the **onConnect()** callback is invoked and returns an **IRemoteObject** defining the proxy used for communicating with the Service ability. OpenHarmony provides a default implementation of **IRemoteObject**. You can extend **rpc.RemoteObject** to implement your own class of **IRemoteObject**.
The following code snippet shows how the Service ability instance returns itself to the calling ability:
```ts
import rpc from "@ohos.rpc";
class FirstServiceAbilityStub extends rpc.RemoteObject {
constructor(des: any) {
if (typeof des === 'string') {
super(des)
} else {
return
}
}
onRemoteRequest(code: number, data: any, reply: any, option: any) {
console.log(printLog + ` onRemoteRequest called`)
if (code === 1) {
let string = data.readString()
console.log(printLog + ` string=${string}`)
let result = Array.from(string).sort().join('')
console.log(printLog + ` result=${result}`)
reply.writeString(result)
} else {
console.log(printLog + ` unknown request code`)
}
return true;
}
}
export default {
onStart() {
console.info('ServiceAbility onStart');
},
onStop() {
console.info('ServiceAbility onStop');
},
onConnect(want) {
console.log("ServiceAbility onConnect");
try {
let value = JSON.stringify(want);
console.log("ServiceAbility want:" + value);
} catch(error) {
console.log("ServiceAbility error:" + error);
}
return new FirstServiceAbilityStub("first ts service stub");
},
onDisconnect(want) {
console.log("ServiceAbility onDisconnect");
let value = JSON.stringify(want);
console.log("ServiceAbility want:" + value);
},
onCommand(want, startId) {
console.info('ServiceAbility onCommand');
let value = JSON.stringify(want);
console.log("ServiceAbility want:" + value);
console.log("ServiceAbility startId:" + startId);
}
};
```
...@@ -14,6 +14,8 @@ The sample server provides a package search server for checking update packages ...@@ -14,6 +14,8 @@ The sample server provides a package search server for checking update packages
openssl req -newkey rsa:2048 -nodes -keyout serverKey.pem -x509 -days 365 -out serverCert.cer -subj "/C=CN/ST=GD/L=GZ/O=abc/OU=defg/CN=hijk/emailAddress=test.com" openssl req -newkey rsa:2048 -nodes -keyout serverKey.pem -x509 -days 365 -out serverCert.cer -subj "/C=CN/ST=GD/L=GZ/O=abc/OU=defg/CN=hijk/emailAddress=test.com"
``` ```
2. Modify the **bundle.json** file. 2. Modify the **bundle.json** file.
Add **sub_component** to the **build** field. Add **sub_component** to the **build** field.
...@@ -173,7 +175,7 @@ The sample server provides a package search server for checking update packages ...@@ -173,7 +175,7 @@ The sample server provides a package search server for checking update packages
"\"descriptPackageId\": \"abcdefg1234567ABCDEFG\"," "\"descriptPackageId\": \"abcdefg1234567ABCDEFG\","
"}]," "}],"
"\"descriptInfo\": [{" "\"descriptInfo\": [{"
"\"descriptPackageId\": \"abcdefg1234567ABCDEFG\"," "\"descriptionType\": 0,"
"\"content\": \"This package message is used for sampleContent\"" "\"content\": \"This package message is used for sampleContent\""
"}]" "}]"
"}"; "}";
......
...@@ -30,7 +30,7 @@ The following is an example of the JSON response returned by the server. Note th ...@@ -30,7 +30,7 @@ The following is an example of the JSON response returned by the server. Note th
"descriptPackageId": "abcdefg1234567ABCDEFG" "descriptPackageId": "abcdefg1234567ABCDEFG"
}], }],
"descriptInfo": [{ "descriptInfo": [{
"descriptPackageId": "abcdefg1234567ABCDEFG", "descriptionType": 0,
"content": "This package is used for update." "content": "This package is used for update."
}] }]
} }
......
...@@ -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.
...@@ -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.
...@@ -2,11 +2,11 @@ ...@@ -2,11 +2,11 @@
## Introduction ## Introduction
You can use audio playback APIs to convert audio data into audible analog signals and play the signals using output devices. You can also manage playback tasks. For example, you can start, suspend, stop playback, release resources, set the volume, seek to a playback position, and obtain track information. You can use audio playback APIs to convert audio data into audible analog signals and play the signals using output devices. You can also manage playback tasks. For example, you can control the playback and volume, obtain track information, and release resources.
## Working Principles ## Working Principles
The following figures show the audio playback status changes and the interaction with external modules for audio playback. The following figures show the audio playback state transition and the interaction with external modules for audio playback.
**Figure 1** Audio playback state transition **Figure 1** Audio playback state transition
...@@ -28,7 +28,7 @@ For details about the APIs, see [AudioPlayer in the Media API](../reference/apis ...@@ -28,7 +28,7 @@ For details about the APIs, see [AudioPlayer in the Media API](../reference/apis
> **NOTE** > **NOTE**
> >
> The method for obtaining the path in the FA model is different from that in the stage model. **pathDir** used in the sample code below is an example. You need to obtain the path based on project requirements. For details about how to obtain the path, see [Application Sandbox Path Guidelines](../reference/apis/js-apis-fileio.md#guidelines). > The method for obtaining the path in the FA model is different from that in the stage model. For details about how to obtain the path, see [Application Sandbox Path Guidelines](../reference/apis/js-apis-fileio.md#guidelines).
### Full-Process Scenario ### Full-Process Scenario
...@@ -109,7 +109,7 @@ async function audioPlayerDemo() { ...@@ -109,7 +109,7 @@ async function audioPlayerDemo() {
setCallBack(audioPlayer); // Set the event callbacks. setCallBack(audioPlayer); // Set the event callbacks.
// 2. Set the URI of the audio file. // 2. Set the URI of the audio file.
let fdPath = 'fd://' let fdPath = 'fd://'
let pathDir = "/data/storage/el2/base/haps/entry/files" // The method for obtaining pathDir in the FA model is different from that in the stage model. For details, see NOTE just below How to Develop. You need to obtain pathDir based on project requirements. let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements.
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command. // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command.
let path = pathDir + '/01.mp3' let path = pathDir + '/01.mp3'
await fileIO.open(path).then((fdNumber) => { await fileIO.open(path).then((fdNumber) => {
...@@ -151,7 +151,7 @@ export class AudioDemo { ...@@ -151,7 +151,7 @@ export class AudioDemo {
let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance.
this.setCallBack(audioPlayer); // Set the event callbacks. this.setCallBack(audioPlayer); // Set the event callbacks.
let fdPath = 'fd://' let fdPath = 'fd://'
let pathDir = "/data/storage/el2/base/haps/entry/files" // The method for obtaining pathDir in the FA model is different from that in the stage model. For details, see NOTE just below How to Develop. You need to obtain pathDir based on project requirements. let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements.
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command. // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command.
let path = pathDir + '/01.mp3' let path = pathDir + '/01.mp3'
await fileIO.open(path).then((fdNumber) => { await fileIO.open(path).then((fdNumber) => {
...@@ -199,7 +199,7 @@ export class AudioDemo { ...@@ -199,7 +199,7 @@ export class AudioDemo {
async nextMusic(audioPlayer) { async nextMusic(audioPlayer) {
this.isNextMusic = true; this.isNextMusic = true;
let nextFdPath = 'fd://' let nextFdPath = 'fd://'
let pathDir = "/data/storage/el2/base/haps/entry/files" // The method for obtaining pathDir in the FA model is different from that in the stage model. For details, see NOTE just below How to Develop. You need to obtain pathDir based on project requirements. let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements.
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\02.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command. // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\02.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command.
let nextpath = pathDir + '/02.mp3' let nextpath = pathDir + '/02.mp3'
await fileIO.open(nextpath).then((fdNumber) => { await fileIO.open(nextpath).then((fdNumber) => {
...@@ -217,7 +217,7 @@ export class AudioDemo { ...@@ -217,7 +217,7 @@ export class AudioDemo {
let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance.
this.setCallBack(audioPlayer); // Set the event callbacks. this.setCallBack(audioPlayer); // Set the event callbacks.
let fdPath = 'fd://' let fdPath = 'fd://'
let pathDir = "/data/storage/el2/base/haps/entry/files" // The method for obtaining pathDir in the FA model is different from that in the stage model. For details, see NOTE just below How to Develop. You need to obtain pathDir based on project requirements. let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements.
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command. // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command.
let path = pathDir + '/01.mp3' let path = pathDir + '/01.mp3'
await fileIO.open(path).then((fdNumber) => { await fileIO.open(path).then((fdNumber) => {
...@@ -256,7 +256,7 @@ export class AudioDemo { ...@@ -256,7 +256,7 @@ export class AudioDemo {
let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance.
this.setCallBack(audioPlayer); // Set the event callbacks. this.setCallBack(audioPlayer); // Set the event callbacks.
let fdPath = 'fd://' let fdPath = 'fd://'
let pathDir = "/data/storage/el2/base/haps/entry/files" // The method for obtaining pathDir in the FA model is different from that in the stage model. For details, see NOTE just below How to Develop. You need to obtain pathDir based on project requirements. let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements.
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command. // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command.
let path = pathDir + '/01.mp3' let path = pathDir + '/01.mp3'
await fileIO.open(path).then((fdNumber) => { await fileIO.open(path).then((fdNumber) => {
......
...@@ -81,6 +81,9 @@ for (let index = 0; index < cameraArray.length; index++) { ...@@ -81,6 +81,9 @@ for (let index = 0; index < cameraArray.length; index++) {
// Create a camera input stream. // Create a camera input stream.
let cameraInput = await cameraManager.createCameraInput(cameraArray[0]) let cameraInput = await cameraManager.createCameraInput(cameraArray[0])
// Open camera
await cameraInput.open();
// Obtain the output stream capabilities supported by the camera. // Obtain the output stream capabilities supported by the camera.
let cameraOutputCap = await cameraManager.getSupportedOutputCapability(cameraArray[0]); let cameraOutputCap = await cameraManager.getSupportedOutputCapability(cameraArray[0]);
if (!cameraOutputCap) { if (!cameraOutputCap) {
......
...@@ -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.|
......
# 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.
...@@ -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**
......
# EnterpriseAdminExtensionAbility # @ohos.enterprise.EnterpriseAdminExtensionAbility
The **EnterpriseAdminExtensionAbility** module provides Extension abilities for enterprise administrators. The **EnterpriseAdminExtensionAbility** module provides Extension abilities for enterprise administrators.
......
# Ability # @ohos.ability.ability
The **Ability** module provides all level-2 module APIs for developers to export. The **Ability** module provides all level-2 module APIs for developers to export.
...@@ -37,5 +37,3 @@ let abilityResult: ability.AbilityResult; ...@@ -37,5 +37,3 @@ let abilityResult: ability.AbilityResult;
let connectOptions: ability.ConnectOptions; let connectOptions: ability.ConnectOptions;
let startAbilityParameter: ability.StartAbilityParameter; let startAbilityParameter: ability.StartAbilityParameter;
``` ```
<!--no_check-->
\ No newline at end of file
# DataUriUtils # @ohos.ability.dataUriUtils
The **DataUriUtils** module provides APIs to handle utility classes for objects using the **DataAbilityHelper** schema. You can use the APIs to attach an ID to the end of a given URI and obtain, delete, or update the ID attached to the end of a given URI. The **DataUriUtils** module provides APIs to handle utility classes for objects using the **DataAbilityHelper** schema. You can use the APIs to attach an ID to the end of a given URI and obtain, delete, or update the ID attached to the end of a given URI. This module will be replaced by the **app.ability.dataUriUtils** module in the near future. You are advised to use the **[@ohos.app.ability.dataUriUtils](js-apis-app-ability-dataUriUtils.md)** module.
> **NOTE** > **NOTE**
> >
...@@ -8,7 +8,7 @@ The **DataUriUtils** module provides APIs to handle utility classes for objects ...@@ -8,7 +8,7 @@ The **DataUriUtils** module provides APIs to handle utility classes for objects
## Modules to Import ## Modules to Import
```js ```ts
import dataUriUtils from '@ohos.ability.dataUriUtils'; import dataUriUtils from '@ohos.ability.dataUriUtils';
``` ```
...@@ -34,7 +34,7 @@ Obtains the ID attached to the end of a given URI. ...@@ -34,7 +34,7 @@ Obtains the ID attached to the end of a given URI.
**Example** **Example**
```js ```ts
dataUriUtils.getId("com.example.dataUriUtils/1221") dataUriUtils.getId("com.example.dataUriUtils/1221")
``` ```
...@@ -63,7 +63,7 @@ Attaches an ID to the end of a given URI. ...@@ -63,7 +63,7 @@ Attaches an ID to the end of a given URI.
**Example** **Example**
```js ```ts
var idint = 1122; var idint = 1122;
dataUriUtils.attachId( dataUriUtils.attachId(
"com.example.dataUriUtils", "com.example.dataUriUtils",
...@@ -95,12 +95,10 @@ Deletes the ID from the end of a given URI. ...@@ -95,12 +95,10 @@ Deletes the ID from the end of a given URI.
**Example** **Example**
```js ```ts
dataUriUtils.deleteId("com.example.dataUriUtils/1221") dataUriUtils.deleteId("com.example.dataUriUtils/1221")
``` ```
## dataUriUtils.updateId ## dataUriUtils.updateId
updateId(uri: string, id: number): string updateId(uri: string, id: number): string
...@@ -124,7 +122,7 @@ Updates the ID in a given URI. ...@@ -124,7 +122,7 @@ Updates the ID in a given URI.
**Example** **Example**
```js ```ts
var idint = 1122; var idint = 1122;
dataUriUtils.updateId( dataUriUtils.updateId(
"com.example.dataUriUtils", "com.example.dataUriUtils",
......
# ErrorCode # @ohos.ability.errorCode
The **ErrorCode** module defines the error codes that can be used when the ability is started. The **ErrorCode** module defines the error codes that can be used when the ability is started.
> **NOTE** **NOTE**
>
> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import ## Modules to Import
``` ```ts
import errorCode from '@ohos.ability.errorCode' import errorCode from '@ohos.ability.errorCode'
``` ```
......
# FeatureAbility # @ohos.ability.featureAbility
The **FeatureAbility** module provides a UI for interacting with users. You can use APIs of this module to start a new ability, obtain the **dataAbilityHelper**, set a Page ability, obtain the window corresponding to this ability, and connect to a Service ability. The **FeatureAbility** module provides a UI for interacting with users. You can use APIs of this module to start a new ability, obtain the **dataAbilityHelper**, set a Page ability, obtain the window corresponding to this ability, and connect to a Service ability.
...@@ -13,7 +13,7 @@ APIs of the **FeatureAbility** module can be called only by Page abilities. ...@@ -13,7 +13,7 @@ APIs of the **FeatureAbility** module can be called only by Page abilities.
## Modules to Import ## Modules to Import
``` ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
``` ```
...@@ -29,12 +29,12 @@ Starts an ability. This API uses an asynchronous callback to return the result. ...@@ -29,12 +29,12 @@ Starts an ability. This API uses an asynchronous callback to return the result.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| --------- | ---------------------------------------- | ---- | -------------- | | --------- | ---------------------------------------- | ---- | -------------- |
| parameter | [StartAbilityParameter](#startabilityparameter) | Yes | Ability to start.| | parameter | [StartAbilityParameter](js-apis-inner-ability-startAbilityParameter.md) | Yes | Ability to start.|
| callback | AsyncCallback\<number> | Yes | Callback used to return the result. | | callback | AsyncCallback\<number> | Yes | Callback used to return the result. |
**Example** **Example**
```javascript ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
import wantConstant from '@ohos.ability.wantConstant'; import wantConstant from '@ohos.ability.wantConstant';
featureAbility.startAbility( featureAbility.startAbility(
...@@ -72,11 +72,11 @@ Starts an ability. This API uses a promise to return the result. ...@@ -72,11 +72,11 @@ Starts an ability. This API uses a promise to return the result.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| --------- | ---------------------------------------- | ---- | -------------- | | --------- | ---------------------------------------- | ---- | -------------- |
| parameter | [StartAbilityParameter](#startabilityparameter) | Yes | Ability to start.| | parameter | [StartAbilityParameter](js-apis-inner-ability-startAbilityParameter.md) | Yes | Ability to start.|
**Example** **Example**
```javascript ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
import wantConstant from '@ohos.ability.wantConstant'; import wantConstant from '@ohos.ability.wantConstant';
featureAbility.startAbility( featureAbility.startAbility(
...@@ -121,7 +121,7 @@ Obtains a **dataAbilityHelper** object. ...@@ -121,7 +121,7 @@ Obtains a **dataAbilityHelper** object.
**Example** **Example**
```javascript ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var dataAbilityHelper = featureAbility.acquireDataAbilityHelper( var dataAbilityHelper = featureAbility.acquireDataAbilityHelper(
"dataability:///com.example.DataAbility" "dataability:///com.example.DataAbility"
...@@ -140,12 +140,12 @@ Starts an ability. This API uses an asynchronous callback to return the executio ...@@ -140,12 +140,12 @@ Starts an ability. This API uses an asynchronous callback to return the executio
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| --------- | ---------------------------------------- | ---- | -------------- | | --------- | ---------------------------------------- | ---- | -------------- |
| parameter | [StartAbilityParameter](#startabilityparameter) | Yes | Ability to start.| | parameter | [StartAbilityParameter](js-apis-inner-ability-startAbilityParameter.md) | Yes | Ability to start.|
| callback | AsyncCallback\<[AbilityResult](#abilityresult)> | Yes | Callback used to return the result. | | callback | AsyncCallback\<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | Yes | Callback used to return the result. |
**Example** **Example**
```javascript ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
import wantConstant from '@ohos.ability.wantConstant'; import wantConstant from '@ohos.ability.wantConstant';
featureAbility.startAbilityForResult( featureAbility.startAbilityForResult(
...@@ -181,17 +181,17 @@ Starts an ability. This API uses a promise to return the execution result when t ...@@ -181,17 +181,17 @@ Starts an ability. This API uses a promise to return the execution result when t
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| --------- | ---------------------------------------- | ---- | ------------- | | --------- | ---------------------------------------- | ---- | ------------- |
| parameter | [StartAbilityParameter](#startabilityparameter) | Yes | Ability to start.| | parameter | [StartAbilityParameter](js-apis-inner-ability-startAbilityParameter.md) | Yes | Ability to start.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ---------------------------------------- | ------- | | ---------------------------------------- | ------- |
| Promise\<[AbilityResult](#abilityresult)> | Promised returned with the execution result.| | Promise\<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | Promised returned with the execution result.|
**Example** **Example**
```javascript ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
import wantConstant from '@ohos.ability.wantConstant'; import wantConstant from '@ohos.ability.wantConstant';
featureAbility.startAbilityForResult( featureAbility.startAbilityForResult(
...@@ -237,12 +237,12 @@ Destroys this Page ability, with the result code and data sent to the caller. Th ...@@ -237,12 +237,12 @@ Destroys this Page ability, with the result code and data sent to the caller. Th
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| --------- | ------------------------------- | ---- | -------------- | | --------- | ------------------------------- | ---- | -------------- |
| parameter | [AbilityResult](#abilityresult) | Yes | Ability to destroy.| | parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Yes | Ability to start.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. | | callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
**Example** **Example**
```javascript ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
import wantConstant from '@ohos.ability.wantConstant'; import wantConstant from '@ohos.ability.wantConstant';
featureAbility.terminateSelfWithResult( featureAbility.terminateSelfWithResult(
...@@ -289,7 +289,7 @@ Destroys this Page ability, with the result code and data sent to the caller. Th ...@@ -289,7 +289,7 @@ Destroys this Page ability, with the result code and data sent to the caller. Th
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| --------- | ------------------------------- | ---- | ------------- | | --------- | ------------------------------- | ---- | ------------- |
| parameter | [AbilityResult](#abilityresult) | Yes | Ability to destroy.| | parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Yes | Ability to start.|
**Return value** **Return value**
...@@ -299,7 +299,7 @@ Destroys this Page ability, with the result code and data sent to the caller. Th ...@@ -299,7 +299,7 @@ Destroys this Page ability, with the result code and data sent to the caller. Th
**Example** **Example**
```javascript ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
import wantConstant from '@ohos.ability.wantConstant'; import wantConstant from '@ohos.ability.wantConstant';
featureAbility.terminateSelfWithResult( featureAbility.terminateSelfWithResult(
...@@ -349,7 +349,7 @@ Checks whether the main window of this ability has the focus. This API uses an a ...@@ -349,7 +349,7 @@ Checks whether the main window of this ability has the focus. This API uses an a
**Example** **Example**
```javascript ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
featureAbility.hasWindowFocus((err, data) => { featureAbility.hasWindowFocus((err, data) => {
console.info("hasWindowFocus err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); console.info("hasWindowFocus err: " + JSON.stringify(err) + "data: " + JSON.stringify(data));
...@@ -372,7 +372,7 @@ Checks whether the main window of this ability has the focus. This API uses a pr ...@@ -372,7 +372,7 @@ Checks whether the main window of this ability has the focus. This API uses a pr
**Example** **Example**
```javascript ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
featureAbility.hasWindowFocus().then((data) => { featureAbility.hasWindowFocus().then((data) => {
console.info("hasWindowFocus data: " + JSON.stringify(data)); console.info("hasWindowFocus data: " + JSON.stringify(data));
...@@ -391,11 +391,11 @@ Obtains the **Want** object sent from this ability. This API uses an asynchronou ...@@ -391,11 +391,11 @@ Obtains the **Want** object sent from this ability. This API uses an asynchronou
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ----------------------------- | ---- | --------- | | -------- | ----------------------------- | ---- | --------- |
| callback | AsyncCallback\<[Want](js-apis-application-Want.md)> | Yes | Callback used to return the result.| | callback | AsyncCallback\<[Want](js-apis-application-want.md)> | Yes | Callback used to return the result.|
**Example** **Example**
```javascript ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
featureAbility.getWant((err, data) => { featureAbility.getWant((err, data) => {
console.info("getWant err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); console.info("getWant err: " + JSON.stringify(err) + "data: " + JSON.stringify(data));
...@@ -414,11 +414,11 @@ Obtains the **Want** object sent from this ability. This API uses a promise to r ...@@ -414,11 +414,11 @@ Obtains the **Want** object sent from this ability. This API uses a promise to r
| Type | Description | | Type | Description |
| ----------------------- | ---------------- | | ----------------------- | ---------------- |
| Promise\<[Want](js-apis-application-Want.md)> | Promise used to return the result.| | Promise\<[Want](js-apis-application-want.md)> | Promise used to return the result.|
**Example** **Example**
```javascript ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
featureAbility.getWant().then((data) => { featureAbility.getWant().then((data) => {
console.info("getWant data: " + JSON.stringify(data)); console.info("getWant data: " + JSON.stringify(data));
...@@ -441,7 +441,7 @@ Obtains the application context. ...@@ -441,7 +441,7 @@ Obtains the application context.
**Example** **Example**
```javascript ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext() var context = featureAbility.getContext()
context.getBundleName((err, data) => { context.getBundleName((err, data) => {
...@@ -465,7 +465,7 @@ Destroys this Page ability, with the result code and data sent to the caller. Th ...@@ -465,7 +465,7 @@ Destroys this Page ability, with the result code and data sent to the caller. Th
**Example** **Example**
```javascript ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
featureAbility.terminateSelf( featureAbility.terminateSelf(
(err) => { (err) => {
...@@ -490,7 +490,7 @@ Destroys this Page ability, with the result code and data sent to the caller. Th ...@@ -490,7 +490,7 @@ Destroys this Page ability, with the result code and data sent to the caller. Th
**Example** **Example**
```javascript ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
featureAbility.terminateSelf().then((data) => { featureAbility.terminateSelf().then((data) => {
console.info("==========================>terminateSelf=======================>"); console.info("==========================>terminateSelf=======================>");
...@@ -509,20 +509,8 @@ Connects this ability to a specific Service ability. This API uses an asynchrono ...@@ -509,20 +509,8 @@ Connects this ability to a specific Service ability. This API uses an asynchrono
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------- | -------------- | ---- | --------------------- | | ------- | -------------- | ---- | --------------------- |
| request | [Want](js-apis-application-Want.md) | Yes | Service ability to connect.| | request | [Want](js-apis-application-want.md) | Yes | Service ability to connect.|
| options | [ConnectOptions](#connectoptions) | Yes | Callback used to return the result. | | options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | Yes | Callback used to return the result. |
## ConnectOptions
Describes the connection options.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
| Name | Readable|Writable| Type | Mandatory | Description |
| ------------ | -- | -- | -------- | ---- | ------------------------- |
| onConnect<sup>7+</sup> | Yes|No | function | Yes | Callback invoked when the connection is successful. |
| onDisconnect<sup>7+</sup> | Yes|No | function | Yes | Callback invoked when the connection fails. |
| onFailed<sup>7+</sup> | Yes|No | function | Yes | Callback invoked when **connectAbility** fails to be called.|
**Return value** **Return value**
...@@ -532,7 +520,7 @@ Describes the connection options. ...@@ -532,7 +520,7 @@ Describes the connection options.
**Example** **Example**
```javascript ```ts
import rpc from '@ohos.rpc'; import rpc from '@ohos.rpc';
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
function onConnectCallback(element, remote){ function onConnectCallback(element, remote){
...@@ -575,7 +563,7 @@ Disconnects this ability from a specific Service ability. This API uses an async ...@@ -575,7 +563,7 @@ Disconnects this ability from a specific Service ability. This API uses an async
**Example** **Example**
```javascript ```ts
import rpc from '@ohos.rpc'; import rpc from '@ohos.rpc';
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
function onConnectCallback(element, remote){ function onConnectCallback(element, remote){
...@@ -627,7 +615,7 @@ Disconnects this ability from a specific Service ability. This API uses a promis ...@@ -627,7 +615,7 @@ Disconnects this ability from a specific Service ability. This API uses a promis
**Example** **Example**
```javascript ```ts
import rpc from '@ohos.rpc'; import rpc from '@ohos.rpc';
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
function onConnectCallback(element, remote){ function onConnectCallback(element, remote){
...@@ -675,7 +663,7 @@ Obtains the window corresponding to this ability. This API uses an asynchronous ...@@ -675,7 +663,7 @@ Obtains the window corresponding to this ability. This API uses an asynchronous
**Example** **Example**
```javascript ```ts
featureAbility.getWindow((err, data) => { featureAbility.getWindow((err, data) => {
console.info("getWindow err: " + JSON.stringify(err) + "data: " + typeof(data)); console.info("getWindow err: " + JSON.stringify(err) + "data: " + typeof(data));
}); });
...@@ -697,143 +685,12 @@ Obtains the window corresponding to this ability. This API uses a promise to ret ...@@ -697,143 +685,12 @@ Obtains the window corresponding to this ability. This API uses a promise to ret
**Example** **Example**
```javascript ```ts
featureAbility.getWindow().then((data) => { featureAbility.getWindow().then((data) => {
console.info("getWindow data: " + typeof(data)); console.info("getWindow data: " + typeof(data));
}); });
``` ```
## ConnectOptions.onConnect<sup>7+</sup>
onConnect(elementName: ElementName, remote: rpc.IRemoteObject): void;
Callback invoked when the connection is successful.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name | Type | Mandatory | Description |
| ----------- | ----------------- | ---- | -------- |
| elementName | ElementName | Yes | Element name. |
| remote | rpc.IRemoteObject | Yes | RPC remote object.|
**Example**
```javascript
import rpc from '@ohos.rpc';
import featureAbility from '@ohos.ability.featureAbility';
function onConnectCallback(element, remote){
console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy));
}
function onDisconnectCallback(element){
console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId)
}
function onFailedCallback(code){
console.log('featureAbilityTest ConnectAbility onFailed errCode : ' + code)
}
var connectId = featureAbility.connectAbility(
{
deviceId: "",
bundleName: "com.ix.ServiceAbility",
abilityName: "ServiceAbilityA",
},
{
onConnect: onConnectCallback,
onDisconnect: onDisconnectCallback,
onFailed: onFailedCallback,
},
);
```
## ConnectOptions.onDisconnect<sup>7+</sup>
onDisconnect(elementName: ElementName): void;
Callback invoked when the connection fails.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name | Type | Mandatory | Description |
| ----------- | ----------- | ---- | ---- |
| elementName | ElementName | Yes | Element name.|
**Example**
```javascript
import rpc from '@ohos.rpc';
import featureAbility from '@ohos.ability.featureAbility';
function onConnectCallback(element, remote){
console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy));
}
function onDisconnectCallback(element){
console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId)
}
function onFailedCallback(code){
console.log('featureAbilityTest ConnectAbility onFailed errCode : ' + code)
}
var connectId = featureAbility.connectAbility(
{
deviceId: "",
bundleName: "com.ix.ServiceAbility",
abilityName: "ServiceAbilityA",
},
{
onConnect: onConnectCallback,
onDisconnect: onDisconnectCallback,
onFailed: onFailedCallback,
},
);
```
## ConnectOptions.onFailed<sup>7+</sup>
onFailed(code: number): void;
Callback invoked when **connectAbility** fails to be called.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | --------- |
| code | number | Yes | Number type.|
**Example**
```javascript
import rpc from '@ohos.rpc';
import featureAbility from '@ohos.ability.featureAbility';
function onConnectCallback(element, remote){
console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy));
}
function onDisconnectCallback(element){
console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId)
}
function onFailedCallback(code){
console.log('featureAbilityTest ConnectAbility onFailed errCode : ' + code)
}
var connectId = featureAbility.connectAbility(
{
deviceId: "",
bundleName: "com.ix.ServiceAbility",
abilityName: "ServiceAbilityA",
},
{
onConnect: onConnectCallback,
onDisconnect: onDisconnectCallback,
onFailed: onFailedCallback,
},
);
```
## AbilityWindowConfiguration ## AbilityWindowConfiguration
The value is obtained through the **featureAbility.AbilityWindowConfiguration** API. The value is obtained through the **featureAbility.AbilityWindowConfiguration** API.
...@@ -902,26 +759,6 @@ Enumerates operation types of the Data ability. ...@@ -902,26 +759,6 @@ Enumerates operation types of the Data ability.
| TYPE_DELETE<sup>7+</sup> | 3 | Deletion operation.| | TYPE_DELETE<sup>7+</sup> | 3 | Deletion operation.|
| TYPE_ASSERT<sup>7+</sup> | 4 | Assert operation.| | TYPE_ASSERT<sup>7+</sup> | 4 | Assert operation.|
## AbilityResult
**System capability**: SystemCapability.Ability.AbilityBase
| Name | Type | Readable| Writable | Mandatory | Description |
| --------------- |-------- | ------ | ------------- | ---- | ------------------------------------- |
| resultCode<sup>7+</sup>| number| Yes | No | Yes | Result code returned after the ability is destroyed. The feature for defining error-specific result codes is coming soon.|
| want<sup>7+</sup> | [Want](js-apis-application-Want.md)| Yes | No| No | Data returned after the ability is destroyed. You can define the data to be returned. This parameter can be **null**. |
## StartAbilityParameter
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel
| Name | Type | Readable| Writable | Mandatory | Description |
| ------------------- | -------- | -------------------- | ---- | -------------------------------------- |
| want | [Want](js-apis-application-Want.md)| Yes | No | Yes | Information about the ability to start. |
| abilityStartSetting | {[key: string]: any} | Yes |No | No | Special attribute of the ability to start. This attribute can be passed in the method call.|
## flags ## flags
**System capability**: SystemCapability.Ability.AbilityBase **System capability**: SystemCapability.Ability.AbilityBase
......
# particleAbility # @ohos.ability.particleAbility
The **particleAbility** module provides APIs for Service abilities. You can use the APIs to start and terminate a Particle ability, obtain a **dataAbilityHelper** object, connect the current ability to a specific Service ability, and disconnect the current ability from a specific Service ability. The **particleAbility** module provides APIs for Service abilities. You can use the APIs to start and terminate a Particle ability, obtain a **dataAbilityHelper** object, connect the current ability to a specific Service ability, and disconnect the current ability from a specific Service ability.
...@@ -13,7 +13,7 @@ The ParticleAbility module is used to perform operations on abilities of the Dat ...@@ -13,7 +13,7 @@ The ParticleAbility module is used to perform operations on abilities of the Dat
## Modules to Import ## Modules to Import
```js ```ts
import particleAbility from '@ohos.ability.particleAbility' import particleAbility from '@ohos.ability.particleAbility'
``` ```
...@@ -27,17 +27,17 @@ Starts a Particle ability. This API uses an asynchronous callback to return the ...@@ -27,17 +27,17 @@ Starts a Particle ability. This API uses an asynchronous callback to return the
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| --------- | ----------------------------------------------- | ---- | ----------------- | | --------- | ----------------------------------------------- | ---- | ----------------- |
| parameter | [StartAbilityParameter](js-apis-featureAbility.md#startabilityparameter) | Yes | Ability to start.| | parameter | [StartAbilityParameter](js-apis-inner-ability-startAbilityParameter.md) | Yes | Ability to start.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. | | callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
**Example** **Example**
```js ```ts
import particleAbility from '@ohos.ability.particleAbility' import particleAbility from '@ohos.ability.particleAbility'
import wantConstant from '@ohos.ability.wantConstant' import wantConstant from '@ohos.ability.wantConstant'
particleAbility.startAbility( particleAbility.startAbility(
{ {
want: want:
...@@ -49,7 +49,7 @@ particleAbility.startAbility( ...@@ -49,7 +49,7 @@ particleAbility.startAbility(
deviceId: "", deviceId: "",
bundleName: "com.example.Data", bundleName: "com.example.Data",
abilityName: "com.example.Data.MainAbility", abilityName: "com.example.Data.MainAbility",
uri:"" uri: ""
}, },
}, },
(error, result) => { (error, result) => {
...@@ -58,8 +58,6 @@ particleAbility.startAbility( ...@@ -58,8 +58,6 @@ particleAbility.startAbility(
) )
``` ```
## particleAbility.startAbility ## particleAbility.startAbility
startAbility(parameter: StartAbilityParameter): Promise\<void>; startAbility(parameter: StartAbilityParameter): Promise\<void>;
...@@ -70,10 +68,9 @@ Starts a Particle ability. This API uses a promise to return the result. ...@@ -70,10 +68,9 @@ Starts a Particle ability. This API uses a promise to return the result.
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| --------- | ----------------------------------------------- | ---- | ----------------- | | --------- | ----------------------------------------------- | ---- | ----------------- |
| parameter | [StartAbilityParameter](js-apis-featureAbility.md#startabilityparameter) | Yes | Ability to start.| | parameter | [StartAbilityParameter](js-apis-inner-ability-startAbilityParameter.md) | Yes | Ability to start.|
**Return value** **Return value**
...@@ -83,9 +80,10 @@ Starts a Particle ability. This API uses a promise to return the result. ...@@ -83,9 +80,10 @@ Starts a Particle ability. This API uses a promise to return the result.
**Example** **Example**
```js ```ts
import particleAbility from '@ohos.ability.particleAbility' import particleAbility from '@ohos.ability.particleAbility'
import wantConstant from '@ohos.ability.wantConstant' import wantConstant from '@ohos.ability.wantConstant'
particleAbility.startAbility( particleAbility.startAbility(
{ {
want: want:
...@@ -97,7 +95,7 @@ particleAbility.startAbility( ...@@ -97,7 +95,7 @@ particleAbility.startAbility(
deviceId: "", deviceId: "",
bundleName: "com.example.Data", bundleName: "com.example.Data",
abilityName: "com.example. Data.MainAbility", abilityName: "com.example. Data.MainAbility",
uri:"" uri: ""
}, },
}, },
).then((data) => { ).then((data) => {
...@@ -105,8 +103,6 @@ particleAbility.startAbility( ...@@ -105,8 +103,6 @@ particleAbility.startAbility(
}); });
``` ```
## particleAbility.terminateSelf ## particleAbility.terminateSelf
terminateSelf(callback: AsyncCallback\<void>): void terminateSelf(callback: AsyncCallback\<void>): void
...@@ -123,8 +119,9 @@ Terminates this Particle ability. This API uses an asynchronous callback to retu ...@@ -123,8 +119,9 @@ Terminates this Particle ability. This API uses an asynchronous callback to retu
**Example** **Example**
```js ```ts
import particleAbility from '@ohos.ability.particleAbility' import particleAbility from '@ohos.ability.particleAbility'
particleAbility.terminateSelf( particleAbility.terminateSelf(
(error, result) => { (error, result) => {
console.log('particleAbility terminateSelf errCode:' + error + 'result:' + result) console.log('particleAbility terminateSelf errCode:' + error + 'result:' + result)
...@@ -132,8 +129,6 @@ particleAbility.terminateSelf( ...@@ -132,8 +129,6 @@ particleAbility.terminateSelf(
) )
``` ```
## particleAbility.terminateSelf ## particleAbility.terminateSelf
terminateSelf(): Promise\<void> terminateSelf(): Promise\<void>
...@@ -150,8 +145,9 @@ Terminates this Particle ability. This API uses a promise to return the result. ...@@ -150,8 +145,9 @@ Terminates this Particle ability. This API uses a promise to return the result.
**Example** **Example**
```js ```ts
import particleAbility from '@ohos.ability.particleAbility' import particleAbility from '@ohos.ability.particleAbility'
particleAbility.terminateSelf().then((data) => { particleAbility.terminateSelf().then((data) => {
console.info("particleAbility terminateSelf"); console.info("particleAbility terminateSelf");
}); });
...@@ -181,8 +177,9 @@ Obtains a **dataAbilityHelper** object. ...@@ -181,8 +177,9 @@ Obtains a **dataAbilityHelper** object.
**Example** **Example**
```js ```ts
import particleAbility from '@ohos.ability.particleAbility' import particleAbility from '@ohos.ability.particleAbility'
var uri = ""; var uri = "";
particleAbility.acquireDataAbilityHelper(uri) particleAbility.acquireDataAbilityHelper(uri)
``` ```
...@@ -208,7 +205,7 @@ Requests a continuous task from the system. This API uses an asynchronous callba ...@@ -208,7 +205,7 @@ Requests a continuous task from the system. This API uses an asynchronous callba
**Example** **Example**
```js ```ts
import notification from '@ohos.notification'; import notification from '@ohos.notification';
import particleAbility from '@ohos.ability.particleAbility'; import particleAbility from '@ohos.ability.particleAbility';
import wantAgent from '@ohos.wantAgent'; import wantAgent from '@ohos.wantAgent';
...@@ -277,7 +274,7 @@ Requests a continuous task from the system. This API uses a promise to return th ...@@ -277,7 +274,7 @@ Requests a continuous task from the system. This API uses a promise to return th
**Example** **Example**
```js ```ts
import notification from '@ohos.notification'; import notification from '@ohos.notification';
import particleAbility from '@ohos.ability.particleAbility'; import particleAbility from '@ohos.ability.particleAbility';
import wantAgent from '@ohos.wantAgent'; import wantAgent from '@ohos.wantAgent';
...@@ -333,7 +330,7 @@ Requests to cancel a continuous task from the system. This API uses an asynchron ...@@ -333,7 +330,7 @@ Requests to cancel a continuous task from the system. This API uses an asynchron
**Example** **Example**
```js ```ts
import particleAbility from '@ohos.ability.particleAbility'; import particleAbility from '@ohos.ability.particleAbility';
function callback(err, data) { function callback(err, data) {
...@@ -364,7 +361,7 @@ Requests a continuous task from the system. This API uses a promise to return th ...@@ -364,7 +361,7 @@ Requests a continuous task from the system. This API uses a promise to return th
**Example** **Example**
```js ```ts
import particleAbility from '@ohos.ability.particleAbility'; import particleAbility from '@ohos.ability.particleAbility';
particleAbility.cancelBackgroundRunning().then(() => { particleAbility.cancelBackgroundRunning().then(() => {
...@@ -375,7 +372,6 @@ particleAbility.cancelBackgroundRunning().then(() => { ...@@ -375,7 +372,6 @@ particleAbility.cancelBackgroundRunning().then(() => {
``` ```
## particleAbility.connectAbility ## particleAbility.connectAbility
connectAbility(request: Want, options:ConnectOptions): number connectAbility(request: Want, options:ConnectOptions): number
...@@ -388,7 +384,7 @@ Connects this ability to a specific Service ability. This API uses a callback to ...@@ -388,7 +384,7 @@ Connects this ability to a specific Service ability. This API uses a callback to
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------- | -------------- | ---- | ---------------------------- | | ------- | -------------- | ---- | ---------------------------- |
| request | [Want](js-apis-application-Want.md) | Yes | Service ability to connect.| | request | [Want](js-apis-application-want.md) | Yes | Service ability to connect.|
| options | ConnectOptions | Yes | Callback used to return the result. | | options | ConnectOptions | Yes | Callback used to return the result. |
...@@ -396,26 +392,30 @@ ConnectOptions ...@@ -396,26 +392,30 @@ ConnectOptions
**System capability**: SystemCapability.Ability.AbilityRuntime.Core **System capability**: SystemCapability.Ability.AbilityRuntime.Core
| Name | Readable/Writable| Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------------ | ---- | -------- | ---- | ------------------------- | | ------------ | -------- | ---- | ------------------------- |
| onConnect | Read only | function | Yes | Callback invoked when the connection is successful. | | onConnect | function | Yes | Callback invoked when the connection is successful. |
| onDisconnect | Read only | function | Yes | Callback invoked when the connection fails. | | onDisconnect | function | Yes | Callback invoked when the connection fails. |
| onFailed | Read only | function | Yes | Callback invoked when **connectAbility** fails to be called.| | onFailed | function | Yes | Callback invoked when **connectAbility** fails to be called.|
**Example** **Example**
```js ```ts
import rpc from '@ohos.rpc' import rpc from '@ohos.rpc'
function onConnectCallback(element, remote){
function onConnectCallback(element, remote) {
console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy)); console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy));
} }
function onDisconnectCallback(element){
function onDisconnectCallback(element) {
console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId) console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId)
} }
function onFailedCallback(code){
function onFailedCallback(code) {
console.log('particleAbilityTest ConnectAbility onFailed errCode : ' + code) console.log('particleAbilityTest ConnectAbility onFailed errCode : ' + code)
} }
var connId = particleAbility.connectAbility(
var connId = particleAbility.connectAbility(
{ {
bundleName: "com.ix.ServiceAbility", bundleName: "com.ix.ServiceAbility",
abilityName: "ServiceAbilityA", abilityName: "ServiceAbilityA",
...@@ -425,18 +425,16 @@ ConnectOptions ...@@ -425,18 +425,16 @@ ConnectOptions
onDisconnect: onDisconnectCallback, onDisconnect: onDisconnectCallback,
onFailed: onFailedCallback, onFailed: onFailedCallback,
}, },
); );
particleAbility.disconnectAbility(connId).then((data)=>{
console.log( " data: " + data);
}).catch((error)=>{
console.log('particleAbilityTest result errCode : ' + error.code )
});
particleAbility.disconnectAbility(connId).then((data) => {
console.log(" data: " + data);
}).catch((error) => {
console.log('particleAbilityTest result errCode : ' + error.code)
});
``` ```
## particleAbility.disconnectAbility ## particleAbility.disconnectAbility
disconnectAbility(connection: number, callback:AsyncCallback\<void>): void; disconnectAbility(connection: number, callback:AsyncCallback\<void>): void;
...@@ -453,18 +451,22 @@ Disconnects this ability from the Service ability. This API uses a callback to r ...@@ -453,18 +451,22 @@ Disconnects this ability from the Service ability. This API uses a callback to r
**Example** **Example**
```js ```ts
import rpc from '@ohos.rpc' import rpc from '@ohos.rpc'
function onConnectCallback(element, remote){
function onConnectCallback(element, remote) {
console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy)); console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy));
} }
function onDisconnectCallback(element){
function onDisconnectCallback(element) {
console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId) console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId)
} }
function onFailedCallback(code){
function onFailedCallback(code) {
console.log('particleAbilityTest ConnectAbility onFailed errCode : ' + code) console.log('particleAbilityTest ConnectAbility onFailed errCode : ' + code)
} }
var connId = particleAbility.connectAbility(
var connId = particleAbility.connectAbility(
{ {
bundleName: "com.ix.ServiceAbility", bundleName: "com.ix.ServiceAbility",
abilityName: "ServiceAbilityA", abilityName: "ServiceAbilityA",
...@@ -474,13 +476,12 @@ import rpc from '@ohos.rpc' ...@@ -474,13 +476,12 @@ import rpc from '@ohos.rpc'
onDisconnect: onDisconnectCallback, onDisconnect: onDisconnectCallback,
onFailed: onFailedCallback, onFailed: onFailedCallback,
}, },
); );
var result = particleAbility.disconnectAbility(connId).then((data)=>{ var result = particleAbility.disconnectAbility(connId).then((data) => {
console.log( " data: " + data); console.log(" data: " + data);
}).catch((error)=>{ }).catch((error) => {
console.log('particleAbilityTest result errCode : ' + error.code ) console.log('particleAbilityTest result errCode : ' + error.code)
}); });
``` ```
...@@ -500,18 +501,22 @@ Disconnects this ability from the Service ability. This API uses a promise to re ...@@ -500,18 +501,22 @@ Disconnects this ability from the Service ability. This API uses a promise to re
**Example** **Example**
```js ```ts
import rpc from '@ohos.rpc' import rpc from '@ohos.rpc'
function onConnectCallback(element, remote){
function onConnectCallback(element, remote) {
console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy)); console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy));
} }
function onDisconnectCallback(element){
function onDisconnectCallback(element) {
console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId) console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId)
} }
function onFailedCallback(code){
function onFailedCallback(code) {
console.log('particleAbilityTest ConnectAbility onFailed errCode : ' + code) console.log('particleAbilityTest ConnectAbility onFailed errCode : ' + code)
} }
var connId = particleAbility.connectAbility(
var connId = particleAbility.connectAbility(
{ {
bundleName: "com.ix.ServiceAbility", bundleName: "com.ix.ServiceAbility",
abilityName: "ServiceAbilityA", abilityName: "ServiceAbilityA",
...@@ -521,13 +526,13 @@ function onConnectCallback(element, remote){ ...@@ -521,13 +526,13 @@ function onConnectCallback(element, remote){
onDisconnect: onDisconnectCallback, onDisconnect: onDisconnectCallback,
onFailed: onFailedCallback, onFailed: onFailedCallback,
}, },
); );
particleAbility.disconnectAbility(connId).then((data)=>{ particleAbility.disconnectAbility(connId).then((data) => {
console.log( " data: " + data); console.log(" data: " + data);
}).catch((error)=>{ }).catch((error) => {
console.log('particleAbilityTest result errCode : ' + error.code ) console.log('particleAbilityTest result errCode : ' + error.code)
}); });
``` ```
......
# wantConstant # @ohos.ability.wantConstant
The **wantConstant** module provides the actions, entities, and flags used in **Want** objects. The **wantConstant** module provides the actions, entities, and flags used in **Want** objects.
> **NOTE** > **NOTE**
> >
> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs of this module are supported since API version 6 and deprecated since API version 9. You are advised to use [@ohos.app.ability.wantConstant](js-apis-app-ability-wantConstant.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import ## Modules to Import
```js ```ts
import wantConstant from '@ohos.ability.wantConstant'; import wantConstant from '@ohos.ability.wantConstant';
``` ```
...@@ -46,6 +46,7 @@ Enumerates the action constants of the **Want** object. ...@@ -46,6 +46,7 @@ Enumerates the action constants of the **Want** object.
| ACTION_FILE_SELECT<sup>7+</sup> | ohos.action.fileSelect | Action of selecting a file. | | ACTION_FILE_SELECT<sup>7+</sup> | ohos.action.fileSelect | Action of selecting a file. |
| PARAMS_STREAM<sup>7+</sup> | ability.params.stream | URI of the data stream associated with the target when the data is sent. | | PARAMS_STREAM<sup>7+</sup> | ability.params.stream | URI of the data stream associated with the target when the data is sent. |
| ACTION_APP_ACCOUNT_OAUTH <sup>8+</sup> | ohos.account.appAccount.action.oauth | Action of providing the OAuth service. | | ACTION_APP_ACCOUNT_OAUTH <sup>8+</sup> | ohos.account.appAccount.action.oauth | Action of providing the OAuth service. |
| ACTION_APP_ACCOUNT_AUTH <sup>9+</sup> | account.appAccount.action.auth | Action of providing the authentication service. |
| ACTION_MARKET_DOWNLOAD <sup>9+</sup> | ohos.want.action.marketDownload | Action of downloading an application from the application market.<br>**System API**: This is a system API and cannot be called by third-party applications. | | ACTION_MARKET_DOWNLOAD <sup>9+</sup> | ohos.want.action.marketDownload | Action of downloading an application from the application market.<br>**System API**: This is a system API and cannot be called by third-party applications. |
| ACTION_MARKET_CROWDTEST <sup>9+</sup> | ohos.want.action.marketCrowdTest | Action of crowdtesting an application from the application market.<br>**System API**: This is a system API and cannot be called by third-party applications. | | ACTION_MARKET_CROWDTEST <sup>9+</sup> | ohos.want.action.marketCrowdTest | Action of crowdtesting an application from the application market.<br>**System API**: This is a system API and cannot be called by third-party applications. |
| DLP_PARAMS_SANDBOX<sup>9+</sup> |ohos.dlp.params.sandbox | Action of obtaining the sandbox flag.<br>**System API**: This is a system API and cannot be called by third-party applications. | | DLP_PARAMS_SANDBOX<sup>9+</sup> |ohos.dlp.params.sandbox | Action of obtaining the sandbox flag.<br>**System API**: This is a system API and cannot be called by third-party applications. |
......
# Want # @ohos.app.ability.Want
Want is a carrier for information transfer between objects (application components). Want can be used as a parameter of **startAbility** to specify a startup target and information that needs to be carried during startup, for example, **bundleName** and **abilityName**, which respectively indicate the bundle name of the target ability and the ability name in the bundle. When ability A needs to start ability B and transfer some data to ability B, it can use Want a carrier to transfer the data. Want is a carrier for information transfer between objects (application components). Want can be used as a parameter of **startAbility** to specify a startup target and information that needs to be carried during startup, for example, **bundleName** and **abilityName**, which respectively indicate the bundle name of the target ability and the ability name in the bundle. When ability A needs to start ability B and transfer some data to ability B, it can use Want a carrier to transfer the data.
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册