提交 2297e7e4 编写于 作者: zyjhandsome's avatar zyjhandsome

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

......@@ -13,6 +13,9 @@
- Vibrator
- [Vibrator Overview](vibrator-overview.md)
- [Vibrator Development](vibrator-guidelines.md)
- Multimodal Input
- [Input Device Development](inputdevice-guidelines.md)
- [Mouse Pointer Development](pointerstyle-guidelines.md)
- Update Service
- [Sample Server Overview](sample-server-overview.md)
- [Sample Server Development](sample-server-guidelines.md)
# Input Device Development
## When to Use
Input device management provides functions such as listening for device hot swap events and querying the keyboard type of a specified device. For example, as a user enters text, the input method determines whether to launch the virtual keyboard based on whether a physical keyboard is currently inserted. Your application can determine whether a physical keyboard is inserted by listening to device hot swap events.
## Modules to Import
```js
import inputDevice from '@ohos.multimodalInput.inputDevice';
```
## Available APIs
The following table lists the common APIs for input device management. For details about the APIs, see [ohos.multimodalInput.inputDevice](../reference/apis/js-apis-inputdevice.md).
| Instance| API | Description|
| ----------- | ------------------------------------------------------------ | -------------------------- |
| inputDevice | function getDeviceList(callback: AsyncCallback\<Array\<number>>): void; | Obtains the list of input devices.|
| inputDevice | function getKeyboardType(deviceId: number, callback: AsyncCallback\<KeyboardType>): void; | Obtains the keyboard type of the input device.|
| inputDevice | function on(type: "change", listener: Callback\<DeviceListener>): void; | Enables listening for device hot swap events.|
| inputDevice | function off(type: "change", listener?: Callback\<DeviceListener>): void; | Disables listening for device hot swap events.|
## Virtual Keyboard Detection
When a user enters text, the input method determines whether to launch the virtual keyboard based on whether a physical keyboard is currently inserted. Your application can determine whether a physical keyboard is inserted by listening to device hot swap events.
## How to Develop
1. Call the **getDeviceList** API to obtain the list of connected input devices. Call the **getKeyboardType** API to traverse all connected devices to check whether a physical keyboard exists. If a physical keyboard exists, mark the physical keyboard as connected. This step ensures that your application detects all inserted input devices before listening for device hot swap events.
2. Call the **on** API to listen for device hot swap events. If a physical keyboard is inserted, mark the physical keyboard as connected. If a physical keyboard is removed, mark the physical keyboard as disconnected.
3. When a user enters text, check whether a physical keyboard is connected. If a physical keyboard is not connected, launch the virtual keyboard.
```js
import inputDevice from '@ohos.multimodalInput.inputDevice';
let isPhysicalKeyboardExist = true;
try {
// 1. Obtain the list of input devices and check whether a physical keyboard is connected.
inputDevice.getDeviceList().then(data => {
for (let i = 0; i < data.length; ++i) {
inputDevice.getKeyboardType(data[i]).then(res => {
if (type == inputDevice.KeyboardType.ALPHABETIC_KEYBOARD) {
// The physical keyboard is connected.
isPhysicalKeyboardExist = true;
}
});
}
});
// 2. Listen for device hot swap events.
inputDevice.on("change", (data) => {
console.log(`Device event info: ${JSON.stringify(data)}`);
inputDevice.getKeyboardType(data.deviceId, (error, type) => {
console.log("The keyboard type is: " + type);
if (type == inputDevice.KeyboardType.ALPHABETIC_KEYBOARD && data.type == 'add') {
// The physical keyboard is inserted.
isPhysicalKeyboardExist = true;
} else if (type == inputDevice.KeyboardType.ALPHABETIC_KEYBOARD && data.type == 'remove') {
// The physical keyboard is removed.
isPhysicalKeyboardExist = false;
}
});
});
} catch (error) {
console.log(`Execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
}
// 3. Determine whether to launch the virtual keyboard based on the value of isPhysicalKeyboardExist.
// TODO
```
# Mouse Pointer Development
## When to Use
Mouse pointer management provides the functions such as displaying or hiding the mouse pointer as well as querying and setting the pointer style. For example, you can determine whether to display or hide the mouse pointer when a user watches a video in full screen, and can switch the mouse pointer to a color picker when a user attempts color pickup.
## Modules to Import
```js
import inputDevice from '@ohos.multimodalInput.pointer';
```
## Available APIs
The following table lists the common APIs for mouse pointer management. For details about the APIs, see [ohos.multimodalInput.pointer](../reference/apis/js-apis-pointer.md).
| Instance | API | Description |
| ------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| pointer | function isPointerVisible(callback: AsyncCallback\<boolean>): void; | Checks the visible status of the mouse pointer. |
| pointer | function setPointerVisible(visible: boolean, callback: AsyncCallback\<void>): void; | Sets the visible status of the mouse pointer. This setting takes effect for the mouse pointer globally.|
| pointer | function setPointerStyle(windowId: number, pointerStyle: PointerStyle, callback: AsyncCallback\<void>): void; | Sets the mouse pointer style. This setting takes effect for the mouse pointer style of a specified window. |
| pointer | function getPointerStyle(windowId: number, callback: AsyncCallback\<PointerStyle>): void; | Obtains the mouse pointer style. |
## Hiding the Mouse Pointer
When watching a video in full-screen mode, a user can hide the mouse pointer for an improved user experience.
## How to Develop
1. Switch to the full-screen playback mode.
2. Hide the mouse pointer.
3. Exit the full-screen playback mode.
4. Display the mouse pointer.
```js
import pointer from '@ohos.multimodalInput.pointer';
// 1. Switch to the full-screen playback mode.
// 2. Hide the mouse pointer.
try {
pointer.setPointerVisible(false, (error) => {
if (error) {
console.log(`Set pointer visible failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
return;
}
console.log(`Set pointer visible success.`);
});
} catch (error) {
console.log(`The mouse pointer hide attributes is failed. ${JSON.stringify(error, [`code`, `message`])}`);
}
// 3. Exit the full-screen playback mode.
// 4. Display the mouse pointer.
try {
pointer.setPointerVisible(true, (error) => {
if (error) {
console.log(`Set pointer visible failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
return;
}
console.log(`Set pointer visible success.`);
});
} catch (error) {
console.log(`Set pointer visible failed, ${JSON.stringify(error, [`code`, `message`])}`);
}
```
## Setting the Mouse Pointer Style
When designing a color picker, you can have the mouse pointer switched to the color picker style during color pickup and then switched to the default style on completion of color pickup. This setting takes effect for the pointer style of a specified window in the current application. A total of 39 pointer styles can be set. For details, see [Pointer Style](../reference/apis/js-apis-pointer.md#pointerstyle9).
### How to Develop
1. Enable the color pickup function.
2. Obtain the window ID.
3. Set the mouse pointer to the color picker style.
4. End color pickup.
5. Set the mouse pointer to the default style.
```js
import window from '@ohos.window';
// 1. Enable the color pickup function.
// 2. Obtain the window ID.
window.getTopWindow((error, windowClass) => {
windowClass.getProperties((error, data) => {
var windowId = data.id;
if (windowId < 0) {
console.log(`Invalid windowId`);
return;
}
try {
// 3. Set the mouse pointer to the color picker style.
pointer.setPointerStyle(windowId, pointer.PointerStyle.COLOR_SUCKER).then(() => {
console.log(`Successfully set mouse pointer style`);
});
} catch (error) {
console.log(`Failed to set the pointer style, error=${JSON.stringify(error)}, msg=${JSON.stringify(message)}`);
}
});
});
// 4. End color pickup.
window.getTopWindow((error, windowClass) => {
windowClass.getProperties((error, data) => {
var windowId = data.id;
if (windowId < 0) {
console.log(`Invalid windowId`);
return;
}
try {
// 5. Set the mouse pointer to the default style.
pointer.setPointerStyle(windowId, pointer.PointerStyle.DEFAULT).then(() => {
console.log(`Successfully set mouse pointer style`);
});
} catch (error) {
console.log(`Failed to set the pointer style, error=${JSON.stringify(error)}, msg=${JSON.stringify(message)}`);
}
});
});
```
......@@ -197,12 +197,12 @@ Disables listening for hot swap events of an input device.
**Example**
```js
callback: function(data) {
function callback(data) {
console.log("type: " + data.type + ", deviceId: " + data.deviceId);
}
try {
inputDevice.on("change", this.callback);
inputDevice.on("change", callback);
} catch (error) {
console.info("oninputdevcie " + error.code + " " + error.message)
}
......@@ -212,7 +212,7 @@ inputDevice.on("change", listener);
// Disable this listener.
try {
inputDevice.off("change", this.callback);
inputDevice.off("change", callback);
} catch (error) {
console.info("offinputdevcie " + error.code + " " + error.message)
}
......
......@@ -2,83 +2,192 @@
## Overview
### Function
### Function Introduction
HiSysEvent provides event logging APIs for OpenHarmony to record important information of key processes during system running. Besides, it supports shielding of event logging by event domain, helping you to evaluate the impact of event logging.
### Working Principles
Before logging system events, you need to complete HiSysEvent logging configuration. For details, see [HiSysEvent Logging Configuration](subsys-dfx-hisysevent-logging-config.md).
Before logging system events, you need to configure HiSysEvent logging. For details, see [HiSysEvent Logging Configuration](subsys-dfx-hisysevent-logging-config.md).
## How to Develop
### Use Cases
Use HiSysEvent logging to flush logged event data to disks.
Use HiSysEvent logging to flush logged event data to the event file.
### Available APIs
#### C++ Event Logging APIs
#### C++ Event Logging API
HiSysEvent logging is implemented using the API provided by the **HiSysEvent** class. For details, see the API Reference.
HiSysEvent logging is implemented using the API provided by the **HiSysEvent** class. For details, see the [API Header Files](/base/hiviewdfx/hisysevent/interfaces/native/innerkits/hisysevent/include/).
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> **NOTE**
>
> In OpenHarmony-3.2-Beta3, HiSysEvent logging is open for restricted use to avoid event storms. The **HiSysEvent::Write** API in Table 1 is replaced by the **HiSysEventWrite** API in Table 2. The **HiSysEvent::Write** API has been deprecated. Use the **HiSysEventWrite** API instead for HiSysEvent logging.
**Table 1** C++ event logging API (deprecated)
**Table 1** Description of the C++ event logging API (deprecated)
| API | Description |
| ------------------------------------------------------------ | ---------------------- |
| template&lt;typename... Types&gt; <br>static int Write(const std::string &amp;domain, const std::string &amp;eventName, EventType type, Types... keyValues) | Flushes logged event data to disks.|
| ------------------------------------------------------------ | --------------------- |
| template&lt;typename...&nbsp;Types&gt;&nbsp;<br>static&nbsp;int&nbsp;Write(const&nbsp;std::string&nbsp;&amp;domain,&nbsp;const&nbsp;std::string&nbsp;&amp;eventName,&nbsp;EventType&nbsp;type,&nbsp;Types...&nbsp;keyValues) | Flushes logged event data to the event file.|
**Table 2** C++ event logging API (in use)
| API | Description |
| ------------------------------------------------------------ | ---------------------- |
| HiSysEventWrite(domain, eventName, type, ...) | Flushes logged event data to disks.|
**Table 3** Event types
**Table 2** Description of the C++ event logging API (in use)
| API | Description |
| --------- | ------------ |
| FAULT | Fault event|
| STATISTIC | Statistical event|
| SECURITY | Security event|
| BEHAVIOR | Behavior event|
| API | Description |
| ------------------------------------------------------------ | --------------------- |
| HiSysEventWrite(domain, eventName, type, ...) | Flushes logged event data to the event file.|
**Table 3** Description of EventType enums
| Event Type | Description |
| --------- | ----------- |
| FAULT | Fault event.|
| STATISTIC | Statistical event.|
| SECURITY | Security event.|
| BEHAVIOR | Behavior event.|
#### C Event Logging API
HiSysEvent logging is implemented using the API provided in the following table. For details, see the [API Header Files](/base/hiviewdfx/hisysevent/interfaces/native/innerkits/hisysevent/include/).
**Table 4** Description of the C event logging API
| API | Description |
| ------------------------------------------------------------ | ------------------------ |
| int OH_HiSysEvent_Write(const char\* domain, const char\* name, HiSysEventEventType type, HiSysEventParam params[], size_t size); | Flushes logged event data to the event file.|
**Table 5** Description of HiSysEventEventType enums
| Event Type | Description |
| -------------------- | -------------- |
| HISYSEVENT_FAULT | Fault event.|
| HISYSEVENT_STATISTIC | Statistical event.|
| HISYSEVENT_SECURITY | Security event.|
| HISYSEVENT_BEHAVIOR | Behavior event.|
**Table 6** Description of the HiSysEventParam structure
| Attribute | Type | Description |
| --------- | -------------------- | ---------------------------------- |
| name | char name[] | Event parameter name. |
| t | HiSysEventParamType | Event parameter type. |
| v | HiSysEventParamValue | Event parameter value. |
| arraySize | size_t | Array length when the event parameter value is of the array type.|
**Table 7** Description of HiSysEventParamType enums
| Type | Description |
| ----------------------- | -------------------------- |
| HISYSEVENT_INVALID | Invalid event parameter. |
| HISYSEVENT_BOOL | Event parameter of the bool type. |
| HISYSEVENT_INT8 | Event parameter of the int8_t type. |
| HISYSEVENT_UINT8 | Event parameter of the uint8_t type. |
| HISYSEVENT_INT16 | Event parameter of the int16_t type. |
| HISYSEVENT_UINT16 | Event parameter of the uint16_t type. |
| HISYSEVENT_INT32 | Event parameter of the int32_t type. |
| HISYSEVENT_UINT32 | Event parameter of the uint32_t type. |
| HISYSEVENT_INT64 | Event parameter of the int64_t type. |
| HISYSEVENT_UINT64 | Event parameter of the uint64_t type. |
| HISYSEVENT_FLOAT | Event parameter of the float type. |
| HISYSEVENT_DOUBLE | Event parameter of the double type. |
| HISYSEVENT_STRING | Event parameter of the char* type. |
| HISYSEVENT_BOOL_ARRAY | Event parameter of the bool array type. |
| HISYSEVENT_INT8_ARRAY | Event parameter of the int8_t array type. |
| HISYSEVENT_UINT8_ARRAY | Event parameter of the uint8_t array type. |
| HISYSEVENT_INT16_ARRAY | Event parameter of the int16_t array type. |
| HISYSEVENT_UINT16_ARRAY | Event parameter of the uint16_t array type.|
| HISYSEVENT_INT32_ARRAY | Event parameter of the int32_t array type. |
| HISYSEVENT_UINT32_ARRAY | Event parameter of the uint32_t array type.|
| HISYSEVENT_INT64_ARRAY | Event parameter of the int64_t array type. |
| HISYSEVENT_UINT64_ARRAY | Event parameter of the uint64_t array type.|
| HISYSEVENT_FLOAT_ARRAY | Event parameter of the float array type. |
| HISYSEVENT_DOUBLE_ARRAY | Event parameter of the double array type. |
| HISYSEVENT_STRING_ARRAY | Event parameter of the char* array type. |
**Table 8** Description of the HiSysEventParamValue union
| Attribute| Type| Description |
| -------- | -------- | ------------------------ |
| b | bool | Event parameter value of the bool type. |
| i8 | int8_t | Event parameter value of the int8_t type. |
| ui8 | uint8_t | Event parameter value of the uint8_t type. |
| i16 | int16_t | Event parameter value of the int16_t type. |
| ui16 | uint16_t | Event parameter value of the uint16_t type.|
| i32 | int32_t | Event parameter value of the int32_t type. |
| ui32 | uint32_t | Event parameter value of the uint32_t type.|
| i64 | int64_t | Event parameter value of the int64_t type. |
| ui64 | uint64_t | Event parameter value of the uint64_t type.|
| f | float | Event parameter value of the float type. |
| d | double | Event parameter value of the double type. |
| s | char* | Event parameter value of the char* type. |
| array | void* | Event parameter value of the array type. |
#### Kernel Event Logging APIs
The following table describes the kernel event logging APIs.
Kernel event logging is implemented using the APIs provided in the following table. For details, see the [API Header File](/kernel/linux/linux-5.10/include/dfx/hiview_hisysevent.h).
**Table 4** Kernel event logging APIs
**Table 9** Description of kernel event logging APIs
| API | Description |
| ------------------------------------------------------------ | ------------------------------------ |
| struct hiview_hisysevent *hisysevent_create(const char *domain, const char *name, enum hisysevent_type type); | Creates a **hisysevent** object. |
| void hisysevent_destroy(struct hiview_hisysevent *event); | Destroys a **hisysevent** object. |
| ------------------------------------------------------------ | ----------------------------------- |
| struct hiview_hisysevent *hisysevent_create(const char *domain, const char *name, enum hisysevent_type type); | Creates a **hisysevent** object. |
| void hisysevent_destroy(struct hiview_hisysevent *event); | Destroys a **hisysevent** object. |
| int hisysevent_put_integer(struct hiview_hisysevent *event, const char *key, long long value); | Adds event parameters of the integer type to a **hisysevent** object. |
| int hisysevent_put_string(struct hiview_hisysevent *event, const char *key, const char *value); | Adds event parameters of the string type to a **hisysevent** object.|
| int hisysevent_write(struct hiview_hisysevent *event); | Flushes **hisysevent** object data to disks. |
| int hisysevent_write(struct hiview_hisysevent *event); | Flushes **hisysevent** object data to the event file. |
**Table 5** Kernel event types
**Table 10** Description of hisysevent_type enums
| API | Description |
| --------- | ------------ |
| FAULT | Fault event|
| STATISTIC | Statistical event|
| SECURITY | Security event|
| BEHAVIOR | Behavior event|
| Event Type | Description |
| --------- | ----------- |
| FAULT | Fault event.|
| STATISTIC | Statistical event.|
| SECURITY | Security event.|
| BEHAVIOR | Behavior event.|
### How to Develop
#### C++ Event Logging
1. Call the event logging API wherever needed, with required event parameters passed to the API.
Call the event logging API wherever needed, with required event parameters passed to the API.
```c++
HiSysEventWrite(HiSysEvent::Domain::AAFWK, "START_APP", HiSysEvent::EventType::BEHAVIOR, "APP_NAME", "com.ohos.demo");
```
#### C Event Logging
1. If you want to pass custom event parameters to the event logging API, create an event parameter object based on the event parameter type and add the object to the event parameter array.
```c
// Create an event parameter of the int32_t type.
HiSysEventParam param1 = {
.name = "KEY_INT32",
.t = HISYSEVENT_INT32,
.v = { .i32 = 1 },
.arraySize = 0,
};
// Create an event parameter of the int32_t array type.
int32_t int32Arr[] = { 1, 2, 3 };
HiSysEventParam param2 = {
.name = "KEY_INT32_ARR",
.t = HISYSEVENT_INT32_ARRAY,
.v = { .array = int32Arr },
.arraySize = sizeof(int32Arr) / sizeof(int32Arr[0]),
};
// Add the event parameter object to the created event parameter array.
HiSysEventParam params[] = { param1, param2 };
```
2. Call the event logging API wherever needed, with required event parameters passed to the API.
```c
OH_HiSysEvent_Write("TEST_DOMAIN", "TEST_NAME", HISYSEVENT_BEHAVIOR, params, sizeof(params) / sizeof(params[0]));
```
#### Kernel Event Logging
1. Create a **hisysevent** object based on the specified event domain, event name, and event type.
......@@ -151,7 +260,7 @@ Assume that a service module needs to trigger event logging during application s
external_deps = [ "hisysevent_native:libhisysevent" ]
```
2. In the application startup function **StartAbility()** of the service module, call the event logging API with the event parameters passed in.
2. In the application startup function **StartAbility()** of the service module, call the event logging API with event parameters passed in.
```c++
#include "hisysevent.h"
......@@ -164,6 +273,37 @@ Assume that a service module needs to trigger event logging during application s
}
```
#### C Event Logging
Assume that a service module needs to trigger event logging during application startup to record the application startup event and application bundle name. The following is the complete sample code:
1. Add the HiSysEvent component dependency to the **BUILD.gn** file of the service module.
```c++
external_deps = [ "hisysevent_native:libhisysevent" ]
```
2. In the application startup function **StartAbility()** of the service module, call the event logging API with event parameters passed in.
```c
#include "hisysevent_c.h"
int StartAbility()
{
... // Other service logic
char packageName[] = "com.ohos.demo";
HiSysEventParam param = {
.name = "APP_NAME",
.t = HISYSEVENT_STRING,
.v = { .s = packageName },
.arraySize = 0,
};
HiSysEventParam params[] = { param };
int ret = OH_HiSysEvent_Write("AAFWK", "START_APP", HISYSEVENT_BEHAVIOR, params, sizeof(params) / sizeof(params[0]));
... // Other service logic
}
```
#### Kernel Event Logging
Assume that the kernel service module needs to trigger event logging during device startup to record the device startup event. The following is the complete sample code:
......@@ -200,11 +340,10 @@ Assume that the kernel service module needs to trigger event logging during devi
}
```
#### Shielding of Event Logging by Event Domain
#### Shielding of Event Logging by Event Domain
- If you want to shield event logging for the **AAFWK** and **POWER** domains in a **.cpp** file, define the **DOMAIN_MASKS** macro before including the **hisysevent.h** header file to the **.cpp** file.
```c++
#define DOMAIN_MASKS "AAFWK|POWER"
#include "hisysevent.h"
......@@ -212,14 +351,13 @@ Assume that the kernel service module needs to trigger event logging during devi
HiSysEventWrite(OHOS:HiviewDFX::HiSysEvent::Domain::AAFWK, "JS_ERROR", OHOS:HiviewDFX::HiSysEvent::EventType::FAULT, "MODULE", "com.ohos.module"); // HiSysEvent logging is not performed.
... // Other service logic
HiSysEventWrite(OHOS:HiviewDFX::HiSysEvent::Domain::POWER, "POWER_RUNNINGLOCK", OHOS:HiviewDFX::HiSysEvent::EventType::FAULT, "NAME", "com.ohos.module"); // HiSysEvent logging is not performed.
```
- If you want to shield event logging for the **AAFWK** and **POWER** domains of the entire service module, define the **DOMAIN_MASKS** macro as follows in the **BUILG.gn** file of the service module.
```gn
config("module_a") {
... // Other configuration items
cflags_cc += ["-DDOMAIN_MASKS=\"AAFWK|POWER\""]
... // Other configuration items
cflags_cc += ["-DDOMAIN_MASKS=\"AAFWK|POWER\""]
}
```
......
......@@ -6,106 +6,382 @@
HiSysEvent allows you to query system events by specifying search criteria. For example, for a power consumption module, you can query required system events for analysis.
## Development Guidelines
## How to Develop
### Available APIs
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
#### C++ Event Query API
HiSysEvent query is implemented using the API provided by the **HiSysEventManager** class. For details, see the [API Header Files](/base/hiviewdfx/hisysevent/interfaces/native/innerkits/hisysevent_manager/include/).
> **NOTE**
>
> For details about the **HiSysEventRecord** argument in the **OnQuery()** method of **HiSysEventQueryCallback**, see Table 5 in [HiSysEvent Listening](subsys-dfx-hisysevent-listening.md).
> For details about **HiSysEventRecord** in the **OnQuery()** API of **HiSysEventQueryCallback**, see Table 5 in [HiSysEvent Listening](subsys-dfx-hisysevent-listening.md).
**Table 1** Description of the HiSysEvent query API
**Table 1** Description of the HiSysEvent query API
| API | Description |
| --- | ----------- |
| int32_t HiSysEventManager::Query(struct QueryArg&amp; arg, std::vector&lt;QueryRule&gt;&amp; rules, std::shared_ptr&lt;HiSysEventQueryCallback&gt; callback) | Queries system events by specifying search criteria such as the time segment, event domain, and event name.<br>Input arguments:<br>- **arg**: event query parameter.<br>- **rules**: rules for event filtering.<br>- **callback**: callback object for event query.<br>Return value:<br>- **0**: Query is successful.<br>- A negative value: Query has failed.|
| API| Description|
| -------- | -------- |
| int32_t Query(struct&nbsp;QueryArg&amp;&nbsp;arg,<br>std::vector&lt;QueryRule&gt;&amp;&nbsp;rules,<br>std::shared_ptr&lt;HiSysEventQueryCallback&gt;&nbsp;callback) | Queries system events by search criteria such as the time segment, event domain, and event name.<br>Input arguments:<br>- **arg**: event query parameter.<br>- **rules**: rules for event filtering.<br>- **callback**: callback object for event query.<br>Return value:<br>- **0**: Query is successful.<br>- A negative value: Query has failed.|
**Table 2** Description of QueryArg
**Table 2** Description of QueryArg objects
| Attribute | Description |
| --------- | ----------- |
| beginTime | Start time, in the **long long int** format.|
| endTime | End time, in the **long long int** format.|
| maxEvents | Maximum number of returned events, in the **int** format.|
| Attribute| Type| Description|
| -------- | -------- | -------- |
| beginTime | long long | Start time for query. The value is a Unix timestamp, in milliseconds.|
| endTime | long long | End time for query. The value is a Unix timestamp, in milliseconds.|
| maxEvents | int | Maximum number of returned events.|
**Table 3** Description of QueryRule
**Table 3** Description of QueryRule objects
| API| Description|
| -------- | -------- |
| QueryRule(const std::string&amp; domain, const std::vector&lt;std::string&gt;&amp; eventList) | Constructor used to create a **QueryRule** object.<br>Input arguments:<br>- **domain**: domain to which the event of the **QueryRule** object belongs, in the string format. By default, an empty string indicates that the domain is successfully matched.<br>- **eventList**: event name list, in the **std::vector&lt;std::string&gt;** format. By default, an empty string indicates that the event names on the list are successfully matched.|
| QueryRule(const&nbsp;std::string&amp;&nbsp;domain,<br>const&nbsp;std::vector&lt;std::string&gt;&amp;&nbsp;eventList) | Constructor used to create a **QueryRule** object.<br>Input arguments:<br>- **domain**: domain to which the event of the **QueryRule** object belongs, in the string format. By default, an empty string indicates that the domain is successfully matched.<br>**eventList**: event name list, in the **std::vector&lt;std::string&gt;** format. By default, an empty string indicates that the event names on the list are successfully matched.|
**Table 4** Description of HiSysEventQueryCallback
**Table 4** Description of HiSysEventQueryCallback objects
| API| Description|
| -------- | -------- |
| void HiSysEventQueryCallback::OnQuery(std::shared_ptr&lt;std::vector&lt;HiSysEventRecord&gt;&gt; sysEvents) | Callback object for event query.<br>Input arguments:<br>- **sysEvents**: event list.<br>Return value:<br>None.|
| void HiSysEventQueryCallback::OnComplete(int32_t reason, int32_t total) | Callback object for completion of event query.<br>Input arguments:<br>- **reason**: reason for completion of event query. The default value is **0**.<br>- **total**: total number of events returned in this query.<br>Return value:<br>None.|
| void&nbsp;HiSysEventQueryCallback::OnQuery(std::shared_ptr&lt;std::vector&lt;HiSysEventRecord&gt;&gt;&nbsp;sysEvents) | Callback object for event query.<br>Input arguments:<br>- **sysEvents**: event list.|
| void&nbsp;HiSysEventQueryCallback::OnComplete(int32_t&nbsp;reason,&nbsp;int32_t&nbsp;total) | Callback object for completion of event query.<br>Input arguments:<br>- **reason**: reason for completion of event query. The value **0** indicates that the query is normal, and any other value indicates that the query has failed.<br>- **total**: total number of events returned in this query.|
#### C Event Query API
HiSysEvent query is implemented using the API provided in the following table. For details, see the [API Header Files](/base/hiviewdfx/hisysevent/interfaces/native/innerkits/hisysevent_manager/include/).
**Table 5** Description of the HiSysEvent query API
| API | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| int OH_HiSysEvent_Query(const HiSysEventQueryArg& arg, HiSysEventQueryRule rules[], size_t ruleSize, HiSysEventQueryCallback& callback); | Queries system events by search criteria such as the time segment, event domain, event name, and event parameter.<br>Input arguments:<br>- **arg**: event query parameter.<br>- **rules**: rules for event filtering.<br>- **ruleSize**: number of event filtering rules.<br>- **callback**: callback object for event query.<br>Return value:<br>- **0**: Query is successful.<br>- A negative value: Query has failed.|
**Table 6** Description of the HiSysEventQueryArg structure
| Attribute | Type| Description |
| --------- | -------- | ---------------------------------------------------- |
| beginTime | int64_t | Start time for query. The value is a Unix timestamp, in milliseconds.|
| endTime | int64_t | End time for query. The value is a Unix timestamp, in milliseconds.|
| maxEvents | int32_t | Maximum number of returned events. |
**Table 7** Description of the HiSysEventQueryRule structure
| Attribute | Type | Description |
| ------------- | --------- | ---------------------------------- |
| domain | char[] | Event domain. |
| eventList | char\[][] | Event name list. |
| eventListSize | size_t | Size of the event name list. |
| condition | char* | Custom event parameter conditions for the query.|
The **condition** parameter must be in the specified JSON string format. For example:
```json
{
"version":"V1",
"condition":{
"and":[
{"param":"type_","op":">","value":0},
{"param":"uid_","op":"=","value":1201}
],
"or":[
{"param":"NAME","op":"=","value":"SysEventService"},
{"param":"NAME","op":"=","value":"SysEventSource"}
]
}
}
```
- The **version** field is mandatory, indicating the supported version of the input condition. Currently, only **V1** is supported.
- The **condition** field is mandatory, indicating the input condition.
- The **and** field is optional, indicating the AND relationship between conditions.
- The **or** field is optional, indicating the OR relationship between conditions.
- The **param** field is mandatory, indicating the parameter name for condition matching. The value must be a string.
- The **op** field is mandatory, indicating the parameter comparison operator for condition matching. The value must be a string. Supported comparison operators include the following: =, >, <, >=, and <=.
- The **value** field is mandatory, indicating the parameter value for condition matching. The value must be a string or an integer.
**Table 8** Description of the HiSysEventQueryCallback structure
| Attribute | Type | Description |
| ---------- | -------------------------------------------------- | ------------------------------------------------------------ |
| OnQuery | void (*)(HiSysEventRecord records[], size_t size); | Callback object for event query.<br>Input arguments:<br>- **records**: event list.<br>- **size**: size of the event list.|
| OnComplete | void (*)(int32_t reason, int32_t total); | Callback object for completion of event query.<br>Input arguments:<br>- **reason**: reason for completion of event query. The value **0** indicates that the query is normal, and any other value indicates that the query has failed.<br>- **total**: total number of events returned in this query.|
**Table 9** Description of the HiSysEventRecord event structure
| Attribute | Type | Description |
| --------- | ------------------- | -------------------------- |
| domain | char[] | Event domain. |
| eventName | char\[] | Event name. |
| type | HiSysEventEventType | Event type. |
| time | uint64_t | Event timestamp. |
| tz | char\[] | Event time zone. |
| pid | int64_t | Process ID of the event. |
| tid | int64_t | Thread ID of the event. |
| uid | int64_t | User ID of the event. |
| traceId | uint64_t | Distributed call chain trace ID of the event. |
| spandId | uint64_t | Span ID for the distributed call chain trace of the event. |
| pspanId | uint64_t | Parent span ID for the distributed call chain trace of the event.|
| traceFlag | int | Distributed call chain trace flag of the event. |
| level | char* | Event level. |
| tag | char* | Event tag. |
| jsonStr | char* | Event content. |
**Table 10** Description of HiSysEventRecord APIs
| API | |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| void OH_HiSysEvent_GetParamNames(const HiSysEventRecord& record, char*** params, size_t& len); | Obtains all parameter names of an event.<br>Input arguments:<br>- **record**: event structure.<br>- **params**: parameter name array.<br>- **len**: size of the parameter name array.|
| int OH_HiSysEvent_GetParamInt64Value(const HiSysEventRecord& record, const char* name, int64_t& value); | Parses the parameter value in the event to an int64_t value and assigns the value to **value**.<br>Input arguments:<br>- **record**: event structure.<br>- **name**: parameter name.<br>- **value**: parameter value of the int64_t type.|
| int OH_HiSysEvent_GetParamUint64Value(const HiSysEventRecord& record, const char* name, uint64_t& value); | Parses the parameter value in the event to an uint64_t value and assigns the value to **value**.<br>Input arguments:<br>- **record**: event structure.<br>- **name**: parameter name.<br>- **value**: parameter value of the uint64_t type.|
| int OH_HiSysEvent_GetParamDoubleValue(const HiSysEventRecord& record, const char* name, double& value); | Parses the parameter value in the event to a double value and assigns the value to **value**.<br>Input arguments:<br>- **record**: event structure.<br>- **name**: parameter name.<br>- **value**: parameter value of the double type.|
| int OH_HiSysEvent_GetParamStringValue(const HiSysEventRecord& record, const char* name, char** value); | Parses the parameter value in the event to a char array value and assigns the value to **value**. You need to release the memory manually after usage.<br>Input arguments:<br>- **record**: event structure.<br>- **name**: parameter name.<br>- **value**: char\* reference.|
| int OH_HiSysEvent_GetParamInt64Values(const HiSysEventRecord& record, const char* name, int64_t** value, size_t& len); | Parses the parameter value in the event to a int64_t array value and assigns the value to **value**. You need to release the memory manually after usage.<br>Input arguments:<br>- **record**: event structure.<br>- **name**: parameter name.<br>- **value**: int64_t\* reference.<br>- **len**: array size.|
| int OH_HiSysEvent_GetParamUint64Values(const HiSysEventRecord& record, const char* name, uint64_t** value, size_t& len); | Parses the parameter value in the event to a uint64_t array value and assigns the value to **value**. You need to release the memory manually after usage.<br>Input arguments:<br>- **record**: event structure.<br>- **name**: parameter name.<br>- **value**: uint64_t\* reference.<br>- **len**: array size.|
| int OH_HiSysEvent_GetParamDoubleValues(const HiSysEventRecord& record, const char* name, double** value, size_t& len); | Parses the parameter value in the event to a double array value and assigns the value to **value**. You need to release the memory manually after usage.<br>Input arguments:<br>- **record**: event structure.<br>- **name**: parameter name.<br>- **value**: double\* reference.<br>- **len**: array size.|
| int OH_HiSysEvent_GetParamStringValues(const HiSysEventRecord& record, const char* name, char*** value, size_t& len); | Parses the parameter value in the event to a char* array value and assigns the value to **value**. You need to release the memory manually after usage.<br>Input arguments:<br>- **record**: event structure.<br>- **name**: parameter name.<br>- **value**: char\*\* reference.<br>- **len**: array size.|
The return values of the HiSysEventRecord APIs are described as follows:
- **0**: The parsing is successful.
- -**1**: The event fails to be initialized.
- -**2**: The parameter name does not exist.
- -**3**: The type of the parameter value to be parsed does not match the type of the input parameter value.
### How to Develop
**C++**
#### C++ HiSysEvent Query API
1. Develop the source code.
Import the corresponding header file:
1. Import the corresponding header file:
```
```c++
#include "hisysevent_manager.h"
```
Implement the callback API.
2. Implement the callback API.
```
void HiSysEventQueryCallback::OnQuery(std::shared_ptr<std::vector<HiSysEventRecord>> sysEvents)
void HiSysEventQueryCallback::OnComplete(int32_t reason, int32_t total)
```c++
class TestQueryCallback : public HiSysEventQueryCallback {
public:
void OnQuery(std::shared_ptr<std::vector<HiSysEventRecord>> sysEvents) override
{
if (sysEvents == nullptr) {
return;
}
for_each((*sysEvents).cbegin(), (*sysEvents).cend(), [](const HiSysEventRecord& event) {
std::cout << event.AsJson() << std::endl;
});
}
void OnComplete(int32_t reason, int32_t total) override
{
std::cout << "Query completed" << std::endl;
return;
}
};
```
Call the query API in the corresponding service logic.
3. Call the query API while passing in the query parameter, rule, and callback object.
```c++
// Create a query parameter object.
long long startTime = 0;
long long endTime = 1668245644000; //2022-11-12 09:34:04
int queryCount = 10;
QueryArg arg(startTime, endTime, queryCount);
// Create a query rule object.
QueryRule rule("HIVIEWDFX", { "PLUGIN_LOAD" });
std::vector<QueryRule> queryRules = { rule };
// Create a query callback object.
auto queryCallback = std::make_shared<TestQueryCallback>();
// Call the query API.
HiSysEventManager::Query(arg, queryRules, queryCallback);
```
HiSysEventManager::Query(struct QueryArg& queryArg,
std::vector<QueryRule>& queryRules, std::shared_ptr<HiSysEventQueryCallback> queryCallBack)
```
In this example, you'll query all system events.
#### C HiSysEvent Query API
1. Import the corresponding header file:
```c++
#include "hisysevent_manager_c.h"
```
#include "hisysevent_manager.h"
#include <iostream>
namespace OHOS {
namespace HiviewDFX {
// Implement the query callback API.
void HiSysEventToolQuery::OnQuery(std::shared_ptr<std::vector<HiSysEventRecord>> sysEvents)
2. Implement the callback API.
```c++
void OnQueryTest(HiSysEventRecord records[], size_t size)
{
if (sysEvents == nullptr) {
return;
for (size_t i = 0; i < size; i++) {
printf("OnQuery: event=%s", records[i].jsonStr);
}
for_each((*sysEvents).cbegin(), (*sysEvents).cend(), [](const HiSysEventRecord& event) {
std::cout << event.AsJson() << std::endl;
});
}
void HiSysEventToolQuery::OnComplete(int32_t reason, int32_t total)
void OnCompleteTest(int32_t reason, int32_t total)
{
return;
printf("OnCompleted, res=%d, total=%d\n", reason, total);
}
} // namespace HiviewDFX
} // namespace OHOS
// Call the query callback API to obtain system events.
auto queryCallBack = std::make_shared<HiSysEventToolQuery>();
struct QueryArg args(clientCmdArg.beginTime, clientCmdArg.endTime, clientCmdArg.maxEvents);
std::vector<QueryRule> rules;
HiSysEventManager::QueryHiSysEvent(args, rules, queryCallBack);
```
2. Modify the **BUILD.gn** file.
In the **BUILD.gn** file, add the **libhisysevent** and **libhisyseventmanager** libraries that depend on the **hisysevent_native** component.
3. Call the query API while passing in the query parameter, rule, and callback object.
```c++
// Create a query parameter object.
HiSysEventQueryArg arg;
arg.beginTime = 0;
arg.endTime = 1668245644000; //2022-11-12 09:34:04
arg.maxEvents = 10;
// Create a query rule object.
constexpr char TEST_DOMAIN[] = "HIVIEWDFX";
constexpr char TEST_NAME[] = "PLUGIN_LOAD";
HiSysEventQueryRule rule;
(void)strcpy_s(rule.domain, strlen(TEST_DOMAIN) + 1, TEST_DOMAIN);
(void)strcpy_s(rule.eventList[0], strlen(TEST_NAME) + 1, TEST_NAME);
rule.eventListSize = 1;
rule.condition = nullptr;
HiSysEventQueryRule rules[] = { rule };
// Create a query callback object.
HiSysEventQueryCallback callback;
callback.OnQuery = OnQueryTest;
callback.OnComplete = OnCompleteTest;
// Call the query API.
OH_HiSysEvent_Query(arg, rules, sizeof(rules) / sizeof(HiSysEventQueryRule), callback);
```
### Development Example
#### C++ HiSysEvent Query
Assume that you need to query all **PLUGIN_LOAD** events that are generated for the **HIVIEWDFX** domain until the current time on a service module. The development procedure is as follows:
1. Add the **libhisysevent** and **libhisyseventmanager** dependencies of the **hisysevent_native** component to **BUILD.gn** of the service module.
```c++
external_deps = [
"hisysevent_native:libhisysevent",
"hisysevent_native:libhisyseventmanager",
]
```
2. Call the query API in the **TestQuery()** function of the service module.
```c++
#include "hisysevent_manager.h"
#include <iostream>
#include <unistd.h>
using namespace OHOS::HiviewDFX;
class TestQueryCallback : public HiSysEventQueryCallback {
public:
void OnQuery(std::shared_ptr<std::vector<HiSysEventRecord>> sysEvents) override
{
if (sysEvents == nullptr) {
return;
}
for_each((*sysEvents).cbegin(), (*sysEvents).cend(), [](const HiSysEventRecord& event) {
std::cout << event.AsJson() << std::endl;
});
}
void OnComplete(int32_t reason, int32_t total) override
{
std::cout << "Query completed" << std::endl;
return;
}
};
int64_t GetMilliseconds()
{
auto now = std::chrono::system_clock::now();
auto millisecs = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch());
return millisecs.count();
}
void TestQuery()
{
// Create a query parameter object.
long long startTime = 0;
long long endTime = GetMilliseconds();
int maxEvents = 100;
QueryArg arg(startTime, endTime, maxEvents);
// Create a query rule object.
QueryRule rule("HIVIEWDFX", { "PLUGIN_LOAD" });
std::vector<QueryRule> queryRules = { rule };
// Create a query callback object.
auto queryCallback = std::make_shared<TestQueryCallback>();
// Call the query API.
int ret = HiSysEventManager::Query(arg, queryRules, queryCallback);
}
```
#### C HiSysEvent Query
Assume that you need to query all **PLUGIN_LOAD** events that are generated for the **HIVIEWDFX** domain until the current time on a service module. The development procedure is as follows:
1. Add the **libhisyseventmanager** dependency of the **hisysevent_native** component to the **BUILD.gn** file of the service module.
```c++
external_deps = [ "hisysevent_native:libhisyseventmanager" ]
// for strcpy_s
deps = [ "//third_party/bounds_checking_function:libsec_shared" ]
```
2. Call the query API in the **TestQuery()** function of the service module.
```c++
#include "hisysevent_manager_c.h"
#include <securec.h>
#include <time.h>
void OnQueryTest(HiSysEventRecord records[], size_t size)
{
for (size_t i = 0; i < size; i++) {
printf("OnQuery: event=%s", records[i].jsonStr);
}
}
void OnCompleteTest(int32_t reason, int32_t total)
{
printf("OnCompleted, res=%d, total=%d\n", reason, total);
}
int64_t GetMilliseconds()
{
return time(NULL);
}
void TestQuery()
{
// Create a query parameter object.
HiSysEventQueryArg arg;
arg.beginTime = 0;
arg.endTime = GetMilliseconds();
arg.maxEvents = 100;
// Create a query rule object.
constexpr char TEST_DOMAIN[] = "HIVIEWDFX";
constexpr char TEST_NAME[] = "PLUGIN_LOAD";
HiSysEventQueryRule rule;
(void)strcpy_s(rule.domain, strlen(TEST_DOMAIN) + 1, TEST_DOMAIN);
(void)strcpy_s(rule.eventList[0], strlen(TEST_NAME) + 1, TEST_NAME);
rule.eventListSize = 1;
rule.condition = nullptr;
HiSysEventQueryRule rules[] = { rule };
// Create a query callback object.
HiSysEventQueryCallback callback;
callback.OnQuery = OnQueryTest;
callback.OnComplete = OnCompleteTest;
// Call the query API.
int ret = OH_HiSysEvent_Query(arg, rules, sizeof(rules) / sizeof(HiSysEventQueryRule), callback);
}
```
......@@ -3,6 +3,5 @@
| FA模型接口 | Stage模型接口对应d.ts文件 | Stage模型对应接口 |
| -------- | -------- | -------- |
| [enum&nbsp;WindowType&nbsp;{<br/>TYPE_APP<br/>}](../reference/apis/js-apis-window.md#windowtype7) | \@ohos.window.d.ts | [createSubWindow(name:&nbsp;string,&nbsp;callback:&nbsp;AsyncCallback&lt;Window&gt;):&nbsp;void;](../reference/apis/js-apis-window.md#createsubwindow9)<br/>[createSubWindow(name:&nbsp;string):&nbsp;Promise;](../reference/apis/js-apis-window.md#createsubwindow9-1)<br/>FA模型应用通过window.create(id,&nbsp;WindowType.TYPE_APP)接口创建应用子窗口,Stage模型应用可使用WindowStage.CreateSubWindow()接口代替 |
| [create(id:&nbsp;string,&nbsp;type:&nbsp;WindowType,&nbsp;callback:&nbsp;AsyncCallback&lt;Window&gt;):&nbsp;void;](../reference/apis/js-apis-window.md#windowcreatedeprecated)<br/>[create(id:&nbsp;string,&nbsp;type:&nbsp;WindowType):&nbsp;Promise&lt;Window&gt;;](../reference/apis/js-apis-window.md#windowcreatedeprecated-1) | \@ohos.window.d.ts | [createWindow(config:&nbsp;Configuration,&nbsp;callback:&nbsp;AsyncCallback&lt;Window&gt;):&nbsp;void;](../reference/apis/js-apis-window.md#windowcreatewindow9)<br/>[createWindow(config:&nbsp;Configuration):&nbsp;Promise&lt;Window&gt;;](../reference/apis/js-apis-window.md#windowcreatewindow9-1) |
| [create(id:&nbsp;string,&nbsp;type:&nbsp;WindowType,&nbsp;callback:&nbsp;AsyncCallback&lt;Window&gt;):&nbsp;void;](../reference/apis/js-apis-window.md#windowcreatedeprecated)<br/>[create(id:&nbsp;string,&nbsp;type:&nbsp;WindowType):&nbsp;Promise&lt;Window&gt;;](../reference/apis/js-apis-window.md#windowcreatedeprecated-1) | \@ohos.window.d.ts | [createSubWindow(name:&nbsp;string,&nbsp;callback:&nbsp;AsyncCallback&lt;Window&gt;):&nbsp;void;](../reference/apis/js-apis-window.md#createsubwindow9)<br/>[createSubWindow(name:&nbsp;string):&nbsp;Promise;](../reference/apis/js-apis-window.md#createsubwindow9-1)<br/>FA模型应用通过window.create(id,&nbsp;WindowType.TYPE_APP)接口创建应用子窗口,Stage模型应用可使用WindowStage.CreateSubWindow()接口代替 |
| [getTopWindow(callback:&nbsp;AsyncCallback&lt;Window&gt;):&nbsp;void;](../reference/apis/js-apis-window.md#windowgettopwindowdeprecated)<br/>[getTopWindow():&nbsp;Promise&lt;Window&gt;;](../reference/apis/js-apis-window.md#windowgettopwindowdeprecated-1) | \@ohos.window.d.ts | [getLastWindow(ctx:&nbsp;BaseContext,&nbsp;callback:&nbsp;AsyncCallback&lt;Window&gt;):&nbsp;void;](../reference/apis/js-apis-window.md#windowgetlastwindow9)<br/>[getLastWindow(ctx:&nbsp;BaseContext):&nbsp;Promise&lt;Window&gt;;](../reference/apis/js-apis-window.md#windowgetlastwindow9-1) |
......@@ -363,7 +363,7 @@ startAbilityForResultWithAccount(want: Want, accountId: number, callback: AsyncC
启动一个Ability并在该Ability帐号销毁时返回执行结果(callback形式)。
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS,当accountId为当前用户时,不需要校验该权限。
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
......@@ -420,7 +420,7 @@ startAbilityForResultWithAccount(want: Want, accountId: number, options: StartOp
启动一个Ability并在该Ability帐号销毁时返回执行结果(callback形式)。
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS,当accountId为当前用户时,不需要校验该权限。
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
......@@ -481,7 +481,7 @@ startAbilityForResultWithAccount(want: Want, accountId: number, options?: StartO
启动一个Ability并在该Ability帐号销毁时返回执行结果(promise形式)。
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS,当accountId为当前用户时,不需要校验该权限。
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
......@@ -646,7 +646,7 @@ startServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback:
启动一个新的ServiceExtensionAbility(callback形式)。
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS,当accountId为当前用户时,不需要校验该权限。
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
......@@ -701,7 +701,7 @@ startServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\
启动一个新的ServiceExtensionAbility(Promise形式)。
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS,当accountId为当前用户时,不需要校验该权限。
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
......@@ -782,8 +782,14 @@ stopServiceExtensionAbility(want: Want, callback: AsyncCallback\<void>): void;
};
try {
this.context.startAbility(want, (error) => {
if (error.code != 0) {
console.log("start ability fail, err: " + JSON.stringify(err));
}
})
this.context.stopServiceExtensionAbility(want, (error) => {
if (error.code) {
if (error.code != 0) {
// 处理业务逻辑错误
console.log('stopServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) +
' error.message: ' + JSON.stringify(error.message));
......@@ -832,6 +838,12 @@ stopServiceExtensionAbility(want: Want): Promise\<void>;
};
try {
this.context.startAbility(want, (error) => {
if (error.code != 0) {
console.log("start ability fail, err: " + JSON.stringify(err));
}
})
this.context.stopServiceExtensionAbility(want)
.then((data) => {
// 执行正常业务
......@@ -855,7 +867,7 @@ stopServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback:
使用帐户停止同一应用程序内的服务(callback形式)。
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS,当accountId为当前用户时,不需要校验该权限。
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
......@@ -887,6 +899,12 @@ stopServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback:
var accountId = 100;
try {
this.context.startAbilityWithAccount(want, accountId, (error) => {
if (error.code != 0) {
console.log("start ability fail, err: " + JSON.stringify(err));
}
})
this.context.stopServiceExtensionAbilityWithAccount(want, accountId, (error) => {
if (error.code) {
// 处理业务逻辑错误
......@@ -910,7 +928,7 @@ stopServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\<
使用帐户停止同一应用程序内的服务(Promise形式)。
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS,当accountId为当前用户时,不需要校验该权限。
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
......@@ -941,6 +959,12 @@ stopServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\<
var accountId = 100;
try {
this.context.startAbilityWithAccount(want, accountId, (error) => {
if (error.code != 0) {
console.log("start ability fail, err: " + JSON.stringify(err));
}
})
this.context.stopServiceExtensionAbilityWithAccount(want, accountId)
.then((data) => {
// 执行正常业务
......@@ -1207,7 +1231,7 @@ connectServiceExtensionAbilityWithAccount(want: Want, accountId: number, options
使用AbilityInfo.AbilityType.SERVICE模板和account将当前Ability连接到一个Ability。
**需要权限:** ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**需要权限:** ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS,当accountId为当前用户时,不需要校验该权限。
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
......@@ -1451,7 +1475,7 @@ startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\<
根据account启动Ability(callback形式)。
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS,当accountId为当前用户时,不需要校验该权限。
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
......@@ -1507,7 +1531,7 @@ startAbilityWithAccount(want: Want, accountId: number, options: StartOptions, ca
根据account启动Ability(callback形式)。
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS,当accountId为当前用户时,不需要校验该权限。
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
......@@ -1567,7 +1591,7 @@ startAbilityWithAccount(want: Want, accountId: number, options?: StartOptions):
根据account启动Ability(Promise形式)。
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS,当accountId为当前用户时,不需要校验该权限。
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
......
......@@ -23,40 +23,66 @@ import AbilityConstant from '@ohos.app.ability.AbilityConstant';
| 名称 | 类型 | 可读 | 可写 | 说明 |
| -------- | -------- | -------- | -------- | -------- |
| launchReason | [LaunchReason](#abilityconstantlaunchreason)| 是 | 是 | 示启动原因。 |
| lastExitReason | [LastExitReason](#abilityconstantlastexitreason) | 是 | 是 | 表示最后退出原因。 |
| launchReason | [LaunchReason](#abilityconstantlaunchreason)| 是 | 是 | 枚举类型,表示启动原因。 |
| lastExitReason | [LastExitReason](#abilityconstantlastexitreason) | 是 | 是 | 枚举类型,表示最后退出原因。 |
## AbilityConstant.LaunchReason
初次启动原因
Ability初次启动原因,该类型为枚举,可配合[Ability](js-apis-app-ability-uiAbility.md)[onCreate(want, launchParam)](js-apis-app-ability-uiAbility.md#uiabilityoncreate)方法根据launchParam.launchReason的不同类型执行相应操作
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core
| 名称 | 值 | 说明 |
| ----------------------------- | ---- | ------------------------------------------------------------ |
| UNKNOWN | 0 | 未知的状态。 |
| START_ABILITY | 1 | 启动能力。 |
| CALL | 2 | 呼叫。 |
| CONTINUATION | 3 | 继续。 |
| APP_RECOVERY | 4 | 状态恢复。 |
| UNKNOWN | 0 | 未知原因。 |
| START_ABILITY | 1 | 通过[startAbility](js-apis-ability-context.md#abilitycontextstartability)接口启动ability。 |
| CALL | 2 | 通过[startAbilityByCall](js-apis-ability-context.md#abilitycontextstartabilitybycall)接口启动ability。 |
| CONTINUATION | 3 | 跨端设备迁移启动ability。 |
| APP_RECOVERY | 4 | 设置应用恢复后,应用故障时自动恢复启动ability。 |
**示例:**
```ts
import UIAbility form '@ohos.app.ability.UIAbility';
class MyAbility extends UIAbility {
onCreate(want, launchParam) {
if (launcherParam.launchReason == AbilityConstant.LaunchReason.START_ABILITY) {
console.log("The ability has been started by the way of startAbility.");
}
}
}
```
## AbilityConstant.LastExitReason
上次退出原因
Ability上次退出原因,该类型为枚举,可配合[Ability](js-apis-app-ability-uiAbility.md)[onCreate(want, launchParam)](js-apis-app-ability-uiAbility.md#uiabilityoncreate)方法根据launchParam.lastExitReason的不同类型执行相应操作
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core
| 名称 | 值 | 说明 |
| ----------------------------- | ---- | ------------------------------------------------------------ |
| UNKNOWN | 0 | 未知的状态。 |
| ABILITY_NOT_RESPONDING | 1 | 能力没有反应 |
| NORMAL | 2 | 正常的状态。 |
| UNKNOWN | 0 | 未知原因。 |
| ABILITY_NOT_RESPONDING | 1 | ability未响应。 |
| NORMAL | 2 | 正常退出。 |
**示例:**
```ts
import UIAbility form '@ohos.app.ability.UIAbility';
class MyAbility extends UIAbility {
onCreate(want, launchParam) {
if (launcherParam.lastExitReason == AbilityConstant.LastExitReason.ABILITY_NOT_RESPONDING) {
console.log("The ability has exit last because the ability was not responding.");
}
}
}
```
## AbilityConstant.OnContinueResult
迁移结果
Ability迁移结果,该类型为枚举,可配合[Ability](js-apis-app-ability-uiAbility.md)[onContinue(wantParam)](js-apis-app-ability-uiAbility.md#uiabilityoncontinue)方法进完成相应的返回
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core
......@@ -66,9 +92,21 @@ import AbilityConstant from '@ohos.app.ability.AbilityConstant';
| REJECT | 1 | 拒绝。 |
| MISMATCH | 2 | 不匹配。|
**示例:**
```ts
import UIAbility form '@ohos.app.ability.UIAbility';
class MyAbility extends UIAbility {
onContinue(wantParam) {
return AbilityConstant.OnConinueResult.AGREE;
}
}
```
## AbilityConstant.WindowMode
启动Ability时的窗口模式。
启动Ability时的窗口模式,该类型为枚举,可配合startAbility使用指定启动Ability的窗口模式
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core
......@@ -80,36 +118,81 @@ import AbilityConstant from '@ohos.app.ability.AbilityConstant';
| WINDOW_MODE_SPLIT_SECONDARY | 101 | 分屏多窗口次要模式。 |
| WINDOW_MODE_FLOATING | 102 | 自由悬浮形式窗口模式。 |
**示例:**
```ts
let want = {
bundleName: "com.test.example",
abilityName: "MainAbility"
};
let option = {
windowMode: AbilityConstant.WindowMode.WINDOW_MODE_FULLSCREEN
};
// 确保从上下文获取到context
this.context.startAbility(want, option).then(()={
console.log("Succeed to start ability.");
}).catch((error)=>{
console.log("Failed to start ability with error: " + JSON.stringify(error));
});
```
## AbilityConstant.MemoryLevel
内存级别。
内存级别,该类型为枚举,可配合[Ability](js-apis-app-ability-ability.md)[onMemoryLevel(level)](js-apis-app-ability-ability.md#abilityonmemorylevel)方法根据level执行不同内存级别的相应操作
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core
| 名称 | 值 | 说明 |
| --- | --- | --- |
| MEMORY_LEVEL_MODERATE | 0 | 内存占用适中。 |
| MEMORY_LEVEL_LOW | 1 | 内存占用低。 |
| --- | --- | --- |
| MEMORY_LEVEL_MODERATE | 0 | 内存占用适中。 |
| MEMORY_LEVEL_LOW | 1 | 内存占用低。 |
| MEMORY_LEVEL_CRITICAL | 2 | 内存占用高。 |
**示例:**
```ts
import UIAbility form '@ohos.app.ability.UIAbility';
class MyAbility extends UIAbility {
onMemoryLevel(level) {
if (level == AbilityConstant.MemoryLevel.MEMORY_LEVEL_CRITICAL) {
console.log("The memory of device is critical, please release some memory.");
}
}
}
```
## AbilityConstant.OnSaveResult
保存应用数据的结果。
保存应用数据的结果,该类型为枚举,可配合[Ability](js-apis-app-ability-uiAbility.md)[onSaveState(reason, wantParam)](js-apis-app-ability-uiAbility.md#uiabilityonsavestate)方法完成相应的返回
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core
| 名称 | 值 | 说明 |
| ----------------------------- | ---- | ------------------------------------------------------------ |
| ALL_AGREE | 0 | 同意保存状态。 |
| ALL_AGREE | 0 | 总是同意保存状态。 |
| CONTINUATION_REJECT | 1 | 拒绝迁移保存状态。 |
| CONTINUATION_MISMATCH | 2 | 迁移不匹配。|
| RECOVERY_AGREE | 3 | 同意恢复保存状态。 |
| RECOVERY_REJECT | 4 | 拒绝恢复保存状态。|
| ALL_REJECT | 5 | 拒绝保存状态。|
| ALL_REJECT | 5 | 总是拒绝保存状态。|
**示例:**
```ts
import UIAbility form '@ohos.app.ability.UIAbility';
class MyAbility extends UIAbility {
onSaveState(reason, wantParam) {
return AbilityConstant.OnSaveResult.ALL_AGREE;
}
}
```
## AbilityConstant.StateType
保存应用数据场景原因。
保存应用数据场景原因,该类型为枚举,可配合[Ability](js-apis-app-ability-uiAbility.md)[onSaveState(reason, wantParam)](js-apis-app-ability-uiAbility.md#uiabilityonsavestate)方法根据reason的不同类型执行相应操作
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core
......@@ -117,3 +200,18 @@ import AbilityConstant from '@ohos.app.ability.AbilityConstant';
| ----------------------------- | ---- | ------------------------------------------------------------ |
| CONTINUATION | 0 | 迁移保存状态。 |
| APP_RECOVERY | 1 | 应用恢复保存状态。 |
**示例:**
```ts
import UIAbility form '@ohos.app.ability.UIAbility';
class MyAbility extends UIAbility {
onSaveState(reason, wantParam) {
if (reason == AbilityConstant.StateType.CONTINUATION) {
console.log("Save the ability data when the ability continuation.");
}
return AbilityConstant.OnSaveResult.ALL_AGREE;
}
}
```
\ No newline at end of file
# @ohos.app.ability.abilityDelegatorRegistry (AbilityDelegatorRegistry)
AbilityDelegatorRegistry模块提供用于存储已注册的AbilityDelegator和AbilityDelegatorArgs对象的全局寄存器的能力,包括获取应用程序的AbilityDelegator对象、获取单元测试参数AbilityDelegatorArgs对象
AbilityDelegatorRegistry[测试框架](../../ability-deprecated/ability-delegator.md)模块,该模块用于获取[AbilityDelegator](js-apis-inner-application-abilityDelegator.md)[AbilityDelegatorArgs](js-apis-inner-application-abilityDelegatorArgs.md)对象,其中[AbilityDelegator](js-apis-inner-application-abilityDelegator.md)对象提供添加用于监视指定ability的生命周期状态更改的AbilityMonitor对象的能力,[AbilityDelegatorArgs](js-apis-inner-application-abilityDelegatorArgs.md)对象提供获取当前测试参数的能力
> **说明:**
>
> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
> 本模块接口仅可在测试框架中使用。
## 导入模块
```ts
import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'
import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry';
```
## AbilityLifecycleState
Ability生命周期状态。
Ability生命周期状态,该类型为枚举,可配合[AbilityDelegator](js-apis-inner-application-abilityDelegator.md)[getAbilityState(ability)](js-apis-inner-application-abilityDelegator.md#getabilitystate9)方法返回不同ability生命周期
**系统能力** :以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core
| 名称 | 值 | 说明 |
| ------------- | ---- | --------------------------- |
| UNINITIALIZED | 0 | 表示无效状态。 |
| UNINITIALIZED | 0 | 表示Ability处于无效状态。 |
| CREATE | 1 | 表示Ability处于已创建状态。 |
| FOREGROUND | 2 | 表示Ability处于前台状态。 |
| BACKGROUND | 3 | 表示Ability处于后台状态。 |
......@@ -30,7 +31,7 @@ Ability生命周期状态。
getAbilityDelegator(): AbilityDelegator
获取应用程序的AbilityDelegator对象
获取应用程序的[AbilityDelegator](js-apis-inner-application-abilityDelegator.md)对象,该对象能够使用调度测试框架的相关功能。
**系统能力:** SystemCapability.Ability.AbilityRuntime.Core
......@@ -43,15 +44,29 @@ getAbilityDelegator(): AbilityDelegator
**示例:**
```ts
import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry';
var abilityDelegator;
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
let want = {
bundleName: "com.ohos.example",
abilityName: "MainAbility"
}
abilityDelegator.startAbility(want, (err)=>{
if (err.code != 0) {
console.log("Success start ability.");
} else {
console.log("Failed start ability, error: " + JSON.stringify(err));
}
})
```
## AbilityDelegatorRegistry.getArguments
getArguments(): AbilityDelegatorArgs
获取单元测试参数AbilityDelegatorArgs对象
获取单元测试参数[AbilityDelegatorArgs](js-apis-inner-application-abilityDelegatorArgs.md)对象。
**系统能力:** SystemCapability.Ability.AbilityRuntime.Core
......@@ -64,8 +79,11 @@ getArguments(): AbilityDelegatorArgs
**示例:**
```ts
import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry';
var args = AbilityDelegatorRegistry.getArguments();
console.info("getArguments bundleName:" + args.bundleName);
console.info("getArguments parameters:" + JSON.stringify(args.parameters));
console.info("getArguments testCaseNames:" + args.testCaseNames);
console.info("getArguments testRunnerClassName:" + args.testRunnerClassName);
```
# @ohos.app.ability.abilityLifecycleCallback (AbilityLifecycleCallback)
AbilityLifecycleCallback模块提供应用上下文ApplicationContext的生命周期监听方法的回调类的能力,包括onAbilityCreate、onWindowStageCreate、onWindowStageDestroy等方法。
AbilityLifecycleCallback模块提供应用上下文[ApplicationContext](js-apis-inner-application-applicationContext.md)的生命周期发生变化时触发相应回调的能力,包括[onAbilityCreate](#abilitylifecyclecallbackonabilitycreate)[onWindowStageCreate](#abilitylifecyclecallbackonwindowstagecreate)[onWindowStageActive](#abilitylifecyclecallbackonwindowstageactive)[onWindowStageInactive](#abilitylifecyclecallbackonwindowstageinactive)[onWindowStageDestroy](#abilitylifecyclecallbackonwindowstagedestroy)[onAbilityDestroy](#abilitylifecyclecallbackonabilitydestroy)[onAbilityForeground](#abilitylifecyclecallbackonabilityforeground)[onAbilityBackground](#abilitylifecyclecallbackonabilitybackground)[onAbilityContinue](#abilitylifecyclecallbackonabilitycontinue)方法。
> **说明:**
>
......@@ -27,7 +27,7 @@ onAbilityCreate(ability: UIAbility): void;
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| ability | [UIAbility](js-apis-app-ability-uiAbility.md#Ability) | 是 | 当前Ability对象 |
| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | 是 | 当前Ability对象 |
## AbilityLifecycleCallback.onWindowStageCreate
......@@ -42,7 +42,7 @@ onWindowStageCreate(ability: UIAbility, windowStage: window.WindowStage): void;
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| ability | [UIAbility](js-apis-app-ability-uiAbility.md#Ability) | 是 | 当前Ability对象 |
| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | 是 | 当前Ability对象 |
| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | 是 | 当前WindowStage对象 |
......@@ -58,7 +58,7 @@ onWindowStageActive(ability: UIAbility, windowStage: window.WindowStage): void;
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| ability | [UIAbility](js-apis-app-ability-uiAbility.md#Ability) | 是 | 当前Ability对象 |
| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | 是 | 当前Ability对象 |
| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | 是 | 当前WindowStage对象 |
......@@ -74,7 +74,7 @@ onWindowStageInactive(ability: UIAbility, windowStage: window.WindowStage): void
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| ability | [UIAbility](js-apis-app-ability-uiAbility.md#Ability) | 是 | 当前Ability对象 |
| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | 是 | 当前Ability对象 |
| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | 是 | 当前WindowStage对象 |
......@@ -90,7 +90,7 @@ onWindowStageDestroy(ability: UIAbility, windowStage: window.WindowStage): void;
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| ability | [UIAbility](js-apis-app-ability-uiAbility.md#Ability) | 是 | 当前Ability对象 |
| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | 是 | 当前Ability对象 |
| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | 是 | 当前WindowStage对象 |
......@@ -106,7 +106,7 @@ onAbilityDestroy(ability: UIAbility): void;
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| ability | [UIAbility](js-apis-app-ability-uiAbility.md#Ability) | 是 | 当前Ability对象 |
| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | 是 | 当前Ability对象 |
## AbilityLifecycleCallback.onAbilityForeground
......@@ -121,7 +121,7 @@ onAbilityForeground(ability: UIAbility): void;
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| ability | [UIAbility](js-apis-app-ability-uiAbility.md#Ability) | 是 | 当前Ability对象 |
| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | 是 | 当前Ability对象 |
## AbilityLifecycleCallback.onAbilityBackground
......@@ -136,7 +136,7 @@ onAbilityBackground(ability: UIAbility): void;
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| ability | [UIAbility](js-apis-app-ability-uiAbility.md#Ability) | 是 | 当前Ability对象 |
| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | 是 | 当前Ability对象 |
## AbilityLifecycleCallback.onAbilityContinue
......@@ -151,61 +151,77 @@ onAbilityContinue(ability: UIAbility): void;
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| ability | [UIAbility](js-apis-app-ability-uiAbility.md#Ability) | 是 | 当前Ability对象 |
| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | 是 | 当前Ability对象 |
**示例:**
```ts
import UIAbility from "@ohos.app.ability.UIAbility";
export default class MyAbility extends UIAbility {
onCreate() {
console.log("MyAbility onCreate")
let AbilityLifecycleCallback = {
onAbilityCreate(ability){
console.log("AbilityLifecycleCallback onAbilityCreate ability:" + JSON.stringify(ability));
},
onWindowStageCreate(ability, windowStage){
console.log("AbilityLifecycleCallback onWindowStageCreate ability:" + JSON.stringify(ability));
console.log("AbilityLifecycleCallback onWindowStageCreate windowStage:" + JSON.stringify(windowStage));
},
onWindowStageActive(ability, windowStage){
console.log("AbilityLifecycleCallback onWindowStageActive ability:" + JSON.stringify(ability));
console.log("AbilityLifecycleCallback onWindowStageActive windowStage:" + JSON.stringify(windowStage));
},
onWindowStageInactive(ability, windowStage){
console.log("AbilityLifecycleCallback onWindowStageInactive ability:" + JSON.stringify(ability));
console.log("AbilityLifecycleCallback onWindowStageInactive windowStage:" + JSON.stringify(windowStage));
},
onWindowStageDestroy(ability, windowStage){
console.log("AbilityLifecycleCallback onWindowStageDestroy ability:" + JSON.stringify(ability));
console.log("AbilityLifecycleCallback onWindowStageDestroy windowStage:" + JSON.stringify(windowStage));
},
onAbilityDestroy(ability){
console.log("AbilityLifecycleCallback onAbilityDestroy ability:" + JSON.stringify(ability));
},
onAbilityForeground(ability){
console.log("AbilityLifecycleCallback onAbilityForeground ability:" + JSON.stringify(ability));
},
onAbilityBackground(ability){
console.log("AbilityLifecycleCallback onAbilityBackground ability:" + JSON.stringify(ability));
},
onAbilityContinue(ability){
console.log("AbilityLifecycleCallback onAbilityContinue ability:" + JSON.stringify(ability));
}
}
// 1.通过context属性获取applicationContext
let applicationContext = this.context.getApplicationContext();
// 2.通过applicationContext注册监听应用内生命周期
let lifecycleid = applicationContext.on("abilityLifecycle", AbilityLifecycleCallback);
console.log("registerAbilityLifecycleCallback number: " + JSON.stringify(lifecycleid));
},
onDestroy() {
let applicationContext = this.context.getApplicationContext();
applicationContext.off("abilityLifecycle", lifecycleid, (error, data) => {
console.log("unregisterAbilityLifecycleCallback success, err: " + JSON.stringify(error));
});
}
}
```
\ No newline at end of file
MyAbilityStage.ts
```ts
import AbilityLifecycleCallback from "@ohos.app.ability.AbilityLifecycleCallback";
import AbilityStage from "@ohos.app.ability.AbilityStage"
// 声明ability生命周期回调
let abilityLifecycleCallback = {
onAbilityCreate(ability){
console.log("AbilityLifecycleCallback onAbilityCreate.");
},
onWindowStageCreate(ability, windowStage){
console.log("AbilityLifecycleCallback onWindowStageCreate.");
},
onWindowStageActive(ability, windowStage){
console.log("AbilityLifecycleCallback onWindowStageActive.");
},
onWindowStageInactive(ability, windowStage){
console.log("AbilityLifecycleCallback onWindowStageInactive.");
},
onWindowStageDestroy(ability, windowStage){
console.log("AbilityLifecycleCallback onWindowStageDestroy.");
},
onAbilityDestroy(ability){
console.log("AbilityLifecycleCallback onAbilityDestroy.");
},
onAbilityForeground(ability){
console.log("AbilityLifecycleCallback onAbilityForeground.");
},
onAbilityBackground(ability){
console.log("AbilityLifecycleCallback onAbilityBackground.");
},
onAbilityContinue(ability){
console.log("AbilityLifecycleCallback onAbilityContinue.");
}
}
export default class MyAbilityStage extends AbilityStage {
onCreate() {
console.log("MyAbilityStage onCreate");
// 1.通过context属性获取applicationContext
let applicationContext = this.context.getApplicationContext();
// 2.通过applicationContext注册监听应用内生命周期
try {
globalThis.lifecycleId = applicationContext.on("abilityLifecycle", abilityLifecycleCallback);
console.log("registerAbilityLifecycleCallback number: " + JSON.stringify(lifecycleId));
} catch (paramError) {
console.log("error: " + paramError.code + " ," + paramError.message);
}
}
}
```
MyAbility.ts
```ts
import UIAbility from "ohos.app.ability.UIAbility"
export default class MyAbility extends UIAbility {
onDestroy() {
let applicationContext = this.context.getApplicationContext();
// 3.通过applicationContext注销监听应用内生命周期
applicationContext.off("abilityLifecycle", globalThis.lifecycleId, (error) => {
if (error.code != 0) {
console.log("unregisterAbilityLifecycleCallback failed, error: " + JSON.stringify(error));
} else {
console.log("unregisterAbilityLifecycleCallback success.");
}
});
}
}
```
\ No newline at end of file
# @ohos.app.ability.abilityManager (AbilityManager)
AbilityManager模块提供对Ability相关信息和状态信息进行获取、新增、修改等能力。
AbilityManager模块提供获取、新增、修改Ability相关信息和状态信息进行的能力。
> **说明:**
>
......@@ -15,25 +15,25 @@ import abilityManager from '@ohos.app.ability.abilityManager'
## AbilityState
Ability的状态信息
Ability的状态,该类型为枚举,可配合[AbilityRunningInfo](js-apis-inner-application-abilityRunningInfo.md)返回Abiltiy的状态
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core
**系统API**: 此接口为系统接口,三方应用不支持调用。
**系统API**: 此枚举类型为系统接口内部定义,三方应用不支持调用。
| 名称 | 值 | 说明 |
| -------- | -------- | -------- |
| INITIAL | 0 | 表示ability为initial状态。|
| FOREGROUND | 9 | 表示ability为foreground状态。 |
| BACKGROUND | 10 | 表示ability为background状态。 |
| FOREGROUNDING | 11 | 表示ability为foregrounding状态。 |
| BACKGROUNDING | 12 | 表示ability为backgrounding状态。 |
| INITIAL | 0 | 表示ability为初始化状态。|
| FOREGROUND | 9 | 表示ability为前台状态。 |
| BACKGROUND | 10 | 表示ability为后台状态。 |
| FOREGROUNDING | 11 | 表示ability为前台调度中状态。 |
| BACKGROUNDING | 12 | 表示ability为后台调度中状态。 |
## updateConfiguration
updateConfiguration(config: Configuration, callback: AsyncCallback\<void>): void
通过修改配置来更新配置(callback形式)。
通过传入修改的配置项来更新配置(callback形式)。
**需要权限**: ohos.permission.UPDATE_CONFIGURATION
......@@ -43,23 +43,32 @@ updateConfiguration(config: Configuration, callback: AsyncCallback\<void>): void
| 参数名 | 类型 | 必填 | 说明 |
| --------- | ---------------------------------------- | ---- | -------------- |
| config | [Configuration](js-apis-app-ability-configuration.md) | 是 | 新的配置项。 |
| callback | AsyncCallback\<void> | 是 | 被指定的回调方法。 |
| config | [Configuration](js-apis-app-ability-configuration.md) | 是 | 新的配置项,仅需配置需要更新的项。 |
| callback | AsyncCallback\<void> | 是 | 以回调方式返回接口运行结果,可进行错误处理或其他自定义处理。 |
**示例**
```ts
var config = {
language: 'chinese'
language: 'Zh-Hans',
colorMode: COLOR_MODE_LIGHT,
direction: DIRECTION_VERTICAL,
screenDensity: SCREEN_DENSITY_SDPI,
displayId: 1,
hasPointerDevice: true,
}
try {
abilityManager.updateConfiguration(config, () => {
console.log('------------ updateConfiguration -----------');
})
abilityManager.updateConfiguration(config, (err) => {
if (err.code != 0) {
console.log("updateConfiguration fail, err: " + JSON.stringify(err));
} else {
console.log("updateConfiguration success.");
}
})
} catch (paramError) {
console.log('error.code: ' + JSON.stringify(paramError.code) +
' error.message: ' + JSON.stringify(paramError.message));
console.log('error.code: ' + JSON.stringify(paramError.code) +
' error.message: ' + JSON.stringify(paramError.message));
}
```
......@@ -77,30 +86,35 @@ updateConfiguration(config: Configuration): Promise\<void>
| 参数名 | 类型 | 必填 | 说明 |
| --------- | ---------------------------------------- | ---- | -------------- |
| config | [Configuration](js-apis-app-ability-configuration.md) | 是 | 新的配置项。 |
| config | [Configuration](js-apis-app-ability-configuration.md) | 是 | 新的配置项,仅需配置需要更新的项。 |
**返回值:**
| 类型 | 说明 |
| ---------------------------------------- | ------- |
| Promise\<void> | 返回执行结果。 |
| Promise\<void> | 以Promise方式返回接口运行结果息,可进行错误处理或其他自定义处理。 |
**示例**
```ts
var config = {
language: 'chinese'
language: 'Zh-Hans',
colorMode: COLOR_MODE_LIGHT,
direction: DIRECTION_VERTICAL,
screenDensity: SCREEN_DENSITY_SDPI,
displayId: 1,
hasPointerDevice: true,
}
try {
abilityManager.updateConfiguration(config).then(() => {
console.log('updateConfiguration success');
}).catch((err) => {
console.log('updateConfiguration fail');
})
abilityManager.updateConfiguration(config).then(() => {
console.log('updateConfiguration success.');
}).catch((err) => {
console.log('updateConfiguration fail, err: ' + JSON.stringify(err));
})
} catch (paramError) {
console.log('error.code: ' + JSON.stringify(paramError.code) +
' error.message: ' + JSON.stringify(paramError.message));
console.log('error.code: ' + JSON.stringify(paramError.code) +
' error.message: ' + JSON.stringify(paramError.message));
}
```
......@@ -118,18 +132,22 @@ getAbilityRunningInfos(callback: AsyncCallback\<Array\<AbilityRunningInfo>>): vo
| 参数名 | 类型 | 必填 | 说明 |
| --------- | ---------------------------------------- | ---- | -------------- |
| callback | AsyncCallback\<Array\<[AbilityRunningInfo](js-apis-inner-application-abilityRunningInfo.md)>> | 是 | 被指定的回调方法。 |
| callback | AsyncCallback\<Array\<[AbilityRunningInfo](js-apis-inner-application-abilityRunningInfo.md)>> | 是 | 以回调方式返回接口运行结果及运行中的ability信息,可进行错误处理或其他自定义处理。 |
**示例**
```ts
try {
abilityManager.getAbilityRunningInfos((err,data) => {
console.log("getAbilityRunningInfos err: " + err + " data: " + JSON.stringify(data));
});
abilityManager.getAbilityRunningInfos((err,data) => {
if (err.code != 0) {
console.log("getAbilityRunningInfos fail, error: " + JSON.stringify(err));
} else {
console.log("getAbilityRunningInfos success, data: " + JSON.stringify(data));
}
});
} catch (paramError) {
console.log('error.code: ' + JSON.stringify(paramError.code) +
' error.message: ' + JSON.stringify(paramError.message));
console.log('error.code: ' + JSON.stringify(paramError.code) +
' error.message: ' + JSON.stringify(paramError.message));
}
```
......@@ -147,20 +165,20 @@ getAbilityRunningInfos(): Promise\<Array\<AbilityRunningInfo>>
| 类型 | 说明 |
| ---------------------------------------- | ------- |
| Promise\<Array\<[AbilityRunningInfo](js-apis-inner-application-abilityRunningInfo.md)>> | 返回执行结果。 |
| Promise\<Array\<[AbilityRunningInfo](js-apis-inner-application-abilityRunningInfo.md)>> | 以Promise方式返回接口运行结果及运行中的ability信息,可进行错误处理或其他自定义处理。 |
**示例**
```ts
try {
abilityManager.getAbilityRunningInfos().then((data) => {
console.log("getAbilityRunningInfos data: " + JSON.stringify(data))
}).catch((err) => {
console.log("getAbilityRunningInfos err: " + err)
});
abilityManager.getAbilityRunningInfos().then((data) => {
console.log("getAbilityRunningInfos success, data: " + JSON.stringify(data))
}).catch((err) => {
console.log("getAbilityRunningInfos fail, err: " + JSON.stringify(err));
});
} catch (paramError) {
console.log('error.code: ' + JSON.stringify(paramError.code) +
' error.message: ' + JSON.stringify(paramError.message));
console.log('error.code: ' + JSON.stringify(paramError.code) +
' error.message: ' + JSON.stringify(paramError.message));
}
```
......@@ -179,7 +197,7 @@ getExtensionRunningInfos(upperLimit: number, callback: AsyncCallback\<Array\<Ext
| 参数名 | 类型 | 必填 | 说明 |
| --------- | ---------------------------------------- | ---- | -------------- |
| upperLimit | number | 是 | 获取消息数量的最大限制。 |
| callback | AsyncCallback\<Array\<[ExtensionRunningInfo](js-apis-inner-application-extensionRunningInfo.md)>> | 是 | 被指定的回调方法。 |
| callback | AsyncCallback\<Array\<[ExtensionRunningInfo](js-apis-inner-application-extensionRunningInfo.md)>> | 是 | 以回调方式返回接口运行结果及运行中的extension信息,可进行错误处理或其他自定义处理。 |
**示例**
......@@ -187,12 +205,16 @@ getExtensionRunningInfos(upperLimit: number, callback: AsyncCallback\<Array\<Ext
var upperLimit = 0;
try {
abilityManager.getExtensionRunningInfos(upperLimit, (err,data) => {
console.log("getExtensionRunningInfos err: " + err + " data: " + JSON.stringify(data));
});
abilityManager.getExtensionRunningInfos(upperLimit, (err,data) => {
if (err.code != 0) {
console.log("getExtensionRunningInfos fail, err: " + JSON.stringify(err));
} else {
console.log("getExtensionRunningInfos success, data: " + JSON.stringify(data));
}
});
} catch (paramError) {
console.log('error.code: ' + JSON.stringify(paramError.code) +
' error.message: ' + JSON.stringify(paramError.message));
console.log('error.code: ' + JSON.stringify(paramError.code) +
' error.message: ' + JSON.stringify(paramError.message));
}
```
......@@ -216,7 +238,7 @@ getExtensionRunningInfos(upperLimit: number): Promise\<Array\<ExtensionRunningIn
| 类型 | 说明 |
| ---------------------------------------- | ------- |
| Promise\<Array\<[ExtensionRunningInfo](js-apis-inner-application-extensionRunningInfo.md)>> | 返回执行结果。 |
| Promise\<Array\<[ExtensionRunningInfo](js-apis-inner-application-extensionRunningInfo.md)>> | 以Promise方式返回接口运行结果及运行中的extension信息,可进行错误处理或其他自定义处理。 |
**示例**
......@@ -224,14 +246,14 @@ getExtensionRunningInfos(upperLimit: number): Promise\<Array\<ExtensionRunningIn
var upperLimit = 0;
try {
abilityManager.getExtensionRunningInfos(upperLimit).then((data) => {
console.log("getAbilityRunningInfos data: " + JSON.stringify(data));
}).catch((err) => {
console.log("getAbilityRunningInfos err: " + err);
})
abilityManager.getExtensionRunningInfos(upperLimit).then((data) => {
console.log("getExtensionRunningInfos success, data: " + JSON.stringify(data));
}).catch((err) => {
console.log("getExtensionRunningInfos fail, err: " + JSON.stringify(err));
})
} catch (paramError) {
console.log('error.code: ' + JSON.stringify(paramError.code) +
' error.message: ' + JSON.stringify(paramError.message));
console.log('error.code: ' + JSON.stringify(paramError.code) +
' error.message: ' + JSON.stringify(paramError.message));
}
```
......@@ -247,13 +269,17 @@ getTopAbility(callback: AsyncCallback\<ElementName>): void;
| 参数名 | 类型 | 必填 | 说明 |
| --------- | ---------------------------------------- | ---- | -------------- |
| callback | AsyncCallback\<[ElementName](js-apis-bundleManager-elementName.md)> | 是 | 被指定的回调方法。 |
| callback | AsyncCallback\<[ElementName](js-apis-bundleManager-elementName.md)> | 是 | 以回调方式返回接口运行结果及应用名,可进行错误处理或其他自定义处理。 |
**示例**
```ts
abilityManager.getTopAbility((err,data) => {
console.log("getTopAbility err: " + err + " data: " + JSON.stringify(data));
if (err.code != 0) {
console.log("getTopAbility fail, err: " + JSON.stringify(err));
} else {
console.log("getTopAbility success, data: " + JSON.stringify(data));
}
});
```
......@@ -269,14 +295,14 @@ getTopAbility(): Promise\<ElementName>;
| 类型 | 说明 |
| ---------------------------------------- | ------- |
| Promise\<[ElementName](js-apis-bundleManager-elementName.md)>| 返回执行结果。 |
| Promise\<[ElementName](js-apis-bundleManager-elementName.md)>| 以Promise方式返回接口运行结果及应用名,可进行错误处理或其他自定义处理。 |
**示例**
```ts
abilityManager.getTopAbility().then((data) => {
console.log("getTopAbility data: " + JSON.stringify(data));
console.log("getTopAbility success, data: " + JSON.stringify(data));
}).catch((err) => {
console.log("getTopAbility err: " + err);
console.log("getTopAbility fail, err: " + JSON.stringify(err));
})
```
\ No newline at end of file
......@@ -25,13 +25,13 @@ onCreate(): void
**示例:**
```ts
class MyAbilityStage extends AbilityStage {
onCreate() {
console.log("MyAbilityStage.onCreate is called")
}
}
```
```ts
class MyAbilityStage extends AbilityStage {
onCreate() {
console.log("MyAbilityStage.onCreate is called");
}
}
```
## AbilityStage.onAcceptWant
......@@ -56,14 +56,14 @@ onAcceptWant(want: Want): string;
**示例:**
```ts
class MyAbilityStage extends AbilityStage {
onAcceptWant(want) {
console.log("MyAbilityStage.onAcceptWant called");
return "com.example.test";
}
}
```
```ts
class MyAbilityStage extends AbilityStage {
onAcceptWant(want) {
console.log("MyAbilityStage.onAcceptWant called");
return "com.example.test";
}
}
```
## AbilityStage.onConfigurationUpdate
......@@ -82,13 +82,13 @@ onConfigurationUpdate(newConfig: Configuration): void;
**示例:**
```ts
class MyAbilityStage extends AbilityStage {
onConfigurationUpdate(config) {
console.log('onConfigurationUpdate, language:' + config.language);
}
}
```
```ts
class MyAbilityStage extends AbilityStage {
onConfigurationUpdate(config) {
console.log('onConfigurationUpdate, language:' + config.language);
}
}
```
## AbilityStage.onMemoryLevel
......@@ -106,22 +106,22 @@ onMemoryLevel(level: AbilityConstant.MemoryLevel): void;
**示例:**
```ts
class MyAbilityStage extends AbilityStage {
```ts
class MyAbilityStage extends AbilityStage {
onMemoryLevel(level) {
console.log('onMemoryLevel, level:' + JSON.stringify(level));
}
}
```
}
```
## AbilityStage.context
context: AbilityStageContext;
指示有关上下文的配置信息
指示AbilityStage的上下文
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
| 属性名 | 类型 | 说明 |
| ----------- | --------------------------- | ------------------------------------------------------------ |
| context | [AbilityStageContext](js-apis-inner-application-abilityStageContext.md) | 在启动能力阶段进行初始化时回调。 |
| context | [AbilityStageContext](js-apis-inner-application-abilityStageContext.md) | 在Ability启动阶段进行初始化时回调,获取到该Ability的context值。 |
......@@ -20,20 +20,23 @@ static isRunningInStabilityTest(callback: AsyncCallback&lt;boolean&gt;): void
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
**参数:**
**返回值:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;boolean&gt; | 是 | 返回当前是否处于稳定性测试场景。 |
| 类型| 说明 |
| -------- | -------- |
|AsyncCallback&lt;boolean&gt; |以回调方式返回接口运行结果及当前是否处于稳定性测试场景,可进行错误处理或其他自定义处理。true: 处于稳定性测试场景,false:处于非稳定性测试场景。 |
**示例:**
```ts
appManager.isRunningInStabilityTest((err, flag) => {
console.log('error:' + JSON.stringify(err));
console.log('The result of isRunningInStabilityTest is:' + JSON.stringify(flag));
})
```
```ts
appManager.isRunningInStabilityTest((err, flag) => {
if (err.code != 0) {
conseole.log("isRunningInStabilityTest faile, err: " + JSON.stringify(err));
} else {
console.log("The result of isRunningInStabilityTest is:" + JSON.stringify(flag));
}
})
```
## appManager.isRunningInStabilityTest
......@@ -48,17 +51,17 @@ static isRunningInStabilityTest(): Promise&lt;boolean&gt;
| 类型 | 说明 |
| -------- | -------- |
| Promise&lt;boolean&gt; | 返回当前是否处于稳定性测试场景。 |
| Promise&lt;boolean&gt; | 以Promise方式返回接口运行结果及当前是否处于稳定性测试场景,可进行错误处理或其他自定义处理。true: 处于稳定性测试场景,false:处于非稳定性测试场景。 |
**示例:**
```ts
appManager.isRunningInStabilityTest().then((flag) => {
console.log('The result of isRunningInStabilityTest is:' + JSON.stringify(flag));
}).catch((error) => {
console.log('error:' + JSON.stringify(error));
});
```
```ts
appManager.isRunningInStabilityTest().then((flag) => {
console.log("The result of isRunningInStabilityTest is:" + JSON.stringify(flag));
}).catch((error) => {
console.log("error:" + JSON.stringify(error));
});
```
## appManager.isRamConstrainedDevice
......@@ -73,17 +76,17 @@ isRamConstrainedDevice(): Promise\<boolean>;
| 类型 | 说明 |
| -------- | -------- |
| Promise&lt;boolean&gt; | 是否为ram受限设备。 |
| Promise&lt;boolean&gt; | 以Promise方式返回接口运行结果及当前设备是否为ram受限设备,可进行错误处理或其他自定义处理。true:当前设备为ram受限设备,false:当前设备为非ram受限设备。 |
**示例:**
```ts
appManager.isRamConstrainedDevice().then((data) => {
console.log('The result of isRamConstrainedDevice is:' + JSON.stringify(data));
}).catch((error) => {
console.log('error:' + JSON.stringify(error));
});
```
```ts
appManager.isRamConstrainedDevice().then((data) => {
console.log("The result of isRamConstrainedDevice is:" + JSON.stringify(data));
}).catch((error) => {
console.log("error:" + JSON.stringify(error));
});
```
## appManager.isRamConstrainedDevice
......@@ -93,20 +96,23 @@ isRamConstrainedDevice(callback: AsyncCallback\<boolean>): void;
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
**参数:**
**返回值:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;boolean&gt; | 是 | 返回当前是否是ram受限设备。 |
| 类型 | 说明 |
| -------- | -------- |
| AsyncCallback&lt;boolean&gt; |以回调方式返回接口运行结果及当前设备是否为ram受限设备,可进行错误处理或其他自定义处理。true:当前设备为ram受限设备,false:当前设备为非ram受限设备。 |
**示例:**
```ts
appManager.isRamConstrainedDevice((err, data) => {
console.log('error:' + JSON.stringify(err));
console.log('The result of isRamConstrainedDevice is:' + JSON.stringify(data));
})
```
```ts
appManager.isRamConstrainedDevice((err, data) => {
if (err.code != 0) {
console.log("isRamConstrainedDevice faile, err: " + JSON.stringify(err));
} else {
console.log("The result of isRamConstrainedDevice is:" + JSON.stringify(data));
}
})
```
## appManager.getAppMemorySize
......@@ -120,17 +126,17 @@ getAppMemorySize(): Promise\<number>;
| 类型 | 说明 |
| -------- | -------- |
| Promise&lt;number&gt; | 应用程序内存大小。 |
| Promise&lt;number&gt; | 以Promise方式返回接口运行结果及应用程序内存大小,可进行错误处理或其他自定义处理。 |
**示例:**
```ts
appManager.getAppMemorySize().then((data) => {
console.log('The size of app memory is:' + JSON.stringify(data));
}).catch((error) => {
console.log('error:' + JSON.stringify(error));
});
```
```ts
appManager.getAppMemorySize().then((data) => {
console.log("The size of app memory is:" + JSON.stringify(data));
}).catch((error) => {
console.log("error:" + JSON.stringify(error));
});
```
## appManager.getAppMemorySize
......@@ -140,20 +146,23 @@ getAppMemorySize(callback: AsyncCallback\<number>): void;
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
**参数:**
**返回值:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;number&gt; | 是 | 应用程序内存大小。 |
| 类型 | 说明 |
| -------- | -------- |
|AsyncCallback&lt;number&gt; |以回调方式返回接口运行结果及应用程序内存大小,可进行错误处理或其他自定义处理。 |
**示例:**
```ts
appManager.getAppMemorySize((err, data) => {
console.log('error:' + JSON.stringify(err));
console.log('The size of app memory is:' + JSON.stringify(data));
})
```
```ts
appManager.getAppMemorySize((err, data) => {
if (err.code != 0) {
console.log("getAppMemorySize faile, err: " + JSON.stringify(err));
} else {
console.log("The size of app memory is:" + JSON.stringify(data));
}
})
```
## appManager.getProcessRunningInformation<sup>9+</sup>
......@@ -171,17 +180,17 @@ getProcessRunningInformation(): Promise\<Array\<ProcessRunningInformation>>;
| 类型 | 说明 |
| -------- | -------- |
| Promise\<Array\<[ProcessRunningInformation](js-apis-inner-application-processRunningInformation.md)>> | 获取有关运行进程的信息。 |
| Promise\<Array\<[ProcessRunningInformation](js-apis-inner-application-processRunningInformation.md)>> | 以Promise方式返回接口运行结果及有关运行进程的信息,可进行错误处理或其他自定义处理。 |
**示例:**
```ts
appManager.getProcessRunningInformation().then((data) => {
console.log('The process running infomation is:' + JSON.stringify(data));
}).catch((error) => {
console.log('error:' + JSON.stringify(error));
});
```
```ts
appManager.getProcessRunningInformation().then((data) => {
console.log("The process running information is:" + JSON.stringify(data));
}).catch((error) => {
console.log("error:" + JSON.stringify(error));
});
```
## appManager.getProcessRunningInformation<sup>9+</sup>
......@@ -195,26 +204,29 @@ getProcessRunningInformation(callback: AsyncCallback\<Array\<ProcessRunningInfor
**系统API**: 此接口为系统接口,三方应用不支持调用。
**参数:**
**返回值:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback\<Array\<[ProcessRunningInformation](js-apis-inner-application-processRunningInformation.md)>> | 是 | 获取有关运行进程的信息。 |
| 类型 | 说明 |
| -------- | -------- |
|AsyncCallback\<Array\<[ProcessRunningInformation](js-apis-inner-application-processRunningInformation.md)>> | 以回调方式返回接口运行结果及有关运行进程的信息,可进行错误处理或其他自定义处理。 |
**示例:**
```ts
appManager.getProcessRunningInformation((err, data) => {
console.log('error :' + JSON.stringify(err));
console.log('The process running information is:' + JSON.stringify(data));
})
```
```ts
appManager.getProcessRunningInformation((err, data) => {
if (err.code != 0) {
console.log("getProcessRunningInformation faile, err: " + JSON.stringify(err));
} else {
console.log("The process running information is:" + JSON.stringify(data));
}
})
```
## appManager.on
on(type: "applicationState", observer: ApplicationStateObserver): number;
注册全部应用程序状态观测器。
注册全部应用程序状态观测器。
**需要权限**:ohos.permission.RUNNING_STATE_OBSERVER
......@@ -226,43 +238,48 @@ on(type: "applicationState", observer: ApplicationStateObserver): number;
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| type | string | 是 | 调用接口类型 |
| observer | [ApplicationStateObserver](./js-apis-inner-application-applicationStateObserver.md) | 是 | 返回观察者的数字代码。 |
| type | string | 是 | 调用接口类型,固定填"applicationState"字符串。 |
| observer | [ApplicationStateObserver](./js-apis-inner-application-applicationStateObserver.md) | 是 | 应用状态观测器,用于观测应用的生命周期变化。 |
**返回值:**
| 类型 | 说明 |
| --- | --- |
| number | 已注册观测器的数字代码,可用于off接口取消注册观测器。|
**示例:**
```js
var applicationStateObserver = {
```js
var applicationStateObserver = {
onForegroundApplicationChanged(appStateData) {
console.log('------------ onForegroundApplicationChanged -----------', appStateData);
console.log('------------ onForegroundApplicationChanged -----------' + JSON.stringify(appStateData));
},
onAbilityStateChanged(abilityStateData) {
console.log('------------ onAbilityStateChanged -----------', abilityStateData);
console.log('------------ onAbilityStateChanged -----------' + JSON.stringify(abilityStateData));
},
onProcessCreated(processData) {
console.log('------------ onProcessCreated -----------', processData);
console.log('------------ onProcessCreated -----------' + JSON.stringify(processData));
},
onProcessDied(processData) {
console.log('------------ onProcessDied -----------', processData);
console.log('------------ onProcessDied -----------' + JSON.stringify(processData));
},
onProcessStateChanged(processData) {
console.log('------------ onProcessStateChanged -----------', processData);
console.log('------------ onProcessStateChanged -----------' + JSON.stringify(processData));
}
}
try {
}
try {
const observerCode = appManager.on(applicationStateObserver);
console.log('-------- observerCode: ---------', observerCode);
} catch (paramError) {
console.log('-------- observerCode: ---------' + observerCode);
} catch (paramError) {
console.log('error: ' + paramError.code + ', ' + paramError.message);
}
```
}
```
## appManager.on
on(type: "applicationState", observer: ApplicationStateObserver, bundleNameList: Array\<string>): number;
注册指定应用程序状态观测器。
注册指定应用程序状态观测器。
**需要权限**:ohos.permission.RUNNING_STATE_OBSERVER
......@@ -274,39 +291,45 @@ on(type: "applicationState", observer: ApplicationStateObserver, bundleNameList:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| type | string | 是 | 调用接口类型 |
| observer | [ApplicationStateObserver](./js-apis-inner-application-applicationStateObserver.md) | 是 | 返回观察者的数字代码。 |
| type | string | 是 | 调用接口类型,固定填"applicationState"字符串。 |
| observer | [ApplicationStateObserver](./js-apis-inner-application-applicationStateObserver.md) | 是 | 应用状态观测器,用于观测应用的生命周期变化。 |
| bundleNameList | Array<string> | 是 | 表示需要注册监听的bundleName数组。最大值128。 |
**返回值:**
| 类型 | 说明 |
| --- | --- |
| number | 已注册观测器的数字代码,可用于off接口注销观测器。|
**示例:**
```js
var applicationStateObserver = {
```js
var applicationStateObserver = {
onForegroundApplicationChanged(appStateData) {
console.log('------------ onForegroundApplicationChanged -----------', appStateData);
console.log('------------ onForegroundApplicationChanged -----------' + JSON.stringify(appStateData));
},
onAbilityStateChanged(abilityStateData) {
console.log('------------ onAbilityStateChanged -----------', abilityStateData);
console.log('------------ onAbilityStateChanged -----------' + JSON.stringify(abilityStateData));
},
onProcessCreated(processData) {
console.log('------------ onProcessCreated -----------', processData);
console.log('------------ onProcessCreated -----------' + JSON.stringify(processData));
},
onProcessDied(processData) {
console.log('------------ onProcessDied -----------', processData);
console.log('------------ onProcessDied -----------' + JSON.stringify(processData));
},
onProcessStateChanged(processData) {
console.log('------------ onProcessStateChanged -----------', processData);
console.log('------------ onProcessStateChanged -----------' + JSON.stringify(processData));
}
}
var bundleNameList = ['bundleName1', 'bundleName2'];
try {
}
var bundleNameList = ['bundleName1', 'bundleName2'];
try {
const observerCode = appManager.on("applicationState", applicationStateObserver, bundleNameList);
console.log('-------- observerCode: ---------', observerCode);
} catch (paramError) {
} catch (paramError) {
console.log('error: ' + paramError.code + ', ' + paramError.message);
}
}
```
```
## appManager.off
off(type: "applicationState", observerId: number, callback: AsyncCallback\<void>): void;
......@@ -323,26 +346,28 @@ off(type: "applicationState", observerId: number, callback: AsyncCallback\<void
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| type | string | 是 | 调用接口类型 |
| observerId | number | 是 | 表示观察者的编号代码。 |
| callback | AsyncCallback\<void> | 是 | 表示指定的回调方法。 |
| type | string | 是 | 调用接口类型,固定填"applicationState"字符串。 |
| observerId | number | 是 | 表示观测器的编号代码。 |
| callback | AsyncCallback\<void> | 是 | 以回调方式返回接口运行结果,可进行错误处理或其他自定义处理。 |
**示例:**
```js
var observerId = 100;
```ts
var observerId = 100;
function unregisterApplicationStateObserverCallback(err) {
if (err) {
console.log('------------ unregisterApplicationStateObserverCallback ------------', err);
}
}
try {
appManager.off(observerId, unregisterApplicationStateObserverCallback);
} catch (paramError) {
console.log('error: ' + paramError.code + ', ' + paramError.message);
function unregisterApplicationStateObserverCallback(err) {
if (err.code != 0) {
console.log("unregisterApplicationStateObserverCallback faile, err: " + JSON.stringify(err));
} else {
console.log("unregisterApplicationStateObserverCallback success.");
}
```
}
try {
appManager.off(observerId, unregisterApplicationStateObserverCallback);
} catch (paramError) {
console.log('error: ' + paramError.code + ', ' + paramError.message);
}
```
## appManager.off
......@@ -360,32 +385,30 @@ off(type: "applicationState", observerId: number): Promise\<void>;
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| type | string | 是 | 调用接口类型 |
| observerId | number | 是 | 表示观察者的编号代码。 |
| type | string | 是 | 调用接口类型,固定填"applicationState"字符串。 |
| observerId | number | 是 | 表示观测器的编号代码。 |
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| Promise\<void> | 返回执行结果。 |
| Promise\<void> | 以Promise方式返回接口运行结果,可进行错误处理或其他自定义处理。 |
**示例:**
```js
var observerId = 100;
```ts
var observerId = 100;
try {
appManager.off(observerId)
.then((data) => {
console.log('----------- unregisterApplicationStateObserver success ----------', data);
})
.catch((err) => {
console.log('----------- unregisterApplicationStateObserver fail ----------', err);
})
} catch (paramError) {
console.log('error: ' + paramError.code + ', ' + paramError.message);
}
```
try {
appManager.off(observerId).then((data) => {
console.log("unregisterApplicationStateObserver success, data: " + JSON.stringify(data));
}).catch((err) => {
console.log("unregisterApplicationStateObserver faile, err: " + JSON.stringify(err));
})
} catch (paramError) {
console.log('error: ' + paramError.code + ', ' + paramError.message);
}
```
## appManager.getForegroundApplications
......@@ -403,63 +426,24 @@ getForegroundApplications(callback: AsyncCallback\<Array\<AppStateData>>): void;
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback\<Array\<[AppStateData](js-apis-inner-application-appStateData.md)>> | 是 | callback形式返回所有当前处于前台的应用信息。 |
| callback | AsyncCallback\<Array\<[AppStateData](js-apis-inner-application-appStateData.md)>> | 是 | 以回调方式返回接口运行结果及应用状态数据数组,可进行错误处理或其他自定义处理。 |
**示例:**
```js
function getForegroundApplicationsCallback(err, data) {
if (err) {
console.log('--------- getForegroundApplicationsCallback fail ---------', err.code + ': ' + err.message);
```ts
function getForegroundApplicationsCallback(err, data) {
if (err.code != 0) {
console.log("getForegroundApplicationsCallback fail, err: " + JSON.stringify(err));
} else {
console.log('--------- getForegroundApplicationsCallback success ---------', data)
console.log("getForegroundApplicationsCallback success, data: " + JSON.stringify(data));
}
}
try {
}
try {
appManager.getForegroundApplications(getForegroundApplicationsCallback);
} catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message);
}
```
unregisterApplicationStateObserver(observerId: number): Promise\<void>;
取消注册应用程序状态观测器。
**需要权限**:ohos.permission.RUNNING_STATE_OBSERVER
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
**系统API**:该接口为系统接口,三方应用不支持调用。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| observerId | number | 是 | 表示观察者的编号代码。 |
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| Promise\<void> | 返回执行结果。 |
**示例:**
```ts
var observerId = 100;
try {
appManager.unregisterApplicationStateObserver(observerId)
.then((data) => {
console.log('----------- unregisterApplicationStateObserver success ----------', data);
})
.catch((err) => {
console.log('----------- unregisterApplicationStateObserver fail ----------', err);
})
} catch (paramError) {
} catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message);
}
```
}
```
## appManager.getForegroundApplications
......@@ -477,24 +461,24 @@ getForegroundApplications(callback: AsyncCallback\<Array\<AppStateData>>): void;
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback\<Array\<[AppStateData](js-apis-inner-application-appStateData.md)>> | 是 | callback形式返回所有当前处于前台的应用信息。 |
| callback | AsyncCallback\<Array\<[AppStateData](js-apis-inner-application-appStateData.md)>> | 是 | 以Promise方式返回接口运行结果及应用状态数据数组,可进行错误处理或其他自定义处理。 |
**示例:**
```ts
function getForegroundApplicationsCallback(err, data) {
if (err) {
console.log('--------- getForegroundApplicationsCallback fail ---------', err);
```ts
function getForegroundApplicationsCallback(err, data) {
if (err.code != 0) {
console.log("getForegroundApplicationsCallback fail, err: " + JSON.stringify(err));
} else {
console.log('--------- getForegroundApplicationsCallback success ---------', data)
console.log("getForegroundApplicationsCallback success, data: " + JSON.stringify(data));
}
}
try {
}
try {
appManager.getForegroundApplications(getForegroundApplicationsCallback);
} catch (paramError) {
} catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message);
}
```
}
```
## appManager.getForegroundApplications
......@@ -512,19 +496,17 @@ getForegroundApplications(): Promise\<Array\<AppStateData>>;
| 类型 | 说明 |
| -------- | -------- |
| Promise\<Array\<[AppStateData](js-apis-inner-application-appStateData.md)>> | Promise形式返回所有当前处于前台的应用信息。 |
| Promise\<Array\<[AppStateData](js-apis-inner-application-appStateData.md)>> | 返回前台进程应用程序的数组。 |
**示例:**
```ts
appManager.getForegroundApplications()
.then((data) => {
console.log('--------- getForegroundApplications success -------', data);
})
.catch((err) => {
console.log('--------- getForegroundApplications fail -------', err);
})
```
```ts
appManager.getForegroundApplications().then((data) => {
console.log("getForegroundApplications success, data: " + JSON.stringify(data));
}).catch((err) => {
console.log("getForegroundApplications fail, err: " + JSON.stringify(err));
})
```
## appManager.killProcessWithAccount
......@@ -532,7 +514,7 @@ killProcessWithAccount(bundleName: string, accountId: number): Promise\<void\>
切断account进程(Promise形式)。
**需要权限**:ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS, ohos.permission.CLEAN_BACKGROUND_PROCESSES
**需要权限**:ohos.permission.CLEAN_BACKGROUND_PROCESSES,ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS,当accountId为当前用户时,不需要校验ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS权限。
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
......@@ -551,15 +533,13 @@ killProcessWithAccount(bundleName: string, accountId: number): Promise\<void\>
var bundleName = 'bundleName';
var accountId = 0;
try {
appManager.killProcessWithAccount(bundleName, accountId)
.then((data) => {
console.log('------------ killProcessWithAccount success ------------', data);
})
.catch((err) => {
console.log('------------ killProcessWithAccount fail ------------', err);
})
appManager.killProcessWithAccount(bundleName, accountId).then(() => {
console.log("killProcessWithAccount success");
}).catch((err) => {
console.log("killProcessWithAccount fail, err: " + JSON.stringify(err));
})
} catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message);
console.log("error: " + paramError.code + ", " + paramError.message);
}
```
......@@ -574,15 +554,15 @@ killProcessWithAccount(bundleName: string, accountId: number, callback: AsyncCal
**系统API**: 此接口为系统接口,三方应用不支持调用。
**需要权限**:ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS, ohos.permission.CLEAN_BACKGROUND_PROCESSES
**需要权限**:ohos.permission.CLEAN_BACKGROUND_PROCESSES,ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS,当accountId为当前用户时,不需要校验ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS权限。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| bundleName | string | 是 | 应用Bundle名称。 |
| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 |
| callback | AsyncCallback\<void\> | 是 | 切断account进程的回调函数。 |
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| bundleName | string | 是 | 应用Bundle名称。 |
| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 |
| callback | AsyncCallback\<void\> | 是 | 以回调方式返回接口运行结果,可进行错误处理或其他自定义处理。 |
**示例:**
......@@ -590,11 +570,11 @@ killProcessWithAccount(bundleName: string, accountId: number, callback: AsyncCal
var bundleName = 'bundleName';
var accountId = 0;
function killProcessWithAccountCallback(err, data) {
if (err) {
console.log('------------- killProcessWithAccountCallback fail, err: --------------', err);
} else {
console.log('------------- killProcessWithAccountCallback success, data: --------------', data);
}
if (err.code != 0) {
console.log("killProcessWithAccountCallback fail, err: " + JSON.stringify(err));
} else {
console.log("killProcessWithAccountCallback success.");
}
}
appManager.killProcessWithAccount(bundleName, accountId, killProcessWithAccountCallback);
```
......@@ -616,25 +596,25 @@ killProcessesByBundleName(bundleName: string, callback: AsyncCallback\<void>);
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| bundleName | string | 是 | 表示Bundle名称。 |
| callback | AsyncCallback\<void> | 是 | 表示指定的回调方法。 |
| callback | AsyncCallback\<void> | 是 | 以回调方式返回接口运行结果,可进行错误处理或其他自定义处理。 |
**示例:**
```ts
var bundleName = 'bundleName';
function killProcessesByBundleNameCallback(err, data) {
if (err) {
console.log('------------- killProcessesByBundleNameCallback fail, err: --------------', err);
```ts
var bundleName = 'bundleName';
function killProcessesByBundleNameCallback(err, data) {
if (err.code != 0) {
console.log("killProcessesByBundleNameCallback fail, err: " + JSON.stringify(err));
} else {
console.log('------------- killProcessesByBundleNameCallback success, data: --------------', data);
console.log("killProcessesByBundleNameCallback success.");
}
}
try {
}
try {
appManager.killProcessesByBundleName(bundleName, killProcessesByBundleNameCallback);
} catch (paramError) {
} catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message);
}
```
}
```
## appManager.killProcessesByBundleName
......@@ -662,20 +642,18 @@ killProcessesByBundleName(bundleName: string): Promise\<void>;
**示例:**
```ts
var bundleName = 'bundleName';
try {
appManager.killProcessesByBundleName(bundleName)
.then((data) => {
console.log('------------ killProcessesByBundleName success ------------', data);
})
.catch((err) => {
console.log('------------ killProcessesByBundleName fail ------------', err);
```ts
var bundleName = 'bundleName';
try {
appManager.killProcessesByBundleName(bundleName).then((data) => {
console.log("killProcessesByBundleName success.");
}).catch((err) => {
console.log("killProcessesByBundleName fail, err: " + JSON.stringify(err));
})
} catch (paramError) {
} catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message);
}
```
}
```
## appManager.clearUpApplicationData
......@@ -694,25 +672,25 @@ clearUpApplicationData(bundleName: string, callback: AsyncCallback\<void>);
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| bundleName | string | 是 | 表示Bundle名称。 |
| callback | AsyncCallback\<void> | 是 | 表示指定的回调方法。 |
| callback | AsyncCallback\<void> | 是 | 以回调方式返回接口运行结果,可进行错误处理或其他自定义处理。 |
**示例:**
```ts
var bundleName = 'bundleName';
function clearUpApplicationDataCallback(err, data) {
```ts
var bundleName = 'bundleName';
function clearUpApplicationDataCallback(err, data) {
if (err) {
console.log('------------- clearUpApplicationDataCallback fail, err: --------------', err);
console.log("clearUpApplicationDataCallback fail, err: " + JSON.stringify(err));
} else {
console.log('------------- clearUpApplicationDataCallback success, data: --------------', data);
console.log("clearUpApplicationDataCallback success.");
}
}
try {
}
try {
appManager.clearUpApplicationData(bundleName, clearUpApplicationDataCallback);
} catch (paramError) {
} catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message);
}
```
}
```
## appManager.clearUpApplicationData
......@@ -736,27 +714,27 @@ clearUpApplicationData(bundleName: string): Promise\<void>;
| 类型 | 说明 |
| -------- | -------- |
| Promise\<void> | 返回执行结果。 |
| Promise\<void> | 以Promise方式返回接口运行结果,可进行错误处理或其他自定义处理。 |
**示例:**
```ts
var bundleName = 'bundleName';
try {
appManager.clearUpApplicationData(bundleName)
.then((data) => {
console.log('------------ clearUpApplicationData success ------------', data);
})
.catch((err) => {
console.log('------------ clearUpApplicationData fail ------------', err);
})
} catch (paramError) {
```ts
var bundleName = 'bundleName';
try {
appManager.clearUpApplicationData(bundleName).then((data) => {
console.log("clearUpApplicationData success.");
}).catch((err) => {
console.log("clearUpApplicationData fail, err: " + JSON.stringify(err));
})
} catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message);
}
```
}
```
## ApplicationState
应用状态,该类型为枚举,可配合[AbilityStateData](js-apis-inner-application-appStateData.md)返回相应的应用状态。
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
**系统API**: 此接口为系统接口,三方应用不支持调用。
......@@ -771,6 +749,8 @@ clearUpApplicationData(bundleName: string): Promise\<void>;
## ProcessState
进程状态,该类型为枚举,可配合[ProcessData](js-apis-inner-application-processData.md)返回相应的进程状态。
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
**系统API**: 此接口为系统接口,三方应用不支持调用。
......
......@@ -14,7 +14,7 @@ import appRecovery from '@ohos.app.ability.appRecovery'
## appRecovery.RestartFlag
[enableAppRecovery](#apprecoveryenableapprecovery)接口重启选项参数
应用重启标志,[enableAppRecovery](#apprecoveryenableapprecovery)接口重启选项参数,该类型为枚举
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core
......@@ -28,7 +28,7 @@ import appRecovery from '@ohos.app.ability.appRecovery'
## appRecovery.SaveOccasionFlag
[enableAppRecovery](#apprecoveryenableapprecovery)接口状态保存时机选项参数
保存条件标志,[enableAppRecovery](#apprecoveryenableapprecovery)接口状态保存时的选项参数,该类型为枚举
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core
......@@ -39,7 +39,7 @@ import appRecovery from '@ohos.app.ability.appRecovery'
## appRecovery.SaveModeFlag
[enableAppRecovery](#apprecoveryenableapprecovery)接口状态保存方式的参数
状态保存标志,[enableAppRecovery](#apprecoveryenableapprecovery)接口状态保存方式的参数,该类型为枚举
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core
......@@ -50,7 +50,7 @@ import appRecovery from '@ohos.app.ability.appRecovery'
## appRecovery.enableAppRecovery
enableAppRecovery(restart?: RestartFlag, saveOccasion?: SaveOccasionFlag, saveMode?: SaveModeFlag) : void;
enableAppRecovery(restart?: [RestartFlag](#apprecoveryrestartflag), saveOccasion?: [SaveOccasionFlag](#apprecoverysaveoccasionflag), saveMode?: [SaveModeFlag](#apprecoverysavemodeflag)) : void;
使能应用恢复功能,参数按顺序填入。
......@@ -60,9 +60,9 @@ enableAppRecovery(restart?: RestartFlag, saveOccasion?: SaveOccasionFlag, saveMo
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| restart | [RestartFlag](#apprecoveryrestartflag) | 否 | 发生对应故障时是否重启,默认为不重启。 |
| saveOccasion | [SaveOccasionFlag](#apprecoverysaveoccasionflag) | 否 | 状态保存时机,默认为故障时保存。 |
| saveMode | [SaveModeFlag](#apprecoverysavemodeflag) | 否 | 状态保存方式, 默认为文件缓存。 |
| restart | [RestartFlag](#apprecoveryrestartflag) | 否 | 枚举类型,发生对应故障时是否重启,默认为不重启。 |
| saveOccasion | [SaveOccasionFlag](#apprecoverysaveoccasionflag) | 否 | 枚举类型,状态保存时机,默认为故障时保存。 |
| saveMode | [SaveModeFlag](#apprecoverysavemodeflag) | 否 | 枚举类型,状态保存方式, 默认为文件缓存。 |
**示例:**
......@@ -94,7 +94,6 @@ var observer = {
appRecovery.restartApp();
}
}
```
## appRecovery.saveAppState
......@@ -109,7 +108,7 @@ saveAppState(): boolean;
| 类型 | 说明 |
| -------- | -------- |
| boolean | 保存成功与否。 |
| boolean | 保存成功与否。true:保存成功,false:保存失败。 |
**示例:**
......
......@@ -482,7 +482,7 @@ killProcessWithAccount(bundleName: string, accountId: number): Promise\<void\>
切断account进程(Promise形式)。
**需要权限**:ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS, ohos.permission.CLEAN_BACKGROUND_PROCESSES
**需要权限**:ohos.permission.CLEAN_BACKGROUND_PROCESSES,ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS,当accountId为当前用户时,不需要校验ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS权限。
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
......@@ -520,7 +520,7 @@ killProcessWithAccount(bundleName: string, accountId: number, callback: AsyncCal
**系统API**: 此接口为系统接口,三方应用不支持调用。
**需要权限**:ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS, ohos.permission.CLEAN_BACKGROUND_PROCESSES
**需要权限**:ohos.permission.CLEAN_BACKGROUND_PROCESSES,ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS,当accountId为当前用户时,不需要校验ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS权限。
**参数:**
......
......@@ -599,7 +599,7 @@ startServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback:
启动一个新的ServiceExtensionAbility(callback形式)。
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS,当accountId为当前用户时,不需要校验该权限。
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
......@@ -666,7 +666,7 @@ startServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\
启动一个新的ServiceExtensionAbility(Promise形式)。
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS,当accountId为当前用户时,不需要校验该权限。
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
......@@ -858,7 +858,7 @@ stopServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback:
使用帐户停止同一应用程序内的服务(callback形式)。
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS,当accountId为当前用户时,不需要校验该权限。
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
......@@ -921,7 +921,7 @@ stopServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\<
使用帐户停止同一应用程序内的服务(Promise形式)。
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS,当accountId为当前用户时,不需要校验该权限。
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
......
......@@ -450,7 +450,7 @@ startAbilityForResultWithAccount(want: Want, accountId: number, callback: AsyncC
启动一个Ability并在该Ability销毁时返回执行结果(callback形式)。
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS,当accountId为当前用户时,不需要校验该权限。
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
......@@ -525,7 +525,7 @@ startAbilityForResultWithAccount(want: Want, accountId: number, options: StartOp
启动一个Ability并在该Ability销毁时返回执行结果(callback形式)。
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS,当accountId为当前用户时,不需要校验该权限。
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
......@@ -604,7 +604,7 @@ startAbilityForResultWithAccount(want: Want, accountId: number, options?: StartO
启动一个Ability并在该Ability销毁时返回执行结果(promise形式)。
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS,当accountId为当前用户时,不需要校验该权限。
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
......@@ -807,7 +807,7 @@ startServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback:
启动一个新的ServiceExtensionAbility(callback形式)。
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS,当accountId为当前用户时,不需要校验该权限。
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
......@@ -869,7 +869,7 @@ startServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\
启动一个新的ServiceExtensionAbility(Promise形式)。
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS,当accountId为当前用户时,不需要校验该权限。
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
......@@ -1048,7 +1048,7 @@ stopServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback:
停止同一应用程序内指定账户的服务(callback形式)。
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS,当accountId为当前用户时,不需要校验该权限。
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
......@@ -1111,7 +1111,7 @@ stopServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\<
停止同一应用程序内指定账户的服务(Promise形式)。
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS,当accountId为当前用户时,不需要校验该权限。
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
......@@ -1450,7 +1450,7 @@ connectServiceExtensionAbilityWithAccount(want: Want, accountId: number, options
将当前Ability连接到一个使用AbilityInfo.AbilityType.SERVICE模板的指定account的Ability。
**需要权限:** ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**需要权限:** ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS,当accountId为当前用户时,不需要校验该权限。
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
......@@ -1710,7 +1710,7 @@ startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\<
根据want和accountId启动Ability(callback形式)。
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS,当accountId为当前用户时,不需要校验该权限。
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
......@@ -1784,7 +1784,7 @@ startAbilityWithAccount(want: Want, accountId: number, options: StartOptions, ca
根据want、accountId及startOptions启动Ability(callback形式)。
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS,当accountId为当前用户时,不需要校验该权限。
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
......@@ -1862,7 +1862,7 @@ startAbilityWithAccount(want: Want, accountId: number, options?: StartOptions):
根据want、accountId和startOptions启动Ability(Promise形式)。
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS,当accountId为当前用户时,不需要校验该权限。
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
......
......@@ -4,10 +4,9 @@
> **说明:**
>
> 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
> - 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
>
> 本模块从API version 9开始支持异常返回功能。
> - 本模块从API version 9开始支持异常返回功能。
## 导入模块
......@@ -15,7 +14,6 @@
import rpc from '@ohos.rpc';
```
## ErrorCode<sup>9+</sup>
从API version 9起,IPC支持异常返回功能。错误码对应数值及含义如下。
......@@ -42,11 +40,11 @@ import rpc from '@ohos.rpc';
## MessageSequence<sup>9+</sup>
在RPC过程中,发送方可以使用MessageSequence提供的写方法,将待发送的数据以特定格式写入该对象。接收方可以使用MessageSequence提供的读方法从该对象中读取特定格式的数据。数据格式包括:基础类型及数组、IPC对象、接口描述符和自定义序列化对象。
在RPC或IPC过程中,发送方可以使用MessageSequence提供的写方法,将待发送的数据以特定格式写入该对象。接收方可以使用MessageSequence提供的读方法从该对象中读取特定格式的数据。数据格式包括:基础类型及数组、IPC对象、接口描述符和自定义序列化对象。
### create
create(): MessageSequence
static create(): MessageSequence
静态方法,创建MessageSequence对象。
......@@ -60,7 +58,7 @@ import rpc from '@ohos.rpc';
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
console.log("RpcClient: data is " + data);
```
......@@ -75,7 +73,7 @@ reclaim(): void
**示例:**
```
```ts
let reply = rpc.MessageSequence.create();
reply.reclaim();
```
......@@ -105,7 +103,7 @@ writeRemoteObject(object: [IRemoteObject](#iremoteobject)): void
**示例:**
```
```ts
class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) {
super(descriptor);
......@@ -146,7 +144,7 @@ readRemoteObject(): IRemoteObject
**示例:**
```
```ts
class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) {
super(descriptor);
......@@ -187,7 +185,7 @@ writeInterfaceToken(token: string): void
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
try {
data.writeInterfaceToken("aaa");
......@@ -201,7 +199,7 @@ writeInterfaceToken(token: string): void
readInterfaceToken(): string
从MessageSequence中读取接口描述符,接口描述符按写入MessageSequence的顺序读取,本地对象可使用该信息检验本次通信。
从MessageSequence对象中读取接口描述符,接口描述符按写入MessageSequence的顺序读取,本地对象可使用该信息检验本次通信。
**系统能力**:SystemCapability.Communication.IPC.Core
......@@ -219,29 +217,28 @@ readInterfaceToken(): string
| ------- | ----- |
| 1900010 | read data from message sequence failed |
**示例:**
```
class Stub extends rpc.RemoteObject {
onRemoteRequest(code, data, reply, option) {
try {
let interfaceToken = data.readInterfaceToken();
console.log("RpcServer: interfaceToken is " + interfaceToken);
} catch(error) {
console.info("RpcServer: read interfaceToken failed, errorCode " + error.code);
console.info("RpcServer: read interfaceToken failed, errorMessage " + error.message);
}
return true;
}
}
```ts
class Stub extends rpc.RemoteObject {
onRemoteRequest(code, data, reply, option) {
try {
let interfaceToken = data.readInterfaceToken();
console.log("RpcServer: interfaceToken is " + interfaceToken);
} catch(error) {
console.info("RpcServer: read interfaceToken failed, errorCode " + error.code);
console.info("RpcServer: read interfaceToken failed, errorMessage " + error.message);
}
return true;
}
}
```
### getSize
getSize(): number
获取当前MessageSequence的数据大小。
获取当前创建的MessageSequence对象的数据大小。
**系统能力**:SystemCapability.Communication.IPC.Core
......@@ -249,11 +246,11 @@ getSize(): number
| 类型 | 说明 |
| ------ | ----------------------------------------------- |
| number | 获取的MessageSequence的数据大小。以字节为单位。 |
| number | 获取的MessageSequence实例的数据大小。以字节为单位。 |
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
let size = data.getSize();
console.log("RpcClient: size is " + size);
......@@ -263,7 +260,7 @@ getSize(): number
getCapacity(): number
获取当前MessageSequence的容量
获取当前MessageSequence对象的容量大小
**系统能力**:SystemCapability.Communication.IPC.Core
......@@ -271,11 +268,11 @@ getCapacity(): number
| 类型 | 说明 |
| ------ | ----- |
| number | 获取的MessageSequence的容量大小。以字节为单位。 |
| number | 获取的MessageSequence实例的容量大小。以字节为单位。 |
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
let result = data.getCapacity();
console.log("RpcClient: capacity is " + result);
......@@ -285,7 +282,7 @@ getCapacity(): number
setSize(size: number): void
设置MessageSequence实例中包含的数据大小。
设置MessageSequence对象中包含的数据大小。
**系统能力**:SystemCapability.Communication.IPC.Core
......@@ -297,7 +294,7 @@ setSize(size: number): void
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
try {
data.setSize(16);
......@@ -312,7 +309,7 @@ setSize(size: number): void
setCapacity(size: number): void
设置MessageSequence实例的存储容量。
设置MessageSequence对象的存储容量。
**系统能力**:SystemCapability.Communication.IPC.Core
......@@ -332,7 +329,7 @@ setCapacity(size: number): void
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
try {
data.setCapacity(100);
......@@ -347,7 +344,7 @@ setCapacity(size: number): void
getWritableBytes(): number
获取MessageSequence的可写字节空间。
获取MessageSequence的可写字节空间大小
**系统能力**:SystemCapability.Communication.IPC.Core
......@@ -355,18 +352,18 @@ getWritableBytes(): number
| 类型 | 说明 |
| ------ | ------ |
| number | 获取到的MessageSequence的可写字节空间。以字节为单位。 |
| number | 获取到的MessageSequence实例的可写字节空间。以字节为单位。 |
**示例:**
```
class Stub extends rpc.RemoteObject {
onRemoteRequest(code, data, reply, option) {
let getWritableBytes = data.getWritableBytes();
console.log("RpcServer: getWritableBytes is " + getWritableBytes);
return true;
}
}
```ts
class Stub extends rpc.RemoteObject {
onRemoteRequest(code, data, reply, option) {
let getWritableBytes = data.getWritableBytes();
console.log("RpcServer: getWritableBytes is " + getWritableBytes);
return true;
}
}
```
### getReadableBytes
......@@ -381,18 +378,18 @@ getReadableBytes(): number
| 类型 | 说明 |
| ------ | ------- |
| number | 获取到的MessageSequence的可读字节空间。以字节为单位。 |
| number | 获取到的MessageSequence实例的可读字节空间。以字节为单位。 |
**示例:**
```
class Stub extends rpc.RemoteObject {
onRemoteRequest(code, data, reply, option) {
let result = data.getReadableBytes();
console.log("RpcServer: getReadableBytes is " + result);
return true;
}
}
```ts
class Stub extends rpc.RemoteObject {
onRemoteRequest(code, data, reply, option) {
let result = data.getReadableBytes();
console.log("RpcServer: getReadableBytes is " + result);
return true;
}
}
```
### getReadPosition
......@@ -411,7 +408,7 @@ getReadPosition(): number
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
let readPos = data.getReadPosition();
console.log("RpcClient: readPos is " + readPos);
......@@ -433,7 +430,7 @@ getWritePosition(): number
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
data.writeInt(10);
let bwPos = data.getWritePosition();
......@@ -456,7 +453,7 @@ rewindRead(pos: number): void
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
data.writeInt(12);
data.writeString("sequence");
......@@ -488,7 +485,7 @@ rewindWrite(pos: number): void
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
data.writeInt(4);
try {
......@@ -526,7 +523,7 @@ writeByte(val: number): void
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
try {
data.writeByte(2);
......@@ -560,7 +557,7 @@ readByte(): number
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
try {
data.writeByte(2);
......@@ -601,7 +598,7 @@ writeShort(val: number): void
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
try {
data.writeShort(8);
......@@ -635,7 +632,7 @@ readShort(): number
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
try {
data.writeShort(8);
......@@ -676,7 +673,7 @@ writeInt(val: number): void
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
try {
data.writeInt(10);
......@@ -710,7 +707,7 @@ readInt(): number
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
try {
data.writeInt(10);
......@@ -751,7 +748,7 @@ writeLong(val: number): void
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
try {
data.writeLong(10000);
......@@ -785,7 +782,7 @@ readLong(): number
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
try {
data.writeLong(10000);
......@@ -826,7 +823,7 @@ writeFloat(val: number): void
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
try {
data.writeFloat(1.2);
......@@ -860,7 +857,7 @@ readFloat(): number
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
try {
data.writeFloat(1.2);
......@@ -901,7 +898,7 @@ writeDouble(val: number): void
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
try {
data.writeDouble(10.2);
......@@ -935,7 +932,7 @@ readDouble(): number
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
try {
data.writeDouble(10.2);
......@@ -976,7 +973,7 @@ writeBoolean(val: boolean): void
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
try {
data.writeBoolean(false);
......@@ -1010,7 +1007,7 @@ readBoolean(): boolean
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
try {
data.writeBoolean(false);
......@@ -1051,7 +1048,7 @@ writeChar(val: number): void
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
try {
data.writeChar(97);
......@@ -1085,7 +1082,7 @@ readChar(): number
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
try {
data.writeChar(97);
......@@ -1126,7 +1123,7 @@ writeString(val: string): void
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
try {
data.writeString('abc');
......@@ -1160,7 +1157,7 @@ readString(): string
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
try {
data.writeString('abc');
......@@ -1201,7 +1198,7 @@ writeParcelable(val: Parcelable): void
**示例:**
```
```ts
class MySequenceable {
num: number;
str: string;
......@@ -1255,7 +1252,7 @@ readParcelable(dataIn: Parcelable): void
**示例:**
```
```ts
class MySequenceable {
num: number;
str: string;
......@@ -1310,7 +1307,7 @@ writeByteArray(byteArray: number[]): void
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
let ByteArrayVar = [1, 2, 3, 4, 5];
try {
......@@ -1345,7 +1342,7 @@ readByteArray(dataIn: number[]): void
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
let ByteArrayVar = [1, 2, 3, 4, 5];
try {
......@@ -1387,7 +1384,7 @@ readByteArray(): number[]
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
let byteArrayVar = [1, 2, 3, 4, 5];
try {
......@@ -1429,7 +1426,7 @@ writeShortArray(shortArray: number[]): void
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
try {
data.writeShortArray([11, 12, 13]);
......@@ -1463,7 +1460,7 @@ readShortArray(dataIn: number[]): void
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
try {
data.writeShortArray([11, 12, 13]);
......@@ -1504,7 +1501,7 @@ readShortArray(): number[]
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
try {
data.writeShortArray([11, 12, 13]);
......@@ -1545,7 +1542,7 @@ writeIntArray(intArray: number[]): void
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
try {
data.writeIntArray([100, 111, 112]);
......@@ -1579,7 +1576,7 @@ readIntArray(dataIn: number[]): void
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
try {
data.writeIntArray([100, 111, 112]);
......@@ -1620,7 +1617,7 @@ readIntArray(): number[]
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
try {
data.writeIntArray([100, 111, 112]);
......@@ -1661,7 +1658,7 @@ writeLongArray(longArray: number[]): void
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
try {
data.writeLongArray([1111, 1112, 1113]);
......@@ -1675,7 +1672,7 @@ writeLongArray(longArray: number[]): void
readLongArray(dataIn: number[]): void
从MessageSequence实例读取长整数数组。
从MessageSequence实例读取长整数数组。
**系统能力**:SystemCapability.Communication.IPC.Core
......@@ -1695,7 +1692,7 @@ readLongArray(dataIn: number[]): void
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
try {
data.writeLongArray([1111, 1112, 1113]);
......@@ -1716,7 +1713,7 @@ readLongArray(dataIn: number[]): void
readLongArray(): number[]
从MessageSequence实例中读取长整数数组。
从MessageSequence实例中读取所有的长整数数组。
**系统能力**:SystemCapability.Communication.IPC.Core
......@@ -1736,7 +1733,7 @@ readLongArray(): number[]
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
try {
data.writeLongArray([1111, 1112, 1113]);
......@@ -1777,7 +1774,7 @@ writeFloatArray(floatArray: number[]): void
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
try {
data.writeFloatArray([1.2, 1.3, 1.4]);
......@@ -1811,7 +1808,7 @@ readFloatArray(dataIn: number[]): void
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
try {
data.writeFloatArray([1.2, 1.3, 1.4]);
......@@ -1852,7 +1849,7 @@ readFloatArray(): number[]
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
try {
data.writeFloatArray([1.2, 1.3, 1.4]);
......@@ -1893,7 +1890,7 @@ writeDoubleArray(doubleArray: number[]): void
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
try {
data.writeDoubleArray([11.1, 12.2, 13.3]);
......@@ -1927,7 +1924,7 @@ readDoubleArray(dataIn: number[]): void
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
try {
data.writeDoubleArray([11.1, 12.2, 13.3]);
......@@ -1948,7 +1945,7 @@ readDoubleArray(dataIn: number[]): void
readDoubleArray(): number[]
从MessageSequence实例读取双精度浮点数组。
从MessageSequence实例读取所有双精度浮点数组。
**系统能力**:SystemCapability.Communication.IPC.Core
......@@ -1968,7 +1965,7 @@ readDoubleArray(): number[]
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
try {
data.writeDoubleArray([11.1, 12.2, 13.3]);
......@@ -2009,7 +2006,7 @@ writeBooleanArray(booleanArray: boolean[]): void
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
try {
data.writeBooleanArray([false, true, false]);
......@@ -2043,7 +2040,7 @@ readBooleanArray(dataIn: boolean[]): void
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
try {
data.writeBooleanArray([false, true, false]);
......@@ -2064,7 +2061,7 @@ readBooleanArray(dataIn: boolean[]): void
readBooleanArray(): boolean[]
从MessageSequence实例中读取布尔数组。
从MessageSequence实例中读取所有布尔数组。
**系统能力**:SystemCapability.Communication.IPC.Core
......@@ -2084,7 +2081,7 @@ readBooleanArray(): boolean[]
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
try {
data.writeBooleanArray([false, true, false]);
......@@ -2125,7 +2122,7 @@ writeCharArray(charArray: number[]): void
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
try {
data.writeCharArray([97, 98, 88]);
......@@ -2159,7 +2156,7 @@ readCharArray(dataIn: number[]): void
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
try {
data.writeCharArray([97, 98, 88]);
......@@ -2200,7 +2197,7 @@ readCharArray(): number[]
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
try {
data.writeCharArray([97, 98, 88]);
......@@ -2242,7 +2239,7 @@ writeStringArray(stringArray: string[]): void
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
try {
data.writeStringArray(["abc", "def"]);
......@@ -2276,7 +2273,7 @@ readStringArray(dataIn: string[]): void
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
try {
data.writeStringArray(["abc", "def"]);
......@@ -2317,7 +2314,7 @@ readStringArray(): string[]
**示例:**
```
```ts
let data = rpc.MessageSequence.create();
try {
data.writeStringArray(["abc", "def"]);
......@@ -2352,7 +2349,7 @@ writeNoException(): void
**示例:**
```
```ts
class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) {
super(descriptor);
......@@ -2394,7 +2391,7 @@ readException(): void
**示例:**
```
```ts
import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
......@@ -2467,7 +2464,7 @@ writeParcelableArray(parcelableArray: Parcelable[]): void
**示例:**
```
```ts
class MyParcelable {
num: number;
str: string;
......@@ -2524,7 +2521,7 @@ readParcelableArray(parcelableArray: Parcelable[]): void
**示例:**
```
```ts
class MyParcelable {
num: number;
str: string;
......@@ -2584,7 +2581,7 @@ writeRemoteObjectArray(objectArray: IRemoteObject[]): void
**示例:**
```
```ts
class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) {
super(descriptor);
......@@ -2631,7 +2628,7 @@ readRemoteObjectArray(objects: IRemoteObject[]): void
**示例:**
```
```ts
class MyDeathRecipient {
onRemoteDied() {
console.log("server died");
......@@ -2684,7 +2681,7 @@ readRemoteObjectArray(): IRemoteObject[]
**示例:**
```
```ts
class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) {
super(descriptor);
......@@ -2712,7 +2709,7 @@ readRemoteObjectArray(): IRemoteObject[]
static closeFileDescriptor(fd: number): void
关闭给定的文件描述符。
静态方法,关闭给定的文件描述符。
**系统能力**:SystemCapability.Communication.IPC.Core
......@@ -2724,7 +2721,7 @@ static closeFileDescriptor(fd: number): void
**示例:**
```
```ts
import fileio from '@ohos.fileio';
let filePath = "path/to/file";
let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666);
......@@ -2740,7 +2737,7 @@ static closeFileDescriptor(fd: number): void
static dupFileDescriptor(fd: number) :number
复制给定的文件描述符。
静态方法,复制给定的文件描述符。
**系统能力**:SystemCapability.Communication.IPC.Core
......@@ -2766,7 +2763,7 @@ static dupFileDescriptor(fd: number) :number
**示例:**
```
```ts
import fileio from '@ohos.fileio';
let filePath = "path/to/file";
let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666);
......@@ -2790,12 +2787,12 @@ containFileDescriptors(): boolean
| 类型 | 说明 |
| ------- | -------------------------------------------------------------------- |
| boolean | 如果此MessageSequence对象包含文件描述符,则返回true;否则返回false。 |
| boolean | true:包含文件描述符,false:不包含文件描述符。|
**示例:**
```
```ts
import fileio from '@ohos.fileio';
let sequence = new rpc.MessageSequence();
let filePath = "path/to/file";
......@@ -2840,7 +2837,7 @@ writeFileDescriptor(fd: number): void
**示例:**
```
```ts
import fileio from '@ohos.fileio';
let sequence = new rpc.MessageSequence();
let filePath = "path/to/file";
......@@ -2853,7 +2850,6 @@ writeFileDescriptor(fd: number): void
}
```
### readFileDescriptor
readFileDescriptor(): number
......@@ -2878,7 +2874,7 @@ readFileDescriptor(): number
**示例:**
```
```ts
import fileio from '@ohos.fileio';
let sequence = new rpc.MessageSequence();
let filePath = "path/to/file";
......@@ -2897,7 +2893,6 @@ readFileDescriptor(): number
}
```
### writeAshmem
writeAshmem(ashmem: Ashmem): void
......@@ -2922,7 +2917,7 @@ writeAshmem(ashmem: Ashmem): void
**示例:**
```
```ts
let sequence = new rpc.MessageSequence();
let ashmem;
try {
......@@ -2964,7 +2959,7 @@ readAshmem(): Ashmem
**示例:**
```
```ts
let sequence = new rpc.MessageSequence();
let ashmem;
try {
......@@ -2988,7 +2983,6 @@ readAshmem(): Ashmem
}
```
### getRawDataCapacity
getRawDataCapacity(): number
......@@ -3005,13 +2999,12 @@ getRawDataCapacity(): number
**示例:**
```
```ts
let sequence = new rpc.MessageSequence();
let result = sequence.getRawDataCapacity();
console.log("RpcTest: sequence get RawDataCapacity result is : " + result);
```
### writeRawData
writeRawData(rawData: number[], size: number): void
......@@ -3037,7 +3030,7 @@ writeRawData(rawData: number[], size: number): void
**示例:**
```
```ts
let sequence = new rpc.MessageSequence();
let arr = [1, 2, 3, 4, 5];
try {
......@@ -3048,7 +3041,6 @@ writeRawData(rawData: number[], size: number): void
}
```
### readRawData
readRawData(size: number): number[]
......@@ -3079,7 +3071,7 @@ readRawData(size: number): number[]
**示例:**
```
```ts
let sequence = new rpc.MessageSequence();
let arr = [1, 2, 3, 4, 5];
try {
......@@ -3105,7 +3097,7 @@ readRawData(size: number): number[]
### create
create(): MessageParcel
static create(): MessageParcel
静态方法,创建MessageParcel对象。
......@@ -3119,7 +3111,7 @@ create(): MessageParcel
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
console.log("RpcClient: data is " + data);
```
......@@ -3134,7 +3126,7 @@ reclaim(): void
**示例:**
```
```ts
let reply = rpc.MessageParcel.create();
reply.reclaim();
```
......@@ -3157,11 +3149,11 @@ writeRemoteObject(object: [IRemoteObject](#iremoteobject)): boolean
| 类型 | 说明 |
| ------- | ----------------------------------------- |
| boolean | 如果操作成功,则返回true;否则返回false。 |
| boolean | true:操作成功,false:操作失败。|
**示例:**
```
```ts
class MyDeathRecipient {
onRemoteDied() {
console.log("server died");
......@@ -3202,7 +3194,7 @@ readRemoteObject(): IRemoteObject
**示例:**
```
```ts
class MyDeathRecipient {
onRemoteDied() {
console.log("server died");
......@@ -3246,11 +3238,11 @@ writeInterfaceToken(token: string): boolean
| 类型 | 说明 |
| ------- | ----------------------------------------- |
| boolean | 如果操作成功,则返回true;否则返回false。 |
| boolean | true:操作成功,false:操作失败。|
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
let result = data.writeInterfaceToken("aaa");
console.log("RpcServer: writeInterfaceToken is " + result);
......@@ -3273,7 +3265,7 @@ readInterfaceToken(): string
**示例:**
```
```ts
class Stub extends rpc.RemoteObject {
onRemoteMessageRequest(code, data, reply, option) {
let interfaceToken = data.readInterfaceToken();
......@@ -3283,7 +3275,6 @@ readInterfaceToken(): string
}
```
### getSize
getSize(): number
......@@ -3300,13 +3291,12 @@ getSize(): number
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
let size = data.getSize();
console.log("RpcClient: size is " + size);
```
### getCapacity
getCapacity(): number
......@@ -3323,13 +3313,12 @@ getCapacity(): number
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
let result = data.getCapacity();
console.log("RpcClient: capacity is " + result);
```
### setSize
setSize(size: number): boolean
......@@ -3348,17 +3337,16 @@ setSize(size: number): boolean
| 类型 | 说明 |
| ------- | --------------------------------- |
| boolean | 设置成功返回true,否则返回false。 |
| boolean | true:设置成功,false:设置失败。|
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
let setSize = data.setSize(16);
console.log("RpcClient: setSize is " + setSize);
```
### setCapacity
setCapacity(size: number): boolean
......@@ -3377,17 +3365,16 @@ setCapacity(size: number): boolean
| 类型 | 说明 |
| ------- | --------------------------------- |
| boolean | 设置成功返回true,否则返回false。 |
| boolean | true:设置成功,false:设置失败。|
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
let result = data.setCapacity(100);
console.log("RpcClient: setCapacity is " + result);
```
### getWritableBytes
getWritableBytes(): number
......@@ -3404,7 +3391,7 @@ getWritableBytes(): number
**示例:**
```
```ts
class Stub extends rpc.RemoteObject {
onRemoteMessageRequest(code, data, reply, option) {
let getWritableBytes = data.getWritableBytes();
......@@ -3414,7 +3401,6 @@ getWritableBytes(): number
}
```
### getReadableBytes
getReadableBytes(): number
......@@ -3431,7 +3417,7 @@ getReadableBytes(): number
**示例:**
```
```ts
class Stub extends rpc.RemoteObject {
onRemoteRequest(code, data, reply, option) {
let result = data.getReadableBytes();
......@@ -3441,7 +3427,6 @@ getReadableBytes(): number
}
```
### getReadPosition
getReadPosition(): number
......@@ -3458,13 +3443,12 @@ getReadPosition(): number
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
let readPos = data.getReadPosition();
console.log("RpcClient: readPos is " + readPos);
```
### getWritePosition
getWritePosition(): number
......@@ -3481,14 +3465,13 @@ getWritePosition(): number
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
data.writeInt(10);
let bwPos = data.getWritePosition();
console.log("RpcClient: bwPos is " + bwPos);
```
### rewindRead
rewindRead(pos: number): boolean
......@@ -3507,11 +3490,11 @@ rewindRead(pos: number): boolean
| 类型 | 说明 |
| ------- | ------------------------------------------------- |
| boolean | 如果读取位置发生更改,则返回true;否则返回false。 |
| boolean | true:读取位置发生更改,false:读取位置未发生更改。|
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
data.writeInt(12);
data.writeString("parcel");
......@@ -3522,7 +3505,6 @@ rewindRead(pos: number): boolean
console.log("RpcClient: rewindRead is " + number2);
```
### rewindWrite
rewindWrite(pos: number): boolean
......@@ -3541,11 +3523,11 @@ rewindWrite(pos: number): boolean
| 类型 | 说明 |
| ------- | --------------------------------------------- |
| boolean | 如果写入位置更改,则返回true;否则返回false。 |
| boolean | true:写入位置发生更改,false:写入位置未发生更改。|
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
data.writeInt(4);
data.rewindWrite(0);
......@@ -3554,7 +3536,6 @@ rewindWrite(pos: number): boolean
console.log("RpcClient: rewindWrite is: " + number);
```
### writeByte
writeByte(val: number): boolean
......@@ -3577,13 +3558,12 @@ writeByte(val: number): boolean
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
let result = data.writeByte(2);
console.log("RpcClient: writeByte is: " + result);
```
### readByte
readByte(): number
......@@ -3600,7 +3580,7 @@ readByte(): number
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
let result = data.writeByte(2);
console.log("RpcClient: writeByte is: " + result);
......@@ -3608,7 +3588,6 @@ readByte(): number
console.log("RpcClient: readByte is: " + ret);
```
### writeShort
writeShort(val: number): boolean
......@@ -3627,17 +3606,16 @@ writeShort(val: number): boolean
| 类型 | 说明 |
| ------- | ----------------------------- |
| boolean | 写入返回true,否则返回false。 |
| boolean | true:写入成功,false:写入失败。|
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
let result = data.writeShort(8);
console.log("RpcClient: writeShort is: " + result);
```
### readShort
readShort(): number
......@@ -3654,7 +3632,7 @@ readShort(): number
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
let result = data.writeShort(8);
console.log("RpcClient: writeShort is: " + result);
......@@ -3662,7 +3640,6 @@ readShort(): number
console.log("RpcClient: readShort is: " + ret);
```
### writeInt
writeInt(val: number): boolean
......@@ -3685,13 +3662,12 @@ writeInt(val: number): boolean
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
let result = data.writeInt(10);
console.log("RpcClient: writeInt is " + result);
```
### readInt
readInt(): number
......@@ -3708,7 +3684,7 @@ readInt(): number
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
let result = data.writeInt(10);
console.log("RpcClient: writeInt is " + result);
......@@ -3716,7 +3692,6 @@ readInt(): number
console.log("RpcClient: readInt is " + ret);
```
### writeLong
writeLong(val: number): boolean
......@@ -3735,17 +3710,16 @@ writeLong(val: number): boolean
| 类型 | 说明 |
| ------- | --------------------------------- |
| boolean | 写入成功返回true,否则返回false。 |
| boolean | true:写入成功,false:写入失败。|
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
let result = data.writeLong(10000);
console.log("RpcClient: writeLong is " + result);
```
### readLong
readLong(): number
......@@ -3762,7 +3736,7 @@ readLong(): number
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
let result = data.writeLong(10000);
console.log("RpcClient: writeLong is " + result);
......@@ -3770,7 +3744,6 @@ readLong(): number
console.log("RpcClient: readLong is " + ret);
```
### writeFloat
writeFloat(val: number): boolean
......@@ -3789,17 +3762,16 @@ writeFloat(val: number): boolean
| 类型 | 说明 |
| ------- | --------------------------------- |
| boolean | 写入成功返回true,否则返回false。 |
| boolean | true:写入成功,false:写入失败。|
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
let result = data.writeFloat(1.2);
console.log("RpcClient: writeFloat is " + result);
```
### readFloat
readFloat(): number
......@@ -3816,7 +3788,7 @@ readFloat(): number
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
let result = data.writeFloat(1.2);
console.log("RpcClient: writeFloat is " + result);
......@@ -3824,7 +3796,6 @@ readFloat(): number
console.log("RpcClient: readFloat is " + ret);
```
### writeDouble
writeDouble(val: number): boolean
......@@ -3843,17 +3814,16 @@ writeDouble(val: number): boolean
| 类型 | 说明 |
| ------- | --------------------------------- |
| boolean | 写入成功返回true,否则返回false。 |
| boolean | true:写入成功,false:写入失败。|
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
let result = data.writeDouble(10.2);
console.log("RpcClient: writeDouble is " + result);
```
### readDouble
readDouble(): number
......@@ -3870,7 +3840,7 @@ readDouble(): number
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
let result = data.writeDouble(10.2);
console.log("RpcClient: writeDouble is " + result);
......@@ -3896,17 +3866,16 @@ writeBoolean(val: boolean): boolean
| 类型 | 说明 |
| ------- | --------------------------------- |
| boolean | 写入成功返回true,否则返回false。 |
| boolean | true:写入成功,false:写入失败。|
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
let result = data.writeBoolean(false);
console.log("RpcClient: writeBoolean is " + result);
```
### readBoolean
readBoolean(): boolean
......@@ -3923,7 +3892,7 @@ readBoolean(): boolean
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
let result = data.writeBoolean(false);
console.log("RpcClient: writeBoolean is " + result);
......@@ -3931,7 +3900,6 @@ readBoolean(): boolean
console.log("RpcClient: readBoolean is " + ret);
```
### writeChar
writeChar(val: number): boolean
......@@ -3950,17 +3918,16 @@ writeChar(val: number): boolean
| 类型 | 说明 |
| ------- | ----------------------------- |
| boolean | 写入返回true,否则返回false。 |
| boolean | true:写入成功,false:写入失败。|
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
let result = data.writeChar(97);
console.log("RpcClient: writeChar is " + result);
```
### readChar
readChar(): number
......@@ -3977,7 +3944,7 @@ readChar(): number
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
let result = data.writeChar(97);
console.log("RpcClient: writeChar is " + result);
......@@ -3985,7 +3952,6 @@ readChar(): number
console.log("RpcClient: readChar is " + ret);
```
### writeString
writeString(val: string): boolean
......@@ -4004,17 +3970,16 @@ writeString(val: string): boolean
| 类型 | 说明 |
| ------- | --------------------------------- |
| boolean | 写入成功返回true,否则返回false。 |
| boolean | true:写入成功,false:写入失败。|
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
let result = data.writeString('abc');
console.log("RpcClient: writeString is " + result);
```
### readString
readString(): string
......@@ -4031,7 +3996,7 @@ readString(): string
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
let result = data.writeString('abc');
console.log("RpcClient: writeString is " + result);
......@@ -4039,7 +4004,6 @@ readString(): string
console.log("RpcClient: readString is " + ret);
```
### writeSequenceable
writeSequenceable(val: Sequenceable): boolean
......@@ -4058,11 +4022,11 @@ writeSequenceable(val: Sequenceable): boolean
| 类型 | 说明 |
| ------- | --------------------------------- |
| boolean | 写入成功返回true,否则返回false。 |
| boolean | true:写入成功,false:写入失败。|
**示例:**
```
```ts
class MySequenceable {
num: number;
str: string;
......@@ -4087,7 +4051,6 @@ writeSequenceable(val: Sequenceable): boolean
console.log("RpcClient: writeSequenceable is " + result);
```
### readSequenceable
readSequenceable(dataIn: Sequenceable): boolean
......@@ -4106,11 +4069,11 @@ readSequenceable(dataIn: Sequenceable): boolean
| 类型 | 说明 |
| ------- | ------------------------------------------- |
| boolean | 如果反序列成功,则返回true;否则返回false。 |
| boolean | true:反序列化成功,false:反序列化失败。|
**示例:**
```
```ts
class MySequenceable {
num: number;
str: string;
......@@ -4138,7 +4101,6 @@ readSequenceable(dataIn: Sequenceable): boolean
console.log("RpcClient: writeSequenceable is " + result2);
```
### writeByteArray
writeByteArray(byteArray: number[]): boolean
......@@ -4157,18 +4119,17 @@ writeByteArray(byteArray: number[]): boolean
| 类型 | 说明 |
| ------- | --------------------------------- |
| boolean | 写入成功返回true,否则返回false。 |
| boolean | true:写入成功,false:写入失败。|
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
let ByteArrayVar = [1, 2, 3, 4, 5];
let result = data.writeByteArray(ByteArrayVar);
console.log("RpcClient: writeByteArray is " + result);
```
### readByteArray
readByteArray(dataIn: number[]): void
......@@ -4185,7 +4146,7 @@ readByteArray(dataIn: number[]): void
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
let ByteArrayVar = [1, 2, 3, 4, 5];
let result = data.writeByteArray(ByteArrayVar);
......@@ -4194,7 +4155,6 @@ readByteArray(dataIn: number[]): void
data.readByteArray(array);
```
### readByteArray
readByteArray(): number[]
......@@ -4211,7 +4171,7 @@ readByteArray(): number[]
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
let ByteArrayVar = [1, 2, 3, 4, 5];
let result = data.writeByteArray(ByteArrayVar);
......@@ -4220,7 +4180,6 @@ readByteArray(): number[]
console.log("RpcClient: readByteArray is " + array);
```
### writeShortArray
writeShortArray(shortArray: number[]): boolean
......@@ -4239,17 +4198,16 @@ writeShortArray(shortArray: number[]): boolean
| 类型 | 说明 |
| ------- | ----------------------------- |
| boolean | 写入返回true,否则返回false。 |
| boolean | true:写入成功,false:写入失败。|
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
let result = data.writeShortArray([11, 12, 13]);
console.log("RpcClient: writeShortArray is " + result);
```
### readShortArray
readShortArray(dataIn: number[]): void
......@@ -4266,7 +4224,7 @@ readShortArray(dataIn: number[]): void
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
let result = data.writeShortArray([11, 12, 13]);
console.log("RpcClient: writeShortArray is " + result);
......@@ -4274,7 +4232,6 @@ readShortArray(dataIn: number[]): void
data.readShortArray(array);
```
### readShortArray
readShortArray(): number[]
......@@ -4291,7 +4248,7 @@ readShortArray(): number[]
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
let result = data.writeShortArray([11, 12, 13]);
console.log("RpcClient: writeShortArray is " + result);
......@@ -4299,7 +4256,6 @@ readShortArray(): number[]
console.log("RpcClient: readShortArray is " + array);
```
### writeIntArray
writeIntArray(intArray: number[]): boolean
......@@ -4318,17 +4274,16 @@ writeIntArray(intArray: number[]): boolean
| 类型 | 说明 |
| ------- | ----------------------------- |
| boolean | 写入返回true,否则返回false。 |
| boolean | true:写入成功,false:写入失败。|
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
let result = data.writeIntArray([100, 111, 112]);
console.log("RpcClient: writeIntArray is " + result);
```
### readIntArray
readIntArray(dataIn: number[]): void
......@@ -4345,7 +4300,7 @@ readIntArray(dataIn: number[]): void
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
let result = data.writeIntArray([100, 111, 112]);
console.log("RpcClient: writeIntArray is " + result);
......@@ -4353,7 +4308,6 @@ readIntArray(dataIn: number[]): void
data.readIntArray(array);
```
### readIntArray
readIntArray(): number[]
......@@ -4370,7 +4324,7 @@ readIntArray(): number[]
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
let result = data.writeIntArray([100, 111, 112]);
console.log("RpcClient: writeIntArray is " + result);
......@@ -4378,7 +4332,6 @@ readIntArray(): number[]
console.log("RpcClient: readIntArray is " + array);
```
### writeLongArray
writeLongArray(longArray: number[]): boolean
......@@ -4397,17 +4350,16 @@ writeLongArray(longArray: number[]): boolean
| 类型 | 说明 |
| ------- | ----------------------------- |
| boolean | 写入返回true,否则返回false。 |
| boolean | true:写入成功,false:写入失败。|
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
let result = data.writeLongArray([1111, 1112, 1113]);
console.log("RpcClient: writeLongArray is " + result);
```
### readLongArray
readLongArray(dataIn: number[]): void
......@@ -4424,7 +4376,7 @@ readLongArray(dataIn: number[]): void
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
let result = data.writeLongArray([1111, 1112, 1113]);
console.log("RpcClient: writeLongArray is " + result);
......@@ -4432,7 +4384,6 @@ readLongArray(dataIn: number[]): void
data.readLongArray(array);
```
### readLongArray
readLongArray(): number[]
......@@ -4449,7 +4400,7 @@ readLongArray(): number[]
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
let result = data.writeLongArray([1111, 1112, 1113]);
console.log("RpcClient: writeLongArray is " + result);
......@@ -4457,7 +4408,6 @@ readLongArray(): number[]
console.log("RpcClient: readLongArray is " + array);
```
### writeFloatArray
writeFloatArray(floatArray: number[]): boolean
......@@ -4476,17 +4426,16 @@ writeFloatArray(floatArray: number[]): boolean
| 类型 | 说明 |
| ------- | ----------------------------- |
| boolean | 写入返回true,否则返回false。 |
| boolean | true:写入成功,false:写入失败。|
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
let result = data.writeFloatArray([1.2, 1.3, 1.4]);
console.log("RpcClient: writeFloatArray is " + result);
```
### readFloatArray
readFloatArray(dataIn: number[]): void
......@@ -4503,7 +4452,7 @@ readFloatArray(dataIn: number[]): void
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
let result = data.writeFloatArray([1.2, 1.3, 1.4]);
console.log("RpcClient: writeFloatArray is " + result);
......@@ -4511,7 +4460,6 @@ readFloatArray(dataIn: number[]): void
data.readFloatArray(array);
```
### readFloatArray
readFloatArray(): number[]
......@@ -4528,7 +4476,7 @@ readFloatArray(): number[]
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
let result = data.writeFloatArray([1.2, 1.3, 1.4]);
console.log("RpcClient: writeFloatArray is " + result);
......@@ -4536,7 +4484,6 @@ readFloatArray(): number[]
console.log("RpcClient: readFloatArray is " + array);
```
### writeDoubleArray
writeDoubleArray(doubleArray: number[]): boolean
......@@ -4555,17 +4502,16 @@ writeDoubleArray(doubleArray: number[]): boolean
| 类型 | 说明 |
| ------- | ----------------------------- |
| boolean | 写入返回true,否则返回false。 |
| boolean | true:写入成功,false:写入失败。|
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
let result = data.writeDoubleArray([11.1, 12.2, 13.3]);
console.log("RpcClient: writeDoubleArray is " + result);
```
### readDoubleArray
readDoubleArray(dataIn: number[]): void
......@@ -4582,7 +4528,7 @@ readDoubleArray(dataIn: number[]): void
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
let result = data.writeDoubleArray([11.1, 12.2, 13.3]);
console.log("RpcClient: writeDoubleArray is " + result);
......@@ -4590,7 +4536,6 @@ readDoubleArray(dataIn: number[]): void
data.readDoubleArray(array);
```
### readDoubleArray
readDoubleArray(): number[]
......@@ -4607,7 +4552,7 @@ readDoubleArray(): number[]
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
let result = data.writeDoubleArray([11.1, 12.2, 13.3]);
console.log("RpcClient: writeDoubleArray is " + result);
......@@ -4615,7 +4560,6 @@ readDoubleArray(): number[]
console.log("RpcClient: readDoubleArray is " + array);
```
### writeBooleanArray
writeBooleanArray(booleanArray: boolean[]): boolean
......@@ -4634,17 +4578,16 @@ writeBooleanArray(booleanArray: boolean[]): boolean
| 类型 | 说明 |
| ------- | --------------------------------- |
| boolean | 写入成功返回true,否则返回false。 |
| boolean | true:写入成功,false:写入失败。|
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
let result = data.writeBooleanArray([false, true, false]);
console.log("RpcClient: writeBooleanArray is " + result);
```
### readBooleanArray
readBooleanArray(dataIn: boolean[]): void
......@@ -4661,7 +4604,7 @@ readBooleanArray(dataIn: boolean[]): void
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
let result = data.writeBooleanArray([false, true, false]);
console.log("RpcClient: writeBooleanArray is " + result);
......@@ -4669,7 +4612,6 @@ readBooleanArray(dataIn: boolean[]): void
data.readBooleanArray(array);
```
### readBooleanArray
readBooleanArray(): boolean[]
......@@ -4686,7 +4628,7 @@ readBooleanArray(): boolean[]
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
let result = data.writeBooleanArray([false, true, false]);
console.log("RpcClient: writeBooleanArray is " + result);
......@@ -4694,7 +4636,6 @@ readBooleanArray(): boolean[]
console.log("RpcClient: readBooleanArray is " + array);
```
### writeCharArray
writeCharArray(charArray: number[]): boolean
......@@ -4713,17 +4654,16 @@ writeCharArray(charArray: number[]): boolean
| 类型 | 说明 |
| ------- | --------------------------------- |
| boolean | 写入成功返回true,否则返回false。 |
| boolean | true:写入成功,false:写入失败。|
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
let result = data.writeCharArray([97, 98, 88]);
console.log("RpcClient: writeCharArray is " + result);
```
### readCharArray
readCharArray(dataIn: number[]): void
......@@ -4740,7 +4680,7 @@ readCharArray(dataIn: number[]): void
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
let result = data.writeCharArray([97, 98, 99]);
console.log("RpcClient: writeCharArray is " + result);
......@@ -4748,7 +4688,6 @@ readCharArray(dataIn: number[]): void
data.readCharArray(array);
```
### readCharArray
readCharArray(): number[]
......@@ -4765,7 +4704,7 @@ readCharArray(): number[]
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
let result = data.writeCharArray([97, 98, 99]);
console.log("RpcClient: writeCharArray is " + result);
......@@ -4773,7 +4712,6 @@ readCharArray(): number[]
console.log("RpcClient: readCharArray is " + array);
```
### writeStringArray
writeStringArray(stringArray: string[]): boolean
......@@ -4792,17 +4730,16 @@ writeStringArray(stringArray: string[]): boolean
| 类型 | 说明 |
| ------- | --------------------------------- |
| boolean | 写入成功返回true,否则返回false。 |
| boolean | true:写入成功,false:写入失败。|
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
let result = data.writeStringArray(["abc", "def"]);
console.log("RpcClient: writeStringArray is " + result);
```
### readStringArray
readStringArray(dataIn: string[]): void
......@@ -4819,7 +4756,7 @@ readStringArray(dataIn: string[]): void
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
let result = data.writeStringArray(["abc", "def"]);
console.log("RpcClient: writeStringArray is " + result);
......@@ -4827,7 +4764,6 @@ readStringArray(dataIn: string[]): void
data.readStringArray(array);
```
### readStringArray
readStringArray(): string[]
......@@ -4844,7 +4780,7 @@ readStringArray(): string[]
**示例:**
```
```ts
let data = rpc.MessageParcel.create();
let result = data.writeStringArray(["abc", "def"]);
console.log("RpcClient: writeStringArray is " + result);
......@@ -4852,7 +4788,6 @@ readStringArray(): string[]
console.log("RpcClient: readStringArray is " + array);
```
### writeNoException<sup>8+</sup>
writeNoException(): void
......@@ -4863,7 +4798,7 @@ writeNoException(): void
**示例:**
```
```ts
class MyDeathRecipient {
onRemoteDied() {
console.log("server died");
......@@ -4905,7 +4840,7 @@ readException(): void
**示例:**
```
```ts
import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
......@@ -4967,11 +4902,11 @@ writeSequenceableArray(sequenceableArray: Sequenceable[]): boolean
| 类型 | 说明 |
| ------- | --------------------------------- |
| boolean | 写入成功返回true,否则返回false。 |
| boolean | true:写入成功,false:写入失败。|
**示例:**
```
```ts
class MySequenceable {
num: number;
str: string;
......@@ -4999,7 +4934,6 @@ writeSequenceableArray(sequenceableArray: Sequenceable[]): boolean
console.log("RpcClient: writeSequenceableArray is " + result);
```
### readSequenceableArray<sup>8+</sup>
readSequenceableArray(sequenceableArray: Sequenceable[]): void
......@@ -5016,7 +4950,7 @@ readSequenceableArray(sequenceableArray: Sequenceable[]): void
**示例:**
```
```ts
class MySequenceable {
num: number;
str: string;
......@@ -5046,7 +4980,6 @@ readSequenceableArray(sequenceableArray: Sequenceable[]): void
data.readSequenceableArray(b);
```
### writeRemoteObjectArray<sup>8+</sup>
writeRemoteObjectArray(objectArray: IRemoteObject[]): boolean
......@@ -5065,11 +4998,11 @@ writeRemoteObjectArray(objectArray: IRemoteObject[]): boolean
| 类型 | 说明 |
| ------- | -------------------------------------------------------------------------------------------------------------------- |
| boolean | 如果IRemoteObject对象数组成功写入MessageParcel,则返回true;如果对象为null或数组写入MessageParcel失败,则返回false。 |
| boolean | true:写入成功,false:写入失败。|
**示例:**
```
```ts
class MyDeathRecipient {
onRemoteDied() {
console.log("server died");
......@@ -5099,7 +5032,6 @@ writeRemoteObjectArray(objectArray: IRemoteObject[]): boolean
console.log("RpcClient: writeRemoteObjectArray is " + result);
```
### readRemoteObjectArray<sup>8+</sup>
readRemoteObjectArray(objects: IRemoteObject[]): void
......@@ -5116,7 +5048,7 @@ readRemoteObjectArray(objects: IRemoteObject[]): void
**示例:**
```
```ts
class MyDeathRecipient {
onRemoteDied() {
console.log("server died");
......@@ -5147,7 +5079,6 @@ readRemoteObjectArray(objects: IRemoteObject[]): void
data.readRemoteObjectArray(b);
```
### readRemoteObjectArray<sup>8+</sup>
readRemoteObjectArray(): IRemoteObject[]
......@@ -5164,7 +5095,7 @@ readRemoteObjectArray(): IRemoteObject[]
**示例:**
```
```ts
class MyDeathRecipient {
onRemoteDied() {
console.log("server died");
......@@ -5196,12 +5127,11 @@ readRemoteObjectArray(): IRemoteObject[]
console.log("RpcClient: readRemoteObjectArray is " + b);
```
### closeFileDescriptor<sup>8+</sup>
static closeFileDescriptor(fd: number): void
关闭给定的文件描述符。
静态方法,关闭给定的文件描述符。
**系统能力**:SystemCapability.Communication.IPC.Core
......@@ -5213,19 +5143,18 @@ static closeFileDescriptor(fd: number): void
**示例:**
```
```ts
import fileio from '@ohos.fileio';
let filePath = "path/to/file";
let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666);
rpc.MessageParcel.closeFileDescriptor(fd);
```
### dupFileDescriptor<sup>8+</sup>
static dupFileDescriptor(fd: number) :number
复制给定的文件描述符。
静态方法,复制给定的文件描述符。
**系统能力**:SystemCapability.Communication.IPC.Core
......@@ -5243,14 +5172,13 @@ static dupFileDescriptor(fd: number) :number
**示例:**
```
```ts
import fileio from '@ohos.fileio';
let filePath = "path/to/file";
let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666);
let newFd = rpc.MessageParcel.dupFileDescriptor(fd);
```
### containFileDescriptors<sup>8+</sup>
containFileDescriptors(): boolean
......@@ -5263,11 +5191,11 @@ containFileDescriptors(): boolean
| 类型 | 说明 |
| ------- | ------------------------------------------------------------------ |
| boolean | 如果此MessageParcel对象包含文件描述符,则返回true;否则返回false。 |
| boolean |true:包含文件描述符,false:未包含文件描述符。|
**示例:**
```
```ts
import fileio from '@ohos.fileio';
let parcel = new rpc.MessageParcel();
let filePath = "path/to/file";
......@@ -5279,7 +5207,6 @@ containFileDescriptors(): boolean
console.log("RpcTest: parcel after write fd containFd result is : " + containFD);
```
### writeFileDescriptor<sup>8+</sup>
writeFileDescriptor(fd: number): boolean
......@@ -5298,11 +5225,11 @@ writeFileDescriptor(fd: number): boolean
| 类型 | 说明 |
| ------- | ----------------------------------------- |
| boolean | 如果操作成功,则返回true;否则返回false。 |
| boolean | true:操作成功,false:操作失败。|
**示例:**
```
```ts
import fileio from '@ohos.fileio';
let parcel = new rpc.MessageParcel();
let filePath = "path/to/file";
......@@ -5311,7 +5238,6 @@ writeFileDescriptor(fd: number): boolean
console.log("RpcTest: parcel writeFd result is : " + writeResult);
```
### readFileDescriptor<sup>8+</sup>
readFileDescriptor(): number
......@@ -5328,7 +5254,7 @@ readFileDescriptor(): number
**示例:**
```
```ts
import fileio from '@ohos.fileio';
let parcel = new rpc.MessageParcel();
let filePath = "path/to/file";
......@@ -5338,7 +5264,6 @@ readFileDescriptor(): number
console.log("RpcTest: parcel read fd is : " + readFD);
```
### writeAshmem<sup>8+</sup>
writeAshmem(ashmem: Ashmem): boolean
......@@ -5357,18 +5282,17 @@ writeAshmem(ashmem: Ashmem): boolean
| 类型 | 说明 |
| ------- | -------------------------------------------------------------------- |
| boolean | 如果匿名共享对象成功写入此MessageParcel,则返回true;否则返回false。 |
| boolean | true:写入成功,false:写入失败。|
**示例:**
```
```ts
let parcel = new rpc.MessageParcel();
let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024);
let isWriteSuccess = parcel.writeAshmem(ashmem);
console.log("RpcTest: write ashmem to result is : " + isWriteSuccess);
```
### readAshmem<sup>8+</sup>
readAshmem(): Ashmem
......@@ -5385,7 +5309,7 @@ readAshmem(): Ashmem
**示例:**
```
```ts
let parcel = new rpc.MessageParcel();
let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024);
let isWriteSuccess = parcel.writeAshmem(ashmem);
......@@ -5394,7 +5318,6 @@ readAshmem(): Ashmem
console.log("RpcTest: read ashmem to result is : " + readAshmem);
```
### getRawDataCapacity<sup>8+</sup>
getRawDataCapacity(): number
......@@ -5411,13 +5334,12 @@ getRawDataCapacity(): number
**示例:**
```
```ts
let parcel = new rpc.MessageParcel();
let result = parcel.getRawDataCapacity();
console.log("RpcTest: parcel get RawDataCapacity result is : " + result);
```
### writeRawData<sup>8+</sup>
writeRawData(rawData: number[], size: number): boolean
......@@ -5437,18 +5359,17 @@ writeRawData(rawData: number[], size: number): boolean
| 类型 | 说明 |
| ------- | ----------------------------------------- |
| boolean | 如果操作成功,则返回true;否则返回false。 |
| boolean | true:写入成功,false:写入失败。|
**示例:**
```
```ts
let parcel = new rpc.MessageParcel();
let arr = [1, 2, 3, 4, 5];
let isWriteSuccess = parcel.writeRawData(arr, arr.length);
console.log("RpcTest: parcel write raw data result is : " + isWriteSuccess);
```
### readRawData<sup>8+</sup>
readRawData(size: number): number[]
......@@ -5471,7 +5392,7 @@ readRawData(size: number): number[]
**示例:**
```
```ts
let parcel = new rpc.MessageParcel();
let arr = [1, 2, 3, 4, 5];
let isWriteSuccess = parcel.writeRawData(arr, arr.length);
......@@ -5480,7 +5401,6 @@ readRawData(size: number): number[]
console.log("RpcTest: parcel read raw data result is : " + result);
```
## Parcelable<sup>9+</sup>
在进程间通信(IPC)期间,将类的对象写入MessageSequence并从MessageSequence中恢复它们。
......@@ -5503,11 +5423,10 @@ marshalling(dataOut: MessageSequence): boolean
| 类型 | 说明 |
| ------- | ----------------------------------------- |
| boolean | 如果封送成功,则返回true;否则返回false。 |
| boolean | true:封送成功,false:封送失败。
**示例:**
```
```ts
class MyParcelable {
num: number;
str: string;
......@@ -5535,7 +5454,6 @@ marshalling(dataOut: MessageSequence): boolean
console.log("RpcClient: readParcelable is " + result2);
```
### unmarshalling
unmarshalling(dataIn: MessageSequence): boolean
......@@ -5554,11 +5472,11 @@ unmarshalling(dataIn: MessageSequence): boolean
| 类型 | 说明 |
| ------- | --------------------------------------------- |
| boolean | 如果可序列化成功,则返回true;否则返回false。 |
| boolean | true:反序列化成功,false:反序列化失败。|
**示例:**
```
```ts
class MyParcelable {
num: number;
str: string;
......@@ -5586,7 +5504,6 @@ unmarshalling(dataIn: MessageSequence): boolean
console.log("RpcClient: readParcelable is " + result2);
```
## Sequenceable<sup>(deprecated)</sup>
>从API version 9 开始不再维护,建议使用[Parcelable](#parcelable9)类替代。
......@@ -5611,11 +5528,10 @@ marshalling(dataOut: MessageParcel): boolean
| 类型 | 说明 |
| ------- | ----------------------------------------- |
| boolean | 如果封送成功,则返回true;否则返回false。 |
| boolean | true:封送成功,false:封送失败。
**示例:**
```
```ts
class MySequenceable {
num: number;
str: string;
......@@ -5643,7 +5559,6 @@ marshalling(dataOut: MessageParcel): boolean
console.log("RpcClient: readSequenceable is " + result2);
```
### unmarshalling
unmarshalling(dataIn: MessageParcel): boolean
......@@ -5662,11 +5577,11 @@ unmarshalling(dataIn: MessageParcel): boolean
| 类型 | 说明 |
| ------- | --------------------------------------------- |
| boolean | 如果可序列化成功,则返回true;否则返回false。 |
| boolean | true:反序列化成功,false:反序列化失败。|
**示例:**
```
```ts
class MySequenceable {
num: number;
str: string;
......@@ -5694,7 +5609,6 @@ unmarshalling(dataIn: MessageParcel): boolean
console.log("RpcClient: readSequenceable is " + result2);
```
## IRemoteBroker
远端对象的代理持有者。用于获取代理对象。
......@@ -5715,17 +5629,38 @@ asObject(): IRemoteObject
**示例:**
```
```ts
class TestAbility extends rpc.RemoteObject {
asObject() {
return this;
}
}
let remoteObject = new TestAbility().asObject();
```
**示例:**
```
```ts
import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function (elementName, remoteProxy) {
console.log("RpcClient: js onConnect called.");
proxy = remoteProxy;
},
onDisconnect: function (elementName) {
console.log("RpcClient: onDisconnect");
},
onFailed: function () {
console.log("RpcClient: onFailed");
}
};
let want = {
"bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.MainAbility",
};
FA.connectAbility(want, connect);
class TestProxy {
remote: rpc.RemoteObject;
constructor(remote) {
......@@ -5735,6 +5670,8 @@ asObject(): IRemoteObject
return this.remote;
}
}
let iRemoteObject = new TestProxy(proxy).asObject();
```
## DeathRecipient
......@@ -5751,7 +5688,7 @@ onRemoteDied(): void
**示例:**
```
```ts
class MyDeathRecipient {
onRemoteDied() {
console.log("server died");
......@@ -5795,7 +5732,7 @@ onRemoteDied(): void
getLocalInterface(descriptor: string): IRemoteBroker
查询接口。
查询接口描述符的字符串
**系统能力**:SystemCapability.Communication.IPC.Core
......@@ -5817,7 +5754,7 @@ getLocalInterface(descriptor: string): IRemoteBroker
queryLocalInterface(descriptor: string): IRemoteBroker
查询接口。
查询接口描述符的字符串
**系统能力**:SystemCapability.Communication.IPC.Core
......@@ -5833,7 +5770,6 @@ queryLocalInterface(descriptor: string): IRemoteBroker
| ------------- | --------------------------------------------- |
| IRemoteBroker | 返回绑定到指定接口描述符的IRemoteBroker对象。 |
### sendRequest<sup>(deprecated)</sup>
>从API version 9 开始不再维护,建议使用[sendMessageRequest](#sendmessagerequest9)类替代。
......@@ -5857,7 +5793,7 @@ sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: Me
| 类型 | 说明 |
| ------- | --------------------------------------------- |
| boolean | 返回一个布尔值,true表示成功,false表示失败。 |
| boolean | true:发送成功,false:发送失败。|
### sendRequest<sup>8+(deprecated)</sup>
......@@ -5928,7 +5864,6 @@ sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence,
| options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 |
| callback | AsyncCallback&lt;RequestResult&gt; | 是 | 接收发送结果的回调。 |
### sendRequest<sup>8+(deprecated)</sup>
>从API version 9 开始不再维护,建议使用[sendMessageRequest](#sendmessagerequest9)类替代。
......@@ -5949,7 +5884,6 @@ sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: Me
| options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 |
| callback | AsyncCallback&lt;SendRequestResult&gt; | 是 | 接收发送结果的回调。 |
### registerDeathRecipient<sup>9+</sup>
registerDeathRecipient(recipient: DeathRecipient, flags: number): void
......@@ -5973,7 +5907,6 @@ registerDeathRecipient(recipient: DeathRecipient, flags: number): void
| ------- | -------- |
| 1900008 | proxy or remote object is invalid |
### addDeathrecipient<sup>(deprecated)</sup>
>从API version 9 开始不再维护,建议使用[registerDeathRecipient](#registerdeathrecipient9)类替代。
......@@ -5995,7 +5928,7 @@ addDeathRecipient(recipient: DeathRecipient, flags: number): boolean
| 类型 | 说明 |
| ------- | --------------------------------------------- |
| boolean | 如果回调注册成功,则返回true;否则返回false。 |
| boolean | true:回调注册成功,false:回调注册失败。|
### unregisterDeathRecipient<sup>9+</sup>
......@@ -6021,7 +5954,6 @@ unregisterDeathRecipient(recipient: DeathRecipient, flags: number): void
| ------- | -------- |
| 1900008 | proxy or remote object is invalid |
### removeDeathRecipient<sup>(deprecated)</sup>
>从API version 9 开始不再维护,建议使用[unregisterDeathRecipient](#unregisterdeathrecipient9)类替代。
......@@ -6043,14 +5975,13 @@ removeDeathRecipient(recipient: DeathRecipient, flags: number): boolean
| 类型 | 说明 |
| ------- | --------------------------------------------- |
| boolean | 如果回调成功注销,则返回true;否则返回false。 |
| boolean | true:回调注销成功,false:回调注销失败。|
### getDescriptor<sup>9+</sup>
getDescriptor(): string
获取对象的接口描述符接口描述符为字符串。
获取对象的接口描述符接口描述符为字符串。
**系统能力**:SystemCapability.Communication.IPC.Core
......@@ -6075,7 +6006,7 @@ getDescriptor(): string
getInterfaceDescriptor(): string
获取对象的接口描述符接口描述符为字符串。
获取对象的接口描述符接口描述符为字符串。
**系统能力**:SystemCapability.Communication.IPC.Core
......@@ -6098,7 +6029,7 @@ isObjectDead(): boolean
| 类型 | 说明 |
| ------- | ------------------------------------------- |
| boolean | 如果对象已死亡,则返回true;否则返回false。 |
| boolean | true:对象死亡,false:对象未死亡。|
## RemoteProxy
......@@ -6107,7 +6038,7 @@ isObjectDead(): boolean
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.IPC.Core。
| 名称 | 值 | 说明 |
| 名称 | 默认值 | 说明 |
| --------------------- | ----------------------- | --------------------------------- |
| PING_TRANSACTION | 1599098439 (0x5f504e47) | 内部指令码,用于测试IPC服务正常。 |
| DUMP_TRANSACTION | 1598311760 (0x5f444d50) | 内部指令码,获取Binder内部状态。 |
......@@ -6115,7 +6046,6 @@ isObjectDead(): boolean
| MIN_TRANSACTION_ID | 1 (0x00000001) | 最小有效指令码。 |
| MAX_TRANSACTION_ID | 16777215 (0x00FFFFFF) | 最大有效指令码。 |
### sendRequest<sup>(deprecated)</sup>
>从API version 9 开始不再维护,建议使用[sendMessageRequest](#sendmessagerequest9)类替代。
......@@ -6139,11 +6069,11 @@ sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: Me
| 类型 | 说明 |
| ------- | --------------------------------------------- |
| boolean | 返回一个布尔值,true表示成功,false表示失败。 |
| boolean | true:发送成功,false:发送失败。|
**示例:**
```
```ts
import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
......@@ -6181,7 +6111,6 @@ sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: Me
reply.reclaim();
```
### sendMessageRequest<sup>9+</sup>
sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence, options: MessageOption): Promise&lt;RequestResult&gt;
......@@ -6207,7 +6136,7 @@ sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence,
**示例:**
```
```ts
import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
......@@ -6251,7 +6180,6 @@ sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence,
});
```
### sendRequest<sup>8+(deprecated)</sup>
>从API version 9 开始不再维护,建议使用[sendMessageRequest](#sendmessagerequest9)类替代。
......@@ -6279,7 +6207,7 @@ sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: Me
**示例:**
```
```ts
import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
......@@ -6341,10 +6269,9 @@ sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence,
| options | [MessageOption](#messageoption) | 是 | 本次请求的同异步模式,默认同步调用。 |
| callback | AsyncCallback&lt;RequestResult&gt; | 是 | 接收发送结果的回调。 |
**示例:**
```
```ts
import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
......@@ -6390,7 +6317,6 @@ sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence,
}
```
### sendRequest<sup>8+(deprecated)</sup>
>从API version 9 开始不再维护,建议使用[sendMessageRequest](#sendmessagerequest9)类替代。
......@@ -6413,7 +6339,7 @@ sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: Me
**示例:**
```
```ts
import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
......@@ -6454,7 +6380,6 @@ sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: Me
proxy.sendRequest(1, data, reply, option, sendRequestCallback);
```
### getLocalInterface<sup>9+</sup>
getLocalInterface(interface: string): IRemoteBroker
......@@ -6485,7 +6410,7 @@ getLocalInterface(interface: string): IRemoteBroker
**示例:**
```
```ts
import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
......@@ -6514,7 +6439,6 @@ getLocalInterface(interface: string): IRemoteBroker
}
```
### queryLocalInterface<sup>(deprecated)</sup>
>从API version 9 开始不再维护,建议使用[getLocalInterface](#getlocalinterface9)类替代。
......@@ -6539,7 +6463,7 @@ queryLocalInterface(interface: string): IRemoteBroker
**示例:**
```
```ts
import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
......@@ -6563,7 +6487,6 @@ queryLocalInterface(interface: string): IRemoteBroker
console.log("RpcClient: queryLocalInterface is " + broker);
```
### registerDeathRecipient<sup>9+</sup>
registerDeathRecipient(recipient: DeathRecipient, flags: number): void
......@@ -6589,7 +6512,7 @@ registerDeathRecipient(recipient: DeathRecipient, flags: number): void
**示例:**
```
```ts
import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
......@@ -6623,7 +6546,6 @@ registerDeathRecipient(recipient: DeathRecipient, flags: number): void
}
```
### addDeathRecippient<sup>(deprecated)</sup>
>从API version 9 开始不再维护,建议使用[registerDeathRecipient](#registerdeathrecipient9)类替代。
......@@ -6645,11 +6567,11 @@ addDeathRecipient(recipient: DeathRecipient, flags: number): boolean
| 类型 | 说明 |
| ------- | --------------------------------------------- |
| boolean | 如果回调注册成功,则返回true;否则返回false。 |
| boolean | true:回调注册成功,false:回调注册失败。|
**示例:**
```
```ts
import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
......@@ -6703,7 +6625,7 @@ unregisterDeathRecipient(recipient: DeathRecipient, flags: number): boolean
**示例:**
```
```ts
import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
......@@ -6738,7 +6660,6 @@ unregisterDeathRecipient(recipient: DeathRecipient, flags: number): boolean
}
```
### removeDeathRecipient<sup>(deprecated)</sup>
>从API version 9 开始不再维护,建议使用[unregisterDeathRecipient](#unregisterdeathrecipient9)类替代。
......@@ -6760,11 +6681,11 @@ removeDeathRecipient(recipient: DeathRecipient, flags: number): boolean
| 类型 | 说明 |
| ------- | --------------------------------------------- |
| boolean | 如果回调成功注销,则返回true;否则返回false。 |
| boolean | true:回调注销成功,false:回调注销失败。|
**示例:**
```
```ts
import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
......@@ -6794,12 +6715,11 @@ removeDeathRecipient(recipient: DeathRecipient, flags: number): boolean
proxy.removeDeathRecipient(deathRecipient, 0);
```
### getDescriptor<sup>9+</sup>
getDescriptor(): string
获取对象的接口描述符接口描述符为字符串。
获取对象的接口描述符接口描述符为字符串。
**系统能力**:SystemCapability.Communication.IPC.Core
......@@ -6820,7 +6740,7 @@ getDescriptor(): string
**示例:**
```
```ts
import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
......@@ -6849,7 +6769,6 @@ getDescriptor(): string
}
```
### getInterfaceDescriptor<sup>(deprecated)</sup>
>从API version 9 开始不再维护,建议使用[getDescriptor](#getdescriptor9)类替代。
......@@ -6868,7 +6787,7 @@ getInterfaceDescriptor(): string
**示例:**
```
```ts
import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
......@@ -6892,7 +6811,6 @@ getInterfaceDescriptor(): string
console.log("RpcClient: descriptor is " + descriptor);
```
### isObjectDead
isObjectDead(): boolean
......@@ -6905,11 +6823,11 @@ isObjectDead(): boolean
| 类型 | 说明 |
| ------- | --------------------------------------------------------- |
| boolean | 如果对应的RemoteObject已经死亡,返回true,否则返回false。 |
| boolean | true:对应的对象已经死亡,false:对应的对象未死亡|
**示例:**
```
```ts
import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
......@@ -6933,14 +6851,13 @@ isObjectDead(): boolean
console.log("RpcClient: isObjectDead is " + isDead);
```
## MessageOption
公共消息选项(int标志,int等待时间),使用标志中指定的标志构造指定的MessageOption对象。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.IPC.Core。
| 名称 | 值 | 说明 |
| 名称 | 默认值 | 说明 |
| ------------- | ---- | ----------------------------------------------------------- |
| TF_SYNC | 0 | 同步调用标识。 |
| TF_ASYNC | 1 | 异步调用标识。 |
......@@ -6963,6 +6880,16 @@ MessageOption构造函数。
| syncFlags | number | 否 | 同步调用或异步调用标志。默认同步调用。 |
**示例:**
```ts
class TestRemoteObject extends rpc.MessageOption {
constructor(async) {
super(async);
}
}
```
### constructor
constructor(syncFlags?: number, waitTime?: number)
......@@ -6978,7 +6905,15 @@ MessageOption构造函数。
| syncFlags | number | 否 | 同步调用或异步调用标志。默认同步调用。 |
| waitTime | number | 否 | 调用rpc最长等待时间。默认&nbsp;TF_WAIT_TIME。 |
**示例:**
```ts
class TestRemoteObject extends rpc.MessageOption {
constructor(syncFlags,waitTime) {
super(syncFlags,waitTime);
}
}
```
### isAsync<sup>9+</sup>
isAsync(): boolean;
......@@ -6991,8 +6926,14 @@ isAsync(): boolean;
| 类型 | 说明 |
| ------- | ------------------------------------ |
| boolean | 调用成功返回同步调用或异步调用标志。 |
| boolean | true:同步调用成功,false:异步调用成功。 |
**示例:**
```ts
let option = new rpc.MessageOption();
let isAsync = option.isAsync();
```
### setAsync<sup>9+</sup>
......@@ -7002,6 +6943,13 @@ setAsync(async: boolean): void;
**系统能力**:SystemCapability.Communication.IPC.Core
**示例:**
```ts
let option = new rpc.MessageOption();
let setAsync = option.setAsync(true);
console.log("Set synchronization flag");
```
### getFlags
......@@ -7017,7 +6965,23 @@ getFlags(): number
| ------ | ------------------------------------ |
| number | 调用成功返回同步调用或异步调用标志。 |
**示例:**
```ts
try {
let option = new rpc.MessageOption();
console.info("create object successfully.");
let flog = option.getFlags();
console.info("run getFlags success, flog is " + flog);
option.setFlags(1)
console.info("run setFlags success");
let flog2 = option.getFlags();
console.info("run getFlags success, flog2 is " + flog2);
} catch (error) {
console.info("error " + error);
}
```
### setFlags
setFlags(flags: number): void
......@@ -7032,6 +6996,19 @@ setFlags(flags: number): void
| ------ | ------ | ---- | ------------------------ |
| flags | number | 是 | 同步调用或异步调用标志。 |
**示例:**
```ts
try {
let option = new rpc.MessageOption();
option.setFlags(1)
console.info("run setFlags success");
let flog = option.getFlags();
console.info("run getFlags success, flog is " + flog);
} catch (error) {
console.info("error " + error);
}
```
### getWaitTime
......@@ -7047,6 +7024,20 @@ getWaitTime(): number
| ------ | ----------------- |
| number | rpc最长等待时间。 |
**示例:**
```ts
try {
let option = new rpc.MessageOption();
let time = option.getWaitTime();
console.info("run getWaitTime success");
option.setWaitTime(16);
let time2 = option.getWaitTime();
console.info("run getWaitTime success, time is " + time);
} catch (error) {
console.info("error " + error);
}
```
### setWaitTime
......@@ -7062,6 +7053,18 @@ setWaitTime(waitTime: number): void
| -------- | ------ | ---- | --------------------- |
| waitTime | number | 是 | rpc调用最长等待时间。 |
**示例:**
```ts
try {
let option = new rpc.MessageOption();
option.setWaitTime(16);
let time = option.getWaitTime();
console.info("run getWaitTime success, time is " + time);
} catch (error) {
console.info("error " + error);
}
```
## IPCSkeleton
......@@ -7071,7 +7074,7 @@ setWaitTime(waitTime: number): void
static getContextObject(): IRemoteObject
获取系统能力的管理者。
静态方法,获取系统能力的管理者。
**系统能力**:SystemCapability.Communication.IPC.Core
......@@ -7083,17 +7086,16 @@ static getContextObject(): IRemoteObject
**示例:**
```
```ts
let samgr = rpc.IPCSkeleton.getContextObject();
console.log("RpcServer: getContextObject result: " + samgr);
```
### getCallingPid
static getCallingPid(): number
获取调用者的PID。此方法由RemoteObject对象在onRemoteRequest方法中调用,不在IPC上下文环境(onRemoteRequest)中调用则返回本进程的PID。
静态方法,获取调用者的PID。此方法由RemoteObject对象在onRemoteRequest方法中调用,不在IPC上下文环境(onRemoteRequest)中调用则返回本进程的PID。
**系统能力**:SystemCapability.Communication.IPC.Core
......@@ -7105,7 +7107,7 @@ static getCallingPid(): number
**示例:**
```
```ts
class Stub extends rpc.RemoteObject {
onRemoteMessageRequest(code, data, reply, option) {
let callerPid = rpc.IPCSkeleton.getCallingPid();
......@@ -7115,12 +7117,11 @@ static getCallingPid(): number
}
```
### getCallingUid
static getCallingUid(): number
获取调用者的UID。此方法由RemoteObject对象在onRemoteRequest方法中调用,不在IPC上下文环境(onRemoteRequest)中调用则返回本进程的UID。
静态方法,获取调用者的UID。此方法由RemoteObject对象在onRemoteRequest方法中调用,不在IPC上下文环境(onRemoteRequest)中调用则返回本进程的UID。
**系统能力**:SystemCapability.Communication.IPC.Core
......@@ -7132,7 +7133,7 @@ static getCallingUid(): number
**示例:**
```
```ts
class Stub extends rpc.RemoteObject {
onRemoteMessageRequest(code, data, reply, option) {
let callerUid = rpc.IPCSkeleton.getCallingUid();
......@@ -7142,16 +7143,14 @@ static getCallingUid(): number
}
```
### getCallingTokenId<sup>8+</sup>
static getCallingTokenId(): number;
获取调用者的TokenId,用于被调用方对调用方的身份校验。
静态方法,获取调用者的TokenId,用于被调用方对调用方的身份校验。
**系统能力**:SystemCapability.Communication.IPC.Core
**返回值:**
| 类型 | 说明 |
......@@ -7160,7 +7159,7 @@ static getCallingTokenId(): number;
**示例:**
```
```ts
class Stub extends rpc.RemoteObject {
onRemoteMessageRequest(code, data, reply, option) {
let callerTokenId = rpc.IPCSkeleton.getCallingTokenId();
......@@ -7175,7 +7174,7 @@ static getCallingTokenId(): number;
static getCallingDeviceID(): string
获取调用者进程所在的设备ID。
静态方法,获取调用者进程所在的设备ID。
**系统能力**:SystemCapability.Communication.IPC.Core
......@@ -7187,7 +7186,7 @@ static getCallingDeviceID(): string
**示例:**
```
```ts
class Stub extends rpc.RemoteObject {
onRemoteMessageRequest(code, data, reply, option) {
let callerDeviceID = rpc.IPCSkeleton.getCallingDeviceID();
......@@ -7197,12 +7196,11 @@ static getCallingDeviceID(): string
}
```
### getLocalDeviceID
static getLocalDeviceID(): string
获取本端设备ID。
静态方法,获取本端设备ID。
**系统能力**:SystemCapability.Communication.IPC.Core
......@@ -7214,7 +7212,7 @@ static getLocalDeviceID(): string
**示例:**
```
```ts
class Stub extends rpc.RemoteObject {
onRemoteMessageRequest(code, data, reply, option) {
let localDeviceID = rpc.IPCSkeleton.getLocalDeviceID();
......@@ -7224,12 +7222,11 @@ static getLocalDeviceID(): string
}
```
### isLocalCalling
static isLocalCalling(): boolean
检查当前通信对端是否是本设备的进程。
静态方法,检查当前通信对端是否是本设备的进程。
**系统能力**:SystemCapability.Communication.IPC.Core
......@@ -7237,11 +7234,11 @@ static isLocalCalling(): boolean
| 类型 | 说明 |
| ------- | --------------------------------------------------------- |
| boolean | 如果调用是在同一设备上进行的,则返回true,否则返回false。 |
| boolean | true:调用在同一台设备,false:调用未在同一台设备。|
**示例:**
```
```ts
class Stub extends rpc.RemoteObject {
onRemoteMessageRequest(code, data, reply, option) {
let isLocalCalling = rpc.IPCSkeleton.isLocalCalling();
......@@ -7251,12 +7248,11 @@ static isLocalCalling(): boolean
}
```
### flushCmdBuffer<sup>9+</sup>
static flushCmdBuffer(object: IRemoteObject): void
将所有挂起的命令从指定的RemoteProxy刷新到相应的RemoteObject。建议在执行任何时间敏感操作之前调用此方法。
静态方法,将所有挂起的命令从指定的RemoteProxy刷新到相应的RemoteObject。建议在执行任何时间敏感操作之前调用此方法。
**系统能力**:SystemCapability.Communication.IPC.Core
......@@ -7269,7 +7265,7 @@ static flushCmdBuffer(object: IRemoteObject): void
**示例:**
```
```ts
class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) {
super(descriptor);
......@@ -7284,14 +7280,13 @@ static flushCmdBuffer(object: IRemoteObject): void
}
```
### flushCommands<sup>(deprecated)</sup>
>从API version 9 开始不再维护,建议使用[flushCmdBuffer](#flushcmdbuffer9)类替代。
static flushCommands(object: IRemoteObject): number
将所有挂起的命令从指定的RemoteProxy刷新到相应的RemoteObject。建议在执行任何时间敏感操作之前调用此方法。
静态方法,将所有挂起的命令从指定的RemoteProxy刷新到相应的RemoteObject。建议在执行任何时间敏感操作之前调用此方法。
**系统能力**:SystemCapability.Communication.IPC.Core
......@@ -7309,7 +7304,7 @@ static flushCommands(object: IRemoteObject): number
**示例:**
```
```ts
class MyDeathRecipient {
onRemoteDied() {
console.log("server died");
......@@ -7338,7 +7333,7 @@ static flushCommands(object: IRemoteObject): number
static resetCallingIdentity(): string
将远程用户的UID和PID替换为本地用户的UID和PID。它可以用于身份验证等场景。
静态方法,将远程用户的UID和PID替换为本地用户的UID和PID。它可以用于身份验证等场景。
**系统能力**:SystemCapability.Communication.IPC.Core
......@@ -7350,7 +7345,7 @@ static resetCallingIdentity(): string
**示例:**
```
```ts
class Stub extends rpc.RemoteObject {
onRemoteMessageRequest(code, data, reply, option) {
let callingIdentity = rpc.IPCSkeleton.resetCallingIdentity();
......@@ -7365,7 +7360,7 @@ static resetCallingIdentity(): string
static restoreCallingIdentity(identity: string): void
将远程用户的UID和PID替换为本地用户的UID和PID。它可以用于身份验证等场景。
静态方法,将远程用户的UID和PID替换为本地用户的UID和PID。它可以用于身份验证等场景。
**系统能力**:SystemCapability.Communication.IPC.Core
......@@ -7377,7 +7372,7 @@ static restoreCallingIdentity(identity: string): void
**示例:**
```
```ts
class Stub extends rpc.RemoteObject {
onRemoteMessageRequest(code, data, reply, option) {
let callingIdentity = null;
......@@ -7392,14 +7387,13 @@ static restoreCallingIdentity(identity: string): void
}
```
### setCallingIdentity<sup>(deprecated)</sup>
>从API version 9 开始不再维护,建议使用[restoreCallingIdentity](#restorecallingidentity9)类替代。
static setCallingIdentity(identity: string): boolean
将UID和PID恢复为远程用户的UID和PID。它通常在使用resetCallingIdentity后调用,需要resetCallingIdentity返回的远程用户的UID和PID。
静态方法,将UID和PID恢复为远程用户的UID和PID。它通常在使用resetCallingIdentity后调用,需要resetCallingIdentity返回的远程用户的UID和PID。
**系统能力**:SystemCapability.Communication.IPC.Core
......@@ -7413,11 +7407,11 @@ static setCallingIdentity(identity: string): boolean
| 类型 | 说明 |
| ------- | ----------------------------------------- |
| boolean | 如果操作成功,则返回true;否则返回false。 |
| boolean | true:设置成功,false:设置失败。|
**示例:**
```
```ts
class Stub extends rpc.RemoteObject {
onRemoteMessageRequest(code, data, reply, option) {
let callingIdentity = null;
......@@ -7433,7 +7427,6 @@ static setCallingIdentity(identity: string): boolean
}
```
## RemoteObject
实现远程对象。服务提供者必须继承此类。
......@@ -7476,11 +7469,11 @@ sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: Me
| 类型 | 说明 |
| ------- | --------------------------------------------- |
| boolean | 返回一个布尔值,true表示成功,false表示失败。 |
| boolean | true:发送成功,false:发送失败。|
**示例:**
```
```ts
class MyDeathRecipient {
onRemoteDied() {
console.log("server died");
......@@ -7519,7 +7512,6 @@ sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: Me
reply.reclaim();
```
### sendRequest<sup>8+(deprecated)</sup>
>从API version 9 开始不再维护,建议使用[sendMessageRequest](#sendmessagerequest9)类替代。
......@@ -7547,7 +7539,7 @@ sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: Me
**示例:**
```
```ts
class MyDeathRecipient {
onRemoteDied() {
console.log("server died");
......@@ -7617,7 +7609,7 @@ sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence,
**示例:**
```
```ts
class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) {
super(descriptor);
......@@ -7648,7 +7640,6 @@ sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence,
});
```
### sendMessageRequest<sup>9+</sup>
sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence, options: MessageOption, callback: AsyncCallback&lt;RequestResult&gt;): void
......@@ -7669,7 +7660,7 @@ sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence,
**示例:**
```
```ts
class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) {
super(descriptor);
......@@ -7697,7 +7688,6 @@ sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence,
testRemoteObject.sendMessageRequest(1, data, reply, option, sendRequestCallback);
```
### sendRequest<sup>8+(deprecated)</sup>
>从API version 9 开始不再维护,建议使用[sendMessageRequest](#sendmessagerequest9)类替代。
......@@ -7720,7 +7710,7 @@ sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: Me
**示例:**
```
```ts
class MyDeathRecipient {
onRemoteDied() {
console.log("server died");
......@@ -7762,7 +7752,6 @@ sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: Me
testRemoteObject.sendRequest(1, data, reply, option, sendRequestCallback);
```
### onRemoteRequest<sup>8+(deprecated)</sup>
>从API version 9 开始不再维护,建议使用[onRemoteMessageRequest](#onremotemessagerequest9)类替代。
......@@ -7786,11 +7775,11 @@ sendMessageRequest请求的响应处理函数,服务端在该函数里处理
| 类型 | 说明 |
| ------- | ----------------------------------------- |
| boolean | 如果操作成功,则返回true;否则返回false。 |
| boolean | true:操作成功,false:操作失败。|
**示例:**
```ets
```ts
class MyDeathRecipient {
onRemoteDied() {
console.log("server died");
......@@ -7847,12 +7836,12 @@ sendMessageRequest请求的响应处理函数,服务端在该函数里同步
| 类型 | 说明 |
| ----------------- | ---------------------------------------------------------------------------------------------- |
| boolean | 若在onRemoteMessageRequest中同步地处理请求,则返回一个布尔值:操作成功,则返回true;否则返回false。 |
| boolean | 若在onRemoteMessageRequest中同步地处理请求,则返回一个布尔值:true:操作成功,false:操作失败。 |
| Promise\<boolean> | 若在onRemoteMessageRequest中异步地处理请求,则返回一个Promise对象。 |
**重载onRemoteMessageRequest方法同步处理请求示例:**
```ets
```ts
class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) {
super(descriptor);
......@@ -7872,7 +7861,7 @@ sendMessageRequest请求的响应处理函数,服务端在该函数里同步
**重载onRemoteMessageRequest方法异步处理请求示例:**
```ets
```ts
class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) {
super(descriptor);
......@@ -7895,7 +7884,7 @@ sendMessageRequest请求的响应处理函数,服务端在该函数里同步
**同时重载onRemoteMessageRequest和onRemoteRequest方法同步处理请求示例:**
```ets
```ts
class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) {
super(descriptor);
......@@ -7926,7 +7915,7 @@ sendMessageRequest请求的响应处理函数,服务端在该函数里同步
**同时重载onRemoteMessageRequest和onRemoteRequest方法异步处理请求示例:**
```ets
```ts
class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) {
super(descriptor);
......@@ -7957,7 +7946,6 @@ sendMessageRequest请求的响应处理函数,服务端在该函数里同步
}
```
### getCallingUid
getCallingUid(): number
......@@ -7973,7 +7961,7 @@ getCallingUid(): number
**示例:**
```
```ts
class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) {
super(descriptor);
......@@ -7999,7 +7987,7 @@ getCallingPid(): number
**示例:**
```
```ts
class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) {
super(descriptor);
......@@ -8013,7 +8001,7 @@ getCallingPid(): number
getLocalInterface(descriptor: string): IRemoteBroker
查询接口。
查询接口描述符的字符串
**系统能力**:SystemCapability.Communication.IPC.Core
......@@ -8032,7 +8020,7 @@ getLocalInterface(descriptor: string): IRemoteBroker
**示例:**
```
```ts
class MyDeathRecipient {
onRemoteDied() {
console.log("server died");
......@@ -8057,7 +8045,6 @@ getLocalInterface(descriptor: string): IRemoteBroker
}
```
### queryLocalInterface<sup>(deprecated)</sup>
>从API version 9 开始不再维护,建议使用[getLocalInterface](#getlocalinterface9)类替代。
......@@ -8082,7 +8069,7 @@ queryLocalInterface(descriptor: string): IRemoteBroker
**示例:**
```
```ts
class MyDeathRecipient {
onRemoteDied() {
console.log("server died");
......@@ -8106,7 +8093,6 @@ queryLocalInterface(descriptor: string): IRemoteBroker
let broker = testRemoteObject.queryLocalInterface("testObject");
```
### getDescriptor<sup>9+</sup>
getDescriptor(): string
......@@ -8131,7 +8117,7 @@ getDescriptor(): string
**示例:**
```
```ts
class MyDeathRecipient {
onRemoteDied() {
console.log("server died");
......@@ -8157,7 +8143,6 @@ getDescriptor(): string
console.log("RpcServer: descriptor is: " + descriptor);
```
### getInterfaceDescriptor<sup>(deprecated)</sup>
>从API version 9 开始不再维护,建议使用[getDescriptor](#getdescriptor9)类替代。
......@@ -8176,7 +8161,7 @@ getInterfaceDescriptor(): string
**示例:**
```
```ts
class MyDeathRecipient {
onRemoteDied() {
console.log("server died");
......@@ -8201,7 +8186,6 @@ getInterfaceDescriptor(): string
console.log("RpcServer: descriptor is: " + descriptor);
```
### modifyLocalInterface<sup>9+</sup>
modifyLocalInterface(localInterface: IRemoteBroker, descriptor: string): void
......@@ -8217,10 +8201,9 @@ modifyLocalInterface(localInterface: IRemoteBroker, descriptor: string): void
| localInterface | IRemoteBroker | 是 | 将与描述符绑定的IRemoteBroker对象。 |
| descriptor | string | 是 | 用于与IRemoteBroker对象绑定的描述符。 |
**示例:**
```
```ts
class MyDeathRecipient {
onRemoteDied() {
console.log("server died");
......@@ -8267,7 +8250,7 @@ attachLocalInterface(localInterface: IRemoteBroker, descriptor: string): void
**示例:**
```
```ts
class MyDeathRecipient {
onRemoteDied() {
console.log("server died");
......@@ -8294,28 +8277,26 @@ attachLocalInterface(localInterface: IRemoteBroker, descriptor: string): void
let testRemoteObject = new TestRemoteObject("testObject");
```
## Ashmem<sup>8+</sup>
提供与匿名共享内存对象相关的方法,包括创建、关闭、映射和取消映射Ashmem、从Ashmem读取数据和写入数据、获取Ashmem大小、设置Ashmem保护。
映射内存保护类型:
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.IPC.Core。
| 名称 | 值 | 说明 |
映射内存保护类型:
| 名称 | 默认值 | 说明 |
| ---------- | --- | ------------------ |
| PROT_EXEC | 4 | 映射的内存可执行 |
| PROT_NONE | 0 | 映射的内存不可访问 |
| PROT_READ | 1 | 映射的内存可读 |
| PROT_WRITE | 2 | 映射的内存可写 |
### create<sup>9+</sup>
static create(name: string, size: number): Ashmem
根据指定的名称和大小创建Ashmem对象。
静态方法,根据指定的名称和大小创建Ashmem对象。
**系统能力**:SystemCapability.Communication.IPC.Core
......@@ -8332,10 +8313,9 @@ static create(name: string, size: number): Ashmem
| ------ | ---------------------------------------------- |
| Ashmem | 返回创建的Ashmem对象;如果创建失败,返回null。 |
**示例:**
```
```ts
let ashmem;
try {
ashmem = rpc.Ashmem.create("ashmem", 1024*1024);
......@@ -8347,14 +8327,13 @@ static create(name: string, size: number): Ashmem
console.log("RpcTest: get ashemm by create : " + ashmem + " size is : " + size);
```
### createAshmem<sup>8+(deprecated)</sup>
>从API version 9 开始不再维护,建议使用[create](#create9)类替代。
static createAshmem(name: string, size: number): Ashmem
根据指定的名称和大小创建Ashmem对象。
静态方法,根据指定的名称和大小创建Ashmem对象。
**系统能力**:SystemCapability.Communication.IPC.Core
......@@ -8373,18 +8352,17 @@ static createAshmem(name: string, size: number): Ashmem
**示例:**
```
```ts
let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024);
let size = ashmem.getAshmemSize();
console.log("RpcTest: get ashemm by createAshmem : " + ashmem + " size is : " + size);
```
### create<sup>9+</sup>
static create(ashmem: Ashmem): Ashmem
通过复制现有Ashmem对象的文件描述符(fd)来创建Ashmem对象。两个Ashmem对象指向同一个共享内存区域。
静态方法,通过复制现有Ashmem对象的文件描述符(fd)来创建Ashmem对象。两个Ashmem对象指向同一个共享内存区域。
**系统能力**:SystemCapability.Communication.IPC.Core
......@@ -8403,7 +8381,7 @@ static create(ashmem: Ashmem): Ashmem
**示例:**
```
```ts
let ashmem2;
try {
let ashmem = rpc.Ashmem.create("ashmem", 1024*1024);
......@@ -8416,14 +8394,13 @@ static create(ashmem: Ashmem): Ashmem
console.log("RpcTest: get ashemm by create : " + ashmem2 + " size is : " + size);
```
### createAshmemFromExisting<sup>8+(deprecated)</sup>
>从API version 9 开始不再维护,建议使用[create](#create9)类替代。
static createAshmemFromExisting(ashmem: Ashmem): Ashmem
通过复制现有Ashmem对象的文件描述符(fd)来创建Ashmem对象。两个Ashmem对象指向同一个共享内存区域。
静态方法,通过复制现有Ashmem对象的文件描述符(fd)来创建Ashmem对象。两个Ashmem对象指向同一个共享内存区域。
**系统能力**:SystemCapability.Communication.IPC.Core
......@@ -8441,14 +8418,13 @@ static createAshmemFromExisting(ashmem: Ashmem): Ashmem
**示例:**
```
```ts
let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024);
let ashmem2 = rpc.Ashmem.createAshmemFromExisting(ashmem);
let size = ashmem2.getAshmemSize();
console.log("RpcTest: get ashemm by createAshmemFromExisting : " + ashmem2 + " size is : " + size);
```
### closeAshmem<sup>8+</sup>
closeAshmem(): void
......@@ -8459,12 +8435,11 @@ closeAshmem(): void
**示例:**
```
```ts
let ashmem = rpc.Ashmem.create("ashmem", 1024*1024);
ashmem.closeAshmem();
```
### unmapAshmem<sup>8+</sup>
unmapAshmem(): void
......@@ -8475,12 +8450,11 @@ unmapAshmem(): void
**示例:**
```
```ts
let ashmem = rpc.Ashmem.create("ashmem", 1024*1024);
ashmem.unmapAshmem();
```
### getAshmemSize<sup>8+</sup>
getAshmemSize(): number
......@@ -8497,13 +8471,12 @@ getAshmemSize(): number
**示例:**
```
```ts
let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024);
let size = ashmem.getAshmemSize();
console.log("RpcTest: get ashmem is " + ashmem + " size is : " + size);
```
### mapTypedAshmem<sup>9+</sup>
mapTypedAshmem(mapType: number): void
......@@ -8528,7 +8501,7 @@ mapTypedAshmem(mapType: number): void
**示例:**
```
```ts
let ashmem = rpc.Ashmem.create("ashmem", 1024*1024);
try {
ashmem.mapTypedAshmem(ashmem.PROT_READ | ashmem.PROT_WRITE);
......@@ -8538,7 +8511,6 @@ mapTypedAshmem(mapType: number): void
}
```
### mapAshmem<sup>8+(deprecated)</sup>
>从API version 9 开始不再维护,建议使用[mapTypedAshmem](#maptypedashmem9)类替代。
......@@ -8559,17 +8531,16 @@ mapAshmem(mapType: number): boolean
| 类型 | 说明 |
| ------- | ----------------------------------------- |
| boolean | 如果映射成功,则返回true;否则返回false。 |
| boolean | true:映射成功,false:映射失败。|
**示例:**
```
```ts
let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024);
let mapReadAndWrite = ashmem.mapAshmem(ashmem.PROT_READ | ashmem.PROT_WRITE);
console.log("RpcTest: map ashmem result is : " + mapReadAndWrite);
```
### mapReadWriteAshmem<sup>9+</sup>
mapReadWriteAshmem(): void
......@@ -8588,7 +8559,7 @@ mapReadWriteAshmem(): void
**示例:**
```
```ts
let ashmem = rpc.Ashmem.create("ashmem", 1024*1024);
try {
ashmem.mapReadWriteAshmem();
......@@ -8598,7 +8569,6 @@ mapReadWriteAshmem(): void
}
```
### mapReadAndWriteAshmem<sup>8+(deprecated)</sup>
>从API version 9 开始不再维护,建议使用[mapReadWriteAshmem](#mapreadwriteashmem9)类替代。
......@@ -8613,17 +8583,16 @@ mapReadAndWriteAshmem(): boolean
| 类型 | 说明 |
| ------- | ----------------------------------------- |
| boolean | 如果映射成功,则返回true;否则返回false。 |
| boolean | true:映射成功,false:映射失败。|
**示例:**
```
```ts
let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024);
let mapResult = ashmem.mapReadAndWriteAshmem();
console.log("RpcTest: map ashmem result is : " + mapResult);
```
### mapReadonlyAshmem<sup>9+</sup>
mapReadonlyAshmem(): void
......@@ -8642,7 +8611,7 @@ mapReadonlyAshmem(): void
**示例:**
```
```ts
let ashmem = rpc.Ashmem.create("ashmem", 1024*1024);
try {
ashmem.mapReadonlyAshmem();
......@@ -8652,7 +8621,6 @@ mapReadonlyAshmem(): void
}
```
### mapReadOnlyAshmem<sup>8+(deprecated)</sup>
>从API version 9 开始不再维护,建议使用[mapReadonlyAshmem](#mapreadonlyashmem9)类替代。
......@@ -8667,17 +8635,16 @@ mapReadOnlyAshmem(): boolean
| 类型 | 说明 |
| ------- | ----------------------------------------- |
| boolean | 如果映射成功,则返回true;否则返回false。 |
| boolean | true:映射成功,false:映射失败。|
**示例:**
```
```ts
let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024);
let mapResult = ashmem.mapReadOnlyAshmem();
console.log("RpcTest: Ashmem mapReadOnlyAshmem result is : " + mapResult);
```
### setProtectionType<sup>9+</sup>
setProtectionType(protectionType: number): void
......@@ -8702,7 +8669,7 @@ setProtectionType(protectionType: number): void
**示例:**
```
```ts
let ashmem = rpc.Ashmem.create("ashmem", 1024*1024);
try {
ashmem.setProtection(ashmem.PROT_READ);
......@@ -8712,7 +8679,6 @@ setProtectionType(protectionType: number): void
}
```
### setProtection<sup>8+(deprecated)</sup>
>从API version 9 开始不再维护,建议使用[setProtectionType](#setprotectiontype9)类替代。
......@@ -8733,17 +8699,16 @@ setProtection(protectionType: number): boolean
| 类型 | 说明 |
| ------- | ----------------------------------------- |
| boolean | 如果设置成功,则返回true;否则返回false。 |
| boolean | true:设置成功,false:设置失败。|
**示例:**
```
```ts
let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024);
let result = ashmem.setProtection(ashmem.PROT_READ);
console.log("RpcTest: Ashmem setProtection result is : " + result);
```
### writeAshmem<sup>9+</sup>
writeAshmem(buf: number[], size: number, offset: number): void
......@@ -8770,7 +8735,7 @@ writeAshmem(buf: number[], size: number, offset: number): void
**示例:**
```
```ts
let ashmem = rpc.Ashmem.create("ashmem", 1024*1024);
ashmem.mapReadWriteAshmem();
var ByteArrayVar = [1, 2, 3, 4, 5];
......@@ -8782,7 +8747,6 @@ writeAshmem(buf: number[], size: number, offset: number): void
}
```
### writeToAshmem<sup>8+(deprecated)</sup>
>从API version 9 开始不再维护,建议使用[writeAshmem](#writeashmem9)类替代。
......@@ -8805,11 +8769,11 @@ writeToAshmem(buf: number[], size: number, offset: number): boolean
| 类型 | 说明 |
| ------- | ----------------------------------------------------------------------------------------- |
| boolean | 如果数据写入成功,则返回true;在其他情况下,如数据写入越界或未获得写入权限,则返回false。 |
| boolean | true:如果数据写入成功,false:在其他情况下,如数据写入越界或未获得写入权限。。 |
**示例:**
```
```ts
let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024);
let mapResult = ashmem.mapReadAndWriteAshmem();
console.info("RpcTest map ashmem result is " + mapResult);
......@@ -8818,7 +8782,6 @@ writeToAshmem(buf: number[], size: number, offset: number): boolean
console.log("RpcTest: write to Ashmem result is : " + writeResult);
```
### readAshmem<sup>9+</sup>
readAshmem(size: number, offset: number): number[]
......@@ -8850,7 +8813,7 @@ readAshmem(size: number, offset: number): number[]
**示例:**
```
```ts
let ashmem = rpc.Ashmem.create("ashmem", 1024*1024);
ashmem.mapReadWriteAshmem();
var ByteArrayVar = [1, 2, 3, 4, 5];
......@@ -8864,7 +8827,6 @@ readAshmem(size: number, offset: number): number[]
}
```
### readFromAshmem<sup>8+(deprecated)</sup>
>从API version 9 开始不再维护,建议使用[readAshmem](#readashmem9)类替代。
......@@ -8890,7 +8852,7 @@ readFromAshmem(size: number, offset: number): number[]
**示例:**
```
```ts
let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024);
let mapResult = ashmem.mapReadAndWriteAshmem();
console.info("RpcTest map ashmem result is " + mapResult);
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册