提交 7a07062e 编写于 作者: H HelloCrease

Merge branch 'OpenHarmony-3.2-Release' of https://gitee.com/HelloCrease/docs...

Merge branch 'OpenHarmony-3.2-Release' of https://gitee.com/HelloCrease/docs into OpenHarmony-3.2-Release
......@@ -3,7 +3,7 @@
## Overview
[Context](../reference/apis/js-apis-inner-application-context.md) is the context of an object in an application. It provides basic information about the application, for example, **resourceManager**, **applicationInfo**, **dir** (application development path), and **area** (encrypted area). It also provides basic methods such as **createBundleContext()** and **getApplicationContext()**. The UIAbility component and ExtensionAbility derived class components have their own **Context** classes, for example, the base class **Context**, **ApplicationContext**, **AbilityStageContext**, **UIAbilityContext**, **ExtensionContext**, and **ServiceExtensionContext**.
[Context](../reference/apis/js-apis-inner-application-context.md) is the context of an object in an application. It provides basic information about the application, for example, **resourceManager**, **applicationInfo**, **dir** (application development path), and **area** (encrypted level). It also provides basic methods such as **createBundleContext()** and **getApplicationContext()**. The UIAbility component and ExtensionAbility derived class components have their own **Context** classes, for example, the base class **Context**, **ApplicationContext**, **AbilityStageContext**, **UIAbilityContext**, **ExtensionContext**, and **ServiceExtensionContext**.
- The figure below illustrates the inheritance relationship of contexts.
......@@ -71,7 +71,7 @@ This topic describes how to use the context in the following scenarios:
- [Obtaining the Application Development Path](#obtaining-the-application-development-path)
- [Obtaining and Modifying Encryption Areas](#obtaining-and-modifying-encryption-areas)
- [Obtaining and Modifying Encryption Levels](#obtaining-and-modifying-encryption-levels)
- [Creating Context of Another Application or Module](#creating-context-of-another-application-or-module)
- [Subscribing to UIAbility Lifecycle Changes in a Process](#subscribing-to-uiability-lifecycle-changes-in-a-process)
......@@ -144,19 +144,19 @@ export default class EntryAbility extends UIAbility {
>
> The sample code obtains the sandbox path of the application development path. The absolute path can be obtained by running the **find / -name <fileName>** command in the hdc shell after file creation or modification.
### Obtaining and Modifying Encryption Areas
### Obtaining and Modifying Encryption Levels
Encrypting application files enhances data security by preventing files from unauthorized access. Different application files require different levels of protection. For private files, such as alarms and wallpapers, the application must place them in the device-level encryption area (EL1) to ensure that they can be accessed before the user enters the password. For sensitive files, such as personal privacy data, the application must place them in the user-level encryption area (EL2).
Encrypting application files enhances data security by preventing files from unauthorized access. Different application files require different levels of protection. For private files, such as alarms and wallpapers, the application must place them in a directory with the device-level encryption (EL1) to ensure that they can be accessed before the user enters the password. For sensitive files, such as personal privacy data, the application must place them in a directory with the user-level encryption (EL2).
In practice, you need to select a proper encrypted area based on scenario-specific requirements to protect application data security. The proper use of EL1 and the EL2 can efficiently improve the security.
In practice, you need to select a proper encrypted level based on scenario-specific requirements to protect application data security. The proper use of EL1 and the EL2 can efficiently improve the security.
> **NOTE**
>
> - AreaMode.EL1: device-level encryption area, which is accessible after the device is powered on.
> - AreaMode.EL1: device-level encryption. Directories with this encryption level are accessible after the device is powered on.
>
> - AreaMode.EL2: user-level encryption area, which is accessible only after the device is powered on and the password is entered (for the first time).
> - AreaMode.EL2: user-level encryption. Directories with this encryption level are accessible only after the device is powered on and the password is entered (for the first time).
You can obtain and set the encryption area by reading and writing the [area attribute in Context](../reference/apis/js-apis-inner-application-context.md).
You can obtain and set the encryption level by reading and writing the [area attribute in Context](../reference/apis/js-apis-inner-application-context.md).
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
......
......@@ -60,7 +60,7 @@ For the complete list of APIs and example code, see [Network Sharing](../referen
4. Return the callback for successfully starting network sharing.
```js
// Import the sharing namespace from @ohos.net.sharing.
// Import the sharing namespace from @ohos.net.sharing.
import sharing from '@ohos.net.sharing'
// Subscribe to network sharing state changes.
......@@ -85,7 +85,7 @@ sharing.startSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => {
4. Return the callback for successfully stopping network sharing.
```js
// Import the sharing namespace from @ohos.net.sharing.
// Import the sharing namespace from @ohos.net.sharing.
import sharing from '@ohos.net.sharing'
// Subscribe to network sharing state changes.
......@@ -110,7 +110,7 @@ sharing.stopSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => {
4. Call **stopSharing** to stop network sharing of the specified type and clear the data volume of network sharing.
```js
// Import the sharing namespace from @ohos.net.sharing.
// Import the sharing namespace from @ohos.net.sharing.
import sharing from '@ohos.net.sharing'
// Call startSharing to start network sharing of the specified type.
......
......@@ -87,81 +87,81 @@ The implementation is similar for UDPSocket and TCPSocket connections. The follo
7. Enable the TCPSocket connection to be automatically closed after use.
```js
import socket from '@ohos.net.socket'
// Create a TCPSocket object.
let tcp = socket.constructTCPSocketInstance();
// Subscribe to TCPSocket connection events.
tcp.on('message', value => {
console.log("on message")
let buffer = value.message
let dataView = new DataView(buffer)
let str = ""
for (let i = 0;i < dataView.byteLength; ++i) {
str += String.fromCharCode(dataView.getUint8(i))
}
console.log("on connect received:" + str)
});
tcp.on('connect', () => {
console.log("on connect")
});
tcp.on('close', () => {
console.log("on close")
});
// Bind the local IP address and port number.
let bindAddress = {
address: '192.168.xx.xx',
port: 1234, // Bound port, for example, 1234.
family: 1
};
tcp.bind(bindAddress, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
// Set up a connection to the specified IP address and port number.
let connectAddress = {
address: '192.168.xx.xx',
port: 5678, // Connection port, for example, 5678.
family: 1
};
tcp.connect({
address: connectAddress, timeout: 6000
}, err => {
if (err) {
console.log('connect fail');
return;
}
console.log('connect success');
// Send data.
tcp.send({
data: 'Hello, server!'
}, err => {
if (err) {
console.log('send fail');
return;
}
console.log('send success');
})
});
});
// Enable the TCPSocket connection to be automatically closed after use. Then, disable listening for TCPSocket connection events.
setTimeout(() => {
tcp.close((err) => {
console.log('close socket.')
});
tcp.off('message');
tcp.off('connect');
tcp.off('close');
}, 30 * 1000);
```
```js
import socket from '@ohos.net.socket'
// Create a TCPSocket object.
let tcp = socket.constructTCPSocketInstance();
// Subscribe to TCPSocket connection events.
tcp.on('message', value => {
console.log("on message")
let buffer = value.message
let dataView = new DataView(buffer)
let str = ""
for (let i = 0; i < dataView.byteLength; ++i) {
str += String.fromCharCode(dataView.getUint8(i))
}
console.log("on connect received:" + str)
});
tcp.on('connect', () => {
console.log("on connect")
});
tcp.on('close', () => {
console.log("on close")
});
// Bind the local IP address and port number.
let bindAddress = {
address: '192.168.xx.xx',
port: 1234, // Bound port, for example, 1234.
family: 1
};
tcp.bind(bindAddress, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
// Set up a connection to the specified IP address and port number.
let connectAddress = {
address: '192.168.xx.xx',
port: 5678, // Connection port, for example, 5678.
family: 1
};
tcp.connect({
address: connectAddress, timeout: 6000
}, err => {
if (err) {
console.log('connect fail');
return;
}
console.log('connect success');
// Send data.
tcp.send({
data: 'Hello, server!'
}, err => {
if (err) {
console.log('send fail');
return;
}
console.log('send success');
})
});
});
// Enable the TCPSocket connection to be automatically closed after use. Then, disable listening for TCPSocket connection events.
setTimeout(() => {
tcp.close((err) => {
console.log('close socket.')
});
tcp.off('message');
tcp.off('connect');
tcp.off('close');
}, 30 * 1000);
```
## Implementing encrypted data transmission over TLSSocket connections
......@@ -184,6 +184,8 @@ TLSSocket connection process on the client:
7. Enable the TLSSocket connection to be automatically closed after use.
```js
import socket from '@ohos.net.socket'
// Create a TLSSocket connection (for two-way authentication).
let tlsTwoWay = socket.constructTLSSocketInstance();
......@@ -206,7 +208,7 @@ tlsTwoWay.on('close', () => {
});
// Bind the local IP address and port number.
tlsTwoWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
tlsTwoWay.bind({ address: '192.168.xxx.xxx', port: xxxx, family: 1 }, err => {
if (err) {
console.log('bind fail');
return;
......@@ -278,7 +280,7 @@ tlsTwoWay.on('close', () => {
});
// Bind the local IP address and port number.
tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
tlsOneWay.bind({ address: '192.168.xxx.xxx', port: xxxx, family: 1 }, err => {
if (err) {
console.log('bind fail');
return;
......
......@@ -3,6 +3,10 @@
- [Development of Application Event Logging](hiappevent-guidelines.md)
- [Development of Performance Tracing](hitracemeter-guidelines.md)
- [Development of Distributed Call Chain Tracing](hitracechain-guidelines.md)
- [HiLog Development (Native)](hilog-guidelines.md)
- Error Management
- [Development of Error Manager](errormanager-guidelines.md)
- [Development of Application Recovery](apprecovery-guidelines.md)
- Log Management
- [Application Freeze (appfreeze) Log Analysis](appfreeze-guidelines.md)
- [Process Crash (cppcrash) Log Analysis](cppcrash-guidelines.md)
# Application Freeze (appfreeze) Log Analysis
## Introduction
Application freeze (appfreeze) means that an application does not respond to user operations (for example, clicking) within a given period of time. OpenHarmony provides a mechanism for detecting appfreeze faults and generates appfreeze logs for fault analysis.
> **NOTE**
>
> This guide applies only to applications in the stage model.
> Before using this guide, you must have basic knowledge about the JS applications, C++ program stacks, and application-related subsystems.
## How to Obtain
appfreeze log is a type of fault logs managed together with the native process crash, JS application crash, and system process crash logs . You can obtain the log in any of the following ways.
### Collecting Logs by Using Shell
appfreeze logs start with **appfreeze-** in **/data/log/faultlog/faultlogger/**.
The log files are named in the format of **appfreeze-application package name-application UID-time (seconds level)**.
![appfreeze_20230308145160](figures/appfreeze_20230308145160.png)
### Collecting Logs by Using DevEco Studio
DevEco Studio collects device fault logs and saves them to FaultLog.
The logs are displayed by the bundle name, fault, and time.
![appfreeze_20230308145161](figures/appfreeze_20230308145161.png)
### Collecting Logs by Using faultLogger APIs
The FaultLogger module provides APIs to query various fault information. For details, see [@ohos.faultLogger](../reference/apis/js-apis-faultLogger.md).
## appfreeze Detection
Currently, appfreeze detection supports the fault types listed in the following table.
| Fault Type| Description|
| -------- | -------- |
| THREAD_BLOCK_6S | The application main thread times out due to a suspension.|
| APPLICATION_BLOCK_INPUT | The user input response times out.|
| LIFECYCLE_TIMEOUT | Ability lifecycle switching times out.|
| APP_LIFECYCLE_TIMEOUT | Application lifecycle switching times out.|
### Application Main Thread Timeout
If this fault occurs, the main thread of the current application is suspended or too many tasks are executed, affecting task execution smoothness and experience.
Such a fault can be detected as follows: The watchdog thread of the application periodically inserts an activation detection subthread to the main thread and inserts a timeout reporting subthread to its own thread. If activation detection is not executed within 3 seconds, the THREAD_BLOCK_3S event is reported; if activation detection is not executed within 6 seconds, the THREAD_BLOCK_6S event is reported. The two events together form an appfreeze log. The following figure shows the working principle.
![appfreeze_20230308145163](figures/appfreeze_20230308145163.png)
### User Input Response Timeout
This fault affects user experience. If this fault occurs, the system does not respond to a click event within 10 seconds.
Such a fault can be detected as follows: When a user clicks a certain button of the application, the input system sends a click event to the application. If the input system does not receive a response from the application within 10 seconds, a fault event is reported. The following figure shows the working principle.
![appfreeze_20230308145162](figures/appfreeze_20230308145162.png)
### Lifecycle Switching Timeout
This fault refers to an ability lifecycle switching timeout (LIFECYCLE\_TIMEOUT) or an application lifecycle switching timeout (APP\_LIFECYCLE\_TIMEOUT).
The fault occurs during lifecycle switching and affects the switchover between abilities in the current application or the switchover between applications.
Such a fault can be detected as follows: Upon the start of a lifecycle switchover process, the main thread inserts a timeout task to the watchdog thread, and then removes the timeout task when the lifecycle switchover is complete. If the timeout duration expires, a fault event is reported.
![appfreeze_20230308145164](figures/appfreeze_20230308145164.png)
The timeout duration varies according to the lifecycle.
| Lifecycle| Timeout Duration|
| -------- | -------- |
| Load | 10s |
| Terminate | 10s |
| Connect | 3s |
| Disconnect | 0.5s |
| Foreground | 5s |
| Background | 3s |
## appfreeze Log Analysis
To identify the cause of appfreeze, analyze the appfreeze logs together with HiLog logs.
The following example uses main tread suspension as an example to illustrate how to conduct log analysis. You can treat other types of faults in a similar way.
appfreeze logs are divided into several parts, including header information, and general and specific information in the body.
### Log Header Information
| Field| Description|
| -------- | -------- |
| Reason | Reason why the application does not respond. For details, see [appfreeze Detection](#appfreeze-detection).|
| PID | PID of the failed process, which can be used to search for related process information in the log.|
| PACKAGE_NAME | Application package name.|
![appfreeze_20230310105865](figures/appfreeze_20230310105865.png)
### General Information in the Log Body
General information is present in all logs. It contains the fields listed in the following table. You can search for these fields to locate the related information in the log.
| Field| Description|
| -------- | -------- |
| EVENTNAME | One or more fault events that constitute the cause of main thread suspension.|
| TIMESTAMP | Time when the fault event reported. You can narrow down the time range for viewing HiLog logs based on the timeout duration described in [appfreeze Detection](#appfreeze-detection).|
| PID | PID of the failed process, which can be used with the timestamp and timeout duration to search for related process information in the log.|
| PACKAGE_NAME | Application package name.|
| MSG | Dump information or description of the fault.|
| OpenStacktraceCatcher | Stack trace information of the process.|
| BinderCatcher | Information about IPC calls between a process and other system processes, such as the call waiting time.|
| PeerBinder Stacktrace | Information about stack trace of the peer process.|
| cpuusage | CPU usage of the device.|
| memory | Memory usage of the process.|
The following is an example process stack of OpenStacktraceCatcher.
In this example, when the stack surface window sends events through IPC, the process is stuck in the IPC communication phase.
![appfreeze_20230310105869](figures/appfreeze_20230310105869.png)
Example BinderCatcher information:
In the following example, process 1561 sends an IPC request to process 685 but does not receive any response within 10 seconds.
![appfreeze_20230310105868](figures/appfreeze_20230310105868.png)
Example PeerBinder Stacktrace information:
The following example shows the stack information of process 685, which is suspended at the peer end.
![appfreeze_20230310105870](figures/appfreeze_20230310105870.png)
Example CPU usage information:
The following example shows the CPU usage information of the device.
![appfreeze_20230310105871](figures/appfreeze_20230310105871.png)
Example memory usage information:
The following example shows the memory usage information of the process.
![appfreeze_20230310105872](figures/appfreeze_20230310105872.png)
### Specific Information in the Log Body (Application Main Thread Timeout)
According to [Application Main Thread Timeout] (#application-main-thread-timeout), the log in which **Reason** is **THREAD\_BLOCK\_6S** consists of two parts: THREAD\_BLOCK\_3S and THREAD\_BLOCK\_6S. By comparing the two parts, you can determine whether the appfreeze is due to a suspension or an excess number of tasks.
THREAD\_BLOCK\_3S is followed by THREAD\_BLOCK\_6S in the log. You can use the **EVENTNAME** field to search for the locations of the two events in the log.
Both events contain the **MSG** field, which stores information about the processing queue of the main thread when the suspension occurs. Hence, you can view the status of the event processing queue of the main thread at the two time points.
The example log shows that the event carrying **05:06:18.145** in the low-priority queue is being processed, and it is present in both the THREAD_BLOCK_3S and THREAD_BLOCK_6S. This indicates that the main thread suspension is not caused by an excess number of tasks.
Because THREAD_BLOCK_6S indicates a main thread suspension, you only need to analyze the stack information of the main thread (the ID of the main thread is the same as the process ID). In the example log, the main thread stack is run in the JS through ArkUI and therefore it can be concluded that the suspension occurs in the JS. Because stack is present in both THREAD_BLOCK_3S and THREAD_BLOCK_6S in the same position, the JS suspension is not caused by an excess number of tasks.
THREAD_BLOCK_3S:
![appfreeze_20230310105866](figures/appfreeze_20230310105866.png)
THREAD_BLOCK_6S:
![appfreeze_20230310105867](figures/appfreeze_20230310105867.png)
Then, you can check for the code segment being executed on the application side based on the HiLog log.
Generally, you can view the [general information in the log body](#general-information-in-the-log-body) to check for the cause of the suspension, for example, IPC suspension, high CPU usage, memory leakage, or high memory usage.
### Specific Information in the Log Body (User Input Response Timeout)
If **Reason** is **APPLICATION\_BLOCK\_INPUT**, no response is received within 10 seconds after a user click.
You can find the event description in **MSG**.
For details, see [General Information in the Log Body](#general-information-in-the-log-body). Note that there is a high probability that the main thread is suspended in the case of no response to the user input. You can compare the stack and BinderCatcher information in two log records for further analysis. If there is no log record indicating a main thread suspension, a large number of other events may exist before the input event. This may not cause a main thread suspension but can probably result in no response to user input.
### Specific Information in the Log Body (Lifecycle Switching Timeout)
For a lifecycle switching timeout, **Reason** can be **LIFECYCLE\_TIMEOUT** or **APP\_LIFECYCLE\_TIMEOUT**.
**LIFECYCLE\_TIMEOUT** indicates a lifecycle switching timeout at the ability level, and **APP\_LIFECYCLE\_TIMEOUT** indicates a lifecycle switching timeout at the application level.
MSG indicates the lifecycle that encounters a timeout.
In this example, **LIFECYCLE\_TIMEOUT** indicates that the timeout occurs during switching of the ability to the background, and **APP\_LIFECYCLE\_TIMEOUT** indicates that the timeout occurs in the application termination phase. You can locate related HiLog logs according to the timeout duration described in [Lifecycle Switching Timeout] (#lifecycle-switching-timeout).
LIFECYCLE_TIMEOUT:
![appfreeze_20230310105873](figures/appfreeze_20230310105873.png)
APP_LIFECYCLE_TIMEOUT:
![appfreeze_20230310105874](figures/appfreeze_20230310105874.png)
For details about other log information, see [General Information in the Log Body](#general-information-in-the-log-body). Note that there is a high probability that the main thread is suspended during lifecycle switching. You can compare the stack and BinderCatcher information in two log records for further analysis.
......@@ -40,7 +40,9 @@ Fault management is an important way for applications to deliver a better user e
- Fault query is the process of calling APIs of [faultLogger](../reference/apis/js-apis-faultLogger.md) to obtain the fault information.
The figure below does not illustrate the time when [faultLogger](../reference/apis/js-apis-faultLogger.md) is called. You can refer to the [LastExitReason](../reference/apis/js-apis-app-ability-abilityConstant.md#abilityconstantlastexitreason) passed during application initialization to determine whether to call [faultLogger](../reference/apis/js-apis-faultLogger.md) to query information about the previous fault.
![Fault rectification process](./figures/fault_rectification.png)
It is recommended that you call [errorManager](../reference/apis/js-apis-app-ability-errorManager.md) to handle the exception. After the processing is complete, you can call the **saveAppState** API and restart the application.
If you do not register [ErrorObserver](../reference/apis/js-apis-inner-application-errorObserver.md) or enable application recovery, the application process will exit according to the default processing logic of the system. Users can restart the application from the home screen.
If you have enabled application recovery, the recovery framework first checks whether application state saving is supported and whether the application state saving is enabled. If so, the recovery framework invokes [onSaveState](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonsavestate) of the [Ability](../reference/apis/js-apis-app-ability-uiAbility.md). Finally, the application is restarted.
......
# cppcrash Log Analysis
## Introduction
A process crash refers to a C/C++ runtime crash. The FaultLogger module of OpenHarmony provides capabilities such as process crash detection, log collection, log storage, and log reporting, helping you to locate faults more effectively.
In this document, you'll be guided through how to implement process crash detection, crash log collection, and crash log analysis. Before getting started, make sure you have basic knowledge about C/C++ program stacks.
## Process Crash Detection
Process crash detection is implemented based on the Linux signal mechanism. Currently, C/C++ crash exception signals listed in the following table are supported.
| Signal Value| Signal| Description| Trigger Cause|
| ------ | --------- | --------------- | ------------------------------------------- |
| 4 | SIGILL | Invalid instruction | An invalid, incorrectly formatted, unknown, or privileged instruction is executed.|
| 5 | SIGTRAP | Breakpoint or trap | An exception occurs or a trap instruction is executed.|
| 6 | SIGABRT | Process abort | The process is aborted abnormally. Generally, this problem occurs if the process calls the `abort()` function of the standard function library.|
| 7 | SIGBUS | Illegal memory access | The process accesses an aligned or nonexistent physical address.|
| 8 | SIGFPE | Floating-point exception | The process performs an incorrect arithmetic operation, for example, a 0 divisor, floating point overflow, or integer overflow.|
| 11 | SIGSEGV | Invalid memory access | The process accesses an invalid memory reference.|
| 16 | SIGSTKFLT | Stack error | The processor performs an incorrect stack operation, such as a pop when the stack is empty or a push when the stack is full.|
| 31 | SIGSYS | Incorrect system call | An incorrect or invalid parameter is used in a system call.|
## Crash Log Collection
Process crash log is the fault log managed together with the app freeze and JS application crash logs by the FaultLogger module. You can collect process crash logs in any of the following ways:
### Collecting Logs by Using Shell
- Fault logs in the `/data/log/faultlog/faultlogger/` directory of the device. The log files are named in the format of `cppcrash-process name-process UID-time (seconds level)`. They contain only information such as the device name, system version, and process crash call stack.
![cppcrash-faultlogger-log](figures/20230407112159.png)
- Fault logs in the `/data/log/faultlog/temp/` directory of the device. The log files are named in the format of `cppcrash-process name-process PID-system timestamp (seconds level)`. In addition to basic information, they also contain information such as the stack memory and process maps at the time of process crash.
![cppcrash-temp-log](figures/20230407111853.png)
### Collecting Logs by Using DevEco Studio
DevEco Studio collects process crash logs from `/data/log/faultlog/faultlogger/` to FaultLog, where logs are displayed by process name, fault, and time.
![DevEco Studio cppcrash](figures/20230407112620.png)
### Collecting Logs by Using faultLogger APIs
The FaultLogger module provides APIs to query various fault information. For details, see [@ohos.faultLogger](../reference/apis/js-apis-faultLogger.md).
## Process Crash Log Analysis
### Log Format
The following is an example process crash log archived by DevEco Studio in FaultLog:
```
Generated by HiviewDFX@OpenHarmony
==================================================================
Device info:OpenHarmony 3.2 <- Device information
Build info:OpenHarmony 4.0.5.5 <- Version information
Module name:crasher_c <- Module name
Pid:1205 <- Process ID
Uid:0 <- User ID
Reason:Signal:SIGSEGV(SEGV_ACCERR)@0x0042d33d <- Exception information
Thread name:crasher <- Abnormal thread
#00 pc 0000332c /data/crasher(TriggerSegmentFaultException+15)(8bc37ceb8d6169e919d178fdc7f5449e) <- Call stack
#01 pc 000035c7 /data/crasher(ParseAndDoCrash+277)(8bc37ceb8d6169e919d178fdc7f5449e)
#02 pc 00003689 /data/crasher(main+39)(8bc37ceb8d6169e919d178fdc7f5449e)
#03 pc 000c3b08 /system/lib/ld-musl-arm.so.1(__libc_start_main+116)
#04 pc 000032f8 /data/crasher(_start_c+112)(8bc37ceb8d6169e919d178fdc7f5449e)
#05 pc 00003284 /data/crasher(_start+32)(8bc37ceb8d6169e919d178fdc7f5449e)
...
```
### Locating Faults Through Logs
1. Determine the faulty module and fault type based on fault logs.
Generally, you can identify the faulty module based on the crash process name and identify the crash cause based on the signal. Besides, you can restore the function call chain of the crash stack based on the method name in the stack.
In the example, **SIGSEGV** is thrown by the Linux kernel because of access to an invalid memory address. The problem occurs in the **TriggerSegmentFaultException** function.
In most scenarios, a crash is caused by the top layer of the crash stack, such as null pointer access and proactive program abort.
If the cause cannot be located through the call stack, you need to check for other faults, for example, memory corruption or stack overflow.
2. Use the addr2line tool of Linux to parse the code line number to restore the call stack at the time of process crash.
When using the addr2line tool to parse the code line number of the crash stack, make sure that binary files with debugging information is used. Generally, such files are generated during version build or application build.
Application binary files are located in DevEco Studio's temporary directory for application build, for example, `build/default/intermediates/libs`.
System binary files are stored in the directories listed below. For versions that are directly obtained, the binary files are archived in the image package.
```
\code root directory\out\product\lib.unstripped
\code root directory\out\product\exe.unstripped
```
You can run `apt-get install addr2line` to install the addr2line tool on Linux.
On On DevEco Studio, you can also use the llvm-addr2line tool archived in the SDK to parse code line numbers. The usage method is the same.
The following example shows how to use the addr2line tool to parse the code line number based on the offset address:
```
root:~/OpenHarmony/out/rk3568/exe.unstripped/hiviewdfx/faultloggerd$ addr2line -e crasher 0000332c
base/hiviewdfx/faultloggerd/tools/crasher/dfx_crasher.c:57
```
In this example, the crash is caused by assignment of a value to an unwritable area. It is in code line 57 in the **dfx_crasher.c** file. You can modify it to avoid the crash.
If the obtained code line number is seemingly incorrect, you can fine-tune the address (for example, subtract the address by 1) or disable some compilation optimization items. It is known that the obtained code line number may be incorrect when Link Time Optimization (LTO) is enabled.
en/application-dev/dfx/figures/20230407111853.png

7.5 KB

en/application-dev/dfx/figures/20230407112159.png

5.6 KB

en/application-dev/dfx/figures/20230407112620.png

216.2 KB

en/application-dev/dfx/figures/appfreeze_20230308145160.png

35.9 KB

en/application-dev/dfx/figures/appfreeze_20230308145161.png

581.7 KB

en/application-dev/dfx/figures/appfreeze_20230308145162.png

160.3 KB

en/application-dev/dfx/figures/appfreeze_20230308145163.png

134.5 KB

en/application-dev/dfx/figures/appfreeze_20230308145164.png

112.6 KB

en/application-dev/dfx/figures/appfreeze_20230310105865.png

153.9 KB

en/application-dev/dfx/figures/appfreeze_20230310105866.png

541.9 KB

en/application-dev/dfx/figures/appfreeze_20230310105867.png

534.4 KB

en/application-dev/dfx/figures/appfreeze_20230310105868.png

225.1 KB

en/application-dev/dfx/figures/appfreeze_20230310105869.png

503.6 KB

en/application-dev/dfx/figures/appfreeze_20230310105870.png

459.9 KB

en/application-dev/dfx/figures/appfreeze_20230310105871.png

305.9 KB

en/application-dev/dfx/figures/appfreeze_20230310105872.png

176.6 KB

en/application-dev/dfx/figures/appfreeze_20230310105873.png

61.9 KB

en/application-dev/dfx/figures/appfreeze_20230310105874.png

64.7 KB

# HiLog Development (Native)
## Introduction
HiLog is the log system of OpenHarmony that provides logging for the system framework, services, and applications to record information on user operations and system running status.
> **NOTE**
>
> This development guide is applicable only when you use Native APIs for application development. For details about the APIs, see [HiLog Native API Reference](../reference/native-apis/_hi_log.md).
## Available APIs
| API/Macro| Description|
| -------- | -------- |
| int OH_LOG_Print(LogType type, LogLevel level, unsigned int domain, const char *tag, const char *fmt, ...) | Outputs logs based on the specified log type, log level, service domain, log tag, and variable parameters determined by the format specifier and privacy identifier in the printf format.<br>Input arguments: See [Parameter Description](#parameter-description).<br>Output arguments: None<br>Return value: total number of bytes if log printing is successful; **-1** otherwise.|
| #define OH_LOG_DEBUG(type, ...) ((void)OH_LOG_Print((type), LOG_DEBUG, LOG_DOMAIN, LOG_TAG, \_*VA*ARGS__))| Outputs DEBUG logs. This is a function-like macro.|
| #define OH_LOG_INFO(type, ...) ((void)OH_LOG_Print((type), LOG_INFO, LOG_DOMAIN, LOG_TAG, \_*VA*ARGS__)) | Outputs INFO logs. This is a function-like macro.|
| #define OH_LOG_WARN(type, ...) ((void)OH_LOG_Print((type), LOG_WARN, LOG_DOMAIN, LOG_TAG, \_*VA*ARGS__)) | Outputs WARN logs. This is a function-like macro.|
| #define OH_LOG_ERROR(type, ...) ((void)OH_LOG_Print((type), LOG_ERROR, LOG_DOMAIN, LOG_TAG, \_*VA*ARGS__)) | Outputs ERROR logs. This is a function-like macro.|
| #define OH_LOG_FATAL(type, ...) ((void)OH_LOG_Print((type), LOG_FATAL, LOG_DOMAIN, LOG_TAG, \_*VA*ARGS__)) | Outputs FATAL logs. This is a function-like macro.|
| bool OH_LOG_IsLoggable(unsigned int domain, const char *tag, LogLevel level) | Checks whether logs of the specified service domain, tag, and level can be printed.<br>Input arguments: See [Parameter Description](#parameter-description).<br>Output arguments: none<br>Return value: **true** if the specified logs can be printed; **false** otherwise.|
## Parameter Description
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------------------------------------------------ |
| type | enum | Yes | Log printing type. The default value is **LOG_APP** for application logs.|
| level | enum | Yes | Log printing level. For details, see [Log Level](#loglevel).|
| domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**.<br>You can define the value as required. |
| tag | string | Yes | Log tag in the string format. You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.|
| fmt | string | Yes | Format string used to output logs in a specified format. It can contain several parameters, where the parameter type and privacy identifier are mandatory.<br>Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by **\<private>**.|
| args | any[] | Yes | Variable-length parameter list corresponding to the format string. The number and type of parameters must map to the identifier in the format string.|
## LogLevel
Log level.
| Name | Value | Description |
| ----- | ------ | ------------------------------------------------------------ |
| DEBUG | 3 | Log level used to record more detailed process information than INFO logs to help developers analyze service processes and locate faults.|
| INFO | 4 | Log level used to record key service process nodes and exceptions that occur during service running,<br>Log level used to record information about unexpected exceptions, such as network signal loss and login failure.<br>These logs should be recorded by the dominant module in the service to avoid repeated logging conducted by multiple invoked modules or low-level functions.|
| WARN | 5 | Log level used to record severe, unexpected faults that have little impact on users and can be rectified by the programs themselves or through simple operations.|
| ERROR | 6 | Log level used to record program or functional errors that affect the normal running or use of the functionality and can be fixed at a high cost, for example, by resetting data.|
| FATAL | 7 | Log level used to record program or functionality crashes that cannot be rectified.
## Development Example
1. Add the link of **libhilog_ndk.z.so** to **CMakeLists.txt**:
```
target_link_libraries(entry PUBLIC libhilog_ndk.z.so)
```
2. Include the **hilog** header file in the source file, and define the **domain** and **tag** macros.
```c++
#include "hilog/log.h"
```
```c++
#undef LOG_DOMAIN
#undef LOG_TAG
#define LOG_DOMAIN 0x3200 // Global domain, which identifies the service domain.
#define LOG_TAG "MY_TAG" // Global tag, which identifies the module log tag.
```
3. Print logs. For example, to print ERROR logs, use the following code:
```c++
OH_LOG_ERROR(LOG_APP, "Failed to visit %{private}s, reason:%{public}d.", url, errno);
```
4. View the output log information.
```
12-11 12:21:47.579 2695 2695 E A03200/MY_TAG: Failed to visit <private>, reason:11.
```
# FAQs
- [Ability Development](faqs-ability.md)
- [ArkUI Development](faqs-arkui.md)
- [Web Development](faqs-arkui-web.md)
- [Bundle Management Development](faqs-bundle-management.md)
- [Resource Manager Development](faqs-globalization.md)
- [Common Event and Notification Development](faqs-event-notification.md)
......@@ -16,4 +18,5 @@
- [Pan-Sensor Development](faqs-sensor.md)
- [Startup Development](faqs-startup.md)
- [Distributed Device Development](faqs-distributed-device-profile.md)
- [SDK Usage](faqs-sdk.md)
- [Usage of Third- and Fourth-Party Libraries](faqs-third-fourth-party-library.md)
# Web Development
## How does the return result of onUrlLoadIntercept affect onInterceptRequest in the \<Web> component?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
**Solution**
The operation that follows **onUrlLoadIntercept** is subject to its return result.
- If **true** is returned, the URL request is intercepted.
- If **false** is returned , the **onInterceptRequest** callback is performed.
**Reference**
[onUrlloadIntercept](../reference/arkui-ts/ts-basic-components-web.md#onurlloadinterceptdeprecated)
## What should I do if the onKeyEvent event of the \<Web> component is not triggered as expected?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
**Problem**
The **onKeyEvent** event is set for the **\<Web>** component to listen for keyboard events. However, it is not triggered when a key is pressed or lifted.
**Solution**
Currently, the **\<Web>** component does not support the **onKeyEvent** event. To listen for keyboard events for the **\<Web>** component, you can use the **onInterceptKeyEvent** callback function.
**Reference**
[onInterceptKeyEvent](../reference/arkui-ts/ts-basic-components-web.md#oninterceptkeyevent9)
## What should I do if page loading fails when onInterceptRequest is used to intercept URLs and return the custom HTML file?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
**Problem**
The **onInterceptRequest** API intercepts URLs specified by **src** and returns the custom HTML file. However, the content in the **script** tag in the HTML file is not loaded.
**Solution**
If only **setResponseData** is set for the interceptor, the kernel cannot identify the HTML file. You must also set parameters such as **setResponseEncoding**, **setResponseMimeType**, and **setResponseHeader** for the kernel to identify the HTML file.
**Example**
```
Web({ src: 'www.example.com', controller: this.controller })
.onInterceptRequest((event) => {
console.log('url:' + event.request.getRequestUrl())
this.responseweb = new WebResourceResponse();
var head1:Header = {
headerKey:"Connection",
headerValue:"keep-alive"
}
var length = this.heads.push(head1)
this.responseweb.setResponseHeader(this.heads)
this.responseweb.setResponseData(this.webdata)
this.responseweb.setResponseEncoding('utf-8')
this.responseweb.setResponseMimeType('text/html')
this.responseweb.setResponseCode(200)
this.responseweb.setReasonMessage('OK')
return this.responseweb
})
```
**Reference**
[WebResourceResponse](../reference/arkui-ts/ts-basic-components-web.md#webresourceresponse)
## How do I execute JS functions in HTML in ArkTS code?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
**Solution**
Use the **runJavaScript** API in **WebviewController** to asynchronously execute JavaScript scripts and obtain the execution result in a callback.
>**NOTE**
>
>**runJavaScript** can be invoked only after l**oadUrl** is executed. For example, it can be invoked in **onPageEnd**.
**Reference**
[runJavaScript](../reference/apis/js-apis-webview.md#runjavascript)
## How do I invoke an ArkTS method on a local web page loaded in the \<Web> component?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
**Solution**
1. Prepare an HTML file. Below is the sample code:
```
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Title</h1>
<h5 id="h5"></h5>
<h5 id = "h6"></h5>
<button onclick="handleFromH5">Invoke ArkTS method </button>
<script type="text/javascript">
function handleFromH5(){
let result = window.objName.test();
document.getElementById('h6').innerHTML = result;
}
</script>
</body>
</html>
```
2. Use the **JavaScriptProxy** API in ArkTs to register the object in ArkTS with the window object of H5, and then use the window object to call the method in H5. In the following example, the **testObj** object in ArkTS is registered with the window object of H5 with the alias **objName**. In H5, **window.objName** can then be used to access the object.
```
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct Index {
@State message: string = 'Hello World'
controller: web_webview.WebviewController = new web_webview.WebviewController()
testObj = {
test: (data1, data2, data3) => {
console.log("data1:" + data1);
console.log("data2:" + data2);
console.log("data3:" + data3);
return "AceString";
},
toString: () => {
console.log('toString' + "interface instead.");
}
}
build() {
Row() {
Column() {
Web({ src:$rawfile('index.html'), controller:this.controller })
.javaScriptAccess(true)
.javaScriptProxy({
object: this.testObj,
name: "objName",
methodList: ["test", "toString"],
controller: this.controller,
})
}
.width('100%')
}
.height('100%')
}
}
```
**Reference**
[javaScriptProxy](../reference/arkui-ts/ts-basic-components-web.md#javascriptproxy)
## How do I set the domStorageAccess attribute of the \<Web> component?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
**Solution**
The **domStorageAccess** attribute sets whether to enable the DOM Storage API. By default, this feature is disabled.
**Reference**
[domStorageAccess](../reference/arkui-ts/ts-basic-components-web.md#domstorageaccess)
此差异已折叠。
# Common Event and Notification Development
# Event and Notification Development
## What is the emitter data size limit?
## How do I encapsulate a commonEvent utility class?
Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9
Applicable to: OpenHarmony 3.1 Beta 5 (API version 9)
The emitter data size cannot exceed 10240.
**Problem**
## How do I implement the click-a-notification-to-open-an-application function?
A commonEvent utility class needs to be encapsulated for the following purpose: Register a custom callback function when creating a subscriber, and then call the custom callback function when receiving an event notification.
Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9
**Solution**
You can implement this function by setting the **wantAgent** attribute in the **NotificationRequest** parameter of the **Notification.publish** API.
```
import commonEvent from '@ohos.commonEventManager';
Reference: [Notification](../reference/apis/js-apis-notification.md#notificationpublish) and [WantAgent](../reference/apis/js-apis-app-ability-wantAgent.md)
export class SubscribeEvent {
private static subscriber = null
// Custom callback function
private static callback = null
/**
* Create a subscriber.
* @param subscribeInfo Indicates the event to subscribe to.
* @callback Indicates the custom callback.
*/
static createSubscriber(subscribeInfo, callback:(a,b)=>void) {
this.callback = callback
commonEvent.createSubscriber(subscribeInfo, (err, subscriber) => {
if (err) {
console.error('CreateSubscriberCallBack err = ' + JSON.stringify(err))
} else {
this.subscriber = subscriber;
this.subscribe(this.subscriber)
console.info('Create subscriber succeed')
}
})
}
Example:
/**
* Subscribe to a common event.
* @param subscriber Indicates the subscriber.
*/
private static subscribe(subscriber) {
if (subscriber != null) {
commonEvent.subscribe(subscriber, (err, data) => {
if (err) {
console.error('subscribe err = ' + JSON.stringify(err))
} else {
console.info('SubscribeCallBack data= ' + JSON.stringify(data))
this.callback('hello callback', data)
}
})
} else {
console.info("Need create subscriber")
}
}
}
```ts
import WantAgent from '@ohos.app.ability.wantAgent';
@Entry
@Component
struct Faq10_1 {
@State message: string = ''
async function publishNotification() {
let wantAgentInfo = {
wants: [
{
bundleName: "com.example.myapplication",
abilityName: "EntryAbility",
build() {
Row() {
Column() {
Text ('Subscribe:' + this.message)
.fontSize(30)
.fontWeight(FontWeight.Bold)
.onClick(() => {
let subscribeInfo = {
events: ["myEvent"]
};
let callback = (a,b) => {
this.message = a
}
SubscribeEvent.createSubscriber(subscribeInfo,callback)
})
Text ('Publish')
.fontSize(30)
.fontWeight(FontWeight.Bold)
.onClick(() => {
// Attributes of a common event.
let options = {
code: 0, // Result code of the common event.
data: "initial data",// Result data of the common event.
isOrdered: true // The common event is an ordered one.
}
// Callback for common event publication.
function publishCB(err) {
if (err) {
console.error(`publish failed, code is ${err.code}, message is ${err.message}`);
} else {
console.info("publish");
}
}
// Publish a common event.
try {
commonEvent.publish("myEvent", options, publishCB);
} catch (err) {
console.error(`publish failed, code is ${err.code}, message is ${err.message}`);
}
})
}
],
operationType: WantAgent.OperationType.START_ABILITIES,
requestCode: 0,
.width('100%')
}
.height('100%')
}
const wantAgent = await WantAgent.getWantAgent(wantAgentInfo)
let contentType = Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT;
await Notification.publish({
content: {
contentType: contentType,
normal: {
title: "Test Title",
text: "Test content",
}
},
id: 1,
wantAgent: wantAgent
})
prompt.showToast ({ message: "Sent successfully." })
}
```
**Reference**
[@ohos.commonEventManager (Common Event)](../reference/apis/js-apis-commonEventManager.md)
## How do I make events be transferred in only one UIAbility instance?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
**Problem**
Events need to be subscribed to and triggered only in one UIAbility instance.
**Solution**
Use the API in the **EventHub** module of the UIAbility to subscribe to events. The **EventHub** module offers the event center, which provides the API for subscribing to, unsubscribing from, and triggering events.
**Example**
```
import UIAbility from '@ohos.app.ability.UIAbility';
export default class EntryAbility extends UIAbility {
onForeground() {
this.context.eventHub.on('myEvent', this.eventFunc);
// Result
// eventFunc is called,undefined,undefined
this.context.eventHub.emit('myEvent');
// Result
// eventFunc is called,1,undefined
this.context.eventHub.emit('myEvent', 1);
// Result
// eventFunc is called,1,2
this.context.eventHub.emit('myEvent', 1, 2);
}
eventFunc(argOne, argTwo) {
console.log('eventFunc is called, ${argOne}, ${argTwo}');
}}
```
**Reference**
[Using EventHub for Data Synchronization](../application-models/uiability-data-sync-with-ui.md#using-eventhub-for-data-synchronization).
# SDK Usage
## What is the macro definition of the arm64-v8a/armeabi-v7a directory in CMake?
Applicable to: OpenHarmony 3.1 Beta 5 (API version 9)
**Solution**
The **arm64-v8a** and **armeabi-v7a** directories are as follows:
```
entry
├─ libs
│ ├─ arm64-v8a
│ │ └─ libMyDemo.so
│ └─ armeabi-v7a
│ └─ libMyDemo.so
└─ src
└─ main
└─ cpp
└─ CMakeLists.txt
```
The macro for accessing the directory is **\$\{CMAKE\_CURRENT\_SOURCE\_DIR\}/../../../libs/$\{OHOS\_ARCH\}/xxxx.so**.
**CMAKE\_CURRENT\_SOURCE\_DIR**: directory where the **CMakeList.txt** file is stored.
**OHOS\_ARCH**: type of the application binary interface (ABI). The value can be **armeabi-v7a** or **arm64-v8a**. The default value is **arm64-v8a**.
**Example**
Add the link library to **CMakeLists.txt**.
```
target_link_libraries(entry PUBLIC
libace_napi.z.so
libhilog_ndk.z.so
${CMAKE_CURRENT_SOURCE_DIR}/../../../libs/${OHOS_ARCH}/libMyDemo.so
)
```
......@@ -17,11 +17,14 @@ Before developing an audio feature, especially before implementing audio data pr
Before developing features related to audio and video playback, you are advised to understand the following concepts:
- Playback process: network protocol > container format > audio and video codec > graphics/audio rendering
- Network protocols: HLS, HTTP, HTTPS, and more
- Container formats: MP4, MKV, MPEG-TS, WebM, and more
- Encoding formats: H.263/H.264/H.265, MPEG4/MPEG2, and more
## Introduction to Audio Streams
## Introduction to Audio Streams
An audio stream is an independent audio data processing unit that has a specific audio format and audio usage scenario information. The audio stream can be used in playback and recording scenarios, and supports independent volume adjustment and audio device routing.
......@@ -29,20 +32,20 @@ The basic audio stream information is defined by [AudioStreamInfo](../reference/
### Audio Stream Usage Scenario Information
In addition to the basic information (which describes only audio data), an audio stream has usage scenario information. This is because audio streams differ in the volume, device routing, and concurrency policy. The system chooses an appropriate processing policy for an audio stream based on the usage scenario information, thereby delivering the optimal user experience.
In addition to the basic information (which describes only audio data), an audio stream has usage scenario information. This is because audio streams differ in the volume, device routing, and concurrency policy. The system chooses an appropriate processing policy for an audio stream based on the usage scenario information, thereby delivering better user experience.
- Playback scenario
Information about the audio playback scenario is defined by using [StreamUsage](../reference/apis/js-apis-audio.md#streamusage) and [ContentType](../reference/apis/js-apis-audio.md#contenttype).
- **StreamUsage** specifies the usage type of an audio stream, for example, used for media, voice communication, voice assistant, notification, and ringtone.
- **ContentType** specifies the content type of data in an audio stream, for example, speech, music, movie, notification tone, and ringtone.
Information about the audio playback scenario is defined by using [StreamUsage](../reference/apis/js-apis-audio.md#streamusage) and [ContentType](../reference/apis/js-apis-audio.md#contenttype).
- **StreamUsage** specifies the usage type of an audio stream, for example, used for media, voice communication, voice assistant, notification, and ringtone.
- **ContentType** specifies the content type of data in an audio stream, for example, speech, music, movie, notification tone, and ringtone.
- Recording scenario
Information about the audio stream recording scenario is defined by [SourceType](../reference/apis/js-apis-audio.md#sourcetype8).
Information about the audio stream recording scenario is defined by [SourceType](../reference/apis/js-apis-audio.md#sourcetype8).
**SourceType** specifies the recording source type of an audio stream, including the mic source, voice recognition source, and voice communication source.
## Supported Audio Formats
......@@ -58,9 +61,9 @@ The sampling rate varies according to the device type.
- Mono and stereo are supported. For details, see [AudioChannel](../reference/apis/js-apis-audio.md#audiochannel8).
- The following sampling formats are supported: U8 (unsigned 8-bit integer), S16LE (signed 16-bit integer, little endian), S24LE (signed 24-bit integer, little endian), S32LE (signed 32-bit integer, little endian), and F32LE (signed 32-bit floating point number, little endian). For details, see [AudioSampleFormat](../reference/apis/js-apis-audio.md#audiosampleformat8).
Due to system restrictions, only some devices support the sampling formats S24LE, S32LE, and F32LE.
Due to system restrictions, only some devices support the sampling formats S24LE, S32LE, and F32LE.
Little endian means that the most significant byte is stored at the largest memory address and the least significant byte of data is stored at the smallest. This storage mode effectively combines the memory address with the bit weight of the data. Specifically, the largest memory address has a high weight, and the smallest memory address has a low weight.
The audio and video formats supported by the APIs of the media module are described in [AVPlayer and AVRecorder](avplayer-avrecorder-overview.md).
......@@ -16,7 +16,7 @@ AppStorage is a singleton LocalStorage object that is created by the UI framewor
UI components synchronize application state attributes with the AppStorage. Implementation of application business logic can access AppStorage as well.
Selected state attributes of AppStorage can be synched with different data sources or data sinks. Those data sources and sinks can be on a local or remote device, and have different capabilities, such as data persistence (see [PersistentStorage](arkts-persiststorage.md)). These data sources and sinks are implemented in the business logic, separate from the UI. Link those AppStorage attributes to [@StorageProp](#storageprop) and [@StorageLink](#storagelink) whose values should be kept until application re-start.
Selected state attributes of AppStorage can be synced with different data sources or data sinks. Those data sources and sinks can be on a local or remote device, and have different capabilities, such as data persistence (see [PersistentStorage](arkts-persiststorage.md)). These data sources and sinks are implemented in the business logic, separate from the UI. Link those AppStorage attributes to [@StorageProp](#storageprop) and [@StorageLink](#storagelink) whose values should be kept until application re-start.
## \@StorageProp
......
......@@ -35,7 +35,8 @@ LocalStorage provides two decorators based on the synchronization type of the co
## Restrictions
Once created, the type of a named attribute cannot be changed. Subsequent calls to **Set** must set a value of same type.
- Once created, the type of a named attribute cannot be changed. Subsequent calls to **Set** must set a value of same type.
- LocalStorage provides page-level storage. The [GetShared](../reference/arkui-ts/ts-state-management.md#getshared9) API can only obtain the LocalStorage instance transferred through [windowStage.loadContent](../reference/apis/js-apis-window.md#loadcontent9) in the current stage. Otherwise, **undefined** is returned. Example: [Sharing a LocalStorage Instance from UIAbility to One or More Pages](#sharing-a-localstorage-instance-from-uiability-to-one-or-more-pages).
## \@LocalStorageProp
......@@ -51,7 +52,7 @@ When a custom component is initialized, the \@LocalStorageProp(key)/\@LocalStora
> Since API version 9, this decorator is supported in ArkTS widgets.
By decorating a variable with \@LocalStorageProp(key), a one-way data synchronization is established with the attribute with the given key in LocalStorage. A local change can be made, but it will not besynchronized to LocalStorage. An update to the attribute with the given key in LocalStorage will overwrite local changes.
By decorating a variable with \@LocalStorageProp(key), a one-way data synchronization is established with the attribute with the given key in LocalStorage. A local change can be made, but it will not be synchronized to LocalStorage. An update to the attribute with the given key in LocalStorage will overwrite local changes.
### Rules of Use
......@@ -127,7 +128,7 @@ By decorating a variable with \@LocalStorageProp(key), a one-way data synchroniz
| Transfer/Access | Description |
| ---------- | ---------------------------------------- |
| Initialization and update from the parent component| Forbidden.|
| Subnode initialization | Supported; can be used to initialize a n \@State, \@Link, \@Prop, or \@Provide decorated variable in the child component.|
| Subnode initialization | Supported; can be used to initialize an \@State, \@Link, \@Prop, or \@Provide decorated variable in the child component.|
| Access | None. |
......@@ -423,3 +424,5 @@ struct CompA {
> **NOTE**
>
> It is good practice to always create a LocalStorage instance with meaningful default values, which serve as a backup when execution exceptions occur and are also useful for unit testing of pages.
<!--no_check-->
......@@ -24,7 +24,7 @@ For an \@Prop decorated variable, the value synchronization is uni-directional f
| ----------- | ---------------------------------------- |
| Decorator parameters | None. |
| Synchronization type | One-way: from the data source provided by the parent component to the @Prop decorated variable.|
| Allowed variable types | string, number, boolean, or enum type.<br>**any** is not supported. The **undefined** and **null** values are not allowed.<br>The type must be specified.<br>Negative examples:<br>CompA&nbsp;({&nbsp;aProp:&nbsp;undefined&nbsp;})<br>CompA&nbsp;({&nbsp;aProp:&nbsp;null&nbsp;})<br>The type must be the same as that of the [data source](arkts-state-management-overview.md#basic-concepts). There are three cases (\@State is used as an example of the data source):<br>- The type of the \@Prop decorated variable is the same as that of the state variable of the parent component, that is, \@Prop: S and \@State: S. For an example, see [Simple Type @Prop Synced from @State in Parent Component](#simple-type-prop-synced-from-state-in-parent-component).<br>- When the state variable of the parent component is an array, the type of the \@Prop decorated variable is the same as that of the array item of the state variable of the parent component, that is, \@Prop: S and \@State: Array\<S>. For examples, see [Simple Type @Prop Synched from @State Array Item in Parent Component](#simple-type-prop-synched-from-state-array-item-in-parent-component).<br>- When the state variable of the parent component is Object or class, the type of the \@Prop decorated variableis the same as the attribute type of the state variable of the parent component, that is, \@Prop: S and \@State: { propA: S }. For examples, see [Class Object Type @Prop Synchedd from @State Class Object Property in Parent Component](#class-object-type-prop-synchedd-from-state-class-object-property-in-parent-component).|
| Allowed variable types | string, number, boolean, or enum type.<br>**any** is not supported. The **undefined** and **null** values are not allowed.<br>The type must be specified.<br>Negative examples:<br>CompA&nbsp;({&nbsp;aProp:&nbsp;undefined&nbsp;})<br>CompA&nbsp;({&nbsp;aProp:&nbsp;null&nbsp;})<br>The type must be the same as that of the [data source](arkts-state-management-overview.md#basic-concepts). There are three cases (\@State is used as an example of the data source):<br>- The type of the \@Prop decorated variable is the same as that of the state variable of the parent component, that is, \@Prop: S and \@State: S. For an example, see [Simple Type @Prop Synced from @State in Parent Component](#simple-type-prop-synced-from-state-in-parent-component).<br>- When the state variable of the parent component is an array, the type of the \@Prop decorated variable is the same as that of the array item of the state variable of the parent component, that is, \@Prop: S and \@State: Array\<S>. For examples, see [Simple Type @Prop Synced from @State Array Item in Parent Component](#simple-type-prop-synced-from-state-array-item-in-parent-component).<br>- When the state variable of the parent component is Object or class, the type of the \@Prop decorated variable is the same as the attribute type of the state variable of the parent component, that is, \@Prop: S and \@State: { propA: S }. For examples, see [Class Object Type @Prop Synced from @State Class Object Attribute in Parent Component](#class-object-type-prop-synced-from-state-class-object-attribute-in-parent-component). |
| Initial value for the decorated variable | Local initialization is allowed. |
......@@ -146,16 +146,16 @@ In the preceding example:
1. On initial render, when the **CountDownComponent** child component is created, its @Prop decorated **count** variable is initialized from the \@State decorated **countDownStartValue** variable in the **ParentComponent**.
2. When the "+1" or "-1" button is touched, the @State decorated **countDownStartValue** of the **ParentComponent** changes. This will cause the **ParentComponent** to re-render. At the minumum, the **CountDownComponent** will be updated because of the changed **count** variable value.
2. When the "+1" or "-1" button is touched, the @State decorated **countDownStartValue** of the **ParentComponent** changes. This will cause the **ParentComponent** to re-render. At the minimum, the **CountDownComponent** will be updated because of the changed **count** variable value.
3. Because of the changed **count** variable value, the **CountDownComponent** child component will re-render. At a minimum, the **if** statement's conditions (**this.counter> 0**) is-evaluated and the **\<Text>** child component inside the **if** would be updated.
4. When **Try again** in the **CountDownComponent** child component is touched, the value of the **count** variable is modified, but the change remains within the child component and does not affect the **countDownStartValue** in the parenet component.
4. When **Try again** in the **CountDownComponent** child component is touched, the value of the **count** variable is modified, but the change remains within the child component and does not affect the **countDownStartValue** in the parent component.
5. Updating **countDownStartValue** will overwrite the local value changes of the @Prop decorated **count** in the **CountDownComponent** child component.
### Simple Type @Prop Synched from @State Array Item in Parent Component
### Simple Type @Prop Synced from @State Array Item in Parent Component
The \@State decorated array an array item in the parent component can be used as data source to initialize and update a @Prop decorated variable. In the following example, the \@State decorated array **arr** in the parent component **Index** initializes the \@Prop decorated **value** variable in the child component **Child**.
......@@ -240,7 +240,7 @@ After **replace entire arr** is clicked, the following information is displayed:
```
- Changes made in the **Child** component are not synchronized to the parent component **Index**. Therefore, even if the values of the six intances of the **Child** component are 7, the value of **this.arr** in the **Index** component is still **[1,2,3]**.
- Changes made in the **Child** component are not synchronized to the parent component **Index**. Therefore, even if the values of the six instances of the **Child** component are 7, the value of **this.arr** in the **Index** component is still **[1,2,3]**.
- After **replace entire arr** is clicked, if **this.arr[0] == 1** is true, **this.arr** is set to **[3, 4, 5]**.
......@@ -250,9 +250,9 @@ After **replace entire arr** is clicked, the following information is displayed:
- The change of **this.arr** causes **ForEach** to update: The array item with the ID **3** is retained in this update, array items with IDs **1** and **2** are deleted, and array items with IDs **4** and **5** are added. The array before and after the update is **[1, 2, 3]** and **[3, 4, 5]**, respectively. This implies that the **Child** instance generated for item **3** will be moved to the first place, but not updated. In this case, the component value corresponding to **3** is **7**, and the final render result of **ForEach** is **7**, **4**, and **5**.
### Class Object Type @Prop Synchedd from @State Class Object Property in Parent Component
### Class Object Type @Prop Synced from @State Class Object Attribute in Parent Component
In a library with one book and two users, each user can mark the book as read, but this does not affect the other user reader. Technically speaking, local changes to the \@Prop decorated **book** object do not sync back to the @State decorated **book** in the **Library** component.
In a library with one book and two users, each user can mark the book as read, and the marking does not affect the other user reader. Technically speaking, local changes to the \@Prop decorated **book** object do not sync back to the @State decorated **book** in the **Library** component.
```ts
......@@ -296,7 +296,7 @@ struct Library {
```
### Simple Type @Prop with Local Initialization and No Sync from Parent Parent
### Simple Type @Prop with Local Initialization and No Sync from Parent Component
To enable an \@Component decorated component to be reusable, \@Prop allows for optional local initialization. This makes the synchronization with a variable in the parent component a choice, rather than mandatory. Providing a data source in the parent component is optional only when local initialization is provided for the \@Prop decorated variable.
......@@ -351,11 +351,11 @@ struct MainProgram {
Row() {
Column()
// customCounter must be initialized from the parent component due to lack of local initialization. Here, customCounter2 does not need to be initialized.
MyComponent({ customCounter: this.mainCounter })
// customCounter2 of the child component can also be initialized from the parent component. The value from the parent component overwrites the locally assigned value of customCounter2 during initialization.
MyComponent({ customCounter: this.mainCounter, customCounter2: this.mainCounter })
}.width('40%')
// customCounter must be initialized from the parent component due to lack of local initialization. Here, customCounter2 does not need to be initialized.
MyComponent({ customCounter: this.mainCounter })
// customCounter2 of the child component can also be initialized from the parent component. The value from the parent component overwrites the locally assigned value of customCounter2 during initialization.
MyComponent({ customCounter: this.mainCounter, customCounter2: this.mainCounter })
}.width('40%')
}
}
}
......
# Full SDK Compilation Guide
# Full SDK Compilation
The full SDK provides a full set of APIs available in OpenHarmony, including system APIs required by system applications. Vendors can leverage this SDK to develop applications.
......
# Guide to Switching to Full SDK
# Switching to Full SDK
Both the public SDK and full SDK are toolkits for application development. <br>The public SDK is intended for application developers and provided as standard in DevEco Studio. It does not contain system APIs – APIs required by system applications.
......
......@@ -256,7 +256,6 @@
- [@ohos.net.connection (Network Connection Management)](js-apis-net-connection.md)
- [@ohos.net.ethernet (Ethernet Connection Management)](js-apis-net-ethernet.md)
- [@ohos.net.http (Data Request)](js-apis-http.md)
- [@ohos.net.policy (Network Policy Management)](js-apis-net-policy.md)
- [@ohos.net.sharing (Network Sharing)](js-apis-net-sharing.md)
- [@ohos.net.socket (Socket Connection)](js-apis-socket.md)
- [@ohos.net.webSocket (WebSocket Connection)](js-apis-webSocket.md)
......
......@@ -29,19 +29,19 @@ A description regarding system APIs will be provided in the document.
A common application is an application whose application type is **hos_normal_app** in the HarmonyAppProvision configuration file. **hos_normal_app** is the default value for project creation.
The public SDK, which does not include system APIs, is provided as standard in DevEco Studio. To use the system APIs, you must:
- Switch the public SDK to the full SDK by following the instructions provided in [Guide to Switching to Full SDK] (../../quick-start/full-sdk-switch-guide.md).
- Switch the public SDK to the full SDK by following the instructions provided in [Guide to Switching to Full SDK](../../quick-start/full-sdk-switch-guide.md).
- Change the value of **app-feature** in the HarmonyAppProvision configuration file to **hos_system_app**. For details, see [HarmonyAppProvision Configuration File](../../security/app-provision-structure.md).
## Permission Description
By default, applications can access limited system resources. However, in some cases, an application needs to access excess data (including personal data) and functions of the system or another application to implement extended functions. For details, see [Access Control Overview](../../security/accesstoken-overview.md).
By default, applications can access limited system resources. However, in some cases, an application needs to access excess data (including personal data) and functions of the system or another application to implement extended functions. For details, see [Access Control (Permission) Overview](../../security/accesstoken-overview.md).
To call APIs to access these resources, you must apply for the corresponding permissions by following the instructions provided in [Access Control Development](../../security/accesstoken-guidelines.md).
To call APIs to access these resources, you must apply for the corresponding permissions by following the instructions provided in [Applying for Permissions](../../security/accesstoken-guidelines.md).
- If an application can call an API only after it has obtained a specific permission, the following description is provided for the API: "**Required permissions**: ohos.permission.xxxx"
- If an application can call an API without any permission, no special description is provided.
To determine whether an application can request a specific permission, see [Permission Application and Use](../../security/accesstoken-overview.md#applying-for-and-using-a-permission).
To determine whether an application can request a specific permission, see [Applying for and Using a Permission](../../security/accesstoken-overview.md#applying-for-and-using-a-permission).
## System Capability Description
......
......@@ -44,8 +44,6 @@ Obtains an [AbilityDelegator](js-apis-inner-application-abilityDelegator.md) obj
**Example**
```ts
import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry';
let abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
let want = {
......@@ -78,8 +76,6 @@ Obtains an [AbilityDelegatorArgs](js-apis-inner-application-abilityDelegatorArgs
**Example**
```ts
import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry';
let args = AbilityDelegatorRegistry.getArguments();
console.info('getArguments bundleName:' + args.bundleName);
console.info('getArguments parameters:' + JSON.stringify(args.parameters));
......
......@@ -7,14 +7,12 @@ The **AbilityLifecycleCallback** module defines the callbacks to receive lifecyc
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The APIs of this module can be used only in the stage model.
## Modules to Import
```ts
import AbilityLifecycleCallback from '@ohos.app.ability.AbilityLifecycleCallback';
```
## AbilityLifecycleCallback.onAbilityCreate
onAbilityCreate(ability: UIAbility): void;
......
......@@ -641,7 +641,7 @@ Obtains applications that are running in the foreground. This API uses a promise
| Type| Description|
| -------- | -------- |
| Promise\<Array\<[AppStateData](js-apis-inner-application-appStateData.md)>> | Promise used to return an array holding the application state data|
| Promise\<Array\<[AppStateData](js-apis-inner-application-appStateData.md)>> | Promise used to return an array holding the application state data.|
**Error codes**
......@@ -669,7 +669,11 @@ killProcessWithAccount(bundleName: string, accountId: number): Promise\<void\>
Kills a process by bundle name and account ID. This API uses a promise to return the result.
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) and ohos.permission.CLEAN_BACKGROUND_PROCESSES
> **NOTE**
>
> The **ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS** permission is not required when **accountId** specifies the current user.
**Required permissions**: ohos.permission.CLEAN_BACKGROUND_PROCESSES and ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -715,12 +719,16 @@ killProcessWithAccount(bundleName: string, accountId: number, callback: AsyncCal
Kills a process by bundle name and account ID. This API uses an asynchronous callback to return the result.
> **NOTE**
>
> The **ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS** permission is not required when **accountId** specifies the current user.
**Required permissions**: ohos.permission.CLEAN_BACKGROUND_PROCESSES and ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**System API**: This is a system API and cannot be called by third-party applications.
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) and ohos.permission.CLEAN_BACKGROUND_PROCESSES
**Parameters**
| Name| Type| Mandatory| Description|
......
......@@ -11,7 +11,6 @@ The **appRecovery** module provides APIs for recovering faulty applications.
import appRecovery from '@ohos.app.ability.appRecovery';
```
## appRecovery.RestartFlag
Enumerates the application restart flags. This enum is used as an input parameter of [enableAppRecovery](#apprecoveryenableapprecovery).
......@@ -51,7 +50,7 @@ Enumerates the application state saving modes. This enum is used as an input par
enableAppRecovery(restart?: [RestartFlag](#apprecoveryrestartflag), saveOccasion?: [SaveOccasionFlag](#apprecoverysaveoccasionflag), saveMode?: [SaveModeFlag](#apprecoverysavemodeflag)) : void;
Enables application recovery.
Enables application recovery. After this API is called, the first ability that is displayed when the application is started from the initiator can be restored.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......
......@@ -6,9 +6,15 @@ The **Configuration** module defines environment change information. **Configura
>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
```ts
import Configuration from '@ohos.app.ability.Configuration';
```
**System capability**: SystemCapability.Ability.AbilityBase
| Name| Type| Readable| Writable| Description|
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| language | string | Yes| Yes| Language of the application, for example, **zh**.|
| colorMode | [ColorMode](js-apis-app-ability-configurationConstant.md#configurationconstantcolormode) | Yes| Yes| Color mode. The default value is **COLOR_MODE_LIGHT**. The options are as follows:<br>- **COLOR_MODE_NOT_SET**: The color mode is not set.<br>- **COLOR_MODE_LIGHT**: light mode.<br>- **COLOR_MODE_DARK**: dark mode.|
......
# @ohos.app.ability.contextConstant (ContextConstant)
The **ContextConstant** module defines context-related enums. Currently, it defines only the enum of data encryption levels.
The **ContextConstant** module defines context-related enums. Currently, it defines only the enum of encryption levels.
> **NOTE**
>
>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>
> The APIs of this module can be used only in the stage model.
## Modules to Import
......@@ -21,5 +22,5 @@ You can obtain the value of this constant by calling the **ContextConstant.AreaM
| Name| Value| Description|
| -------- | -------- | -------- |
| EL1 | 0 | Device-level encryption area, which is accessible after the device is powered on.|
| EL2 | 1 | User-level encryption area, which is accessible only after the device is powered on and the password is entered (for the first time).|
| EL1 | 0 | Device-level encryption. Directories with this encryption level are accessible after the device is powered on. |
| EL2 | 1 | User-level encryption. Directories with this encryption level are accessible only after the device is powered on and the password is entered (for the first time). |
......@@ -43,6 +43,8 @@ try {
}
```
## dataUriUtils.attachId
attachId(uri: string, id: number): string
......@@ -80,6 +82,8 @@ try {
```
## dataUriUtils.deleteId
deleteId(uri: string): string
......@@ -112,6 +116,8 @@ try {
```
## dataUriUtils.updateId
updateId(uri: string, id: number): string
......@@ -147,4 +153,3 @@ try {
console.error('delete uri err, check the input uri ${err}');
}
```
......@@ -41,32 +41,71 @@ Obtains the request information from Want.
import rpc from '@ohos.rpc';
import dialogRequest from '@ohos.app.ability.dialogRequest';
export default class ServiceExtAbility extends ServiceExtensionAbility {
onCreate(want) {
console.info(TAG, `onCreate, want: ${want.abilityName}`);
}
onRequest(want, startId) {
console.info(TAG, `onRequest, want: ${want.abilityName}`);
try {
var requestInfo = dialogRequest.getRequestInfo(want);
} catch(err) {
console.error('getRequestInfo err= ${JSON.stringify(err)}');
const REQUEST_VALUE = 1;
class StubTest extends rpc.RemoteObject {
constructor(des) {
super(des);
}
onRemoteRequest(code, data, reply, option) {
if (code === REQUEST_VALUE) {
let optFir = data.readInt();
let optSec = data.readInt();
reply.writeInt(optFir + optSec);
}
}
return true;
}
queryLocallInterface(descriptor) {
return null;
}
getInterfaceDescriptor() {
return "";
}
getCallingPid() {
return REQUEST_VALUE;
}
getCallingUid() {
return REQUEST_VALUE;
}
attachLocalInterface(localInterface, descriptor) {
}
}
let TAG = "getRequestInfoTest";
export default class ServiceExtAbility extends ServiceExtensionAbility {
onCreate(want) {
console.info(TAG, `onCreate, want: ${want.abilityName}`);
}
onRequest(want, startId) {
console.info(TAG, `onRequest, want: ${want.abilityName}`);
try {
var requestInfo = dialogRequest.getRequestInfo(want);
} catch (err) {
console.error('getRequestInfo err= ${JSON.stringify(err)}');
}
}
onConnect(want) {
console.info(TAG, `onConnect, want: ${want.abilityName}`);
}
onConnect(want) {
console.info(TAG, `onConnect, want: ${want.abilityName}`);
return new StubTest("test");
}
onDisconnect(want) {
console.info(TAG, `onDisconnect, want: ${want.abilityName}`);
}
onDisconnect(want) {
console.info(TAG, `onDisconnect, want: ${want.abilityName}`);
}
onDestroy() {
console.info(TAG, `onDestroy`);
}
}
onDestroy() {
console.info(TAG, `onDestroy`);
}
}
```
## dialogRequest.getRequestCallback
......@@ -95,6 +134,44 @@ Obtains the request callback from Want.
import ServiceExtensionAbility from '@ohos.app.ability.ServiceExtensionAbility';
import rpc from '@ohos.rpc';
import dialogRequest from '@ohos.app.ability.dialogRequest';
let TAG = "getRequestCallbackTest";
const REQUEST_VALUE = 1;
class StubTest extends rpc.RemoteObject {
constructor(des) {
super(des);
}
onRemoteRequest(code, data, reply, option) {
if (code === REQUEST_VALUE) {
let optFir = data.readInt();
let optSec = data.readInt();
reply.writeInt(optFir + optSec);
}
return true;
}
queryLocallInterface(descriptor) {
return null;
}
getInterfaceDescriptor() {
return "";
}
getCallingPid() {
return REQUEST_VALUE;
}
getCallingUid() {
return REQUEST_VALUE;
}
attachLocalInterface(localInterface, descriptor) {
}
}
export default class ServiceExtAbility extends ServiceExtensionAbility {
onCreate(want) {
......@@ -112,6 +189,7 @@ Obtains the request callback from Want.
onConnect(want) {
console.info(TAG, `onConnect, want: ${want.abilityName}`);
return new StubTest("test");
}
onDisconnect(want) {
......@@ -127,8 +205,7 @@ Obtains the request callback from Want.
## RequestInfo
Defines the request information, which is used as an input parameter for binding the modal dialog box.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Example**
......@@ -137,6 +214,44 @@ Defines the request information, which is used as an input parameter for binding
import rpc from '@ohos.rpc';
import dialogRequest from '@ohos.app.ability.dialogRequest';
import window from '@ohos.window';
let TAG = "RequestInfoTest";
const REQUEST_VALUE = 1;
class StubTest extends rpc.RemoteObject {
constructor(des) {
super(des);
}
onRemoteRequest(code, data, reply, option) {
if (code === REQUEST_VALUE) {
let optFir = data.readInt();
let optSec = data.readInt();
reply.writeInt(optFir + optSec);
}
return true;
}
queryLocallInterface(descriptor) {
return null;
}
getInterfaceDescriptor() {
return "";
}
getCallingPid() {
return REQUEST_VALUE;
}
getCallingUid() {
return REQUEST_VALUE;
}
attachLocalInterface(localInterface, descriptor) {
}
}
export default class ServiceExtAbility extends ServiceExtensionAbility {
onCreate(want) {
......@@ -163,6 +278,8 @@ Defines the request information, which is used as an input parameter for binding
onConnect(want) {
console.info(TAG, `onConnect, want: ${want.abilityName}`);
return new StubTest("test");
}
onDisconnect(want) {
......@@ -179,7 +296,7 @@ Defines the request information, which is used as an input parameter for binding
Enumerates the result codes of the request for the modal dialog box.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
| Name | Value | Description |
| ------------ | ------------------ | ---------------------- |
......@@ -191,7 +308,7 @@ Defines the result of the request for the modal dialog box. Only the result code
## Attributes
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
......@@ -207,7 +324,7 @@ setRequestResult(result: RequestResult): void;
Sets the result of the request for the modal dialog box.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
......@@ -229,6 +346,44 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error
import ServiceExtensionAbility from '@ohos.app.ability.ServiceExtensionAbility';
import rpc from '@ohos.rpc';
import dialogRequest from '@ohos.app.ability.dialogRequest';
let TAG = "setRequestResultTest";
const REQUEST_VALUE = 1;
class StubTest extends rpc.RemoteObject {
constructor(des) {
super(des);
}
onRemoteRequest(code, data, reply, option) {
if (code === REQUEST_VALUE) {
let optFir = data.readInt();
let optSec = data.readInt();
reply.writeInt(optFir + optSec);
}
return true;
}
queryLocallInterface(descriptor) {
return null;
}
getInterfaceDescriptor() {
return "";
}
getCallingPid() {
return REQUEST_VALUE;
}
getCallingUid() {
return REQUEST_VALUE;
}
attachLocalInterface(localInterface, descriptor) {
}
}
export default class ServiceExtAbility extends ServiceExtensionAbility {
onCreate(want) {
......@@ -250,6 +405,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error
onConnect(want) {
console.info(TAG, `onConnect, want: ${want.abilityName}`);
return new StubTest("test");
}
onDisconnect(want) {
......
......@@ -45,9 +45,8 @@ Called when the system memory level changes.
**Example**
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
```ts
import UIAbility from '@ohos.app.ability.Ability';
let callbackId;
......@@ -57,8 +56,9 @@ export default class MyAbility extends UIAbility {
globalThis.applicationContext = this.context.getApplicationContext();
let EnvironmentCallback = {
onConfigurationUpdated(config){
console.log('onConfigurationUpdated config:' + JSON.stringify(config));
console.log(`onConfigurationUpdated config: ${JSON.stringify(config)}`);
},
onMemoryLevel(level){
console.log('onMemoryLevel level: ${JSON.stringify(level)}');
}
......@@ -76,4 +76,4 @@ export default class MyAbility extends UIAbility {
});
}
}
```
```
......@@ -36,7 +36,7 @@ Defines the quick fix information at the application level.
| Name | Type | Mandatory| Description |
| ----------- | -------------------- | ---- | ------------------------------------------------------------ |
| bundleName | string | Yes | Bundle name. |
| bundleName | string | Yes | Bundle name. |
| bundleVersionCode | number | Yes | Internal version number of the application. |
| bundleVersionName | string | Yes | Version number of the application that is shown to users. |
| quickFixVersionCode | number | Yes | Version code of the quick fix patch package. |
......@@ -57,19 +57,19 @@ Applies a quick fix patch. This API uses an asynchronous callback to return the
**Parameters**
| Parameter| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| hapModuleQuickFixFiles | Array\<string> | Yes| Quick fix patch files, each of which must contain a valid file path.|
| callback | AsyncCallback\<void> | Yes| Callback used to return the result.|
| Parameter| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| hapModuleQuickFixFiles | Array\<string> | Yes| Quick fix patch files, each of which must contain a valid file path.|
| callback | AsyncCallback\<void> | Yes| Callback used to return the result.|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 18500002 | Copy file failed, maybe not exist or inaccessible. |
| 18500002 | The specified quick fix is invalid. It may not exist or inaccessible. |
| 18500008 | Internal error. |
If an error occurs during patch installation, the error code and message are returned through the common event [COMMON_EVENT_QUICK_FIX_APPLY_RESULT](commonEvent-definitions.md#common_event_quick_fix_apply_result9). The table below lists the possible error codes and messages.
If an error occurs during patch installation, the error code and message are returned through the common event [COMMON_EVENT_QUICK_FIX_APPLY_RESULT](commonEventManager-definitions.md#common_event_quick_fix_apply_result-9). The table below lists the possible error codes and messages.
| ID| Error Message|
| ------- | -------- |
......@@ -118,24 +118,24 @@ Applies a quick fix patch. This API uses a promise to return the result.
**Parameters**
| Parameter| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| hapModuleQuickFixFiles | Array\<string> | Yes| Quick fix patch files, each of which must contain a valid file path.|
| Parameter| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| hapModuleQuickFixFiles | Array\<string> | Yes| Quick fix patch files, each of which must contain a valid file path.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise\<void> | Promise used to return the result.|
| Type| Description|
| -------- | -------- |
| Promise\<void> | Promise used to return the result.|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 18500002 | Copy file failed, maybe not exist or inaccessible. |
| 18500002 | The specified quick fix is invalid. It may not exist or inaccessible. |
| 18500008 | Internal error. |
If an error occurs during patch installation, the error code and message are returned through the common event [COMMON_EVENT_QUICK_FIX_APPLY_RESULT](commonEvent-definitions.md#common_event_quick_fix_apply_result9). The table below lists the possible error codes and messages.
If an error occurs during patch installation, the error code and message are returned through the common event [COMMON_EVENT_QUICK_FIX_APPLY_RESULT](commonEventManager-definitions.md#common_event_quick_fix_apply_result-9). The table below lists the possible error codes and messages.
| ID| Error Message|
| ------- | -------- |
......@@ -178,16 +178,16 @@ Obtains the quick fix information of the application. This API uses an asynchron
**Parameters**
| Parameter| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| bundleName | string | Yes|Bundle name. |
| callback | AsyncCallback\<[ApplicationQuickFixInfo](#applicationquickfixinfo)> | Yes| Callback used to return the quick fix information.|
| Parameter| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| bundleName | string | Yes|Bundle name. |
| callback | AsyncCallback\<[ApplicationQuickFixInfo](#applicationquickfixinfo)> | Yes| Callback used to return the quick fix information.|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 18500001 | The bundle is not exist. |
| 18500001 | The specified bundleName is invalid. |
| 18500008 | Internal error. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
......@@ -225,21 +225,21 @@ Obtains the quick fix information of the application. This API uses a promise to
**Parameters**
| Parameter| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| bundleName | string | Yes| Bundle name.|
| Parameter| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| bundleName | string | Yes| Bundle name. |
**Return value**
| Type| Description|
| -------- | -------- |
| Promise\<[ApplicationQuickFixInfo](#applicationquickfixinfo)> | Promise used to return the quick fix information.|
| Type| Description|
| -------- | -------- |
| Promise\<[ApplicationQuickFixInfo](#applicationquickfixinfo)> | Promise used to return the quick fix information.|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 18500001 | The bundle is not exist. |
| 18500001 | The specified bundleName is invalid. |
| 18500008 | Internal error. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
......
......@@ -15,15 +15,12 @@ import StartOptions from '@ohos.app.ability.StartOptions';
## Attributes
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**System API**: This is a system API and cannot be called by third-party applications.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| [windowMode](js-apis-app-ability-abilityConstant.md#abilityconstantwindowmode) | number | No| Window mode.|
| displayId | number | No| Display ID.|
| displayId | number | No| Display ID. |
**Example**
......
......@@ -333,7 +333,7 @@ Sends parcelable data to the target ability.
| ------- | -------------------------------- |
| 16200001 | Caller released. The caller has been released. |
| 16200002 | Callee invalid. The callee does not exist. |
| 16000050 | Internal Error. |
| 16000050 | Internal error. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
......@@ -416,7 +416,7 @@ Sends parcelable data to the target ability and obtains the parcelable data retu
| ------- | -------------------------------- |
| 16200001 | Caller released. The caller has been released. |
| 16200002 | Callee invalid. The callee does not exist. |
| 16000050 | Internal Error. |
| 16000050 | Internal error. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
......@@ -569,7 +569,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error
## Caller.on
on(type: 'release', callback: OnReleaseCallback): void;
on(type: 'release', callback: OnReleaseCallback): void;
Registers a callback that is invoked when the stub on the target ability is disconnected.
......@@ -586,6 +586,7 @@ Registers a callback that is invoked when the stub on the target ability is disc
| ID| Error Message|
| ------- | -------------------------------- |
| 401 | If the input parameter is not valid parameter. |
| 16200001 | Caller released. The caller has been released. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
......
......@@ -26,7 +26,7 @@ import Want from '@ohos.app.ability.Want';
| entities | Array\<string> | No| Additional category information (such as browser and video player) of the ability. It is a supplement to the **action** field for implicit Want. and is used to filter ability types.|
| uri | string | No| Data carried. This field is used together with **type** to specify the data type. If **uri** is specified in a Want, the Want will match the specified URI information, including **scheme**, **schemeSpecificPart**, **authority**, and **path**.|
| type | string | No| MIME type, that is, the type of the file to open, for example, **'text/xml'** and **'image/*'**. For details about the MIME type definition, see https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com.|
| parameters | {[key: string]: any} | No | Want parameters in the form of custom key-value (KV) pairs. By default, the following keys are carried:<br>- **ohos.aafwk.callerPid**: PID of the caller.<br>- **ohos.aafwk.param.callerBundleName**: bundle name of the caller.<br>- **ohos.aafwk.param.callerToken**: token of the caller.<br>- **ohos.aafwk.param.callerUid**: UID in [BundleInfo](js-apis-bundleManager-bundleInfo.md#bundleinfo-1), that is, the application UID in the bundle information.<br>- **component.startup.newRules**: whether to enable the new control rule.<br>- **moduleName**: module name of the caller. No matter what this field is set to, the correct module name will be sent to the peer.<br>- **ohos.dlp.params.sandbox**: available only for DLP files.|
| parameters | {[key: string]: any} | No | Want parameters in the form of custom key-value (KV) pairs. By default, the following keys are carried:<br>- **ohos.aafwk.callerPid**: PID of the caller.<br>- **ohos.aafwk.param.callerBundleName**: bundle name of the caller.<br>- **ohos.aafwk.param.callerToken**: token of the caller.<br>- **ohos.aafwk.param.callerUid**: UID in [BundleInfo](js-apis-bundleManager-bundleInfo.md#bundleinfo-1), that is, the application UID in the bundle information.<br>- **component.startup.newRules**: whether to enable the new control rule.<br>- **moduleName**: module name of the caller. No matter what this field is set to, the correct module name will be sent to the peer.<br>- **ohos.dlp.params.sandbox**: available only for DLP files.<br>- **ability.params.backToOtherMissionStack**: whether to support redirection back across mission stacks.|
| [flags](js-apis-ability-wantConstant.md#wantconstantflags) | number | No| How the **Want** object will be handled. By default, a number is passed in.<br>For example, **wantConstant.Flags.FLAG_ABILITY_CONTINUATION** specifies whether to start the ability in cross-device migration scenarios.|
**Example**
......@@ -34,7 +34,8 @@ import Want from '@ohos.app.ability.Want';
- Basic usage: called in a UIAbility object, as shown in the example below. For details about how to obtain the context, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability).
```ts
let context = ...; // UIAbilityContext
import common from '@ohos.app.ability.common';
let context = getContext(this) as common.UIAbilityContext; // UIAbilityContext
let want = {
'deviceId': '', // An empty deviceId indicates the local device.
'bundleName': 'com.example.myapplication',
......@@ -52,7 +53,8 @@ import Want from '@ohos.app.ability.Want';
* String
```ts
let context = ...; // UIAbilityContext
import common from '@ohos.app.ability.common';
let context = getContext(this) as common.UIAbilityContext; // UIAbilityContext
let want = {
bundleName: 'com.example.myapplication',
abilityName: 'FuncAbility',
......@@ -67,7 +69,8 @@ import Want from '@ohos.app.ability.Want';
```
* Number
```ts
let context = ...; // UIAbilityContext
import common from '@ohos.app.ability.common';
let context = getContext(this) as common.UIAbilityContext; // UIAbilityContext
let want = {
bundleName: 'com.example.myapplication',
abilityName: 'FuncAbility',
......@@ -83,7 +86,8 @@ import Want from '@ohos.app.ability.Want';
```
* Boolean
```ts
let context = ...; // UIAbilityContext
import common from '@ohos.app.ability.common';
let context = getContext(this) as common.UIAbilityContext; // UIAbilityContext
let want = {
bundleName: 'com.example.myapplication',
abilityName: 'FuncAbility',
......@@ -98,7 +102,8 @@ import Want from '@ohos.app.ability.Want';
```
* Object
```ts
let context = ...; // UIAbilityContext
import common from '@ohos.app.ability.common';
let context = getContext(this) as common.UIAbilityContext; // UIAbilityContext
let want = {
bundleName: 'com.example.myapplication',
abilityName: 'FuncAbility',
......@@ -118,7 +123,8 @@ import Want from '@ohos.app.ability.Want';
```
* Array
```ts
let context = ...; // UIAbilityContext
import common from '@ohos.app.ability.common';
let context = getContext(this) as common.UIAbilityContext; // UIAbilityContext
let want = {
bundleName: 'com.example.myapplication',
abilityName: 'FuncAbility',
......@@ -138,7 +144,8 @@ import Want from '@ohos.app.ability.Want';
```ts
import fs from '@ohos.file.fs';
let context = ...; // UIAbilityContext
import common from '@ohos.app.ability.common';
let context = getContext(this) as common.UIAbilityContext; // UIAbilityContext
let fd;
try {
......@@ -160,3 +167,33 @@ import Want from '@ohos.app.ability.Want';
console.error(`Failed to startAbility. Code: ${err.code}, message: ${err.message}`);
});
```
- Usage of **parameters**: The following uses **ability.params.backToOtherMissionStack** as an example. When a ServiceExtensionAbility starts a UIAbility, redirection back across mission stacks is supported.
```ts
// (1) UIAbility1 starts a ServiceExtensionAbility.
let context = getContext(this) as common.UIAbilityContext; // UIAbilityContext
let want = {
bundleName: 'com.example.myapplication1',
abilityName: 'ServiceExtensionAbility',
};
context.startAbility(want, (err) => {
console.error(`Failed to startAbility. Code: ${err.code}, message: ${err.message}`);
});
// (2) The ServiceExtensionAbility starts UIAbility2, carrying **"ability.params.backToOtherMissionStack": true** during the startup.
let context = ...; // ServiceExtensionContext
let want = {
bundleName: 'com.example.myapplication2',
abilityName: 'MainAbility',
parameters: {
"ability.params.backToOtherMissionStack": true,
},
};
context.startAbility(want, (err) => {
console.error(`Failed to startAbility. Code: ${err.code}, message: ${err.message}`);
});
```
Note: In the preceding example, when the ServiceExtensionAbility starts UIAbility2, **"ability.params.backToOtherMissionStack": true** is carried, indicating that redirection back across mission stacks is supported. Therefore, when you press **Back** on the page of UIAbility 2, the page of UIAbility1 page is displayed. However, if **ability.params.backToOtherMissionStack** is not carried or if **"ability.params.backToOtherMissionStack": false** is carried, the page of UIAbility1 is not displayed when you press **Back** on the page of UIAbility 2.
......@@ -113,10 +113,8 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error
**Example**
```js
import WantAgent from '@ohos.app.ability.wantAgent';
```ts
let wantAgent;
// WantAgentInfo object
let wantAgentInfo = {
wants: [
......@@ -1126,6 +1124,27 @@ let wantAgentInfo = {
wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
};
// getWantAgent callback
function getWantAgentCallback(err, data) {
if (err === undefined) {
wantAgent = data;
} else {
console.error('getWantAgent failed ${JSON.stringify(wantAgent)}');
}
// getOperationTypeCallback callback
function getOperationTypeCallback(err, data) {
if(err) {
console.error('getOperationType failed! ${err.code} ${err.message}');
} else {
console.info('getOperationType ok! ${JSON.stringify(data)}');
}
}
try {
WantAgent.getOperationType(wantAgent, getOperationTypeCallback);
} catch(err) {
console.error('getOperationTypeCallback failed! ${err.code} ${err.message}');
}
}
try {
WantAgent.getWantAgent(wantAgentInfo).then((data) => {
console.info('==========================>getWantAgentCallback=======================>');
......
......@@ -18,14 +18,14 @@ Enumerates the action constants of the **Want** object. **action** specifies the
**System capability**: SystemCapability.Ability.AbilityBase
| Name | Value | Description |
| ------------ | ------------------ | ---------------------- |
| DLP_PARAMS_SANDBOX |ohos.dlp.params.sandbox | Action of obtaining the sandbox flag.<br>**System API**: This is a system API and cannot be called by third-party applications. |
| DLP_PARAMS_BUNDLE_NAME |ohos.dlp.params.bundleName |Action of obtaining the DLP bundle name.<br>**System API**: This is a system API and cannot be called by third-party applications. |
| DLP_PARAMS_MODULE_NAME |ohos.dlp.params.moduleName |Action of obtaining the DLP module name.<br>**System API**: This is a system API and cannot be called by third-party applications. |
| DLP_PARAMS_ABILITY_NAME |ohos.dlp.params.abilityName |Action of obtaining the DLP ability name.<br>**System API**: This is a system API and cannot be called by third-party applications. |
| DLP_PARAMS_INDEX |ohos.dlp.params.index |Action of obtaining the DLP index.<br>**System API**: This is a system API and cannot be called by third-party applications. |
| ABILITY_BACK_TO_OTHER_MISSION_STACK |ability.params.backToOtherMissionStack |Action of returning the ability to the mission stack. |
| Name | Value | Description |
| ----------------------- | ---------------------------------- | ------------------------------------------------------------------------------ |
| DLP_PARAMS_SANDBOX | ohos.dlp.params.sandbox | Action of obtaining the sandbox flag.<br>**System API**: This is a system API and cannot be called by third-party applications.|
| DLP_PARAMS_BUNDLE_NAME | ohos.dlp.params.bundleName | Action of obtaining the DLP bundle name.<br>**System API**: This is a system API and cannot be called by third-party applications.|
| DLP_PARAMS_MODULE_NAME | ohos.dlp.params.moduleName | Action of obtaining the DLP module name.<br>**System API**: This is a system API and cannot be called by third-party applications.|
| DLP_PARAMS_ABILITY_NAME | ohos.dlp.params.abilityName | Action of obtaining the DLP ability name.<br>**System API**: This is a system API and cannot be called by third-party applications.|
| DLP_PARAMS_INDEX | ohos.dlp.params.index | Action of obtaining the DLP index.<br>**System API**: This is a system API and cannot be called by third-party applications.|
| ABILITY_BACK_TO_OTHER_MISSION_STACK | ability.params.backToOtherMissionStack | Whether to support redirection back across mission stacks.<br>**System API**: This is a system API and cannot be called by third-party applications.|
## wantConstant.Flags
......@@ -37,4 +37,4 @@ Enumerates the action constants of the **Want** object. **action** specifies the
| ------------------------------------ | ---------- | ------------------------------------------------------------ |
| FLAG_AUTH_READ_URI_PERMISSION | 0x00000001 | Indicates the permission to read the URI. |
| FLAG_AUTH_WRITE_URI_PERMISSION | 0x00000002 | Indicates the permission to write data to the URI. |
| FLAG_INSTALL_ON_DEMAND | 0x00000800 | Indicates that the specific ability will be installed if it has not been installed. |
| FLAG_INSTALL_ON_DEMAND | 0x00000800 | Indicates that the specific ability will be installed if it has not been installed. |
# @ohos.app.form.formInfo (formInfo)
# @ohos.app.form.formInfo (FormInfo)
The **formInfo** module provides types and enums related to the widget information and state.
The **FormInfo** module provides widget information and state.
> **NOTE**
>
......@@ -18,10 +18,12 @@ Describes widget information.
**System capability**: SystemCapability.Ability.Form
**System API**: This is a system API and cannot be called by third-party applications.
| Name | Type | Readable | Writable | Description |
| ----------- | -------- | -------- | -------------------- | ------------------------------------------------------------ |
| bundleName | string | Yes | No | Name of the bundle to which the widget belongs. |
| moduleName | string | Yes | No | Name of the module to which the widget belongs. |
| bundleName | string | Yes | No | Name of the bundle to which the widget belongs. |
| moduleName | string | Yes | No | Name of the module to which the widget belongs. |
| abilityName | string | Yes | No | Name of the ability to which the widget belongs. |
| name | string | Yes | No | Widget name. |
| description | string | Yes | No | Description of the widget. |
......@@ -30,10 +32,10 @@ Describes widget information.
| colorMode | [ColorMode](#colormode) | Yes | No | Color mode of the widget. |
| isDefault | boolean | Yes | No | Whether the widget is the default one. |
| updateEnabled | boolean | Yes | No | Whether the widget is updatable. |
| formVisibleNotify | boolean | Yes | No | Whether to send a notification when the widget is visible. |
| formVisibleNotify | string | Yes | No | Whether to send a notification when the widget is visible. |
| scheduledUpdateTime | string | Yes | No | Time when the widget was updated. |
| formConfigAbility | string | Yes | No | Configuration ability of the widget, that is, the ability corresponding to the option in the selection box displayed when the widget is long pressed. |
| updateDuration | number | Yes | No | Update period of the widget.|
| updateDuration | string | Yes | No | Update period of the widget.|
| defaultDimension | number | Yes | No | Default dimension of the widget. |
| supportDimensions | Array&lt;number&gt; | Yes | No | Dimensions supported by the widget. For details, see [FormDimension](#formdimension). |
| customizeData | {[key: string]: [value: string]} | Yes | No | Custom data of the widget. |
......@@ -99,8 +101,8 @@ Enumerates the widget parameters.
| WIDTH_KEY | "ohos.extra.param.key.form_width" | Widget width. |
| HEIGHT_KEY | "ohos.extra.param.key.form_height" | Widget height. |
| TEMPORARY_KEY | "ohos.extra.param.key.form_temporary" | Temporary widget. |
| ABILITY_NAME_KEY | "ohos.extra.param.key.ability_name" | Ability name. |
| DEVICE_ID_KEY | "ohos.extra.param.key.device_id" | Device ID. |
| ABILITY_NAME_KEY | "ohos.extra.param.key.ability_name" | Ability name. |
| DEVICE_ID_KEY | "ohos.extra.param.key.device_id" | Device ID.<br>**System API**: This is a system API. |
| BUNDLE_NAME_KEY | "ohos.extra.param.key.bundle_name" | Key that specifies the target bundle name.|
## FormDimension
......@@ -124,9 +126,9 @@ Defines the widget information filter. Only the widget information that meets th
**System capability**: SystemCapability.Ability.Form
| Name | Type | Description |
| ----------- | ---- | ------------ |
| moduleName | string | Optional. Only the information about the widget whose **moduleName** is the same as the provided value is returned.<br>If this parameter is not set, **moduleName** is not used for filtering. |
| Name | Description |
| ----------- | ------------ |
| moduleName | Only the information about the widget whose **moduleName** is the same as the provided value is returned.|
## VisibilityType
......@@ -136,5 +138,6 @@ Enumerates the visibility types of the widget.
| Name | Value | Description |
| ----------- | ---- | ------------ |
| UNKNOWN | 0 | The visibility type of the widget is unknown.|
| FORM_VISIBLE | 1 | The widget is visible.|
| FORM_INVISIBLE | 2 | The widget is invisible.|
......@@ -265,7 +265,7 @@ Deregisters the application state observer. This API uses an asynchronous callba
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| observerId | number | Yes| Numeric code of the observer.|
......@@ -327,7 +327,7 @@ Deregisters the application state observer. This API uses a promise to return th
getForegroundApplications(callback: AsyncCallback\<Array\<AppStateData>>): void;
Obtains information about the applications that are running in the foreground. This API uses an asynchronous callback to return the result. The application information is defined by [AppStateData](js-apis-inner-application-appStateData.md).
**Required permissions**: ohos.permission.GET_RUNNING_INFO
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -389,7 +389,11 @@ killProcessWithAccount(bundleName: string, accountId: number): Promise\<void\>
Kills a process by bundle name and account ID. This API uses a promise to return the result.
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS and ohos.permission.CLEAN_BACKGROUND_PROCESSES
> **NOTE**
>
> The **ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS** permission is not required when **accountId** specifies the current user.
**Required permissions**: ohos.permission.CLEAN_BACKGROUND_PROCESSES and ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -397,10 +401,10 @@ Kills a process by bundle name and account ID. This API uses a promise to return
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| bundleName | string | Yes| Bundle name.|
| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| bundleName | string | Yes| Bundle name.|
| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).|
**Example**
......@@ -423,19 +427,23 @@ killProcessWithAccount(bundleName: string, accountId: number, callback: AsyncCal
Kills a process by bundle name and account ID. This API uses an asynchronous callback to return the result.
> **NOTE**
>
> The **ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS** permission is not required when **accountId** specifies the current user.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**System API**: This is a system API and cannot be called by third-party applications.
**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS and ohos.permission.CLEAN_BACKGROUND_PROCESSES
**Required permissions**: ohos.permission.CLEAN_BACKGROUND_PROCESSES and ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| bundleName | string | Yes| Bundle name.|
| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).|
| callback | AsyncCallback\<void\> | Yes| Callback used to return the result.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| bundleName | string | Yes| Bundle name.|
| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).|
| callback | AsyncCallback\<void\> | Yes| Callback used to return the result.|
**Example**
......
......@@ -3,9 +3,16 @@
The **Configuration** module defines environment change information. **Configuration** is an interface definition and is used only for field declaration.
> **NOTE**
>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> This module is deprecated since API version 9. You are advised to use [@ohos.app.ability.Configuration](js-apis-app-ability-configuration.md) instead.
## Modules to Import
```ts
import Configuration from '@ohos.app.application.Configuration';
```
**System capability**: SystemCapability.Ability.AbilityBase
| Name| Type| Readable| Writable| Description|
......
......@@ -22,7 +22,7 @@ Sets the screen brightness.
**System API**: This is a system API.
**System capability**: SystemCapability.PowerManager.DisplayPowerManager
**System capability:** SystemCapability.PowerManager.DisplayPowerManager
**Parameters**
......@@ -34,9 +34,9 @@ Sets the screen brightness.
For details about the error codes, see [Screen Brightness Error Codes](../errorcodes/errorcode-brightness.md).
| Code | Error Message |
| ID | Error Message |
|---------|---------|
| 4700101 | Operation failed. Cannot connect to service.|
| 4700101 | If connecting to the service failed. |
**Example**
......
......@@ -1252,10 +1252,10 @@ For details about the following error codes, see [Telephony Error Codes](../../r
let rejectMessageOptions={
messageContent: "Unknown number blocked"
}
call.reject(1, rejectMessageOptions).then(() => {
console.log(`reject success.`);
call.rejectCall(1, rejectMessageOptions).then(() => {
console.log(`rejectCall success.`);
}).catch((err) => {
console.error(`reject fail, promise: err->${JSON.stringify(err)}`);
console.error(`rejectCall fail, promise: err->${JSON.stringify(err)}`);
});
```
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册
新手
引导
客服 返回
顶部