提交 341bacce 编写于 作者: Z zengyawen 提交者: Gitee

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

Signed-off-by: Nzengyawen <zengyawen1@huawei.com>
# File Management # File
- MediaLibrary Management
- [MediaLibrary Overview](medialibrary-overview.md)
- [Media Asset Management](medialibrary-resource-guidelines.md)
- [File Path Management](medialibrary-filepath-guidelines.md)
- [Album Management](medialibrary-album-guidelines.md)
- File Access Framework - [File Management Overview](file-management-overview.md)
- [File Access Framework Overview](file-access-framework-overview.md) - Application File
- [FilePicker Guide](filepicker-guidelines.md) - [Application File Overview](app-file-overview.md)
\ No newline at end of file - [Application Sandbox Directory](app-sandbox-directory.md)
- Application File Access and Management
- [Accessing Application Files](app-file-access.md)
- [Uploading and Downloading Application Files](app-file-upload-download.md)
- [Obtaining Application and File System Space Statistics](app-fs-space-statistics.md)
- [Sending Files to an Application Sandbox](send-file-to-app-sandbox.md)
- [Sharing an Application File](share-app-file.md)
- User File
- [User File Overview](user-file-overview.md)
- Selecting and Saving User Files (FilePicker)
- [Selecting User Files](select-user-file.md)
- [Saving User Files](save-user-file.md)
- [Developing a FileManager Application (Available Only for System Applications)](dev-user-file-manager.md)
- [Managing External Storage Devices (Available Only for System Applications)](manage-external-storage.md)
- Distributed File System
- [Distributed File System Overview](distributed-fs-overview.md)
- [Setting the Security Level of a Distributed File](set-security-label.md)
- [Access Files Across Devices](file-access-across-devices.md)
# Accessing Application Files
This topic describes how to view, create, read, write, delete, move, or copy a file in the application file directory and obtain the file information.
## Available APIs
You can use [ohos.file.fs](../reference/apis/js-apis-file-fs.md) to implement the application file access capabilities. The following table describes the APIs.
**Table 1** APIs for basic application file operations
| API| Description| Type| Synchronous Programming| Asynchronous Programming|
| -------- | -------- | -------- | -------- | -------- |
| access | Checks whether a file exists.| Method| √ | √ |
| close | Closes a file.| Method| √ | √ |
| copyFile | Copies a file.| Method| √ | √ |
| createStream | Creates a stream based on the specified file path.| Method| √ | √ |
| listFile | Lists all files in a directory.| Method| √ | √ |
| mkdir | Creates a directory.| Method| √ | √ |
| moveFile | Moves a file.| Method| √ | √ |
| open | Opens a file.| Method| √ | √ |
| read | Reads data from a file.| Method| √ | √ |
| rename | Renames a file or folder.| Method| √ | √ |
| rmdir | Deletes a directory.| Method| √ | √ |
| stat | Obtains detailed file information.| Method| √ | √ |
| unlink | Deletes a single file.| Method| √ | √ |
| write | Writes data to a file.| Method| √ | √ |
| Stream.close | Closes a stream.| Method| √ | √ |
| Stream.flush | Flushes all data from this stream.| Method| √ | √ |
| Stream.write | Writes data to a stream.| Method| √ | √ |
| Stream.read | Reads data from a stream.| Method| √ | √ |
| File.fd | Defines a file descriptor.| Attribute| √ | × |
| OpenMode | Defines the mode for opening a file.| Attribute| √ | × |
| Filter | Defines the options for setting the file filter.| Type| × | × |
## Development Example
Obtain the [application file path](../application-models/application-context-stage.md#obtaining-the-application-development-path). The following example shows how to obtain a HAP file path using **UIAbilityContext**. For details about how to obtain **UIAbilityContext**, see [Obtaining the Context of UIAbility](../application-models/uiability-usage.md#obtaining-the-context-of-uiability).
The following describes common file operations.
### Creating, Reading, and Writing a File
The following example demonstrates how to create a file, read data from it, and write data to it.
```ts
// pages/xxx.ets
import fs from '@ohos.file.fs';
import common from '@ohos.app.ability.common';
function createFile() {
// Obtain the application file path.
let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir;
// Create a file and open it.
let file = fs.openSync(filesDir + '/test.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
// Write data to the file.
let writeLen = fs.writeSync(file.fd, "Try to write str.");
console.info("The length of str is: " + writeLen);
// Read data from the file.
let buf = new ArrayBuffer(1024);
let readLen = fs.readSync(file.fd, buf, { offset: 0 });
console.info("the content of file: " + String.fromCharCode.apply(null, new Uint8Array(buf.slice(0, readLen))));
// Close the file.
fs.closeSync(file);
}
```
### Copying Data to Another File
The following example demonstrates how to write the data read from a file to another file.
```ts
// pages/xxx.ets
import fs from '@ohos.file.fs';
import common from '@ohos.app.ability.common';
function readWriteFile() {
// Obtain the application file path.
let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir;
// Open the source and destination files.
let srcFile = fs.openSync(filesDir + '/test.txt', fs.OpenMode.READ_WRITE);
let destFile = fs.openSync(filesDir + '/destFile.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
// Read data from the source file and copy it to the destination file.
let bufSize = 4096;
let readSize = 0;
let buf = new ArrayBuffer(bufSize);
let readLen = fs.readSync(srcFile.fd, buf, { offset: readSize });
while (readLen > 0) {
readSize += readLen;
fs.writeSync(destFile.fd, buf);
readLen = fs.readSync(srcFile.fd, buf, { offset: readSize });
}
// Close the files.
fs.closeSync(srcFile);
fs.closeSync(destFile);
}
```
> **NOTE**
>
> When using **read()** or **write()**, pay attention to the optional parameter **offset**. For a file that has been read or written, the offset pointer is at the end position of the last read or write operation by default.
### Reading and Writing Files in a Stream
The following example demonstrates how to read and write file data using a stream.
```ts
// pages/xxx.ets
import fs from '@ohos.file.fs';
import common from '@ohos.app.ability.common';
async function readWriteFileWithStream() {
// Obtain the application file path.
let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir;
// Open the file streams.
let inputStream = fs.createStreamSync(filesDir + '/test.txt', 'r+');
let outputStream = fs.createStreamSync(filesDir + '/destFile.txt', "w+");
// Read data from the source file and write the data to the destination file using a stream.
let bufSize = 4096;
let readSize = 0;
let buf = new ArrayBuffer(bufSize);
let readLen = await inputStream.read(buf, { offset: readSize });
readSize += readLen;
while (readLen > 0) {
await outputStream.write(buf);
readLen = await inputStream.read(buf, { offset: readSize });
readSize += readLen;
}
// Close the streams.
inputStream.closeSync();
outputStream.closeSync();
}
```
> **NOTE**
>
> Close the stream that is no longer used in a timely manner. <br>Comply with the related programming specifications for **Stream** APIs in asynchronous mode and avoid mixed use of the APIs in synchronous mode and asynchronous mode. <br>The **Stream** APIs do not support concurrent read and write operations.
### Listing Files
The following example demonstrates how to list files.
```ts
// List files.
import fs from '@ohos.file.fs';
import common from '@ohos.app.ability.common';
// Obtain the application file path.
let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir;
// List files that meet the specified conditions.
let options = {
recursion: false,
listNum: 0,
filter: {
suffix: ['.png', '.jpg', '.txt'], // The filename extension can be '.png', '.jpg', or '.txt'.
displayName: ['test%'], // The filename starts with 'test'.
fileSizeOver: 0, // The file size is greater than or equal to 0.
lastModifiedAfter: new Date(0).getTime(), // The latest modification time of the file is later than January 1, 1970.
},
}
let files = fs.listFileSync(filesDir, options);
for (let i = 0; i < files.length; i++) {
console.info(`The name of file: ${files[i]}`);
}
```
# Application File Overview
Application files are files of an application, including the application's installation files, resource files, and cache files.
- The data used and saved by an application is stored in files, key-value (KV) pairs, and databases in a dedicated directory on a device. This directory is called application file directory, and the files in the directory are application files.
- The directories visible to an application include the application file directory and a directory containing the minimum system files required for the running of the application. These two directories constitute an [application sandbox directory](app-sandbox-directory.md). That means, the application file directory is a subset of the application sandbox directory.
- The system files and directories are read-only for the application. The application can only save files to sub-directories in the [application file directory](app-sandbox-directory.md#application-file-directory-and-application-file-path) based on certain rules.
The following topics describe the application sandbox, application file directories, and how to access, manage, and share application files.
# Uploading and Downloading an Application File
This topic describes how to upload an application file to a network server and download a network resource file from a network server to a local application directory.
## Uploading an Application File
You can use [ohos.request](../reference/apis/js-apis-request.md) **uploadFile()** to upload local files. The system service proxy implements the upload.
> **NOTE**
>
> Currently, only the files in the **cache/** directories (**cacheDir**) can be uploaded.
>
> <br>The **ohos.permission.INTERNET** permission is required for using **ohos.request**. For details about how to apply for a permission, see [Applying for Permissions](../security/accesstoken-guidelines.md).
The following example demonstrates how to upload a file in the **cache** directory of an application to a network server.
```ts
// pages/xxx.ets
import common from '@ohos.app.ability.common';
import fs from '@ohos.file.fs';
import request from '@ohos.request';
// Obtain the application file path.
let context = getContext(this) as common.UIAbilityContext;
let cacheDir = context.cacheDir;
// Create an application file locally.
let file = fs.openSync(cacheDir + '/test.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
fs.writeSync(file.fd, 'upload file test');
fs.closeSync(file);
// Configure the upload task.
let uploadConfig = {
url: 'https://xxx',
header: { key1: 'value1', key2: 'value2' },
method: 'POST',
files: [
{ filename: 'test.txt', name: 'test', uri: 'internal://cache/test.txt', type: 'txt' }
],
data: [
{ name: 'name', value: 'value' }
]
}
// Upload the created application file to the network server.
try {
request.uploadFile(context, uploadConfig)
.then((uploadTask) => {
uploadTask.on('complete', (taskStates) => {
for (let i = 0; i < taskStates.length; i++) {
console.info(`upload complete taskState: ${JSON.stringify(taskStates[i])}');
}
});
})
.catch((err) => {
console.error(`Invoke uploadFile failed, code is ${err.code}, message is ${err.message}`);
})
} catch (err) {
console.error(`Invoke uploadFile failed, code is ${err.code}, message is ${err.message}`);
}
```
## Downloading a Network Resource File to the Application File Directory
You can use [ohos.request](../reference/apis/js-apis-request.md) **downloadFile()** to download network resource files to a local application directory. You can use the ([ohos.file.fs](../reference/apis/js-apis-file-fs.md) APIs to access the downloaded files. For details, see [Accessing Application Files](app-file-access.md). The system service proxy implements the download.
> **NOTE**
>
> Currently, network resource files can be downloaded only to an application file directory.
>
> <br>The **ohos.permission.INTERNET** permission is required for using **ohos.request**. For details about how to apply for a permission, see [Applying for Permissions](../security/accesstoken-guidelines.md).
The following example demonstrates how to download a network resource file to a local application file directory.
```ts
// pages/xxx.ets
// Download the network resource file to the local application file directory, and read data from the file.
import common from '@ohos.app.ability.common';
import fs from '@ohos.file.fs';
import request from '@ohos.request';
// Obtain the application file path.
let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir;
try {
request.downloadFile(context, {
url: 'https://xxxx/xxxx.txt',
filePath: filesDir + '/xxxx.txt'
}).then((downloadTask) => {
downloadTask.on('complete', () => {
console.info('download complete');
let file = fs.openSync(filesDir + '/xxxx.txt', fs.OpenMode.READ_WRITE);
let buf = new ArrayBuffer(1024);
let readLen = fs.readSync(file.fd, buf);
console.info(`The content of file: ${String.fromCharCode.apply(null, new Uint8Array(buf.slice(0, readLen)))}`);
fs.closeSync(file);
})
}).catch((err) => {
console.error(`Invoke downloadTask failed, code is ${err.code}, message is ${err.message}`);
});
} catch (err) {
console.error(`Invoke downloadFile failed, code is ${err.code}, message is ${err.message}`);
}
```
# Obtaining Application and File System Space Statistics
This topic describes how to obtain information about the free system space and space occupied by applications so as to prevent insufficient storage space of the system or ensure proper use of quota-controlled **cacheDir** directories.
## Available APIs
For details about the APIs, see [ohos.file.statvfs](../reference/apis/js-apis-file-statvfs.md) and [ohos.file.storageStatistics](../reference/apis/js-apis-file-storage-statistics.md).
**Table 1** APIs for file system and application space statistics
| Module| API| Description|
| -------- | -------- | -------- |
| \@ohos.file.storageStatistic | getCurrentBundleStats | Obtains the storage space of the current application, in bytes.|
| \@ohos.file.statvfs | getFreeSize | Obtains the free space of a file system, in bytes.|
| \@ohos.file.statvfs | getTotalSize | Obtains the total space of a file system, in bytes.|
**Table 2** Attributes for application space statistics
| BundleStats Attribute| Description| Directory for Statistics|
| -------- | -------- | -------- |
| appSize | Size of the application installation files, in bytes.| Application installation file directory:<br>**/data/storage/el1/bundle **|
| cacheSize | Size of the application cache files, in bytes.| Application cache file directories:<br>**/data/storage/el1/base/cache**<br>**/data/storage/el1/base/haps/entry/cache**<br>**/data/storage/el2/base/cache**<br>**/data/storage/el2/base/haps/entry/cache **|
| dataSize | Size of the application files (excluding the application installation files and cache files), in bytes.| The application files include local files, distributed files, and database files.<br>- Local application file directories (parent directories of the **cache** directories):<br>**/data/storage/el1/base**<br>**/data/storage/el2/base**<br>- Distributed application directory:<br>/data/storage/el2/distributedfiles<br>- Database directories:<br>**/data/storage/el1/database**<br>**/data/storage/el2/database **|
## Development Example
- Obtain the free space of **/data** of the file system.
```ts
import statvfs from '@ohos.file.statvfs';
let path = "/data";
statvfs.getFreeSize(path, (err, number) => {
if (err) {
console.error(`Invoke getFreeSize failed, code is ${err.code}, message is ${err.message}`);
} else {
console.info(`Invoke getFreeSize succeeded, size is ${number}`);
}
});
```
- Obtain the space occupied by the current application.
```ts
import storageStatistics from "@ohos.file.storageStatistics";
storageStatistics.getCurrentBundleStats((err, bundleStats) => {
if (err) {
console.error(`Invoke getCurrentBundleStats failed, code is ${err.code}, message is ${err.message}`);
} else {
console.info(`Invoke getCurrentBundleStats succeeded, appsize is ${bundleStats.appSize}`);
}
});
```
# Application Sandbox Directory
The application sandbox is an isolation mechanism to prevent data from being accessed through path traversal. This mechanism allows only the application sandbox directory visible to an application.
- The system maps a dedicated application sandbox directory in the internal storage space for each application. The directory is a collection of the [application file directory](app-file-overview.md) and a directory containing the minimum system files required during application's runtime.
- The application sandbox specifies the minimum range of data visible to each application. In the application sandbox directory, an application can access only its own application files and the system files required for its running. The application cannot access files of other applications. The security of application files is protected in this way.
- In each application sandbox directory, the application can save and process its own application files in the [application file directory](app-file-overview.md), and can only read the system files and directories. The application can access [user files](user-file-overview.md) by using specific APIs only with authorization from the user.
The following figure illustrates the file access scope and modes for an application in an application sandbox.
**Figure 1** File access in an application sandbox
![Application sandbox file access relationship](figures/application-sandbox-file-access-relationship.png)
## Application Sandbox Directory and Application Sandbox Path
With the application sandbox mechanism, an application cannot learn the location and existence of other applications' directories and user file directories. In addition, all the application directories visible to an application are isolated by permission and namespace to form an independent directory view and shield the real (physical) paths.
- As shown in the following figure, the sandbox mechanism minimizes the number of directories and files visible to a common application (third-party application). The directories and file paths visible to a common application are different from those visible to a system process. The path of a file or folder in the application sandbox directory visible to a common application is called the application sandbox path.
- You can view the real application paths (the directory view visible to a system process) in the HDC shell environment. For details about the mappings between the application sandbox paths and real application paths, see [Mappings Between Application Sandbox Paths and Physical Paths](send-file-to-app-sandbox.md#mappings-between-application-sandbox-paths-and-physical-paths).
- The application sandbox paths and physical paths are not in one-to-one mappings. The application sandbox paths are always less than the physical paths. You may not obtain the the application sandbox path based on a physical path in certain cases, but you can obtain the physical path based on an application sandbox path.
**Figure 2** Different directory views to processes and applications
![Application sandbox path](figures/application-sandbox-path.png)
## Application File Directory and Application File Path
The application sandbox directory includes application file directories and system file directories.
The system file directories visible to an application are preset by OpenHarmony.
The following figure shows the application file directories. The path of a file or a folder in the application file directory is called the application file path. The file paths in the application file directory have different attributes and characteristics.
**Figure 3** Application file directory structure
![Application file directory structure](figures/application-file-directory-structure.png)
1. Level 1 directory **data/**: indicates the application file directory.
2. Level 2 directory **storage/**: indicates a directory for persistent files of the application.
3. Level 3 directories **el1/** and **el2/**: indicate directories for files of different encryption levels (els).
- **el1**: directory for the data that can be accessed once the device starts. This directory contains device-focused files.
- **el2**: directory for the data that can be accessed only after at lease one successful unlocking operation (by PIN, fingerprint, or facial authentication, or password-free sign-in) upon the start of the device. This directory contains user-focused files.<br>
Unless otherwise required, application data is placed in the **el2** directory for security purposes. However, the data that needs to be accessed before the screen is unlocked (such as the clock, alarm, and wallpaper data) can be placed in the **el1** directory. For details about how to switch to and modify the **el** directories, see [Obtaining and Modifying el Directories](../application-models/application-context-stage.md#obtaining-and-modifying-encryption-areas).
4. Level 4 and level 5 directories:
The application's global data is stored in the **files**, **cache**, **preferences**, **temp**, and **distributedfiles** folders in **base**. You can use **ApplicationContext** to obtain the application file paths of these folders.
You can use **UIAbilityContext**, **AbilityStageContext**, and **ExtensionContext** to obtain application file paths related to the OpenHarmoy Ability Package (HAP). When the HAP is uninstalled, the files stored in these directories are automatically deleted, without affecting the files in app-level directories. An application in the development state contains one or more HAPs. For details, see [Application Package Structure in Stage Mode](../quick-start/application-package-structure-stage.md).
For details about how to obtain the context and application file paths, see [Context (Stage Model)](../application-models/application-context-stage.md).
> **NOTE**
>
> - Do not directly use file paths made up by level 1 to level 4 directory names. Incompatibility problems may occur if the directory names are changed in later versions.
> - Use **Context** to obtain application file paths, which include but are not limited to the directories highlighted in green in **Figure 3**.
The following table describes the application file paths and lifecycle.
**Table 1** Application file paths
| Folder| Context Attribute Name| Type| Description|
| -------- | -------- | -------- | -------- |
| bundle | bundleCodeDir | Installation file directory| Directory for saving the HAPs of the application after an application is installed.<br>This directory is cleared when the application is uninstalled.<br> Do not access resource files by concatenating paths. Use [@ohos.resourceManager] instead.|
| base | NA | Directory for local device files| Directory for saving the application's persistent data on the device. Subdirectories include **files/**,** cache/**, **temp/**, and **haps/**.<br>This directory is cleared when the application is uninstalled.|
| database | databaseDir | Database directory| Directory in **el1** for saving the files operated by the distributed database service.<br>This directory is cleared when the application is uninstalled.|
| distributedfiles | distributedFilesDir | Distributed file directory| Directory in **el2** for saving the application files that can be directly accessed across devices.<br>This directory is cleared when the application is uninstalled.|
| files | filesDir | Application file directory| Directory for saving the application's persistent files on the device.<br>This directory is cleared when the application is uninstalled.|
| cache | cacheDir | Application cache file directory| Directory for caching the downloaded files of the application or saving the cache files regenerated on the device.<br>This directory is automatically cleared when the size of the **cache** directory reaches the quota or the system storage space reaches a certain threshold. The user can also clear this directory by using a system space management application. <br>The application needs to check whether the file still exists and determine whether to cache the file again.|
| preferences | preferencesDir | Preferences file directory| Directory for saving common application configuration and user preference data managed by using database APIs.<br>This directory is cleared when the application is uninstalled. For details, see [Data Persistence by User Preferences](../database/data-persistence-by-preferences.md).|
| temp | tempDir | Temporary file directory| Directory for saving the files generated and required during the application's runtime on the device. <br>This directory is cleared when the application exits.|
The application file paths are used in the following scenarios:
- Installation file directory<br>
Used to store the code resource data of the application, including the HAPs of the application, reusable library files, and plug-ins. The code stored in this directory can be dynamically loaded.
- Database directory<br>
Used to store only the application's private database data, such as database files. This directory can be used to store distributed database data only.
- Distributed file directory<br>
Used to store the application's data used for distributed scenarios, including file sharing, file backup, and file processing across devices. The data stored in this directory enables the application to run smoothly on multiple devices.
- Application file directory<br>
Used to store private data of the application, including persistent files, images, media files, and log files. The data is stored in this directory to ensure privacy, security, and permanent validity.
- Cached application file directory<br>
Used to store cached data of the application, including offline data, cached images, database backup, and temporary files. Data stored in this directory may be automatically deleted by the system. Therefore, do not store important data in this directory.
- Preferences file directory<br>
Used to store application preferences data, including preference files and configuration files. This directory applied to storing only a small amount of data.
- Temporary file directory<br>
Used to store temporarily generated data of an application, including cached database data and images, temporary log files, downloaded application installation package files. The data stored in this directory is deleted after being used.
<!--no_check-->
\ No newline at end of file
# Developing a FileManager Application (Available Only for System Applications)
OpenHarmony is prebuilt with the **FileManager** application. You can also develop your own **FileManager** as required.
## Available APIs
For details about the APIs, see [User File Access and Management](../reference/apis/js-apis-fileAccess.md).
## How to Develop
1. Configure the permissions required and import dependent modules.
Apply for the **ohos.permission.FILE_ACCESS_MANAGER** and **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** permissions. For details, see [Applying for Permissions](../security/accesstoken-guidelines.md).
> **NOTE**
>
> **ohos.permission.FILE_ACCESS_MANAGER** is required for using the user file access framework APIs.
>
> **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** is required for querying information about file management server applications supported by the system.
2. Import the dependent modules.
```ts
import fileAccess from '@ohos.file.fileAccess';
import fileExtensionInfo from '@ohos.file.fileExtensionInfo';
```
The **fileAccess** module provides APIs for basic file operations, and the **fileExtensionInfo** module provides key structs for application development.
3. Query device information.
You can obtain attributes of one or all devices managed by the file management server in the current system. You can also filter devices as required.
In the user file access framework, **RootInfo** indicates the attribute information of a device. For example, obtain **RootInfo** of all devices.
```ts
// Create a helper object for connecting to all file management servers in the system.
let fileAccessHelperAllServer = null;
createFileAccessHelper() {
try { // this.context is the context passed from EntryAbility.
fileAccessHelperAllServer = fileAccess.createFileAccessHelper(this.context);
if (!fileAccessHelperAllServer) {
console.error("createFileAccessHelper interface returns an undefined object");
}
} catch (error) {
console.error("createFileAccessHelper failed, errCode:" + error.code + ", errMessage:" + error.message);
}
}
async getRoots() {
let rootIterator = null;
let rootInfos = [];
let isDone = false;
try {
rootIterator = await fileAccessHelperAllServer.getRoots();
if (!rootIterator) {
console.error("getRoots interface returns an undefined object");
return;
}
while (!isDone) {
let result = rootIterator.next();
console.info("next result = " + JSON.stringify(result));
isDone = result.done;
if (!isDone)
rootinfos.push(result.value);
}
} catch (error) {
console.error("getRoots failed, errCode:" + error.code + ", errMessage:" + error.message);
}
}
```
4. View directories.
In the user file access framework, **FileInfo** indicates basic information about a file (directory). You can use **listfile()** to traverse all files (directories) of the next level to obtain a **FileIterator** object or use **scanfile()** to filter the specified directories and obtain the **FileIterator** object that meets the conditions.
Currently, **listfile()** and **scanfile()** can be called by the **RootInfo** object to traverse lower-level files or filter the entire directory tree. In addition, **listfile()** and **scanfile()** can be called by the **FileInfo** object to traverse lower-level files or filter specified directories.
```ts
// Start from the root directory.
let rootInfo = rootinfos[0];
let fileInfos = [];
let isDone = false;
let filter = {suffix: [".txt", ".jpg", ".xlsx"]}; // Set filter criteria.
try {
let fileIterator = rootInfo.listFile(); // Traverse the root directory of rootinfos[0] and return an iterator object.
// let fileIterator = rootInfo.scanFile(filter); // Filter the file information of device rootinfos[0] that meets the specified conditions and return an iteration object.
if (!fileIterator) {
console.error("listFile interface returns an undefined object");
return;
}
while (!isDone) {
let result = fileIterator.next();
console.info("next result = " + JSON.stringify(result));
isDone = result.done;
if (!isDone)
fileInfos.push(result.value);
}
} catch (error) {
console.error("listFile failed, errCode:" + error.code + ", errMessage:" + error.message);
}
// Start from the specified directory.
let fileInfoDir = fileInfos[0]; // fileInfoDir indicates information about a directory.
let subFileInfos = [];
let isDone = false;
let filter = {suffix: [".txt", ".jpg", ".xlsx"]}; // Set filter criteria.
try {
let fileIterator = fileInfoDir.listFile(); // Traverse files in the specified directory and return an iterator object.
// let fileIterator = rootInfo.scanFile(filter); // Filter the files in the specified directory and return an iterator object.
if (!fileIterator) {
console.error("listFile interface returns an undefined object");
return;
}
while (!isDone) {
let result = fileIterator.next();
console.info("next result = " + JSON.stringify(result));
isDone = result.done;
if (!isDone)
subfileInfos.push(result.value);
}
} catch (error) {
console.error("listFile failed, errCode:" + error.code + ", errMessage:" + error.message);
}
```
5. Perform operations on files or directories.
You can integrate APIs of the user file access framework to implement user behaviors, such as deleting, renaming, creating, and moving a file (directory). The following example shows how to create a file. For details about other APIs, see [User File Access and Management](../reference/apis/js-apis-fileAccess.md).
```ts
// The local device is used as an example.
// Create a file.
// sourceUri is the URI in fileinfo of the Download directory.
// You need to use the obtained URI for development.
let sourceUri = "datashare:///media/file/6";
let displayName = "file1";
let fileUri = null;
try {
// Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
fileUri = await fileAccessHelper.createFile(sourceUri, displayName);
if (!fileUri) {
console.error("createFile return undefined object");
return;
}
console.info("createFile sucess, fileUri: " + JSON.stringify(fileUri));
} catch (error) {
console.error("createFile failed, errCode:" + error.code + ", errMessage:" + error.message);
};
```
# Distributed File System Overview
OpenHarmony distributed file system (hmdfs) provides cross-device file access capabilities applicable to the following scenarios:
- The user can use the editing software on one device to edit the files on another device.
- Music stored on a tablet can be directly viewed and played by a in-car system.
- The user can use a tablet to view the photos taken by another device.
The hmdfs provides a globally consistent access view for each device dynamically connected to a network via DSoftBus and allows you to implement high-performance read and write operations on files with low latency by using basic file system APIs.
## Distributed File System Architecture
![Distributed File System Architecture](figures/distributed-file-system-architecture.png)
- distributedfile_daemon: listens for device online status, establishes links over DSoftBus, and applies data transfer policies based on the security level of the device.
- hmdfs: implements a network file system in the kernel, providing cache management, file access, metadata management, and conflict management.
- Buffer management
- After devices are connected to form a Virtual Device, hmdfs provides file access capabilities, but does not proactively transmit or copy files. Active copy is required when an application needs to save data to a local directory.
- The hmdfs ensures close-to-open cache consistency, which allows data to flushed when a client closes a file. Then, the latest data can be read when the file is opened on any other client. The hmdfs does not ensure real-time consistency of the file content.
- If data written at the peer end has not been flushed to the local end in a timely manner due to network problems, the file system flushes the data to the local end upon the next network access. However, if the data has been modified on the remote end, only the latest data can be flushed.
- File access
- OpenHarmony provides the same interface, [ohos.file.fs](../reference/apis/js-apis-file-fs.md), for accessing files in the local and distributed file systems.
- The files in the local file system are accessed in overlay mode.
- The files on another device are accessed over a synchronous network.
> **NOTE**
>
> symlink is not supported.
- Metadata management
- In distributed networking, when a file is created, deleted, or modified on a client, the latest file can be viewed on another client. The speed varies depending on the network status.
- If a device goes offline, its data is no longer visible to other devices. However, due to the delay in sensing the device offline, the files of some offline devices may also be visible to other devices. Therefore, you need to consider the network delay in application development.
- Conflict Handling
- If a file on the local end and a file on the remote end have the same name, the file on the remote end will be renamed.
- If multiple remote devices have files of the same name, the name of the file with the smallest device access ID is retained and the files on other devices will be renamed.
- In the networking scenario, the directory tree has remote files. If "duplicate file name" is displayed when a file is created,
- the conflict file is renamed "_conflict_dev_ID". The ID automatically increases from 1.
- If a local directory has the same name as a remote directory, "_remote_directory" will be added to the end of the peer directory.
# Access Files Across Devices
The distributed file system provides cross-device file access capabilities for applications. For the same application installed on multiple devices, you can implement read and write of the files in the application's distributed directory (**/data/storage/el2/distributedfiles/**) across devices by using [ohos.file.fs](app-file-access.md). For example, device A and device B are installed with the same application. After device A and device B are connected to form a Virtual Device, the application on device A can access the files of the same application on Device B. What you need to do is place the files to the distributed directory.
## How to Develop
1. Complete distributed networking for the devices.
Connect the devices to a LAN, and complete authentication of the devices. The devices must have the same account number.
2. Implement cross-device access to the files of the same application.
Place the files in the **distributedfiles/** directory of the application sandbox to implement access from difference devices.
For example, create a test file in the **distributedfiles/** directory on device A and write data to the file. For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../application-models/uiability-usage.md#obtaining-the-context-of-uiability).
```ts
import fs from '@ohos.file.fs';
let context =...; // Obtain the UIAbilityContext information of device A.
let pathDir = context.distributedFilesDir;
// Obtain the file path of the distributed directory.
let filePath = pathDir + '/test.txt';
try {
// Create a file in the distributed directory.
let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
console.info('Succeeded in createing.');
// Write data to the file.
fs.writeSync(file.fd, 'content');
// Close the file.
fs.closeSync(file.fd);
} catch (err) {
console.error(`Failed to openSync / writeSync / closeSync. Code: ${err.code}, message: ${err.message}`);
}
```
Read the file on device B.
```ts
import fs from '@ohos.file.fs';
let context =...; // Obtain the UIAbilityContext information of device B.
let pathDir = context.distributedFilesDir;
// Obtain the file path of the distributed directory.
let filePath = pathDir + '/test.txt';
try {
// Open the file in the distributed directory.
let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE);
// Set the buffer for receiving the read data.
let buffer = new ArrayBuffer(4096);
// Read the file. The return value is the number of read bytes.
let num = fs.readSync(file.fd, buffer, {
offset: 0
});
// Print the read data.
console.info('read result: ' + String.fromCharCode.apply(null, new Uint8Array(buffer.slice(0, num))));
} catch (err) {
console.error(`Failed to openSync / readSync. Code: ${err.code}, message: ${err.message}`);
}
```
# File Access Framework Overview
On devices running OpenHarmony 3.2 (API version 9) or later, applications can access public files on the local device, remote device, and external storage device, as well as files shared by multiple users, based on the File Access Framework (FAF).
To ensure user data privacy, this framework allows users to create, open, delete, rename, and move files on the file access server only through the **File Manager** and **File Picker** applications.
The user data of an application is stored on the device even after the application is uninstalled.
If a system application needs to access public files on the local device, use [File Path Management](medialibrary-filepath-guidelines.md).
> **NOTE**
> 1. For a non-management system application, for example, **Gallery**, use the **mediaLibrary** APIs for direct file operation.
> 2. In principle, do not mix use the FAF APIs with the mediaLibrary APIs.
## FAF Mechanism
Based on the OpenHarmony [ExtensionAbility mechanism](../application-models/extensionability-overview.md), the FAF provides unified APIs for external systems. With these APIs, applications can preview and operate public files to implement their own logic.
You can visit the [source repository](https://gitee.com/openharmony/filemanagement_user_file_service) for more details.
The following figure shows the FAF-based file operation process.
**Figure 1** Hierarchy of public file operations
![](figures/public-file-operation.png)
- **File access client**: an application that needs to access or operate public files. By starting the file selector application, it enables users to perform file operations on the UI.
- **File selector application**: a system application that allows users to access all shared datasets. You can use the FAF APIs to operate the datasets.
- **File access server**: a service that supports dataset sharing in the system. Currently, [UserFileManager](https://gitee.com/openharmony/multimedia_medialibrary_standard) and ExternalFileManager are available. UserFileManager manages datasets on local disks and distributed devices, and ExternalFileManager manages datasets on external storage devices such as SD cards and USB flash drives. You can also share your own datasets based on the FAF server configuration.
The FAF has the following features:
- Users can browse the datasets provided by all file server applications in the system, rather than those provided by a single application.
- The file access client can operate files through the file selector application, without obtaining the permission to use the FAF.
- Multiple temporarily mounted devices, such as external storage cards and distributed devices, can be accessed at the same time.
## Data Models
Data models in the FAF are transferred through URI, FileInfo, and RootInfo. For details, see [fileExtension](../reference/apis/js-apis-fileExtensionInfo.md). Applications on the file access server can use the **FileAccessExtensionAbility** APIs to securely share their data.
**Figure 2** Data flow of the public file access framework
![](figures/faf-data-flow.png)
NOTE
- In the FAF, the file access client does not directly interact with the file access server. The client only needs to have the permission to start the file selector application.
- The file selector application provides a standard document access UI for users, even if the underlying file access servers differ greatly.
# File Management Overview
The data in an operating system (OS) can be classified into the following types based on the data structure:
- Structured data: data that can be defined in a unified data model. The structured data is generally stored in a database. In application development, the management of structured data is implemented by the [data management module](../database/data-mgmt-overview.md).
- Unstructured data: data that does not conform to any predefined data structure or model and cannot be easily presented in two-dimensional database tables. Unstructured data includes files in a variety of formats, such as documents, images, videos, and audio clips. In application development, the management of unstructured data is implemented by the file management module, which will be elaborated in this document.
In the file management module, the files can be classified into the following types based on the file owner:
- [Application files](app-file-overview.md): files of an application, including the application's installation files, resource files, and cached files.
- [User files](user-file-overview.md): files of a user who logs in to the device, including the user's images, video and audio clips, and documents.
- System files: files irrelevant to applications and users, including public libraries, device files, and system resource files. System files do not need to be managed by developers and are not described in this document.
The file systems can be classified into the following types based on the file storage location (data source location):
- Local file system: provides capabilities for accessing the files stored on a local device or its external storage devices (such as USB flash drives and removable hard drives). The local file system is the most basic file system and is not described in this document.
- [Distributed file system](distributed-fs-overview.md): provides capabilities for accessing files across devices, which are connected through a computer network.
**Figure 1** Files in an OS
![File classification model](figures/file-classification-model.png)
<!--no_check-->
\ No newline at end of file
# FilePicker Guide
FilePicker is a system application preset in OpenHarmony. You can use it to select and save files. For details about the implementation of FilePicker, see [applications_filepicker](https://gitee.com/openharmony/applications_filepicker).
FilePicker provides the following modes:
- **choose**: Use this mode when an application needs to select and upload or send files (including media resources such as images, and audio and video clips) in the device. When this mode is selected, the FilePicker **choose** mode window will be triggered to display a dialog box for you to select a file. You can select the target file and tap **Upload**. The application will receive the URI of the target file returned by FilePicker.
- **save**: Use this mode when an application needs to download and save files (including media resources such as images and audio and video clips). When this mode is selected, the FilePicker **save** mode window will be triggered to display a dialog box for you to select the destination path of the file to save. You can select the destination path and tap **Save**. The application will receive the URI of the saved file returned by FilePicker.
## Development Guidelines
> **NOTE**
> FilePicker supports only the applications developed based on the stage model.
> For details about the stage model, see [Interpretation of the Application Model](../application-models/application-model-description.md).
You can use [AbilityContext.startAbilityForResult(want, options)](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartabilityforresult-1) with different parameters to start FilePicker in different modes.
You need to use [Want](../reference/apis/js-apis-application-want.md) to specify **bundleName** and **abilityName** to start FilePicker. For details, see the following sample code.
You also need to set **Want.parameters** to specify the FilePicker mode to start and the name of the file to save.
- To select a file, set **'startMode': 'choose'**.
- To save a file, set **'startMode': 'save'** and **'saveFile'**.
You can set **options** of the [StartOptions](../reference/apis/js-apis-app-ability-startOptions.md) type to specify the dialog box style. The recommended value is **windowMode: 102**, which indicates a floating window.
> **CAUTION**
> - In the **save** mode, a strong verification is performed on the file path based on the name of the file to save. For details about the file path format, see [File Path Management](medialibrary-filepath-guidelines.md).
> - If a file with the same name exists, a dialog box will be displayed asking you whether to overwrite the existing file.
ArkTS sample code:
```ts
// Start FilePicker to select a file.
globalThis.context.startAbilityForResult(
{
action: "ohos.want.action.OPEN_FILE",
parameters: {
'startMode': 'choose', //choose or save
}
},
{ windowMode: 102 }
)
// Start FilePicker to save a file.
globalThis.context.startAbilityForResult(
{
action: "ohos.want.action.CREATE_FILE",
parameters: {
'startMode': 'save', //choose or save
'saveFile': 'test.jpg',
}
},
{ windowMode: 102 }
)
// Data returned by FilePicker to startAbilityForResult.
let abilityResult = {
resultCode: resultCode,
want: {
parameters: {
'startMode': startMode,
'result': result
}
}
}
globalThis.context.terminateSelfWithResult(abilityResult)
```
# Managing External Storage Devices (Available Only for System Applications)
External storage devices are pluggable. OpenHarmony provides the functions of listening for the device insertion and removal events and mounting/unmounting an external storage device.
External storage devices are managed by the StorageManager and StorageDaemon services. StorageDaemon implements the underlying listening and mount/unmount functions. StorageManager provides status change notifications, query, and management capabilities for system applications.
**Figure 1** External storage device management
![External storage device management](figures/external-storage-device-management.png)
- When an external storage device is inserted, the StorageDaemon process obtains an insertion event over netlink and creates a disk device and volume. The created volume is in the **UNMOUNTED** state.
- Then, the StorageDaemon process checks the volume. During the check process, the volume is in the **CHECKING** state.
- The StorageDaemon process mounts the volume if the check is successful. If the mount operation is successful, the volume state changes to **MOUNTED** and StorageManager is instructed to send the COMMON_EVENT_VOLUME_MOUNTED broadcast.
- If the check fails, the volume state changes to **UNMOUNTED**.
- For a volume in the **MOUNTED** state:
- If the device is directly removed, the volume information will be deleted and COMMON_EVENT_VOLUME_BAD_REMOVAL is broadcast.
- If the user chooses **Eject device**, the volume state changes to **EJECTING** and the COMMON_EVENT_VOLUME_EJECT is broadcast. After StorageDaemon unmounts the volume, the volume state changes to **UNMOUNTED** and COMMON_EVENT_VOLUME_UNMOUNTED is broadcast.
- For a volume in the **UNMOUNTED** state, removing the device will delete the volume information and broadcast COMMON_EVENT_VOLUME_REMOVED.
## Available APIs
For details about APIs, see [Volume Management](../reference/apis/js-apis-file-volumemanager.md).
The following table describes the broadcast related parameters.
**Table 1** Broadcast parameters
| Broadcast| Parameter|
| -------- | -------- |
| usual.event.data.VOLUME_REMOVED | **id**: ID of the volume.<br>**diskId**: ID of the disk to which the volume belongs.|
| usual.event.data.VOLUME_UNMOUNTED | **id**: ID of the volume.<br>**diskId**: ID of the disk to which the volume belongs.<br>**volumeState**: state of the volume.|
| usual.event.data.VOLUME_MOUNTED | **id**: ID of the volume.<br>**diskId**: ID of the disk to which the volume belongs.<br>**volumeState**: state of the volume.<br>**fsUuid**: universally unique identifier (UUID) of the volume.<br>**path**: path where the volume is mounted.|
| usual.event.data.VOLUME_BAD_REMOVAL | **id**: ID of the volume.<br>**diskId**: ID of the disk to which the volume belongs.|
| usual.event.data.VOLUME_EJECT | **id**: ID of the volume.<br>**diskId**: ID of the disk to which the volume belongs.<br>**volumeState**: state of the volume.|
## How to Develop
Subscribe to broadcast events to notify the insertion and removal of external storage devices. The volumes can be queried and managed based on the volume information obtained from the broadcast.
1. Apply for permissions.
Apply for the **ohos.permission.STORAGE_MANAGER** permission for subscribing to volume broadcast events. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
2. Subscribe to broadcast events.
Subscribe to the following events:
- "usual.event.data.VOLUME_REMOVED": The device is removed.
- "usual.event.data.VOLUME_UNMOUNTED": The volume is unmounted.
- "usual.event.data.VOLUME_MOUNTED": The volume is mounted.
- "usual.event.data.VOLUME_BAD_REMOVAL": The device is forcibly removed.
- "usual.event.data.VOLUME_EJECT": The device is being ejected.
```ts
import CommonEvent from '@ohos.commonEventManager';
import volumeManager from '@ohos.file.volumeManager';
const subscribeInfo = {
events: [
"usual.event.data.VOLUME_REMOVED",
"usual.event.data.VOLUME_UNMOUNTED",
"usual.event.data.VOLUME_MOUNTED",
"usual.event.data.VOLUME_BAD_REMOVAL",
"usual.event.data.VOLUME_EJECT"
]
};
let subscriber = await CommonEvent.createSubscriber(subscribeInfo);
```
3. Obtain the volume information from the broadcast.
```ts
CommonEvent.subscribe(subscriber, function (err, data) {
if (data.event === 'usual.event.data.VOLUME_MOUNTED') {
// Manage the volume device based on the information obtained from the broadcast.
let volId = data.parameters.id;
volumeManager.getVolumeById(volId, function(error, vol) {
if (error) {
console.error('volumeManager getVolumeById failed');
} else {
console.info('volumeManager getVolumeById successfully, the volume state is ' + vol.state);
}
})
}
})
```
# Album Management
You can use the APIs provided by the **mediaLibrary** module to create and delete an album and obtain images in the album.
> **NOTE**
>
> Before developing features, read [MediaLibrary Overview](medialibrary-overview.md) to learn how to obtain a **MediaLibrary** instance and request the permissions to call the APIs of **MediaLibrary**.
To ensure the application running efficiency, most **MediaLibrary** API calls are asynchronous, and both callback and promise modes are provided for these APIs. The following code samples use the promise mode. For details about the APIs, see [MediaLibrary API Reference](../reference/apis/js-apis-medialibrary.md).
## Obtaining Images and Videos in an Album
You can obtain images and videos in an album in either of the following ways:
- Call [MediaLibrary.getFileAssets](../reference/apis/js-apis-medialibrary.md#getfileassets7-1) with an album specified to obtain the media assets. For details, see [Querying Media Assets with the Specified Album Name](medialibrary-resource-guidelines.md#querying-media-assets-with-the-specified-album-name).
- Call [Album.getFileAssets](../reference/apis/js-apis-medialibrary.md#getfileassets7-3) to obtain an **Album** instance, so as to obtain the media assets in it. For details, see [Obtaining Images and Videos in an Album](medialibrary-resource-guidelines.md#obtaining-images-and-videos-in-an-album).
## Creating an Album
You can use [MediaLibrary.createAsset](../reference/apis/js-apis-medialibrary.md#createasset8-1), with the relative path set, to create an album while adding a media asset to the album. The relative path is the album name.
**Prerequisites**
- You have obtained a **MediaLibrary** instance.
- You have granted the permission **ohos.permission.WRITE_MEDIA**.
The following describes how to create an album named **myAlbum**.
**How to Develop**
1. Call **getPublicDirectory** to obtain the public directory that stores files of a certain type.
For details about the operation, see [Obtaining a Public Directory](medialibrary-filepath-guidelines.md#obtaining-a-public-directory).
2. Call **createAsset** to create an image, with the relative path set to **path + 'myAlbum/'**.
This operation creates an album and adds an image to it.
```ts
async function example() {
let mediaType = mediaLibrary.MediaType.IMAGE;
let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE;
const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context);
const path = await media.getPublicDirectory(DIR_IMAGE);
// myAlbum is the path for storing the new file and the name of the new album.
media.createAsset(mediaType, 'test.jpg', path + 'myAlbum/', (err, fileAsset) => {
if (fileAsset === undefined) {
console.error('createAlbum failed, message = ' + err);
} else {
console.info('createAlbum successfully, message = ' + JSON.stringify(fileAsset));
}
});
}
```
## Renaming an Album
Renaming modifies the **FileAsset.albumName** attribute of the album, that is, the album name. After the modification, call [Album.commitModify](../reference/apis/js-apis-medialibrary.md#commitmodify8-3) to commit the modification to the database.
**Prerequisites**
- You have obtained a **MediaLibrary** instance.
- You have granted the permission **ohos.permission.WRITE_MEDIA**.
The following describes how to rename the album **newAlbum**.
**How to Develop**
1. Create a retrieval condition for obtaining the target album.
2. Call **getAlbums** to obtain the album list.
3. Rename the album **newAlbum**.
4. Call **Album.commitModify** to commit the modification of the attributes to the database.
```ts
async function example() {
let AlbumNoArgsfetchOp = {
selections: '',
selectionArgs: [],
};
const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context);
let albumList = await media.getAlbums(AlbumNoArgsfetchOp);
let album = albumList[0];
album.albumName = 'newAlbum';
// Void callback.
album.commitModify().then(() => {
console.info("albumRename successfully");
}).catch((err) => {
console.error("albumRename failed with error: " + err);
});
}
```
# File Path Management
User data on OpenHarmony is managed by the **mediaLibrary** module in a unified manner. You can use the APIs provided by this module to access and operate the user data.
> **NOTE**
>
> Before developing features, read [MediaLibrary Overview](medialibrary-overview.md) to learn how to obtain a **MediaLibrary** instance and request the permissions to call the APIs of **MediaLibrary**.
To ensure the application running efficiency, most **MediaLibrary** API calls are asynchronous, and both callback and promise modes are provided for these APIs. The following code samples use the promise mode. For details about the APIs, see [MediaLibrary API Reference](../reference/apis/js-apis-medialibrary.md).
## File Formats Supported by Public Directories
Before using file paths for development, learn the file formats supported by each public directory.
> **CAUTION**
>
> The following table lists only the file types that can be identified by the system. In your application development, pay attention to the file formats supported by the corresponding interfaces. <br> For example, only .jpeg and .webp can be used for image encoding, and only .jpg, .png, .gif, .bmp, .webp, and .raw can be used for image decoding.
| Directory | Directory Type | Media Type | Description | Supported File Format |
| ---------- | ------------- | ------------- | -------------- | ------------------------------------------------------------ |
| Camera/ | DIR_CAMERA | VIDEO and IMAGE | Directory for storing images and videos taken by the camera. Videos and images can be stored in this directory and its subdirectories.| .bmp / .bm / .gif / .jpg /. jpeg / .jpe / .png / .webp / .raw / .svg / .heif / .mp4 / .3gp / .mpg / .mov / .webm / .mkv |
| Videos/ | DIR_VIDEO | VIDEO | Dedicated video directory. Only videos can be stored in this directory and its subdirectories.| .mp4 / .3gp / .mpg / .mov / .webm / .mkv |
| Pictures/ | DIR_IMAGE | IMAGE | Dedicated image directory. Only images can be stored in this directory and its subdirectories.| .bmp / .bm / .gif / .jpg /. jpeg / .jpe / .png / .webp / .raw / .svg / .heif |
| Audios/ | DIR_AUDIO | AUDIO |Dedicated audio directory. Only audio files can be stored in this directory and its subdirectories.| .aac/.mp3/.flac/.wav/.ogg |
| Documents/ | DIR_DOCUMENTS | FILE |Dedicated file directory. Only files except audios, images, and videos can be stored in this directory and its subdirectories.| - |
| Download/ | DIR_DOWNLOAD | ALLTYPE |Directory for storing downloaded files. The types of files in this directory and its subdirectories are not restricted.| - |
## Obtaining a Public Directory
Different types of files are stored in different public directories. You can call [getPublicDirectory](../reference/apis/js-apis-medialibrary.md#getpublicdirectory8-1) to obtain the public directory that stores files of a certain type.
**Prerequisites**
- You have obtained a **MediaLibrary** instance.
- You have granted the permission **ohos.permission.READ_MEDIA**.
The following describes how to obtain the public directory that stores camera files.
```ts
async function example(){
const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context);
let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA;
const dicResult = await media.getPublicDirectory(DIR_CAMERA);
if (dicResult == 'Camera/') {
console.info('mediaLibraryTest : getPublicDirectory passed');
} else {
console.error('mediaLibraryTest : getPublicDirectory failed');
}
}
```
## Copying Files Between the Application Sandbox and the Public Directory
OpenHarmony provides the application sandbox to minimize the leakage of application data and user privacy information.
Users can access files stored in the public directories through the system applications **Files** and **Gallery**. However, files in the application sandbox can be accessed only by the application itself.
### Copying a File
You can call [mediaLibrary.FileAsset.open](../reference/apis/js-apis-medialibrary.md#open8-1) to open a file in a public directory.
You can call [fs.open](../reference/apis/js-apis-file-fs.md#fsopen) to open a file in the application sandbox. The sandbox directory can be accessed only through the application context.
**Prerequisites**
- You have obtained a **MediaLibrary** instance.
- You have granted the permissions **ohos.permission.READ_MEDIA** and **ohos.permission.WRITE_MEDIA**.
- You have imported the module [@ohos.file.fs](../reference/apis/js-apis-file-fs.md) in addition to @ohos.multimedia.mediaLibrary.
- The **testFile.txt** file has been created and contains content.
**How to Develop**
1. Call [context.filesDir](../reference/apis/js-apis-file-fs.md) to obtain the directory of the application sandbox.
2. Call **MediaLibrary.getFileAssets** and **FetchFileResult.getFirstObject** to obtain the first file in the result set of the public directory.
3. Call **fs.open** to open the file in the sandbox.
4. Call **fileAsset.open** to open the file in the public directory.
5. Call [fs.copyfile](../reference/apis/js-apis-file-fs.md#fscopyfile) to copy the file.
6. Call **fileAsset.close** and [fs.close](../reference/apis/js-apis-file-fs.md#fsclose) to close the file.
**Example 1: Copying Files from the Public Directory to the Sandbox**
```ts
async function copyPublic2Sandbox() {
try {
const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context);
let sandboxDirPath = context.filesDir;
let fileKeyObj = mediaLibrary.FileKey;
let fileAssetFetchOp = {
selections: fileKeyObj.DISPLAY_NAME + '= ?',
selectionArgs: ['testFile.txt'],
};
let fetchResult = await media.getFileAssets(fileAssetFetchOp);
let fileAsset = await fetchResult.getFirstObject();
let fdPub = await fileAsset.open('rw');
let fdSand = await fs.open(sandboxDirPath + '/testFile.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
await fs.copyFile(fdPub, fdSand.fd);
await fileAsset.close(fdPub);
await fs.close(fdSand.fd);
let content_sand = await fs.readText(sandboxDirPath + '/testFile.txt');
console.info('content read from sandbox file: ', content_sand)
} catch (err) {
console.info('[demo] copyPublic2Sandbox fail, err: ', err);
}
}
```
**Example 2: Copying a File from the Sandbox to the Public Directory**
```ts
async function copySandbox2Public() {
const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context);
let sandboxDirPath = context.filesDir;
let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS;
const publicDirPath = await media.getPublicDirectory(DIR_DOCUMENTS);
try {
let fileAsset = await media.createAsset(mediaLibrary.MediaType.FILE, 'testFile02.txt', publicDirPath);
console.info('createFile successfully, message = ' + fileAsset);
} catch (err) {
console.error('createFile failed, message = ' + err);
}
try {
let fileKeyObj = mediaLibrary.FileKey;
let fileAssetFetchOp = {
selections: fileKeyObj.DISPLAY_NAME + '= ?',
selectionArgs: ['testFile02.txt'],
};
let fetchResult = await media.getFileAssets(fileAssetFetchOp);
var fileAsset = await fetchResult.getFirstObject();
} catch (err) {
console.error('file asset get failed, message = ' + err);
}
let fdPub = await fileAsset.open('rw');
let fdSand = await fs.open(sandboxDirPath + 'testFile.txt', fs.OpenMode.READ_WRITE);
await fs.copyFile(fdSand.fd, fdPub);
await fileAsset.close(fdPub);
await fs.close(fdSand.fd);
let fdPubRead = await fileAsset.open('rw');
try {
let arrayBuffer = new ArrayBuffer(4096);
await fs.read(fdPubRead, arrayBuffer);
var content_pub = String.fromCharCode(...new Uint8Array(arrayBuffer));
fileAsset.close(fdPubRead);
} catch (err) {
console.error('read text failed, message = ', err);
}
console.info('content read from public file: ', content_pub);
}
```
### Reading and Writing a File
You can use **FileAsset.open** and **FileAsset.close** of [mediaLibrary](../reference/apis/js-apis-medialibrary.md) to open and close a file, and use **fs.read** and **fs.write** in [file.fs](../reference/apis/js-apis-file-fs.md) to read and write the file.
**Prerequisites**
- You have obtained a **MediaLibrary** instance.
- You have granted the permissions **ohos.permission.READ_MEDIA** and **ohos.permission.WRITE_MEDIA**.
- You have imported the module [@ohos.file.fs](../reference/apis/js-apis-file-fs.md) in addition to @ohos.multimedia.mediaLibrary.
**How to Develop**
1. Create a file.
```ts
async function example() {
let mediaType = mediaLibrary.MediaType.FILE;
let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS;
const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context);
const path = await media.getPublicDirectory(DIR_DOCUMENTS);
media.createAsset(mediaType, "testFile.txt", path).then((asset) => {
console.info("createAsset successfully:" + JSON.stringify(asset));
}).catch((err) => {
console.error("createAsset failed with error: " + err);
});
}
```
2. Call **FileAsset.open** to open the file.
3. Call [fs.write](../reference/apis/js-apis-file-fs.md#fswrite) to write a string to the file.
4. Call [fs.read](../reference/apis/js-apis-file-fs.md#fsread) to read the file and save the data read in an array buffer.
5. Convert the array buffer to a string.
6. Use **FileAsset.close** to close the file.
**Example 1: Opening an Existing File and Writing Data to It**
```ts
async function writeOnlyPromise() {
const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context);
let fileKeyObj = mediaLibrary.FileKey;
let fileAssetFetchOp = {
selections: fileKeyObj.DISPLAY_NAME + '= ?',
selectionArgs: ['testFile.txt'],
};
let fetchResult = await media.getFileAssets(fileAssetFetchOp);
let fileAsset = await fetchResult.getFirstObject();
console.info('fileAssetName: ', fileAsset.displayName);
try {
let fd = await fileAsset.open('w');
console.info('file descriptor: ', fd);
await fs.write(fd, "Write file test content.");
await fileAsset.close(fd);
} catch (err) {
console.error('write file failed, message = ', err);
}
}
```
**Example 2: Opening an Existing File and Reading Data from It**
```ts
async function readOnlyPromise() {
const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context);
let fileKeyObj = mediaLibrary.FileKey;
let fileAssetFetchOp = {
selections: fileKeyObj.DISPLAY_NAME + '= ?' ,
selectionArgs: ['testFile.txt'],
};
let fetchResult = await media.getFileAssets(fileAssetFetchOp);
let fileAsset = await fetchResult.getFirstObject();
console.info('fileAssetName: ', fileAsset.displayName);
try {
let fd = await fileAsset.open('r');
let arrayBuffer = new ArrayBuffer(4096);
await fs.read(fd, arrayBuffer);
let fileContent = String.fromCharCode(...new Uint8Array(arrayBuffer));
globalThis.fileContent = fileContent;
globalThis.fileName = fileAsset.displayName;
console.info('file content: ', fileContent);
await fileAsset.close(fd);
} catch (err) {
console.error('read file failed, message = ', err);
}
}
```
# MediaLibrary Development Overview
The **mediaLibrary** module provides APIs for you to access and modify media files.
- You can manage [media assets (audios, videos, image, and files)](medialibrary-resource-guidelines.md) as follows:
- Query media assets.
- Obtain an image or a video.
- Obtain the thumbnail of an image or a video.
- Create a media asset.
- Rename a media asset.
- Move a media asset to the recycle bin.
- You can manage [file paths](medialibrary-filepath-guidelines.md) as follows:
- Obtain the public directory that stores files of a certain type.
- Copy files between the application sandbox and the public directory.
- Read and write a file.
- You can manage [albums](medialibrary-album-guidelines.md) as follows:
- Obtain images and videos in an album.
- Create an album.
- Rename an album.
> **NOTE**
>
> This development guide applies only to the stage model (available from API version 9).
To access and modify personal media data, an application must obtain a **MediaLibrary** instance and request the media asset read and write permissions from the user. Unless otherwise specified, the **MediaLibrary** APIs are used in **pages/index.ets** or custom .ets files of the project code.
Before using the **MediaLibrary** APIs to develop features, you must learn how to:
- [Obtain a MediaLibrary Instance](#obtaining-a-medialibrary-instance)
- [Request Permissions](#requesting-permissions)
## Obtaining a MediaLibrary Instance
An application must call [getMediaLibrary](../reference/apis/js-apis-medialibrary.md#medialibrarygetmedialibrary8) to obtain a **MediaLibrary** instance based on the application context. Through this instance, the application can access and modify personal media data (such as audios, videos, images, and files).
**How to Develop**
1. Import the **mediaLibrary** module.
2. Call **getContext** to obtain the application context.
3. Obtain a **MediaLibrary** instance.
```ts
import mediaLibrary from '@ohos.multimedia.mediaLibrary';
const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context);
```
## Requesting Permissions
To read and write a **MediaLibrary** instance, you must have the required permissions, as described in the table below. Before requesting the permissions, ensure that the [basic principles for permission management](../security/accesstoken-overview.md#basic-principles-for-permission-management) are met.
| Permission | Description | Authorization Mode |
| ------------------------------ | ------------------------------------------ | ---------- |
| ohos.permission.READ_MEDIA | Allows an application to read media files from the user's external storage.| user_grant |
| ohos.permission.WRITE_MEDIA | Allows an application to read media files from and write media files into the user's external storage.| user_grant |
| ohos.permission.MEDIA_LOCATION | Allows an application to access geographical locations in the user's media file.| user_grant |
After configuring the permissions in the **module.json5** file, the application must call [abilityAccessCtrl.requestPermissionsFromUser](../reference/apis/js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9) to check for the required permissions and if they are not granted, request the permissions from the user by displaying a dialog box.
> **NOTE**<br>Even if the user has granted a permission, the application must check for the permission before calling an API protected by the permission. It should not persist the permission granted status, because the user can revoke the permission through the system application **Settings**.
**How to Develop**
1. Declare the permissions in the **module.json5** file. Add the **requestPermissions** tag under **module** in the file, and set the tag based on the project requirements. For details about the tag, see [Guide for Requesting Permissions from User](../security/accesstoken-guidelines.md).
```json
{
"module": {
"requestPermissions": [
{
"name": "ohos.permission.MEDIA_LOCATION",
"reason": "$string:reason",
"usedScene": {
"abilities": [
"EntryAbility"
],
"when": "always"
}
},
{
"name": "ohos.permission.READ_MEDIA",
"reason": "$string:reason",
"usedScene": {
"abilities": [
"EntryAbility"
],
"when": "always"
}
},
{
"name": "ohos.permission.WRITE_MEDIA",
"reason": "$string:reason",
"usedScene": {
"abilities": [
"EntryAbility"
],
"when": "always"
}
}
]
}
}
```
2. In the **Ability.ts** file, call **requestPermissionsFromUser** in the **onWindowStageCreate** callback to check for the required permissions and if they are not granted, request the permissions from the user by displaying a dialog box.
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import abilityAccessCtrl, {Permissions} from '@ohos.abilityAccessCtrl';
export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) {
let list : Array<Permissions> = ['ohos.permission.READ_MEDIA', 'ohos.permission.WRITE_MEDIA'];
let permissionRequestResult;
let atManager = abilityAccessCtrl.createAtManager();
atManager.requestPermissionsFromUser(this.context, list, (err, result) => {
if (err) {
console.error('requestPermissionsFromUserError: ' + JSON.stringify(err));
} else {
permissionRequestResult = result;
console.info('permissionRequestResult: ' + JSON.stringify(permissionRequestResult));
}
});
}
}
```
# Media Asset Management
Your applications can use the APIs provided by the **mediaLibrary** module to perform operations on media assets such as audios, videos, images, and files.
> **NOTE**
>
> Before developing features, read [MediaLibrary Overview](medialibrary-overview.md) to learn how to obtain a **MediaLibrary** instance and request the permissions to call the APIs of **MediaLibrary**.
To maximize the application running efficiency, most **MediaLibrary** API calls are asynchronous in callback or promise mode. The following code samples use the promise mode. For details about the APIs, see [MediaLibrary API Reference](../reference/apis/js-apis-medialibrary.md).
## Querying Media Assets
You can query media assets by condition such as the media type, date, or album name.
To do so, call [MediaLibrary.getFileAssets](../reference/apis/js-apis-medialibrary.md#getfileassets7-1), with a **MediaFetchOptions** object passed in to specify the conditions. In this object, **MediaFetchOptions.selections** are the retrieval conditions, and the enumerated values of **FileKey** are used as the column names of the conditions; **MediaFetchOptions.selectionArgs** are the values of the conditions. You can also specify **order** (sorting mode of the search result), **uri** (file URI), and **networkId** (network ID of the registered device) as the conditions.
To obtain the object at the specified position (for example, the first, the last, or with the specified index) in the result set, call [FetchFileResult](../reference/apis/js-apis-medialibrary.md#fetchfileresult7). In this section, **getNextObject** is used cyclically to obtain all media assets in the result set.
**Prerequisites**
- You have obtained a **MediaLibrary** instance.
- You have granted the permission **ohos.permission.READ_MEDIA**.
### Querying Media Assets with the Specified Media Type
The following describes how to obtain images.
**How to Develop**
To specify the media type as the retrieval condition, set **selections** to **FileKey.MEDIA_TYPE**.
To specify the image as the media type, set **selectionArgs** to **MediaType.IMAGE**.
```ts
async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let fileType = mediaLibrary.MediaType.IMAGE;
let option = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [fileType.toString()],
};
const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option);
fetchFileResult.getFirstObject().then(async (fileAsset) => {
console.log('getFirstObject.displayName : ' + fileAsset.displayName);
for (let i = 1; i < fetchFileResult.getCount(); i++) {
let fileAsset = await fetchFileResult.getNextObject();
console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName);
}
}).catch((err) => {
console.error('Failed to get first object: ' + err);
});
}
```
### Querying Media Assets with the Specified Date
The following describes how to obtain all the media assets that are added from the specified date. You can also use the modification date and shooting date as the retrieval conditions.
To specify the date when the files are added as the retrieval condition, set **selections** to **FileKey.DATE_ADDED**.
To specify the date 2022-8-5, set **selectionArgs** to **2022-8-5**.
```ts
async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let option = {
selections: fileKeyObj.DATE_ADDED + '> ?',
selectionArgs: ['2022-8-5'],
};
const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option);
fetchFileResult.getFirstObject().then(async (fileAsset) => {
console.info('getFirstObject.displayName : ' + fileAsset.displayName);
for (let i = 1; i < fetchFileResult.getCount(); i++) {
let fileAsset = await fetchFileResult.getNextObject();
console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName);
}
}).catch((err) => {
console.error('Failed to get first object: ' + err);
});
}
```
### Querying Media Assets and Sorting Them
The following describes how to query images and sort them in descending order by the date when they are added. You can also sort them in ascending order.
To sort files in descending order by the date when they are added, set **order** to **FileKey.DATE_ADDED + " DESC"**.
```ts
async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let fileType = mediaLibrary.MediaType.IMAGE;
let option = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [fileType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC",
};
const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option);
fetchFileResult.getFirstObject().then(async (fileAsset) => {
console.info('getFirstObject.displayName : ' + fileAsset.displayName);
for (let i = 1; i < fetchFileResult.getCount(); i++) {
let fileAsset = await fetchFileResult.getNextObject();
console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName);
}
}).catch((err) => {
console.error('Failed to get first object: ' + err);
});
}
```
### Querying Media Assets with the Specified Album Name
The following describes how to query media assets in **myAlbum**.
To specify the album name as the retrieval condition, set **selections** to **FileKey.ALBUM_NAME**.
To specify the album name **'myAlbum'**, set **selectionArgs** to **'myAlbum'**.
```ts
async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let option = {
selections: fileKeyObj.ALBUM_NAME + '= ?',
selectionArgs: ['myAlbum'],
};
const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option);
if (albumList.length > 0) {
fetchFileResult.getFirstObject().then((album) => {
console.info('getFirstObject.displayName : ' + album.albumName);
}).catch((err) => {
console.error('Failed to get first object: ' + err);
});
} else {
console.info('getAlbum list is: 0');
}
}
```
## Obtaining Images and Videos in an Album
You can obtain media assets in an album in either of the following ways:
- Call [MediaLibrary.getFileAssets](../reference/apis/js-apis-medialibrary.md#getfileassets7-1) with an album specified, as described in [Querying Media Assets with the Specified Album Name](#querying-media-assets-with-the-specified-album-name).
- Call [Album.getFileAssets](../reference/apis/js-apis-medialibrary.md#getfileassets7-3) to obtain an **Album** instance, so as to obtain the media assets in it.
**Prerequisites**
- You have obtained a **MediaLibrary** instance.
- You have granted the permission **ohos.permission.READ_MEDIA**.
**How to Develop**
The following describes how to obtain videos in an album named **New Album 1**.
1. Create a retrieval condition for obtaining the target **Album** instance.
```ts
let fileKeyObj = mediaLibrary.FileKey;
let AlbumNoArgsFetchOp = {
selections: fileKeyObj.ALBUM_NAME + '= ?',
selectionArgs:['New Album 1']
}
```
2. Create a retrieval condition for obtaining videos in the target album.
```ts
let fileKeyObj = mediaLibrary.FileKey;
let videoType = mediaLibrary.MediaType.VIDEO;
let videoFetchOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [videoType.toString()],
}
```
3. Call **Album.getFileAssets** to obtain the videos in the target album.
Complete sample code:
```ts
async function getCameraImagePromise() {
const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context);
let fileKeyObj = mediaLibrary.FileKey;
let videoType = mediaLibrary.MediaType.VIDEO;
let videoFetchOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [videoType.toString()],
}
let AlbumNoArgsFetchOp = {
selections: fileKeyObj.ALBUM_NAME + '= ?',
selectionArgs:['New Album 1']
}
let albumList = await media.getAlbums(AlbumNoArgsFetchOp);
if (albumList.length > 0) {
const album = albumList[0];
let fetchFileResult = await album.getFileAssets(videoFetchOp);
let count = fetchFileResult.getCount();
console.info("get mediaLibrary VIDEO number", count);
} else {
console.info('getAlbum list is: 0');
}
}
```
## Obtaining the Thumbnail of an Image or a Video
You can call [FileAsset.getThumbnail](../reference/apis/js-apis-medialibrary.md#getthumbnail8-2) with the thumbnail size passed in to obtain the thumbnail of an image or a video. Your application can use thumbnails to offer a quick preview on images and videos.
**Prerequisites**
- You have obtained a **MediaLibrary** instance.
- You have granted the permission **ohos.permission.READ_MEDIA**.
### Obtaining the Thumbnail of an Image
The following describes how to obtain the thumbnail (size: 720 x 720) of the first image in the album.
**How to Develop**
1. Create a retrieval condition for obtaining images in the target album.
2. Call **getFileAssets** to obtain the images in the target album.
3. Call **getFirstObject** to obtain the first image among all the images obtained.
4. Call **getThumbnail** to obtain the thumbnail of the first image.
```ts
async function getFirstThumbnailPromise() {
const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context);
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let imagesFetchOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()],
}
let size = { width: 720, height: 720 };
const fetchFileResult = await media.getFileAssets(imagesFetchOp);
if (fetchFileResult === undefined) {
console.error("get image failed with error");
return;
} else {
const asset = await fetchFileResult.getFirstObject();
asset.getThumbnail(size).then((pixelMap) => {
pixelMap.getImageInfo().then((info) => {
console.info('get Thumbnail info: ' + "width: " + info.size.width + " height: " + info.size.height);
}).catch((err) => {
console.error("getImageInfo failed with error: " + err);
});
}).catch((err) => {
console.error("getImageInfo failed with error: " + err);
});
}
}
```
## Creating a Media Asset
You can call [MediaLibrary.createAsset](../reference/apis/js-apis-medialibrary.md#createasset8-1) to create a media asset.
**Prerequisites**
- You have obtained a **MediaLibrary** instance.
- You have granted the permission **ohos.permission.WRITE_MEDIA**.
- [You have obtained a public directory](medialibrary-filepath-guidelines.md).
The following describes how to create a file of the **MediaType.FILE** type.
```ts
async function example() {
let mediaType = mediaLibrary.MediaType.FILE;
let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS;
const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context);
const path = await media.getPublicDirectory(DIR_DOCUMENTS);
media.createAsset(mediaType, "testFile.text", path).then((asset) => {
console.info("createAsset successfully:"+ JSON.stringify(asset));
}).catch((err) => {
console.error("createAsset failed with error: " + err);
});
}
```
## Moving a Media Asset to the Recycle Bin
You can use [FileAsset.trash](../reference/apis/js-apis-medialibrary.md#trash8) to move a media asset to the recycle bin.
By default, files in the recycle bin will be stored for 30 days before being permanently removed. During this period, you can set **isTrash** in **trash** to **false** to recover the files. Application users can also recover the files through the system applications **Files** or **Gallery**.
**Prerequisites**
- You have obtained a **MediaLibrary** instance.
- You have granted the permission **ohos.permission.WRITE_MEDIA**.
The following describes how to move the first file in the result set to the recycle bin.
**How to Develop**
1. Create a retrieval condition for obtaining images in the target album.
2. Call **getFileAssets** to obtain the images in the target album.
3. Call **getFirstObject** to obtain the first image among all the images obtained.
4. Call **trash** to move the first image to the recycle bin.
```ts
async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let fileType = mediaLibrary.MediaType.FILE;
let option = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [fileType.toString()],
};
const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option);
let asset = await fetchFileResult.getFirstObject();
if (asset === undefined) {
console.error('asset not exist');
return;
}
// Void callback.
asset.trash(true).then(() => {
console.info("trash successfully");
}).catch((err) => {
console.error("trash failed with error: " + err);
});
}
```
## Renaming a Media Asset
To rename a media asset, modify the **FileAsset.displayName** attribute (which specifies the displayed file name, including the file name extension) and commit the modification through [FileAsset.commitModify](../reference/apis/js-apis-medialibrary.md#commitmodify8-1).
Before renaming a file, you must obtain the file, for example, by calling [FetchFileResult](../reference/apis/js-apis-medialibrary.md#fetchfileresult7).
**Prerequisites**
- You have obtained a **MediaLibrary** instance.
- You have granted the permission **ohos.permission.WRITE_MEDIA**.
The following describes how to rename the first file in the result set as **newImage.jpg**.
**How to Develop**
1. Create a retrieval condition for obtaining images in the target album.
2. Call **getFileAssets** to obtain the images in the target album.
3. Call **getFirstObject** to obtain the first image among all the images obtained.
4. Rename the image as **newImage.jpg**.
5. Call **FileAsset.commitModify** to commit the modification to the database.
```ts
async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let fileType = mediaLibrary.MediaType.IMAGE;
let option = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [fileType.toString()],
};
const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option);
let asset = await fetchFileResult.getFirstObject();
if (asset === undefined) {
console.error('asset not exist');
return;
}
asset.displayName = 'newImage.jpg';
// Void callback.
asset.commitModify((err) => {
if (err) {
console.error('fileRename Failed ');
return;
}
console.info('fileRename successful.');
});
}
```
# Saving User Files
When a user needs to download a file from the network to a local directory or save a user file into another directory, use **FilePicker** to save the file.
The operations for saving images, audio or video clips, and documents are similar. Call **save()** of the corresponding picker instance and pass in **saveOptions**.
## Saving Images or Video Files
1. Import the **FilePicker** module.
```ts
import picker from '@ohos.file.picker';
```
2. Create a **photoSaveOptions** instance.
```ts
const photoSaveOptions = new picker.PhotoSaveOptions(); // Create a photoSaveOptions instance.
photoSaveOptions.newFileNames = ["PhotoViewPicker01.jpg"]; // (Optional) Set the names of the files to save.
```
3. Create a **photoViewPicker** instance and call [save()](../reference/apis/js-apis-file-picker.md#save) to open the **FilePicker** page to save the files.
After the user selects the target folder, the file saving operation is complete. After the files are saved successfully, the URIs of the files saved are returned.
```ts
const photoViewPicker = new picker.PhotoViewPicker();
photoViewPicker.save(photoSaveOptions)
.then(async (photoSaveResult) => {
let uri = photoSaveResult[0];
// Perform operations on the files based on the file URIs obtained.
})
.catch((err) => {
console.error(`Invoke documentPicker.select failed, code is ${err.code}, message is ${err.message}`);
})
```
## Saving Documents
1. Import the **FilePicker** module.
```ts
import picker from '@ohos.file.picker';
```
2. Create a **documentSaveOptions** instance.
```ts
const documentSaveOptions = new picker.DocumentSaveOptions(); // Create a documentSaveOptions instance.
documentSaveOptions.newFileNames = ["DocumentViewPicker01.txt"]; // (Optional) Set the names of the documents to save.
```
3. Create a **documentViewPicker** instance, and call [save()](../reference/apis/js-apis-file-picker.md#save-3) to open the **FilePicker** page to save the documents.
After the user selects the target folder, the file saving operation is complete. After the files are saved successfully, the URIs of the files saved are returned.
> **NOTE**
>
> Currently, **DocumentSelectOptions** is not configurable. By default, all types of user files are selected.
```ts
const documentViewPicker = new picker.DocumentViewPicker(); // Create a documentViewPicker instance.
documentViewPicker.save(documentSaveOptions)
.then(async (documentSaveResult) => {
let uri = documentSaveResult[0];
// For example, write data to the documents based on the obtained URIs.
})
.catch((err) => {
console.error(`Invoke documentPicker.save failed, code is ${err.code}, message is ${err.message}`);
})
```
## Saving Audio Files
1. Import the **FilePicker** module.
```ts
import picker from '@ohos.file.picker';
```
2. Create an **audioSaveOptions** instance.
```ts
const audioSaveOptions = new picker.AudioSaveOptions(); // Create an audioSaveOptions instance.
audioSaveOptions.newFileNames = ['AudioViewPicker01.mp3']; // (Optional) Set the names of the files to save.
```
3. Create an **audioViewPicker** instance, and call [save()](../reference/apis/js-apis-file-picker.md#save-6) to open the **FilePicker** page to save the files.
After the user selects the target folder, the file saving operation is complete. After the files are saved successfully, the URIs of the files saved are returned.
> **NOTE**
>
> Currently, **AudioSelectOptions** is not configurable. By default, all types of user files are selected.
```ts
const audioViewPicker = new picker.AudioViewPicker();
audioViewPicker.save(audioSaveOptions)
.then((audioSelectResult) => {
let uri = audioSelectResult[0];
// Perform operations on the audio files based on the file URIs.
})
.catch((err) => {
console.error(`Invoke audioPicker.select failed, code is ${err.code}, message is ${err.message}`);
})
```
# Selecting User Files
If your application needs to support share and saving of user files (such as images and videos) by users, you can use the [FilePicker](../reference/apis/js-apis-file-picker.md) prebuilt in OpenHarmony to implement selecting and saving of user files.
The **FilePicker** provides the following interfaces by file type:
- [**PhotoViewPicker**](../reference/apis/js-apis-file-picker.md#photoviewpicker): used to select and save images or video files.
- [**DocumentViewPicker**](../reference/apis/js-apis-file-picker.md#documentviewpicker): used to select and save documents.
- [**AudioViewPicker**](../reference/apis/js-apis-file-picker.md#audioviewpicker): used to select and save audio files.
## Selecting Images or Video Files
1. Import the **FilePicker** module.
```ts
import picker from '@ohos.file.picker';
```
2. Create a **photoSelectOptions** instance.
```ts
const photoSelectOptions = new picker.PhotoSelectOptions();
```
3. Set the file type and the maximum number of media files to select.
For example, select a maximum of five images. For details about the media file type, see [PhotoViewMIMETypes](../reference/apis/js-apis-file-picker.md#photoviewmimetypes).
```ts
photoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE; // Select images.
photoSelectOptions.maxSelectNumber = 5; // Set the maximum number of images to select.
```
4. Create a **photoPicker** instance and call [select()](../reference/apis/js-apis-file-picker.md#select) to open the **FilePicker** page for the user to select files.
Use [PhotoSelectResult](../reference/apis/js-apis-file-picker.md#photoselectresult) to return a result set. Further operations on the selected files can be performed based on the file URIs in the result set.
```ts
const photoPicker = new picker.PhotoViewPicker();
photoPicker.select(photoSelectOptions)
.then(async (photoSelectResult) => {
let uri = photoSelectResult.photoUris[0];
// Perform operations on the files based on the file URIs obtained.
})
.catch((err) => {
console.error(`Invoke documentPicker.select failed, code is ${err.code}, message is ${err.message}`);
})
```
## Selecting Documents
1. Import the **FilePicker** module.
```ts
import picker from '@ohos.file.picker';
```
2. Create a **documentSelectOptions** instance.
```ts
const documentSelectOptions = new picker.DocumentSelectOptions();
```
3. Create a **documentViewPicker** instance, and call [**select()**](../reference/apis/js-apis-file-picker.md#select-3) to open the **FilePicker** page for the user to select documents.
After the documents are selected successfully, a result set containing the file URIs is returned. Further operations can be performed on the documents based on the file URIs.
> **NOTE**
>
> Currently, **DocumentSelectOptions** is not configurable. By default, all types of user files are selected.
```ts
const documentViewPicker = new picker.DocumentViewPicker(); // Create a documentViewPicker instance.
documentViewPicker.select(documentSelectOptions)
.then((documentSelectResult) => {
let uri = documentSelectResult[0];
// Perform operations on the documents based on the file URIs.
})
.catch((err) => {
console.error(`Invoke documentPicker.select failed, code is ${err.code}, message is ${err.message}`);
})
```
## Selecting an Audio File
1. Import the **FilePicker** module.
```ts
import picker from '@ohos.file.picker';
```
2. Create an **audioSelectOptions** instance.
```ts
const audioSelectOptions = new picker.AudioSelectOptions();
```
3. Create an **audioViewPicker** instance, and call [**select()**](../reference/apis/js-apis-file-picker.md#select-6) to open the **FilePicker** page for the user to select audio files.
After the files are selected successfully, a result set containing the URIs of the audio files selected is returned. Further operations can be performed on the documents based on the file URIs.
For example, use the [file management interface](../reference/apis/js-apis-file-fs.md) to obtain the file handle (FD) of the audio clip based on the URI, and then develop the audio playback function based on the media service. For details, see [Audio Playback Development](../media/audio-playback-overview.md).
> **NOTE**
>
> Currently, **AudioSelectOptions** is not configurable. By default, all types of user files are selected.
```ts
const audioViewPicker = new picker.AudioViewPicker();
audioViewPicker.select(audioSelectOptions)
.then(audioSelectResult => {
let uri = audioSelectOptions[0];
// Perform operations on the audio files based on the file URIs.
})
.catch((err) => {
console.error(`Invoke audioPicker.select failed, code is ${err.code}, message is ${err.message}`);
})
```
# Sending Files to an Application Sandbox
During the development and debugging process of an application, you may need to place some files to the application sandbox for intra-application access or for testing purposes. In this case, you can use either of the following methods:
1. Use DevEco Studio to place the files to the application installation directory. For details, see [Application Installation Resource Access](../quick-start/resource-categories-and-access.md# resource-access).
2. Use the hdc tool to send files to the application sandbox directory on the device. This section describes the second method.
However, the file directories visible to the debugged process in the hdc shell are different from the application sandbox directories visible to the application. You need to understand the mappings between the application sandbox directories and the physical (real) directories.
## Mappings Between Application Sandbox Directories and Physical Directories
The read and write operations performed based on the application sandbox paths via APIs are performed on the files in the physical directories after address conversion. The following table lists the mappings between application sandbox paths and physical paths.
**Table 1** Mapping between application sandbox paths and physical paths
| Application Sandbox Path| Physical Path in hdc| Description|
| -------- | -------- | -------- |
| /data/storage/el1/bundle | /data/app/el1/bundle/public/&lt;PACKAGENAME&gt; | Application installation package directory.|
| /data/storage/el1/base | /data/app/el1/&lt;USERID&gt;/base/&lt;PACKAGENAME&gt; | Application directory of encryption level (el) 1.|
| /data/storage/el2/base | /data/app/el2/&lt;USERID&gt;/base/&lt;PACKAGENAME&gt; | Application directory of el 2.|
| /data/storage/el1/database | /data/app/el1/&lt;USERID&gt;/database/&lt;PACKAGENAME&gt; | Database directory of the application under **el1/**.|
| /data/storage/el2/database | /data/app/el2/&lt;USERID&gt;/database/&lt;PACKAGENAME&gt; | Database directory of the application under **el2/**.|
| /data/storage/el2/distributedfiles | /mnt/hmdfs/&lt;USERID&gt;/account/merge_view/data/&lt;PACKAGENAME&gt; | Distributed data directory of the application under **el2/**.|
## Development Example
The following uses the application bundle **com.ohos.example** as an example. If the application sandbox path is **/data/storage/el1/bundle**, the physical path is **/data/app/el1/bundle/public/<PACKAGENAME>**, that is, **/data/app/el1/bundle/public/com.ohos.example**.
Run the following command to send the file:
```
hdc file send ${Path of the local file to send} /data/app/el1/bundle/public/com.ohos.example/
```
## Switching to the Application View
During the debugging process, if you do not have the permission or the file does not exist, you need to switch from the process view to the application view and further analyze permission and directory problems. To switch to the application view, run the following commands:
```
hdc shell // Switch to shell.
ps -ef|grep [hapName] // Obtain the process identifier (PID) of the application.
nsenter -t [hapPid] -m /bin/sh // Enter the application sandbox environment based on the PID.
```
The application view is in use, and the path you see is the application sandbox path.
# Setting the Security Level of a Distributed File
The security capabilities vary with devices. For example, small embedded devices provide fewer security capabilities than tablets. The security requirements also vary with data. For example, personal health information and bank card information are not expected to be accessed by devices of lower security levels. OpenHarmony provides a complete set of standards for data and device classification and custom data transfer policies for different devices. For details, see [Data and Device Security Classification](../database/access-control-by-device-and-data-level.md).
## Available APIs
For details about the APIs, see [ohos.file.securityLabel](../reference/apis/js-apis-file-securityLabel.md).
**Table 1** APIs
| API| Description| Type| Synchronous Programming| Asynchronous Programming|
| -------- | -------- | -------- | -------- | -------- |
| setSecurityLabel | Sets a security label for a file.| Method| √ | √ |
| getSecurityLabel | Obtains the security label of a file.| Method| √ | √ |
> **NOTICE**
>
> 1. In distributed networking, a device can view the files that do not match its security level but cannot access them.
>
> 2. The default security level of the distributed file system data is S3. Applications can set the security level of files.
## Development Example
Obtain the sandbox path of the file and set the data security label. For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../application-models/uiability-usage.md#obtaining-the-context-of-uiability).
```ts
import securityLabel from '@ohos.file.securityLabel';
//Obtain the sandbox path of the file.
let context =...; // Obtain UIAbilityContext information.
let pathDir = context.filesDir;
let filePath = pathDir + '/test.txt';
// Set the data level of the file to S0.
securityLabel.setSecurityLabel(filePath, 's0').then(() => {
console.info('Succeeded in setSecurityLabeling.');
}).catch((err) => {
console.error(`Failed to setSecurityLabel. Code: ${err.code}, message: ${err.message}`);
});
```
<!--no_check-->
\ No newline at end of file
# Sharing an Application File
The file of an application can be shared with another application based on the file descriptor (FD) or uniform resource identifier (URI) of the file. However, if the FD of a shared file is closed, the file cannot be opened. Therefore, the file sharing based on the FD is not recommended. This section describes how to share an application file based on its URI.
- You can use **wantConstant.Flags()** of the [ohos.app.ability.wantConstant](../reference/apis/js-apis-app-ability-wantConstant.md#wantconstantflags) module to share an application file in read or read/write mode based on its URI with another application. The target application can use **open()** of the [ohos.file.fs](../reference/apis/js-apis-file-fs.md#fsopen) module to open the URI and then perform read and/or write operations based on the permissions granted. Currently, OpenHarmony API version 9 supports only temporary authorization. The permission on shared file is revoked once the target application exits.
- You can also use **open()** of the ohos.file.fs module to share an application file with the specified permissions to another application based on the FD. After parsing the FD from **Want**, the target application can read and write the file by using **read()** and **write()** APIs of ohos.file.fs.
You can use the related APIs to [share a file with another application](#sharing-a-file-with-another-application) or [use shared application files](#using-shared-files).
## File URI Specifications
The file URIs are in the following format:
file://&lt;bundleName&gt;/&lt;path&gt;/\#networkid=&lt;networkid&gt;
- **file**: indicates a file URI.
- *bundleName*: specifies the owner of the file.
- *path*: specifies the application sandbox path of the file.
- *networkid* (optional): specifies the device to which the file belongs in a distributed file system. Leave this parameter unspecified if the file location does not need to be set.
## Sharing a File with Another Application
Before sharing application files, you need to [obtain the application file path](../application-models/application-context-stage.md#obtaining-the-application-development-path).
1. Obtain the application sandbox path of the file and convert it into the file URI.
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import fileuri from '@ohos.file.fileuri';
import window from '@ohos.window';
export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage: window.WindowStage) {
// Obtain the application sandbox path of the file.
let pathInSandbox = this.context.filesDir + "/test.txt";
// Convert the application sandbox path into a URI.
let uri = fileuri.getUriFromPath(pathInSandbox);
// The obtained URI is file://com.example.demo/data/storage/el2/base/files/test.txt.
}
}
```
2. Set the target application, with which you want to share the file, and grant permissions on the file.
Use [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to share the file with the target application. You need to pass in the URI obtained in **uri** of the **want** parameter, set the type of the file to share, set **action** to **ohos.want.action.sendData**, and set the granted permission on the file in **flags**. For details, see [Want](../reference/apis/js-apis-app-ability-want.md#attributes).
> **NOTE**
>
> The write permission granted includes the read permission.
```ts
import fileuri from '@ohos.file.fileuri';
import window from '@ohos.window';
import wantConstant from '@ohos.app.ability.wantConstant';
import UIAbility from '@ohos.app.ability.UIAbility';
export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage: window.WindowStage) {
// Obtain the application sandbox path of the file.
let filePath = this.context.filesDir + '/test.txt';
// Convert the application sandbox path into a URI.
let uri = fileuri.getUriFromPath(filePath);
let want = {
// Grant the read and write permissions on the shared file to the target application.
flags: wantConstant.Flags.FLAG_AUTH_WRITE_URI_PERMISSION | wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION,
// Set the implicit startup rule for the application that shares the file.
action: 'ohos.want.action.sendData',
uri: uri,
type: 'text/plain'
}
this.context.startAbility(want)
.then(() => {
console.info('Invoke getCurrentBundleStats succeeded.');
})
.catch((err) => {
console.error(`Invoke startAbility failed, code is ${err.code}, message is ${err.message}`);
});
}
...
}
```
## Using Shared Files
In the [**module.json5** file](../quick-start/module-configuration-file.md) of the application, which wants to use the shared file, set **actions** to **ohos.want.action.sendData** to allow the application to receive files shared by another application and set **uris** to the type of the URI to receive. In the following example, the application receives only .txt files with **scheme** of **file**.
```json
{
"module": {
...
"abilities": [
{
...
"skills": [
{
...
"actions": [
"ohos.want.action.sendData"
],
"uris": [
{
"scheme": "file",
"type": "text/plain"
}
]
}
]
}
]
}
}
```
After **UIAbility** of the application starts, the application obtains **want** information from [**onCreate()**](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) or [**onNewWant()**](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonnewwant).
After obtaining the URI of the shared file through **want**, the application can call **fs.open()** to open the file, and then read and write the file after obtaining the related file object.
```ts
// xxx.ets
import fs from '@ohos.file.fs';
function getShareFile() {
try {
let want =...; // Obtain the want information sent from the application that shares the file.
// Obtain the uri field from the want information.
let uri = want.uri;
if (uri == null || uri == undefined) {
console.info('uri is invalid');
return;
}
try {
// Perform operations on the URI of the shared file as required. For example, open the URI to obtain the file object in read/write mode.
let file = fs.openSync(uri, fs.OpenMode.READ_WRITE);
console.info('open file successfully!');
} catch (error) {
console.error(`Invoke openSync failed, code is ${error.code}, message is ${error.message}`);
}
} catch (error) {
console.error(`Invoke openSync failed, code is ${error.code}, message is ${error.message}`);
}
}
```
# User File Overview
User files are the private images, video and audio clips, and documents of the user who logs in to the device.
1. User files are stored in a directory, whose owner is the user who logs in to the device.
2. User files can be stored in [built-in storage](#built-in-storage) and [external storage](#external-storage).
3. An application cannot access user files without user authorization, or the operations on user files must be performed by the user.
OpenHarmony provides the [user file access framework](#user-file-access-framework) for developers to access and manage user files, which will be described in detail below.
## User File Storage
### Built-in Storage
Built-in storage refers to the internal storage device (space) of a device. The built-in storage device cannot be removed. The following files can be stored in the built-in storage of a device:
- Files owned by a user: The files belong to the user who logs in to the device. Different users who log in to a device can view only their own files.
These user files can be classified into the following types based on file attributes and access habits of users/applications:
- Image/Video files
The files have attributes, such as the shooting time, location, rotation angle, and file width and height information, and are stored in media file formats. The files are usually presented as media files or albums, without the specific location in the system.
- Audio files
The files have attributes, such as the album, creator, and shooting duration information, and are stored in media file formats. Generally, the files are presented by file, album, or creator, without the specific location in the system.
- Documents
The files are stored as common files, including common text files, compressed files, and images, videos and audio clips stored as common files. These files are presented in a directory tree.
- Files shared by users: The files are stored in a directory for share and shared by multiple users.
The files in the shared directory are stored as common files and presented in a directory tree.
### External Storage
External storage is not inside a device's main storage or memory. Common external storage devices include pluggable devices, such as SD cards and USB flash drives. Same as the files in the shared directory of the built-in storage device, the files in an external storage device can be viewed by all the users who log in to the system.
External storage devices are pluggable. OpenHarmony provides the functions of listening for the device insertion and removal events and mounting/unmounting an external storage device. For details, see [Managing External Storage Devices)](manage-external-storage.md).
The files on external storage devices are presented as common files in a directory tree, like the documents stored in built-in storage.
## User File Access Framework
OpenHarmony provides the user file access framework for developers to access and manage user files. This framework leverages the ExtensionAbility of OpenHarmony to provide a set of methods and interfaces for accessing user files.
**Figure 1** User file access framework
![User file access framework](figures/user-file-access-framework.png)
- To access user files, for example, select a photo or save multiple documents, a system application or third-party application (file access client in **Figure 1**) starts the **FilePicker** application.
- OpenHarmony is prebuilt with the **FilePicker** and **FileManager** applications.
- **FilePicker**: provides APIs for a file access client to select and save user files without any permission. For details, see [Selecting User Files](select-user-file.md).
- **FileManager**: allows users to view and modify files, and delete, rename, move, and create files or directories by using a system FileManager.
You can also develop your own FilePicker or FileManager applications as required. FilePicker is a subset of FileManager. For details about how to develop a FileManager application, see [Developing a FileManager Application)](dev-user-file-manager.md).
- The user file access framework provides the following functional modules:
- **File Access Helper**: provides APIs for the **FileManager** and **FilePicker** to access user files.
- **File Access ExtensionAbility**: provides a file access framework to implement file access functions. The **File Access ExtensionAbility** consists of the following:
- **UserFileManager**: implements management of the files stored on the built-in storage.
- **ExternalFileManager**: implements management of the files stored on the external storage.
...@@ -64,7 +64,7 @@ For details about the error codes, see [Application Access Control Error Codes]( ...@@ -64,7 +64,7 @@ For details about the error codes, see [Application Access Control Error Codes](
| ID| Error Message| | ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 12100001 | The parameter is invalid. The tokenID is 0, or the permissionName is greater than 256 bytes. | | 12100001 | The parameter is invalid. The tokenID is 0 or the permissionName exceeds 256 bytes. |
**Example** **Example**
...@@ -111,7 +111,7 @@ For details about the error codes, see [Application Access Control Error Codes]( ...@@ -111,7 +111,7 @@ For details about the error codes, see [Application Access Control Error Codes](
| ID| Error Message| | ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 12100001 | The parameter is invalid. The tokenID is 0, or the permissionName is greater than 256 bytes. | | 12100001 | The parameter is invalid. The tokenID is 0 or the permissionName exceeds 256 bytes. |
**Example** **Example**
...@@ -206,9 +206,9 @@ For details about the error codes, see [Application Access Control Error Codes]( ...@@ -206,9 +206,9 @@ For details about the error codes, see [Application Access Control Error Codes](
| ID| Error Message| | ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 12100001 | The parameter is invalid. The tokenID is 0, the permissionName is greater than 256 bytes, or the flags value is invalid. | | 12100001 | The parameter is invalid. The tokenID is 0, the permissionName exceeds 256 bytes, or the flags value is invalid. |
| 12100002 | TokenId does not exist. | | 12100002 | The specified tokenID does not exist. |
| 12100003 | Permission does not exist. | | 12100003 | The specified permission does not exist. |
| 12100006 | The application specified by the tokenID is not allowed to be granted with the specified permission. Either the application is a sandbox or the tokenID is from a remote device. | | 12100006 | The application specified by the tokenID is not allowed to be granted with the specified permission. Either the application is a sandbox or the tokenID is from a remote device. |
| 12100007 | Service is abnormal. | | 12100007 | Service is abnormal. |
...@@ -265,7 +265,7 @@ For details about the error codes, see [Application Access Control Error Codes]( ...@@ -265,7 +265,7 @@ For details about the error codes, see [Application Access Control Error Codes](
| ID| Error Message| | ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 12100001 | The parameter is invalid. The tokenID is 0, the permissionName is greater than 256 bytes, or the flags value is invalid. | | 12100001 | The parameter is invalid. The tokenID is 0, the permissionName exceeds 256 bytes, or the flags value is invalid. |
| 12100002 | The specified tokenID does not exist. | | 12100002 | The specified tokenID does not exist. |
| 12100003 | The specified permission does not exist. | | 12100003 | The specified permission does not exist. |
| 12100006 | The application specified by the tokenID is not allowed to be revoked with the specified permission. Either the application is a sandbox or the tokenID is from a remote device. | | 12100006 | The application specified by the tokenID is not allowed to be revoked with the specified permission. Either the application is a sandbox or the tokenID is from a remote device. |
...@@ -317,9 +317,9 @@ For details about the error codes, see [Application Access Control Error Codes]( ...@@ -317,9 +317,9 @@ For details about the error codes, see [Application Access Control Error Codes](
| ID| Error Message| | ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 12100001 | The parameter is invalid. The tokenID is 0, the permissionName is greater than 256 bytes, or the flags value is invalid. | | 12100001 | The parameter is invalid. The tokenID is 0, the permissionName exceeds 256 bytes, or the flags value is invalid. |
| 12100002 | TokenId does not exist. | | 12100002 | The specified tokenID does not exist. |
| 12100003 | Permission does not exist. | | 12100003 | The specified permission does not exist. |
| 12100006 | The application specified by the tokenID is not allowed to be revoked with the specified permission. Either the application is a sandbox or the tokenID is from a remote device. | | 12100006 | The application specified by the tokenID is not allowed to be revoked with the specified permission. Either the application is a sandbox or the tokenID is from a remote device. |
| 12100007 | Service is abnormal. | | 12100007 | Service is abnormal. |
...@@ -375,7 +375,7 @@ For details about the error codes, see [Application Access Control Error Codes]( ...@@ -375,7 +375,7 @@ For details about the error codes, see [Application Access Control Error Codes](
| ID| Error Message| | ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 12100001 | The parameter is invalid. The tokenID is 0, or the permissionName is greater than 256 bytes. | | 12100001 | The parameter is invalid. The tokenID is 0 or the permissionName exceeds 256 bytes. |
| 12100002 | The specified tokenID does not exist. | | 12100002 | The specified tokenID does not exist. |
| 12100003 | The specified permission does not exist. | | 12100003 | The specified permission does not exist. |
| 12100006 | The operation is not allowed. Either the application is a sandbox or the tokenID is from a remote device. | | 12100006 | The operation is not allowed. Either the application is a sandbox or the tokenID is from a remote device. |
...@@ -452,7 +452,7 @@ For details about the error codes, see [Application Access Control Error Codes]( ...@@ -452,7 +452,7 @@ For details about the error codes, see [Application Access Control Error Codes](
| ID| Error Message| | ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 12100001 | The parameter is invalid. The tokenID is 0, or the permissionName is greater than 256 bytes. | | 12100001 | The parameter is invalid. The tokenID is 0 or the permissionName exceeds 256 bytes. |
| 12100004 | The interface is called repeatedly with the same input. | | 12100004 | The interface is called repeatedly with the same input. |
| 12100005 | The registration time has exceeded the limitation. | | 12100005 | The registration time has exceeded the limitation. |
| 12100007 | Service is abnormal. | | 12100007 | Service is abnormal. |
...@@ -462,10 +462,10 @@ For details about the error codes, see [Application Access Control Error Codes]( ...@@ -462,10 +462,10 @@ For details about the error codes, see [Application Access Control Error Codes](
```js ```js
import abilityAccessCtrl, {Permissions} from '@ohos.abilityAccessCtrl'; import abilityAccessCtrl, {Permissions} from '@ohos.abilityAccessCtrl';
import bundle from '@ohos.bundle.bundleManager'; import bundleManager from '@ohos.bundle.bundleManager';
let atManager = abilityAccessCtrl.createAtManager(); let atManager = abilityAccessCtrl.createAtManager();
let appInfo = bundle.getApplicationInfoSync('com.example.myapplication', 0, 100); let appInfo = bundleManager.getApplicationInfoSync('com.example.myapplication', 0, 100);
let tokenIDList: Array<number> = [appInfo.accessTokenId]; let tokenIDList: Array<number> = [appInfo.accessTokenId];
let permissionList: Array<Permissions> = ["ohos.permission.DISTRIBUTED_DATASYNC"]; let permissionList: Array<Permissions> = ["ohos.permission.DISTRIBUTED_DATASYNC"];
try { try {
...@@ -513,10 +513,10 @@ For details about the error codes, see [Application Access Control Error Codes]( ...@@ -513,10 +513,10 @@ For details about the error codes, see [Application Access Control Error Codes](
```js ```js
import abilityAccessCtrl, {Permissions} from '@ohos.abilityAccessCtrl'; import abilityAccessCtrl, {Permissions} from '@ohos.abilityAccessCtrl';
import bundle from '@ohos.bundle.bundleManager'; import bundleManager from '@ohos.bundle.bundleManager';
let atManager = abilityAccessCtrl.createAtManager(); let atManager = abilityAccessCtrl.createAtManager();
let appInfo = bundle.getApplicationInfoSync('com.example.myapplication', 0, 100); let appInfo = bundleManager.getApplicationInfoSync('com.example.myapplication', 0, 100);
let tokenIDList: Array<number> = [appInfo.accessTokenId]; let tokenIDList: Array<number> = [appInfo.accessTokenId];
let permissionList: Array<Permissions> = ["ohos.permission.DISTRIBUTED_DATASYNC"]; let permissionList: Array<Permissions> = ["ohos.permission.DISTRIBUTED_DATASYNC"];
try { try {
...@@ -568,7 +568,10 @@ promise.then(data => { ...@@ -568,7 +568,10 @@ promise.then(data => {
requestPermissionsFromUser(context: Context, permissionList: Array&lt;Permissions&gt;, requestCallback: AsyncCallback&lt;PermissionRequestResult&gt;) : void; requestPermissionsFromUser(context: Context, permissionList: Array&lt;Permissions&gt;, requestCallback: AsyncCallback&lt;PermissionRequestResult&gt;) : void;
Requests permissions from the user in a dialog box. This API uses an asynchronous callback to return the result. Requests user authorization in a dialog box opened by a UIAbility. This API uses an asynchronous callback to return the result.
> **NOTE**
>
> The API cannot be called by any non-UIAbility.
**Model restriction**: This API can be used only in the stage model. **Model restriction**: This API can be used only in the stage model.
...@@ -578,7 +581,7 @@ Requests permissions from the user in a dialog box. This API uses an asynchronou ...@@ -578,7 +581,7 @@ Requests permissions from the user in a dialog box. This API uses an asynchronou
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| context | Context | Yes| Ability context of the application that requests the permissions. | | context | Context | Yes| Context of the UIAbility.|
| permissionList | Array&lt;Permissions&gt; | Yes| Permissions requested. For details about the permissions, see the [Application Permission List](../../security/permission-list.md).| | permissionList | Array&lt;Permissions&gt; | Yes| Permissions requested. For details about the permissions, see the [Application Permission List](../../security/permission-list.md).|
| callback | AsyncCallback&lt;[PermissionRequestResult](js-apis-permissionrequestresult.md)&gt; | Yes| Callback invoked to return the result.| | callback | AsyncCallback&lt;[PermissionRequestResult](js-apis-permissionrequestresult.md)&gt; | Yes| Callback invoked to return the result.|
...@@ -610,7 +613,11 @@ try { ...@@ -610,7 +613,11 @@ try {
requestPermissionsFromUser(context: Context, permissionList: Array&lt;Permissions&gt;) : Promise&lt;PermissionRequestResult&gt;; requestPermissionsFromUser(context: Context, permissionList: Array&lt;Permissions&gt;) : Promise&lt;PermissionRequestResult&gt;;
Requests permissions from the user in a dialog box. This API uses a promise to return the result. Requests user authorization in a dialog box opened by a UIAbility. This API uses a promise to return the result.
> **NOTE**
>
> The API cannot be called by any non-UIAbility.
**Model restriction**: This API can be used only in the stage model. **Model restriction**: This API can be used only in the stage model.
...@@ -620,7 +627,7 @@ Requests permissions from the user in a dialog box. This API uses a promise to ...@@ -620,7 +627,7 @@ Requests permissions from the user in a dialog box. This API uses a promise to
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| context | Context | Yes| Ability context of the application that requests the permissions. | | context | Context | Yes| Context of the UIAbility.|
| permissionList | Array&lt;Permissions&gt; | Yes| Permissions requested. For details about the permissions, see the [Application Permission List](../../security/permission-list.md).| | permissionList | Array&lt;Permissions&gt; | Yes| Permissions requested. For details about the permissions, see the [Application Permission List](../../security/permission-list.md).|
**Return value** **Return value**
...@@ -693,6 +700,44 @@ promise.then(data => { ...@@ -693,6 +700,44 @@ promise.then(data => {
}); });
``` ```
### checkAccessTokenSync<sup>10+</sup>
checkAccessTokenSync(tokenID: number, permissionName: Permissions): GrantStatus;
Checks whether a permission is granted to an application. This API returns the result synchronously.
**System capability**: SystemCapability.Security.AccessToken
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------- | ---- | ------------------------------------------ |
| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundleManager-applicationInfo.md). |
| permissionName | Permissions | Yes | Permission to check. For details about the permissions, see the [Application Permission List](../../security/permission-list.md).|
**Return value**
| Type | Description |
| :------------ | :---------------------------------- |
| [GrantStatus](#grantstatus) | Permission grant state.|
**Error codes**
For details about the error codes, see [Application Access Control Error Codes](../errorcodes/errorcode-access-token.md).
| ID| Error Message|
| -------- | -------- |
| 12100001 | The parameter is invalid. The tokenID is 0 or the permissionName exceeds 256 bytes. |
**Example**
```js
let atManager = abilityAccessCtrl.createAtManager();
let tokenID = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a non-system application.
let data = atManager.checkAccessTokenSync(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS");
console.log(`data->${JSON.stringify(data)}`);
```
### GrantStatus ### GrantStatus
Enumerates the permission grant states. Enumerates the permission grant states.
...@@ -730,4 +775,3 @@ Defines detailed information about the permission grant state change. ...@@ -730,4 +775,3 @@ Defines detailed information about the permission grant state change.
| change | [PermissionStateChangeType](#permissionstatechangetype9) | Yes | No | Operation that triggers the permission grant state change. | | change | [PermissionStateChangeType](#permissionstatechangetype9) | Yes | No | Operation that triggers the permission grant state change. |
| tokenID | number | Yes | No | Token ID of the application. | | tokenID | number | Yes | No | Token ID of the application. |
| permissionName | Permissions | Yes | No | Permission whose grant state changes. For details about the permissions, see the [Application Permission List](../../security/permission-list.md). | | permissionName | Permissions | Yes | No | Permission whose grant state changes. For details about the permissions, see the [Application Permission List](../../security/permission-list.md). |
...@@ -2085,31 +2085,34 @@ Obtains the authenticator callback for the authentication session. This API uses ...@@ -2085,31 +2085,34 @@ Obtains the authenticator callback for the authentication session. This API uses
**Example** **Example**
```js ```js
import featureAbility from '@ohos.ability.featureAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
featureAbility.getWant((err, want) => {
var sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID]; export default class EntryAbility extends UIAbility {
try { onCreate(want, param) {
appAccountManager.getAuthCallback(sessionId, (err, callback) => { var sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID];
if (err.code != account_appAccount.ResultCode.SUCCESS) { try {
console.log("getAuthCallback err: " + JSON.stringify(err)); appAccountManager.getAuthCallback(sessionId, (err, callback) => {
return; if (err != null) {
} console.log("getAuthCallback err: " + JSON.stringify(err));
var result = { return;
accountInfo: {
name: "Lisi",
owner: "com.example.accountjsdemo",
},
tokenInfo: {
token: "xxxxxx",
authType: "getSocialData"
} }
}; var result = {
callback.onResult(account_appAccount.ResultCode.SUCCESS, result); accountInfo: {
}); name: "Lisi",
} catch (err) { owner: "com.example.accountjsdemo",
console.log("getAuthCallback exception: " + JSON.stringify(err)); },
tokenInfo: {
token: "xxxxxx",
authType: "getSocialData"
}
};
callback.onResult(0, result);
});
} catch (err) {
console.log("getAuthCallback exception: " + JSON.stringify(err));
}
} }
}); }
``` ```
### getAuthCallback<sup>9+</sup> ### getAuthCallback<sup>9+</sup>
...@@ -2143,9 +2146,10 @@ Obtains the authenticator callback for the authentication session. This API uses ...@@ -2143,9 +2146,10 @@ Obtains the authenticator callback for the authentication session. This API uses
**Example** **Example**
```js ```js
import featureAbility from '@ohos.ability.featureAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
featureAbility.getWant().then((want) => { export default class EntryAbility extends UIAbility {
onCreate(want, param) {
var sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID]; var sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID];
try { try {
appAccountManager.getAuthCallback(sessionId).then((callback) => { appAccountManager.getAuthCallback(sessionId).then((callback) => {
...@@ -2159,16 +2163,15 @@ Obtains the authenticator callback for the authentication session. This API uses ...@@ -2159,16 +2163,15 @@ Obtains the authenticator callback for the authentication session. This API uses
authType: "getSocialData" authType: "getSocialData"
} }
}; };
callback.onResult(account_appAccount.ResultCode.SUCCESS, result); callback.onResult(0, result);
}).catch((err) => { }).catch((err) => {
console.log("getAuthCallback err: " + JSON.stringify(err)); console.log("getAuthCallback err: " + JSON.stringify(err));
}); });
} catch (err) { } catch (err) {
console.log("getAuthCallback exception: " + JSON.stringify(err)); console.log("getAuthCallback exception: " + JSON.stringify(err));
} }
}).catch((err) => { }
console.log("getWant err: " + JSON.stringify(err)); }
});
``` ```
### queryAuthenticatorInfo<sup>9+</sup> ### queryAuthenticatorInfo<sup>9+</sup>
...@@ -2768,7 +2771,8 @@ addAccount(name: string, extraInfo?: string): Promise&lt;void&gt; ...@@ -2768,7 +2771,8 @@ addAccount(name: string, extraInfo?: string): Promise&lt;void&gt;
Adds an app account name and additional information. This API uses an asynchronous callback to return the result. This API uses a promise to return the result. Adds an app account name and additional information. This API uses an asynchronous callback to return the result. This API uses a promise to return the result.
> **NOTE**<br> > **NOTE**
>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [createAccount](#createaccount9-2). > This API is supported since API version 7 and deprecated since API version 9. You are advised to use [createAccount](#createaccount9-2).
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
...@@ -4281,10 +4285,12 @@ Obtains the authenticator callback for an authentication session. This API uses ...@@ -4281,10 +4285,12 @@ Obtains the authenticator callback for an authentication session. This API uses
**Example** **Example**
```js ```js
import featureAbility from '@ohos.ability.featureAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
featureAbility.getWant((err, want) => {
var sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID]; export default class EntryAbility extends UIAbility {
appAccountManager.getAuthenticatorCallback(sessionId, (err, callback) => { onCreate(want, param) {
var sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID];
appAccountManager.getAuthenticatorCallback(sessionId, (err, callback) => {
if (err.code != account_appAccount.ResultCode.SUCCESS) { if (err.code != account_appAccount.ResultCode.SUCCESS) {
console.log("getAuthenticatorCallback err: " + JSON.stringify(err)); console.log("getAuthenticatorCallback err: " + JSON.stringify(err));
return; return;
...@@ -4294,8 +4300,9 @@ Obtains the authenticator callback for an authentication session. This API uses ...@@ -4294,8 +4300,9 @@ Obtains the authenticator callback for an authentication session. This API uses
[account_appAccount.Constants.KEY_AUTH_TYPE]: "getSocialData", [account_appAccount.Constants.KEY_AUTH_TYPE]: "getSocialData",
[account_appAccount.Constants.KEY_TOKEN]: "xxxxxx"}; [account_appAccount.Constants.KEY_TOKEN]: "xxxxxx"};
callback.onResult(account_appAccount.ResultCode.SUCCESS, result); callback.onResult(account_appAccount.ResultCode.SUCCESS, result);
}); });
}); }
}
``` ```
### getAuthenticatorCallback<sup>(deprecated)</sup> ### getAuthenticatorCallback<sup>(deprecated)</sup>
...@@ -4325,22 +4332,22 @@ Obtains the authenticator callback for an authentication session. This API uses ...@@ -4325,22 +4332,22 @@ Obtains the authenticator callback for an authentication session. This API uses
**Example** **Example**
```js ```js
import featureAbility from '@ohos.ability.featureAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
featureAbility.getWant().then((want) => { export default class EntryAbility extends UIAbility {
onCreate(want, param) {
var sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID]; var sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID];
appAccountManager.getAuthenticatorCallback(sessionId).then((callback) => { appAccountManager.getAuthenticatorCallback(sessionId).then((callback) => {
var result = {[account_appAccount.Constants.KEY_NAME]: "LiSi", var result = {[account_appAccount.Constants.KEY_NAME]: "LiSi",
[account_appAccount.Constants.KEY_OWNER]: "com.example.accountjsdemo", [account_appAccount.Constants.KEY_OWNER]: "com.example.accountjsdemo",
[account_appAccount.Constants.KEY_AUTH_TYPE]: "getSocialData", [account_appAccount.Constants.KEY_AUTH_TYPE]: "getSocialData",
[account_appAccount.Constants.KEY_TOKEN]: "xxxxxx"}; [account_appAccount.Constants.KEY_TOKEN]: "xxxxxx"};
callback.onResult(account_appAccount.ResultCode.SUCCESS, result); callback.onResult(account_appAccount.ResultCode.SUCCESS, result);
}).catch((err) => { }).catch((err) => {
console.log("getAuthenticatorCallback err: " + JSON.stringify(err)); console.log("getAuthenticatorCallback err: " + JSON.stringify(err));
}); });
}).catch((err) => { }
console.log("getWant err: " + JSON.stringify(err)); }
});
``` ```
### getAuthenticatorInfo<sup>(deprecated)</sup> ### getAuthenticatorInfo<sup>(deprecated)</sup>
...@@ -4554,7 +4561,8 @@ Enumerates the constants. ...@@ -4554,7 +4561,8 @@ Enumerates the constants.
Enumerates the result codes. Enumerates the result codes.
> **NOTE**<br> > **NOTE**
>
> This enum is supported since API version 8 and deprecated since API version 9. Error codes are used from API version 9. For details, see [Account Management Error Codes](../errorcodes/errorcode-account.md). > This enum is supported since API version 8 and deprecated since API version 9. Error codes are used from API version 9. For details, see [Account Management Error Codes](../errorcodes/errorcode-account.md).
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
......
...@@ -16,6 +16,8 @@ This module provides the following functions: ...@@ -16,6 +16,8 @@ This module provides the following functions:
>- The APIs provided by this module are no longer maintained since API version 9. You are advised to use [@ohos.data.distributedKVStore](js-apis-distributedKVStore.md). >- The APIs provided by this module are no longer maintained since API version 9. You are advised to use [@ohos.data.distributedKVStore](js-apis-distributedKVStore.md).
> >
>- The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. >- The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>
>- All the APIs that need to obtain **deviceId** in this module are available only to system applications.
## Modules to Import ## Modules to Import
...@@ -88,25 +90,22 @@ Creates a **KVManager** instance to manage KV stores. This API uses a promise to ...@@ -88,25 +90,22 @@ Creates a **KVManager** instance to manage KV stores. This API uses a promise to
**Example** **Example**
```js ```js
let kvManager;
try { try {
const kvManagerConfig = { const kvManagerConfig = {
bundleName : 'com.example.datamanagertest', bundleName: 'com.example.datamanagertest',
userInfo : { userInfo: {
userId : '0', userId: '0',
userType : distributedData.UserType.SAME_USER_ID userType: distributedData.UserType.SAME_USER_ID
}
} }
distributedData.createKVManager(kvManagerConfig, function (err, manager) { }
if (err) { distributedData.createKVManager(kvManagerConfig).then((manager) => {
console.log("Failed to create KVManager: " + JSON.stringify(err)); console.log("Created KVManager successfully");
return; kvManager = manager;
} }).catch((err) => {
console.log("Created KVManager successfully"); console.error("Failed to create KVManager: " + JSON.stringify(err));
kvManager = manager; });
});
} catch (e) { } catch (e) {
console.log("An unexpected error occurred. Error:" + e); console.log("An unexpected error occurred. Error:" + e);
} }
``` ```
...@@ -212,7 +211,7 @@ Creates and obtains a KV store. This API uses a promise to return the result. ...@@ -212,7 +211,7 @@ Creates and obtains a KV store. This API uses a promise to return the result.
| Type | Description | | Type | Description |
| -------------------------------------- | ------------------------ | | -------------------------------------- | ------------------------ |
| Promise&lt;T&gt;, &lt;T extends [KVStore](#kvstore)&gt; | Promise used to return the KV store instance created. | | Promise&lt;T&gt;, &lt;T extends [KVStore](#kvstore)&gt; | Promise used to return the KV store instance created.|
**Example** **Example**
...@@ -485,7 +484,7 @@ Obtains the IDs of all KV stores that are created by [getKVStore()](#getkvstore) ...@@ -485,7 +484,7 @@ Obtains the IDs of all KV stores that are created by [getKVStore()](#getkvstore)
| Type | Description | | Type | Description |
| ------------- | -------------- | | ------------- | -------------- |
| Promise&lt;string[]&gt;| Promise used to return the IDs of all created KV stores. | | Promise&lt;string[]&gt;| Promise used to return the IDs of all created KV stores.|
**Example** **Example**
...@@ -2012,6 +2011,10 @@ try { ...@@ -2012,6 +2011,10 @@ try {
deviceId(deviceId:string):Query deviceId(deviceId:string):Query
Creates a **Query** object with the device ID as the key prefix. Creates a **Query** object with the device ID as the key prefix.
> **NOTE**
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core **System capability**: SystemCapability.DistributedDataManager.KVStore.Core
...@@ -3664,6 +3667,10 @@ try { ...@@ -3664,6 +3667,10 @@ try {
removeDeviceData(deviceId: string, callback: AsyncCallback&lt;void&gt;): void removeDeviceData(deviceId: string, callback: AsyncCallback&lt;void&gt;): void
Deletes data of a device. This API uses an asynchronous callback to return the result. Deletes data of a device. This API uses an asynchronous callback to return the result.
> **NOTE**
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core **System capability**: SystemCapability.DistributedDataManager.KVStore.Core
...@@ -3706,6 +3713,10 @@ try { ...@@ -3706,6 +3713,10 @@ try {
removeDeviceData(deviceId: string): Promise&lt;void&gt; removeDeviceData(deviceId: string): Promise&lt;void&gt;
Deletes data of a device. This API uses a promise to return the result. Deletes data of a device. This API uses a promise to return the result.
> **NOTE**
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core **System capability**: SystemCapability.DistributedDataManager.KVStore.Core
...@@ -3754,8 +3765,8 @@ try { ...@@ -3754,8 +3765,8 @@ try {
sync(deviceIds: string[], mode: SyncMode, delayMs?: number): void sync(deviceIds: string[], mode: SyncMode, delayMs?: number): void
Synchronizes the KV store manually. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview](../../database/database-mdds-overview.md). Synchronizes the KV store manually.
> **NOTE**<br/> > **NOTE**
> >
> The value of **deviceIds** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. > The value of **deviceIds** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
...@@ -3825,7 +3836,7 @@ Subscribes to data changes of the specified type. ...@@ -3825,7 +3836,7 @@ Subscribes to data changes of the specified type.
| -------- | --------------------------------------------------------- | ---- | ---------------------------------------------------- | | -------- | --------------------------------------------------------- | ---- | ---------------------------------------------------- |
| event | string | Yes | Event to subscribe to. The value is **dataChange**, which indicates a data change event.| | event | string | Yes | Event to subscribe to. The value is **dataChange**, which indicates a data change event.|
| type | [SubscribeType](#subscribetype) | Yes | Type of data change. | | type | [SubscribeType](#subscribetype) | Yes | Type of data change. |
| listener | Callback&lt;[ChangeNotification](#changenotification)&gt; | Yes | Callback invoked to return the result. | | listener | Callback&lt;[ChangeNotification](#changenotification)&gt; | Yes | Callback invoked to return a data change event. |
**Example** **Example**
...@@ -4084,6 +4095,10 @@ Before calling any method in **DeviceKVStore**, you must use [getKVStore](#getkv ...@@ -4084,6 +4095,10 @@ Before calling any method in **DeviceKVStore**, you must use [getKVStore](#getkv
get(deviceId: string, key: string, callback: AsyncCallback&lt;boolean|string|number|Uint8Array&gt;): void get(deviceId: string, key: string, callback: AsyncCallback&lt;boolean|string|number|Uint8Array&gt;): void
Obtains a string value that matches the specified device ID and key. This API uses an asynchronous callback to return the result. Obtains a string value that matches the specified device ID and key. This API uses an asynchronous callback to return the result.
> **NOTE**
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
...@@ -4119,6 +4134,10 @@ try{ ...@@ -4119,6 +4134,10 @@ try{
get(deviceId: string, key: string): Promise&lt;boolean|string|number|Uint8Array&gt; get(deviceId: string, key: string): Promise&lt;boolean|string|number|Uint8Array&gt;
Obtains a string value that matches the specified device ID and key. This API uses a promise to return the result. Obtains a string value that matches the specified device ID and key. This API uses a promise to return the result.
> **NOTE**
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
...@@ -4163,6 +4182,10 @@ try { ...@@ -4163,6 +4182,10 @@ try {
getEntries(deviceId: string, keyPrefix: string, callback: AsyncCallback&lt;Entry[]&gt;): void getEntries(deviceId: string, keyPrefix: string, callback: AsyncCallback&lt;Entry[]&gt;): void
Obtains all KV pairs that match the specified device ID and key prefix. This API uses an asynchronous callback to return the result. Obtains all KV pairs that match the specified device ID and key prefix. This API uses an asynchronous callback to return the result.
> **NOTE**
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
...@@ -4211,6 +4234,10 @@ try { ...@@ -4211,6 +4234,10 @@ try {
getEntries(deviceId: string, keyPrefix: string): Promise&lt;Entry[]&gt; getEntries(deviceId: string, keyPrefix: string): Promise&lt;Entry[]&gt;
Obtains all KV pairs that match the specified device ID and key prefix. This API uses a promise to return the result. Obtains all KV pairs that match the specified device ID and key prefix. This API uses a promise to return the result.
> **NOTE**
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
...@@ -4380,6 +4407,10 @@ try { ...@@ -4380,6 +4407,10 @@ try {
getEntries(deviceId: string, query: Query, callback: AsyncCallback&lt;Entry[]&gt;): void getEntries(deviceId: string, query: Query, callback: AsyncCallback&lt;Entry[]&gt;): void
Obtains the KV pairs that match the specified device ID and **Query** object. This API uses an asynchronous callback to return the result. Obtains the KV pairs that match the specified device ID and **Query** object. This API uses an asynchronous callback to return the result.
> **NOTE**
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
...@@ -4433,6 +4464,10 @@ try { ...@@ -4433,6 +4464,10 @@ try {
getEntries(deviceId: string, query: Query): Promise&lt;Entry[]&gt; getEntries(deviceId: string, query: Query): Promise&lt;Entry[]&gt;
Obtains the KV pairs that match the specified device ID and **Query** object. This API uses a promise to return the result. Obtains the KV pairs that match the specified device ID and **Query** object. This API uses a promise to return the result.
> **NOTE**
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
...@@ -4493,6 +4528,10 @@ try { ...@@ -4493,6 +4528,10 @@ try {
getResultSet(deviceId: string, keyPrefix: string, callback: AsyncCallback&lt;KvStoreResultSet&gt;): void getResultSet(deviceId: string, keyPrefix: string, callback: AsyncCallback&lt;KvStoreResultSet&gt;): void
Obtains a **KvStoreResultSet** object that matches the specified device ID and key prefix. This API uses an asynchronous callback to return the result. Obtains a **KvStoreResultSet** object that matches the specified device ID and key prefix. This API uses an asynchronous callback to return the result.
> **NOTE**
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
...@@ -4528,6 +4567,10 @@ try { ...@@ -4528,6 +4567,10 @@ try {
getResultSet(deviceId: string, keyPrefix: string): Promise&lt;KvStoreResultSet&gt; getResultSet(deviceId: string, keyPrefix: string): Promise&lt;KvStoreResultSet&gt;
Obtains a **KvStoreResultSet** object that matches the specified device ID and key prefix. This API uses a promise to return the result. Obtains a **KvStoreResultSet** object that matches the specified device ID and key prefix. This API uses a promise to return the result.
> **NOTE**
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
...@@ -4688,6 +4731,10 @@ try { ...@@ -4688,6 +4731,10 @@ try {
getResultSet(deviceId: string, query: Query, callback: AsyncCallback&lt;KvStoreResultSet&gt;): void getResultSet(deviceId: string, query: Query, callback: AsyncCallback&lt;KvStoreResultSet&gt;): void
Obtains a **KvStoreResultSet** object that matches the specified device ID and **Query** object. This API uses an asynchronous callback to return the result. Obtains a **KvStoreResultSet** object that matches the specified device ID and **Query** object. This API uses an asynchronous callback to return the result.
> **NOTE**
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
...@@ -4740,6 +4787,10 @@ try { ...@@ -4740,6 +4787,10 @@ try {
getResultSet(deviceId: string, query: Query): Promise&lt;KvStoreResultSet&gt; getResultSet(deviceId: string, query: Query): Promise&lt;KvStoreResultSet&gt;
Obtains a **KvStoreResultSet** object that matches the specified device ID and **Query** object. This API uses a promise to return the result. Obtains a **KvStoreResultSet** object that matches the specified device ID and **Query** object. This API uses a promise to return the result.
> **NOTE**
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
...@@ -4982,6 +5033,10 @@ try { ...@@ -4982,6 +5033,10 @@ try {
getResultSize(deviceId: string, query: Query, callback: AsyncCallback&lt;number&gt;): void; getResultSize(deviceId: string, query: Query, callback: AsyncCallback&lt;number&gt;): void;
Obtains the number of results that matches the specified device ID and **Query** object. This API uses an asynchronous callback to return the result. Obtains the number of results that matches the specified device ID and **Query** object. This API uses an asynchronous callback to return the result.
> **NOTE**
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
...@@ -5029,6 +5084,10 @@ try { ...@@ -5029,6 +5084,10 @@ try {
getResultSize(deviceId: string, query: Query): Promise&lt;number&gt; getResultSize(deviceId: string, query: Query): Promise&lt;number&gt;
Obtains the number of results that matches the specified device ID and **Query** object. This API uses a promise to return the result. Obtains the number of results that matches the specified device ID and **Query** object. This API uses a promise to return the result.
> **NOTE**
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
...@@ -5085,6 +5144,10 @@ try { ...@@ -5085,6 +5144,10 @@ try {
removeDeviceData(deviceId: string, callback: AsyncCallback&lt;void&gt;): void removeDeviceData(deviceId: string, callback: AsyncCallback&lt;void&gt;): void
Deletes data of the specified device from this KV store. This API uses an asynchronous callback to return the result. Deletes data of the specified device from this KV store. This API uses an asynchronous callback to return the result.
> **NOTE**
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
...@@ -5127,6 +5190,10 @@ try { ...@@ -5127,6 +5190,10 @@ try {
removeDeviceData(deviceId: string): Promise&lt;void&gt; removeDeviceData(deviceId: string): Promise&lt;void&gt;
Deletes data of the specified device from this KV store. This API uses a promise to return the result. Deletes data of the specified device from this KV store. This API uses a promise to return the result.
> **NOTE**
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
...@@ -5175,9 +5242,9 @@ try { ...@@ -5175,9 +5242,9 @@ try {
sync(deviceIds: string[], mode: SyncMode, delayMs?: number): void sync(deviceIds: string[], mode: SyncMode, delayMs?: number): void
Synchronizes the KV store manually. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview](../../database/database-mdds-overview.md). Synchronizes the KV store manually.
> **NOTE**<br/> > **NOTE**
> >
> The value of **deviceIds** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. > The value of **deviceIds** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
...@@ -5247,7 +5314,7 @@ Subscribes to data changes of the specified type. ...@@ -5247,7 +5314,7 @@ Subscribes to data changes of the specified type.
| -------- | --------------------------------------------------------- | ---- | ---------------------------------------------------- | | -------- | --------------------------------------------------------- | ---- | ---------------------------------------------------- |
| event | string | Yes | Event to subscribe to. The value is **dataChange**, which indicates a data change event.| | event | string | Yes | Event to subscribe to. The value is **dataChange**, which indicates a data change event.|
| type | [SubscribeType](#subscribetype) | Yes | Type of data change. | | type | [SubscribeType](#subscribetype) | Yes | Type of data change. |
| listener | Callback&lt;[ChangeNotification](#changenotification)&gt; | Yes | Callback invoked to return the result. | | listener | Callback&lt;[ChangeNotification](#changenotification)&gt; | Yes | Callback invoked to return a data change event. |
**Example** **Example**
......
# @ohos.data.distributedKVStore (Distributed KV Store) # @ohos.data.distributedKVStore (Distributed KV Store)
The **distributedKVStore** module implements collaboration between databases for different devices that forms a Super Device. The APIs provided by this module can be used to save data to a distributed key-value (KV) store and perform operations, such as adding, deleting, modifying, querying, and synchronizing data in distributed KV stores. The **distributedKVStore** module implements collaboration between databases for different devices that forms a Super Device. You can use the APIs provided by this module to save application data to a distributed key-value (KV) store and perform operations, such as adding, deleting, modifying, querying, and synchronizing data in distributed KV stores.
The **distributedKVStore** module provides the following functions: The **distributedKVStore** module provides the following functions:
- [KVManager](#kvmanager): provides a **KVManager** instance to obtain KV store information. - [KVManager](#kvmanager): provides a **KVManager** instance to obtain KV store information.
- [KVStoreResultSet](#kvstoreresultset): provides APIs for obtaining KV store result sets. - [KVStoreResultSet](#kvstoreresultset): provides APIs for accessing the results obtained from a KV store.
- [Query](#query): provides APIs for setting predicates and querying data using predicates. - [Query](#query): provides APIs for setting predicates for data query.
- [SingleKVStore](#singlekvstore): provides APIs for querying data in single KV stores and synchronizing data. The single KV stores manage data without distinguishing devices. - [SingleKVStore](#singlekvstore): provides APIs for querying and synchronizing data in single KV stores. The single KV stores manage data without distinguishing devices.
- [DeviceKVStore](#devicekvstore): provides APIs for querying in device KV stores and synchronizing data. This class inherits from [SingleKVStore](#singlekvstore). The device KV stores manage data by device. - [DeviceKVStore](#devicekvstore): provides APIs for querying and synchronizing data in device KV stores. This class inherits from [SingleKVStore](#singlekvstore). The device KV stores manage data by device.
> **NOTE** > **NOTE**
> >
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> <br>All the APIs that need to obtain **deviceId** in this module are available only to system applications.
## Modules to Import ## Modules to Import
...@@ -22,13 +23,13 @@ import distributedKVStore from '@ohos.data.distributedKVStore'; ...@@ -22,13 +23,13 @@ import distributedKVStore from '@ohos.data.distributedKVStore';
## KVManagerConfig ## KVManagerConfig
Provides the **KVManager** instance configuration, including the bundle name of the invoker and the application context. Defines the **KVManager** instance configuration, including the bundle name of the invoker and the application context.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core **System capability**: SystemCapability.DistributedDataManager.KVStore.Core
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ---------- | --------------------- | ---- | ------------------------------------------------------------ | | ---------- | --------------------- | ---- | ------------------------------------------------------------ |
| context | Context | Yes |Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).| | context | Context | Yes |Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).<br>Since API version 10, the type of **context** is [BaseContext](js-apis-inner-application-baseContext.md).|
| bundleName | string | Yes | Bundle name. | | bundleName | string | Yes | Bundle name. |
## Constants ## Constants
...@@ -39,16 +40,16 @@ Provides constants of the distributed KV store. ...@@ -39,16 +40,16 @@ Provides constants of the distributed KV store.
| Name | Value | Description | | Name | Value | Description |
| --------------------- | ------- | --------------------------------------- | | --------------------- | ------- | --------------------------------------- |
| MAX_KEY_LENGTH | 1024 | Maximum length of a key in the distributed KV store, in bytes. | | MAX_KEY_LENGTH | 1024 | Maximum length of a key in a distributed KV store, in bytes. |
| MAX_VALUE_LENGTH | 4194303 | Maximum length of a value in the distributed KV store, in bytes.| | MAX_VALUE_LENGTH | 4194303 | Maximum length of a value in a distributed KV store, in bytes. |
| MAX_KEY_LENGTH_DEVICE | 896 | Maximum length of a device key, in bytes. | | MAX_KEY_LENGTH_DEVICE | 896 | Maximum length of a key in a device KV store, in bytes.|
| MAX_STORE_ID_LENGTH | 128 | Maximum length of a KV store ID, in bytes. | | MAX_STORE_ID_LENGTH | 128 | Maximum length of a KV store ID, in bytes. |
| MAX_QUERY_LENGTH | 512000 | Maximum query length, in bytes. | | MAX_QUERY_LENGTH | 512000 | Maximum query length, in bytes. |
| MAX_BATCH_SIZE | 128 | Maximum number of batch operations. | | MAX_BATCH_SIZE | 128 | Maximum number of batch operations. |
## ValueType ## ValueType
Enumerates the data types. Enumerates the types of the value in a KV pair.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core **System capability**: SystemCapability.DistributedDataManager.KVStore.Core
...@@ -70,18 +71,18 @@ Defines the **value** object in a KV store. ...@@ -70,18 +71,18 @@ Defines the **value** object in a KV store.
| Name | Type |Mandatory | Description | | Name | Type |Mandatory | Description |
| ----- | ------- |-----|------------------------ | | ----- | ------- |-----|------------------------ |
| type | [ValueType](#valuetype) | Yes|Type of the value. | | type | [ValueType](#valuetype) | Yes|Type of the value. |
| value | Uint8Array \| string \| number \| boolean| Yes|Value of the KV pair stored in the KV store. | | value | Uint8Array \| string \| number \| boolean| Yes|Value of the KV pair. |
## Entry ## Entry
Defines the KV pairs stored in the KV store. Defines the KV pairs stored in a KV store.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core **System capability**: SystemCapability.DistributedDataManager.KVStore.Core
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ----- | --------------- | ---- | -------- | | ----- | --------------- | ---- | -------- |
| key | string | Yes | Key of the KV pair stored in the KV store. | | key | string | Yes | Key of a KV pair in the KV store. |
| value | [Value](#value) | Yes | Value of the KV pair stored in the KV store.| | value | [Value](#value) | Yes | Value of a KV pair in the KV store. |
## ChangeNotification ## ChangeNotification
...@@ -126,8 +127,8 @@ Enumerates the distributed KV store types. ...@@ -126,8 +127,8 @@ Enumerates the distributed KV store types.
| Name | Description | | Name | Description |
| -------------------- | ------------------------------------------------------------ | | -------------------- | ------------------------------------------------------------ |
| DEVICE_COLLABORATION | Device KV store.<br> The device KV store manages data by device, which eliminates conflicts. Data can be queried by device.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore| | DEVICE_COLLABORATION | Device KV store.<br>The device KV store manages data by device, which eliminates conflicts. Data can be queried by device.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore |
| SINGLE_VERSION | Single KV store.<br> The single KV store does not differentiate data by device. If the same key is modified by different devices, the data will be overwritten.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| | SINGLE_VERSION | Single KV store.<br>The single KV store does not differentiate data by device. If entries with the same key are modified on different devices, the value will be overwritten.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core |
## SecurityLevel ## SecurityLevel
...@@ -135,12 +136,12 @@ Enumerates the KV store security levels. ...@@ -135,12 +136,12 @@ Enumerates the KV store security levels.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core **System capability**: SystemCapability.DistributedDataManager.KVStore.Core
| Name | Description | | Name | Description |
| -------: | ------------------------------------------------------------ | | ---: | ------------------------------------------------------------ |
| S1 | The KV store security level is low. If data leakage occurs, minor impact will be caused on the database. For example, a KV store that contains system data such as wallpapers.| | S1 | Low security level. Disclosure, tampering, corruption, or loss of the data may cause minor impact on an individual or group.<br>Examples: gender and nationality information, and user application records |
| S2 | The KV store security level is medium. If data leakage occurs, moderate impact will be caused on the database. For example, a KV store that contains information created by users or call records, such as audio or video clips.| | S2 | Medium security level. Disclosure, tampering, corruption, or loss of the data may cause major impact on an individual or group.<br>Examples: mailing addresses and nicknames of individuals |
| S3 | The KV store security level is high. If data leakage occurs, major impact will be caused on the database. For example, a KV store that contains information such as user fitness, health, and location data.| | S3 | High security level. Disclosure, tampering, corruption, or loss of the data may cause critical impact on an individual or group.<br>Examples: real-time precise positioning information and movement trajectory |
| S4 | The KV store security level is critical. If data leakage occurs, severe impact will be caused on the database. For example, a KV store that contains information such as authentication credentials and financial data.| | S4 | Critical security level. Disclosure, tampering, corruption, or loss of the data may cause significant adverse impact on an individual or group.<br>Examples: political opinions, religious and philosophical belief, trade union membership, genetic data, biological information, health and sexual life status, sexual orientation, device authentication, and personal credit card information |
## Options ## Options
...@@ -149,10 +150,10 @@ Provides KV store configuration. ...@@ -149,10 +150,10 @@ Provides KV store configuration.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| --------------- | -------------- | ---- | -------------------------| | --------------- | -------------- | ---- | -------------------------|
| createIfMissing | boolean | No | Whether to create a KV store if no database file exists. By default, a KV store is created.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| | createIfMissing | boolean | No | Whether to create a KV store if no database file exists. By default, a KV store is created.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core|
| encrypt | boolean | No | Whether to encrypt database files. By default, database files are not encrypted.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| | encrypt | boolean | No | Whether to encrypt the KV store. By default, KV stores are not encrypted.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core |
| backup | boolean | No | Whether to back up database files. By default, database files are backed up. <br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| | backup | boolean | No | Whether to back up database files. By default, database files are backed up. <br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core|
| autoSync | boolean | No | Whether to automatically synchronize database files. The value **false** (default) means to manually synchronize database files; the value **true** means to automatically synchronize database files.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core<br>**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC| | autoSync | boolean | No | Whether to automatically synchronize the KV store data. The value **true** means to automatically synchronize the KV store data; the value **false** (default) means the opposite.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core<br>**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC |
| kvStoreType | [KVStoreType](#kvstoretype) | No | Type of the KV store to create. By default, a device KV store is created. The device KV store stores data for multiple devices that collaborate with each other.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| | kvStoreType | [KVStoreType](#kvstoretype) | No | Type of the KV store to create. By default, a device KV store is created.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core |
| securityLevel | [SecurityLevel](#securitylevel) | Yes |Security level of the KV store.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| | securityLevel | [SecurityLevel](#securitylevel) | Yes |Security level of the KV store.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core|
| schema | [Schema](#schema) | No | Schema used to define the values stored in the KV store. By default, **schema** is not used.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore| | schema | [Schema](#schema) | No | Schema used to define the values stored in the KV store. By default, **schema** is not used.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore|
...@@ -165,7 +166,7 @@ Defines the schema of a KV store. You can create a **Schema** object and place i ...@@ -165,7 +166,7 @@ Defines the schema of a KV store. You can create a **Schema** object and place i
| Name | Type | Readable| Writable| Description | | Name | Type | Readable| Writable| Description |
| ------- | ----------------------- | ---- | ---- | -------------------------- | | ------- | ----------------------- | ---- | ---- | -------------------------- |
| root | [FieldNode](#fieldnode) | Yes | Yes | JSON root object. | | root | [FieldNode](#fieldnode) | Yes | Yes | JSON root object. |
| indexes | Array\<string> | Yes | Yes | String array in JSON format.| | indexes | Array\<string> | Yes | Yes | Array of strings in JSON format. |
| mode | number | Yes | Yes | Schema mode. | | mode | number | Yes | Yes | Schema mode. |
| skip | number | Yes | Yes | Size of a skip of the schema. | | skip | number | Yes | Yes | Size of a skip of the schema. |
...@@ -226,23 +227,22 @@ Appends a child node to this **FieldNode**. ...@@ -226,23 +227,22 @@ Appends a child node to this **FieldNode**.
**Example** **Example**
```js ```js
import ddm from '@ohos.data.distributedKVStore';
try { try {
let node = new ddm.FieldNode("root"); let node = new distributedKVStore.FieldNode("root");
let child1 = new ddm.FieldNode("child1"); let child1 = new distributedKVStore.FieldNode("child1");
let child2 = new ddm.FieldNode("child2"); let child2 = new distributedKVStore.FieldNode("child2");
let child3 = new ddm.FieldNode("child3"); let child3 = new distributedKVStore.FieldNode("child3");
node.appendChild(child1); node.appendChild(child1);
node.appendChild(child2); node.appendChild(child2);
node.appendChild(child3); node.appendChild(child3);
console.log("appendNode " + JSON.stringify(node)); console.info("appendNode " + JSON.stringify(node));
child1 = null; child1 = null;
child2 = null; child2 = null;
child3 = null; child3 = null;
node = null; node = null;
} catch (e) { } catch (e) {
console.log("AppendChild " + e); console.error("AppendChild " + e);
} }
``` ```
...@@ -250,7 +250,7 @@ try { ...@@ -250,7 +250,7 @@ try {
createKVManager(config: KVManagerConfig): KVManager createKVManager(config: KVManagerConfig): KVManager
Creates a **KVManager** instance to manage KV stores. Creates a **KVManager** instance for KV store management.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core **System capability**: SystemCapability.DistributedDataManager.KVStore.Core
...@@ -276,7 +276,7 @@ import UIAbility from '@ohos.app.ability.UIAbility'; ...@@ -276,7 +276,7 @@ import UIAbility from '@ohos.app.ability.UIAbility';
let kvManager; let kvManager;
export default class EntryAbility extends UIAbility { export default class EntryAbility extends UIAbility {
onCreate() { onCreate() {
console.log("MyAbilityStage onCreate") console.info("MyAbilityStage onCreate")
let context = this.context let context = this.context
const kvManagerConfig = { const kvManagerConfig = {
context: context, context: context,
...@@ -284,7 +284,7 @@ export default class EntryAbility extends UIAbility { ...@@ -284,7 +284,7 @@ export default class EntryAbility extends UIAbility {
} }
try { try {
kvManager = distributedKVStore.createKVManager(kvManagerConfig); kvManager = distributedKVStore.createKVManager(kvManagerConfig);
console.log("Created KVManager successfully"); console.info("Succeeded in creating KVManager");
} catch (e) { } catch (e) {
console.error(`Failed to create KVManager.code is ${e.code},message is ${e.message}`); console.error(`Failed to create KVManager.code is ${e.code},message is ${e.message}`);
} }
...@@ -304,7 +304,7 @@ const kvManagerConfig = { ...@@ -304,7 +304,7 @@ const kvManagerConfig = {
} }
try { try {
kvManager = distributedKVStore.createKVManager(kvManagerConfig); kvManager = distributedKVStore.createKVManager(kvManagerConfig);
console.log("Created KVManager successfully"); console.info("Succeeded in creating KVManager");
} catch (e) { } catch (e) {
console.error(`Failed to create KVManager.code is ${e.code},message is ${e.message}`); console.error(`Failed to create KVManager.code is ${e.code},message is ${e.message}`);
} }
...@@ -316,7 +316,7 @@ Provides an instance to obtain information about a distributed KV store. Before ...@@ -316,7 +316,7 @@ Provides an instance to obtain information about a distributed KV store. Before
### getKVStore ### getKVStore
getKVStore&lt;T &gt;(storeId: string, options: Options, callback: AsyncCallback&lt;T&gt;): void getKVStore&lt;T&gt;(storeId: string, options: Options, callback: AsyncCallback&lt;T&gt;): void
Creates and obtains a distributed KV store. This API uses an asynchronous callback to return the result. Creates and obtains a distributed KV store. This API uses an asynchronous callback to return the result.
...@@ -343,7 +343,6 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -343,7 +343,6 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
```js ```js
let kvStore; let kvStore;
let kvManager;
try { try {
const options = { const options = {
createIfMissing: true, createIfMissing: true,
...@@ -355,20 +354,20 @@ try { ...@@ -355,20 +354,20 @@ try {
}; };
kvManager.getKVStore('storeId', options, function (err, store) { kvManager.getKVStore('storeId', options, function (err, store) {
if (err) { if (err) {
console.error(`Fail to get KVStore.code is ${err.code},message is ${err.message}`); console.error(`Failed to get KVStore.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log("Succeeded in getting KVStore"); console.info("Succeeded in getting KVStore");
kvStore = store; kvStore = store;
}); });
} catch (e) { } catch (e) {
console.log(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
} }
``` ```
### getKVStore ### getKVStore
getKVStore&lt;T &gt;(storeId: string, options: Options): Promise&lt;T&gt; getKVStore&lt;T&gt;(storeId: string, options: Options): Promise&lt;T&gt;
Creates and obtains a distributed KV store. This API uses a promise to return the result. Creates and obtains a distributed KV store. This API uses a promise to return the result.
...@@ -400,7 +399,6 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -400,7 +399,6 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
```js ```js
let kvStore; let kvStore;
let kvManager;
try { try {
const options = { const options = {
createIfMissing: true, createIfMissing: true,
...@@ -411,13 +409,13 @@ try { ...@@ -411,13 +409,13 @@ try {
securityLevel: distributedKVStore.SecurityLevel.S2, securityLevel: distributedKVStore.SecurityLevel.S2,
}; };
kvManager.getKVStore('storeId', options).then((store) => { kvManager.getKVStore('storeId', options).then((store) => {
console.log("Succeeded in getting KVStore"); console.info("Succeeded in getting KVStore");
kvStore = store; kvStore = store;
}).catch((err) => { }).catch((err) => {
console.error(`Fail to get KVStore.code is ${err.code},message is ${err.message}`); console.error(`Failed to get KVStore.code is ${err.code},message is ${err.message}`);
}); });
} catch (e) { } catch (e) {
console.log(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
} }
``` ```
...@@ -440,8 +438,6 @@ Closes a distributed KV store. This API uses an asynchronous callback to return ...@@ -440,8 +438,6 @@ Closes a distributed KV store. This API uses an asynchronous callback to return
**Example** **Example**
```js ```js
let kvStore;
let kvManager;
const options = { const options = {
createIfMissing: true, createIfMissing: true,
encrypt: false, encrypt: false,
...@@ -453,14 +449,20 @@ const options = { ...@@ -453,14 +449,20 @@ const options = {
} }
try { try {
kvManager.getKVStore('storeId', options, async function (err, store) { kvManager.getKVStore('storeId', options, async function (err, store) {
console.log('Succeeded in getting KVStore'); if (err != undefined) {
console.error(`Failed to get KVStore.code is ${err.code},message is ${err.message}`);
return;
}
console.info('Succeeded in getting KVStore');
kvStore = store; kvStore = store;
kvStore = null;
store = null;
kvManager.closeKVStore('appId', 'storeId', function (err, data) { kvManager.closeKVStore('appId', 'storeId', function (err, data) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to close KVStore.code is ${err.code},message is ${err.message}`); console.error(`Failed to close KVStore.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Succeeded in closing KVStore'); console.info('Succeeded in closing KVStore');
}); });
}); });
} catch (e) { } catch (e) {
...@@ -492,8 +494,6 @@ Closes a distributed KV store. This API uses a promise to return the result. ...@@ -492,8 +494,6 @@ Closes a distributed KV store. This API uses a promise to return the result.
**Example** **Example**
```js ```js
let kvManager;
let kvStore;
const options = { const options = {
createIfMissing: true, createIfMissing: true,
encrypt: false, encrypt: false,
...@@ -505,18 +505,20 @@ const options = { ...@@ -505,18 +505,20 @@ const options = {
} }
try { try {
kvManager.getKVStore('storeId', options).then(async (store) => { kvManager.getKVStore('storeId', options).then(async (store) => {
console.log('Succeeded in getting KVStore'); console.info('Succeeded in getting KVStore');
kvStore = store; kvStore = store;
kvStore = null;
store = null;
kvManager.closeKVStore('appId', 'storeId').then(() => { kvManager.closeKVStore('appId', 'storeId').then(() => {
console.log('Succeeded in closing KVStore'); console.info('Succeeded in closing KVStore');
}).catch((err) => { }).catch((err) => {
console.error(`Fail to close KVStore.code is ${err.code},message is ${err.message}`); console.error(`Failed to close KVStore.code is ${err.code},message is ${err.message}`);
}); });
}).catch((err) => { }).catch((err) => {
console.error(`Fail to get KVStore.code is ${err.code},message is ${err.message}`); console.error(`Failed to get KVStore.code is ${err.code},message is ${err.message}`);
}); });
} catch (e) { } catch (e) {
console.error(`Fail to close KVStore.code is ${e.code},message is ${e.message}`); console.error(`Failed to close KVStore.code is ${e.code},message is ${e.message}`);
} }
``` ```
...@@ -547,8 +549,6 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -547,8 +549,6 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
**Example** **Example**
```js ```js
let kvManager;
let kvStore;
const options = { const options = {
createIfMissing: true, createIfMissing: true,
encrypt: false, encrypt: false,
...@@ -561,21 +561,23 @@ const options = { ...@@ -561,21 +561,23 @@ const options = {
try { try {
kvManager.getKVStore('store', options, async function (err, store) { kvManager.getKVStore('store', options, async function (err, store) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to get KVStore.code is ${err.code},message is ${err.message}`); console.error(`Failed to get KVStore.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Succeeded in getting KVStore'); console.info('Succeeded in getting KVStore');
kvStore = store; kvStore = store;
kvStore = null;
store = null;
kvManager.deleteKVStore('appId', 'storeId', function (err, data) { kvManager.deleteKVStore('appId', 'storeId', function (err, data) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to delete KVStore.code is ${err.code},message is ${err.message}`); console.error(`Failed to delete KVStore.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log(`Succeeded in deleting KVStore`); console.info(`Succeeded in deleting KVStore`);
}); });
}); });
} catch (e) { } catch (e) {
console.error(`Fail to delete KVStore.code is ${e.code},message is ${e.message}`); console.error(`Failed to delete KVStore.code is ${e.code},message is ${e.message}`);
} }
``` ```
...@@ -611,8 +613,6 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -611,8 +613,6 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
**Example** **Example**
```js ```js
let kvManager;
let kvStore;
const options = { const options = {
createIfMissing: true, createIfMissing: true,
encrypt: false, encrypt: false,
...@@ -624,18 +624,20 @@ const options = { ...@@ -624,18 +624,20 @@ const options = {
} }
try { try {
kvManager.getKVStore('storeId', options).then(async (store) => { kvManager.getKVStore('storeId', options).then(async (store) => {
console.log('Succeeded in getting KVStore'); console.info('Succeeded in getting KVStore');
kvStore = store; kvStore = store;
kvStore = null;
store = null;
kvManager.deleteKVStore('appId', 'storeId').then(() => { kvManager.deleteKVStore('appId', 'storeId').then(() => {
console.log('Succeeded in deleting KVStore'); console.info('Succeeded in deleting KVStore');
}).catch((err) => { }).catch((err) => {
console.error(`Fail to delete KVStore.code is ${err.code},message is ${err.message}`); console.error(`Failed to delete KVStore.code is ${err.code},message is ${err.message}`);
}); });
}).catch((err) => { }).catch((err) => {
console.error(`Fail to get KVStore.code is ${err.code},message is ${err.message}`); console.error(`Failed to get KVStore.code is ${err.code},message is ${err.message}`);
}); });
} catch (e) { } catch (e) {
console.error(`Fail to delete KVStore.code is ${e.code},message is ${e.message}`); console.error(`Failed to delete KVStore.code is ${e.code},message is ${e.message}`);
} }
``` ```
...@@ -643,7 +645,7 @@ try { ...@@ -643,7 +645,7 @@ try {
getAllKVStoreId(appId: string, callback: AsyncCallback&lt;string[]&gt;): void getAllKVStoreId(appId: string, callback: AsyncCallback&lt;string[]&gt;): void
Obtains the IDs of all distributed KV stores that are created by [getKVStore](#getkvstore) and have not been deleted by [deleteKVStore](#deletekvstore). This API uses an asynchronous callback to return the result. Obtains IDs of all distributed KV stores that are created by [getKVStore](#getkvstore) and have not been deleted by [deleteKVStore](#deletekvstore). This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core **System capability**: SystemCapability.DistributedDataManager.KVStore.Core
...@@ -657,18 +659,17 @@ Obtains the IDs of all distributed KV stores that are created by [getKVStore](#g ...@@ -657,18 +659,17 @@ Obtains the IDs of all distributed KV stores that are created by [getKVStore](#g
**Example** **Example**
```js ```js
let kvManager;
try { try {
kvManager.getAllKVStoreId('appId', function (err, data) { kvManager.getAllKVStoreId('appId', function (err, data) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to get AllKVStoreId.code is ${err.code},message is ${err.message}`); console.error(`Failed to get AllKVStoreId.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Succeeded in getting AllKVStoreId'); console.info('Succeeded in getting AllKVStoreId');
console.log(`GetAllKVStoreId size = ${data.length}`); console.info(`GetAllKVStoreId size = ${data.length}`);
}); });
} catch (e) { } catch (e) {
console.error(`Fail to get AllKVStoreId.code is ${e.code},message is ${e.message}`); console.error(`Failed to get AllKVStoreId.code is ${e.code},message is ${e.message}`);
} }
``` ```
...@@ -676,7 +677,7 @@ try { ...@@ -676,7 +677,7 @@ try {
getAllKVStoreId(appId: string): Promise&lt;string[]&gt; getAllKVStoreId(appId: string): Promise&lt;string[]&gt;
Obtains the IDs of all distributed KV stores that are created by [getKVStore](#getkvstore) and have not been deleted by [deleteKVStore](#deletekvstore). This API uses a promise to return the result. Obtains IDs of all distributed KV stores that are created by [getKVStore](#getkvstore) and have not been deleted by [deleteKVStore](#deletekvstore). This API uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core **System capability**: SystemCapability.DistributedDataManager.KVStore.Core
...@@ -690,22 +691,21 @@ Obtains the IDs of all distributed KV stores that are created by [getKVStore](#g ...@@ -690,22 +691,21 @@ Obtains the IDs of all distributed KV stores that are created by [getKVStore](#g
| Type | Description | | Type | Description |
| ----------------------- | ------------------------------------------------------ | | ----------------------- | ------------------------------------------------------ |
| Promise&lt;string[]&gt; | Promise used to return the IDs of all the distributed KV stores created. | | Promise&lt;string[]&gt; | Promise used to return IDs of all the distributed KV stores created. |
**Example** **Example**
```js ```js
let kvManager;
try { try {
console.log('GetAllKVStoreId'); console.info('GetAllKVStoreId');
kvManager.getAllKVStoreId('appId').then((data) => { kvManager.getAllKVStoreId('appId').then((data) => {
console.log('Succeeded in getting AllKVStoreId'); console.info('Succeeded in getting AllKVStoreId');
console.log(`GetAllKVStoreId size = ${data.length}`); console.info(`GetAllKVStoreId size = ${data.length}`);
}).catch((err) => { }).catch((err) => {
console.error(`Fail to get AllKVStoreId.code is ${err.code},message is ${err.message}`); console.error(`Failed to get AllKVStoreId.code is ${err.code},message is ${err.message}`);
}); });
} catch (e) { } catch (e) {
console.error(`Fail to get AllKVStoreId.code is ${e.code},message is ${e.message}`); console.error(`Failed to get AllKVStoreId.code is ${e.code},message is ${e.message}`);
} }
``` ```
...@@ -713,7 +713,7 @@ try { ...@@ -713,7 +713,7 @@ try {
on(event: 'distributedDataServiceDie', deathCallback: Callback&lt;void&gt;): void on(event: 'distributedDataServiceDie', deathCallback: Callback&lt;void&gt;): void
Subscribes to service status changes. Subscribes to service status changes. If a service is terminated, you need to register the callbacks for data change notifications and synchronization complete notifications again. In addition, an error will be returned for a synchronization operation.
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
...@@ -727,15 +727,14 @@ Subscribes to service status changes. ...@@ -727,15 +727,14 @@ Subscribes to service status changes.
**Example** **Example**
```js ```js
let kvManager;
try { try {
console.log('KVManagerOn'); console.info('KVManagerOn');
const deathCallback = function () { const deathCallback = function () {
console.log('death callback call'); console.info('death callback call');
} }
kvManager.on('distributedDataServiceDie', deathCallback); kvManager.on('distributedDataServiceDie', deathCallback);
} catch (e) { } catch (e) {
console.log(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
} }
``` ```
...@@ -743,7 +742,7 @@ try { ...@@ -743,7 +742,7 @@ try {
off(event: 'distributedDataServiceDie', deathCallback?: Callback&lt;void&gt;): void off(event: 'distributedDataServiceDie', deathCallback?: Callback&lt;void&gt;): void
Unsubscribes from service status changes. Unsubscribes from service status changes. The **deathCallback** parameter must be a callback registered for subscribing to service status changes. Otherwise, the unsubscription will fail.
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
...@@ -752,26 +751,25 @@ Unsubscribes from service status changes. ...@@ -752,26 +751,25 @@ Unsubscribes from service status changes.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------------- | -------------------- | ---- | ------------------------------------------------------------ | | ------------- | -------------------- | ---- | ------------------------------------------------------------ |
| event | string | Yes | Event to unsubscribe from. The value is **distributedDataServiceDie**, which indicates a service status change event.| | event | string | Yes | Event to unsubscribe from. The value is **distributedDataServiceDie**, which indicates a service status change event.|
| deathCallback | Callback&lt;void&gt; | No | Callback for the service status change event. | | deathCallback | Callback&lt;void&gt; | No | Callback for the service status change event. If this parameter is not specified, all deathCallback subscriptions will be canceled. |
**Example** **Example**
```js ```js
let kvManager;
try { try {
console.log('KVManagerOff'); console.info('KVManagerOff');
const deathCallback = function () { const deathCallback = function () {
console.log('death callback call'); console.info('death callback call');
} }
kvManager.off('distributedDataServiceDie', deathCallback); kvManager.off('distributedDataServiceDie', deathCallback);
} catch (e) { } catch (e) {
console.log(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
} }
``` ```
## KVStoreResultSet ## KVStoreResultSet
Provides APIs for obtaining the distributed KV store result sets. Provides APIs for obtaining the distributed KV store result sets. A maximum of eight result sets can be opened at a time.
Before calling any API in **KVStoreResultSet**, you must use **[getKVStore](#getkvstore)** to construct a **SingleKVStore** or **DeviceKVStore** instance. Before calling any API in **KVStoreResultSet**, you must use **[getKVStore](#getkvstore)** to construct a **SingleKVStore** or **DeviceKVStore** instance.
...@@ -792,19 +790,19 @@ Obtains the total number of rows in the result set. ...@@ -792,19 +790,19 @@ Obtains the total number of rows in the result set.
**Example** **Example**
```js ```js
let kvStore;
try { try {
let resultSet; let resultSet;
let count;
kvStore.getResultSet('batch_test_string_key').then((result) => { kvStore.getResultSet('batch_test_string_key').then((result) => {
console.log('getResultSet succeed.'); console.info('getResultSet succeed.');
resultSet = result; resultSet = result;
count = resultSet.getCount();
console.info("getCount succeed:" + count);
}).catch((err) => { }).catch((err) => {
console.log('getResultSet failed: ' + err); console.error('getResultSet failed: ' + err);
}); });
const count = resultSet.getCount();
console.log("getCount succeed:" + count);
} catch (e) { } catch (e) {
console.log("getCount failed: " + e); console.error("getCount failed: " + e);
} }
``` ```
...@@ -812,7 +810,7 @@ try { ...@@ -812,7 +810,7 @@ try {
getPosition(): number getPosition(): number
Obtains the current data read position (position from which data is read) in the result set. Obtains the current data read position (position from which data is read) in the result set. The read position changes with the operations, such as [moveToFirst](#movetofirst) and [moveToLast](#movetolast).
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core **System capability**: SystemCapability.DistributedDataManager.KVStore.Core
...@@ -820,24 +818,24 @@ Obtains the current data read position (position from which data is read) in the ...@@ -820,24 +818,24 @@ Obtains the current data read position (position from which data is read) in the
| Type | Description | | Type | Description |
| ------ | ------------------ | | ------ | ------------------ |
| number | Current data read position obtained.| | number | Current data read position obtained. The value must be greater than or equal to **-1**. The value **-1** means no data is read; the value **0** indicates the first row.|
**Example** **Example**
```js ```js
let kvStore;
try { try {
let resultSet; let resultSet;
let position;
kvStore.getResultSet('batch_test_string_key').then((result) => { kvStore.getResultSet('batch_test_string_key').then((result) => {
console.log('getResultSet succeeded.'); console.info('getResultSet succeeded.');
resultSet = result; resultSet = result;
position = resultSet.getPosition();
console.info("getPosition succeed:" + position);
}).catch((err) => { }).catch((err) => {
console.log('getResultSet failed: ' + err); console.error('getResultSet failed: ' + err);
}); });
const position = resultSet.getPosition();
console.log("getPosition succeed:" + position);
} catch (e) { } catch (e) {
console.log("getPosition failed: " + e); console.error("getPosition failed: " + e);
} }
``` ```
...@@ -858,19 +856,19 @@ Moves the data read position to the first row. If the result set is empty, **fal ...@@ -858,19 +856,19 @@ Moves the data read position to the first row. If the result set is empty, **fal
**Example** **Example**
```js ```js
let kvStore;
try { try {
let resultSet; let resultSet;
let moved;
kvStore.getResultSet('batch_test_string_key').then((result) => { kvStore.getResultSet('batch_test_string_key').then((result) => {
console.log('getResultSet succeed.'); console.info('getResultSet succeed.');
resultSet = result; resultSet = result;
moved = resultSet.moveToFirst();
console.info("moveToFirst succeed: " + moved);
}).catch((err) => { }).catch((err) => {
console.log('getResultSet failed: ' + err); console.error('getResultSet failed: ' + err);
}); });
const moved1 = resultSet.moveToFirst();
console.log("moveToFirst succeed: " + moved1);
} catch (e) { } catch (e) {
console.log("moveToFirst failed " + e); console.error("moveToFirst failed " + e);
} }
``` ```
...@@ -891,19 +889,19 @@ Moves the data read position to the last row. If the result set is empty, **fals ...@@ -891,19 +889,19 @@ Moves the data read position to the last row. If the result set is empty, **fals
**Example** **Example**
```js ```js
let kvStore;
try { try {
let resultSet; let resultSet;
let moved;
kvStore.getResultSet('batch_test_string_key').then((result) => { kvStore.getResultSet('batch_test_string_key').then((result) => {
console.log('getResultSet succeed.'); console.info('getResultSet succeed.');
resultSet = result; resultSet = result;
moved = resultSet.moveToLast();
console.info("moveToLast succeed:" + moved);
}).catch((err) => { }).catch((err) => {
console.log('getResultSet failed: ' + err); console.error('getResultSet failed: ' + err);
}); });
const moved2 = resultSet.moveToLast();
console.log("moveToLast succeed:" + moved2);
} catch (e) { } catch (e) {
console.log("moveToLast failed: " + e); console.error("moveToLast failed: " + e);
} }
``` ```
...@@ -911,7 +909,7 @@ try { ...@@ -911,7 +909,7 @@ try {
moveToNext(): boolean moveToNext(): boolean
Moves the data read position to the next row. If the result set is empty, **false** will be returned. Moves the data read position to the next row. If the result set is empty, **false** will be returned. This API applies when the whole result set is obtained.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core **System capability**: SystemCapability.DistributedDataManager.KVStore.Core
...@@ -924,19 +922,22 @@ Moves the data read position to the next row. If the result set is empty, **fals ...@@ -924,19 +922,22 @@ Moves the data read position to the next row. If the result set is empty, **fals
**Example** **Example**
```js ```js
let kvStore;
try { try {
let resultSet; let resultSet;
let moved;
kvStore.getResultSet('batch_test_string_key').then((result) => { kvStore.getResultSet('batch_test_string_key').then((result) => {
console.log('getResultSet succeed.'); console.info('getResultSet succeed.');
resultSet = result; resultSet = result;
do {
moved = resultSet.moveToNext();
const entry = resultSet.getEntry();
console.info("moveToNext succeed: " + moved);
} while (moved)
}).catch((err) => { }).catch((err) => {
console.log('getResultSet failed: ' + err); console.error('getResultSet failed: ' + err);
}); });
const moved3 = resultSet.moveToNext();
console.log("moveToNext succeed: " + moved3);
} catch (e) { } catch (e) {
console.log("moveToNext failed: " + e); console.error("moveToNext failed: " + e);
} }
``` ```
...@@ -944,7 +945,7 @@ try { ...@@ -944,7 +945,7 @@ try {
moveToPrevious(): boolean moveToPrevious(): boolean
Moves the data read position to the previous row. If the result set is empty, **false** will be returned. Moves the data read position to the previous row. If the result set is empty, **false** will be returned. This API applies when the whole result set is obtained.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core **System capability**: SystemCapability.DistributedDataManager.KVStore.Core
...@@ -957,19 +958,20 @@ Moves the data read position to the previous row. If the result set is empty, ** ...@@ -957,19 +958,20 @@ Moves the data read position to the previous row. If the result set is empty, **
**Example** **Example**
```js ```js
let kvStore;
try { try {
let resultSet; let resultSet;
let moved;
kvStore.getResultSet('batch_test_string_key').then((result) => { kvStore.getResultSet('batch_test_string_key').then((result) => {
console.log('getResultSet succeed.'); console.info('getResultSet succeed.');
resultSet = result; resultSet = result;
moved = resultSet.moveToLast();
moved = resultSet.moveToPrevious();
console.info("moveToPrevious succeed:" + moved);
}).catch((err) => { }).catch((err) => {
console.log('getResultSet failed: ' + err); console.error('getResultSet failed: ' + err);
}); });
const moved4 = resultSet.moveToPrevious();
console.log("moveToPrevious succeed:" + moved4);
} catch (e) { } catch (e) {
console.log("moveToPrevious failed: " + e); console.error("moveToPrevious failed: " + e);
} }
``` ```
...@@ -977,7 +979,7 @@ try { ...@@ -977,7 +979,7 @@ try {
move(offset: number): boolean move(offset: number): boolean
Moves the data read position with the specified offset from the current position. Moves the data read position with the specified offset from the current position. That is, move the number of rows specified by **offset** from the current position.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core **System capability**: SystemCapability.DistributedDataManager.KVStore.Core
...@@ -996,19 +998,19 @@ Moves the data read position with the specified offset from the current position ...@@ -996,19 +998,19 @@ Moves the data read position with the specified offset from the current position
**Example** **Example**
```js ```js
let kvStore;
try { try {
let resultSet; let resultSet;
let moved;
kvStore.getResultSet('batch_test_string_key').then((result) => { kvStore.getResultSet('batch_test_string_key').then((result) => {
console.log('Succeeded in getting resultSet'); console.info('Succeeded in getting resultSet');
resultSet = result; resultSet = result;
moved = resultSet.move(2); // If the current position is 0, move the read position forward by two rows, that is, move to row 3.
console.info(`Succeeded in moving.moved = ${moved}`);
}).catch((err) => { }).catch((err) => {
console.error(`Fail to get resultSet.code is ${err.code},message is ${err.message}`); console.error(`Failed to get resultSet.code is ${err.code},message is ${err.message}`);
}); });
const moved5 = resultSet.move(1);
console.log(`Succeeded in moving.moved5 = ${moved5}`);
} catch (e) { } catch (e) {
console.log(`Fail to move.code is ${e.code},message is ${e.message}`); console.error(`Failed to move.code is ${e.code},message is ${e.message}`);
} }
``` ```
...@@ -1035,19 +1037,19 @@ Moves the data read position from 0 to an absolute position. ...@@ -1035,19 +1037,19 @@ Moves the data read position from 0 to an absolute position.
**Example** **Example**
```js ```js
let kvStore;
try { try {
let resultSet; let resultSet;
let moved;
kvStore.getResultSet('batch_test_string_key').then((result) => { kvStore.getResultSet('batch_test_string_key').then((result) => {
console.log('Succeeded in getting resultSet'); console.info('Succeeded in getting resultSet');
resultSet = result; resultSet = result;
moved = resultSet.moveToPosition(1);
console.info(`Succeeded in moving to position.moved=${moved}`);
}).catch((err) => { }).catch((err) => {
console.error(`Fail to get resultSet.code is ${err.code},message is ${err.message}`); console.error(`Failed to get resultSet.code is ${err.code},message is ${err.message}`);
}); });
const moved6 = resultSet.moveToPosition(1);
console.log(`Succeeded in moving to position.moved6=${moved6}`);
} catch (e) { } catch (e) {
console.error(`Fail to move to position.code is ${e.code},message is ${e.message}`); console.error(`Failed to move to position.code is ${e.code},message is ${e.message}`);
} }
``` ```
...@@ -1068,19 +1070,19 @@ Checks whether the data read position is the first row. ...@@ -1068,19 +1070,19 @@ Checks whether the data read position is the first row.
**Example** **Example**
```js ```js
let kvStore;
try { try {
let resultSet; let resultSet;
let isfirst;
kvStore.getResultSet('batch_test_string_key').then((result) => { kvStore.getResultSet('batch_test_string_key').then((result) => {
console.log('getResultSet succeed.'); console.info('getResultSet succeed.');
resultSet = result; resultSet = result;
isfirst = resultSet.isFirst();
console.info("Check isFirst succeed:" + isfirst);
}).catch((err) => { }).catch((err) => {
console.log('getResultSet failed: ' + err); console.error('getResultSet failed: ' + err);
}); });
const isfirst = resultSet.isFirst();
console.log("Check isFirst succeed:" + isfirst);
} catch (e) { } catch (e) {
console.log("Check isFirst failed: " + e); console.error("Check isFirst failed: " + e);
} }
``` ```
...@@ -1101,19 +1103,19 @@ Checks whether the data read position is the last row. ...@@ -1101,19 +1103,19 @@ Checks whether the data read position is the last row.
**Example** **Example**
```js ```js
let kvStore;
try { try {
let resultSet; let resultSet;
let islast;
kvStore.getResultSet('batch_test_string_key').then((result) => { kvStore.getResultSet('batch_test_string_key').then((result) => {
console.log('getResultSet succeed.'); console.info('getResultSet succeed.');
resultSet = result; resultSet = result;
islast = resultSet.isLast();
console.info("Check isLast succeed: " + islast);
}).catch((err) => { }).catch((err) => {
console.log('getResultSet failed: ' + err); console.error('getResultSet failed: ' + err);
}); });
const islast = resultSet.isLast();
console.log("Check isLast succeed: " + islast);
} catch (e) { } catch (e) {
console.log("Check isLast failed: " + e); console.error("Check isLast failed: " + e);
} }
``` ```
...@@ -1134,19 +1136,18 @@ Checks whether the data read position is before the first row. ...@@ -1134,19 +1136,18 @@ Checks whether the data read position is before the first row.
**Example** **Example**
```js ```js
let kvStore;
try { try {
let resultSet; let resultSet;
kvStore.getResultSet('batch_test_string_key').then((result) => { kvStore.getResultSet('batch_test_string_key').then((result) => {
console.log('getResultSet succeed.'); console.info('getResultSet succeed.');
resultSet = result; resultSet = result;
const isbeforefirst = resultSet.isBeforeFirst();
console.info("Check isBeforeFirst succeed: " + isbeforefirst);
}).catch((err) => { }).catch((err) => {
console.log('getResultSet failed: ' + err); console.error('getResultSet failed: ' + err);
}); });
const isbeforefirst = resultSet.isBeforeFirst();
console.log("Check isBeforeFirst succeed: " + isbeforefirst);
} catch (e) { } catch (e) {
console.log("Check isBeforeFirst failed: " + e); console.error("Check isBeforeFirst failed: " + e);
} }
``` ```
...@@ -1167,19 +1168,18 @@ Checks whether the data read position is after the last row. ...@@ -1167,19 +1168,18 @@ Checks whether the data read position is after the last row.
**Example** **Example**
```js ```js
let kvStore;
try { try {
let resultSet; let resultSet;
kvStore.getResultSet('batch_test_string_key').then((result) => { kvStore.getResultSet('batch_test_string_key').then((result) => {
console.log('getResultSet succeed.'); console.info('getResultSet succeed.');
resultSet = result; resultSet = result;
const isafterlast = resultSet.isAfterLast();
console.info("Check isAfterLast succeed:" + isafterlast);
}).catch((err) => { }).catch((err) => {
console.log('getResultSet failed: ' + err); console.error('getResultSet failed: ' + err);
}); });
const isafterlast = resultSet.isAfterLast();
console.log("Check isAfterLast succeed:" + isafterlast);
} catch (e) { } catch (e) {
console.log("Check isAfterLast failed: " + e); console.error("Check isAfterLast failed: " + e);
} }
``` ```
...@@ -1200,25 +1200,24 @@ Obtains the KV pair from the current position. ...@@ -1200,25 +1200,24 @@ Obtains the KV pair from the current position.
**Example** **Example**
```js ```js
let kvStore;
try { try {
let resultSet; let resultSet;
kvStore.getResultSet('batch_test_string_key').then((result) => { kvStore.getResultSet('batch_test_string_key').then((result) => {
console.log('getResultSet succeed.'); console.info('getResultSet succeed.');
resultSet = result; resultSet = result;
const entry = resultSet.getEntry();
console.info("getEntry succeed:" + JSON.stringify(entry));
}).catch((err) => { }).catch((err) => {
console.log('getResultSet failed: ' + err); console.error('getResultSet failed: ' + err);
}); });
const entry = resultSet.getEntry();
console.log("getEntry succeed:" + JSON.stringify(entry));
} catch (e) { } catch (e) {
console.log("getEntry failed: " + e); console.error("getEntry failed: " + e);
} }
``` ```
## Query ## Query
Provides methods to create a **Query** object, which defines different data query criteria. Provides methods to create a **Query** object, which defines different data query criteria. A **Query** object supports a maximum of 256 predicates.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core **System capability**: SystemCapability.DistributedDataManager.KVStore.Core
...@@ -1250,12 +1249,12 @@ Resets the **Query** object. ...@@ -1250,12 +1249,12 @@ Resets the **Query** object.
try { try {
let query = new distributedKVStore.Query(); let query = new distributedKVStore.Query();
query.equalTo("key", "value"); query.equalTo("key", "value");
console.log("query is " + query.getSqlLike()); console.info("query is " + query.getSqlLike());
query.reset(); query.reset();
console.log("query is " + query.getSqlLike()); console.info("query is " + query.getSqlLike());
query = null; query = null;
} catch (e) { } catch (e) {
console.log("simply calls should be ok :" + e); console.error("simply calls should be ok :" + e);
} }
``` ```
...@@ -1286,7 +1285,7 @@ Creates a **Query** object to match the specified field whose value is equal to ...@@ -1286,7 +1285,7 @@ Creates a **Query** object to match the specified field whose value is equal to
try { try {
let query = new distributedKVStore.Query(); let query = new distributedKVStore.Query();
query.equalTo("field", "value"); query.equalTo("field", "value");
console.log(`query is ${query.getSqlLike()}`); console.info(`query is ${query.getSqlLike()}`);
query = null; query = null;
} catch (e) { } catch (e) {
console.error(`duplicated calls should be ok.ode is ${e.code},message is ${e.message}`); console.error(`duplicated calls should be ok.ode is ${e.code},message is ${e.message}`);
...@@ -1320,7 +1319,7 @@ Creates a **Query** object to match the specified field whose value is not equal ...@@ -1320,7 +1319,7 @@ Creates a **Query** object to match the specified field whose value is not equal
try { try {
let query = new distributedKVStore.Query(); let query = new distributedKVStore.Query();
query.notEqualTo("field", "value"); query.notEqualTo("field", "value");
console.log(`query is ${query.getSqlLike()}`); console.info(`query is ${query.getSqlLike()}`);
query = null; query = null;
} catch (e) { } catch (e) {
console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`);
...@@ -1353,7 +1352,7 @@ Creates a **Query** object to match the specified field whose value is greater t ...@@ -1353,7 +1352,7 @@ Creates a **Query** object to match the specified field whose value is greater t
try { try {
let query = new distributedKVStore.Query(); let query = new distributedKVStore.Query();
query.greaterThan("field", "value"); query.greaterThan("field", "value");
console.log(`query is ${query.getSqlLike()}`); console.info(`query is ${query.getSqlLike()}`);
query = null; query = null;
} catch (e) { } catch (e) {
console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`);
...@@ -1388,7 +1387,7 @@ Creates a **Query** object to match the specified field whose value is less than ...@@ -1388,7 +1387,7 @@ Creates a **Query** object to match the specified field whose value is less than
try { try {
let query = new distributedKVStore.Query(); let query = new distributedKVStore.Query();
query.lessThan("field", "value"); query.lessThan("field", "value");
console.log(`query is ${query.getSqlLike()}`); console.info(`query is ${query.getSqlLike()}`);
query = null; query = null;
} catch (e) { } catch (e) {
console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`);
...@@ -1423,7 +1422,7 @@ Creates a **Query** object to match the specified field whose value is greater t ...@@ -1423,7 +1422,7 @@ Creates a **Query** object to match the specified field whose value is greater t
try { try {
let query = new distributedKVStore.Query(); let query = new distributedKVStore.Query();
query.greaterThanOrEqualTo("field", "value"); query.greaterThanOrEqualTo("field", "value");
console.log(`query is ${query.getSqlLike()}`); console.info(`query is ${query.getSqlLike()}`);
query = null; query = null;
} catch (e) { } catch (e) {
console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`);
...@@ -1458,7 +1457,7 @@ Creates a **Query** object to match the specified field whose value is less than ...@@ -1458,7 +1457,7 @@ Creates a **Query** object to match the specified field whose value is less than
try { try {
let query = new distributedKVStore.Query(); let query = new distributedKVStore.Query();
query.lessThanOrEqualTo("field", "value"); query.lessThanOrEqualTo("field", "value");
console.log(`query is ${query.getSqlLike()}`); console.info(`query is ${query.getSqlLike()}`);
query = null; query = null;
} catch (e) { } catch (e) {
console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`);
...@@ -1491,7 +1490,7 @@ Creates a **Query** object to match the specified field whose value is **null**. ...@@ -1491,7 +1490,7 @@ Creates a **Query** object to match the specified field whose value is **null**.
try { try {
let query = new distributedKVStore.Query(); let query = new distributedKVStore.Query();
query.isNull("field"); query.isNull("field");
console.log(`query is ${query.getSqlLike()}`); console.info(`query is ${query.getSqlLike()}`);
query = null; query = null;
} catch (e) { } catch (e) {
console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`);
...@@ -1525,7 +1524,7 @@ Creates a **Query** object to match the specified field whose value is within th ...@@ -1525,7 +1524,7 @@ Creates a **Query** object to match the specified field whose value is within th
try { try {
let query = new distributedKVStore.Query(); let query = new distributedKVStore.Query();
query.inNumber("field", [0, 1]); query.inNumber("field", [0, 1]);
console.log(`query is ${query.getSqlLike()}`); console.info(`query is ${query.getSqlLike()}`);
query = null; query = null;
} catch (e) { } catch (e) {
console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`);
...@@ -1559,7 +1558,7 @@ Creates a **Query** object to match the specified field whose value is within th ...@@ -1559,7 +1558,7 @@ Creates a **Query** object to match the specified field whose value is within th
try { try {
let query = new distributedKVStore.Query(); let query = new distributedKVStore.Query();
query.inString("field", ['test1', 'test2']); query.inString("field", ['test1', 'test2']);
console.log(`query is ${query.getSqlLike()}`); console.info(`query is ${query.getSqlLike()}`);
query = null; query = null;
} catch (e) { } catch (e) {
console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`);
...@@ -1593,7 +1592,7 @@ Creates a **Query** object to match the specified field whose value is not withi ...@@ -1593,7 +1592,7 @@ Creates a **Query** object to match the specified field whose value is not withi
try { try {
let query = new distributedKVStore.Query(); let query = new distributedKVStore.Query();
query.notInNumber("field", [0, 1]); query.notInNumber("field", [0, 1]);
console.log(`query is ${query.getSqlLike()}`); console.info(`query is ${query.getSqlLike()}`);
query = null; query = null;
} catch (e) { } catch (e) {
console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`);
...@@ -1627,7 +1626,7 @@ Creates a **Query** object to match the specified field whose value is not withi ...@@ -1627,7 +1626,7 @@ Creates a **Query** object to match the specified field whose value is not withi
try { try {
let query = new distributedKVStore.Query(); let query = new distributedKVStore.Query();
query.notInString("field", ['test1', 'test2']); query.notInString("field", ['test1', 'test2']);
console.log(`query is ${query.getSqlLike()}`); console.info(`query is ${query.getSqlLike()}`);
query = null; query = null;
} catch (e) { } catch (e) {
console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`);
...@@ -1661,7 +1660,7 @@ Creates a **Query** object to match the specified field whose value is similar t ...@@ -1661,7 +1660,7 @@ Creates a **Query** object to match the specified field whose value is similar t
try { try {
let query = new distributedKVStore.Query(); let query = new distributedKVStore.Query();
query.like("field", "value"); query.like("field", "value");
console.log(`query is ${query.getSqlLike()}`); console.info(`query is ${query.getSqlLike()}`);
query = null; query = null;
} catch (e) { } catch (e) {
console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`);
...@@ -1695,7 +1694,7 @@ Creates a **Query** object to match the specified field whose value is not simil ...@@ -1695,7 +1694,7 @@ Creates a **Query** object to match the specified field whose value is not simil
try { try {
let query = new distributedKVStore.Query(); let query = new distributedKVStore.Query();
query.unlike("field", "value"); query.unlike("field", "value");
console.log(`query is ${query.getSqlLike()}`); console.info(`query is ${query.getSqlLike()}`);
query = null; query = null;
} catch (e) { } catch (e) {
console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`);
...@@ -1724,10 +1723,10 @@ try { ...@@ -1724,10 +1723,10 @@ try {
query.notEqualTo("field", "value1"); query.notEqualTo("field", "value1");
query.and(); query.and();
query.notEqualTo("field", "value2"); query.notEqualTo("field", "value2");
console.log("query is " + query.getSqlLike()); console.info("query is " + query.getSqlLike());
query = null; query = null;
} catch (e) { } catch (e) {
console.log("duplicated calls should be ok :" + e); console.error("duplicated calls should be ok :" + e);
} }
``` ```
...@@ -1753,10 +1752,10 @@ try { ...@@ -1753,10 +1752,10 @@ try {
query.notEqualTo("field", "value1"); query.notEqualTo("field", "value1");
query.or(); query.or();
query.notEqualTo("field", "value2"); query.notEqualTo("field", "value2");
console.log("query is " + query.getSqlLike()); console.info("query is " + query.getSqlLike());
query = null; query = null;
} catch (e) { } catch (e) {
console.log("duplicated calls should be ok :" + e); console.error("duplicated calls should be ok :" + e);
} }
``` ```
...@@ -1787,7 +1786,7 @@ try { ...@@ -1787,7 +1786,7 @@ try {
let query = new distributedKVStore.Query(); let query = new distributedKVStore.Query();
query.notEqualTo("field", "value"); query.notEqualTo("field", "value");
query.orderByAsc("field"); query.orderByAsc("field");
console.log(`query is ${query.getSqlLike()}`); console.info(`query is ${query.getSqlLike()}`);
query = null; query = null;
} catch (e) { } catch (e) {
console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`);
...@@ -1821,7 +1820,7 @@ try { ...@@ -1821,7 +1820,7 @@ try {
let query = new distributedKVStore.Query(); let query = new distributedKVStore.Query();
query.notEqualTo("field", "value"); query.notEqualTo("field", "value");
query.orderByDesc("field"); query.orderByDesc("field");
console.log(`query is ${query.getSqlLike()}`); console.info(`query is ${query.getSqlLike()}`);
query = null; query = null;
} catch (e) { } catch (e) {
console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`);
...@@ -1832,7 +1831,7 @@ try { ...@@ -1832,7 +1831,7 @@ try {
limit(total: number, offset: number): Query limit(total: number, offset: number): Query
Creates a **Query** object to specify the number of results and where to start. Creates a **Query** object to specify the number of records of the query result and where to start. This API must be called after the invocation of the **orderByAsc()**, **orderByDesc()**, and the query APIs of the **Query** object.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core **System capability**: SystemCapability.DistributedDataManager.KVStore.Core
...@@ -1858,7 +1857,7 @@ try { ...@@ -1858,7 +1857,7 @@ try {
let query = new distributedKVStore.Query(); let query = new distributedKVStore.Query();
query.notEqualTo("field", "value"); query.notEqualTo("field", "value");
query.limit(total, offset); query.limit(total, offset);
console.log(`query is ${query.getSqlLike()}`); console.info(`query is ${query.getSqlLike()}`);
query = null; query = null;
} catch (e) { } catch (e) {
console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`);
...@@ -1891,7 +1890,7 @@ Creates a **Query** object to match the specified field whose value is not **nul ...@@ -1891,7 +1890,7 @@ Creates a **Query** object to match the specified field whose value is not **nul
try { try {
let query = new distributedKVStore.Query(); let query = new distributedKVStore.Query();
query.isNotNull("field"); query.isNotNull("field");
console.log(`query is ${query.getSqlLike()}`); console.info(`query is ${query.getSqlLike()}`);
query = null; query = null;
} catch (e) { } catch (e) {
console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`);
...@@ -1920,10 +1919,10 @@ try { ...@@ -1920,10 +1919,10 @@ try {
query.beginGroup(); query.beginGroup();
query.isNotNull("field"); query.isNotNull("field");
query.endGroup(); query.endGroup();
console.log("query is " + query.getSqlLike()); console.info("query is " + query.getSqlLike());
query = null; query = null;
} catch (e) { } catch (e) {
console.log("duplicated calls should be ok :" + e); console.error("duplicated calls should be ok :" + e);
} }
``` ```
...@@ -1949,10 +1948,10 @@ try { ...@@ -1949,10 +1948,10 @@ try {
query.beginGroup(); query.beginGroup();
query.isNotNull("field"); query.isNotNull("field");
query.endGroup(); query.endGroup();
console.log("query is " + query.getSqlLike()); console.info("query is " + query.getSqlLike());
query = null; query = null;
} catch (e) { } catch (e) {
console.log("duplicated calls should be ok :" + e); console.error("duplicated calls should be ok :" + e);
} }
``` ```
...@@ -1983,7 +1982,7 @@ try { ...@@ -1983,7 +1982,7 @@ try {
let query = new distributedKVStore.Query(); let query = new distributedKVStore.Query();
query.prefixKey("$.name"); query.prefixKey("$.name");
query.prefixKey("0"); query.prefixKey("0");
console.log(`query is ${query.getSqlLike()}`); console.info(`query is ${query.getSqlLike()}`);
query = null; query = null;
} catch (e) { } catch (e) {
console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`);
...@@ -2017,7 +2016,7 @@ try { ...@@ -2017,7 +2016,7 @@ try {
let query = new distributedKVStore.Query(); let query = new distributedKVStore.Query();
query.setSuggestIndex("$.name"); query.setSuggestIndex("$.name");
query.setSuggestIndex("0"); query.setSuggestIndex("0");
console.log(`query is ${query.getSqlLike()}`); console.info(`query is ${query.getSqlLike()}`);
query = null; query = null;
} catch (e) { } catch (e) {
console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`);
...@@ -2029,6 +2028,10 @@ try { ...@@ -2029,6 +2028,10 @@ try {
deviceId(deviceId:string):Query deviceId(deviceId:string):Query
Creates a **Query** object with the device ID as the key prefix. Creates a **Query** object with the device ID as the key prefix.
> **NOTE**<br/>
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core **System capability**: SystemCapability.DistributedDataManager.KVStore.Core
...@@ -2050,7 +2053,7 @@ Creates a **Query** object with the device ID as the key prefix. ...@@ -2050,7 +2053,7 @@ Creates a **Query** object with the device ID as the key prefix.
try { try {
let query = new distributedKVStore.Query(); let query = new distributedKVStore.Query();
query.deviceId("deviceId"); query.deviceId("deviceId");
console.log(`query is ${query.getSqlLike()}`); console.info(`query is ${query.getSqlLike()}`);
} catch (e) { } catch (e) {
console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`);
} }
...@@ -2076,9 +2079,9 @@ Obtains the query statement of the **Query** object. ...@@ -2076,9 +2079,9 @@ Obtains the query statement of the **Query** object.
try { try {
let query = new distributedKVStore.Query(); let query = new distributedKVStore.Query();
let sql1 = query.getSqlLike(); let sql1 = query.getSqlLike();
console.log(`GetSqlLike sql= ${sql1}`); console.info(`GetSqlLike sql= ${sql1}`);
} catch (e) { } catch (e) {
console.log("duplicated calls should be ok : " + e); console.error("duplicated calls should be ok : " + e);
} }
``` ```
...@@ -2108,24 +2111,29 @@ Adds a KV pair of the specified type to this KV store. This API uses an asynchro ...@@ -2108,24 +2111,29 @@ Adds a KV pair of the specified type to this KV store. This API uses an asynchro
For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).
| ID| **Error Message** | | ID| **Error Message** |
| ------------ | -------------------------------------- | | ------------ | ---------------------------------------- |
| 15100003 | Database corrupted. | | 15100003 | Database corrupted. |
| 15100005 | Database or result set already closed. | | 15100005 | Database or result set already closed. |
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| ID| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800047 | The WAL file size exceeds the default limit. |
**Example** **Example**
```js ```js
let kvStore;
const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const KEY_TEST_STRING_ELEMENT = 'key_test_string';
const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; const VALUE_TEST_STRING_ELEMENT = 'value-test-string';
try { try {
kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err, data) { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err, data) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to put.code is ${err.code},message is ${err.message}`); console.error(`Failed to put.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log("Succeeded in putting"); console.info("Succeeded in putting");
}); });
} catch (e) { } catch (e) {
console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
...@@ -2157,22 +2165,27 @@ Adds a KV pair of the specified type to this KV store. This API uses a promise t ...@@ -2157,22 +2165,27 @@ Adds a KV pair of the specified type to this KV store. This API uses a promise t
For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).
| ID| **Error Message** | | ID| **Error Message** |
| ------------ | -------------------------------------- | | ------------ | ---------------------------------------- |
| 15100003 | Database corrupted. | | 15100003 | Database corrupted. |
| 15100005 | Database or result set already closed. | | 15100005 | Database or result set already closed. |
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| ID| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800047 | The WAL file size exceeds the default limit. |
**Example** **Example**
```js ```js
let kvStore;
const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const KEY_TEST_STRING_ELEMENT = 'key_test_string';
const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; const VALUE_TEST_STRING_ELEMENT = 'value-test-string';
try { try {
kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => {
console.log(`Succeeded in putting.data=${data}`); console.info(`Succeeded in putting.data=${data}`);
}).catch((err) => { }).catch((err) => {
console.error(`Fail to put.code is ${err.code},message is ${err.message}`); console.error(`Failed to put.code is ${err.code},message is ${err.message}`);
}); });
} catch (e) { } catch (e) {
console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
...@@ -2191,22 +2204,27 @@ Batch inserts KV pairs to this single KV store. This API uses an asynchronous ca ...@@ -2191,22 +2204,27 @@ Batch inserts KV pairs to this single KV store. This API uses an asynchronous ca
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------ | ---- | ------------------------ | | -------- | ------------------------ | ---- | ------------------------ |
| entries | [Entry](#entry)[] | Yes | KV pairs to insert in batches.| | entries | [Entry](#entry)[] | Yes | KV pairs to insert in batches. An **entries** object allows a maximum of 128 entries.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. | | callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. |
**Error codes** **Error codes**
For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).
| ID| **Error Message** | | ID| **Error Message** |
| ------------ | -------------------------------------- | | ------------ | ---------------------------------------- |
| 15100003 | Database corrupted. | | 15100003 | Database corrupted. |
| 15100005 | Database or result set already closed. | | 15100005 | Database or result set already closed. |
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| ID| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800047 | The WAL file size exceeds the default limit. |
**Example** **Example**
```js ```js
let kvStore;
try { try {
let entries = []; let entries = [];
for (var i = 0; i < 10; i++) { for (var i = 0; i < 10; i++) {
...@@ -2220,20 +2238,20 @@ try { ...@@ -2220,20 +2238,20 @@ try {
} }
entries.push(entry); entries.push(entry);
} }
console.log(`entries: ${entries}`); console.info(`entries: ${entries}`);
kvStore.putBatch(entries, async function (err, data) { kvStore.putBatch(entries, async function (err, data) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to put Batch.code is ${err.code},message is ${err.message}`); console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Succeeded in putting Batch'); console.info('Succeeded in putting Batch');
kvStore.getEntries('batch_test_string_key', function (err, entries) { kvStore.getEntries('batch_test_string_key', function (err, entries) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`);
} }
console.log('Succeeded in getting Entries'); console.info('Succeeded in getting Entries');
console.log(`entries.length: ${entries.length}`); console.info(`entries.length: ${entries.length}`);
console.log(`entries[0]: ${entries[0]}`); console.info(`entries[0]: ${entries[0]}`);
}); });
}); });
} catch (e) { } catch (e) {
...@@ -2253,7 +2271,7 @@ Batch inserts KV pairs to this single KV store. This API uses a promise to retur ...@@ -2253,7 +2271,7 @@ Batch inserts KV pairs to this single KV store. This API uses a promise to retur
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------- | ----------------- | ---- | ------------------------ | | ------- | ----------------- | ---- | ------------------------ |
| entries | [Entry](#entry)[] | Yes | KV pairs to insert in batches.| | entries | [Entry](#entry)[] | Yes | KV pairs to insert in batches. An **entries** object allows a maximum of 128 entries.|
**Return value** **Return value**
...@@ -2265,15 +2283,20 @@ Batch inserts KV pairs to this single KV store. This API uses a promise to retur ...@@ -2265,15 +2283,20 @@ Batch inserts KV pairs to this single KV store. This API uses a promise to retur
For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).
| ID| **Error Message** | | ID| **Error Message** |
| ------------ | -------------------------------------- | | ------------ | ---------------------------------------- |
| 15100003 | Database corrupted. | | 15100003 | Database corrupted. |
| 15100005 | Database or result set already closed. | | 15100005 | Database or result set already closed. |
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| ID| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800047 | The WAL file size exceeds the default limit. |
**Example** **Example**
```js ```js
let kvStore;
try { try {
let entries = []; let entries = [];
for (var i = 0; i < 10; i++) { for (var i = 0; i < 10; i++) {
...@@ -2287,17 +2310,17 @@ try { ...@@ -2287,17 +2310,17 @@ try {
} }
entries.push(entry); entries.push(entry);
} }
console.log(`entries: ${entries}`); console.info(`entries: ${entries}`);
kvStore.putBatch(entries).then(async (entries) => { kvStore.putBatch(entries).then(async (entries) => {
console.log('Succeeded in putting Batch'); console.info('Succeeded in putting Batch');
kvStore.getEntries('batch_test_string_key').then((entries) => { kvStore.getEntries('batch_test_string_key').then((entries) => {
console.log('Succeeded in getting Entries'); console.info('Succeeded in getting Entries');
console.log(`PutBatch ${entries}`); console.info(`PutBatch ${entries}`);
}).catch((err) => { }).catch((err) => {
console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`);
}); });
}).catch((err) => { }).catch((err) => {
console.error(`Fail to put Batch.code is ${err.code},message is ${err.message}`); console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`);
}); });
} catch (e) { } catch (e) {
console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message} `); console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message} `);
...@@ -2325,15 +2348,20 @@ Writes data to this single KV store. This API uses an asynchronous callback to r ...@@ -2325,15 +2348,20 @@ Writes data to this single KV store. This API uses an asynchronous callback to r
For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).
| ID| **Error Message** | | ID| **Error Message** |
| ------------ | -------------------------------------- | | ------------ | ---------------------------------------- |
| 15100003 | Database corrupted. | | 15100003 | Database corrupted. |
| 15100005 | Database or result set already closed. | | 15100005 | Database or result set already closed. |
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| ID| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800047 | The WAL file size exceeds the default limit. |
**Example** **Example**
```js ```js
let kvStore;
try { try {
let v8Arr = []; let v8Arr = [];
let arr = new Uint8Array([4, 5, 6, 7]); let arr = new Uint8Array([4, 5, 6, 7]);
...@@ -2346,13 +2374,13 @@ try { ...@@ -2346,13 +2374,13 @@ try {
v8Arr.push(vb3); v8Arr.push(vb3);
kvStore.putBatch(v8Arr, async function (err, data) { kvStore.putBatch(v8Arr, async function (err, data) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Succeeded in putting batch'); console.info('Succeeded in putting batch');
}) })
} catch (e) { } catch (e) {
console.error(`Fail to put batch.code is ${e.code},message is ${e.message}`); console.error(`Failed to put batch.code is ${e.code},message is ${e.message}`);
} }
``` ```
...@@ -2382,15 +2410,20 @@ Write data to this KV store. This API uses a promise to return the result. ...@@ -2382,15 +2410,20 @@ Write data to this KV store. This API uses a promise to return the result.
For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).
| ID| **Error Message** | | ID| **Error Message** |
| ------------ | -------------------------------------- | | ------------ | ---------------------------------------- |
| 15100003 | Database corrupted. | | 15100003 | Database corrupted. |
| 15100005 | Database or result set already closed. | | 15100005 | Database or result set already closed. |
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| ID| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800047 | The WAL file size exceeds the default limit. |
**Example** **Example**
```js ```js
let kvStore;
try { try {
let v8Arr = []; let v8Arr = [];
let arr = new Uint8Array([4, 5, 6, 7]); let arr = new Uint8Array([4, 5, 6, 7]);
...@@ -2402,7 +2435,7 @@ try { ...@@ -2402,7 +2435,7 @@ try {
v8Arr.push(vb2); v8Arr.push(vb2);
v8Arr.push(vb3); v8Arr.push(vb3);
kvStore.putBatch(v8Arr).then(async (data) => { kvStore.putBatch(v8Arr).then(async (data) => {
console.log(`Succeeded in putting patch`); console.info(`Succeeded in putting patch`);
}).catch((err) => { }).catch((err) => {
console.error(`putBatch fail.code is ${err.code},message is ${err.message}`); console.error(`putBatch fail.code is ${err.code},message is ${err.message}`);
}); });
...@@ -2435,25 +2468,30 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -2435,25 +2468,30 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
| 15100003 | Database corrupted. | | 15100003 | Database corrupted. |
| 15100005 | Database or result set already closed. | | 15100005 | Database or result set already closed. |
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| ID| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800047 | The WAL file size exceeds the default limit. |
**Example** **Example**
```js ```js
let kvStore;
const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const KEY_TEST_STRING_ELEMENT = 'key_test_string';
const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; const VALUE_TEST_STRING_ELEMENT = 'value-test-string';
try { try {
kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err, data) { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err, data) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to put.code is ${err.code},message is ${err.message}`); console.error(`Failed to put.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Succeeded in putting'); console.info('Succeeded in putting');
kvStore.delete(KEY_TEST_STRING_ELEMENT, function (err, data) { kvStore.delete(KEY_TEST_STRING_ELEMENT, function (err, data) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to delete.code is ${err.code},message is ${err.message}`); console.error(`Failed to delete.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Succeeded in deleting'); console.info('Succeeded in deleting');
}); });
}); });
} catch (e) { } catch (e) {
...@@ -2485,27 +2523,32 @@ Deletes a KV pair from this KV store. This API uses a promise to return the resu ...@@ -2485,27 +2523,32 @@ Deletes a KV pair from this KV store. This API uses a promise to return the resu
For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).
| ID| **Error Message** | | ID| **Error Message** |
| ------------ | -------------------------------------- | | ------------ | ---------------------------------------- |
| 15100003 | Database corrupted. | | 15100003 | Database corrupted. |
| 15100005 | Database or result set already closed. | | 15100005 | Database or result set already closed. |
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| ID| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800047 | The WAL file size exceeds the default limit. |
**Example** **Example**
```js ```js
let kvStore;
const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const KEY_TEST_STRING_ELEMENT = 'key_test_string';
const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; const VALUE_TEST_STRING_ELEMENT = 'value-test-string';
try { try {
kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => {
console.log(`Succeeded in putting: ${data}`); console.info(`Succeeded in putting: ${data}`);
kvStore.delete(KEY_TEST_STRING_ELEMENT).then((data) => { kvStore.delete(KEY_TEST_STRING_ELEMENT).then((data) => {
console.log('Succeeded in deleting'); console.info('Succeeded in deleting');
}).catch((err) => { }).catch((err) => {
console.error(`Fail to delete.code is ${err.code},message is ${err.message}`); console.error(`Failed to delete.code is ${err.code},message is ${err.message}`);
}); });
}).catch((err) => { }).catch((err) => {
console.error(`Fail to put.code is ${err.code},message is ${err.message}`); console.error(`Failed to put.code is ${err.code},message is ${err.message}`);
}); });
} catch (e) { } catch (e) {
console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
...@@ -2526,7 +2569,7 @@ Deletes KV pairs from this KV store. This API uses an asynchronous callback to r ...@@ -2526,7 +2569,7 @@ Deletes KV pairs from this KV store. This API uses an asynchronous callback to r
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------- | | ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------- |
| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | **DataSharePredicates** object that specifies the KV pairs to delete. If this parameter is **null**, define the processing logic.| | predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | **DataSharePredicates** object that specifies the **KVStoreResultSet** object to obtain. If this parameter is **null**, define the processing logic.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. | | callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. |
**Error codes** **Error codes**
...@@ -2538,19 +2581,33 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -2538,19 +2581,33 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
| 15100003 | Database corrupted. | | 15100003 | Database corrupted. |
| 15100005 | Database or result set already closed. | | 15100005 | Database or result set already closed. |
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| ID| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800047 | The WAL file size exceeds the default limit. |
**Example** **Example**
```js ```js
import dataSharePredicates from '@ohos.data.dataSharePredicates'; import dataSharePredicates from '@ohos.data.dataSharePredicates';
let kvStore;
try { try {
let predicates = new dataSharePredicates.DataSharePredicates(); let predicates = new dataSharePredicates.DataSharePredicates();
kvStore.delete(predicates, function (err, data) { let arr = ["name"];
if (err == undefined) { predicates.inKeys(arr);
console.log('Succeeded in deleting'); kvStore.put("name", "bob", function (err, data) {
} else { if (err != undefined) {
console.error(`Fail to delete.code is ${err.code},message is ${err.message}`); console.error(`Failed to put.code is ${err.code},message is ${err.message}`);
return;
} }
console.info("Succeeded in putting");
kvStore.delete(predicates, function (err, data) {
if (err == undefined) {
console.info('Succeeded in deleting');
} else {
console.error(`Failed to delete.code is ${err.code},message is ${err.message}`);
}
});
}); });
} catch (e) { } catch (e) {
console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
...@@ -2583,30 +2640,35 @@ Deletes KV pairs from this KV store. This API uses a promise to return the resul ...@@ -2583,30 +2640,35 @@ Deletes KV pairs from this KV store. This API uses a promise to return the resul
For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).
| ID| **Error Message** | | ID| **Error Message** |
| ------------ | -------------------------------------- | | ------------ | ---------------------------------------- |
| 15100003 | Database corrupted. | | 15100003 | Database corrupted. |
| 15100005 | Database or result set already closed. | | 15100005 | Database or result set already closed. |
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| ID| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800047 | The WAL file size exceeds the default limit. |
**Example** **Example**
```js ```js
import dataSharePredicates from '@ohos.data.dataSharePredicates'; import dataSharePredicates from '@ohos.data.dataSharePredicates';
let kvStore;
try { try {
let predicates = new dataSharePredicates.DataSharePredicates(); let predicates = new dataSharePredicates.DataSharePredicates();
let arr = ["name"]; let arr = ["name"];
predicates.inKeys(arr); predicates.inKeys(arr);
kvStore.put("name", "bob").then((data) => { kvStore.put("name", "bob").then((data) => {
console.log(`Succeeded in putting: ${data}`); console.info(`Succeeded in putting: ${data}`);
kvStore.delete(predicates).then((data) => { kvStore.delete(predicates).then((data) => {
console.log('Succeeded in deleting'); console.info('Succeeded in deleting');
}).catch((err) => { }).catch((err) => {
console.error(`Fail to delete.code is ${err.code},message is ${err.message}`); console.error(`Failed to delete.code is ${err.code},message is ${err.message}`);
}); });
}).catch((err) => { }).catch((err) => {
console.error(`Fail to put.code is ${err.code},message is ${err.message}`); console.error(`Failed to put.code is ${err.code},message is ${err.message}`);
}); });
} catch (e) { } catch (e) {
console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
...@@ -2632,15 +2694,20 @@ Batch deletes KV pairs from this single KV store. This API uses an asynchronous ...@@ -2632,15 +2694,20 @@ Batch deletes KV pairs from this single KV store. This API uses an asynchronous
For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).
| ID| **Error Message** | | ID| **Error Message** |
| ------------ | -------------------------------------- | | ------------ | ---------------------------------------- |
| 15100003 | Database corrupted. | | 15100003 | Database corrupted. |
| 15100005 | Database or result set already closed. | | 15100005 | Database or result set already closed. |
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| ID| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800047 | The WAL file size exceeds the default limit. |
**Example** **Example**
```js ```js
let kvStore;
try { try {
let entries = []; let entries = [];
let keys = []; let keys = [];
...@@ -2656,19 +2723,19 @@ try { ...@@ -2656,19 +2723,19 @@ try {
entries.push(entry); entries.push(entry);
keys.push(key + i); keys.push(key + i);
} }
console.log(`entries: ${entries}`); console.info(`entries: ${entries}`);
kvStore.putBatch(entries, async function (err, data) { kvStore.putBatch(entries, async function (err, data) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to put Batch.code is ${err.code},message is ${err.message}`); console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Succeeded in putting Batch'); console.info('Succeeded in putting Batch');
kvStore.deleteBatch(keys, async function (err, data) { kvStore.deleteBatch(keys, async function (err, data) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to delete Batch.code is ${err.code},message is ${err.message}`); console.error(`Failed to delete Batch.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Succeeded in deleting Batch'); console.info('Succeeded in deleting Batch');
}); });
}); });
} catch (e) { } catch (e) {
...@@ -2700,15 +2767,20 @@ Batch deletes KV pairs from this single KV store. This API uses a promise to ret ...@@ -2700,15 +2767,20 @@ Batch deletes KV pairs from this single KV store. This API uses a promise to ret
For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).
| ID| **Error Message** | | ID| **Error Message** |
| ------------ | -------------------------------------- | | ------------ | ---------------------------------------- |
| 15100003 | Database corrupted. | | 15100003 | Database corrupted. |
| 15100005 | Database or result set already closed. | | 15100005 | Database or result set already closed. |
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| ID| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800047 | The WAL file size exceeds the default limit. |
**Example** **Example**
```js ```js
let kvStore;
try { try {
let entries = []; let entries = [];
let keys = []; let keys = [];
...@@ -2724,16 +2796,16 @@ try { ...@@ -2724,16 +2796,16 @@ try {
entries.push(entry); entries.push(entry);
keys.push(key + i); keys.push(key + i);
} }
console.log(`entries: ${entries}`); console.info(`entries: ${entries}`);
kvStore.putBatch(entries).then(async (data) => { kvStore.putBatch(entries).then(async (data) => {
console.log('Succeeded in putting Batch'); console.info('Succeeded in putting Batch');
kvStore.deleteBatch(keys).then((err) => { kvStore.deleteBatch(keys).then((err) => {
console.log('Succeeded in deleting Batch'); console.info('Succeeded in deleting Batch');
}).catch((err) => { }).catch((err) => {
console.error(`Fail to delete Batch.code is ${err.code},message is ${err.message}`); console.error(`Failed to delete Batch.code is ${err.code},message is ${err.message}`);
}); });
}).catch((err) => { }).catch((err) => {
console.error(`Fail to put Batch.code is ${err.code},message is ${err.message}`); console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`);
}); });
} catch (e) { } catch (e) {
console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
...@@ -2745,6 +2817,10 @@ try { ...@@ -2745,6 +2817,10 @@ try {
removeDeviceData(deviceId: string, callback: AsyncCallback&lt;void&gt;): void removeDeviceData(deviceId: string, callback: AsyncCallback&lt;void&gt;): void
Deletes data of a device. This API uses an asynchronous callback to return the result. Deletes data of a device. This API uses an asynchronous callback to return the result.
> **NOTE**<br/>
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
...@@ -2766,20 +2842,19 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -2766,20 +2842,19 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
**Example** **Example**
```js ```js
let kvStore;
const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; const KEY_TEST_STRING_ELEMENT = 'key_test_string_2';
const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; const VALUE_TEST_STRING_ELEMENT = 'value-string-002';
try { try {
kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err, data) { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err, data) {
console.log('Succeeded in putting data'); console.info('Succeeded in putting data');
const deviceid = 'no_exist_device_id'; const deviceid = 'no_exist_device_id';
kvStore.removeDeviceData(deviceid, async function (err, data) { kvStore.removeDeviceData(deviceid, async function (err, data) {
if (err == undefined) { if (err == undefined) {
console.log('succeeded in removing device data'); console.info('succeeded in removing device data');
} else { } else {
console.error(`Fail to remove device data.code is ${err.code},message is ${err.message} `); console.error(`Failed to remove device data.code is ${err.code},message is ${err.message} `);
kvStore.get(KEY_TEST_STRING_ELEMENT, async function (err, data) { kvStore.get(KEY_TEST_STRING_ELEMENT, async function (err, data) {
console.log('Succeeded in getting data'); console.info('Succeeded in getting data');
}); });
} }
}); });
...@@ -2794,6 +2869,10 @@ try { ...@@ -2794,6 +2869,10 @@ try {
removeDeviceData(deviceId: string): Promise&lt;void&gt; removeDeviceData(deviceId: string): Promise&lt;void&gt;
Deletes data of a device. This API uses a promise to return the result. Deletes data of a device. This API uses a promise to return the result.
> **NOTE**<br/>
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
...@@ -2820,25 +2899,24 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -2820,25 +2899,24 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
**Example** **Example**
```js ```js
let kvStore;
const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; const KEY_TEST_STRING_ELEMENT = 'key_test_string_2';
const VALUE_TEST_STRING_ELEMENT = 'value-string-001'; const VALUE_TEST_STRING_ELEMENT = 'value-string-001';
try { try {
kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((err) => { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((err) => {
console.log('Succeeded in putting data'); console.info('Succeeded in putting data');
}).catch((err) => { }).catch((err) => {
console.error(`Fail to put data.code is ${err.code},message is ${err.message} `); console.error(`Failed to put data.code is ${err.code},message is ${err.message} `);
}); });
const deviceid = 'no_exist_device_id'; const deviceid = 'no_exist_device_id';
kvStore.removeDeviceData(deviceid).then((err) => { kvStore.removeDeviceData(deviceid).then((err) => {
console.log('succeeded in removing device data'); console.info('succeeded in removing device data');
}).catch((err) => { }).catch((err) => {
console.error(`Fail to remove device data.code is ${err.code},message is ${err.message} `); console.error(`Failed to remove device data.code is ${err.code},message is ${err.message} `);
}); });
kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => { kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => {
console.log('Succeeded in getting data'); console.info('Succeeded in getting data');
}).catch((err) => { }).catch((err) => {
console.error(`Fail to get data.code is ${err.code},message is ${err.message} `); console.error(`Failed to get data.code is ${err.code},message is ${err.message} `);
}); });
} catch (e) { } catch (e) {
console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`) console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`)
...@@ -2873,26 +2951,25 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -2873,26 +2951,25 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
**Example** **Example**
```js ```js
let kvStore;
const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const KEY_TEST_STRING_ELEMENT = 'key_test_string';
const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; const VALUE_TEST_STRING_ELEMENT = 'value-test-string';
try { try {
kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err, data) { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err, data) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to put.code is ${err.code},message is ${err.message}`); console.error(`Failed to put.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log("Succeeded in putting"); console.info("Succeeded in putting");
kvStore.get(KEY_TEST_STRING_ELEMENT, function (err, data) { kvStore.get(KEY_TEST_STRING_ELEMENT, function (err, data) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to get.code is ${err.code},message is ${err.message}`); console.error(`Failed to get.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log(`Succeeded in getting data.data=${data}`); console.info(`Succeeded in getting data.data=${data}`);
}); });
}); });
} catch (e) { } catch (e) {
console.error(`Fail to get.code is ${e.code},message is ${e.message}`); console.error(`Failed to get.code is ${e.code},message is ${e.message}`);
} }
``` ```
...@@ -2929,22 +3006,21 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -2929,22 +3006,21 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
**Example** **Example**
```js ```js
let kvStore;
const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const KEY_TEST_STRING_ELEMENT = 'key_test_string';
const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; const VALUE_TEST_STRING_ELEMENT = 'value-test-string';
try { try {
kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => {
console.log(`Succeeded in putting data.data=${data}`); console.info(`Succeeded in putting data.data=${data}`);
kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => { kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => {
console.log(`Succeeded in getting data.data=${data}`); console.info(`Succeeded in getting data.data=${data}`);
}).catch((err) => { }).catch((err) => {
console.error(`Fail to get.code is ${err.code},message is ${err.message}`); console.error(`Failed to get.code is ${err.code},message is ${err.message}`);
}); });
}).catch((err) => { }).catch((err) => {
console.error(`Fail to put.code is ${err.code},message is ${err.message}`); console.error(`Failed to put.code is ${err.code},message is ${err.message}`);
}); });
} catch (e) { } catch (e) {
console.error(`Fail to get.code is ${e.code},message is ${e.message}`); console.error(`Failed to get.code is ${e.code},message is ${e.message}`);
} }
``` ```
...@@ -2975,7 +3051,6 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -2975,7 +3051,6 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
**Example** **Example**
```js ```js
let kvStore;
try { try {
let entries = []; let entries = [];
for (var i = 0; i < 10; i++) { for (var i = 0; i < 10; i++) {
...@@ -2989,21 +3064,21 @@ try { ...@@ -2989,21 +3064,21 @@ try {
} }
entries.push(entry); entries.push(entry);
} }
console.log(`entries: ${entries}`); console.info(`entries: ${entries}`);
kvStore.putBatch(entries, async function (err, data) { kvStore.putBatch(entries, async function (err, data) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to put Batch.code is ${err.code},message is ${err.message}`); console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Succeeded in putting Batch'); console.info('Succeeded in putting Batch');
kvStore.getEntries('batch_test_string_key', function (err, entries) { kvStore.getEntries('batch_test_string_key', function (err, entries) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Succeeded in getting Entries'); console.info('Succeeded in getting Entries');
console.log(`entries.length: ${entries.length}`); console.info(`entries.length: ${entries.length}`);
console.log(`entries[0]: ${entries[0]}`); console.info(`entries[0]: ${entries[0]}`);
}); });
}); });
} catch (e) { } catch (e) {
...@@ -3043,7 +3118,6 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -3043,7 +3118,6 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
**Example** **Example**
```js ```js
let kvStore;
try { try {
let entries = []; let entries = [];
for (var i = 0; i < 10; i++) { for (var i = 0; i < 10; i++) {
...@@ -3057,17 +3131,17 @@ try { ...@@ -3057,17 +3131,17 @@ try {
} }
entries.push(entry); entries.push(entry);
} }
console.log(`entries: ${entries}`); console.info(`entries: ${entries}`);
kvStore.putBatch(entries).then(async (entries) => { kvStore.putBatch(entries).then(async (entries) => {
console.log('Succeeded in putting Batch'); console.info('Succeeded in putting Batch');
kvStore.getEntries('batch_test_string_key').then((entries) => { kvStore.getEntries('batch_test_string_key').then((entries) => {
console.log('Succeeded in getting Entries'); console.info('Succeeded in getting Entries');
console.log(`PutBatch ${entries}`); console.info(`PutBatch ${entries}`);
}).catch((err) => { }).catch((err) => {
console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`);
}); });
}).catch((err) => { }).catch((err) => {
console.error(`Fail to put Batch.code is ${err.code},message is ${err.message}`); console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`);
}); });
} catch (e) { } catch (e) {
console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message} `); console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message} `);
...@@ -3101,7 +3175,6 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -3101,7 +3175,6 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
**Example** **Example**
```js ```js
let kvStore;
try { try {
var arr = new Uint8Array([21, 31]); var arr = new Uint8Array([21, 31]);
let entries = []; let entries = [];
...@@ -3116,23 +3189,23 @@ try { ...@@ -3116,23 +3189,23 @@ try {
} }
entries.push(entry); entries.push(entry);
} }
console.log(`entries: {entries}`); console.info(`entries: {entries}`);
kvStore.putBatch(entries, async function (err, data) { kvStore.putBatch(entries, async function (err, data) {
console.log('Succeeded in putting Batch'); console.info('Succeeded in putting Batch');
const query = new distributedKVStore.Query(); const query = new distributedKVStore.Query();
query.prefixKey("batch_test"); query.prefixKey("batch_test");
kvStore.getEntries(query, function (err, entries) { kvStore.getEntries(query, function (err, entries) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Succeeded in getting Entries'); console.info('Succeeded in getting Entries');
console.log(`entries.length: ${entries.length}`); console.info(`entries.length: ${entries.length}`);
console.log(`entries[0]: ${entries[0]}`); console.info(`entries[0]: ${entries[0]}`);
}); });
}); });
} catch (e) { } catch (e) {
console.error(`Fail to get Entries.code is ${e.code},message is ${e.message}`); console.error(`Failed to get Entries.code is ${e.code},message is ${e.message}`);
} }
``` ```
...@@ -3168,7 +3241,6 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -3168,7 +3241,6 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
**Example** **Example**
```js ```js
let kvStore;
try { try {
var arr = new Uint8Array([21, 31]); var arr = new Uint8Array([21, 31]);
let entries = []; let entries = [];
...@@ -3183,22 +3255,22 @@ try { ...@@ -3183,22 +3255,22 @@ try {
} }
entries.push(entry); entries.push(entry);
} }
console.log(`entries: {entries}`); console.info(`entries: {entries}`);
kvStore.putBatch(entries).then(async (err) => { kvStore.putBatch(entries).then(async (err) => {
console.log('Succeeded in putting Batch'); console.info('Succeeded in putting Batch');
const query = new distributedKVStore.Query(); const query = new distributedKVStore.Query();
query.prefixKey("batch_test"); query.prefixKey("batch_test");
kvStore.getEntries(query).then((entries) => { kvStore.getEntries(query).then((entries) => {
console.log('Succeeded in getting Entries'); console.info('Succeeded in getting Entries');
}).catch((err) => { }).catch((err) => {
console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`);
}); });
}).catch((err) => { }).catch((err) => {
console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`) console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`)
}); });
console.log('Succeeded in getting Entries'); console.info('Succeeded in getting Entries');
} catch (e) { } catch (e) {
console.error(`Fail to get Entries.code is ${e.code},message is ${e.message}`); console.error(`Failed to get Entries.code is ${e.code},message is ${e.message}`);
} }
``` ```
...@@ -3223,13 +3295,14 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -3223,13 +3295,14 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
| ID| **Error Message** | | ID| **Error Message** |
| ------------ | -------------------------------------- | | ------------ | -------------------------------------- |
| 15100001 | Over max limits. |
| 15100003 | Database corrupted. | | 15100003 | Database corrupted. |
| 15100005 | Database or result set already closed. | | 15100005 | Database or result set already closed. |
**Example** **Example**
```js ```js
let kvStore;
try { try {
let resultSet; let resultSet;
let entries = []; let entries = [];
...@@ -3246,23 +3319,23 @@ try { ...@@ -3246,23 +3319,23 @@ try {
} }
kvStore.putBatch(entries, async function (err, data) { kvStore.putBatch(entries, async function (err, data) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Succeeded in putting batch'); console.info('Succeeded in putting batch');
kvStore.getResultSet('batch_test_string_key', async function (err, result) { kvStore.getResultSet('batch_test_string_key', async function (err, result) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Succeeded in getting result set'); console.info('Succeeded in getting result set');
resultSet = result; resultSet = result;
kvStore.closeResultSet(resultSet, function (err, data) { kvStore.closeResultSet(resultSet, function (err, data) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Succeeded in closing result set'); console.info('Succeeded in closing result set');
}) })
}); });
}); });
...@@ -3297,13 +3370,13 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -3297,13 +3370,13 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
| ID| **Error Message** | | ID| **Error Message** |
| ------------ | -------------------------------------- | | ------------ | -------------------------------------- |
| 15100001 | Over max limits. |
| 15100003 | Database corrupted. | | 15100003 | Database corrupted. |
| 15100005 | Database or result set already closed. | | 15100005 | Database or result set already closed. |
**Example** **Example**
```js ```js
let kvStore;
try { try {
let resultSet; let resultSet;
let entries = []; let entries = [];
...@@ -3319,20 +3392,20 @@ try { ...@@ -3319,20 +3392,20 @@ try {
entries.push(entry); entries.push(entry);
} }
kvStore.putBatch(entries).then(async (err) => { kvStore.putBatch(entries).then(async (err) => {
console.log('Succeeded in putting batch'); console.info('Succeeded in putting batch');
}).catch((err) => { }).catch((err) => {
console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
}); });
kvStore.getResultSet('batch_test_string_key').then((result) => { kvStore.getResultSet('batch_test_string_key').then((result) => {
console.log('Succeeded in getting result set'); console.info('Succeeded in getting result set');
resultSet = result; resultSet = result;
}).catch((err) => { }).catch((err) => {
console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`);
}); });
kvStore.closeResultSet(resultSet).then((err) => { kvStore.closeResultSet(resultSet).then((err) => {
console.log('Succeeded in closing result set'); console.info('Succeeded in closing result set');
}).catch((err) => { }).catch((err) => {
console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`);
}); });
} catch (e) { } catch (e) {
console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`); console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`);
...@@ -3360,13 +3433,13 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -3360,13 +3433,13 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
| ID| **Error Message** | | ID| **Error Message** |
| ------------ | -------------------------------------- | | ------------ | -------------------------------------- |
| 15100001 | Over max limits. |
| 15100003 | Database corrupted. | | 15100003 | Database corrupted. |
| 15100005 | Database or result set already closed. | | 15100005 | Database or result set already closed. |
**Example** **Example**
```js ```js
let kvStore;
try { try {
let resultSet; let resultSet;
let entries = []; let entries = [];
...@@ -3383,18 +3456,18 @@ try { ...@@ -3383,18 +3456,18 @@ try {
} }
kvStore.putBatch(entries, async function (err, data) { kvStore.putBatch(entries, async function (err, data) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Succeeded in putting batch'); console.info('Succeeded in putting batch');
const query = new distributedKVStore.Query(); const query = new distributedKVStore.Query();
query.prefixKey("batch_test"); query.prefixKey("batch_test");
kvStore.getResultSet(query, async function (err, result) { kvStore.getResultSet(query, async function (err, result) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Succeeded in getting result set'); console.info('Succeeded in getting result set');
}); });
}); });
} catch (e) { } catch (e) {
...@@ -3428,13 +3501,13 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -3428,13 +3501,13 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
| ID| **Error Message** | | ID| **Error Message** |
| ------------ | -------------------------------------- | | ------------ | -------------------------------------- |
| 15100001 | Over max limits. |
| 15100003 | Database corrupted. | | 15100003 | Database corrupted. |
| 15100005 | Database or result set already closed. | | 15100005 | Database or result set already closed. |
**Example** **Example**
```js ```js
let kvStore;
try { try {
let resultSet; let resultSet;
let entries = []; let entries = [];
...@@ -3450,17 +3523,17 @@ try { ...@@ -3450,17 +3523,17 @@ try {
entries.push(entry); entries.push(entry);
} }
kvStore.putBatch(entries).then(async (err) => { kvStore.putBatch(entries).then(async (err) => {
console.log('Succeeded in putting batch'); console.info('Succeeded in putting batch');
}).catch((err) => { }).catch((err) => {
console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
}); });
const query = new distributedKVStore.Query(); const query = new distributedKVStore.Query();
query.prefixKey("batch_test"); query.prefixKey("batch_test");
kvStore.getResultSet(query).then((result) => { kvStore.getResultSet(query).then((result) => {
console.log('Succeeded in getting result set'); console.info('Succeeded in getting result set');
resultSet = result; resultSet = result;
}).catch((err) => { }).catch((err) => {
console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`);
}); });
} catch (e) { } catch (e) {
console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`); console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`);
...@@ -3490,6 +3563,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -3490,6 +3563,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
| ID| **Error Message** | | ID| **Error Message** |
| ------------ | -------------------------------------- | | ------------ | -------------------------------------- |
| 15100001 | Over max limits. |
| 15100003 | Database corrupted. | | 15100003 | Database corrupted. |
| 15100005 | Database or result set already closed. | | 15100005 | Database or result set already closed. |
...@@ -3498,24 +3572,23 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -3498,24 +3572,23 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
```js ```js
import dataSharePredicates from '@ohos.data.dataSharePredicates'; import dataSharePredicates from '@ohos.data.dataSharePredicates';
let kvStore;
try { try {
let resultSet; let resultSet;
let predicates = new dataSharePredicates.DataSharePredicates(); let predicates = new dataSharePredicates.DataSharePredicates();
predicates.prefixKey("batch_test_string_key"); predicates.prefixKey("batch_test_string_key");
kvStore.getResultSet(predicates, async function (err, result) { kvStore.getResultSet(predicates, async function (err, result) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Succeeded in getting result set'); console.info('Succeeded in getting result set');
resultSet = result; resultSet = result;
kvStore.closeResultSet(resultSet, function (err, data) { kvStore.closeResultSet(resultSet, function (err, data) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Succeeded in closing result set'); console.info('Succeeded in closing result set');
}) })
}); });
} catch (e) { } catch (e) {
...@@ -3551,6 +3624,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -3551,6 +3624,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
| ID| **Error Message** | | ID| **Error Message** |
| ------------ | -------------------------------------- | | ------------ | -------------------------------------- |
| 15100001 | Over max limits. |
| 15100003 | Database corrupted. | | 15100003 | Database corrupted. |
| 15100005 | Database or result set already closed. | | 15100005 | Database or result set already closed. |
...@@ -3559,21 +3633,20 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -3559,21 +3633,20 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
```js ```js
import dataSharePredicates from '@ohos.data.dataSharePredicates'; import dataSharePredicates from '@ohos.data.dataSharePredicates';
let kvStore;
try { try {
let resultSet; let resultSet;
let predicates = new dataSharePredicates.DataSharePredicates(); let predicates = new dataSharePredicates.DataSharePredicates();
predicates.prefixKey("batch_test_string_key"); predicates.prefixKey("batch_test_string_key");
kvStore.getResultSet(predicates).then((result) => { kvStore.getResultSet(predicates).then((result) => {
console.log('Succeeded in getting result set'); console.info('Succeeded in getting result set');
resultSet = result; resultSet = result;
}).catch((err) => { }).catch((err) => {
console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`);
}); });
kvStore.closeResultSet(resultSet).then((err) => { kvStore.closeResultSet(resultSet).then((err) => {
console.log('Succeeded in closing result set'); console.info('Succeeded in closing result set');
}).catch((err) => { }).catch((err) => {
console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`);
}); });
} catch (e) { } catch (e) {
console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`); console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`);
...@@ -3598,14 +3671,13 @@ Closes the **KVStoreResultSet** object returned by [SingleKvStore.getResultSet]( ...@@ -3598,14 +3671,13 @@ Closes the **KVStoreResultSet** object returned by [SingleKvStore.getResultSet](
**Example** **Example**
```js ```js
let kvStore;
try { try {
let resultSet = null; let resultSet = null;
kvStore.closeResultSet(resultSet, function (err, data) { kvStore.closeResultSet(resultSet, function (err, data) {
if (err == undefined) { if (err == undefined) {
console.log('Succeeded in closing result set'); console.info('Succeeded in closing result set');
} else { } else {
console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`);
} }
}); });
} catch (e) { } catch (e) {
...@@ -3636,13 +3708,12 @@ Closes the **KVStoreResultSet** object returned by [SingleKvStore.getResultSet]( ...@@ -3636,13 +3708,12 @@ Closes the **KVStoreResultSet** object returned by [SingleKvStore.getResultSet](
**Example** **Example**
```js ```js
let kvStore;
try { try {
let resultSet = null; let resultSet = null;
kvStore.closeResultSet(resultSet).then(() => { kvStore.closeResultSet(resultSet).then(() => {
console.log('Succeeded in closing result set'); console.info('Succeeded in closing result set');
}).catch((err) => { }).catch((err) => {
console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`);
}); });
} catch (e) { } catch (e) {
console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`); console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`);
...@@ -3676,7 +3747,6 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -3676,7 +3747,6 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
**Example** **Example**
```js ```js
let kvStore;
try { try {
let entries = []; let entries = [];
for (var i = 0; i < 10; i++) { for (var i = 0; i < 10; i++) {
...@@ -3691,15 +3761,15 @@ try { ...@@ -3691,15 +3761,15 @@ try {
entries.push(entry); entries.push(entry);
} }
kvStore.putBatch(entries, async function (err, data) { kvStore.putBatch(entries, async function (err, data) {
console.log('Succeeded in putting batch'); console.info('Succeeded in putting batch');
const query = new distributedKVStore.Query(); const query = new distributedKVStore.Query();
query.prefixKey("batch_test"); query.prefixKey("batch_test");
kvStore.getResultSize(query, async function (err, resultSize) { kvStore.getResultSize(query, async function (err, resultSize) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to get result size.code is ${err.code},message is ${err.message}`); console.error(`Failed to get result size.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Succeeded in getting result set size'); console.info('Succeeded in getting result set size');
}); });
}); });
} catch (e) { } catch (e) {
...@@ -3739,7 +3809,6 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -3739,7 +3809,6 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
**Example** **Example**
```js ```js
let kvStore;
try { try {
let entries = []; let entries = [];
for (var i = 0; i < 10; i++) { for (var i = 0; i < 10; i++) {
...@@ -3754,16 +3823,16 @@ try { ...@@ -3754,16 +3823,16 @@ try {
entries.push(entry); entries.push(entry);
} }
kvStore.putBatch(entries).then(async (err) => { kvStore.putBatch(entries).then(async (err) => {
console.log('Succeeded in putting batch'); console.info('Succeeded in putting batch');
}).catch((err) => { }).catch((err) => {
console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
}); });
const query = new distributedKVStore.Query(); const query = new distributedKVStore.Query();
query.prefixKey("batch_test"); query.prefixKey("batch_test");
kvStore.getResultSize(query).then((resultSize) => { kvStore.getResultSize(query).then((resultSize) => {
console.log('Succeeded in getting result set size'); console.info('Succeeded in getting result set size');
}).catch((err) => { }).catch((err) => {
console.error(`Fail to get result size.code is ${err.code},message is ${err.message}`); console.error(`Failed to get result size.code is ${err.code},message is ${err.message}`);
}); });
} catch (e) { } catch (e) {
console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`); console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`);
...@@ -3796,12 +3865,11 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -3796,12 +3865,11 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
**Example** **Example**
```js ```js
let kvStore;
let file = "BK001"; let file = "BK001";
try { try {
kvStore.backup(file, (err, data) => { kvStore.backup(file, (err, data) => {
if (err) { if (err) {
console.error(`Fail to backup.code is ${err.code},message is ${err.message} `); console.error(`Failed to backup.code is ${err.code},message is ${err.message} `);
} else { } else {
console.info(`Succeeded in backupping data.data=${data}`); console.info(`Succeeded in backupping data.data=${data}`);
} }
...@@ -3842,13 +3910,12 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -3842,13 +3910,12 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
**Example** **Example**
```js ```js
let kvStore;
let file = "BK001"; let file = "BK001";
try { try {
kvStore.backup(file).then((data) => { kvStore.backup(file).then((data) => {
console.info(`Succeeded in backupping data.data=${data}`); console.info(`Succeeded in backupping data.data=${data}`);
}).catch((err) => { }).catch((err) => {
console.error(`Fail to backup.code is ${err.code},message is ${err.message}`); console.error(`Failed to backup.code is ${err.code},message is ${err.message}`);
}); });
} catch (e) { } catch (e) {
console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
...@@ -3881,12 +3948,11 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -3881,12 +3948,11 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
**Example** **Example**
```js ```js
let kvStore;
let file = "BK001"; let file = "BK001";
try { try {
kvStore.restore(file, (err, data) => { kvStore.restore(file, (err, data) => {
if (err) { if (err) {
console.error(`Fail to restore.code is ${err.code},message is ${err.message}`); console.error(`Failed to restore.code is ${err.code},message is ${err.message}`);
} else { } else {
console.info(`Succeeded in restoring data.data=${data}`); console.info(`Succeeded in restoring data.data=${data}`);
} }
...@@ -3927,13 +3993,12 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -3927,13 +3993,12 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
**Example** **Example**
```js ```js
let kvStore;
let file = "BK001"; let file = "BK001";
try { try {
kvStore.restore(file).then((data) => { kvStore.restore(file).then((data) => {
console.info(`Succeeded in restoring data.data=${data}`); console.info(`Succeeded in restoring data.data=${data}`);
}).catch((err) => { }).catch((err) => {
console.error(`Fail to restore.code is ${err.code},message is ${err.message}`); console.error(`Failed to restore.code is ${err.code},message is ${err.message}`);
}); });
} catch (e) { } catch (e) {
console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
...@@ -3958,12 +4023,11 @@ Deletes a backup file. This API uses an asynchronous callback to return the resu ...@@ -3958,12 +4023,11 @@ Deletes a backup file. This API uses an asynchronous callback to return the resu
**Example** **Example**
```js ```js
let kvStore;
let files = ["BK001", "BK002"]; let files = ["BK001", "BK002"];
try { try {
kvStore.deleteBackup(files, (err, data) => { kvStore.deleteBackup(files, (err, data) => {
if (err) { if (err) {
console.error(`Fail to delete Backup.code is ${err.code},message is ${err.message}`); console.error(`Failed to delete Backup.code is ${err.code},message is ${err.message}`);
} else { } else {
console.info(`Succeed in deleting Backup.data=${data}`); console.info(`Succeed in deleting Backup.data=${data}`);
} }
...@@ -3996,16 +4060,15 @@ Deletes a backup file. This API uses a promise to return the result. ...@@ -3996,16 +4060,15 @@ Deletes a backup file. This API uses a promise to return the result.
**Example** **Example**
```js ```js
let kvStore;
let files = ["BK001", "BK002"]; let files = ["BK001", "BK002"];
try { try {
kvStore.deleteBackup(files).then((data) => { kvStore.deleteBackup(files).then((data) => {
console.info(`Succeed in deleting Backup.data=${data}`); console.info(`Succeed in deleting Backup.data=${data}`);
}).catch((err) => { }).catch((err) => {
console.error(`Fail to delete Backup.code is ${err.code},message is ${err.message}`); console.error(`Failed to delete Backup.code is ${err.code},message is ${err.message}`);
}) })
} catch (e) { } catch (e) {
console.log(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
} }
``` ```
...@@ -4027,14 +4090,19 @@ Starts the transaction in this single KV store. This API uses an asynchronous ca ...@@ -4027,14 +4090,19 @@ Starts the transaction in this single KV store. This API uses an asynchronous ca
For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).
| ID| **Error Message** | | ID| **Error Message** |
| ------------ | -------------------------------------- | | ------------ | ---------------------------------------- |
| 15100005 | Database or result set already closed. | | 15100005 | Database or result set already closed. |
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| ID| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800047 | The WAL file size exceeds the default limit. |
**Example** **Example**
```js ```js
let kvStore;
function putBatchString(len, prefix) { function putBatchString(len, prefix) {
let entries = []; let entries = [];
for (var i = 0; i < len; i++) { for (var i = 0; i < len; i++) {
...@@ -4053,27 +4121,27 @@ function putBatchString(len, prefix) { ...@@ -4053,27 +4121,27 @@ function putBatchString(len, prefix) {
try { try {
var count = 0; var count = 0;
kvStore.on('dataChange', 0, function (data) { kvStore.on('dataChange', 0, function (data) {
console.log(`startTransaction 0 ${data}`); console.info(`startTransaction 0 ${data}`);
count++; count++;
}); });
kvStore.startTransaction(async function (err, data) { kvStore.startTransaction(async function (err, data) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to start Transaction.code is ${err.code},message is ${err.message}`); console.error(`Failed to start Transaction.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Succeeded in starting Transaction'); console.info('Succeeded in starting Transaction');
let entries = putBatchString(10, 'batch_test_string_key'); let entries = putBatchString(10, 'batch_test_string_key');
console.log(`entries: ${entries}`); console.info(`entries: ${entries}`);
kvStore.putBatch(entries, async function (err, data) { kvStore.putBatch(entries, async function (err, data) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Succeeded in putting Batch'); console.info('Succeeded in putting Batch');
}); });
}); });
} catch (e) { } catch (e) {
console.error(`Fail to start Transaction.code is ${e.code},message is ${e.message}`); console.error(`Failed to start Transaction.code is ${e.code},message is ${e.message}`);
} }
``` ```
...@@ -4095,27 +4163,32 @@ Starts the transaction in this single KV store. This API uses a promise to retur ...@@ -4095,27 +4163,32 @@ Starts the transaction in this single KV store. This API uses a promise to retur
For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).
| ID| **Error Message** | | ID| **Error Message** |
| ------------ | -------------------------------------- | | ------------ | ---------------------------------------- |
| 15100005 | Database or result set already closed. | | 15100005 | Database or result set already closed. |
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| ID| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800047 | The WAL file size exceeds the default limit. |
**Example** **Example**
```js ```js
let kvStore;
try { try {
var count = 0; var count = 0;
kvStore.on('dataChange', distributedKVStore.SubscribeType.SUBSCRIBE_TYPE_ALL, function (data) { kvStore.on('dataChange', distributedKVStore.SubscribeType.SUBSCRIBE_TYPE_ALL, function (data) {
console.log(`startTransaction 0 ${data}`); console.info(`startTransaction 0 ${data}`);
count++; count++;
}); });
kvStore.startTransaction().then(async (err) => { kvStore.startTransaction().then(async (err) => {
console.log('Succeeded in starting Transaction'); console.info('Succeeded in starting Transaction');
}).catch((err) => { }).catch((err) => {
console.error(`Fail to start Transaction.code is ${err.code},message is ${err.message}`); console.error(`Failed to start Transaction.code is ${err.code},message is ${err.message}`);
}); });
} catch (e) { } catch (e) {
console.error(`Fail to start Transaction.code is ${e.code},message is ${e.message}`); console.error(`Failed to start Transaction.code is ${e.code},message is ${e.message}`);
} }
``` ```
...@@ -4144,13 +4217,12 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -4144,13 +4217,12 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
**Example** **Example**
```js ```js
let kvStore;
try { try {
kvStore.commit(function (err, data) { kvStore.commit(function (err, data) {
if (err == undefined) { if (err == undefined) {
console.log('Succeeded in committing'); console.info('Succeeded in committing');
} else { } else {
console.error(`Fail to commit.code is ${err.code},message is ${err.message}`); console.error(`Failed to commit.code is ${err.code},message is ${err.message}`);
} }
}); });
} catch (e) { } catch (e) {
...@@ -4183,12 +4255,11 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -4183,12 +4255,11 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
**Example** **Example**
```js ```js
let kvStore;
try { try {
kvStore.commit().then(async (err) => { kvStore.commit().then(async (err) => {
console.log('Succeeded in committing'); console.info('Succeeded in committing');
}).catch((err) => { }).catch((err) => {
console.error(`Fail to commit.code is ${err.code},message is ${err.message}`); console.error(`Failed to commit.code is ${err.code},message is ${err.message}`);
}); });
} catch (e) { } catch (e) {
console.error(`An unexpected error occurred.ode is ${e.code},message is ${e.message}`); console.error(`An unexpected error occurred.ode is ${e.code},message is ${e.message}`);
...@@ -4220,13 +4291,12 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -4220,13 +4291,12 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
**Example** **Example**
```js ```js
let kvStore;
try { try {
kvStore.rollback(function (err,data) { kvStore.rollback(function (err,data) {
if (err == undefined) { if (err == undefined) {
console.log('Succeeded in rolling back'); console.info('Succeeded in rolling back');
} else { } else {
console.error(`Fail to rollback.code is ${err.code},message is ${err.message}`); console.error(`Failed to rollback.code is ${err.code},message is ${err.message}`);
} }
}); });
}catch(e) { }catch(e) {
...@@ -4259,12 +4329,11 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -4259,12 +4329,11 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
**Example** **Example**
```js ```js
let kvStore;
try { try {
kvStore.rollback().then(async (err) => { kvStore.rollback().then(async (err) => {
console.log('Succeeded in rolling back'); console.info('Succeeded in rolling back');
}).catch((err) => { }).catch((err) => {
console.error(`Fail to rollback.code is ${err.code},message is ${err.message}`); console.error(`Failed to rollback.code is ${err.code},message is ${err.message}`);
}); });
} catch (e) { } catch (e) {
console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
...@@ -4289,13 +4358,12 @@ Sets data synchronization, which can be enabled or disabled. This API uses an as ...@@ -4289,13 +4358,12 @@ Sets data synchronization, which can be enabled or disabled. This API uses an as
**Example** **Example**
```js ```js
let kvStore;
try { try {
kvStore.enableSync(true, function (err, data) { kvStore.enableSync(true, function (err, data) {
if (err == undefined) { if (err == undefined) {
console.log('Succeeded in enabling sync'); console.info('Succeeded in enabling sync');
} else { } else {
console.error(`Fail to enable sync.code is ${err.code},message is ${err.message}`); console.error(`Failed to enable sync.code is ${err.code},message is ${err.message}`);
} }
}); });
} catch (e) { } catch (e) {
...@@ -4326,12 +4394,11 @@ Sets data synchronization, which can be enabled or disabled. This API uses a pro ...@@ -4326,12 +4394,11 @@ Sets data synchronization, which can be enabled or disabled. This API uses a pro
**Example** **Example**
```js ```js
let kvStore;
try { try {
kvStore.enableSync(true).then((err) => { kvStore.enableSync(true).then((err) => {
console.log('Succeeded in enabling sync'); console.info('Succeeded in enabling sync');
}).catch((err) => { }).catch((err) => {
console.error(`Fail to enable sync.code is ${err.code},message is ${err.message}`); console.error(`Failed to enable sync.code is ${err.code},message is ${err.message}`);
}); });
} catch (e) { } catch (e) {
console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
...@@ -4357,16 +4424,15 @@ Sets the data synchronization range. This API uses an asynchronous callback to r ...@@ -4357,16 +4424,15 @@ Sets the data synchronization range. This API uses an asynchronous callback to r
**Example** **Example**
```js ```js
let kvStore;
try { try {
const localLabels = ['A', 'B']; const localLabels = ['A', 'B'];
const remoteSupportLabels = ['C', 'D']; const remoteSupportLabels = ['C', 'D'];
kvStore.setSyncRange(localLabels, remoteSupportLabels, function (err, data) { kvStore.setSyncRange(localLabels, remoteSupportLabels, function (err, data) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to set syncRange.code is ${err.code},message is ${err.message}`); console.error(`Failed to set syncRange.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Succeeded in setting syncRange'); console.info('Succeeded in setting syncRange');
}); });
} catch (e) { } catch (e) {
console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
...@@ -4397,14 +4463,13 @@ Sets the data synchronization range. This API uses a promise to return the resul ...@@ -4397,14 +4463,13 @@ Sets the data synchronization range. This API uses a promise to return the resul
**Example** **Example**
```js ```js
let kvStore;
try { try {
const localLabels = ['A', 'B']; const localLabels = ['A', 'B'];
const remoteSupportLabels = ['C', 'D']; const remoteSupportLabels = ['C', 'D'];
kvStore.setSyncRange(localLabels, remoteSupportLabels).then((err) => { kvStore.setSyncRange(localLabels, remoteSupportLabels).then((err) => {
console.log('Succeeded in setting syncRange'); console.info('Succeeded in setting syncRange');
}).catch((err) => { }).catch((err) => {
console.error(`Fail to set syncRange.code is ${err.code},message is ${err.message}`); console.error(`Failed to set syncRange.code is ${err.code},message is ${err.message}`);
}); });
} catch (e) { } catch (e) {
console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
...@@ -4429,15 +4494,14 @@ Sets the default delay allowed for KV store synchronization. This API uses an as ...@@ -4429,15 +4494,14 @@ Sets the default delay allowed for KV store synchronization. This API uses an as
**Example** **Example**
```js ```js
let kvStore;
try { try {
const defaultAllowedDelayMs = 500; const defaultAllowedDelayMs = 500;
kvStore.setSyncParam(defaultAllowedDelayMs, function (err, data) { kvStore.setSyncParam(defaultAllowedDelayMs, function (err, data) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to set syncParam.code is ${err.code},message is ${err.message}`); console.error(`Failed to set syncParam.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Succeeded in setting syncParam'); console.info('Succeeded in setting syncParam');
}); });
} catch (e) { } catch (e) {
console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
...@@ -4467,13 +4531,12 @@ Sets the default delay allowed for KV store synchronization. This API uses a pro ...@@ -4467,13 +4531,12 @@ Sets the default delay allowed for KV store synchronization. This API uses a pro
**Example** **Example**
```js ```js
let kvStore;
try { try {
const defaultAllowedDelayMs = 500; const defaultAllowedDelayMs = 500;
kvStore.setSyncParam(defaultAllowedDelayMs).then((err) => { kvStore.setSyncParam(defaultAllowedDelayMs).then((err) => {
console.log('Succeeded in setting syncParam'); console.info('Succeeded in setting syncParam');
}).catch((err) => { }).catch((err) => {
console.error(`Fail to set syncParam.code is ${err.code},message is ${err.message}`); console.error(`Failed to set syncParam.code is ${err.code},message is ${err.message}`);
}); });
} catch (e) { } catch (e) {
console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
...@@ -4484,8 +4547,8 @@ try { ...@@ -4484,8 +4547,8 @@ try {
sync(deviceIds: string[], mode: SyncMode, delayMs?: number): void sync(deviceIds: string[], mode: SyncMode, delayMs?: number): void
Synchronizes the KV store manually. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview](../../database/database-mdds-overview.md). Synchronizes the KV store manually. For details about the synchronization modes of KV stores, see [Cross-Device Synchronization of KV Stores](../../database/data-sync-of-kv-store.md).
> **NOTE** > **NOTE**<br/>
> >
> The value of **deviceIds** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. > The value of **deviceIds** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
...@@ -4516,7 +4579,6 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -4516,7 +4579,6 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
import deviceManager from '@ohos.distributedHardware.deviceManager'; import deviceManager from '@ohos.distributedHardware.deviceManager';
let devManager; let devManager;
let kvStore;
const KEY_TEST_SYNC_ELEMENT = 'key_test_sync'; const KEY_TEST_SYNC_ELEMENT = 'key_test_sync';
const VALUE_TEST_SYNC_ELEMENT = 'value-string-001'; const VALUE_TEST_SYNC_ELEMENT = 'value-string-001';
// create deviceManager // create deviceManager
...@@ -4532,19 +4594,19 @@ deviceManager.createDeviceManager('bundleName', (err, value) => { ...@@ -4532,19 +4594,19 @@ deviceManager.createDeviceManager('bundleName', (err, value) => {
} }
try { try {
kvStore.on('syncComplete', function (data) { kvStore.on('syncComplete', function (data) {
console.log('Sync dataChange'); console.info('Sync dataChange');
}); });
kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err, data) { kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err, data) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to sync.code is ${err.code},message is ${err.message}`); console.error(`Failed to sync.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Succeeded in putting data'); console.info('Succeeded in putting data');
const mode = distributedKVStore.SyncMode.PULL_ONLY; const mode = distributedKVStore.SyncMode.PULL_ONLY;
kvStore.sync(deviceIds, mode, 1000); kvStore.sync(deviceIds, mode, 1000);
}); });
} catch (e) { } catch (e) {
console.error(`Fail to sync.code is ${e.code},message is ${e.message}`); console.error(`Failed to sync.code is ${e.code},message is ${e.message}`);
} }
} }
}); });
...@@ -4554,7 +4616,7 @@ deviceManager.createDeviceManager('bundleName', (err, value) => { ...@@ -4554,7 +4616,7 @@ deviceManager.createDeviceManager('bundleName', (err, value) => {
sync(deviceIds: string[], query: Query, mode: SyncMode, delayMs?: number): void sync(deviceIds: string[], query: Query, mode: SyncMode, delayMs?: number): void
Synchronizes the KV store manually. This API returns the result synchronously. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview](../../database/database-mdds-overview.md). Synchronizes the KV store manually. This API returns the result synchronously. For details about the synchronization modes of KV stores, see [Cross-Device Synchronization of KV Stores](../../database/data-sync-of-kv-store.md).
> **NOTE**<br/> > **NOTE**<br/>
> >
> The value of **deviceIds** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. > The value of **deviceIds** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
...@@ -4587,7 +4649,6 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -4587,7 +4649,6 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
import deviceManager from '@ohos.distributedHardware.deviceManager'; import deviceManager from '@ohos.distributedHardware.deviceManager';
let devManager; let devManager;
let kvStore;
const KEY_TEST_SYNC_ELEMENT = 'key_test_sync'; const KEY_TEST_SYNC_ELEMENT = 'key_test_sync';
const VALUE_TEST_SYNC_ELEMENT = 'value-string-001'; const VALUE_TEST_SYNC_ELEMENT = 'value-string-001';
// create deviceManager // create deviceManager
...@@ -4603,14 +4664,14 @@ deviceManager.createDeviceManager('bundleName', (err, value) => { ...@@ -4603,14 +4664,14 @@ deviceManager.createDeviceManager('bundleName', (err, value) => {
} }
try { try {
kvStore.on('syncComplete', function (data) { kvStore.on('syncComplete', function (data) {
console.log('Sync dataChange'); console.info('Sync dataChange');
}); });
kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err, data) { kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err, data) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to sync.code is ${err.code},message is ${err.message}`); console.error(`Failed to sync.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Succeeded in putting data'); console.info('Succeeded in putting data');
const mode = distributedKVStore.SyncMode.PULL_ONLY; const mode = distributedKVStore.SyncMode.PULL_ONLY;
const query = new distributedKVStore.Query(); const query = new distributedKVStore.Query();
query.prefixKey("batch_test"); query.prefixKey("batch_test");
...@@ -4618,7 +4679,7 @@ deviceManager.createDeviceManager('bundleName', (err, value) => { ...@@ -4618,7 +4679,7 @@ deviceManager.createDeviceManager('bundleName', (err, value) => {
kvStore.sync(deviceIds, query, mode, 1000); kvStore.sync(deviceIds, query, mode, 1000);
}); });
} catch (e) { } catch (e) {
console.error(`Fail to sync.code is ${e.code},message is ${e.message}`); console.error(`Failed to sync.code is ${e.code},message is ${e.message}`);
} }
} }
}); });
...@@ -4646,16 +4707,15 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -4646,16 +4707,15 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
| ID| **Error Message** | | ID| **Error Message** |
| ------------ | -------------------------------------- | | ------------ | -------------------------------------- |
| 15100001 | Over max subscribe limits. | | 15100001 | Over max limits. |
| 15100005 | Database or result set already closed. | | 15100005 | Database or result set already closed. |
**Example** **Example**
```js ```js
let kvStore;
try { try {
kvStore.on('dataChange', distributedKVStore.SubscribeType.SUBSCRIBE_TYPE_LOCAL, function (data) { kvStore.on('dataChange', distributedKVStore.SubscribeType.SUBSCRIBE_TYPE_LOCAL, function (data) {
console.log(`dataChange callback call data: ${data}`); console.info(`dataChange callback call data: ${data}`);
}); });
} catch (e) { } catch (e) {
console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
...@@ -4680,20 +4740,19 @@ Subscribes to synchronization complete events. ...@@ -4680,20 +4740,19 @@ Subscribes to synchronization complete events.
**Example** **Example**
```js ```js
let kvStore;
const KEY_TEST_FLOAT_ELEMENT = 'key_test_float'; const KEY_TEST_FLOAT_ELEMENT = 'key_test_float';
const VALUE_TEST_FLOAT_ELEMENT = 321.12; const VALUE_TEST_FLOAT_ELEMENT = 321.12;
try { try {
kvStore.on('syncComplete', function (data) { kvStore.on('syncComplete', function (data) {
console.log(`syncComplete ${data}`); console.info(`syncComplete ${data}`);
}); });
kvStore.put(KEY_TEST_FLOAT_ELEMENT, VALUE_TEST_FLOAT_ELEMENT).then((data) => { kvStore.put(KEY_TEST_FLOAT_ELEMENT, VALUE_TEST_FLOAT_ELEMENT).then((data) => {
console.log('succeeded in putting'); console.info('succeeded in putting');
}).catch((err) => { }).catch((err) => {
console.error(`Fail to put.code is ${err.code},message is ${err.message}`); console.error(`Failed to put.code is ${err.code},message is ${err.message}`);
}); });
} catch (e) { } catch (e) {
console.error(`Fail to subscribe syncComplete.code is ${e.code},message is ${e.message}`); console.error(`Failed to subscribe syncComplete.code is ${e.code},message is ${e.message}`);
} }
``` ```
...@@ -4723,10 +4782,9 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -4723,10 +4782,9 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
**Example** **Example**
```js ```js
let kvStore;
class KvstoreModel { class KvstoreModel {
call(data) { call(data) {
console.log(`dataChange : ${data}`); console.info(`dataChange : ${data}`);
} }
subscribeDataChange() { subscribeDataChange() {
...@@ -4735,7 +4793,7 @@ class KvstoreModel { ...@@ -4735,7 +4793,7 @@ class KvstoreModel {
kvStore.on('dataChange', distributedKVStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, this.call); kvStore.on('dataChange', distributedKVStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, this.call);
} }
} catch (err) { } catch (err) {
console.error(`Fail to subscribeDataChange.code is ${err.code},message is ${err.message}`); console.error(`Failed to subscribeDataChange.code is ${err.code},message is ${err.message}`);
} }
} }
...@@ -4745,7 +4803,7 @@ class KvstoreModel { ...@@ -4745,7 +4803,7 @@ class KvstoreModel {
kvStore.off('dataChange', this.call); kvStore.off('dataChange', this.call);
} }
} catch (err) { } catch (err) {
console.error(`Fail to unsubscribeDataChange.code is ${err.code},message is ${err.message}`); console.error(`Failed to unsubscribeDataChange.code is ${err.code},message is ${err.message}`);
} }
} }
} }
...@@ -4769,10 +4827,9 @@ Unsubscribes from synchronization complete events. ...@@ -4769,10 +4827,9 @@ Unsubscribes from synchronization complete events.
**Example** **Example**
```js ```js
let kvStore;
class KvstoreModel { class KvstoreModel {
call(data) { call(data) {
console.log(`syncComplete : ${data}`); console.info(`syncComplete : ${data}`);
} }
subscribeDataChange() { subscribeDataChange() {
...@@ -4781,7 +4838,7 @@ class KvstoreModel { ...@@ -4781,7 +4838,7 @@ class KvstoreModel {
kvStore.on('syncComplete', distributedKVStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, this.call); kvStore.on('syncComplete', distributedKVStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, this.call);
} }
} catch (err) { } catch (err) {
console.error(`Fail to subscribeDataChange.code is ${err.code},message is ${err.message}`); console.error(`Failed to subscribeDataChange.code is ${err.code},message is ${err.message}`);
} }
} }
...@@ -4791,7 +4848,7 @@ class KvstoreModel { ...@@ -4791,7 +4848,7 @@ class KvstoreModel {
kvStore.off('dsyncComplete', this.call); kvStore.off('dsyncComplete', this.call);
} }
} catch (err) { } catch (err) {
console.error(`Fail to unsubscribeDataChange.code is ${err.code},message is ${err.message}`); console.error(`Failed to unsubscribeDataChange.code is ${err.code},message is ${err.message}`);
} }
} }
} }
...@@ -4822,14 +4879,13 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -4822,14 +4879,13 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
**Example** **Example**
```js ```js
let kvStore;
try { try {
kvStore.getSecurityLevel(function (err, data) { kvStore.getSecurityLevel(function (err, data) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to get SecurityLevel.code is ${err.code},message is ${err.message}`); console.error(`Failed to get SecurityLevel.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Succeeded in getting securityLevel'); console.info('Succeeded in getting securityLevel');
}); });
} catch (e) { } catch (e) {
console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
...@@ -4861,12 +4917,11 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -4861,12 +4917,11 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
**Example** **Example**
```js ```js
let kvStore;
try { try {
kvStore.getSecurityLevel().then((data) => { kvStore.getSecurityLevel().then((data) => {
console.log('Succeeded in getting securityLevel'); console.info('Succeeded in getting securityLevel');
}).catch((err) => { }).catch((err) => {
console.error(`Fail to get SecurityLevel.code is ${err.code},message is ${err.message}`); console.error(`Failed to get SecurityLevel.code is ${err.code},message is ${err.message}`);
}); });
} catch (e) { } catch (e) {
console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
...@@ -4911,26 +4966,25 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -4911,26 +4966,25 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
**Example** **Example**
```js ```js
let kvStore;
const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const KEY_TEST_STRING_ELEMENT = 'key_test_string';
const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; const VALUE_TEST_STRING_ELEMENT = 'value-test-string';
try { try {
kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err, data) { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err, data) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to put.code is ${err.code},message is ${err.message}`); console.error(`Failed to put.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log("Succeeded in putting"); console.info("Succeeded in putting");
kvStore.get(KEY_TEST_STRING_ELEMENT, function (err, data) { kvStore.get(KEY_TEST_STRING_ELEMENT, function (err, data) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to get.code is ${err.code},message is ${err.message}`); console.error(`Failed to get.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log(`Succeeded in getting data.data=${data}`); console.info(`Succeeded in getting data.data=${data}`);
}); });
}); });
} catch (e) { } catch (e) {
console.error(`Fail to get.code is ${e.code},message is ${e.message}`); console.error(`Failed to get.code is ${e.code},message is ${e.message}`);
} }
``` ```
...@@ -4967,22 +5021,21 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -4967,22 +5021,21 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
**Example** **Example**
```js ```js
let kvStore;
const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const KEY_TEST_STRING_ELEMENT = 'key_test_string';
const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; const VALUE_TEST_STRING_ELEMENT = 'value-test-string';
try { try {
kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => {
console.log(`Succeeded in putting data.data=${data}`); console.info(`Succeeded in putting data.data=${data}`);
kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => { kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => {
console.log(`Succeeded in getting data.data=${data}`); console.info(`Succeeded in getting data.data=${data}`);
}).catch((err) => { }).catch((err) => {
console.error(`Fail to get.code is ${err.code},message is ${err.message}`); console.error(`Failed to get.code is ${err.code},message is ${err.message}`);
}); });
}).catch((err) => { }).catch((err) => {
console.error(`Fail to put.code is ${err.code},message is ${err.message}`); console.error(`Failed to put.code is ${err.code},message is ${err.message}`);
}); });
} catch (e) { } catch (e) {
console.error(`Fail to get.code is ${e.code},message is ${e.message}`); console.error(`Failed to get.code is ${e.code},message is ${e.message}`);
} }
``` ```
...@@ -4991,6 +5044,10 @@ try { ...@@ -4991,6 +5044,10 @@ try {
get(deviceId: string, key: string, callback: AsyncCallback&lt;boolean | string | number | Uint8Array&gt;): void get(deviceId: string, key: string, callback: AsyncCallback&lt;boolean | string | number | Uint8Array&gt;): void
Obtains a string value that matches the specified device ID and key. This API uses an asynchronous callback to return the result. Obtains a string value that matches the specified device ID and key. This API uses an asynchronous callback to return the result.
> **NOTE**<br/>
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
...@@ -5015,26 +5072,25 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -5015,26 +5072,25 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
**Example** **Example**
```js ```js
let kvStore;
const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; const KEY_TEST_STRING_ELEMENT = 'key_test_string_2';
const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; const VALUE_TEST_STRING_ELEMENT = 'value-string-002';
try { try {
kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err, data) { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err, data) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to put.code is ${err.code},message is ${err.message}`); console.error(`Failed to put.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Succeeded in putting'); console.info('Succeeded in putting');
kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT, function (err, data) { kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT, function (err, data) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to get.code is ${err.code},message is ${err.message}`); console.error(`Failed to get.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Succeeded in getting'); console.info('Succeeded in getting');
}); });
}) })
} catch (e) { } catch (e) {
console.error(`Fail to get.code is ${e.code},message is ${e.message}`); console.error(`Failed to get.code is ${e.code},message is ${e.message}`);
} }
``` ```
...@@ -5043,6 +5099,10 @@ try { ...@@ -5043,6 +5099,10 @@ try {
get(deviceId: string, key: string): Promise&lt;boolean | string | number | Uint8Array&gt; get(deviceId: string, key: string): Promise&lt;boolean | string | number | Uint8Array&gt;
Obtains a string value that matches the specified device ID and key. This API uses a promise to return the result. Obtains a string value that matches the specified device ID and key. This API uses a promise to return the result.
> **NOTE**<br/>
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
...@@ -5072,22 +5132,21 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -5072,22 +5132,21 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
**Example** **Example**
```js ```js
let kvStore;
const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; const KEY_TEST_STRING_ELEMENT = 'key_test_string_2';
const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; const VALUE_TEST_STRING_ELEMENT = 'value-string-002';
try { try {
kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then(async (data) => { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then(async (data) => {
console.log('Succeeded in putting'); console.info('Succeeded in putting');
kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT).then((data) => { kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT).then((data) => {
console.log('Succeeded in getting'); console.info('Succeeded in getting');
}).catch((err) => { }).catch((err) => {
console.error(`Fail to get.code is ${err.code},message is ${err.message}`); console.error(`Failed to get.code is ${err.code},message is ${err.message}`);
}); });
}).catch((error) => { }).catch((error) => {
console.error(`Fail to put.code is ${error.code},message is ${error.message}`); console.error(`Failed to put.code is ${error.code},message is ${error.message}`);
}); });
} catch (e) { } catch (e) {
console.error(`Fail to get.code is ${e.code},message is ${e.message}`); console.error(`Failed to get.code is ${e.code},message is ${e.message}`);
} }
``` ```
...@@ -5118,7 +5177,6 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -5118,7 +5177,6 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
**Example** **Example**
```js ```js
let kvStore;
try { try {
let entries = []; let entries = [];
for (var i = 0; i < 10; i++) { for (var i = 0; i < 10; i++) {
...@@ -5132,21 +5190,21 @@ try { ...@@ -5132,21 +5190,21 @@ try {
} }
entries.push(entry); entries.push(entry);
} }
console.log(`entries: ${entries}`); console.info(`entries: ${entries}`);
kvStore.putBatch(entries, async function (err, data) { kvStore.putBatch(entries, async function (err, data) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to put Batch.code is ${err.code},message is ${err.message}`); console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Succeeded in putting Batch'); console.info('Succeeded in putting Batch');
kvStore.getEntries('batch_test_string_key', function (err, entries) { kvStore.getEntries('batch_test_string_key', function (err, entries) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Succeeded in getting Entries'); console.info('Succeeded in getting Entries');
console.log(`entries.length: ${entries.length}`); console.info(`entries.length: ${entries.length}`);
console.log(`entries[0]: ${entries[0]}`); console.info(`entries[0]: ${entries[0]}`);
}); });
}); });
} catch (e) { } catch (e) {
...@@ -5186,7 +5244,6 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -5186,7 +5244,6 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
**Example** **Example**
```js ```js
let kvStore;
try { try {
let entries = []; let entries = [];
for (var i = 0; i < 10; i++) { for (var i = 0; i < 10; i++) {
...@@ -5200,17 +5257,17 @@ try { ...@@ -5200,17 +5257,17 @@ try {
} }
entries.push(entry); entries.push(entry);
} }
console.log(`entries: ${entries}`); console.info(`entries: ${entries}`);
kvStore.putBatch(entries).then(async (entries) => { kvStore.putBatch(entries).then(async (entries) => {
console.log('Succeeded in putting Batch'); console.info('Succeeded in putting Batch');
kvStore.getEntries('batch_test_string_key').then((entries) => { kvStore.getEntries('batch_test_string_key').then((entries) => {
console.log('Succeeded in getting Entries'); console.info('Succeeded in getting Entries');
console.log(`PutBatch ${entries}`); console.info(`PutBatch ${entries}`);
}).catch((err) => { }).catch((err) => {
console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`);
}); });
}).catch((err) => { }).catch((err) => {
console.error(`Fail to put Batch.code is ${err.code},message is ${err.message}`); console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`);
}); });
} catch (e) { } catch (e) {
console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message} `); console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message} `);
...@@ -5222,6 +5279,10 @@ try { ...@@ -5222,6 +5279,10 @@ try {
getEntries(deviceId: string, keyPrefix: string, callback: AsyncCallback&lt;Entry[]&gt;): void getEntries(deviceId: string, keyPrefix: string, callback: AsyncCallback&lt;Entry[]&gt;): void
Obtains all KV pairs that match the specified device ID and key prefix. This API uses an asynchronous callback to return the result. Obtains all KV pairs that match the specified device ID and key prefix. This API uses an asynchronous callback to return the result.
> **NOTE**<br/>
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
...@@ -5245,7 +5306,6 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -5245,7 +5306,6 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
**Example** **Example**
```js ```js
let kvStore;
try { try {
let entries = []; let entries = [];
for (var i = 0; i < 10; i++) { for (var i = 0; i < 10; i++) {
...@@ -5259,25 +5319,25 @@ try { ...@@ -5259,25 +5319,25 @@ try {
} }
entries.push(entry); entries.push(entry);
} }
console.log(`entries : ${entries}`); console.info(`entries : ${entries}`);
kvStore.putBatch(entries, async function (err, data) { kvStore.putBatch(entries, async function (err, data) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Succeeded in putting batch'); console.info('Succeeded in putting batch');
kvStore.getEntries('localDeviceId', 'batch_test_string_key', function (err, entries) { kvStore.getEntries('localDeviceId', 'batch_test_string_key', function (err, entries) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to get entries.code is ${err.code},message is ${err.message}`); console.error(`Failed to get entries.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Succeeded in getting entries'); console.info('Succeeded in getting entries');
console.log(`entries.length: ${entries.length}`); console.info(`entries.length: ${entries.length}`);
console.log(`entries[0]: ${entries[0]}`); console.info(`entries[0]: ${entries[0]}`);
}); });
}); });
} catch (e) { } catch (e) {
console.error(`Fail to put batch.code is ${e.code},message is ${e.message}`); console.error(`Failed to put batch.code is ${e.code},message is ${e.message}`);
} }
``` ```
...@@ -5286,6 +5346,10 @@ try { ...@@ -5286,6 +5346,10 @@ try {
getEntries(deviceId: string, keyPrefix: string): Promise&lt;Entry[]&gt; getEntries(deviceId: string, keyPrefix: string): Promise&lt;Entry[]&gt;
Obtains all KV pairs that match the specified device ID and key prefix. This API uses a promise to return the result. Obtains all KV pairs that match the specified device ID and key prefix. This API uses a promise to return the result.
> **NOTE**<br/>
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
...@@ -5314,7 +5378,6 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -5314,7 +5378,6 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
**Example** **Example**
```js ```js
let kvStore;
try { try {
let entries = []; let entries = [];
for (var i = 0; i < 10; i++) { for (var i = 0; i < 10; i++) {
...@@ -5328,23 +5391,23 @@ try { ...@@ -5328,23 +5391,23 @@ try {
} }
entries.push(entry); entries.push(entry);
} }
console.log(`entries: ${entries}`); console.info(`entries: ${entries}`);
kvStore.putBatch(entries).then(async (err) => { kvStore.putBatch(entries).then(async (err) => {
console.log('Succeeded in putting batch'); console.info('Succeeded in putting batch');
kvStore.getEntries('localDeviceId', 'batch_test_string_key').then((entries) => { kvStore.getEntries('localDeviceId', 'batch_test_string_key').then((entries) => {
console.log('Succeeded in getting entries'); console.info('Succeeded in getting entries');
console.log(`entries.length: ${entries.length}`); console.info(`entries.length: ${entries.length}`);
console.log(`entries[0]: ${entries[0]}`); console.info(`entries[0]: ${entries[0]}`);
console.log(`entries[0].value: ${entries[0].value}`); console.info(`entries[0].value: ${entries[0].value}`);
console.log(`entries[0].value.value: ${entries[0].value.value}`); console.info(`entries[0].value.value: ${entries[0].value.value}`);
}).catch((err) => { }).catch((err) => {
console.error(`Fail to get entries.code is ${err.code},message is ${err.message}`); console.error(`Failed to get entries.code is ${err.code},message is ${err.message}`);
}); });
}).catch((err) => { }).catch((err) => {
console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
}); });
} catch (e) { } catch (e) {
console.error(`Fail to put batch.code is ${e.code},message is ${e.message}`); console.error(`Failed to put batch.code is ${e.code},message is ${e.message}`);
} }
``` ```
...@@ -5375,7 +5438,6 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -5375,7 +5438,6 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
**Example** **Example**
```js ```js
let kvStore;
try { try {
var arr = new Uint8Array([21, 31]); var arr = new Uint8Array([21, 31]);
let entries = []; let entries = [];
...@@ -5390,23 +5452,23 @@ try { ...@@ -5390,23 +5452,23 @@ try {
} }
entries.push(entry); entries.push(entry);
} }
console.log(`entries: {entries}`); console.info(`entries: {entries}`);
kvStore.putBatch(entries, async function (err, data) { kvStore.putBatch(entries, async function (err, data) {
console.log('Succeeded in putting Batch'); console.info('Succeeded in putting Batch');
const query = new distributedKVStore.Query(); const query = new distributedKVStore.Query();
query.prefixKey("batch_test"); query.prefixKey("batch_test");
kvStore.getEntries(query, function (err, entries) { kvStore.getEntries(query, function (err, entries) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Succeeded in getting Entries'); console.info('Succeeded in getting Entries');
console.log(`entries.length: ${entries.length}`); console.info(`entries.length: ${entries.length}`);
console.log(`entries[0]: ${entries[0]}`); console.info(`entries[0]: ${entries[0]}`);
}); });
}); });
} catch (e) { } catch (e) {
console.error(`Fail to get Entries.code is ${e.code},message is ${e.message}`); console.error(`Failed to get Entries.code is ${e.code},message is ${e.message}`);
} }
``` ```
...@@ -5442,7 +5504,6 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -5442,7 +5504,6 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
**Example** **Example**
```js ```js
let kvStore;
try { try {
var arr = new Uint8Array([21, 31]); var arr = new Uint8Array([21, 31]);
let entries = []; let entries = [];
...@@ -5457,22 +5518,22 @@ try { ...@@ -5457,22 +5518,22 @@ try {
} }
entries.push(entry); entries.push(entry);
} }
console.log(`entries: {entries}`); console.info(`entries: {entries}`);
kvStore.putBatch(entries).then(async (err) => { kvStore.putBatch(entries).then(async (err) => {
console.log('Succeeded in putting Batch'); console.info('Succeeded in putting Batch');
const query = new distributedKVStore.Query(); const query = new distributedKVStore.Query();
query.prefixKey("batch_test"); query.prefixKey("batch_test");
kvStore.getEntries(query).then((entries) => { kvStore.getEntries(query).then((entries) => {
console.log('Succeeded in getting Entries'); console.info('Succeeded in getting Entries');
}).catch((err) => { }).catch((err) => {
console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`);
}); });
}).catch((err) => { }).catch((err) => {
console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`) console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`)
}); });
console.log('Succeeded in getting Entries'); console.info('Succeeded in getting Entries');
} catch (e) { } catch (e) {
console.error(`Fail to get Entries.code is ${e.code},message is ${e.message}`); console.error(`Failed to get Entries.code is ${e.code},message is ${e.message}`);
} }
``` ```
...@@ -5481,6 +5542,10 @@ try { ...@@ -5481,6 +5542,10 @@ try {
getEntries(deviceId: string, query: Query, callback: AsyncCallback&lt;Entry[]&gt;): void getEntries(deviceId: string, query: Query, callback: AsyncCallback&lt;Entry[]&gt;): void
Obtains the KV pairs that match the specified device ID and **Query** object. This API uses an asynchronous callback to return the result. Obtains the KV pairs that match the specified device ID and **Query** object. This API uses an asynchronous callback to return the result.
> **NOTE**<br/>
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
...@@ -5504,7 +5569,6 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -5504,7 +5569,6 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
**Example** **Example**
```js ```js
let kvStore;
try { try {
var arr = new Uint8Array([21, 31]); var arr = new Uint8Array([21, 31]);
let entries = []; let entries = [];
...@@ -5519,29 +5583,29 @@ try { ...@@ -5519,29 +5583,29 @@ try {
} }
entries.push(entry); entries.push(entry);
} }
console.log(`entries: ${entries}`); console.info(`entries: ${entries}`);
kvStore.putBatch(entries, async function (err, data) { kvStore.putBatch(entries, async function (err, data) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Succeeded in putting batch'); console.info('Succeeded in putting batch');
var query = new distributedKVStore.Query(); var query = new distributedKVStore.Query();
query.deviceId('localDeviceId'); query.deviceId('localDeviceId');
query.prefixKey("batch_test"); query.prefixKey("batch_test");
kvStore.getEntries('localDeviceId', query, function (err, entries) { kvStore.getEntries('localDeviceId', query, function (err, entries) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to get entries.code is ${err.code},message is ${err.message}`); console.error(`Failed to get entries.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Succeeded in getting entries'); console.info('Succeeded in getting entries');
console.log(`entries.length: ${entries.length}`); console.info(`entries.length: ${entries.length}`);
console.log(`entries[0]: ${entries[0]}`); console.info(`entries[0]: ${entries[0]}`);
}) })
}); });
console.log('Succeeded in getting entries'); console.info('Succeeded in getting entries');
} catch (e) { } catch (e) {
console.error(`Fail to get entries.code is ${e.code},message is ${e.message}`); console.error(`Failed to get entries.code is ${e.code},message is ${e.message}`);
} }
``` ```
...@@ -5550,6 +5614,10 @@ try { ...@@ -5550,6 +5614,10 @@ try {
getEntries(deviceId: string, query: Query): Promise&lt;Entry[]&gt; getEntries(deviceId: string, query: Query): Promise&lt;Entry[]&gt;
Obtains the KV pairs that match the specified device ID and **Query** object. This API uses a promise to return the result. Obtains the KV pairs that match the specified device ID and **Query** object. This API uses a promise to return the result.
> **NOTE**<br/>
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
...@@ -5578,7 +5646,6 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -5578,7 +5646,6 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
**Example** **Example**
```js ```js
let kvStore;
try { try {
var arr = new Uint8Array([21, 31]); var arr = new Uint8Array([21, 31]);
let entries = []; let entries = [];
...@@ -5593,23 +5660,23 @@ try { ...@@ -5593,23 +5660,23 @@ try {
} }
entries.push(entry); entries.push(entry);
} }
console.log(`entries: ${entries}`); console.info(`entries: ${entries}`);
kvStore.putBatch(entries).then(async (err) => { kvStore.putBatch(entries).then(async (err) => {
console.log('Succeeded in putting batch'); console.info('Succeeded in putting batch');
var query = new distributedKVStore.Query(); var query = new distributedKVStore.Query();
query.deviceId('localDeviceId'); query.deviceId('localDeviceId');
query.prefixKey("batch_test"); query.prefixKey("batch_test");
kvStore.getEntries('localDeviceId', query).then((entries) => { kvStore.getEntries('localDeviceId', query).then((entries) => {
console.log('Succeeded in getting entries'); console.info('Succeeded in getting entries');
}).catch((err) => { }).catch((err) => {
console.error(`Fail to get entries.code is ${err.code},message is ${err.message}`); console.error(`Failed to get entries.code is ${err.code},message is ${err.message}`);
}); });
}).catch((err) => { }).catch((err) => {
console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
}); });
console.log('Succeeded in getting entries'); console.info('Succeeded in getting entries');
} catch (e) { } catch (e) {
console.error(`Fail to get entries.code is ${e.code},message is ${e.message}`); console.error(`Failed to get entries.code is ${e.code},message is ${e.message}`);
} }
``` ```
...@@ -5634,13 +5701,13 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -5634,13 +5701,13 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
| ID| **Error Message** | | ID| **Error Message** |
| ------------ | -------------------------------------- | | ------------ | -------------------------------------- |
| 15100001 | Over max limits. |
| 15100003 | Database corrupted. | | 15100003 | Database corrupted. |
| 15100005 | Database or result set already closed. | | 15100005 | Database or result set already closed. |
**Example** **Example**
```js ```js
let kvStore;
try { try {
let resultSet; let resultSet;
let entries = []; let entries = [];
...@@ -5657,23 +5724,23 @@ try { ...@@ -5657,23 +5724,23 @@ try {
} }
kvStore.putBatch(entries, async function (err, data) { kvStore.putBatch(entries, async function (err, data) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Succeeded in putting batch'); console.info('Succeeded in putting batch');
kvStore.getResultSet('batch_test_string_key', async function (err, result) { kvStore.getResultSet('batch_test_string_key', async function (err, result) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Succeeded in getting result set'); console.info('Succeeded in getting result set');
resultSet = result; resultSet = result;
kvStore.closeResultSet(resultSet, function (err, data) { kvStore.closeResultSet(resultSet, function (err, data) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Succeeded in closing result set'); console.info('Succeeded in closing result set');
}) })
}); });
}); });
...@@ -5708,13 +5775,13 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -5708,13 +5775,13 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
| ID| **Error Message** | | ID| **Error Message** |
| ------------ | -------------------------------------- | | ------------ | -------------------------------------- |
| 15100001 | Over max limits. |
| 15100003 | Database corrupted. | | 15100003 | Database corrupted. |
| 15100005 | Database or result set already closed. | | 15100005 | Database or result set already closed. |
**Example** **Example**
```js ```js
let kvStore;
try { try {
let resultSet; let resultSet;
let entries = []; let entries = [];
...@@ -5730,20 +5797,20 @@ try { ...@@ -5730,20 +5797,20 @@ try {
entries.push(entry); entries.push(entry);
} }
kvStore.putBatch(entries).then(async (err) => { kvStore.putBatch(entries).then(async (err) => {
console.log('Succeeded in putting batch'); console.info('Succeeded in putting batch');
}).catch((err) => { }).catch((err) => {
console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
}); });
kvStore.getResultSet('batch_test_string_key').then((result) => { kvStore.getResultSet('batch_test_string_key').then((result) => {
console.log('Succeeded in getting result set'); console.info('Succeeded in getting result set');
resultSet = result; resultSet = result;
}).catch((err) => { }).catch((err) => {
console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`);
}); });
kvStore.closeResultSet(resultSet).then((err) => { kvStore.closeResultSet(resultSet).then((err) => {
console.log('Succeeded in closing result set'); console.info('Succeeded in closing result set');
}).catch((err) => { }).catch((err) => {
console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`);
}); });
} catch (e) { } catch (e) {
console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`); console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`);
...@@ -5755,6 +5822,10 @@ try { ...@@ -5755,6 +5822,10 @@ try {
getResultSet(deviceId: string, keyPrefix: string, callback: AsyncCallback&lt;KVStoreResultSet&gt;): void getResultSet(deviceId: string, keyPrefix: string, callback: AsyncCallback&lt;KVStoreResultSet&gt;): void
Obtains a **KVStoreResultSet** object that matches the specified device ID and key prefix. This API uses an asynchronous callback to return the result. Obtains a **KVStoreResultSet** object that matches the specified device ID and key prefix. This API uses an asynchronous callback to return the result.
> **NOTE**<br/>
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
...@@ -5764,7 +5835,7 @@ Obtains a **KVStoreResultSet** object that matches the specified device ID and k ...@@ -5764,7 +5835,7 @@ Obtains a **KVStoreResultSet** object that matches the specified device ID and k
| --------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | --------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| deviceId | string | Yes | ID of the target device. | | deviceId | string | Yes | ID of the target device. |
| keyPrefix | string | Yes | Key prefix to match. | | keyPrefix | string | Yes | Key prefix to match. |
| callback | AsyncCallback&lt;[KVStoreResultSet](#kvstoreresultset)&gt; | Yes | Callback invoked to return the **KVStoreResultSet** object that matches the specified device ID and key prefix.| | callback | AsyncCallback&lt;[KVStoreResultSet](#kvstoreresultset)&gt; | Yes | Callback invoked to return the **KvStoreResultSet** object that matches the specified device ID and key prefix.|
**Error codes** **Error codes**
...@@ -5772,32 +5843,32 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -5772,32 +5843,32 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
| ID| **Error Message** | | ID| **Error Message** |
| ------------ | -------------------------------------- | | ------------ | -------------------------------------- |
| 15100001 | Over max limits. |
| 15100003 | Database corrupted. | | 15100003 | Database corrupted. |
| 15100005 | Database or result set already closed. | | 15100005 | Database or result set already closed. |
**Example** **Example**
```js ```js
let kvStore;
try { try {
let resultSet; let resultSet;
kvStore.getResultSet('localDeviceId', 'batch_test_string_key', async function (err, result) { kvStore.getResultSet('localDeviceId', 'batch_test_string_key', async function (err, result) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to get resultSet.code is ${err.code},message is ${err.message}`); console.error(`Failed to get resultSet.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Succeeded in getting resultSet'); console.info('Succeeded in getting resultSet');
resultSet = result; resultSet = result;
kvStore.closeResultSet(resultSet, function (err, data) { kvStore.closeResultSet(resultSet, function (err, data) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to close resultSet.code is ${err.code},message is ${err.message}`); console.error(`Failed to close resultSet.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Succeeded in closing resultSet'); console.info('Succeeded in closing resultSet');
}) })
}); });
} catch (e) { } catch (e) {
console.error(`Fail to get resultSet.code is ${e.code},message is ${e.message}`); console.error(`Failed to get resultSet.code is ${e.code},message is ${e.message}`);
} }
``` ```
...@@ -5806,6 +5877,10 @@ try { ...@@ -5806,6 +5877,10 @@ try {
getResultSet(deviceId: string, keyPrefix: string): Promise&lt;KVStoreResultSet&gt; getResultSet(deviceId: string, keyPrefix: string): Promise&lt;KVStoreResultSet&gt;
Obtains a **KVStoreResultSet** object that matches the specified device ID and key prefix. This API uses a promise to return the result. Obtains a **KVStoreResultSet** object that matches the specified device ID and key prefix. This API uses a promise to return the result.
> **NOTE**<br/>
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
...@@ -5820,7 +5895,7 @@ Obtains a **KVStoreResultSet** object that matches the specified device ID and k ...@@ -5820,7 +5895,7 @@ Obtains a **KVStoreResultSet** object that matches the specified device ID and k
| Type | Description | | Type | Description |
| ------------------------------------------------------ | ------------------------------------------------------------ | | ------------------------------------------------------ | ------------------------------------------------------------ |
| Promise&lt;[KVStoreResultSet](#kvstoreresultset)&gt; | Promise used to return the **KVStoreResultSet** object that matches the specified device ID and key prefix.| | Promise&lt;[KVStoreResultSet](#kvstoreresultset)&gt; | Promise used to return the **KvStoreResultSet** object that matches the specified device ID and key prefix.|
**Error codes** **Error codes**
...@@ -5828,28 +5903,28 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -5828,28 +5903,28 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
| ID| **Error Message** | | ID| **Error Message** |
| ------------ | -------------------------------------- | | ------------ | -------------------------------------- |
| 15100001 | Over max limits. |
| 15100003 | Database corrupted. | | 15100003 | Database corrupted. |
| 15100005 | Database or result set already closed. | | 15100005 | Database or result set already closed. |
**Example** **Example**
```js ```js
let kvStore;
try { try {
let resultSet; let resultSet;
kvStore.getResultSet('localDeviceId', 'batch_test_string_key').then((result) => { kvStore.getResultSet('localDeviceId', 'batch_test_string_key').then((result) => {
console.log('Succeeded in getting resultSet'); console.info('Succeeded in getting resultSet');
resultSet = result; resultSet = result;
}).catch((err) => { }).catch((err) => {
console.error(`Fail to get resultSet.code is ${err.code},message is ${err.message}`); console.error(`Failed to get resultSet.code is ${err.code},message is ${err.message}`);
}); });
kvStore.closeResultSet(resultSet).then((err) => { kvStore.closeResultSet(resultSet).then((err) => {
console.log('Succeeded in closing resultSet'); console.info('Succeeded in closing resultSet');
}).catch((err) => { }).catch((err) => {
console.error(`Fail to close resultSet.code is ${err.code},message is ${err.message}`); console.error(`Failed to close resultSet.code is ${err.code},message is ${err.message}`);
}); });
} catch (e) { } catch (e) {
console.error(`Fail to get resultSet.code is ${e.code},message is ${e.message}`); console.error(`Failed to get resultSet.code is ${e.code},message is ${e.message}`);
} }
``` ```
...@@ -5858,6 +5933,10 @@ try { ...@@ -5858,6 +5933,10 @@ try {
getResultSet(deviceId: string, query: Query, callback: AsyncCallback&lt;KVStoreResultSet&gt;): void getResultSet(deviceId: string, query: Query, callback: AsyncCallback&lt;KVStoreResultSet&gt;): void
Obtains a **KVStoreResultSet** object that matches the specified device ID and **Query** object. This API uses an asynchronous callback to return the result. Obtains a **KVStoreResultSet** object that matches the specified device ID and **Query** object. This API uses an asynchronous callback to return the result.
> **NOTE**<br/>
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
...@@ -5867,7 +5946,7 @@ Obtains a **KVStoreResultSet** object that matches the specified device ID and * ...@@ -5867,7 +5946,7 @@ Obtains a **KVStoreResultSet** object that matches the specified device ID and *
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| deviceId | string | Yes | ID of the device to which the **KVStoreResultSet** object belongs. | | deviceId | string | Yes | ID of the device to which the **KVStoreResultSet** object belongs. |
| query | [Query](#query) | Yes | **Query** object to match. | | query | [Query](#query) | Yes | **Query** object to match. |
| callback | AsyncCallback&lt;[KVStoreResultSet](#kvstoreresultset)&gt; | Yes | Callback invoked to return the **KVStoreResultSet** object that matches the specified device ID and **Query** object.| | callback | AsyncCallback&lt;[KVStoreResultSet](#kvstoreresultset)&gt; | Yes | Callback invoked to return the **KvStoreResultSet** object that matches the specified device ID and **Query** object.|
**Error codes** **Error codes**
...@@ -5875,13 +5954,13 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -5875,13 +5954,13 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
| ID| **Error Message** | | ID| **Error Message** |
| ------------ | -------------------------------------- | | ------------ | -------------------------------------- |
| 15100001 | Over max limits. |
| 15100003 | Database corrupted. | | 15100003 | Database corrupted. |
| 15100005 | Database or result set already closed. | | 15100005 | Database or result set already closed. |
**Example** **Example**
```js ```js
let kvStore;
try { try {
let resultSet; let resultSet;
let entries = []; let entries = [];
...@@ -5898,30 +5977,30 @@ try { ...@@ -5898,30 +5977,30 @@ try {
} }
kvStore.putBatch(entries, async function (err, data) { kvStore.putBatch(entries, async function (err, data) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Succeeded in putting batch'); console.info('Succeeded in putting batch');
const query = new distributedKVStore.Query(); const query = new distributedKVStore.Query();
query.prefixKey("batch_test"); query.prefixKey("batch_test");
kvStore.getResultSet('localDeviceId', query, async function (err, result) { kvStore.getResultSet('localDeviceId', query, async function (err, result) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to get resultSet.code is ${err.code},message is ${err.message}`); console.error(`Failed to get resultSet.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Succeeded in getting resultSet'); console.info('Succeeded in getting resultSet');
resultSet = result; resultSet = result;
kvStore.closeResultSet(resultSet, function (err, data) { kvStore.closeResultSet(resultSet, function (err, data) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to close resultSet.code is ${err.code},message is ${err.message}`); console.error(`Failed to close resultSet.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Succeeded in closing resultSet'); console.info('Succeeded in closing resultSet');
}) })
}); });
}); });
} catch (e) { } catch (e) {
console.error(`Fail to get resultSet.code is ${e.code},message is ${e.message}`); console.error(`Failed to get resultSet.code is ${e.code},message is ${e.message}`);
} }
``` ```
...@@ -5930,6 +6009,10 @@ try { ...@@ -5930,6 +6009,10 @@ try {
getResultSet(deviceId: string, query: Query): Promise&lt;KVStoreResultSet&gt; getResultSet(deviceId: string, query: Query): Promise&lt;KVStoreResultSet&gt;
Obtains a **KVStoreResultSet** object that matches the specified device ID and **Query** object. This API uses a promise to return the result. Obtains a **KVStoreResultSet** object that matches the specified device ID and **Query** object. This API uses a promise to return the result.
> **NOTE**<br/>
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
...@@ -5944,7 +6027,7 @@ Obtains a **KVStoreResultSet** object that matches the specified device ID and * ...@@ -5944,7 +6027,7 @@ Obtains a **KVStoreResultSet** object that matches the specified device ID and *
| Type | Description | | Type | Description |
| ------------------------------------------------------ | ------------------------------------------------------------ | | ------------------------------------------------------ | ------------------------------------------------------------ |
| Promise&lt;[KVStoreResultSet](#kvstoreresultset)&gt; | Promise used to return the **KVStoreResultSet** object that matches the specified device ID and **Query** object.| | Promise&lt;[KVStoreResultSet](#kvstoreresultset)&gt; | Promise used to return the **KvStoreResultSet** object that matches the specified device ID and **Query** object.|
**Error codes** **Error codes**
...@@ -5952,13 +6035,13 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -5952,13 +6035,13 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
| ID| **Error Message** | | ID| **Error Message** |
| ------------ | -------------------------------------- | | ------------ | -------------------------------------- |
| 15100001 | Over max limits. |
| 15100003 | Database corrupted. | | 15100003 | Database corrupted. |
| 15100005 | Database or result set already closed. | | 15100005 | Database or result set already closed. |
**Example** **Example**
```js ```js
let kvStore;
try { try {
let resultSet; let resultSet;
let entries = []; let entries = [];
...@@ -5974,28 +6057,28 @@ try { ...@@ -5974,28 +6057,28 @@ try {
entries.push(entry); entries.push(entry);
} }
kvStore.putBatch(entries).then(async (err) => { kvStore.putBatch(entries).then(async (err) => {
console.log('Succeeded in putting batch'); console.info('Succeeded in putting batch');
}).catch((err) => { }).catch((err) => {
console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
}); });
const query = new distributedKVStore.Query(); const query = new distributedKVStore.Query();
query.prefixKey("batch_test"); query.prefixKey("batch_test");
kvStore.getResultSet('localDeviceId', query).then((result) => { kvStore.getResultSet('localDeviceId', query).then((result) => {
console.log('Succeeded in getting resultSet'); console.info('Succeeded in getting resultSet');
resultSet = result; resultSet = result;
}).catch((err) => { }).catch((err) => {
console.error(`Fail to get resultSet.code is ${err.code},message is ${err.message}`); console.error(`Failed to get resultSet.code is ${err.code},message is ${err.message}`);
}); });
query.deviceId('localDeviceId'); query.deviceId('localDeviceId');
console.log("GetResultSet " + query.getSqlLike()); console.info("GetResultSet " + query.getSqlLike());
kvStore.closeResultSet(resultSet).then((err) => { kvStore.closeResultSet(resultSet).then((err) => {
console.log('Succeeded in closing resultSet'); console.info('Succeeded in closing resultSet');
}).catch((err) => { }).catch((err) => {
console.error(`Fail to close resultSet.code is ${err.code},message is ${err.message}`); console.error(`Failed to close resultSet.code is ${err.code},message is ${err.message}`);
}); });
} catch (e) { } catch (e) {
console.error(`Fail to get resultSet.code is ${e.code},message is ${e.message}`); console.error(`Failed to get resultSet.code is ${e.code},message is ${e.message}`);
} }
``` ```
...@@ -6025,13 +6108,13 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -6025,13 +6108,13 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
| ID| **Error Message** | | ID| **Error Message** |
| ------------ | -------------------------------------- | | ------------ | -------------------------------------- |
| 15100001 | Over max limits. |
| 15100003 | Database corrupted. | | 15100003 | Database corrupted. |
| 15100005 | Database or result set already closed. | | 15100005 | Database or result set already closed. |
**Example** **Example**
```js ```js
let kvStore;
try { try {
let resultSet; let resultSet;
let entries = []; let entries = [];
...@@ -6047,17 +6130,17 @@ try { ...@@ -6047,17 +6130,17 @@ try {
entries.push(entry); entries.push(entry);
} }
kvStore.putBatch(entries).then(async (err) => { kvStore.putBatch(entries).then(async (err) => {
console.log('Succeeded in putting batch'); console.info('Succeeded in putting batch');
}).catch((err) => { }).catch((err) => {
console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
}); });
const query = new distributedKVStore.Query(); const query = new distributedKVStore.Query();
query.prefixKey("batch_test"); query.prefixKey("batch_test");
kvStore.getResultSet(query).then((result) => { kvStore.getResultSet(query).then((result) => {
console.log('Succeeded in getting result set'); console.info('Succeeded in getting result set');
resultSet = result; resultSet = result;
}).catch((err) => { }).catch((err) => {
console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`);
}); });
} catch (e) { } catch (e) {
console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`); console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`);
...@@ -6066,24 +6149,23 @@ try { ...@@ -6066,24 +6149,23 @@ try {
### getResultSet ### getResultSet
getResultSet(deviceId: string, query: Query): Promise&lt;KVStoreResultSet&gt; getResultSet(query: Query, callback:AsyncCallback&lt;KVStoreResultSet&gt;): void
Obtains a **KVStoreResultSet** object that matches the specified device ID and **Query** object. This API uses a promise to return the result. Obtains a **KVStoreResultSet** object that matches the specified **Query** object for this device. This API uses an asynchronous callback to return the result.
> **NOTE**<br/>
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **System capability**: SystemCapability.DistributedDataManager.KVStore.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | -------------- | ---- | ---------------------------------- | | -------- | -------------- | ---- | ---------------------------------- |
| deviceId | string | Yes | ID of the device to which the **KVStoreResultSet** object belongs.|
| query | [Query](#query) | Yes | **Query** object to match. | | query | [Query](#query) | Yes | **Query** object to match. |
| callback | AsyncCallback&lt;[KVStoreResultSet](#kvstoreresultset)&gt; | Yes | Callback invoked to return the **KVStoreResultSet** object obtained. |
**Return value**
| Type | Description |
| ---------------------------------------------------- | ------------------------------------------------------------ |
| Promise&lt;[KVStoreResultSet](#kvstoreresultset)&gt; | Promise used to return the **KVStoreResultSet** object obtained.|
**Error codes** **Error codes**
...@@ -6091,13 +6173,13 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -6091,13 +6173,13 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
| ID| **Error Message** | | ID| **Error Message** |
| ------------ | -------------------------------------- | | ------------ | -------------------------------------- |
| 15100001 | Over max limits. |
| 15100003 | Database corrupted. | | 15100003 | Database corrupted. |
| 15100005 | Database or result set already closed. | | 15100005 | Database or result set already closed. |
**Example** **Example**
```js ```js
let kvStore;
try { try {
let resultSet; let resultSet;
let entries = []; let entries = [];
...@@ -6112,29 +6194,32 @@ try { ...@@ -6112,29 +6194,32 @@ try {
} }
entries.push(entry); entries.push(entry);
} }
kvStore.putBatch(entries).then(async (err) => { kvStore.putBatch(entries, async function (err, data) {
console.log('Succeeded in putting batch'); if (err != undefined) {
}).catch((err) => { console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); return;
}); }
const query = new distributedKVStore.Query(); console.info('Succeeded in putting batch');
query.prefixKey("batch_test"); const query = new distributedKVStore.Query();
kvStore.getResultSet('localDeviceId', query).then((result) => { query.prefixKey("batch_test");
console.log('Succeeded in getting resultSet'); kvStore.getResultSet(query, async function (err, result) {
resultSet = result; if (err != undefined) {
}).catch((err) => { console.error(`Failed to get resultSet.code is ${err.code},message is ${err.message}`);
console.error(`Fail to get resultSet.code is ${err.code},message is ${err.message}`); return;
}); }
query.deviceId('localDeviceId'); console.info('Succeeded in getting resultSet');
console.log("GetResultSet " + query.getSqlLike()); resultSet = result;
kvStore.closeResultSet(resultSet).then((err) => { kvStore.closeResultSet(resultSet, function (err, data) {
console.log('Succeeded in closing resultSet'); if (err != undefined) {
}).catch((err) => { console.error(`Failed to close resultSet.code is ${err.code},message is ${err.message}`);
console.error(`Fail to close resultSet.code is ${err.code},message is ${err.message}`); return;
}
console.info('Succeeded in closing resultSet');
})
});
}); });
} catch (e) { } catch (e) {
console.error(`Fail to get resultSet.code is ${e.code},message is ${e.message}`); console.error(`Failed to get resultSet.code is ${e.code},message is ${e.message}`);
} }
``` ```
...@@ -6152,7 +6237,7 @@ Obtains a **KVStoreResultSet** object that matches the specified predicate objec ...@@ -6152,7 +6237,7 @@ Obtains a **KVStoreResultSet** object that matches the specified predicate objec
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | **DataSharePredicates** object that specifies the **KVStoreResultSet** object to obtain. If this parameter is **null**, define the processing logic. | | predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | **DataSharePredicates** object that specifies the KV pairs to delete. If this parameter is **null**, define the processing logic. |
| callback | AsyncCallback&lt;[KVStoreResultSet](#kvstoreresultset)&gt; | Yes | Callback invoked to return the **KVStoreResultSet** object obtained.| | callback | AsyncCallback&lt;[KVStoreResultSet](#kvstoreresultset)&gt; | Yes | Callback invoked to return the **KVStoreResultSet** object obtained.|
**Error codes** **Error codes**
...@@ -6161,6 +6246,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -6161,6 +6246,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
| ID| **Error Message** | | ID| **Error Message** |
| ------------ | -------------------------------------- | | ------------ | -------------------------------------- |
| 15100001 | Over max limits. |
| 15100003 | Database corrupted. | | 15100003 | Database corrupted. |
| 15100005 | Database or result set already closed. | | 15100005 | Database or result set already closed. |
...@@ -6169,24 +6255,23 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -6169,24 +6255,23 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
```js ```js
import dataSharePredicates from '@ohos.data.dataSharePredicates'; import dataSharePredicates from '@ohos.data.dataSharePredicates';
let kvStore;
try { try {
let resultSet; let resultSet;
let predicates = new dataSharePredicates.DataSharePredicates(); let predicates = new dataSharePredicates.DataSharePredicates();
predicates.prefixKey("batch_test_string_key"); predicates.prefixKey("batch_test_string_key");
kvStore.getResultSet(predicates, async function (err, result) { kvStore.getResultSet(predicates, async function (err, result) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Succeeded in getting result set'); console.info('Succeeded in getting result set');
resultSet = result; resultSet = result;
kvStore.closeResultSet(resultSet, function (err, data) { kvStore.closeResultSet(resultSet, function (err, data) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Succeeded in closing result set'); console.info('Succeeded in closing result set');
}) })
}); });
} catch (e) { } catch (e) {
...@@ -6208,7 +6293,7 @@ Obtains a **KVStoreResultSet** object that matches the specified predicate objec ...@@ -6208,7 +6293,7 @@ Obtains a **KVStoreResultSet** object that matches the specified predicate objec
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------- | | ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------- |
| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | **DataSharePredicates** object that specifies the **KVStoreResultSet** object to obtain. If this parameter is **null**, define the processing logic.| | predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | **DataSharePredicates** object that specifies the KV pairs to delete. If this parameter is **null**, define the processing logic.|
**Return value** **Return value**
...@@ -6222,6 +6307,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -6222,6 +6307,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
| ID| **Error Message** | | ID| **Error Message** |
| ------------ | -------------------------------------- | | ------------ | -------------------------------------- |
| 15100001 | Over max limits. |
| 15100003 | Database corrupted. | | 15100003 | Database corrupted. |
| 15100005 | Database or result set already closed. | | 15100005 | Database or result set already closed. |
...@@ -6230,21 +6316,20 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -6230,21 +6316,20 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
```js ```js
import dataSharePredicates from '@ohos.data.dataSharePredicates'; import dataSharePredicates from '@ohos.data.dataSharePredicates';
let kvStore;
try { try {
let resultSet; let resultSet;
let predicates = new dataSharePredicates.DataSharePredicates(); let predicates = new dataSharePredicates.DataSharePredicates();
predicates.prefixKey("batch_test_string_key"); predicates.prefixKey("batch_test_string_key");
kvStore.getResultSet(predicates).then((result) => { kvStore.getResultSet(predicates).then((result) => {
console.log('Succeeded in getting result set'); console.info('Succeeded in getting result set');
resultSet = result; resultSet = result;
}).catch((err) => { }).catch((err) => {
console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`);
}); });
kvStore.closeResultSet(resultSet).then((err) => { kvStore.closeResultSet(resultSet).then((err) => {
console.log('Succeeded in closing result set'); console.info('Succeeded in closing result set');
}).catch((err) => { }).catch((err) => {
console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`);
}); });
} catch (e) { } catch (e) {
console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`); console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`);
...@@ -6256,6 +6341,10 @@ try { ...@@ -6256,6 +6341,10 @@ try {
getResultSet(deviceId: string, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback&lt;KVStoreResultSet&gt;): void getResultSet(deviceId: string, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback&lt;KVStoreResultSet&gt;): void
Obtains a **KVStoreResultSet** object that matches the specified predicate object and device ID. This API uses an asynchronous callback to return the result. Obtains a **KVStoreResultSet** object that matches the specified predicate object and device ID. This API uses an asynchronous callback to return the result.
> **NOTE**<br/>
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System API**: This is a system API. **System API**: This is a system API.
...@@ -6275,6 +6364,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -6275,6 +6364,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
| ID| **Error Message** | | ID| **Error Message** |
| ------------ | -------------------------------------- | | ------------ | -------------------------------------- |
| 15100001 | Over max limits. |
| 15100003 | Database corrupted. | | 15100003 | Database corrupted. |
| 15100005 | Database or result set already closed. | | 15100005 | Database or result set already closed. |
...@@ -6283,24 +6373,23 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -6283,24 +6373,23 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
```js ```js
import dataSharePredicates from '@ohos.data.dataSharePredicates'; import dataSharePredicates from '@ohos.data.dataSharePredicates';
let kvStore;
try { try {
let resultSet; let resultSet;
let predicates = new dataSharePredicates.DataSharePredicates(); let predicates = new dataSharePredicates.DataSharePredicates();
predicates.prefixKey("batch_test_string_key"); predicates.prefixKey("batch_test_string_key");
kvStore.getResultSet('localDeviceId', predicates, async function (err, result) { kvStore.getResultSet('localDeviceId', predicates, async function (err, result) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Succeeded in getting result set'); console.info('Succeeded in getting result set');
resultSet = result; resultSet = result;
kvStore.closeResultSet(resultSet, function (err, data) { kvStore.closeResultSet(resultSet, function (err, data) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Succeeded in closing result set'); console.info('Succeeded in closing result set');
}) })
}); });
} catch (e) { } catch (e) {
...@@ -6313,6 +6402,10 @@ try { ...@@ -6313,6 +6402,10 @@ try {
getResultSet(deviceId: string, predicates: dataSharePredicates.DataSharePredicates): Promise&lt;KVStoreResultSet&gt; getResultSet(deviceId: string, predicates: dataSharePredicates.DataSharePredicates): Promise&lt;KVStoreResultSet&gt;
Obtains a **KVStoreResultSet** object that matches the specified predicate object and device ID. This API uses a promise to return the result. Obtains a **KVStoreResultSet** object that matches the specified predicate object and device ID. This API uses a promise to return the result.
> **NOTE**<br/>
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System API**: This is a system API. **System API**: This is a system API.
...@@ -6323,7 +6416,7 @@ Obtains a **KVStoreResultSet** object that matches the specified predicate objec ...@@ -6323,7 +6416,7 @@ Obtains a **KVStoreResultSet** object that matches the specified predicate objec
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------- | | ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------- |
| deviceId | string | Yes | ID of the target device. | | deviceId | string | Yes | ID of the target device. |
| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | **DataSharePredicates** object that specifies the **KVStoreResultSet** object to obtain. If this parameter is **null**, define the processing logic.| | predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | **DataSharePredicates** object that specifies the KV pairs to delete. If this parameter is **null**, define the processing logic.|
**Return value** **Return value**
...@@ -6337,6 +6430,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -6337,6 +6430,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
| ID| **Error Message** | | ID| **Error Message** |
| ------------ | -------------------------------------- | | ------------ | -------------------------------------- |
| 15100001 | Over max limits. |
| 15100003 | Database corrupted. | | 15100003 | Database corrupted. |
| 15100005 | Database or result set already closed. | | 15100005 | Database or result set already closed. |
...@@ -6344,21 +6438,21 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -6344,21 +6438,21 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
```js ```js
import dataSharePredicates from '@ohos.data.dataSharePredicates'; import dataSharePredicates from '@ohos.data.dataSharePredicates';
let kvStore;
try { try {
let resultSet; let resultSet;
let predicates = new dataSharePredicates.DataSharePredicates(); let predicates = new dataSharePredicates.DataSharePredicates();
predicates.prefixKey("batch_test_string_key"); predicates.prefixKey("batch_test_string_key");
kvStore.getResultSet('localDeviceId', predicates).then((result) => { kvStore.getResultSet('localDeviceId', predicates).then((result) => {
console.log('Succeeded in getting result set'); console.info('Succeeded in getting result set');
resultSet = result; resultSet = result;
}).catch((err) => { }).catch((err) => {
console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`);
}); });
kvStore.closeResultSet(resultSet).then((err) => { kvStore.closeResultSet(resultSet).then((err) => {
console.log('Succeeded in closing result set'); console.info('Succeeded in closing result set');
}).catch((err) => { }).catch((err) => {
console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`);
}); });
} catch (e) { } catch (e) {
console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`); console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`);
...@@ -6392,7 +6486,6 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -6392,7 +6486,6 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
**Example** **Example**
```js ```js
let kvStore;
try { try {
let entries = []; let entries = [];
for (var i = 0; i < 10; i++) { for (var i = 0; i < 10; i++) {
...@@ -6407,15 +6500,15 @@ try { ...@@ -6407,15 +6500,15 @@ try {
entries.push(entry); entries.push(entry);
} }
kvStore.putBatch(entries, async function (err, data) { kvStore.putBatch(entries, async function (err, data) {
console.log('Succeeded in putting batch'); console.info('Succeeded in putting batch');
const query = new distributedKVStore.Query(); const query = new distributedKVStore.Query();
query.prefixKey("batch_test"); query.prefixKey("batch_test");
kvStore.getResultSize(query, async function (err, resultSize) { kvStore.getResultSize(query, async function (err, resultSize) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to get result size.code is ${err.code},message is ${err.message}`); console.error(`Failed to get result size.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Succeeded in getting result set size'); console.info('Succeeded in getting result set size');
}); });
}); });
} catch (e) { } catch (e) {
...@@ -6455,7 +6548,6 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -6455,7 +6548,6 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
**Example** **Example**
```js ```js
let kvStore;
try { try {
let entries = []; let entries = [];
for (var i = 0; i < 10; i++) { for (var i = 0; i < 10; i++) {
...@@ -6470,16 +6562,16 @@ try { ...@@ -6470,16 +6562,16 @@ try {
entries.push(entry); entries.push(entry);
} }
kvStore.putBatch(entries).then(async (err) => { kvStore.putBatch(entries).then(async (err) => {
console.log('Succeeded in putting batch'); console.info('Succeeded in putting batch');
}).catch((err) => { }).catch((err) => {
console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
}); });
const query = new distributedKVStore.Query(); const query = new distributedKVStore.Query();
query.prefixKey("batch_test"); query.prefixKey("batch_test");
kvStore.getResultSize(query).then((resultSize) => { kvStore.getResultSize(query).then((resultSize) => {
console.log('Succeeded in getting result set size'); console.info('Succeeded in getting result set size');
}).catch((err) => { }).catch((err) => {
console.error(`Fail to get result size.code is ${err.code},message is ${err.message}`); console.error(`Failed to get result size.code is ${err.code},message is ${err.message}`);
}); });
} catch (e) { } catch (e) {
console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`); console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`);
...@@ -6491,6 +6583,10 @@ try { ...@@ -6491,6 +6583,10 @@ try {
getResultSize(deviceId: string, query: Query, callback: AsyncCallback&lt;number&gt;): void; getResultSize(deviceId: string, query: Query, callback: AsyncCallback&lt;number&gt;): void;
Obtains the number of results that matches the specified device ID and **Query** object. This API uses an asynchronous callback to return the result. Obtains the number of results that matches the specified device ID and **Query** object. This API uses an asynchronous callback to return the result.
> **NOTE**<br/>
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
...@@ -6514,7 +6610,6 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -6514,7 +6610,6 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
**Example** **Example**
```js ```js
let kvStore;
try { try {
let entries = []; let entries = [];
for (var i = 0; i < 10; i++) { for (var i = 0; i < 10; i++) {
...@@ -6530,23 +6625,23 @@ try { ...@@ -6530,23 +6625,23 @@ try {
} }
kvStore.putBatch(entries, async function (err, data) { kvStore.putBatch(entries, async function (err, data) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Succeeded in putting batch'); console.info('Succeeded in putting batch');
const query = new distributedKVStore.Query(); const query = new distributedKVStore.Query();
query.prefixKey("batch_test"); query.prefixKey("batch_test");
kvStore.getResultSize('localDeviceId', query, async function (err, resultSize) { kvStore.getResultSize('localDeviceId', query, async function (err, resultSize) {
if (err != undefined) { if (err != undefined) {
console.error(`Fail to get resultSize.code is ${err.code},message is ${err.message}`); console.error(`Failed to get resultSize.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Succeeded in getting resultSize'); console.info('Succeeded in getting resultSize');
; ;
}); });
}); });
} catch (e) { } catch (e) {
console.error(`Fail to get resultSize.code is ${e.code},message is ${e.message}`); console.error(`Failed to get resultSize.code is ${e.code},message is ${e.message}`);
} }
``` ```
...@@ -6555,6 +6650,10 @@ try { ...@@ -6555,6 +6650,10 @@ try {
getResultSize(deviceId: string, query: Query): Promise&lt;number&gt; getResultSize(deviceId: string, query: Query): Promise&lt;number&gt;
Obtains the number of results that matches the specified device ID and **Query** object. This API uses a promise to return the result. Obtains the number of results that matches the specified device ID and **Query** object. This API uses a promise to return the result.
> **NOTE**<br/>
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
...@@ -6583,7 +6682,6 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err ...@@ -6583,7 +6682,6 @@ For details about the error codes, see [Distributed KV Store Error Codes](../err
**Example** **Example**
```js ```js
let kvStore;
try { try {
let entries = []; let entries = [];
for (var i = 0; i < 10; i++) { for (var i = 0; i < 10; i++) {
...@@ -6598,19 +6696,20 @@ try { ...@@ -6598,19 +6696,20 @@ try {
entries.push(entry); entries.push(entry);
} }
kvStore.putBatch(entries).then(async (err) => { kvStore.putBatch(entries).then(async (err) => {
console.log('Succeeded in putting batch'); console.info('Succeeded in putting batch');
}).catch((err) => { }).catch((err) => {
console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
}); });
var query = new distributedKVStore.Query(); var query = new distributedKVStore.Query();
query.prefixKey("batch_test"); query.prefixKey("batch_test");
kvStore.getResultSize('localDeviceId', query).then((resultSize) => { kvStore.getResultSize('localDeviceId', query).then((resultSize) => {
console.log('Succeeded in getting resultSize'); console.info('Succeeded in getting resultSize');
; ;
}).catch((err) => { }).catch((err) => {
console.error(`Fail to get resultSize.code is ${err.code},message is ${err.message}`); console.error(`Failed to get resultSize.code is ${err.code},message is ${err.message}`);
}); });
} catch (e) { } catch (e) {
console.error(`Fail to get resultSize.code is ${e.code},message is ${e.message}`); console.error(`Failed to get resultSize.code is ${e.code},message is ${e.message}`);
} }
``` ```
<!--no_check-->
\ No newline at end of file
...@@ -8,19 +8,21 @@ ...@@ -8,19 +8,21 @@
**Error Message** **Error Message**
Over max subscribe limits. Over max limits.
**Description** **Description**
The number of subscriptions has reached the limit for **on('dataChange')**. The number of subscriptions or the number of opened result sets has reached the limit.
**Possible Causes** **Possible Causes**
The number of subscriptions has reached the limit for **on('dataChange')**. 1. The number of subscriptions made through **on()** reaches 8.
2. The number of result sets opened by **getResultSet()** reaches 8.
**Solution** **Solution**
Unregister unnecessary subscriptions and try again. 1. Cancel the subscriptions that are not required.
2. Close the result sets that are no longer required.
## 15100002 Parameter Configuration Changes ## 15100002 Parameter Configuration Changes
......
...@@ -428,7 +428,7 @@ Text组件当前文本排列方向固定为横向排列,要设置为竖向排 ...@@ -428,7 +428,7 @@ Text组件当前文本排列方向固定为横向排列,要设置为竖向排
@Entry @Entry
@Component @Component
struct Index15 { struct Index15 {
private message: string = '本文档适用于HarmonyOS应用开发的初学者。通过构建一个简单的具有页面跳转/返回功能的应用,快速了解工程目录的主要文件,熟悉HarmonyOS应用开发流程。'; private message: string = '本文档适用于应用开发的初学者。通过构建一个简单的具有页面跳转/返回功能的应用,快速了解工程目录的主要文件,熟悉应用开发流程。';
build() { build() {
Flex({ direction: FlexDirection.Column, wrap: FlexWrap.Wrap }) { Flex({ direction: FlexDirection.Column, wrap: FlexWrap.Wrap }) {
ForEach(this.message.split(''), (item, index) => { ForEach(this.message.split(''), (item, index) => {
......
...@@ -41,7 +41,7 @@ ...@@ -41,7 +41,7 @@
photoPicker.select(photoSelectOptions) photoPicker.select(photoSelectOptions)
.then(async (photoSelectResult) => { .then(async (photoSelectResult) => {
let uri = photoSelectResult.photoUris[0]; let uri = photoSelectResult.photoUris[0];
// 获取到图片或者视频文件的URI后进行文件读取等操作 // 获取到图片或者视频文件的URI后进行文件读取等操作
}) })
.catch((err) => { .catch((err) => {
console.error(`Invoke documentPicker.select failed, code is ${err.code}, message is ${err.message}`); console.error(`Invoke documentPicker.select failed, code is ${err.code}, message is ${err.message}`);
...@@ -63,7 +63,11 @@ ...@@ -63,7 +63,11 @@
``` ```
3. 创建文档选择器实例。调用[select()](../reference/apis/js-apis-file-picker.md#select-3)接口拉起FilePicker界面进行文件选择。 3. 创建文档选择器实例。调用[select()](../reference/apis/js-apis-file-picker.md#select-3)接口拉起FilePicker界面进行文件选择。
文件选择成功后,返回被选中文档的URI结果集。开发者可以根据结果集中URI做进一步的处理。 文件选择成功后,返回被选中文档的URI结果集。开发者可以根据结果集中URI做进一步的处理。
例如通过[文件管理接口](../reference/apis/js-apis-file-fs.md)根据URI获取部分文件属性信息,比如文件大小、访问时间、修改时间等。如有获取文件名称需求,请暂时使用[startAbilityForResult](../../application-dev/application-models/uiability-intra-device-interaction.md)获取。
> **说明:** > **说明:**
> >
> 目前DocumentSelectOptions不支持参数配置,默认可以选择所有类型的用户文件。 > 目前DocumentSelectOptions不支持参数配置,默认可以选择所有类型的用户文件。
...@@ -73,13 +77,39 @@ ...@@ -73,13 +77,39 @@
documentViewPicker.select(documentSelectOptions) documentViewPicker.select(documentSelectOptions)
.then((documentSelectResult) => { .then((documentSelectResult) => {
let uri = documentSelectResult[0]; let uri = documentSelectResult[0];
// 获取到文档文件的URI后进行文件读取等操作 // 获取到文档文件的URI后进行文件读取等操作
}) })
.catch((err) => { .catch((err) => {
console.error(`Invoke documentPicker.select failed, code is ${err.code}, message is ${err.message}`); console.error(`Invoke documentPicker.select failed, code is ${err.code}, message is ${err.message}`);
}) })
``` ```
> **说明:**
>
> 目前DocumentSelectOptions功能不完整, 如需获取文件名称,请使用startAbilityForResult接口。
```ts
let config = {
action: 'ohos.want.action.OPEN_FILE',
parameters: {
startMode: 'choose',
}
}
try {
let result = await context.startAbilityForResult(config, {windowMode: 1});
if (result.resultCode !== 0) {
console.error(`DocumentPicker.select failed, code is ${result.resultCode}, message is ${result.want.parameters.message}`);
return;
}
// 获取到文档文件的URI
let select_item_list = result.want.parameters.select_item_list;
// 获取到文档文件的文件名称
let file_name_list = result.want.parameters.file_name_list;
} catch (err) {
console.error(`Invoke documentPicker.select failed, code is ${err.code}, message is ${err.message}`);
}
```
## 选择音频类文件 ## 选择音频类文件
1. 导入选择器模块。 1. 导入选择器模块。
...@@ -109,7 +139,7 @@ ...@@ -109,7 +139,7 @@
audioViewPicker.select(audioSelectOptions) audioViewPicker.select(audioSelectOptions)
.then(audioSelectResult => { .then(audioSelectResult => {
let uri = audioSelectOptions[0]; let uri = audioSelectOptions[0];
// 获取到音频文件的URI后进行文件读取等操作 // 获取到音频文件的URI后进行文件读取等操作
}) })
.catch((err) => { .catch((err) => {
console.error(`Invoke audioPicker.select failed, code is ${err.code}, message is ${err.message}`); console.error(`Invoke audioPicker.select failed, code is ${err.code}, message is ${err.message}`);
......
...@@ -32,7 +32,7 @@ ...@@ -32,7 +32,7 @@
### 音频流使用场景信息 ### 音频流使用场景信息
除了基本属性,音频流还需要具备使用场景信息。基础信息只能对音频数据进行描述,但在实际的使用过程中,不同的音频流,在音量大小,设备路由,并发策略上是有区别的。系统就是通过音频流所附带的使用场景信息,为不同的音频流制定合适的处理策略,以达到最佳的音频用户体验。 除了基本属性,音频流还需要具备使用场景信息。基础信息只能对音频数据进行描述,但在实际的使用过程中,不同的音频流,在音量大小,设备路由,并发策略上是有区别的。系统就是通过音频流所附带的使用场景信息,为不同的音频流制定合适的处理策略,以达到更好的音频用户体验。
- 播放场景 - 播放场景
音频播放场景的信息,通过[StreamUsage](../reference/apis/js-apis-audio.md#streamusage)[ContentType](../reference/apis/js-apis-audio.md#contenttype)进行描述。 音频播放场景的信息,通过[StreamUsage](../reference/apis/js-apis-audio.md#streamusage)[ContentType](../reference/apis/js-apis-audio.md#contenttype)进行描述。
......
...@@ -7,14 +7,12 @@ AbilityLifecycleCallback模块提供应用上下文[ApplicationContext](js-apis- ...@@ -7,14 +7,12 @@ AbilityLifecycleCallback模块提供应用上下文[ApplicationContext](js-apis-
> 本模块首批接口从API version 9 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 9 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
> 本模块接口仅可在Stage模型下使用。 > 本模块接口仅可在Stage模型下使用。
## 导入模块 ## 导入模块
```ts ```ts
import AbilityLifecycleCallback from '@ohos.app.ability.AbilityLifecycleCallback'; import AbilityLifecycleCallback from '@ohos.app.ability.AbilityLifecycleCallback';
``` ```
## AbilityLifecycleCallback.onAbilityCreate ## AbilityLifecycleCallback.onAbilityCreate
onAbilityCreate(ability: UIAbility): void; onAbilityCreate(ability: UIAbility): void;
......
...@@ -11,7 +11,6 @@ appRecovery模块提供了应用在故障状态下的恢复能力。 ...@@ -11,7 +11,6 @@ appRecovery模块提供了应用在故障状态下的恢复能力。
import appRecovery from '@ohos.app.ability.appRecovery'; import appRecovery from '@ohos.app.ability.appRecovery';
``` ```
## appRecovery.RestartFlag ## appRecovery.RestartFlag
应用重启标志,[enableAppRecovery](#apprecoveryenableapprecovery)接口重启选项参数,该类型为枚举。 应用重启标志,[enableAppRecovery](#apprecoveryenableapprecovery)接口重启选项参数,该类型为枚举。
......
...@@ -1634,7 +1634,7 @@ executeSql(sql: string, bindArgs: Array&lt;ValueType&gt;, callback: AsyncCallbac ...@@ -1634,7 +1634,7 @@ executeSql(sql: string, bindArgs: Array&lt;ValueType&gt;, callback: AsyncCallbac
```js ```js
const SQL_DELETE_TABLE = "DELETE FROM test WHERE name = ?" const SQL_DELETE_TABLE = "DELETE FROM test WHERE name = ?"
rdbStore.executeSql(SQL_CREATE_TABLE, ['zhangsan'], function(err) { rdbStore.executeSql(SQL_DELETE_TABLE, ['zhangsan'], function(err) {
if (err) { if (err) {
console.info("ExecuteSql failed, err: " + err) console.info("ExecuteSql failed, err: " + err)
return return
......
...@@ -67,7 +67,7 @@ adminManager.enableAdmin(wantTemp, enterpriseInfo, adminManager.AdminType.ADMIN_ ...@@ -67,7 +67,7 @@ adminManager.enableAdmin(wantTemp, enterpriseInfo, adminManager.AdminType.ADMIN_
enableAdmin(admin: Want, enterpriseInfo: EnterpriseInfo, type: AdminType, userId: number, callback: AsyncCallback\<void>): void enableAdmin(admin: Want, enterpriseInfo: EnterpriseInfo, type: AdminType, userId: number, callback: AsyncCallback\<void>): void
激活指定用户下的指定设备管理员应用,使用callback形式返回是否激活成功。其中超级管理员应用只能在管理员用户下被激活。 激活指定用户(通过userId指定)下的指定设备管理员应用,使用callback形式返回是否激活成功。其中超级管理员应用只能在管理员用户下被激活。
**需要权限:** ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN **需要权限:** ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN
...@@ -216,7 +216,7 @@ adminManager.disableAdmin(wantTemp, error => { ...@@ -216,7 +216,7 @@ adminManager.disableAdmin(wantTemp, error => {
disableAdmin(admin: Want, userId: number, callback: AsyncCallback\<void>): void disableAdmin(admin: Want, userId: number, callback: AsyncCallback\<void>): void
将指定用户下的指定普通管理员应用去激活,使用callback形式返回是否去激活成功。 将指定用户(通过userId指定)下的指定普通管理员应用去激活,使用callback形式返回是否去激活成功。
**需要权限:** ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN **需要权限:** ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN
...@@ -419,7 +419,7 @@ adminManager.isAdminEnabled(wantTemp, (error, result) => { ...@@ -419,7 +419,7 @@ adminManager.isAdminEnabled(wantTemp, (error, result) => {
isAdminEnabled(admin: Want, userId: number, callback: AsyncCallback\<boolean>): void isAdminEnabled(admin: Want, userId: number, callback: AsyncCallback\<boolean>): void
查询指定用户下的指定设备管理员应用是否被激活,使用callback形式返回是否处于激活状态。 查询指定用户(通过userId指定)下的指定设备管理员应用是否被激活,使用callback形式返回是否处于激活状态。
**系统能力:** SystemCapability.Customization.EnterpriseDeviceManager **系统能力:** SystemCapability.Customization.EnterpriseDeviceManager
......
...@@ -61,7 +61,7 @@ bundleManager.AddAllowedInstallBundles(wantTemp, appIds, (error) => { ...@@ -61,7 +61,7 @@ bundleManager.AddAllowedInstallBundles(wantTemp, appIds, (error) => {
addAllowedInstallBundles(admin: Want, appIds: Array\<string>, userId: number, callback: AsyncCallback&lt;void&gt;): void; addAllowedInstallBundles(admin: Want, appIds: Array\<string>, userId: number, callback: AsyncCallback&lt;void&gt;): void;
指定设备管理员应用添加包安装白名单接口,添加至白名单的应用允许在指定用户下安装,否则不允许安装,使用callback形式返回是否添加成功。 指定设备管理员应用添加包安装白名单接口,添加至白名单的应用允许在指定用户(通过userId指定)下安装,否则不允许安装,使用callback形式返回是否添加成功。
**需要权限:** ohos.permission.ENTERPRISE_SET_BUNDLE_INSTALL_POLICY **需要权限:** ohos.permission.ENTERPRISE_SET_BUNDLE_INSTALL_POLICY
...@@ -203,7 +203,7 @@ bundleManager.removeAllowedInstallBundles(wantTemp, appIds, (error) => { ...@@ -203,7 +203,7 @@ bundleManager.removeAllowedInstallBundles(wantTemp, appIds, (error) => {
removeAllowedInstallBundles(admin: Want, appIds: Array\<string>, userId: number, callback: AsyncCallback&lt;void&gt;): void; removeAllowedInstallBundles(admin: Want, appIds: Array\<string>, userId: number, callback: AsyncCallback&lt;void&gt;): void;
指定设备管理员应用移除包安装白名单接口,在白名单存在的情况下,不在包安装白名单中的应用不允许在指定用户下安装,使用callback形式返回移除结果。 指定设备管理员应用移除包安装白名单接口,在白名单存在的情况下,不在包安装白名单中的应用不允许在指定用户(通过userId指定)下安装,使用callback形式返回移除结果。
**需要权限:** ohos.permission.ENTERPRISE_SET_BUNDLE_INSTALL_POLICY **需要权限:** ohos.permission.ENTERPRISE_SET_BUNDLE_INSTALL_POLICY
...@@ -343,7 +343,7 @@ bundleManager.getAllowedInstallBundles(wantTemp, (error) => { ...@@ -343,7 +343,7 @@ bundleManager.getAllowedInstallBundles(wantTemp, (error) => {
getAllowedInstallBundles(admin: Want, userId: number, callback: AsyncCallback&lt;Array&lt;string&gt;&gt;): void; getAllowedInstallBundles(admin: Want, userId: number, callback: AsyncCallback&lt;Array&lt;string&gt;&gt;): void;
指定管理员应用获取指定用户下的包安装白名单接口,使用callback形式返回获取包安装白名单。 指定管理员应用获取指定用户(通过userId指定)下的包安装白名单接口,使用callback形式返回获取包安装白名单。
**需要权限:** ohos.permission.ENTERPRISE_SET_BUNDLE_INSTALL_POLICY **需要权限:** ohos.permission.ENTERPRISE_SET_BUNDLE_INSTALL_POLICY
...@@ -387,7 +387,7 @@ bundleManager.getAllowedInstallBundles(wantTemp, 100, (error) => { ...@@ -387,7 +387,7 @@ bundleManager.getAllowedInstallBundles(wantTemp, 100, (error) => {
getAllowedInstallBundles(admin: Want, userId?: number): Promise&lt;Array&lt;string&gt;&gt;; getAllowedInstallBundles(admin: Want, userId?: number): Promise&lt;Array&lt;string&gt;&gt;;
指定管理员应用获取管理员用户下包安装白名单接口,使用promise形式返回获取包安装白名单。 如果调用接口时传入参数userId,指定管理员应用获取指定用户下包安装白名单接口,如果调用接口时没有传入参数userId,指定管理员应用获取当前用户下包安装白名单接口,使用promise形式返回获取包安装白名单。
**需要权限:** ohos.permission.ENTERPRISE_SET_BUNDLE_INSTALL_POLICY **需要权限:** ohos.permission.ENTERPRISE_SET_BUNDLE_INSTALL_POLICY
......
...@@ -6,6 +6,12 @@ ...@@ -6,6 +6,12 @@
> >
> 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 导入模块
```ts
import ability from '@ohos.ability.ability';
```
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase
| 名称 | 可读 | 可写 | 类型 | 必填 | 说明 | | 名称 | 可读 | 可写 | 类型 | 必填 | 说明 |
......
...@@ -2,6 +2,12 @@ ...@@ -2,6 +2,12 @@
在连接指定的后台服务时作为入参,用于接收连接过程中的状态变化,如作为[connectServiceExtensionAbility](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextconnectserviceextensionability)的入参,连接指定的ServiceExtensionAbility。 在连接指定的后台服务时作为入参,用于接收连接过程中的状态变化,如作为[connectServiceExtensionAbility](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextconnectserviceextensionability)的入参,连接指定的ServiceExtensionAbility。
## 导入模块
```ts
import common from '@ohos.app.ability.common';
```
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
...@@ -18,7 +24,7 @@ ...@@ -18,7 +24,7 @@
abilityName: 'MyAbility' abilityName: 'MyAbility'
}; };
let connectOptions = { let connectOptions: common.ConnectOptions = {
onConnect(elementName, remote) { onConnect(elementName, remote) {
console.log('onConnect elementName: ${elementName}'); console.log('onConnect elementName: ${elementName}');
}, },
......
...@@ -7,6 +7,12 @@ ...@@ -7,6 +7,12 @@
> 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
> 本模块接口仅可在FA模型下使用。 > 本模块接口仅可在FA模型下使用。
## 导入模块
```ts
import ability from '@ohos.ability.ability';
```
## 使用说明 ## 使用说明
使用前根据具体情况引入如下模块 使用前根据具体情况引入如下模块
...@@ -35,7 +41,7 @@ openFile(uri: string, mode: string, callback: AsyncCallback\<number>): void ...@@ -35,7 +41,7 @@ openFile(uri: string, mode: string, callback: AsyncCallback\<number>): void
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let DAHelper = featureAbility.acquireDataAbilityHelper( let DAHelper: ability.DataAbilityHelper = featureAbility.acquireDataAbilityHelper(
'dataability:///com.example.DataAbility' 'dataability:///com.example.DataAbility'
); );
let mode = 'rw'; let mode = 'rw';
...@@ -73,7 +79,7 @@ openFile(uri: string, mode: string): Promise\<number> ...@@ -73,7 +79,7 @@ openFile(uri: string, mode: string): Promise\<number>
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let DAHelper = featureAbility.acquireDataAbilityHelper( let DAHelper: ability.DataAbilityHelper = featureAbility.acquireDataAbilityHelper(
'dataability:///com.example.DataAbility' 'dataability:///com.example.DataAbility'
); );
let mode = 'rw'; let mode = 'rw';
...@@ -102,7 +108,7 @@ on(type: 'dataChange', uri: string, callback: AsyncCallback\<void>): void ...@@ -102,7 +108,7 @@ on(type: 'dataChange', uri: string, callback: AsyncCallback\<void>): void
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let DAHelper = featureAbility.acquireDataAbilityHelper( let DAHelper: ability.DataAbilityHelper = featureAbility.acquireDataAbilityHelper(
'dataability:///com.example.DataAbility' 'dataability:///com.example.DataAbility'
); );
function onChangeNotify() { function onChangeNotify() {
...@@ -135,7 +141,7 @@ off(type: 'dataChange', uri: string, callback?: AsyncCallback\<void>): void ...@@ -135,7 +141,7 @@ off(type: 'dataChange', uri: string, callback?: AsyncCallback\<void>): void
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let DAHelper = featureAbility.acquireDataAbilityHelper( let DAHelper: ability.DataAbilityHelper = featureAbility.acquireDataAbilityHelper(
'dataability:///com.example.DataAbility' 'dataability:///com.example.DataAbility'
); );
function onChangeNotify() { function onChangeNotify() {
...@@ -171,7 +177,7 @@ getType(uri: string, callback: AsyncCallback\<string>): void ...@@ -171,7 +177,7 @@ getType(uri: string, callback: AsyncCallback\<string>): void
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let DAHelper = featureAbility.acquireDataAbilityHelper( let DAHelper: ability.DataAbilityHelper = featureAbility.acquireDataAbilityHelper(
'dataability:///com.example.DataAbility' 'dataability:///com.example.DataAbility'
); );
DAHelper.getType('dataability:///com.example.DataAbility', (error, data) => { DAHelper.getType('dataability:///com.example.DataAbility', (error, data) => {
...@@ -207,7 +213,7 @@ getType(uri: string): Promise\<string> ...@@ -207,7 +213,7 @@ getType(uri: string): Promise\<string>
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let DAHelper = featureAbility.acquireDataAbilityHelper( let DAHelper: ability.DataAbilityHelper = featureAbility.acquireDataAbilityHelper(
'dataability:///com.example.DataAbility' 'dataability:///com.example.DataAbility'
); );
DAHelper.getType('dataability:///com.example.DataAbility').then((data) => { DAHelper.getType('dataability:///com.example.DataAbility').then((data) => {
...@@ -235,7 +241,7 @@ getFileTypes(uri: string, mimeTypeFilter: string, callback: AsyncCallback<Array\ ...@@ -235,7 +241,7 @@ getFileTypes(uri: string, mimeTypeFilter: string, callback: AsyncCallback<Array\
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let DAHelper = featureAbility.acquireDataAbilityHelper( let DAHelper: ability.DataAbilityHelper = featureAbility.acquireDataAbilityHelper(
'dataability:///com.example.DataAbility' 'dataability:///com.example.DataAbility'
); );
DAHelper.getFileTypes( 'dataability:///com.example.DataAbility', 'image/*', (error, data) => { DAHelper.getFileTypes( 'dataability:///com.example.DataAbility', 'image/*', (error, data) => {
...@@ -272,7 +278,7 @@ getFileTypes(uri: string, mimeTypeFilter: string): Promise\<Array\<string>> ...@@ -272,7 +278,7 @@ getFileTypes(uri: string, mimeTypeFilter: string): Promise\<Array\<string>>
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let DAHelper = featureAbility.acquireDataAbilityHelper( let DAHelper: ability.DataAbilityHelper = featureAbility.acquireDataAbilityHelper(
'dataability:///com.example.DataAbility' 'dataability:///com.example.DataAbility'
); );
DAHelper.getFileTypes('dataability:///com.example.DataAbility', 'image/*').then((data) => { DAHelper.getFileTypes('dataability:///com.example.DataAbility', 'image/*').then((data) => {
...@@ -299,7 +305,7 @@ normalizeUri(uri: string, callback: AsyncCallback\<string>): void ...@@ -299,7 +305,7 @@ normalizeUri(uri: string, callback: AsyncCallback\<string>): void
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let DAHelper = featureAbility.acquireDataAbilityHelper( let DAHelper: ability.DataAbilityHelper = featureAbility.acquireDataAbilityHelper(
'dataability:///com.example.DataAbility' 'dataability:///com.example.DataAbility'
); );
DAHelper.normalizeUri('dataability:///com.example.DataAbility', (error, data) => { DAHelper.normalizeUri('dataability:///com.example.DataAbility', (error, data) => {
...@@ -335,7 +341,7 @@ normalizeUri(uri: string): Promise\<string> ...@@ -335,7 +341,7 @@ normalizeUri(uri: string): Promise\<string>
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let DAHelper = featureAbility.acquireDataAbilityHelper( let DAHelper: ability.DataAbilityHelper = featureAbility.acquireDataAbilityHelper(
'dataability:///com.example.DataAbility' 'dataability:///com.example.DataAbility'
); );
DAHelper.normalizeUri('dataability:///com.example.DataAbility',).then((data) => { DAHelper.normalizeUri('dataability:///com.example.DataAbility',).then((data) => {
...@@ -362,7 +368,7 @@ denormalizeUri(uri: string, callback: AsyncCallback\<string>): void ...@@ -362,7 +368,7 @@ denormalizeUri(uri: string, callback: AsyncCallback\<string>): void
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let DAHelper = featureAbility.acquireDataAbilityHelper( let DAHelper: ability.DataAbilityHelper = featureAbility.acquireDataAbilityHelper(
'dataability:///com.example.DataAbility' 'dataability:///com.example.DataAbility'
); );
DAHelper.denormalizeUri('dataability:///com.example.DataAbility', (error, data) => { DAHelper.denormalizeUri('dataability:///com.example.DataAbility', (error, data) => {
...@@ -398,7 +404,7 @@ denormalizeUri(uri: string): Promise\<string> ...@@ -398,7 +404,7 @@ denormalizeUri(uri: string): Promise\<string>
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let DAHelper = featureAbility.acquireDataAbilityHelper( let DAHelper: ability.DataAbilityHelper = featureAbility.acquireDataAbilityHelper(
'dataability:///com.example.DataAbility' 'dataability:///com.example.DataAbility'
); );
DAHelper.denormalizeUri('dataability:///com.example.DataAbility',).then((data) => { DAHelper.denormalizeUri('dataability:///com.example.DataAbility',).then((data) => {
...@@ -425,7 +431,7 @@ notifyChange(uri: string, callback: AsyncCallback\<void>): void ...@@ -425,7 +431,7 @@ notifyChange(uri: string, callback: AsyncCallback\<void>): void
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let DAHelper = featureAbility.acquireDataAbilityHelper( let DAHelper: ability.DataAbilityHelper = featureAbility.acquireDataAbilityHelper(
'dataability:///com.example.DataAbility' 'dataability:///com.example.DataAbility'
); );
DAHelper.notifyChange('dataability:///com.example.DataAbility', (error) => { DAHelper.notifyChange('dataability:///com.example.DataAbility', (error) => {
...@@ -461,7 +467,7 @@ notifyChange(uri: string): Promise\<void> ...@@ -461,7 +467,7 @@ notifyChange(uri: string): Promise\<void>
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let DAHelper = featureAbility.acquireDataAbilityHelper( let DAHelper: ability.DataAbilityHelper = featureAbility.acquireDataAbilityHelper(
'dataability:///com.example.DataAbility' 'dataability:///com.example.DataAbility'
); );
DAHelper.notifyChange('dataability:///com.example.DataAbility').then(() => { DAHelper.notifyChange('dataability:///com.example.DataAbility').then(() => {
...@@ -489,7 +495,7 @@ insert(uri: string, valuesBucket: rdb.ValuesBucket, callback: AsyncCallback\<num ...@@ -489,7 +495,7 @@ insert(uri: string, valuesBucket: rdb.ValuesBucket, callback: AsyncCallback\<num
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let DAHelper = featureAbility.acquireDataAbilityHelper( let DAHelper: ability.DataAbilityHelper = featureAbility.acquireDataAbilityHelper(
'dataability:///com.example.DataAbility' 'dataability:///com.example.DataAbility'
); );
const valueBucket = { const valueBucket = {
...@@ -532,7 +538,7 @@ insert(uri: string, valuesBucket: rdb.ValuesBucket): Promise\<number> ...@@ -532,7 +538,7 @@ insert(uri: string, valuesBucket: rdb.ValuesBucket): Promise\<number>
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let DAHelper = featureAbility.acquireDataAbilityHelper( let DAHelper: ability.DataAbilityHelper = featureAbility.acquireDataAbilityHelper(
'dataability:///com.example.DataAbility' 'dataability:///com.example.DataAbility'
); );
const valueBucket = { const valueBucket = {
...@@ -566,7 +572,7 @@ batchInsert(uri: string, valuesBuckets: Array\<rdb.ValuesBucket>, callback: Asyn ...@@ -566,7 +572,7 @@ batchInsert(uri: string, valuesBuckets: Array\<rdb.ValuesBucket>, callback: Asyn
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let DAHelper = featureAbility.acquireDataAbilityHelper( let DAHelper: ability.DataAbilityHelper = featureAbility.acquireDataAbilityHelper(
'dataability:///com.example.DataAbility' 'dataability:///com.example.DataAbility'
); );
let cars = new Array({'name': 'roe11', 'age': 21, 'salary': 20.5, 'blobType': 'u8',}, let cars = new Array({'name': 'roe11', 'age': 21, 'salary': 20.5, 'blobType': 'u8',},
...@@ -606,7 +612,7 @@ batchInsert(uri: string, valuesBuckets: Array<rdb.ValuesBucket>): Promise\<numbe ...@@ -606,7 +612,7 @@ batchInsert(uri: string, valuesBuckets: Array<rdb.ValuesBucket>): Promise\<numbe
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let DAHelper = featureAbility.acquireDataAbilityHelper( let DAHelper: ability.DataAbilityHelper = featureAbility.acquireDataAbilityHelper(
'dataability:///com.example.DataAbility' 'dataability:///com.example.DataAbility'
); );
let cars = new Array({'name': 'roe11', 'age': 21, 'salary': 20.5, 'blobType': 'u8',}, let cars = new Array({'name': 'roe11', 'age': 21, 'salary': 20.5, 'blobType': 'u8',},
...@@ -638,7 +644,7 @@ delete(uri: string, predicates: dataAbility.DataAbilityPredicates, callback: Asy ...@@ -638,7 +644,7 @@ delete(uri: string, predicates: dataAbility.DataAbilityPredicates, callback: Asy
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
import ohos_data_ability from '@ohos.data.dataAbility'; import ohos_data_ability from '@ohos.data.dataAbility';
let DAHelper = featureAbility.acquireDataAbilityHelper( let DAHelper: ability.DataAbilityHelper = featureAbility.acquireDataAbilityHelper(
'dataability:///com.example.DataAbility' 'dataability:///com.example.DataAbility'
); );
let da = new ohos_data_ability.DataAbilityPredicates(); let da = new ohos_data_ability.DataAbilityPredicates();
...@@ -677,7 +683,7 @@ delete(uri: string, predicates?: dataAbility.DataAbilityPredicates): Promise\<nu ...@@ -677,7 +683,7 @@ delete(uri: string, predicates?: dataAbility.DataAbilityPredicates): Promise\<nu
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
import ohos_data_ability from '@ohos.data.dataAbility'; import ohos_data_ability from '@ohos.data.dataAbility';
let DAHelper = featureAbility.acquireDataAbilityHelper( let DAHelper: ability.DataAbilityHelper = featureAbility.acquireDataAbilityHelper(
'dataability:///com.example.DataAbility' 'dataability:///com.example.DataAbility'
); );
let da = new ohos_data_ability.DataAbilityPredicates(); let da = new ohos_data_ability.DataAbilityPredicates();
...@@ -708,7 +714,7 @@ update(uri: string, valuesBucket: rdb.ValuesBucket, predicates: dataAbility.Data ...@@ -708,7 +714,7 @@ update(uri: string, valuesBucket: rdb.ValuesBucket, predicates: dataAbility.Data
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
import ohos_data_ability from '@ohos.data.dataAbility'; import ohos_data_ability from '@ohos.data.dataAbility';
let DAHelper = featureAbility.acquireDataAbilityHelper( let DAHelper: ability.DataAbilityHelper = featureAbility.acquireDataAbilityHelper(
'dataability:///com.example.DataAbility' 'dataability:///com.example.DataAbility'
); );
const va = { const va = {
...@@ -754,7 +760,7 @@ update(uri: string, valuesBucket: rdb.ValuesBucket, predicates?: dataAbility.Dat ...@@ -754,7 +760,7 @@ update(uri: string, valuesBucket: rdb.ValuesBucket, predicates?: dataAbility.Dat
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
import ohos_data_ability from '@ohos.data.dataAbility'; import ohos_data_ability from '@ohos.data.dataAbility';
let DAHelper = featureAbility.acquireDataAbilityHelper( let DAHelper: ability.DataAbilityHelper = featureAbility.acquireDataAbilityHelper(
'dataability:///com.example.DataAbility' 'dataability:///com.example.DataAbility'
); );
const va = { const va = {
...@@ -791,7 +797,7 @@ query(uri: string, columns: Array\<string>, predicates: dataAbility.DataAbilityP ...@@ -791,7 +797,7 @@ query(uri: string, columns: Array\<string>, predicates: dataAbility.DataAbilityP
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
import ohos_data_ability from '@ohos.data.dataAbility'; import ohos_data_ability from '@ohos.data.dataAbility';
let DAHelper = featureAbility.acquireDataAbilityHelper( let DAHelper: ability.DataAbilityHelper = featureAbility.acquireDataAbilityHelper(
'dataability:///com.example.DataAbility' 'dataability:///com.example.DataAbility'
); );
let cars=new Array('value1', 'value2', 'value3', 'value4'); let cars=new Array('value1', 'value2', 'value3', 'value4');
...@@ -834,7 +840,7 @@ query(uri: string, columns?: Array\<string>, predicates?: dataAbility.DataAbilit ...@@ -834,7 +840,7 @@ query(uri: string, columns?: Array\<string>, predicates?: dataAbility.DataAbilit
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
import ohos_data_ability from '@ohos.data.dataAbility'; import ohos_data_ability from '@ohos.data.dataAbility';
let DAHelper = featureAbility.acquireDataAbilityHelper( let DAHelper: ability.DataAbilityHelper = featureAbility.acquireDataAbilityHelper(
'dataability:///com.example.DataAbility' 'dataability:///com.example.DataAbility'
); );
let cars = new Array('value1', 'value2', 'value3', 'value4'); let cars = new Array('value1', 'value2', 'value3', 'value4');
...@@ -867,7 +873,7 @@ call(uri: string, method: string, arg: string, extras: PacMap, callback: AsyncCa ...@@ -867,7 +873,7 @@ call(uri: string, method: string, arg: string, extras: PacMap, callback: AsyncCa
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let dataAbilityHelper = featureAbility.acquireDataAbilityHelper( let dataAbilityHelper: ability.DataAbilityHelper = featureAbility.acquireDataAbilityHelper(
'dataability:///com.example.jsapidemo.UserDataAbility' 'dataability:///com.example.jsapidemo.UserDataAbility'
); );
dataAbilityHelper.call('dataability:///com.example.jsapidemo.UserDataAbility', dataAbilityHelper.call('dataability:///com.example.jsapidemo.UserDataAbility',
...@@ -908,7 +914,7 @@ call(uri: string, method: string, arg: string, extras: PacMap): Promise\<PacMap> ...@@ -908,7 +914,7 @@ call(uri: string, method: string, arg: string, extras: PacMap): Promise\<PacMap>
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let dataAbilityHelper = featureAbility.acquireDataAbilityHelper( let dataAbilityHelper: ability.DataAbilityHelper = featureAbility.acquireDataAbilityHelper(
'dataability:///com.example.jsapidemo.UserDataAbility' 'dataability:///com.example.jsapidemo.UserDataAbility'
); );
dataAbilityHelper.call('dataability:///com.example.jsapidemo.UserDataAbility', dataAbilityHelper.call('dataability:///com.example.jsapidemo.UserDataAbility',
...@@ -942,7 +948,7 @@ import featureAbility from '@ohos.ability.featureAbility'; ...@@ -942,7 +948,7 @@ import featureAbility from '@ohos.ability.featureAbility';
// 根据DataAbilityOperation列表选择要对数据库做的操作 // 根据DataAbilityOperation列表选择要对数据库做的操作
let op=new Array(); let op=new Array();
let dataAbilityHelper = featureAbility.acquireDataAbilityHelper( let dataAbilityHelper: ability.DataAbilityHelper = featureAbility.acquireDataAbilityHelper(
'dataability:///com.example.jsapidemo.UserDataAbility' 'dataability:///com.example.jsapidemo.UserDataAbility'
); );
dataAbilityHelper.executeBatch('dataability:///com.example.jsapidemo.UserDataAbility', op, (error, data) => { dataAbilityHelper.executeBatch('dataability:///com.example.jsapidemo.UserDataAbility', op, (error, data) => {
...@@ -982,7 +988,7 @@ import featureAbility from '@ohos.ability.featureAbility'; ...@@ -982,7 +988,7 @@ import featureAbility from '@ohos.ability.featureAbility';
// 根据DataAbilityOperation列表选择要对数据库做的操作 // 根据DataAbilityOperation列表选择要对数据库做的操作
let op=new Array(); let op=new Array();
let dataAbilityHelper = featureAbility.acquireDataAbilityHelper( let dataAbilityHelper: ability.DataAbilityHelper = featureAbility.acquireDataAbilityHelper(
'dataability:///com.example.jsapidemo.UserDataAbility' 'dataability:///com.example.jsapidemo.UserDataAbility'
); );
dataAbilityHelper.executeBatch('dataability:///com.example.jsapidemo.UserDataAbility', op).then((data) => { dataAbilityHelper.executeBatch('dataability:///com.example.jsapidemo.UserDataAbility', op).then((data) => {
......
...@@ -7,6 +7,12 @@ ...@@ -7,6 +7,12 @@
> 本接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
> 本接口仅可在FA模型下使用 > 本接口仅可在FA模型下使用
## 导入模块
```ts
import ability from '@ohos.ability.ability';
```
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.FAModel **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.FAModel
| 名称 | 类型 | 必填| 说明 | | 名称 | 类型 | 必填| 说明 |
......
...@@ -7,6 +7,12 @@ ...@@ -7,6 +7,12 @@
> 本接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
> 本接口仅可在FA模型下使用 > 本接口仅可在FA模型下使用
## 导入模块
```ts
import ability from '@ohos.ability.ability';
```
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.FAModel **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.FAModel
| 名称 | 类型 | 必填 | 说明 | | 名称 | 类型 | 必填 | 说明 |
...@@ -22,7 +28,7 @@ import featureAbility from '@ohos.ability.featureAbility'; ...@@ -22,7 +28,7 @@ import featureAbility from '@ohos.ability.featureAbility';
// 批量执行数据库操作 // 批量执行数据库操作
function executeBatchOperation() { function executeBatchOperation() {
let dataAbilityUri = ('dataability:///com.example.myapplication.TestDataAbility'); let dataAbilityUri = ('dataability:///com.example.myapplication.TestDataAbility');
let DAHelper; let DAHelper: ability.DataAbilityHelper;
try { try {
DAHelper = featureAbility.acquireDataAbilityHelper(dataAbilityUri); DAHelper = featureAbility.acquireDataAbilityHelper(dataAbilityUri);
if (DAHelper === null) { if (DAHelper === null) {
...@@ -61,7 +67,7 @@ function executeBatchOperation() { ...@@ -61,7 +67,7 @@ function executeBatchOperation() {
try { try {
DAHelper.executeBatch(dataAbilityUri, operations).then((data) => { DAHelper.executeBatch(dataAbilityUri, operations).then((data) => {
for (let i = 0; i < data.length; i++) { for (let i = 0; i < data.length; i++) {
let dataAbilityResult = data[i]; let dataAbilityResult: ability.DataAbilityResult = data[i];
console.log('dataAbilityResult.uri: ${dataAbilityResult.uri}'); console.log('dataAbilityResult.uri: ${dataAbilityResult.uri}');
console.log('dataAbilityResult.count: ${dataAbilityResult.count}'); console.log('dataAbilityResult.count: ${dataAbilityResult.count}');
} }
......
...@@ -7,6 +7,12 @@ ...@@ -7,6 +7,12 @@
> 本接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
> 本接口仅可在FA模型下使用 > 本接口仅可在FA模型下使用
## 导入模块
```ts
import ability from '@ohos.ability.ability';
```
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.FAModel **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.FAModel
| 名称 | 类型 | 必填 | 说明 | | 名称 | 类型 | 必填 | 说明 |
...@@ -30,7 +36,7 @@ let abilityStartSetting ={ ...@@ -30,7 +36,7 @@ let abilityStartSetting ={
[featureAbility.AbilityStartSetting.DISPLAY_ID_KEY] : 1, [featureAbility.AbilityStartSetting.DISPLAY_ID_KEY] : 1,
}; };
let startAbilityParameter = { let startAbilityParameter: ability.StartAbilityParameter = {
want : Want, want : Want,
abilityStartSetting : abilityStartSetting abilityStartSetting : abilityStartSetting
}; };
......
...@@ -6,6 +6,12 @@ Want是对象间信息传递的载体, 可以用于应用组件间的信息传 ...@@ -6,6 +6,12 @@ Want是对象间信息传递的载体, 可以用于应用组件间的信息传
> >
> 本模块首批接口从API version 6开始支持,从API version 9废弃,使用[@ohos.app.ability.Want](js-apis-app-ability-want.md)模块替代。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 6开始支持,从API version 9废弃,使用[@ohos.app.ability.Want](js-apis-app-ability-want.md)模块替代。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 导入模块
```ts
import Want from '@ohos.app.ability.Want';
```
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase
| 名称 | 类型 | 必填 | 说明 | | 名称 | 类型 | 必填 | 说明 |
......
...@@ -6,6 +6,12 @@ ...@@ -6,6 +6,12 @@
> >
> 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 导入模块
```ts
import featureAbility from '@ohos.ability.featureAbility';
```
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core
| 名称 | 类型 | 可读 | 可写 | 说明 | | 名称 | 类型 | 可读 | 可写 | 说明 |
......
...@@ -7,13 +7,19 @@ Context模块提供了ability或application的上下文的能力,包括允许 ...@@ -7,13 +7,19 @@ Context模块提供了ability或application的上下文的能力,包括允许
> 本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
> 本模块接口**仅可在FA模型**下使用。 > 本模块接口**仅可在FA模型**下使用。
## 导入模块
```ts
import featureAbility from '@ohos.ability.featureAbility';
```
## 使用说明 ## 使用说明
Context对象是在featureAbility中创建实例,并通过featureAbility的[getContext](js-apis-ability-featureAbility.md#featureabilitygetcontext)接口返回,因此在使用Context时,必须导入@ohos.ability.featureAbility库。示例如下: Context对象是在featureAbility中创建实例,并通过featureAbility的[getContext](js-apis-ability-featureAbility.md#featureabilitygetcontext)接口返回,因此在使用Context时,必须导入@ohos.ability.featureAbility库。示例如下:
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context: featureAbility.Context = featureAbility.getContext();
context.getOrCreateLocalDir().then((data) => { context.getOrCreateLocalDir().then((data) => {
console.info('getOrCreateLocalDir data: ${JSON.stringify(data)}'); console.info('getOrCreateLocalDir data: ${JSON.stringify(data)}');
}); });
...@@ -39,7 +45,7 @@ getOrCreateLocalDir(callback: AsyncCallback\<string>): void ...@@ -39,7 +45,7 @@ getOrCreateLocalDir(callback: AsyncCallback\<string>): void
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context: featureAbility.Context = featureAbility.getContext();
context.getOrCreateLocalDir((error, data)=>{ context.getOrCreateLocalDir((error, data)=>{
if (error && error.code !== 0) { if (error && error.code !== 0) {
console.error('getOrCreateLocalDir fail, error: ${JSON.stringify(error)}'); console.error('getOrCreateLocalDir fail, error: ${JSON.stringify(error)}');
...@@ -71,7 +77,7 @@ getOrCreateLocalDir(): Promise\<string> ...@@ -71,7 +77,7 @@ getOrCreateLocalDir(): Promise\<string>
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context: featureAbility.Context = featureAbility.getContext();
context.getOrCreateLocalDir().then((data) => { context.getOrCreateLocalDir().then((data) => {
console.info('getOrCreateLocalDir data: ${JSON.stringify(data)}'); console.info('getOrCreateLocalDir data: ${JSON.stringify(data)}');
}); });
...@@ -98,7 +104,7 @@ verifyPermission(permission: string, options: PermissionOptions, callback: Async ...@@ -98,7 +104,7 @@ verifyPermission(permission: string, options: PermissionOptions, callback: Async
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
import bundle from '@ohos.bundle.bundleManager'; import bundle from '@ohos.bundle.bundleManager';
let context = featureAbility.getContext(); let context: featureAbility.Context = featureAbility.getContext();
bundle.getBundleInfo('com.context.test', 1, (err, datainfo) =>{ bundle.getBundleInfo('com.context.test', 1, (err, datainfo) =>{
context.verifyPermission('com.example.permission', {uid:datainfo.appInfo.uid}, (error, data) =>{ context.verifyPermission('com.example.permission', {uid:datainfo.appInfo.uid}, (error, data) =>{
if (error && error.code !== 0) { if (error && error.code !== 0) {
...@@ -132,7 +138,7 @@ verifyPermission(permission: string, callback: AsyncCallback\<number>): void ...@@ -132,7 +138,7 @@ verifyPermission(permission: string, callback: AsyncCallback\<number>): void
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context: featureAbility.Context = featureAbility.getContext();
context.verifyPermission('com.example.permission', (error, data) =>{ context.verifyPermission('com.example.permission', (error, data) =>{
if (error && error.code !== 0) { if (error && error.code !== 0) {
console.error('verifyPermission fail, error: ${JSON.stringify(error)}'); console.error('verifyPermission fail, error: ${JSON.stringify(error)}');
...@@ -167,7 +173,7 @@ verifyPermission(permission: string, options?: PermissionOptions): Promise\<numb ...@@ -167,7 +173,7 @@ verifyPermission(permission: string, options?: PermissionOptions): Promise\<numb
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context: featureAbility.Context = featureAbility.getContext();
let Permission = {pid:1}; let Permission = {pid:1};
context.verifyPermission('com.context.permission',Permission).then((data) => { context.verifyPermission('com.context.permission',Permission).then((data) => {
console.info('verifyPermission data: ${JSON.stringify(data)}'); console.info('verifyPermission data: ${JSON.stringify(data)}');
...@@ -196,7 +202,7 @@ requestPermissionsFromUser(permissions: Array\<string>, requestCode: number, res ...@@ -196,7 +202,7 @@ requestPermissionsFromUser(permissions: Array\<string>, requestCode: number, res
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context: featureAbility.Context = featureAbility.getContext();
context.requestPermissionsFromUser( context.requestPermissionsFromUser(
['com.example.permission1', ['com.example.permission1',
'com.example.permission2', 'com.example.permission2',
...@@ -240,7 +246,7 @@ requestPermissionsFromUser(permissions: Array\<string>, requestCode: number): Pr ...@@ -240,7 +246,7 @@ requestPermissionsFromUser(permissions: Array\<string>, requestCode: number): Pr
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context: featureAbility.Context = featureAbility.getContext();
context.requestPermissionsFromUser( context.requestPermissionsFromUser(
['com.example.permission1', ['com.example.permission1',
'com.example.permission2', 'com.example.permission2',
...@@ -273,7 +279,7 @@ getApplicationInfo(callback: AsyncCallback\<ApplicationInfo>): void ...@@ -273,7 +279,7 @@ getApplicationInfo(callback: AsyncCallback\<ApplicationInfo>): void
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context: featureAbility.Context = featureAbility.getContext();
context.getApplicationInfo((error, data) => { context.getApplicationInfo((error, data) => {
if (error && error.code !== 0) { if (error && error.code !== 0) {
console.error('getApplicationInfo fail, error: ${JSON.stringify(error)}'); console.error('getApplicationInfo fail, error: ${JSON.stringify(error)}');
...@@ -303,7 +309,7 @@ getApplicationInfo(): Promise\<ApplicationInfo> ...@@ -303,7 +309,7 @@ getApplicationInfo(): Promise\<ApplicationInfo>
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context: featureAbility.Context = featureAbility.getContext();
context.getApplicationInfo().then((data) => { context.getApplicationInfo().then((data) => {
console.info('getApplicationInfo data: ${JSON.stringify(data)}'); console.info('getApplicationInfo data: ${JSON.stringify(data)}');
}); });
...@@ -329,7 +335,7 @@ getBundleName(callback: AsyncCallback\<string>): void ...@@ -329,7 +335,7 @@ getBundleName(callback: AsyncCallback\<string>): void
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context: featureAbility.Context = featureAbility.getContext();
context.getBundleName((error, data) => { context.getBundleName((error, data) => {
if (error && error.code !== 0) { if (error && error.code !== 0) {
console.error('getBundleName fail, error: ${JSON.stringify(error)}'); console.error('getBundleName fail, error: ${JSON.stringify(error)}');
...@@ -359,7 +365,7 @@ getBundleName(): Promise\<string> ...@@ -359,7 +365,7 @@ getBundleName(): Promise\<string>
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context: featureAbility.Context = featureAbility.getContext();
context.getBundleName().then((data) => { context.getBundleName().then((data) => {
console.info('getBundleName data: ${JSON.stringify(data)}'); console.info('getBundleName data: ${JSON.stringify(data)}');
}); });
...@@ -383,7 +389,7 @@ getDisplayOrientation(callback: AsyncCallback\<bundle.DisplayOrientation>): void ...@@ -383,7 +389,7 @@ getDisplayOrientation(callback: AsyncCallback\<bundle.DisplayOrientation>): void
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context: featureAbility.Context = featureAbility.getContext();
context.getDisplayOrientation((error, data) => { context.getDisplayOrientation((error, data) => {
if (error && error.code !== 0) { if (error && error.code !== 0) {
console.error('getDisplayOrientation fail, error: ${JSON.stringify(error)}'); console.error('getDisplayOrientation fail, error: ${JSON.stringify(error)}');
...@@ -411,7 +417,7 @@ getDisplayOrientation(): Promise\<bundle.DisplayOrientation>; ...@@ -411,7 +417,7 @@ getDisplayOrientation(): Promise\<bundle.DisplayOrientation>;
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context: featureAbility.Context = featureAbility.getContext();
context.getDisplayOrientation().then((data) => { context.getDisplayOrientation().then((data) => {
console.info('getDisplayOrientation data: ${JSON.stringify(data)}'); console.info('getDisplayOrientation data: ${JSON.stringify(data)}');
}); });
...@@ -435,7 +441,7 @@ getExternalCacheDir(callback: AsyncCallback\<string>): void ...@@ -435,7 +441,7 @@ getExternalCacheDir(callback: AsyncCallback\<string>): void
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context: featureAbility.Context = featureAbility.getContext();
context.getExternalCacheDir((error, data) => { context.getExternalCacheDir((error, data) => {
if (error && error.code !== 0) { if (error && error.code !== 0) {
console.error('getExternalCacheDir fail, error: ${JSON.stringify(error)}'); console.error('getExternalCacheDir fail, error: ${JSON.stringify(error)}');
...@@ -463,7 +469,7 @@ getExternalCacheDir(): Promise\<string>; ...@@ -463,7 +469,7 @@ getExternalCacheDir(): Promise\<string>;
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context: featureAbility.Context = featureAbility.getContext();
context.getExternalCacheDir().then((data) => { context.getExternalCacheDir().then((data) => {
console.info('getExternalCacheDir data: ${JSON.stringify(data)}'); console.info('getExternalCacheDir data: ${JSON.stringify(data)}');
}); });
...@@ -489,7 +495,7 @@ setDisplayOrientation(orientation: bundle.DisplayOrientation, callback: AsyncCal ...@@ -489,7 +495,7 @@ setDisplayOrientation(orientation: bundle.DisplayOrientation, callback: AsyncCal
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
import bundle from '@ohos.bundle'; import bundle from '@ohos.bundle';
let context = featureAbility.getContext(); let context: featureAbility.Context = featureAbility.getContext();
let orientation = bundle.DisplayOrientation.UNSPECIFIED; let orientation = bundle.DisplayOrientation.UNSPECIFIED;
context.setDisplayOrientation(orientation, (error) => { context.setDisplayOrientation(orientation, (error) => {
console.error('setDisplayOrientation fail, error: ${JSON.stringify(error)}'); console.error('setDisplayOrientation fail, error: ${JSON.stringify(error)}');
...@@ -516,7 +522,7 @@ setDisplayOrientation(orientation: bundle.DisplayOrientation): Promise\<void>; ...@@ -516,7 +522,7 @@ setDisplayOrientation(orientation: bundle.DisplayOrientation): Promise\<void>;
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
import bundle from '@ohos.bundle'; import bundle from '@ohos.bundle';
let context = featureAbility.getContext(); let context: featureAbility.Context = featureAbility.getContext();
let orientation = bundle.DisplayOrientation.UNSPECIFIED; let orientation = bundle.DisplayOrientation.UNSPECIFIED;
context.setDisplayOrientation(orientation).then((data) => { context.setDisplayOrientation(orientation).then((data) => {
console.info('setDisplayOrientation data: ${JSON.stringify(data)}'); console.info('setDisplayOrientation data: ${JSON.stringify(data)}');
...@@ -543,7 +549,7 @@ setShowOnLockScreen(show: boolean, callback: AsyncCallback\<void>): void ...@@ -543,7 +549,7 @@ setShowOnLockScreen(show: boolean, callback: AsyncCallback\<void>): void
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context: featureAbility.Context = featureAbility.getContext();
let show = true; let show = true;
context.setShowOnLockScreen(show, (error) => { context.setShowOnLockScreen(show, (error) => {
console.error('setShowOnLockScreen fail, error: ${JSON.stringify(error)}'); console.error('setShowOnLockScreen fail, error: ${JSON.stringify(error)}');
...@@ -575,7 +581,7 @@ setShowOnLockScreen(show: boolean): Promise\<void>; ...@@ -575,7 +581,7 @@ setShowOnLockScreen(show: boolean): Promise\<void>;
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context: featureAbility.Context = featureAbility.getContext();
let show = true; let show = true;
context.setShowOnLockScreen(show).then((data) => { context.setShowOnLockScreen(show).then((data) => {
console.info('setShowOnLockScreen data: ${JSON.stringify(data)}'); console.info('setShowOnLockScreen data: ${JSON.stringify(data)}');
...@@ -601,7 +607,7 @@ setWakeUpScreen(wakeUp: boolean, callback: AsyncCallback\<void>): void ...@@ -601,7 +607,7 @@ setWakeUpScreen(wakeUp: boolean, callback: AsyncCallback\<void>): void
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context: featureAbility.Context = featureAbility.getContext();
let wakeUp = true; let wakeUp = true;
context.setWakeUpScreen(wakeUp, (error) => { context.setWakeUpScreen(wakeUp, (error) => {
console.error('setWakeUpScreen fail, error: ${JSON.stringify(error)}'); console.error('setWakeUpScreen fail, error: ${JSON.stringify(error)}');
...@@ -632,7 +638,7 @@ setWakeUpScreen(wakeUp: boolean): Promise\<void>; ...@@ -632,7 +638,7 @@ setWakeUpScreen(wakeUp: boolean): Promise\<void>;
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context: featureAbility.Context = featureAbility.getContext();
let wakeUp = true; let wakeUp = true;
context.setWakeUpScreen(wakeUp).then((data) => { context.setWakeUpScreen(wakeUp).then((data) => {
console.info('setWakeUpScreen data: ${JSON.stringify(data)}'); console.info('setWakeUpScreen data: ${JSON.stringify(data)}');
...@@ -660,7 +666,7 @@ getProcessInfo(callback: AsyncCallback\<ProcessInfo>): void ...@@ -660,7 +666,7 @@ getProcessInfo(callback: AsyncCallback\<ProcessInfo>): void
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context: featureAbility.Context = featureAbility.getContext();
context.getProcessInfo((error, data) => { context.getProcessInfo((error, data) => {
if (error && error.code !== 0) { if (error && error.code !== 0) {
console.error('getProcessInfo fail, error: ${JSON.stringify(error)}'); console.error('getProcessInfo fail, error: ${JSON.stringify(error)}');
...@@ -690,7 +696,7 @@ getProcessInfo(): Promise\<ProcessInfo> ...@@ -690,7 +696,7 @@ getProcessInfo(): Promise\<ProcessInfo>
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context: featureAbility.Context = featureAbility.getContext();
context.getProcessInfo().then((data) => { context.getProcessInfo().then((data) => {
console.info('getProcessInfo data: ${JSON.stringify(data)}'); console.info('getProcessInfo data: ${JSON.stringify(data)}');
}); });
...@@ -718,7 +724,7 @@ getElementName(callback: AsyncCallback\<ElementName>): void ...@@ -718,7 +724,7 @@ getElementName(callback: AsyncCallback\<ElementName>): void
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context: featureAbility.Context = featureAbility.getContext();
context.getElementName((error, data) => { context.getElementName((error, data) => {
if (error && error.code !== 0) { if (error && error.code !== 0) {
console.error('getElementName fail, error: ${JSON.stringify(error)}'); console.error('getElementName fail, error: ${JSON.stringify(error)}');
...@@ -750,7 +756,7 @@ getElementName(): Promise\<ElementName> ...@@ -750,7 +756,7 @@ getElementName(): Promise\<ElementName>
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context: featureAbility.Context = featureAbility.getContext();
context.getElementName().then((data) => { context.getElementName().then((data) => {
console.info('getElementName data: ${JSON.stringify(data)}'); console.info('getElementName data: ${JSON.stringify(data)}');
}); });
...@@ -774,7 +780,7 @@ getProcessName(callback: AsyncCallback\<string>): void ...@@ -774,7 +780,7 @@ getProcessName(callback: AsyncCallback\<string>): void
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context: featureAbility.Context = featureAbility.getContext();
context.getProcessName((error, data) => { context.getProcessName((error, data) => {
if (error && error.code !== 0) { if (error && error.code !== 0) {
console.error('getProcessName fail, error: ${JSON.stringify(error)}'); console.error('getProcessName fail, error: ${JSON.stringify(error)}');
...@@ -804,7 +810,7 @@ getProcessName(): Promise\<string> ...@@ -804,7 +810,7 @@ getProcessName(): Promise\<string>
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context: featureAbility.Context = featureAbility.getContext();
context.getProcessName().then((data) => { context.getProcessName().then((data) => {
console.info('getProcessName data: ${JSON.stringify(data)}'); console.info('getProcessName data: ${JSON.stringify(data)}');
}); });
...@@ -830,7 +836,7 @@ getCallingBundle(callback: AsyncCallback\<string>): void ...@@ -830,7 +836,7 @@ getCallingBundle(callback: AsyncCallback\<string>): void
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context: featureAbility.Context = featureAbility.getContext();
context.getCallingBundle((error, data) => { context.getCallingBundle((error, data) => {
if (error && error.code !== 0) { if (error && error.code !== 0) {
console.error('getCallingBundle fail, error: ${JSON.stringify(error)}'); console.error('getCallingBundle fail, error: ${JSON.stringify(error)}');
...@@ -860,7 +866,7 @@ getCallingBundle(): Promise\<string> ...@@ -860,7 +866,7 @@ getCallingBundle(): Promise\<string>
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context: featureAbility.Context = featureAbility.getContext();
context.getCallingBundle().then((data) => { context.getCallingBundle().then((data) => {
console.info('getCallingBundle data: ${JSON.stringify(data)}'); console.info('getCallingBundle data: ${JSON.stringify(data)}');
}); });
...@@ -884,7 +890,7 @@ getCacheDir(callback: AsyncCallback\<string>): void ...@@ -884,7 +890,7 @@ getCacheDir(callback: AsyncCallback\<string>): void
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context: featureAbility.Context = featureAbility.getContext();
context.getCacheDir((error, data) => { context.getCacheDir((error, data) => {
if (error && error.code !== 0) { if (error && error.code !== 0) {
console.error('getCacheDir fail, error: ${JSON.stringify(error)}'); console.error('getCacheDir fail, error: ${JSON.stringify(error)}');
...@@ -912,7 +918,7 @@ getCacheDir(): Promise\<string> ...@@ -912,7 +918,7 @@ getCacheDir(): Promise\<string>
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context: featureAbility.Context = featureAbility.getContext();
context.getCacheDir().then((data) => { context.getCacheDir().then((data) => {
console.info('getCacheDir data: ${JSON.stringify(data)}'); console.info('getCacheDir data: ${JSON.stringify(data)}');
}); });
...@@ -936,7 +942,7 @@ getFilesDir(callback: AsyncCallback\<string>): void ...@@ -936,7 +942,7 @@ getFilesDir(callback: AsyncCallback\<string>): void
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context: featureAbility.Context = featureAbility.getContext();
context.getFilesDir((error, data) => { context.getFilesDir((error, data) => {
if (error && error.code !== 0) { if (error && error.code !== 0) {
console.error('getFilesDir fail, error: ${JSON.stringify(error)}'); console.error('getFilesDir fail, error: ${JSON.stringify(error)}');
...@@ -964,7 +970,7 @@ getFilesDir(): Promise\<string> ...@@ -964,7 +970,7 @@ getFilesDir(): Promise\<string>
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context: featureAbility.Context = featureAbility.getContext();
context.getFilesDir().then((data) => { context.getFilesDir().then((data) => {
console.info('getFilesDir data: ${JSON.stringify(data)}'); console.info('getFilesDir data: ${JSON.stringify(data)}');
}); });
...@@ -990,7 +996,7 @@ getOrCreateDistributedDir(callback: AsyncCallback\<string>): void ...@@ -990,7 +996,7 @@ getOrCreateDistributedDir(callback: AsyncCallback\<string>): void
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context: featureAbility.Context = featureAbility.getContext();
context.getOrCreateDistributedDir((error, data) => { context.getOrCreateDistributedDir((error, data) => {
if (error && error.code !== 0) { if (error && error.code !== 0) {
console.error('getOrCreateDistributedDir fail, error: ${JSON.stringify(error)}'); console.error('getOrCreateDistributedDir fail, error: ${JSON.stringify(error)}');
...@@ -1020,7 +1026,7 @@ getOrCreateDistributedDir(): Promise\<string> ...@@ -1020,7 +1026,7 @@ getOrCreateDistributedDir(): Promise\<string>
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context: featureAbility.Context = featureAbility.getContext();
context.getOrCreateDistributedDir().then((data) => { context.getOrCreateDistributedDir().then((data) => {
console.info('getOrCreateDistributedDir data: ${JSON.stringify(data)}'); console.info('getOrCreateDistributedDir data: ${JSON.stringify(data)}');
}); });
...@@ -1044,7 +1050,7 @@ getAppType(callback: AsyncCallback\<string>): void ...@@ -1044,7 +1050,7 @@ getAppType(callback: AsyncCallback\<string>): void
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context: featureAbility.Context = featureAbility.getContext();
context.getAppType((error, data) => { context.getAppType((error, data) => {
if (error && error.code !== 0) { if (error && error.code !== 0) {
console.error('getAppType fail, error: ${JSON.stringify(error)}'); console.error('getAppType fail, error: ${JSON.stringify(error)}');
...@@ -1072,7 +1078,7 @@ getAppType(): Promise\<string> ...@@ -1072,7 +1078,7 @@ getAppType(): Promise\<string>
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context: featureAbility.Context = featureAbility.getContext();
context.getAppType().then((data) => { context.getAppType().then((data) => {
console.info('getAppType data: ${JSON.stringify(data)}'); console.info('getAppType data: ${JSON.stringify(data)}');
}); });
...@@ -1096,7 +1102,7 @@ getHapModuleInfo(callback: AsyncCallback\<HapModuleInfo>): void ...@@ -1096,7 +1102,7 @@ getHapModuleInfo(callback: AsyncCallback\<HapModuleInfo>): void
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context: featureAbility.Context = featureAbility.getContext();
context.getHapModuleInfo((error, data) => { context.getHapModuleInfo((error, data) => {
if (error && error.code !== 0) { if (error && error.code !== 0) {
console.error('getHapModuleInfo fail, error: ${JSON.stringify(error)}'); console.error('getHapModuleInfo fail, error: ${JSON.stringify(error)}');
...@@ -1124,7 +1130,7 @@ getHapModuleInfo(): Promise\<HapModuleInfo> ...@@ -1124,7 +1130,7 @@ getHapModuleInfo(): Promise\<HapModuleInfo>
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context: featureAbility.Context = featureAbility.getContext();
context.getHapModuleInfo().then((data) => { context.getHapModuleInfo().then((data) => {
console.info('getHapModuleInfo data: ${JSON.stringify(data)}'); console.info('getHapModuleInfo data: ${JSON.stringify(data)}');
}); });
...@@ -1148,7 +1154,7 @@ getAppVersionInfo(callback: AsyncCallback\<AppVersionInfo>): void ...@@ -1148,7 +1154,7 @@ getAppVersionInfo(callback: AsyncCallback\<AppVersionInfo>): void
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context: featureAbility.Context = featureAbility.getContext();
context.getAppVersionInfo((error, data) => { context.getAppVersionInfo((error, data) => {
if (error && error.code !== 0) { if (error && error.code !== 0) {
console.error('getAppVersionInfo fail, error: ${JSON.stringify(error)}'); console.error('getAppVersionInfo fail, error: ${JSON.stringify(error)}');
...@@ -1176,7 +1182,7 @@ getAppVersionInfo(): Promise\<AppVersionInfo> ...@@ -1176,7 +1182,7 @@ getAppVersionInfo(): Promise\<AppVersionInfo>
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context: featureAbility.Context = featureAbility.getContext();
context.getAppVersionInfo().then((data) => { context.getAppVersionInfo().then((data) => {
console.info('getAppVersionInfo data: ${JSON.stringify(data)}'); console.info('getAppVersionInfo data: ${JSON.stringify(data)}');
}); });
...@@ -1200,7 +1206,7 @@ getAbilityInfo(callback: AsyncCallback\<AbilityInfo>): void ...@@ -1200,7 +1206,7 @@ getAbilityInfo(callback: AsyncCallback\<AbilityInfo>): void
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context: featureAbility.Context = featureAbility.getContext();
context.getAbilityInfo((error, data) => { context.getAbilityInfo((error, data) => {
if (error && error.code !== 0) { if (error && error.code !== 0) {
console.error('getAbilityInfo fail, error: ${JSON.stringify(error)}'); console.error('getAbilityInfo fail, error: ${JSON.stringify(error)}');
...@@ -1228,7 +1234,7 @@ getAbilityInfo(): Promise\<AbilityInfo> ...@@ -1228,7 +1234,7 @@ getAbilityInfo(): Promise\<AbilityInfo>
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context: featureAbility.Context = featureAbility.getContext();
context.getAbilityInfo().then((data) => { context.getAbilityInfo().then((data) => {
console.info('getAbilityInfo data: ${JSON.stringify(data)}'); console.info('getAbilityInfo data: ${JSON.stringify(data)}');
}); });
...@@ -1252,7 +1258,7 @@ getApplicationContext(): Context ...@@ -1252,7 +1258,7 @@ getApplicationContext(): Context
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext().getApplicationContext(); let context: featureAbility.Context = featureAbility.getContext().getApplicationContext();
``` ```
## Context.isUpdatingConfigurations<sup>7+</sup> ## Context.isUpdatingConfigurations<sup>7+</sup>
...@@ -1273,7 +1279,7 @@ isUpdatingConfigurations(callback: AsyncCallback\<boolean>): void; ...@@ -1273,7 +1279,7 @@ isUpdatingConfigurations(callback: AsyncCallback\<boolean>): void;
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context: featureAbility.Context = featureAbility.getContext();
context.isUpdatingConfigurations((error, data) => { context.isUpdatingConfigurations((error, data) => {
if (error && error.code !== 0) { if (error && error.code !== 0) {
console.error('isUpdatingConfigurations fail, error: ${JSON.stringify(error)}'); console.error('isUpdatingConfigurations fail, error: ${JSON.stringify(error)}');
...@@ -1301,7 +1307,7 @@ isUpdatingConfigurations(): Promise\<boolean>; ...@@ -1301,7 +1307,7 @@ isUpdatingConfigurations(): Promise\<boolean>;
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context: featureAbility.Context = featureAbility.getContext();
context.isUpdatingConfigurations().then((data) => { context.isUpdatingConfigurations().then((data) => {
console.info('isUpdatingConfigurations data: ${JSON.stringify(data)}'); console.info('isUpdatingConfigurations data: ${JSON.stringify(data)}');
}); });
...@@ -1325,7 +1331,7 @@ printDrawnCompleted(callback: AsyncCallback\<void>): void; ...@@ -1325,7 +1331,7 @@ printDrawnCompleted(callback: AsyncCallback\<void>): void;
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context: featureAbility.Context = featureAbility.getContext();
context.printDrawnCompleted((err) => { context.printDrawnCompleted((err) => {
console.error('printDrawnCompleted err: ${JSON.stringify(err)}'); console.error('printDrawnCompleted err: ${JSON.stringify(err)}');
}); });
...@@ -1349,7 +1355,7 @@ printDrawnCompleted(): Promise\<void>; ...@@ -1349,7 +1355,7 @@ printDrawnCompleted(): Promise\<void>;
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context: featureAbility.Context = featureAbility.getContext();
context.printDrawnCompleted().then((data) => { context.printDrawnCompleted().then((data) => {
console.info('printDrawnCompleted data: ${JSON.stringify(data)}'); console.info('printDrawnCompleted data: ${JSON.stringify(data)}');
}); });
......
...@@ -6,6 +6,12 @@ ...@@ -6,6 +6,12 @@
> >
> 本模块首批接口从API version 7开始支持,仅支持FA模型。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 7开始支持,仅支持FA模型。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 导入模块
```ts
import featureAbility from '@ohos.ability.featureAbility';
```
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core
| 名称 | 类型 | 可读 | 可写 | 说明 | | 名称 | 类型 | 可读 | 可写 | 说明 |
......
...@@ -6,6 +6,12 @@ AbilityDelegator提供添加用于监视指定ability的生命周期状态更改 ...@@ -6,6 +6,12 @@ AbilityDelegator提供添加用于监视指定ability的生命周期状态更改
> >
> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 导入模块
```ts
import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry';
```
## 使用说明 ## 使用说明
通过AbilityDelegatorRegistry中[getAbilityDelegator](js-apis-app-ability-abilityDelegatorRegistry.md#abilitydelegatorregistrygetabilitydelegator)方法获取。 通过AbilityDelegatorRegistry中[getAbilityDelegator](js-apis-app-ability-abilityDelegatorRegistry.md#abilitydelegatorregistrygetabilitydelegator)方法获取。
...@@ -41,7 +47,7 @@ addAbilityMonitor(monitor: AbilityMonitor, callback: AsyncCallback\<void>): void ...@@ -41,7 +47,7 @@ addAbilityMonitor(monitor: AbilityMonitor, callback: AsyncCallback\<void>): void
**示例:** **示例:**
```ts ```ts
let abilityDelegator; let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
function onAbilityCreateCallback(data) { function onAbilityCreateCallback(data) {
console.info('onAbilityCreateCallback, data: ${JSON.stringify(data)}'); console.info('onAbilityCreateCallback, data: ${JSON.stringify(data)}');
...@@ -89,7 +95,7 @@ addAbilityMonitor(monitor: AbilityMonitor): Promise\<void>; ...@@ -89,7 +95,7 @@ addAbilityMonitor(monitor: AbilityMonitor): Promise\<void>;
**示例:** **示例:**
```ts ```ts
let abilityDelegator; let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
function onAbilityCreateCallback(data) { function onAbilityCreateCallback(data) {
console.info('onAbilityCreateCallback'); console.info('onAbilityCreateCallback');
...@@ -132,7 +138,7 @@ removeAbilityMonitor(monitor: AbilityMonitor, callback: AsyncCallback\<void>): v ...@@ -132,7 +138,7 @@ removeAbilityMonitor(monitor: AbilityMonitor, callback: AsyncCallback\<void>): v
**示例:** **示例:**
```ts ```ts
let abilityDelegator; let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
function onAbilityCreateCallback(data) { function onAbilityCreateCallback(data) {
console.info('onAbilityCreateCallback'); console.info('onAbilityCreateCallback');
...@@ -180,7 +186,7 @@ removeAbilityMonitor(monitor: AbilityMonitor): Promise\<void>; ...@@ -180,7 +186,7 @@ removeAbilityMonitor(monitor: AbilityMonitor): Promise\<void>;
- 示例 - 示例
```ts ```ts
let abilityDelegator; let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
function onAbilityCreateCallback(data) { function onAbilityCreateCallback(data) {
console.info('onAbilityCreateCallback'); console.info('onAbilityCreateCallback');
...@@ -223,7 +229,7 @@ waitAbilityMonitor(monitor: AbilityMonitor, callback: AsyncCallback\<UIAbility>) ...@@ -223,7 +229,7 @@ waitAbilityMonitor(monitor: AbilityMonitor, callback: AsyncCallback\<UIAbility>)
**示例:** **示例:**
```ts ```ts
let abilityDelegator; let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
function onAbilityCreateCallback(data) { function onAbilityCreateCallback(data) {
console.info('onAbilityCreateCallback'); console.info('onAbilityCreateCallback');
...@@ -271,7 +277,7 @@ waitAbilityMonitor(monitor: AbilityMonitor, timeout: number, callback: AsyncCall ...@@ -271,7 +277,7 @@ waitAbilityMonitor(monitor: AbilityMonitor, timeout: number, callback: AsyncCall
**示例:** **示例:**
```ts ```ts
let abilityDelegator; let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
let timeout = 100; let timeout = 100;
function onAbilityCreateCallback(data) { function onAbilityCreateCallback(data) {
...@@ -327,7 +333,7 @@ waitAbilityMonitor(monitor: AbilityMonitor, timeout?: number): Promise\<UIAbilit ...@@ -327,7 +333,7 @@ waitAbilityMonitor(monitor: AbilityMonitor, timeout?: number): Promise\<UIAbilit
**示例:** **示例:**
```ts ```ts
let abilityDelegator; let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
function onAbilityCreateCallback(data) { function onAbilityCreateCallback(data) {
console.info('onAbilityCreateCallback'); console.info('onAbilityCreateCallback');
...@@ -361,7 +367,7 @@ getAppContext(): Context; ...@@ -361,7 +367,7 @@ getAppContext(): Context;
**示例:** **示例:**
```ts ```ts
let abilityDelegator; let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
let context = abilityDelegator.getAppContext(); let context = abilityDelegator.getAppContext();
...@@ -390,7 +396,7 @@ getAbilityState(ability: UIAbility): number; ...@@ -390,7 +396,7 @@ getAbilityState(ability: UIAbility): number;
**示例:** **示例:**
```ts ```ts
let abilityDelegator; let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
let ability; let ability;
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
...@@ -427,7 +433,7 @@ getCurrentTopAbility(callback: AsyncCallback\<UIAbility>): void; ...@@ -427,7 +433,7 @@ getCurrentTopAbility(callback: AsyncCallback\<UIAbility>): void;
**示例:** **示例:**
```ts ```ts
let abilityDelegator; let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
let ability; let ability;
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
...@@ -462,7 +468,7 @@ getCurrentTopAbility(): Promise\<UIAbility>; ...@@ -462,7 +468,7 @@ getCurrentTopAbility(): Promise\<UIAbility>;
**示例:** **示例:**
```ts ```ts
let abilityDelegator; let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
let ability; let ability;
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
...@@ -510,7 +516,7 @@ startAbility(want: Want, callback: AsyncCallback\<void>): void; ...@@ -510,7 +516,7 @@ startAbility(want: Want, callback: AsyncCallback\<void>): void;
**示例:** **示例:**
```ts ```ts
let abilityDelegator; let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
let want = { let want = {
bundleName: 'bundleName', bundleName: 'bundleName',
abilityName: 'abilityName' abilityName: 'abilityName'
...@@ -565,7 +571,7 @@ startAbility(want: Want): Promise\<void>; ...@@ -565,7 +571,7 @@ startAbility(want: Want): Promise\<void>;
**示例:** **示例:**
```ts ```ts
let abilityDelegator; let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
let want = { let want = {
bundleName: 'bundleName', bundleName: 'bundleName',
abilityName: 'abilityName' abilityName: 'abilityName'
...@@ -603,7 +609,7 @@ doAbilityForeground(ability: UIAbility, callback: AsyncCallback\<void>): void; ...@@ -603,7 +609,7 @@ doAbilityForeground(ability: UIAbility, callback: AsyncCallback\<void>): void;
**示例:** **示例:**
```ts ```ts
let abilityDelegator; let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
let ability; let ability;
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
...@@ -647,7 +653,7 @@ doAbilityForeground(ability: UIAbility): Promise\<void>; ...@@ -647,7 +653,7 @@ doAbilityForeground(ability: UIAbility): Promise\<void>;
**示例:** **示例:**
```ts ```ts
let abilityDelegator; let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
let ability; let ability;
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
...@@ -686,7 +692,7 @@ doAbilityBackground(ability: UIAbility, callback: AsyncCallback\<void>): void; ...@@ -686,7 +692,7 @@ doAbilityBackground(ability: UIAbility, callback: AsyncCallback\<void>): void;
**示例:** **示例:**
```ts ```ts
let abilityDelegator; let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
let ability; let ability;
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
...@@ -730,7 +736,7 @@ doAbilityBackground(ability: UIAbility): Promise\<void>; ...@@ -730,7 +736,7 @@ doAbilityBackground(ability: UIAbility): Promise\<void>;
**示例:** **示例:**
```ts ```ts
let abilityDelegator; let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
let ability; let ability;
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
...@@ -760,7 +766,7 @@ printSync(msg: string): void; ...@@ -760,7 +766,7 @@ printSync(msg: string): void;
**示例:** **示例:**
```ts ```ts
let abilityDelegator; let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
let msg = 'msg'; let msg = 'msg';
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
...@@ -785,7 +791,7 @@ print(msg: string, callback: AsyncCallback\<void>): void; ...@@ -785,7 +791,7 @@ print(msg: string, callback: AsyncCallback\<void>): void;
**示例:** **示例:**
```ts ```ts
let abilityDelegator; let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
let msg = 'msg'; let msg = 'msg';
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
...@@ -817,7 +823,7 @@ print(msg: string): Promise\<void>; ...@@ -817,7 +823,7 @@ print(msg: string): Promise\<void>;
**示例:** **示例:**
```ts ```ts
let abilityDelegator; let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
let msg = 'msg'; let msg = 'msg';
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
...@@ -844,7 +850,7 @@ executeShellCommand(cmd: string, callback: AsyncCallback\<ShellCmdResult>): void ...@@ -844,7 +850,7 @@ executeShellCommand(cmd: string, callback: AsyncCallback\<ShellCmdResult>): void
**示例:** **示例:**
```ts ```ts
let abilityDelegator; let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
let cmd = 'cmd'; let cmd = 'cmd';
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
...@@ -872,7 +878,7 @@ executeShellCommand(cmd: string, timeoutSecs: number, callback: AsyncCallback\<S ...@@ -872,7 +878,7 @@ executeShellCommand(cmd: string, timeoutSecs: number, callback: AsyncCallback\<S
**示例:** **示例:**
```ts ```ts
let abilityDelegator; let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
let cmd = 'cmd'; let cmd = 'cmd';
let timeout = 100; let timeout = 100;
...@@ -906,7 +912,7 @@ executeShellCommand(cmd: string, timeoutSecs?: number): Promise\<ShellCmdResult> ...@@ -906,7 +912,7 @@ executeShellCommand(cmd: string, timeoutSecs?: number): Promise\<ShellCmdResult>
**示例:** **示例:**
```ts ```ts
let abilityDelegator; let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
let cmd = 'cmd'; let cmd = 'cmd';
let timeout = 100; let timeout = 100;
...@@ -943,7 +949,7 @@ finishTest(msg: string, code: number, callback: AsyncCallback\<void>): void; ...@@ -943,7 +949,7 @@ finishTest(msg: string, code: number, callback: AsyncCallback\<void>): void;
**示例:** **示例:**
```ts ```ts
let abilityDelegator; let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
let msg = 'msg'; let msg = 'msg';
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
...@@ -984,7 +990,7 @@ finishTest(msg: string, code: number): Promise\<void>; ...@@ -984,7 +990,7 @@ finishTest(msg: string, code: number): Promise\<void>;
**示例:** **示例:**
```ts ```ts
let abilityDelegator; let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
let msg = 'msg'; let msg = 'msg';
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
...@@ -1019,7 +1025,7 @@ addAbilityStageMonitor(monitor: AbilityStageMonitor, callback: AsyncCallback\<vo ...@@ -1019,7 +1025,7 @@ addAbilityStageMonitor(monitor: AbilityStageMonitor, callback: AsyncCallback\<vo
**示例:** **示例:**
```ts ```ts
let abilityDelegator; let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
let monitor = { let monitor = {
moduleName: 'moduleName', moduleName: 'moduleName',
...@@ -1063,7 +1069,7 @@ addAbilityStageMonitor(monitor: AbilityStageMonitor): Promise\<void>; ...@@ -1063,7 +1069,7 @@ addAbilityStageMonitor(monitor: AbilityStageMonitor): Promise\<void>;
**示例:** **示例:**
```ts ```ts
let abilityDelegator; let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
let monitor = { let monitor = {
moduleName: 'moduleName', moduleName: 'moduleName',
...@@ -1102,7 +1108,7 @@ removeAbilityStageMonitor(monitor: AbilityStageMonitor, callback: AsyncCallback\ ...@@ -1102,7 +1108,7 @@ removeAbilityStageMonitor(monitor: AbilityStageMonitor, callback: AsyncCallback\
**示例:** **示例:**
```ts ```ts
let abilityDelegator; let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
let monitor = { let monitor = {
moduleName: 'moduleName', moduleName: 'moduleName',
...@@ -1146,7 +1152,7 @@ removeAbilityStageMonitor(monitor: AbilityStageMonitor): Promise\<void>; ...@@ -1146,7 +1152,7 @@ removeAbilityStageMonitor(monitor: AbilityStageMonitor): Promise\<void>;
**示例:** **示例:**
```ts ```ts
let abilityDelegator; let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
let monitor = { let monitor = {
moduleName: 'moduleName', moduleName: 'moduleName',
...@@ -1185,7 +1191,7 @@ waitAbilityStageMonitor(monitor: AbilityStageMonitor, callback: AsyncCallback\<A ...@@ -1185,7 +1191,7 @@ waitAbilityStageMonitor(monitor: AbilityStageMonitor, callback: AsyncCallback\<A
**示例:** **示例:**
```ts ```ts
let abilityDelegator; let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
function onAbilityCreateCallback(data) { function onAbilityCreateCallback(data) {
console.info('onAbilityCreateCallback'); console.info('onAbilityCreateCallback');
...@@ -1234,7 +1240,7 @@ waitAbilityStageMonitor(monitor: AbilityStageMonitor, timeout?: number): Promise ...@@ -1234,7 +1240,7 @@ waitAbilityStageMonitor(monitor: AbilityStageMonitor, timeout?: number): Promise
**示例:** **示例:**
```ts ```ts
let abilityDelegator; let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
function onAbilityCreateCallback(data) { function onAbilityCreateCallback(data) {
console.info('onAbilityCreateCallback'); console.info('onAbilityCreateCallback');
...@@ -1278,7 +1284,7 @@ waitAbilityStageMonitor(monitor: AbilityStageMonitor, timeout: number, callback: ...@@ -1278,7 +1284,7 @@ waitAbilityStageMonitor(monitor: AbilityStageMonitor, timeout: number, callback:
**示例:** **示例:**
```ts ```ts
let abilityDelegator; let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
let timeout = 100; let timeout = 100;
function onAbilityCreateCallback(data) { function onAbilityCreateCallback(data) {
......
...@@ -6,6 +6,12 @@ AbilityDelegatorArgs模块提供在应用程序执行测试用例期间,获取 ...@@ -6,6 +6,12 @@ AbilityDelegatorArgs模块提供在应用程序执行测试用例期间,获取
> >
> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 导入模块
```ts
import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry';
```
## 使用说明 ## 使用说明
通过AbilityDelegatorRegistry中[getArguments](js-apis-app-ability-abilityDelegatorRegistry.md#abilitydelegatorregistrygetarguments)方法获取。 通过AbilityDelegatorRegistry中[getArguments](js-apis-app-ability-abilityDelegatorRegistry.md#abilitydelegatorregistrygetarguments)方法获取。
...@@ -28,5 +34,5 @@ AbilityDelegatorArgs模块提供在应用程序执行测试用例期间,获取 ...@@ -28,5 +34,5 @@ AbilityDelegatorArgs模块提供在应用程序执行测试用例期间,获取
```ts ```ts
import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry';
let args = AbilityDelegatorRegistry.getArguments(); let args: AbilityDelegatorRegistry.AbilityDelegatorArgs = AbilityDelegatorRegistry.getArguments();
``` ```
...@@ -6,6 +6,12 @@ AbilityMonitor模块提供匹配满足指定条件的受监视能力对象的方 ...@@ -6,6 +6,12 @@ AbilityMonitor模块提供匹配满足指定条件的受监视能力对象的方
> >
> 本模块首批接口从API version 9 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 9 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 导入模块
```ts
import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry';
```
## 使用说明 ## 使用说明
可以作为abilityDelegator中的[addAbilityMonitor](js-apis-inner-application-abilityDelegator.md#addabilitymonitor9)的入参来监听指定Ability的生命周期变化。 可以作为abilityDelegator中的[addAbilityMonitor](js-apis-inner-application-abilityDelegator.md#addabilitymonitor9)的入参来监听指定Ability的生命周期变化。
...@@ -43,7 +49,7 @@ let monitor = { ...@@ -43,7 +49,7 @@ let monitor = {
onAbilityCreate: onAbilityCreateCallback onAbilityCreate: onAbilityCreateCallback
}; };
let abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.addAbilityMonitor(monitor, (error : any) => { abilityDelegator.addAbilityMonitor(monitor, (error : any) => {
if (error) { if (error) {
console.error('addAbilityMonitor fail, error: ${JSON.stringify(error)}'); console.error('addAbilityMonitor fail, error: ${JSON.stringify(error)}');
......
...@@ -6,6 +6,12 @@ AbilityRunningInfo模块提供对Ability运行的相关信息和状态的定义 ...@@ -6,6 +6,12 @@ AbilityRunningInfo模块提供对Ability运行的相关信息和状态的定义
> >
> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 导入模块
```ts
import abilitymanager from '@ohos.app.ability.abilityManager';
```
## 使用说明 ## 使用说明
通过abilityManager中[getAbilityRunningInfos](js-apis-app-ability-abilityManager.md#getabilityrunninginfos)方法获取。 通过abilityManager中[getAbilityRunningInfos](js-apis-app-ability-abilityManager.md#getabilityrunninginfos)方法获取。
......
...@@ -9,6 +9,12 @@ AbilityStageContext提供允许访问特定于abilityStage的资源的能力, ...@@ -9,6 +9,12 @@ AbilityStageContext提供允许访问特定于abilityStage的资源的能力,
> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
> 本模块接口仅可在Stage模型下使用。 > 本模块接口仅可在Stage模型下使用。
## 导入模块
```ts
import common from '@ohos.app.ability.common';
```
## 使用说明 ## 使用说明
通过AbilityStage实例来获取。 通过AbilityStage实例来获取。
......
# AbilityStageMonitor # AbilityStageMonitor
提供用于匹配满足指定条件的受监视的AbilityStage对象的方法。最近匹配的AbilityStage对象将保存在AbilityStageMonitor对象中。 提供用于匹配满足指定条件的受监视的AbilityStage对象的方法。最近匹配的AbilityStage对象将保存在AbilityStageMonitor对象中。
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core
......
...@@ -2,6 +2,12 @@ ...@@ -2,6 +2,12 @@
定义Ability状态信息,可以通过[registerApplicationStateObserver](js-apis-application-appManager.md#appmanagerregisterapplicationstateobserver8)注册生命周期变化监听后,通过[ApplicationStateObserver](js-apis-inner-application-applicationStateObserver.md)的onAbilityStateChanged生命周期回调获取。 定义Ability状态信息,可以通过[registerApplicationStateObserver](js-apis-application-appManager.md#appmanagerregisterapplicationstateobserver8)注册生命周期变化监听后,通过[ApplicationStateObserver](js-apis-inner-application-applicationStateObserver.md)的onAbilityStateChanged生命周期回调获取。
## 导入模块
```ts
import appManager from '@ohos.application.appManager';
```
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core
| 名称 | 类型 | 可读 | 可写 | 说明 | | 名称 | 类型 | 可读 | 可写 | 说明 |
......
...@@ -2,6 +2,12 @@ ...@@ -2,6 +2,12 @@
定义应用状态信息,可以通过[getForegroundApplications](js-apis-app-ability-appManager.md#appmanagergetforegroundapplications)获取当前应用的相关信息。 定义应用状态信息,可以通过[getForegroundApplications](js-apis-app-ability-appManager.md#appmanagergetforegroundapplications)获取当前应用的相关信息。
## 导入模块
```ts
import appManager from '@ohos.app.ability.appManager';
```
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core
**系统API**:本模块被标记为@systemapi,对三方应用隐藏 **系统API**:本模块被标记为@systemapi,对三方应用隐藏
......
...@@ -7,12 +7,18 @@ ApplicationContext模块提供开发者应用级别的的上下文的能力, ...@@ -7,12 +7,18 @@ ApplicationContext模块提供开发者应用级别的的上下文的能力,
> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
> 本模块接口仅可在Stage模型下使用。 > 本模块接口仅可在Stage模型下使用。
## 导入模块
```ts
import common from '@ohos.app.ability.common';
```
## 使用说明 ## 使用说明
在使用ApplicationContext的功能前,需要通过context的实例获取。 在使用ApplicationContext的功能前,需要通过context的实例获取。
```ts ```ts
let applicationContext = this.context.getApplicationContext(); let applicationContext: common.ApplicationContext = this.context.getApplicationContext();
``` ```
## ApplicationContext.on(type: 'abilityLifecycle', callback: AbilityLifecycleCallback) ## ApplicationContext.on(type: 'abilityLifecycle', callback: AbilityLifecycleCallback)
......
...@@ -2,6 +2,12 @@ ...@@ -2,6 +2,12 @@
定义应用状态监听,可以作为[registerApplicationStateObserver](js-apis-application-appManager.md#appmanagerregisterapplicationstateobserver8)的入参监听当前应用的生命周期变化。 定义应用状态监听,可以作为[registerApplicationStateObserver](js-apis-application-appManager.md#appmanagerregisterapplicationstateobserver8)的入参监听当前应用的生命周期变化。
## 导入模块
```ts
import appManager from '@ohos.application.appManager';
```
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core
**系统API**:该接口为系统接口,三方应用不支持调用。 **系统API**:该接口为系统接口,三方应用不支持调用。
......
...@@ -6,6 +6,12 @@ BaseContext抽象类用于表示继承的子类Context是Stage模型还是FA模 ...@@ -6,6 +6,12 @@ BaseContext抽象类用于表示继承的子类Context是Stage模型还是FA模
> >
> 本模块首批接口从API version 8 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 8 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 导入模块
```ts
import common from '@ohos.app.ability.common';
```
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core **系统能力**:SystemCapability.Ability.AbilityRuntime.Core
| 名称 | 类型 | 可读 | 可写 | 说明 | | 名称 | 类型 | 可读 | 可写 | 说明 |
......
...@@ -7,6 +7,12 @@ Context模块提供了ability或application的上下文的能力,包括访问 ...@@ -7,6 +7,12 @@ Context模块提供了ability或application的上下文的能力,包括访问
> - 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > - 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
> - 本模块接口仅可在Stage模型下使用。 > - 本模块接口仅可在Stage模型下使用。
## 导入模块
```ts
import common from '@ohos.app.ability.common';
```
## 属性 ## 属性
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core
...@@ -50,7 +56,7 @@ createBundleContext(bundleName: string): Context; ...@@ -50,7 +56,7 @@ createBundleContext(bundleName: string): Context;
**示例:** **示例:**
```ts ```ts
let bundleContext; let bundleContext: common.Context;
try { try {
bundleContext = this.context.createBundleContext('com.example.test'); bundleContext = this.context.createBundleContext('com.example.test');
} catch (error) { } catch (error) {
...@@ -81,7 +87,7 @@ createModuleContext(moduleName: string): Context; ...@@ -81,7 +87,7 @@ createModuleContext(moduleName: string): Context;
**示例:** **示例:**
```ts ```ts
let moduleContext; let moduleContext: common.Context;
try { try {
moduleContext = this.context.createModuleContext('entry'); moduleContext = this.context.createModuleContext('entry');
} catch (error) { } catch (error) {
...@@ -113,7 +119,7 @@ createModuleContext(bundleName: string, moduleName: string): Context; ...@@ -113,7 +119,7 @@ createModuleContext(bundleName: string, moduleName: string): Context;
**示例:** **示例:**
```ts ```ts
let moduleContext; let moduleContext: common.Context;
try { try {
moduleContext = this.context.createModuleContext('com.example.test', 'entry'); moduleContext = this.context.createModuleContext('com.example.test', 'entry');
} catch (error) { } catch (error) {
...@@ -138,7 +144,7 @@ getApplicationContext(): ApplicationContext; ...@@ -138,7 +144,7 @@ getApplicationContext(): ApplicationContext;
**示例:** **示例:**
```ts ```ts
let applicationContext; let applicationContext: common.Context;
try { try {
applicationContext = this.context.getApplicationContext(); applicationContext = this.context.getApplicationContext();
} catch (error) { } catch (error) {
......
...@@ -2,6 +2,12 @@ ...@@ -2,6 +2,12 @@
定义异常监听,可以作为[ErrorManager.on](js-apis-app-ability-errorManager.md#errormanageron)的入参监听当前应用发生的异常。 定义异常监听,可以作为[ErrorManager.on](js-apis-app-ability-errorManager.md#errormanageron)的入参监听当前应用发生的异常。
## 导入模块
```ts
import errorManager from '@ohos.app.ability.errorManager';
```
## ErrorObserver.onUnhandledException ## ErrorObserver.onUnhandledException
onUnhandledException(errMsg: string): void; onUnhandledException(errMsg: string): void;
......
...@@ -7,6 +7,12 @@ EventHub模块提供了事件中心,提供订阅、取消订阅、触发事件 ...@@ -7,6 +7,12 @@ EventHub模块提供了事件中心,提供订阅、取消订阅、触发事件
> - 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > - 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
> - 本模块接口仅可在Stage模型下使用。 > - 本模块接口仅可在Stage模型下使用。
## 导入模块
```ts
import common from '@ohos.app.ability.common';
```
## 使用说明 ## 使用说明
在使用eventHub的功能前,需要通过UIAbility实例的成员变量context获取。 在使用eventHub的功能前,需要通过UIAbility实例的成员变量context获取。
......
...@@ -9,6 +9,12 @@ ExtensionContext模块提供访问特定Extension的资源的能力,对于拓 ...@@ -9,6 +9,12 @@ ExtensionContext模块提供访问特定Extension的资源的能力,对于拓
> - 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > - 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
> - 本模块接口仅可在Stage模型下使用。 > - 本模块接口仅可在Stage模型下使用。
## 导入模块
```ts
import common from '@ohos.app.ability.common';
```
## 属性 ## 属性
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core **系统能力**:SystemCapability.Ability.AbilityRuntime.Core
......
...@@ -7,6 +7,12 @@ ExtensionRunningInfo模块封装了Extension运行的相关信息,可以通过 ...@@ -7,6 +7,12 @@ ExtensionRunningInfo模块封装了Extension运行的相关信息,可以通过
> - 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > - 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
> - 本模块被标记为@systemapi,对三方应用隐藏 > - 本模块被标记为@systemapi,对三方应用隐藏
## 导入模块
```ts
import abilityManager from '@ohos.app.ability.abilityManager';
```
## 使用说明 ## 使用说明
导入abilityManager模块,通过调用abilityManager中的方法获取ExtensionRunningInfo。 导入abilityManager模块,通过调用abilityManager中的方法获取ExtensionRunningInfo。
......
...@@ -9,6 +9,12 @@ FormExtensionContext模块提供FormExtensionAbility具有的接口和能力。 ...@@ -9,6 +9,12 @@ FormExtensionContext模块提供FormExtensionAbility具有的接口和能力。
> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
> 本模块接口仅可在Stage模型下使用。 > 本模块接口仅可在Stage模型下使用。
## 导入模块
```ts
import common from '@ohos.app.ability.common';
```
## 使用说明 ## 使用说明
在使用FormExtensionContext的功能前,需要通过FormExtensionAbility获取。 在使用FormExtensionContext的功能前,需要通过FormExtensionAbility获取。
......
...@@ -2,6 +2,12 @@ ...@@ -2,6 +2,12 @@
表示任务的详细信息,可以通过[getMissionInfo](js-apis-app-ability-missionManager.md#missionmanagergetmissioninfo)获取。 表示任务的详细信息,可以通过[getMissionInfo](js-apis-app-ability-missionManager.md#missionmanagergetmissioninfo)获取。
## 导入模块
```ts
import missionManager from '@ohos.app.ability.missionManager';
```
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Mission **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Mission
**系统API**: 此接口为系统接口,三方应用不支持调用。 **系统API**: 此接口为系统接口,三方应用不支持调用。
......
...@@ -2,6 +2,12 @@ ...@@ -2,6 +2,12 @@
定义系统任务状态监听,可以通过[on](js-apis-app-ability-missionManager.md#missionmanageron)注册。 定义系统任务状态监听,可以通过[on](js-apis-app-ability-missionManager.md#missionmanageron)注册。
## 导入模块
```ts
import missionManager from '@ohos.app.ability.missionManager';
```
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Mission **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Mission
| 名称 | 类型 | 必填 | 说明 | | 名称 | 类型 | 必填 | 说明 |
......
...@@ -7,6 +7,12 @@ ...@@ -7,6 +7,12 @@
> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
> 本模块接口均为系统接口,三方应用不支持调用 > 本模块接口均为系统接口,三方应用不支持调用
## 导入模块
```ts
import missionManager from '@ohos.app.ability.missionManager';
```
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Mission **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Mission
| 名称 | 类型 | 可读 | 可写 | 说明 | | 名称 | 类型 | 可读 | 可写 | 说明 |
......
...@@ -2,6 +2,12 @@ ...@@ -2,6 +2,12 @@
进程数据的对象定义。使用接口[registerApplicationStateObserver](js-apis-application-appManager.md#appmanagerregisterapplicationstateobserver8)注册生命周期变化监听后,当应用或组件的生命周期变化时,系统通过[ApplicationStateObserver](js-apis-inner-application-applicationStateObserver.md)的onProcessCreated等方法回调给开发者。 进程数据的对象定义。使用接口[registerApplicationStateObserver](js-apis-application-appManager.md#appmanagerregisterapplicationstateobserver8)注册生命周期变化监听后,当应用或组件的生命周期变化时,系统通过[ApplicationStateObserver](js-apis-inner-application-applicationStateObserver.md)的onProcessCreated等方法回调给开发者。
## 导入模块
```ts
import appManager from '@ohos.app.ability.appManager';
```
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core
**系统API**:该接口为系统接口,三方应用不支持调用。 **系统API**:该接口为系统接口,三方应用不支持调用。
......
...@@ -6,6 +6,12 @@ ProcessInformation模块提供对进程运行信息进行查询的能力。 ...@@ -6,6 +6,12 @@ ProcessInformation模块提供对进程运行信息进行查询的能力。
> >
> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 导入模块
```ts
import appManager from '@ohos.app.ability.appManager';
```
## 使用说明 ## 使用说明
通过appManager的[getRunningProcessInformation](js-apis-app-ability-appManager.md#appmanagergetrunningprocessinformation9)来获取。 通过appManager的[getRunningProcessInformation](js-apis-app-ability-appManager.md#appmanagergetrunningprocessinformation9)来获取。
......
...@@ -6,6 +6,12 @@ ...@@ -6,6 +6,12 @@
> - 本模块接口从API version 9 开始废弃,建议使用[ProcessInformation<sup>9+</sup>](js-apis-inner-application-processInformation.md)替代。 > - 本模块接口从API version 9 开始废弃,建议使用[ProcessInformation<sup>9+</sup>](js-apis-inner-application-processInformation.md)替代。
> - 本模块首批接口从API version 8 开始支持。 > - 本模块首批接口从API version 8 开始支持。
## 导入模块
```ts
import appManager from '@ohos.app.ability.appManager';
```
## 属性 ## 属性
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Mission **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Mission
......
...@@ -9,6 +9,12 @@ ServiceExtensionContext模块提供ServiceExtensionAbility具有的能力,包 ...@@ -9,6 +9,12 @@ ServiceExtensionContext模块提供ServiceExtensionAbility具有的能力,包
> - 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > - 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
> - 本模块接口仅可在Stage模型下使用。 > - 本模块接口仅可在Stage模型下使用。
## 导入模块
```ts
import common from '@ohos.app.ability.common';
```
## 使用说明 ## 使用说明
在使用ServiceExtensionContext的功能前,需要通过ServiceExtensionAbility子类实例获取。 在使用ServiceExtensionContext的功能前,需要通过ServiceExtensionAbility子类实例获取。
......
...@@ -6,6 +6,12 @@ ...@@ -6,6 +6,12 @@
> >
> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 导入模块
```ts
import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry';
```
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core
| 名称 | 类型 | 可读 | 可写 | 说明 | | 名称 | 类型 | 可读 | 可写 | 说明 |
...@@ -20,7 +26,7 @@ ...@@ -20,7 +26,7 @@
**示例:** **示例:**
```ts ```ts
import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry';
let abilityDelegator; let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
let cmd = 'cmd'; let cmd = 'cmd';
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
......
...@@ -7,6 +7,12 @@ UIAbilityContext是[UIAbility](js-apis-app-ability-uiAbility.md)的上下文环 ...@@ -7,6 +7,12 @@ UIAbilityContext是[UIAbility](js-apis-app-ability-uiAbility.md)的上下文环
> - 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > - 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
> - 本模块接口仅可在Stage模型下使用。 > - 本模块接口仅可在Stage模型下使用。
## 导入模块
```ts
import common from '@ohos.app.ability.common';
```
## 属性 ## 属性
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core
......
...@@ -2,6 +2,12 @@ ...@@ -2,6 +2,12 @@
作为[trigger](js-apis-app-ability-wantAgent.md#wantagenttrigger)的入参定义触发WantAgent所需要的信息。 作为[trigger](js-apis-app-ability-wantAgent.md#wantagenttrigger)的入参定义触发WantAgent所需要的信息。
## 导入模块
```ts
import wantAgent from '@ohos.app.ability.wantAgent';
```
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core
| 名称 | 类型 | 必填 | 说明 | | 名称 | 类型 | 必填 | 说明 |
......
...@@ -2,6 +2,12 @@ ...@@ -2,6 +2,12 @@
定义触发WantAgent所需要的信息,可以作为[getWantAgent](js-apis-app-ability-wantAgent.md#wantagentgetwantagent)的入参创建指定的WantAgent对象。 定义触发WantAgent所需要的信息,可以作为[getWantAgent](js-apis-app-ability-wantAgent.md#wantagentgetwantagent)的入参创建指定的WantAgent对象。
## 导入模块
```ts
import wantAgent from '@ohos.app.ability.wantAgent';
```
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core
| 名称 | 类型 | 必填 | 说明 | | 名称 | 类型 | 必填 | 说明 |
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册