提交 23949e52 编写于 作者: S swx1239486

Merge branch 'master' of https://gitee.com/playing-song/docs

......@@ -17,3 +17,4 @@ OpenHarmony_Icons.zip filter=lfs diff=lfs merge=lfs -text
zip filter=lfs diff=lfs merge=lfs -text
figures/OpenHarmony_Icons.zip filter=lfs diff=lfs merge=lfs -text
figures/OpenHarmony应用图标模版.zip filter=lfs diff=lfs merge=lfs -text
figures/OpenHarmony_天气应用UX设计交付件_V1.0.zip filter=lfs diff=lfs merge=lfs -text
......@@ -36,7 +36,7 @@ You can use [ohos.file.fs](../reference/apis/js-apis-file-fs.md) to implement ac
First, obtain the [application file path](../application-models/application-context-stage.md#obtaining-application-file-paths). 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).
Then, perform common file operations.
Then, perform file operations.
### Creating, Reading, and Writing a File
......@@ -46,21 +46,29 @@ The following example demonstrates how to create a file, read data from it, and
// pages/xxx.ets
import fs from '@ohos.file.fs';
import common from '@ohos.app.ability.common';
import buffer from '@ohos.buffer';
function createFile() {
// Obtain the application file path.
let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir;
// Obtain the application file path.
let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir;
// Create a file and open it.
function createFile() {
// 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))));
let arrayBuffer = new ArrayBuffer(1024);
class Option {
public offset: number = 0;
public length: number;
}
let option = new Option();
option.length = arrayBuffer.byteLength;
let readLen = fs.readSync(file.fd, arrayBuffer, option);
let buf = buffer.from(arrayBuffer, 0, readLen);
console.info("the content of file: " + buf.toString());
// Close the file.
fs.closeSync(file);
}
......@@ -75,11 +83,11 @@ function createFile() {
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;
// Obtain the application file path.
let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir;
function readWriteFile() {
// 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);
......@@ -87,11 +95,18 @@ function readWriteFile() {
let bufSize = 4096;
let readSize = 0;
let buf = new ArrayBuffer(bufSize);
let readLen = fs.readSync(srcFile.fd, buf, { offset: readSize });
class Option {
public offset: number = 0;
public length: number = bufSize;
}
let option = new Option();
option.offset = readSize;
let readLen = fs.readSync(srcFile.fd, buf, option);
while (readLen > 0) {
readSize += readLen;
fs.writeSync(destFile.fd, buf);
readLen = fs.readSync(srcFile.fd, buf, { offset: readSize });
option.offset = readSize;
readLen = fs.readSync(srcFile.fd, buf, option);
}
// Close the files.
fs.closeSync(srcFile);
......@@ -112,11 +127,11 @@ The following example demonstrates how to read and write file data using a strea
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;
// Obtain the application file path.
let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir;
async function readWriteFileWithStream() {
// Open the file streams.
let inputStream = fs.createStreamSync(filesDir + '/test.txt', 'r+');
let outputStream = fs.createStreamSync(filesDir + '/destFile.txt', "w+");
......@@ -124,11 +139,18 @@ async function readWriteFileWithStream() {
let bufSize = 4096;
let readSize = 0;
let buf = new ArrayBuffer(bufSize);
let readLen = await inputStream.read(buf, { offset: readSize });
class Option {
public offset: number = 0;
public length: number = bufSize;
}
let option = new Option();
option.offset = readSize;
let readLen = await inputStream.read(buf, option);
readSize += readLen;
while (readLen > 0) {
await outputStream.write(buf);
readLen = await inputStream.read(buf, { offset: readSize });
option.offset = readSize;
readLen = await inputStream.read(buf, option);
readSize += readLen;
}
// Close the streams.
......@@ -148,8 +170,7 @@ async function readWriteFileWithStream() {
The following example demonstrates how to list files that meet the specified conditions.
```ts
// List files.
import fs from '@ohos.file.fs';
import fs, { Filter } from '@ohos.file.fs';
import common from '@ohos.app.ability.common';
// Obtain the application file path.
......@@ -157,18 +178,20 @@ 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]}`);
function getListFile() {
class ListFileOption {
public recursion: boolean = false;
public listNum: number = 0;
public filter: Filter
}
let option = new ListFileOption();
option.filter.suffix = ['.png', '.jpg', '.txt']; // The filen ame extension can be '.png', '.jpg', or '.txt'.
option.filter.displayName = ['test%']; // The file name starts with 'test'.
option.filter.fileSizeOver = 0; // The file size is greater than or equal to 0.
option.filter.lastModifiedAfter = new Date(0).getTime(); // The latest modification time of the file is later than January 1, 1970.
let files = fs.listFileSync(filesDir, option);
for (let i = 0; i < files.length; i++) {
console.info(`The name of file: ${files[i]}`);
}
}
```
......@@ -32,17 +32,25 @@ The capability file of an application contains the device type, device version,
Use **backup.getLocalCapabilities()** to obtain capability files.
```js
```ts
import backup from '@ohos.file.backup';
import common from '@ohos.app.ability.common';
import fs from '@ohos.file.fs';
// Obtain the application file path.
let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir;
async function getLocalCapabilities() {
try {
let fileData = await backup.getLocalCapabilities();
console.info('getLocalCapabilities success');
let fpath = await globalThis.context.filesDir + '/localCapabilities.json';
let fpath = filesDir + '/localCapabilities.json';
fs.copyFileSync(fileData.fd, fpath);
fs.closeSync(fileData.fd);
} catch (err) {
console.error('getLocalCapabilities failed with err: ' + err);
} catch (error) {
let err: BusinessError = error as BusinessError;
console.error('getLocalCapabilities failed with err: ' + JSON.stringify(err));
}
}
```
......@@ -88,17 +96,24 @@ You can save the file to a local directory as required.
**Example**
```ts
import backup from '@ohos.file.backup';
import common from '@ohos.app.ability.common';
import fs from '@ohos.file.fs';
import { BusinessError } from '@ohos.base';
// Obtain the sandbox path.
let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir;
// Create a SessionBackup instance for data backup.
let g_session;
let g_session: backup.SessionBackup;
function createSessionBackup() {
let sessionBackup = new backup.SessionBackup({
onFileReady: async (err, file) => {
let generalCallbacks: backup.GeneralCallbacks = {
onFileReady: (err: BusinessError, file: backup.File) => {
if (err) {
console.info('onFileReady err: ' + err);
console.info('onFileReady err: ' + JSON.stringify(err));
}
try {
let bundlePath = await globalThis.context.filesDir + '/' + file.bundleName;
let bundlePath = filesDir + '/' + file.bundleName;
if (!fs.accessSync(bundlePath)) {
fs.mkdirSync(bundlePath);
}
......@@ -109,23 +124,23 @@ You can save the file to a local directory as required.
console.error('onFileReady failed with err: ' + e);
}
},
onBundleBegin: (err, bundleName) => {
onBundleBegin: (err: BusinessError, bundleName: string) => {
if (err) {
console.info('onBundleBegin err: ' + err);
console.info('onBundleBegin err: ' + JSON.stringify(err));
} else {
console.info('onBundleBegin bundleName: ' + bundleName);
}
},
onBundleEnd: (err, bundleName) => {
onBundleEnd: (err: BusinessError, bundleName: string) => {
if (err) {
console.info('onBundleEnd err: ' + err);
console.info('onBundleEnd err: ' + JSON.stringify(err));
} else {
console.info('onBundleEnd bundleName: ' + bundleName);
}
},
onAllBundlesEnd: (err) => {
onAllBundlesEnd: (err: BusinessError) => {
if (err) {
console.info('onAllBundlesEnd err: ' + err);
console.info('onAllBundlesEnd err: ' + JSON.stringify(err));
} else {
console.info('onAllBundlesEnd');
}
......@@ -133,16 +148,16 @@ You can save the file to a local directory as required.
onBackupServiceDied: () => {
console.info('onBackupServiceDied');
},
});
}
let sessionBackup = new backup.SessionBackup(generalCallbacks);
return sessionBackup;
}
async function sessionBackup ()
{
async function sessionBackup () {
g_session = createSessionBackup();
// Select the application to be backed up based on the capability file obtained by backup.getLocalCapabilities().
// You can also back up data based on the application bundle name.
const backupApps = [
const backupApps: string[] = [
"com.example.hiworld",
]
await g_session.appendBundles(backupApps);
......@@ -161,24 +176,26 @@ When all the data of the application is ready, the service starts to restore the
**Example**
```ts
import backup from '@ohos.file.backup';
import fs from '@ohos.file.fs';
import { BusinessError } from '@ohos.base';
// Create a SessionRestore instance for data restoration.
let g_session;
async function publishFile(file)
{
await g_session.publishFile({
let g_session: backup.SessionRestore;
async function publishFile(file: backup.File) {
let fileMeta: backup.FileMeta = {
bundleName: file.bundleName,
uri: file.uri
});
}
await g_session.publishFile(fileMeta);
}
function createSessionRestore() {
let sessionRestore = new backup.SessionRestore({
onFileReady: (err, file) => {
let generalCallbacks: backup.GeneralCallbacks = {
onFileReady: (err: BusinessError, file: backup.File) => {
if (err) {
console.info('onFileReady err: ' + err);
console.info('onFileReady err: ' + JSON.stringify(err));
}
// Set bundlePath based on the actual situation.
let bundlePath;
let bundlePath: string;
if (!fs.accessSync(bundlePath)) {
console.info('onFileReady bundlePath err : ' + bundlePath);
}
......@@ -188,52 +205,51 @@ When all the data of the application is ready, the service starts to restore the
publishFile(file);
console.info('onFileReady success');
},
onBundleBegin: (err, bundleName) => {
onBundleBegin: (err: BusinessError, bundleName: string) => {
if (err) {
console.error('onBundleBegin failed with err: ' + err);
console.error('onBundleBegin failed with err: ' + JSON.stringify(err));
}
console.info('onBundleBegin success');
},
onBundleEnd: (err, bundleName) => {
onBundleEnd: (err: BusinessError, bundleName: string) => {
if (err) {
console.error('onBundleEnd failed with err: ' + err);
console.error('onBundleEnd failed with err: ' + JSON.stringify(err));
}
console.info('onBundleEnd success');
},
onAllBundlesEnd: (err) => {
onAllBundlesEnd: (err: BusinessError) => {
if (err) {
console.error('onAllBundlesEnd failed with err: ' + err);
console.error('onAllBundlesEnd failed with err: ' + JSON.stringify(err));
}
console.info('onAllBundlesEnd success');
},
onBackupServiceDied: () => {
console.info('service died');
}
});
}
let sessionRestore = new backup.SessionRestore(generalCallbacks);
return sessionRestore;
}
async function restore ()
{
async function restore01 () {
g_session = createSessionRestore();
const backupApps = [
const restoreApps: string[] = [
"com.example.hiworld",
]
// You can obtain the capability file based on actual situation. The following is an example only.
// You can also construct capability files as required.
let fileData = await backup.getLocalCapabilities();
await g_session.appendBundles(fileData.fd, backupApps);
await g_session.appendBundles(fileData.fd, restoreApps);
console.info('appendBundles success');
// After the applications to be restored are added, call getFileHandle() to obtain the handles of the application files to be restored based on the application name.
// The number of application data files to be restored varies depending on the number of backup files. The following is only an example.
await g_session.getFileHandle({
let handle: backup.FileMeta = {
bundleName: restoreApps[0],
uri: "manage.json"
});
await g_session.getFileHandle({
bundleName: restoreApps[0],
uri: "1.tar"
});
}
await g_session.getFileHandle(handle);
handle.uri = "1.tar";
await g_session.getFileHandle(handle);
console.info('getFileHandle success');
}
```
......@@ -249,23 +265,30 @@ If the application has not been installed, you can install the application and t
**Example**
```ts
import backup from '@ohos.file.backup';
import common from '@ohos.app.ability.common';
import fs from '@ohos.file.fs';
import { BusinessError } from '@ohos.base';
// Obtain the sandbox path.
let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir;
// Create a SessionRestore instance for data restoration.
let g_session;
async function publishFile(file)
{
await g_session.publishFile({
let g_session: backup.SessionRestore;
async function publishFile(file: backup.File) {
let fileMeta: backup.FileMeta = {
bundleName: file.bundleName,
uri: file.uri
});
}
await g_session.publishFile(fileMeta);
}
function createSessionRestore() {
let sessionRestore = new backup.SessionRestore({
onFileReady: (err, file) => {
if (err) {
console.info('onFileReady err: ' + err);
}
let bundlePath;
let generalCallbacks: backup.GeneralCallbacks = {
onFileReady: (err: BusinessError, file: backup.File) => {
if (err) {
console.info('onFileReady err: ' + JSON.stringify(err));
}
let bundlePath: string;
if( file.uri == "/data/storage/el2/restore/bundle.hap" )
{
// Set the path of the application installation package based on actual situation.
......@@ -281,61 +304,57 @@ If the application has not been installed, you can install the application and t
publishFile(file);
console.info('onFileReady success');
},
onBundleBegin: (err, bundleName) => {
onBundleBegin: (err: BusinessError, bundleName: string) => {
if (err) {
console.error('onBundleBegin failed with err: ' + err);
console.error('onBundleBegin failed with err: ' + JSON.stringify(err));
}
console.info('onBundleBegin success');
},
onBundleEnd: (err, bundleName) => {
onBundleEnd: (err: BusinessError, bundleName: string) => {
if (err) {
console.error('onBundleEnd failed with err: ' + err);
console.error('onBundleEnd failed with err: ' + JSON.stringify(err));
}
console.info('onBundleEnd success');
},
onAllBundlesEnd: (err) => {
onAllBundlesEnd: (err: BusinessError) => {
if (err) {
console.error('onAllBundlesEnd failed with err: ' + err);
console.error('onAllBundlesEnd failed with err: ' + JSON.stringify(err));
}
console.info('onAllBundlesEnd success');
},
onBackupServiceDied: () => {
console.info('service died');
}
});
}
let sessionRestore = new backup.SessionRestore(generalCallbacks);
return sessionRestore;
}
async function restore ()
{
async function restore02 () {
g_session = createSessionRestore();
const backupApps = [
const restoreApps: string[] = [
"com.example.hiworld",
]
let fpath = await globalThis.context.filesDir + '/localCapabilities.json';
let file = fs.openSync(fpath, fileIO.OpenMode.CREATE | fileIO.OpenMode.READ_WRITE);
let fpath = filesDir + '/localCapabilities.json';
let file = fs.openSync(fpath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
let content = "{\"bundleInfos\" :[{\"allToBackup\" : false,\"extensionName\" : \"\"," +
"\"name\" : \"cn.openharmony.inputmethodchoosedialog\",\"needToInstall\" : true,\"spaceOccupied\" : 0," +
"\"versionCode\" : 1000000,\"versionName\" : \"1.0.0\"}],\"deviceType\" : \"default\",\"systemFullName\" : \"OpenHarmony-4.0.6.2(Canary1)\"}";
fs.writeSync(file.fd, content);
fs.fsyncSync(file.fd);
await g_session.appendBundles(file.fd, backupApps);
await g_session.appendBundles(file.fd, restoreApps);
console.info('appendBundles success');
// Obtain the file handle of the application to be installed.
await g_session.getFileHandle({
let handle: backup.FileMeta = {
bundleName: restoreApps[0],
uri: "/data/storage/el2/restore/bundle.hap"
});
await g_session.getFileHandle({
bundleName: restoreApps[0],
uri: "manage.json"
});
await g_session.getFileHandle({
bundleName: restoreApps[0],
uri: "1.tar"
});
}
await g_session.getFileHandle(handle);
handle.uri = "manage.json";
await g_session.getFileHandle(handle);
handle.uri = "1.tar";
await g_session.getFileHandle(handle);
console.info('getFileHandle success');
}
```
......
......@@ -19,6 +19,7 @@ The following example demonstrates how to upload a file in the **cache** directo
import common from '@ohos.app.ability.common';
import fs from '@ohos.file.fs';
import request from '@ohos.request';
import { BusinessError } from '@ohos.base';
// Obtain the application file path.
let context = getContext(this) as common.UIAbilityContext;
......@@ -30,32 +31,36 @@ fs.writeSync(file.fd, 'upload file test');
fs.closeSync(file);
// Configure the upload task.
let uploadConfig = {
let header = new Map<Object, string>();
header.set('key1', 'value1');
header.set('key2', 'value2');
let files: Array<request.File> = [
{ filename: 'test.txt', name: 'test', uri: 'internal://cache/test.txt', type: 'txt' }
]
let data: Array<request.RequestData> = [{ name: 'name', value: 'value' }];
let uploadConfig: request.UploadConfig = {
url: 'https://xxx',
header: { key1: 'value1', key2: 'value2' },
header: header,
method: 'POST',
files: [
{ filename: 'test.txt', name: 'test', uri: 'internal://cache/test.txt', type: 'txt' }
],
data: [
{ name: 'name', value: 'value' }
]
files: files,
data: data
}
// Upload the created application file to the network server.
try {
request.uploadFile(context, uploadConfig)
.then((uploadTask) => {
uploadTask.on('complete', (taskStates) => {
.then((uploadTask: request.UploadTask) => {
uploadTask.on('complete', (taskStates: Array<request.TaskState>) => {
for (let i = 0; i < taskStates.length; i++) {
console.info(`upload complete taskState: ${JSON.stringify(taskStates[i])}`);
}
});
})
.catch((err) => {
.catch((err: BusinessError) => {
console.error(`Invoke uploadFile failed, code is ${err.code}, message is ${err.message}`);
})
} catch (err) {
} catch (error) {
let err: BusinessError = error as BusinessError;
console.error(`Invoke uploadFile failed, code is ${err.code}, message is ${err.message}`);
}
```
......@@ -78,6 +83,8 @@ The following example demonstrates how to download a network resource file to a
import common from '@ohos.app.ability.common';
import fs from '@ohos.file.fs';
import request from '@ohos.request';
import { BusinessError } from '@ohos.base';
import buffer from '@ohos.buffer';
// Obtain the application file path.
let context = getContext(this) as common.UIAbilityContext;
......@@ -87,19 +94,21 @@ try {
request.downloadFile(context, {
url: 'https://xxxx/xxxx.txt',
filePath: filesDir + '/xxxx.txt'
}).then((downloadTask) => {
}).then((downloadTask: request.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)))}`);
let arrayBuffer = new ArrayBuffer(1024);
let readLen = fs.readSync(file.fd, arrayBuffer);
let buf = buffer.from(arrayBuffer, 0, readLen);
console.info(`The content of file: ${buf.toString()}`);
fs.closeSync(file);
})
}).catch((err) => {
}).catch((err: BusinessError) => {
console.error(`Invoke downloadTask failed, code is ${err.code}, message is ${err.message}`);
});
} catch (err) {
} catch (error) {
let err: BusinessError = error as BusinessError;
console.error(`Invoke downloadFile failed, code is ${err.code}, message is ${err.message}`);
}
```
......@@ -10,13 +10,13 @@ For details about the APIs, see [ohos.file.statvfs](../reference/apis/js-apis-fi
| Module| API| Description|
| -------- | -------- | -------- |
| \@ohos.file.storageStatistics | 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.|
| \@ohos.file.storageStatistics | 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|
| BundleStats Attribute| Description| Directory for Statistics|
| -------- | -------- | -------- |
| appSize | Size of the application installation files, in bytes.| /data/storage/el1/bundle |
| cacheSize | Size of the application cache files, in bytes.| /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 |
......@@ -25,12 +25,13 @@ For details about the APIs, see [ohos.file.statvfs](../reference/apis/js-apis-fi
## Development Example
- Obtain the free space of **/data** of the file system.
```ts
import statvfs from '@ohos.file.statvfs';
import { BusinessError } from '@ohos.base';
let path = "/data";
statvfs.getFreeSize(path, (err, number) => {
statvfs.getFreeSize(path, (err: BusinessError, number: number) => {
if (err) {
console.error(`Invoke getFreeSize failed, code is ${err.code}, message is ${err.message}`);
} else {
......@@ -40,11 +41,12 @@ For details about the APIs, see [ohos.file.statvfs](../reference/apis/js-apis-fi
```
- Obtain the space occupied by the current application.
```ts
import storageStatistics from "@ohos.file.storageStatistics";
import { BusinessError } from '@ohos.base';
storageStatistics.getCurrentBundleStats((err, bundleStats) => {
storageStatistics.getCurrentBundleStats((err: BusinessError, bundleStats: storageStatistics.BundleStats) => {
if (err) {
console.error(`Invoke getCurrentBundleStats failed, code is ${err.code}, message is ${err.message}`);
} else {
......
......@@ -8,82 +8,89 @@ For details about the APIs used to develop a file manager application, see [User
## How to Develop
1. Apply for permissions required.<br>
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).
1. Apply for permissions required.
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** allows your application to use the user file access framework APIs.
>
> **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** allows your application to obtain information about file management server applications supported by the system.
> - **ohos.permission.FILE_ACCESS_MANAGER** allows your application to use the user file access framework APIs.
>- **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** allows your application to obtain information about file management server applications supported by the system.
2. Import dependent modules.
```ts
import fileAccess from '@ohos.file.fileAccess';
import fileExtensionInfo from '@ohos.file.fileExtensionInfo';
import { Filter } from '@ohos.file.fs';
import common from '@ohos.app.ability.common';
import { BusinessError } from '@ohos.base';
```
The **fileAccess** module provides APIs for basic file operations, and the **fileExtensionInfo** module provides key structs for application development.
3. Query device information.<br>
3. Query device information.
You can obtain attributes of the devices managed by one or all file management servers in the 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
// Obtain the application context.
let context = getContext(this) as common.UIAbilityContext;
// Create a helper object for connecting to all file management servers in the system.
let fileAccessHelperAllServer = null;
createFileAccessHelper() {
let fileAccessHelperAllServer: fileAccess.FileAccessHelper;
function createFileAccessHelper() {
try { // this.context is the context passed from EntryAbility.
fileAccessHelperAllServer = fileAccess.createFileAccessHelper(this.context);
fileAccessHelperAllServer = fileAccess.createFileAccessHelper(context);
if (!fileAccessHelperAllServer) {
console.error("createFileAccessHelper interface returns an undefined object");
}
} catch (error) {
} catch (err) {
let error: BusinessError = err as BusinessError;
console.error("createFileAccessHelper failed, errCode:" + error.code + ", errMessage:" + error.message);
}
}
async getRoots() {
let rootIterator = null;
let rootInfos = [];
let isDone = false;
let rootInfos: Array<fileAccess.RootInfo> = [];
async function getRoots() {
let rootIterator: fileAccess.RootIterator;
let isDone: boolean = false;
try {
rootIterator = await fileAccessHelperAllServer.getRoots();
if (!rootIterator) {
console.error("getRoots interface returns an undefined object");
return;
}
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) {
rootInfos.push(result.value);
}
} catch (err) {
let error: BusinessError = err as BusinessError;
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 obtain a **FileIterator** object that traverses all files (directories) of the next level or use **scanfile()** to obtain a **FileIterator** object that meets the specified conditions.
Currently, **listfile()** and **scanfile()** can be called by the **RootInfo** object to traverse the next-level files or filter the entire directory tree. In addition, **listfile()** and **scanfile()** can be called by the **FileInfo** object to traverse the next-level files or filter the 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 device rootinfos[0] files that meet the specified conditions and return an iteration object.
let rootInfo = rootInfos[0];
let fileInfos: Array<fileAccess.FileInfo> = [];
let isDone: boolean = false;
let filter: Filter = {suffix : [".txt", ".jpg", ".xlsx"]}; // Set the filter.
try {
let fileIterator = rootInfo.listFile(); // Traverse the root directory of rootinfos[0] and return an iterator object.
// let fileIterator = rootInfo.scanFile(filter); // Filter device rootinfos[0] files that meet 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();
......@@ -92,35 +99,37 @@ For details about the APIs used to develop a file manager application, see [User
if (!isDone)
fileInfos.push(result.value);
}
} catch (error) {
} catch (err) {
let error: BusinessError = err as BusinessError;
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.
let fileInfoDir = fileInfos[0]; // fileInfoDir indicates information about a directory.
let subFileInfos: Array<fileAccess.FileInfo> = [];
let isDone02: boolean = false;
let filter02: Filter = {suffix : [".txt", ".jpg", ".xlsx"]}; // Set the filter.
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.
let fileIterator = fileInfoDir.listFile(); // Traverse files in the specified directory and return an iterator object.
// let fileIterator = rootInfo.scanFile(filter02); // 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) {
while (!isDone02) {
let result = fileIterator.next();
console.info("next result = " + JSON.stringify(result));
isDone = result.done;
if (!isDone)
subfileInfos.push(result.value);
isDone02 = result.done;
if (!isDone02)
subFileInfos.push(result.value);
}
} catch (error) {
} catch (err) {
let error: BusinessError = err as BusinessError;
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
......@@ -128,18 +137,20 @@ For details about the APIs used to develop a file manager application, see [User
// Create a file.
// sourceUri is the URI in fileinfo of the Download directory.
// You need to use the obtained URI for development.
let sourceUri = "file://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);
};
async function creatFile() {
let sourceUri: string = "file://docs/storage/Users/currentUser/Download";
let displayName: string = "file1";
let fileUri: string;
try {
// Obtain fileAccessHelperAllServer by referring to the sample code of fileAccess.createFileAccessHelper.
fileUri = await fileAccessHelperAllServer.createFile(sourceUri, displayName);
if (!fileUri) {
console.error("createFile return undefined object");
}
console.info("createFile sucess, fileUri: " + JSON.stringify(fileUri));
} catch (err) {
let error: BusinessError = err as BusinessError;
console.error("createFile failed, errCode:" + error.code + ", errMessage:" + error.message);
};
}
```
......@@ -8,8 +8,7 @@ For example, device A and device B are installed with the same application. Afte
1. Connect the devices to form a Super Device.
Connect the devices to a LAN, and complete authentication of the devices. The devices must have the same account number.
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.
......@@ -18,11 +17,13 @@ Connect the devices to a LAN, and complete authentication of the devices. The de
```ts
import fs from '@ohos.file.fs';
let context =...; // Obtain the UIAbilityContext information of device A.
let pathDir = context.distributedFilesDir;
import common from '@ohos.app.ability.common';
import { BusinessError } from '@ohos.base';
let context = getContext(this) as common.UIAbilityContext; // Obtain the UIAbilityContext of device A.
let pathDir: string = context.distributedFilesDir;
// Obtain the file path of the distributed directory.
let filePath = pathDir + '/test.txt';
let filePath: string = pathDir + '/test.txt';
try {
// Create a file in the distributed directory.
......@@ -32,7 +33,8 @@ Connect the devices to a LAN, and complete authentication of the devices. The de
fs.writeSync(file.fd, 'content');
// Close the file.
fs.closeSync(file.fd);
} catch (err) {
} catch (error) {
let err: BusinessError = error as BusinessError;
console.error(`Failed to openSync / writeSync / closeSync. Code: ${err.code}, message: ${err.message}`);
}
```
......@@ -41,24 +43,33 @@ Connect the devices to a LAN, and complete authentication of the devices. The de
```ts
import fs from '@ohos.file.fs';
import common from '@ohos.app.ability.common';
import buffer from '@ohos.buffer';
import { BusinessError } from '@ohos.base';
let context =...; // Obtain the UIAbilityContext information of device B.
let pathDir = context.distributedFilesDir;
let context = getContext(this) as common.UIAbilityContext; // Obtain the UIAbilityContext of device B.
let pathDir: string = context.distributedFilesDir;
// Obtain the file path of the distributed directory.
let filePath = pathDir + '/test.txt';
let filePath: string = 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);
let arrayBuffer = new ArrayBuffer(4096);
// Read the file. The return value is the number of read bytes.
let num = fs.readSync(file.fd, buffer, {
offset: 0
});
class Option {
public offset: number = 0;
public length: number;
}
let option = new Option();
option.length = arrayBuffer.byteLength;
let num = fs.readSync(file.fd, arrayBuffer, option);
// Print the read data.
console.info('read result: ' + String.fromCharCode.apply(null, new Uint8Array(buffer.slice(0, num))));
} catch (err) {
let buf = buffer.from(arrayBuffer, 0, num);
console.info('read result: ' + buf.toString());
} catch (error) {
let err: BusinessError = error as BusinessError;
console.error(`Failed to openSync / readSync. Code: ${err.code}, message: ${err.message}`);
}
```
......@@ -28,13 +28,13 @@ The following table describes the broadcast related parameters.
**Table 1** Broadcast parameters
| Broadcast| Parameter|
| 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.|
| 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
......@@ -55,29 +55,33 @@ You can subscribe to broadcast events to observe the insertion and removal of ex
```ts
import CommonEvent from '@ohos.commonEventManager';
import volumeManager from '@ohos.file.volumeManager';
const subscribeInfo = {
import { BusinessError } from '@ohos.base';
let subscriber: CommonEvent.CommonEventSubscriber;
async function example() {
const subscribeInfo: CommonEvent.CommonEventSubscribeInfo = {
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);
"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"
]
};
subscriber = await CommonEvent.createSubscriber(subscribeInfo);
}
```
3. Obtain volume information from the broadcast.
```ts
CommonEvent.subscribe(subscriber, function (err, data) {
CommonEvent.subscribe(subscriber, (err: BusinessError, data: CommonEvent.CommonEventData) => {
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) {
let volId: string = data.parameters.id;
volumeManager.getVolumeById(volId, (error: BusinessError, vol: volumeManager.Volume) => {
if (error) {
console.error('volumeManager getVolumeById failed');
console.error('volumeManager getVolumeById failed for ' + JSON.stringify(error));
} else {
console.info('volumeManager getVolumeById successfully, the volume state is ' + vol.state);
}
......
......@@ -18,37 +18,41 @@ For example, select an image from **Gallery** and save it to the file manager.
import fs from '@ohos.file.fs';
import photoAccessHelper from '@ohos.file.photoAccessHelper';
import dataSharePredicates from '@ohos.data.dataSharePredicates';
import common from '@ohos.app.ability.common';
import image from '@ohos.multimedia.image';
import { BusinessError } from '@ohos.base';
```
2. Obtain the thumbnail of the first image on the device. Before performing this operation, ensure that at least one image exists on the device.
```ts
const context = getContext(this);
let photoAccessHelper = photoAccessHelper.getPhotoAccessHelper(context);
let context = getContext(this) as common.UIAbilityContext;
let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context);
let pixelmapArrayBuffer;
async getPixelmap() {
let pixelmapArrayBuffer: ArrayBuffer;
async function getPixelmap() {
try {
let predicates = new dataSharePredicates.DataSharePredicates();
let fetchOption = {
let fetchOption: photoAccessHelper.FetchOptions = {
fetchColumns: [],
predicates: predicates
};
let fetchResult = await photoAccessHelper.getAssets(fetchOption);
let fetchResult = await phAccessHelper.getAssets(fetchOption);
console.info('[picker] getThumbnail fetchResult: ' + fetchResult);
const asset = await fetchResult.getFirstObject();
console.info('[picker] getThumbnail asset displayName = ', asset.displayName);
asset.getThumbnail().then((pixelMap) => {
asset.getThumbnail().then((pixelMap: image.PixelMap) => {
let pixelBytesNumber = pixelMap.getPixelBytesNumber();
const readBuffer = new ArrayBuffer(pixelBytesNumber);
pixelMap.readPixelsToBuffer(readBuffer).then(() => {
pixelmapArrayBuffer = readBuffer;
})
}).catch((err) => {
console.error('[picker] getThumbnail failed with error: ' + err);
}).catch((err: BusinessError) => {
console.error('[picker] getThumbnail failed with error: ' + JSON.stringify(err));
});
} catch (error) {
console.error('[picker] getThumbnail error = ' + error);
let err: BusinessError = error as BusinessError;
console.error('[picker] getThumbnail error = ' + JSON.stringify(err));
}
}
```
......@@ -58,8 +62,8 @@ For example, select an image from **Gallery** and save it to the file manager.
The permission on the URI returned by **save()** is read/write. Further operations on the file can be performed based on the URI in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening.
```ts
let uri:string;
async photoViewPickerSave() {
let uris: Array<string>;
async function photoViewPickerSave() {
try {
const photoSaveOptions = new picker.PhotoSaveOptions(); // Create a photoSaveOptions instance.
photoSaveOptions.newFileNames = ["PhotoViewPicker01.png"]; // (Optional) Name of the file to be saved. The file name in the square brackets can be customized and must be unique. If the file name already exists on the device, change the file name. Otherwise, an error will be returned.
......@@ -68,15 +72,16 @@ For example, select an image from **Gallery** and save it to the file manager.
try {
let photoSaveResult = await photoViewPicker.save(photoSaveOptions);
if (photoSaveResult != undefined) {
console.info("[picker] photoViewPickerSave photoSaveResult = " + JSON.stringify(photoSaveResult));
this.uri = photoSaveResult[0];
console.info('photoViewPicker.save to file succeed and uri is:' + photoSaveResult[0]);
uris = photoSaveResult;
console.info('photoViewPicker.save to file succeed and uris are:' + uris);
}
} catch (err) {
} catch (error) {
let err: BusinessError = error as BusinessError;
console.error(`[picker] Invoke photoViewPicker.save failed, code is ${err.code}, message is ${err.message}`);
}
} catch (error) {
console.info("[picker] photoViewPickerSave error = " + error);
let err: BusinessError = error as BusinessError;
console.info("[picker] photoViewPickerSave error = " + JSON.stringify(err));
}
}
```
......@@ -86,14 +91,15 @@ For example, select an image from **Gallery** and save it to the file manager.
Then, use [fs.write](../reference/apis/js-apis-file-fs.md#fswrite) to modify the file based on the FD, and close the FD after the modification is complete.
```ts
async writeOnly(uri) {
async function writeOnly(uri: string) {
try {
let file = fs.openSync(uri, fs.OpenMode.WRITE_ONLY);
let writeLen = await fs.write(file.fd, pixelmapArrayBuffer);
fs.closeSync(file);
console.info("[picker] writeOnly writeLen = " + writeLen);
} catch (error) {
console.info("[picker] writeOnly error: " + error);
let err: BusinessError = error as BusinessError;
console.info("[picker] writeOnly error: " + JSON.stringify(err));
}
}
```
......@@ -105,6 +111,7 @@ For example, select an image from **Gallery** and save it to the file manager.
```ts
import picker from '@ohos.file.picker';
import fs from '@ohos.file.fs';
import { BusinessError } from '@ohos.base';
```
2. Create a **documentSaveOptions** instance.
......@@ -112,6 +119,7 @@ For example, select an image from **Gallery** and save it to the file manager.
```ts
const documentSaveOptions = new picker.DocumentSaveOptions(); // Create a documentSaveOptions instance.
documentSaveOptions.newFileNames = ["DocumentViewPicker01.txt"]; // (Optional) Set the name of the document to save.
documentSaveOptions.fileSuffixChoices = ['.png', '.txt', '.mp4']; // (Optional) Types 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 document. After the user selects the destination folder, the document is saved and the URI of the document saved is returned.
......@@ -119,12 +127,12 @@ For example, select an image from **Gallery** and save it to the file manager.
The permission on the URI returned by **save()** is read/write. Further operations on the file can be performed based on the URI in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening.
```ts
let uri = null;
let uris: Array<string>;
const documentViewPicker = new picker.DocumentViewPicker(); // Create a documentViewPicker instance.
documentViewPicker.save(documentSaveOptions).then((documentSaveResult) => {
uri = documentSaveResult[0];
console.info('documentViewPicker.save to file succeed and uri is:' + uri);
}).catch((err) => {
documentViewPicker.save(documentSaveOptions).then((documentSaveResult: Array<string>) => {
uris = documentSaveResult;
console.info('documentViewPicker.save to file succeed and uris are:' + uris);
}).catch((err: BusinessError) => {
console.error(`Invoke documentViewPicker.save failed, code is ${err.code}, message is ${err.message}`);
})
```
......@@ -151,6 +159,7 @@ For example, select an image from **Gallery** and save it to the file manager.
```ts
import picker from '@ohos.file.picker';
import fs from '@ohos.file.fs';
import { BusinessError } from '@ohos.base';
```
2. Create an **audioSaveOptions** instance.
......@@ -160,17 +169,17 @@ For example, select an image from **Gallery** and save it to the file manager.
audioSaveOptions.newFileNames = ['AudioViewPicker01.mp3']; // (Optional) Set the name of the audio file 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 file. After the user selects the destination folder, the audio file is saved and the URI of the file saved is returned.
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 file. After the user selects the destination folder, the audio file is saved and the URI of the document saved is returned.
The permission on the URI returned by **save()** is read/write. Further operations on the file can be performed based on the URI in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening.
```ts
let uri = null;
let uri: string;
const audioViewPicker = new picker.AudioViewPicker();
audioViewPicker.save(audioSaveOptions).then((audioSelectResult) => {
audioViewPicker.save(audioSaveOptions).then((audioSelectResult: Array<string>) => {
uri = audioSelectResult[0];
console.info('audioViewPicker.save to file succeed and uri is:' + uri);
}).catch((err) => {
}).catch((err: BusinessError) => {
console.error(`Invoke audioViewPicker.save failed, code is ${err.code}, message is ${err.message}`);
})
```
......@@ -182,7 +191,7 @@ For example, select an image from **Gallery** and save it to the file manager.
console.info('file fd: ' + file.fd);
```
5. Use [fs.writeSync()](../reference/apis/js-apis-file-fs.md#writesync) to edit the file based on the FD, and then close the FD.
5. Use [fs.writeSync()](../reference/apis/js-apis-file-fs.md#writesync) to edit the document based on the FD, and then close the FD.
```ts
let writeLen = fs.writeSync(file.fd, 'hello, world');
......
......@@ -17,6 +17,7 @@ The **FilePicker** provides the following interfaces by file type:
```ts
import picker from '@ohos.file.picker';
import fs from '@ohos.file.fs';
import { BusinessError } from '@ohos.base';
```
2. Create a **photoSelectOptions** instance.
......@@ -38,12 +39,12 @@ The **FilePicker** provides the following interfaces by file type:
The permission on the URIs returned by **select()** is read-only. Further file operations can be performed based on the URIs in the **PhotoSelectResult**. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening.
```ts
let uri = null;
let uris: Array<string>;
const photoViewPicker = new picker.PhotoViewPicker();
photoViewPicker.select(photoSelectOptions).then((photoSelectResult) => {
uri = photoSelectResult.photoUris[0];
console.info('photoViewPicker.select to file succeed and uri is:' + uri);
}).catch((err) => {
photoViewPicker.select(photoSelectOptions).then((photoSelectResult: picker.PhotoSelectResult) => {
uris = photoSelectResult.photoUris;
console.info('photoViewPicker.select to file succeed and uris are:' + uris);
}).catch((err: BusinessError) => {
console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
})
```
......@@ -71,12 +72,17 @@ The **FilePicker** provides the following interfaces by file type:
```ts
import picker from '@ohos.file.picker';
import fs from '@ohos.file.fs';
import Want from '@ohos.app.ability.Want';
import { BusinessError } from '@ohos.base';
```
2. Create a **documentSelectOptions** instance.
```ts
const documentSelectOptions = new picker.DocumentSelectOptions();
documentSelectOptions.maxSelectNumber = 5; // (Optional) Maximum number of documents to select.
documentSelectOptions.defaultFilePathUri = "file://docs/storage/Users/currentUser/test"; // (Optional) Path of the file or directory to select.
documentSelectOptions.fileSuffixFilters = ['.png', '.txt', '.mp4']; // (Optional) File name extensions of the documents to select.
```
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, a result set containing the file URIs is returned.
......@@ -85,17 +91,13 @@ The **FilePicker** provides the following interfaces by file type:
For example, you can use [file management APIs](../reference/apis/js-apis-file-fs.md) to obtain file attributes, such as the file size, access time, and last modification time, based on the URI. If you need to obtain the file name, use [startAbilityForResult](../../application-dev/application-models/uiability-intra-device-interaction.md).
> **NOTE**
>
> Currently, **DocumentSelectOptions** is not configurable. By default, all types of user files are selected.
```ts
let uri = null;
let uris: Array<string>;
const documentViewPicker = new picker.DocumentViewPicker(); // Create a documentViewPicker instance.
documentViewPicker.select(documentSelectOptions).then((documentSelectResult) => {
uri = documentSelectResult[0];
console.info('documentViewPicker.select to file succeed and uri is:' + uri);
}).catch((err) => {
documentViewPicker.select(documentSelectOptions).then((documentSelectResult: Array<string>) => {
uris = documentSelectResult;
console.info('documentViewPicker.select to file succeed and uris are:' + uris);
}).catch((err: BusinessError) => {
console.error(`Invoke documentViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
})
```
......@@ -105,24 +107,27 @@ The **FilePicker** provides the following interfaces by file type:
> Currently, **DocumentSelectOptions** cannot be used to obtain the file name. To obtain the file name, use **startAbilityForResult()**.
```ts
let config = {
action: 'ohos.want.action.OPEN_FILE',
parameters: {
startMode: 'choose',
async function example() {
let config: Want = {
action: 'ohos.want.action.OPEN_FILE',
parameters: {
startMode: 'choose',
}
}
}
try {
let result = await context.startAbilityForResult(config, {windowMode: 1});
if (result.resultCode !== 0) {
console.error(`documentViewPicker.select failed, code is ${result.resultCode}, message is ${result.want.parameters.message}`);
return;
try {
let result = await context.startAbilityForResult(config, {windowMode: 1});
if (result.resultCode !== 0) {
console.error(`documentViewPicker.select failed, code is ${result.resultCode}, message is ${result.want.parameters.message}`);
return;
}
// Obtain the URI of the document.
let select_item_list = result.want.parameters.select_item_list;
// Obtain the name of the document.
let file_name_list = result.want.parameters.file_name_list;
} catch (error) {
let err: BusinessError = error as BusinessError;
console.error(`Invoke documentViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
}
// Obtain the URI of the document.
let select_item_list = result.want.parameters.select_item_list;
// Obtain the name of the document.
let file_name_list = result.want.parameters.file_name_list;
} catch (err) {
console.error(`Invoke documentViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
}
```
......@@ -150,6 +155,7 @@ The **FilePicker** provides the following interfaces by file type:
```ts
import picker from '@ohos.file.picker';
import fs from '@ohos.file.fs';
import { BusinessError } from '@ohos.base';
```
2. Create an **audioSelectOptions** instance.
......@@ -169,12 +175,12 @@ The **FilePicker** provides the following interfaces by file type:
> Currently, **AudioSelectOptions** is not configurable. By default, all types of user files are selected.
```ts
let uri = null;
let uri: string;
const audioViewPicker = new picker.AudioViewPicker();
audioViewPicker.select(audioSelectOptions).then(audioSelectResult => {
uri = audioSelectOptions[0];
audioViewPicker.select(audioSelectOptions).then((audioSelectResult: Array<string>) => {
uri = audioSelectResult[0];
console.info('audioViewPicker.select to file succeed and uri is:' + uri);
}).catch((err) => {
}).catch((err: BusinessError) => {
console.error(`Invoke audioViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
})
```
......
......@@ -13,7 +13,7 @@ For details about the APIs, see [ohos.file.securityLabel](../reference/apis/js-a
| setSecurityLabel | Sets a security label for a file.| Method| √ | √ |
| getSecurityLabel | Obtains the security label of a file.| Method| √ | √ |
> **NOTE**
> **NOTICE**
>
> - In distributed networking, a device can view the files that do not match its security level but cannot access them.
>
......@@ -26,16 +26,18 @@ Obtain the sandbox path of a file and set the data security label. For details a
```ts
import securityLabel from '@ohos.file.securityLabel';
import { BusinessError } from '@ohos.base';
import common from '@ohos.app.ability.common';
// Obtain the sandbox path of the file.
let context =...; // Obtain UIAbilityContext information.
let context = getContext(this) as common.UIAbilityContext; // Obtain UIAbilityContext.
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) => {
}).catch((err: BusinessError) => {
console.error(`Failed to setSecurityLabel. Code: ${err.code}, message: ${err.message}`);
});
```
......@@ -12,7 +12,7 @@ You can use the related APIs to [share a file with another application](#sharing
The file URIs are in the following format:
**file**://&lt;*bundleName*&gt;/&lt;*path*&gt;
**file://**&lt;bundleName&gt;/&lt;path&gt;
- **file**: indicates a file URI.
......@@ -30,7 +30,7 @@ Before sharing application files, you need to [obtain the application file path]
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.
......@@ -43,6 +43,7 @@ Before sharing application files, you need to [obtain the application file path]
```
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 obtained URI 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**
......@@ -51,37 +52,39 @@ Before sharing application files, you need to [obtain the application file path]
```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}`);
});
}
...
}
import window from '@ohos.window';
import wantConstant from '@ohos.app.ability.wantConstant';
import UIAbility from '@ohos.app.ability.UIAbility';
import Want from '@ohos.app.ability.Want';
import { BusinessError } from '@ohos.base';
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: 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: BusinessError) => {
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**.
......@@ -120,10 +123,12 @@ After obtaining the URI of the shared file from **want**, the application can ca
```ts
// xxx.ets
import fs from '@ohos.file.fs';
import Want from '@ohos.app.ability.Want';
import { BusinessError } from '@ohos.base';
function getShareFile() {
try {
let want =...; // Obtain the want information sent from the application that shares the file.
let want: Want = ...; // Obtain the want sent from the application that shares the file.
// Obtain the uri field from the want information.
let uri = want.uri;
......@@ -135,11 +140,13 @@ function getShareFile() {
// 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) {
} catch (err) {
let error: BusinessError = err as BusinessError;
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}`);
let err: BusinessError = error as BusinessError;
console.error(`Invoke openSync failed, code is ${err.code}, message is ${err.message}`);
}
}
```
......@@ -40,7 +40,7 @@ For details about the APIs, see [@ohos.app.ability.wantAgent](../reference/apis/
Scenario 1: Create a [WantAgentInfo](../reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md) object for starting a UIAbility component.
```typescript
let wantAgentObj:WantAgent = null; // Save the WantAgent object created. It will be used to complete the trigger operations.
let wantAgentObj:WantAgent; // Save the WantAgent object created. It will be used to complete the trigger operations.
// Set the action type through operationType of WantAgentInfo.
let wantAgentInfo:wantAgent.WantAgentInfo = {
......@@ -64,7 +64,7 @@ For details about the APIs, see [@ohos.app.ability.wantAgent](../reference/apis/
Scenario 2: Create a [WantAgentInfo](../reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md) object for publishing a [common event](../application-models/common-event-overview.md).
```typescript
let wantAgentObj:WantAgent = null; // Save the WantAgent object created. It will be used to complete the trigger operations.
let wantAgentObj:WantAgent; // Save the WantAgent object created. It will be used to complete the trigger operations.
// Set the action type through operationType of WantAgentInfo.
let wantAgentInfo:wantAgent.WantAgentInfo = {
......
......@@ -744,7 +744,7 @@ Subscribes to characteristic write request events.
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | -------------------------------------- |
| type | string | Yes | Event type. The value **characteristicWrite** indicates a characteristic write request event.|
| type | string | Yes | Event type. The value is **characteristicWrite**, which indicates a characteristic write request event.|
| callback | Callback&lt;[CharacteristicWriteRequest](#characteristicwriterequest)&gt; | Yes | Callback invoked to return a characteristic write request from the GATT client. |
**Example**
......@@ -983,6 +983,66 @@ gattServer.off('connectionStateChange');
```
### on('BLEMtuChange')
on(type: 'BLEMtuChange', callback: Callback&lt;number&gt;): void
Subscribes to MTU status changes for the server.
**Required permissions**: ohos.permission.ACCESS_BLUETOOTH
**System capability**: SystemCapability.Communication.Bluetooth.Core
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ---------------------------------------- |
| type | string | Yes | Type of event to subscribe to. The value is **BLEMtuChange**, which indicates the MTU status changes. If this parameter is not set correctly, the callback cannot be registered.|
| callback | Callback&lt;number&gt; | Yes | Callback invoked to return the number of MTU bytes.|
**Example**
```js
try {
let gattServer = ble.createGattServer();
gattServer.on('BLEMtuChange', (mtu) => {
console.info('BLEMtuChange, mtu: ' + mtu);
});
} catch (err) {
console.error('errCode: ' + err.code + ', errMessage: ' + err.message);
}
```
### off('BLEMtuChange')
off(type: 'BLEMtuChange', callback?: Callback&lt;number&gt;): void
Unsubscribes from MTU status changes for the server.
**Required permissions**: ohos.permission.ACCESS_BLUETOOTH
**System capability**: SystemCapability.Communication.Bluetooth.Core
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ---------------------------------------- |
| type | string | Yes | Type of event to unsubscribe from. The value is **BLEMtuChange**, which indicates the MTU status changes. If this parameter is not set correctly, the callback cannot be unregistered.|
| callback | Callback&lt;number&gt; | No | Callback for the MTU status changes. If this parameter is not set, this API unsubscribes from all callbacks corresponding to **type**.|
**Example**
```js
try {
let gattServer = ble.createGattServer();
gattServer.off('BLEMtuChange');
} catch (err) {
console.error('errCode: ' + err.code + ', errMessage: ' + err.message);
}
```
## GattClientDevice
Implements the GATT client. Before using an API of this class, you must create a **GattClientDevice** instance using **createGattClientDevice(deviceId: string)**.
......@@ -2179,7 +2239,7 @@ try {
on(type: 'BLEMtuChange', callback: Callback&lt;number&gt;): void
Subscribes to MTU status changes.
Subscribes to MTU status changes for the client.
**Required permissions**: ohos.permission.ACCESS_BLUETOOTH
......@@ -2189,8 +2249,8 @@ Subscribes to MTU status changes.
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ---------------------------------------- |
| type | string | Yes | Event type. The value is **BLEMtuChange**, which indicates a MTU status change event.|
| callback | Callback&lt;number&gt; | Yes | Callback invoked to return the MTU status, which can be connected or disconnected.|
| type | string | Yes | Type of event to subscribe to. The value is **BLEMtuChange**, which indicates the MTU status changes. If this parameter is not set correctly, the callback cannot be registered.|
| callback | Callback&lt;number&gt; | Yes | Callback invoked to return the number of MTU bytes.|
**Example**
......@@ -2210,7 +2270,7 @@ try {
off(type: 'BLEMtuChange', callback?: Callback&lt;number&gt;): void
Unsubscribes from MTU status changes.
Unsubscribes from MTU status changes for the client.
**Required permissions**: ohos.permission.ACCESS_BLUETOOTH
......@@ -2220,8 +2280,8 @@ Unsubscribes from MTU status changes.
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ---------------------------------------- |
| type | string | Yes | Event type. The value is **BLEMtuChange**, which indicates a MTU status change event.|
| callback | Callback&lt;number&gt; | No | Callback for MTU status changes. If this parameter is not set, this API unsubscribes from all callbacks corresponding to **type**.|
| type | string | Yes | Type of event to unsubscribe from. The value is **BLEMtuChange**, which indicates the MTU status changes. If this parameter is not set correctly, the callback cannot be unregistered.|
| callback | Callback&lt;number&gt; | No | Callback for the MTU status changes. If this parameter is not set, this API unsubscribes from all callbacks corresponding to **type**.|
**Example**
......
......@@ -100,6 +100,182 @@ Checks whether an application is the default application of the specified servic
| ------- | ------------------------------------ |
| boolean | Returns **true** if the application is the default payment application; returns **false** otherwise.|
## HceService<sup>8+</sup>
Implements HCE, including receiving Application Protocol Data Units (APDUs) from the peer card reader and sending a response. Before using HCE-related APIs, check whether the device supports HCE. This API is used only for declaration and cannot be used currently.
### startHCE<sup>8+</sup>
startHCE(aidList: string[]): boolean
Starts HCE, including setting the application to be foreground preferred and dynamically registering the application identifier (AID) list. This API is used only for declaration and cannot be used currently.
> **NOTE**
> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [start](#start9).
**Required permissions**: ohos.permission.NFC_CARD_EMULATION
**System capability**: SystemCapability.Communication.NFC.CardEmulation
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | -------- | ---- | ----------------------- |
| aidList | string[] | Yes | AID list to register.|
### start<sup>9+</sup>
start(elementName: ElementName, aidList: string[]): void
Starts HCE, including setting the application to be foreground preferred and dynamically registering the application identifier (AID) list. This API is used only for declaration and cannot be used currently.
**Required permissions**: ohos.permission.NFC_CARD_EMULATION
**System capability**: SystemCapability.Communication.NFC.CardEmulation
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | -------- | ---- | ----------------------- |
| elementName | ElementName | Yes | Element name of a service capability.|
| aidList | string[] | Yes | AID list to register.|
**Error codes**
For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ID| Error Message |
| ------- | -------|
| 3100301 | Card emulation running state is abnormal in service. |
### stopHCE<sup>8+</sup>
stopHCE(): boolean
Stops HCE, including removing the foreground preferred attribute and releasing the dynamically registered AID list. This API is used only for declaration and cannot be used currently.
> **NOTE**
> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [stop](#stop).
**Required permissions**: ohos.permission.NFC_CARD_EMULATION
**System capability**: SystemCapability.Communication.NFC.CardEmulation
### stop<sup>9+</sup>
stop(elementName: ElementName): void;
Stops HCE, including removing the foreground preferred attribute and releasing the dynamically registered AID list. This API is used only for declaration and cannot be used currently.
**Required permissions**: ohos.permission.NFC_CARD_EMULATION
**System capability**: SystemCapability.Communication.NFC.CardEmulation
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | -------- | ---- | ----------------------- |
| elementName | ElementName | Yes | Element name of a service capability.|
**Error codes**
For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ID| Error Message |
| ------- | -------|
| 3100301 | Card emulation running state is abnormal in service. |
### on<sup>8+</sup>
on(type: "hceCmd", callback: AsyncCallback<number[]>): void;
Registers a callback to receive APDUs from the peer card reader. This API is used only for declaration and cannot be used currently.
**Required permissions**: ohos.permission.NFC_CARD_EMULATION
**System capability**: SystemCapability.Communication.NFC.CardEmulation
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------------- |
| type | string | Yes | Event type to subscribe to. The value is **hceCmd**. |
| callback | AsyncCallback<number[]> | Yes | Callback invoked to return the APDU, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.|
### sendResponse<sup>8+</sup>
sendResponse(responseApdu: number[]): void;
Sends a response to the peer card reader. This API is used only for declaration and cannot be used currently.
> **NOTE**
> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [transmit](#transmit9).
**Required permissions**: ohos.permission.NFC_CARD_EMULATION
**System capability**: SystemCapability.Communication.NFC.CardEmulation
**Parameters**
| Name | Type | Mandatory| Description |
| ------------ | -------- | ---- | -------------------------------------------------- |
| responseApdu | number[] | Yes | Response APDU sent to the peer card reader. The value consists of hexadecimal numbers ranging from **0x00** to **0xFF**.|
### transmit<sup>9+</sup>
transmit(response: number[]): Promise\<void>;
Sends a response to the peer card reader. This API is used only for declaration and cannot be used currently.
**Required permissions**: ohos.permission.NFC_CARD_EMULATION
**System capability**: SystemCapability.Communication.NFC.CardEmulation
**Parameters**
| Name | Type | Mandatory| Description |
| ------------ | -------- | ---- | -------------------------------------------------- |
| responseApdu | number[] | Yes | Response APDU sent to the peer card reader. The value consists of hexadecimal numbers ranging from **0x00** to **0xFF**.|
**Return value**
| **Type** | **Description** |
| ------- | -------------------------------------- |
| Promise\<void> | Promise that returns no value.|
**Error codes**
For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ID| Error Message |
| ------- | -------|
| 3100301 | Card emulation running state is abnormal in service. |
### transmit<sup>9+</sup>
transmit(response: number[], callback: AsyncCallback\<void>): void;
Sends a response to the peer card reader. This API is used only for declaration and cannot be used currently.
**Required permissions**: ohos.permission.NFC_CARD_EMULATION
**System capability**: SystemCapability.Communication.NFC.CardEmulation
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | -------- | ---- | ----------------------- |
| responseApdu | number[] | Yes | Response APDU sent to the peer card reader. The value consists of hexadecimal numbers ranging from **0x00** to **0xFF**.|
| callback | AsyncCallback\<void> | Yes | Callback that returns no value.|
**Error codes**
For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ID| Error Message |
| ------- | -------|
| 3100301 | Card emulation running state is abnormal in service. |
**Example**
```js
......
......@@ -60,7 +60,8 @@ function publishCB(err:Base.BusinessError) {
// Publish a common event.
try {
CommonEventManager.publish("event", publishCB);
} catch(err) {
} catch (error) {
let err:Base.BusinessError = error as Base.BusinessError;
console.error(`publish failed, code is ${err.code}, message is ${err.message}`);
}
```
......@@ -114,7 +115,8 @@ function publishCB(err:Base.BusinessError) {
// Publish a common event.
try {
CommonEventManager.publish("event", options, publishCB);
} catch (err) {
} catch (error) {
let err:Base.BusinessError = error as Base.BusinessError;
console.error(`publish failed, code is ${err.code}, message is ${err.message}`);
}
```
......@@ -166,7 +168,8 @@ let userId = 100;
// Publish a common event.
try {
CommonEventManager.publishAsUser("event", userId, publishCB);
} catch (err) {
} catch (error) {
let err:Base.BusinessError = error as Base.BusinessError;
console.error(`publishAsUser failed, code is ${err.code}, message is ${err.message}`);
}
```
......@@ -226,7 +229,8 @@ let userId = 100;
// Publish a common event.
try {
CommonEventManager.publishAsUser("event", userId, options, publishCB);
} catch (err) {
} catch (error) {
let err:Base.BusinessError = error as Base.BusinessError;
console.error(`publishAsUser failed, code is ${err.code}, message is ${err.message}`);
}
```
......@@ -269,7 +273,8 @@ function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManag
// Create a subscriber.
try {
CommonEventManager.createSubscriber(subscribeInfo, createCB);
} catch (err) {
} catch (error) {
let err:Base.BusinessError = error as Base.BusinessError;
console.error(`createSubscriber failed, code is ${err.code}, message is ${err.message}`);
}
```
......@@ -366,7 +371,8 @@ function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManag
// Subscribe to a common event.
try {
CommonEventManager.subscribe(subscriber, SubscribeCB);
} catch (err) {
} catch (error) {
let err:Base.BusinessError = error as Base.BusinessError;
console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`);
}
} else {
......@@ -377,7 +383,8 @@ function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManag
// Create a subscriber.
try {
CommonEventManager.createSubscriber(subscribeInfo, createCB);
} catch (err) {
} catch (error) {
let err:Base.BusinessError = error as Base.BusinessError;
console.error(`createSubscriber failed, code is ${err.code}, message is ${err.message}`);
}
```
......@@ -433,7 +440,8 @@ function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManag
// Subscribe to a common event.
try {
CommonEventManager.subscribe(subscriber, subscribeCB);
} catch(err) {
} catch (error) {
let err:Base.BusinessError = error as Base.BusinessError;
console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`);
}
}
......@@ -449,14 +457,16 @@ function unsubscribeCB(err:Base.BusinessError) {
// Create a subscriber.
try {
CommonEventManager.createSubscriber(subscribeInfo, createCB);
} catch (err) {
} catch (error) {
let err:Base.BusinessError = error as Base.BusinessError;
console.error(`createSubscriber failed, code is ${err.code}, message is ${err.message}`);
}
// Unsubscribe from the common event.
try {
CommonEventManager.unsubscribe(subscriber, unsubscribeCB);
} catch (err) {
} catch (error) {
let err:Base.BusinessError = error as Base.BusinessError;
console.error(`unsubscribe failed, code is ${err.code}, message is ${err.message}`);
}
```
......@@ -583,7 +593,7 @@ CommonEventManager.setStaticSubscriberState(true, (err:Base.BusinessError) => {
console.info(`Set static subscriber state callback failed, err is null.`);
return;
}
if (err.code) {
if (err.code !== undefined && err.code != null) {
console.info(`Set static subscriber state callback failed, errCode: ${err.code}, errMes: ${err.message}`);
return;
}
......
......@@ -40,6 +40,70 @@ export default class EntryAbility extends UIAbility {
For details about how to obtain the FA model context, see [Context](js-apis-inner-app-context.md#context).
## FileUri<sup>10+</sup>
### Attributes
**System capability**: SystemCapability.FileManagement.AppFileService
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| path<sup>10+</sup> | string | Yes| No| Path of the file corresponding to the URI.|
| name<sup>10+</sup> | string | Yes| No| Name of the file.|
### constructor<sup>10+</sup>
constructor(uriOrPath: string)
A constructor used to create a **FileUri** instance.
**System capability**: SystemCapability.FileManagement.AppFileService
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| uriOrPath | string | Yes| URI or path. The following types of URIs are available:<br>- Application sandbox URI: **file://\<bundleName>/\<sandboxPath>**<br>- URI of the user's document: **file://docs/storage/Users/currentUser/\<publicPath>**<br>- URI of the user's media asset: **file://media/\<mediaType>/IMG_DATATIME_ID/\<displayName>**|
**Error codes**
For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
| ID | Error Message |
| ---------------------------- | ---------- |
| 13900005 | I/O error |
| 13900042 | Unknown error |
**Example**
```js
let path = pathDir + '/test';
let uri = fileuri.getUriFromPath(filePath); // file://<packageName>/data/storage/el2/base/haps/entry/files/test
let fileUriObject = new fileuri.FileUri(uri);
console.info("The name of FileUri is " + fileUriObject.name);
```
### toString<sup>10+</sup>
toString(): string
**System capability**: SystemCapability.FileManagement.AppFileService
Obtains the URI of the string type.
**Return value**
| Type| Description|
| -------- | -------- |
| string | URI of the string type obtained.|
**Example**
```js
let path = pathDir + '/test';
let fileUriObject = new fileuri.FileUri(path);
console.info("The uri of FileUri is " + fileUriObject.toString());
```
## fileUri.getUriFromPath
getUriFromPath(path: string): string
......
......@@ -21,7 +21,7 @@ let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = {
// Callback for subscriber creation.
function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManager.CommonEventSubscriber) {
if (err.code) {
if (err.code !== undefined && err.code != null) {
console.error(`createSubscriber failed, code is ${err.code}`);
} else {
console.info("createSubscriber");
......@@ -52,7 +52,7 @@ Obtains the code of this common event. This API uses an asynchronous callback to
```ts
// Callback for result code obtaining of an ordered common event.
function getCodeCB(err:Base.BusinessError, code:number) {
if (err.code) {
if (err.code !== undefined && err.code != null) {
console.error(`getCode failed, code is ${err.code}, message is ${err.message}`);
} else {
console.info("getCode " + JSON.stringify(code));
......@@ -105,7 +105,7 @@ Sets the code for this common event. This API uses an asynchronous callback to r
```ts
// Callback for result code setting of an ordered common event.
function setCodeCB(err:Base.BusinessError) {
if (err.code) {
if (err.code !== undefined && err.code != null) {
console.error(`setCode failed, code is ${err.code}, message is ${err.message}`);
} else {
console.info("setCode");
......@@ -163,7 +163,7 @@ Obtains the data of this common event. This API uses an asynchronous callback to
```ts
// Callback for result data obtaining of an ordered common event.
function getDataCB(err:Base.BusinessError, data:string) {
if (err.code) {
if (err.code !== undefined && err.code != null) {
console.error(`getData failed, code is ${err.code}, message is ${err.message}`);
} else {
console.info("getData " + JSON.stringify(data));
......@@ -216,7 +216,7 @@ Sets the data for this common event. This API uses an asynchronous callback to r
```ts
// Callback for result data setting of an ordered common event
function setDataCB(err:Base.BusinessError) {
if (err.code) {
if (err.code !== undefined && err.code != null) {
console.error(`setCode failed, code is ${err.code}, message is ${err.message}`);
} else {
console.info("setData");
......@@ -276,7 +276,7 @@ Sets the code and data for this common event. This API uses an asynchronous call
```ts
// Callback for code and data setting of an ordered common event.
function setCodeDataCB(err:Base.BusinessError) {
if (err.code) {
if (err.code !== undefined && err.code != null) {
console.error(`setCodeAndData failed, code is ${err.code}, message is ${err.message}`);
} else {
console.info("setCodeDataCallback");
......@@ -335,7 +335,7 @@ Checks whether this common event is an ordered one. This API uses an asynchronou
```ts
// Callback for checking whether the current common event is an ordered one.
function isOrderedCB(err:Base.BusinessError, isOrdered:boolean) {
if (err.code) {
if (err.code !== undefined && err.code != null) {
console.error(`isOrderedCommonEvent failed, code is ${err.code}, message is ${err.message}`);
} else {
console.info("isOrdered " + JSON.stringify(isOrdered));
......@@ -387,7 +387,7 @@ Checks whether this common event is a sticky one. This API uses an asynchronous
```ts
// Callback for checking whether the current common event is a sticky one.
function isStickyCB(err:Base.BusinessError, isSticky:boolean) {
if (err.code) {
if (err.code !== undefined && err.code != null) {
console.error(`isStickyCommonEvent failed, code is ${err.code}, message is ${err.message}`);
} else {
console.info("isSticky " + JSON.stringify(isSticky));
......@@ -439,7 +439,7 @@ Aborts this common event. After the abort, the common event is not sent to the n
```ts
// Callback for common event aborting.
function abortCB(err:Base.BusinessError) {
if (err.code) {
if (err.code !== undefined && err.code != null) {
console.error(`abortCommonEvent failed, code is ${err.code}, message is ${err.message}`);
} else {
console.info("abortCommonEvent");
......@@ -491,7 +491,7 @@ Clears the aborted state of this common event. This API takes effect only for or
```ts
// Callback for clearing the aborted state of the current common event.
function clearAbortCB(err:Base.BusinessError) {
if (err.code) {
if (err.code !== undefined && err.code != null) {
console.error(`clearAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`);
} else {
console.info("clearAbortCommonEvent");
......@@ -543,7 +543,7 @@ Checks whether this common event is in the aborted state. This API takes effect
```ts
// Callback for checking whether the current common event is in the aborted state.
function getAbortCB(err:Base.BusinessError, abortEvent:boolean) {
if (err.code) {
if (err.code !== undefined && err.code != null) {
console.error(`getAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`);
} else {
console.info("abortCommonEvent " + abortEvent)
......@@ -595,7 +595,7 @@ Obtains the subscriber information. This API uses an asynchronous callback to re
```ts
// Callback for subscriber information obtaining.
function getCB(err:Base.BusinessError, subscribeInfo:CommonEventManager.CommonEventSubscribeInfo) {
if (err.code) {
if (err.code !== undefined && err.code != null) {
console.error(`getSubscribeInfo failed, code is ${err.code}, message is ${err.message}`);
} else {
console.info("subscribeInfo " + JSON.stringify(subscribeInfo));
......@@ -647,7 +647,7 @@ Finishes this common event. This API takes effect only for ordered common events
```ts
// Callback for ordered common event finishing.
function finishCB(err:Base.BusinessError) {
if (err.code) {
if (err.code !== undefined && err.code != null) {
console.error(`finishCommonEvent failed, code is ${err.code}, message is ${err.message}`);
} else {
console.info("FinishCommonEvent");
......
......@@ -36,10 +36,17 @@ Enables listening for combination key events. This API uses an asynchronous call
```js
let leftAltKey = 2045;
let tabKey = 2049;
let keyOptions: inputConsumer.KeyOptions = {
preKeys: [ leftAltKey ],
finalKey: tabKey,
isFinalKeyDown: true,
finalKeyDownDuration: 0
};
let callback = (keyOptions: inputConsumer.KeyOptions) => {
console.log(`keyOptions: ${JSON.stringify(keyOptions)}`);
}
try {
inputConsumer.on("key", {preKeys: [leftAltKey], finalKey: tabKey, isFinalKeyDown: true, finalKeyDownDuration: 0}, keyOptions => {
console.log(`keyOptions: ${JSON.stringify(keyOptions)}`);
});
inputConsumer.on("key", keyOptions, callback);
} catch (error) {
console.log(`Subscribe failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
}
......@@ -68,10 +75,10 @@ Disables listening for combination key events.
let leftAltKey = 2045;
let tabKey = 2049;
// Disable listening for a single callback function.
let callback = function (keyOptions) {
let callback = (keyOptions: inputConsumer.KeyOptions) => {
console.log(`keyOptions: ${JSON.stringify(keyOptions)}`);
}
let keyOption = {preKeys: [leftAltKey], finalKey: tabKey, isFinalKeyDown: true, finalKeyDownDuration: 0};
let keyOption: inputConsumer.KeyOptions = {preKeys: [leftAltKey], finalKey: tabKey, isFinalKeyDown: true, finalKeyDownDuration: 0};
try {
inputConsumer.on("key", keyOption, callback);
inputConsumer.off("key", keyOption, callback);
......@@ -84,10 +91,10 @@ try {
let leftAltKey = 2045;
let tabKey = 2049;
// Disable listening for all callback functions.
let callback = function (keyOptions) {
let callback = (keyOptions: inputConsumer.KeyOptions) => {
console.log(`keyOptions: ${JSON.stringify(keyOptions)}`);
}
let keyOption = {preKeys: [leftAltKey], finalKey: tabKey, isFinalKeyDown: true, finalKeyDownDuration: 0};
let keyOption: inputConsumer.KeyOptions = {preKeys: [leftAltKey], finalKey: tabKey, isFinalKeyDown: true, finalKeyDownDuration: 0};
try {
inputConsumer.on("key", keyOption, callback);
inputConsumer.off("key", keyOption);
......
......@@ -64,7 +64,7 @@ Obtains the IDs of all input devices. This API uses a promise to return the resu
```js
try {
inputDevice.getDeviceList().then((ids) => {
inputDevice.getDeviceList().then((ids: Array<number>) => {
console.log(`Device id list: ${JSON.stringify(ids)}`);
});
} catch (error) {
......@@ -157,9 +157,9 @@ Enables listening for device hot swap events.
```js
let isPhysicalKeyboardExist = true;
try {
inputDevice.on("change", (data) => {
inputDevice.on("change", (data: inputDevice.DeviceListener) => {
console.log(`Device event info: ${JSON.stringify(data)}`);
inputDevice.getKeyboardType(data.deviceId, (err, type) => {
inputDevice.getKeyboardType(data.deviceId, (err: Error, type: inputDevice.KeyboardType) => {
console.log("The keyboard type is: " + type);
if (type == inputDevice.KeyboardType.ALPHABETIC_KEYBOARD && data.type == 'add') {
// The physical keyboard is connected.
......@@ -238,7 +238,7 @@ This API is deprecated since API version 9. You are advised to use [inputDevice.
**Example**
```js
inputDevice.getDeviceIds((error, ids) => {
inputDevice.getDeviceIds((error: Error, ids: Array<number>) => {
if (error) {
console.log(`Failed to get device id list, error: ${JSON.stringify(error, [`code`, `message`])}`);
return;
......@@ -266,7 +266,7 @@ This API is deprecated since API version 9. You are advised to use [inputDevice.
**Example**
```js
inputDevice.getDeviceIds().then((ids) => {
inputDevice.getDeviceIds().then((ids: Array<number>) => {
console.log(`Device id list: ${JSON.stringify(ids)}`);
});
```
......@@ -353,7 +353,7 @@ Obtains the key codes supported by the input device. This API uses an asynchrono
```js
// Check whether the input device whose ID is 1 supports key codes 17, 22, and 2055.
try {
inputDevice.supportKeys(1, [17, 22, 2055], (error, supportResult) => {
inputDevice.supportKeys(1, [17, 22, 2055], (error: Error, supportResult: Array<boolean>) => {
console.log(`Query result: ${JSON.stringify(supportResult)}`);
});
} catch (error) {
......@@ -452,7 +452,7 @@ Obtains the keyboard type of an input device. This API uses an asynchronous call
```js
// Query the keyboard type of the input device whose ID is 1.
try {
inputDevice.getKeyboardType(1).then((type) => {
inputDevice.getKeyboardType(1).then((type: number) => {
console.log(`Keyboard type: ${JSON.stringify(type)}`);
});
} catch (error) {
......@@ -547,7 +547,7 @@ Obtains the keyboard repeat delay. This API uses an asynchronous callback to ret
```js
try {
inputDevice.getKeyboardRepeatDelay((error, delay) => {
inputDevice.getKeyboardRepeatDelay((error: Error, delay: number) => {
if (error) {
console.log(`Get keyboard repeat delay failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
return;
......
......@@ -37,7 +37,7 @@ Enables listening for global touch events.
```js
try {
inputMonitor.on("touch", (touchEvent) => {
inputMonitor.on("touch", (touchEvent: TouchEvent) => {
console.log(`Monitor on success ${JSON.stringify(touchEvent)}`);
return false;
});
......@@ -99,7 +99,7 @@ Disables listening for global touch events.
```js
// Disable listening for a single callback function.
function callback(touchEvent) {
let callback = (touchEvent: touchEvent) => {
console.log(`Monitor on success ${JSON.stringify(touchEvent)}`);
return false;
};
......@@ -114,7 +114,7 @@ try {
```js
// Cancel listening for all callback functions.
function callback(touchEvent) {
let callback = (touchEvent: touchEvent) => {
console.log(`Monitor on success ${JSON.stringify(touchEvent)}`);
return false;
};
......@@ -148,7 +148,7 @@ Stops listening for global mouse events.
```js
// Disable listening for a single callback.
function callback(mouseEvent) {
let callback = (mouseEvent: MouseEvent) => {
console.log(`Monitor on success ${JSON.stringify(mouseEvent)}`);
return false;
};
......@@ -163,7 +163,7 @@ try {
```js
// Disable listening for all callback functions.
function callback(mouseEvent) {
let callback = (mouseEvent: MouseEvent) => {
console.log(`Monitor on success ${JSON.stringify(mouseEvent)}`);
return false;
};
......
......@@ -525,7 +525,7 @@ import tag from '@ohos.nfc.tag';
let elementName = null;
let discTech = [tag.NFC_A, tag.NFC_B]; // replace with the tech(s) that is needed by foreground ability
function foregroundCb(err, taginfo) {
function foregroundCb(err, tagInfo) {
if (!err) {
console.log("foreground callback: tag found tagInfo = ", JSON.stringify(tagInfo));
} else {
......
......@@ -1863,7 +1863,7 @@ The following describes the unique APIs of **MifareUltralightTag**.
readMultiplePages(pageIndex: number): Promise\<number[]>
Reads four pages (4 bytes per page) from this tag. This API uses a promise to return the result.
Reads four pages of data (4 bytes per page) from this tag. This API uses a promise to return the result.
**Required permissions**: ohos.permission.NFC_TAG
......@@ -1921,7 +1921,7 @@ try {
readMultiplePages(pageIndex: number, callback: AsyncCallback\<number[]>): void
Reads four pages (4 bytes per page) from this tag. This API uses an asynchronous callback to return the result.
Reads four pages of data (4 bytes per page) from this tag. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.NFC_TAG
......@@ -2188,6 +2188,13 @@ Formats this tag as an NDEF tag, and writes an NDEF message to it. This API uses
| ------------------ | --------------------------|
| callback: AsyncCallback\<void> | Callback invoked to return the result.|
**Error codes**
For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ID| Error Message|
| ------- | -------|
| 3100201 | Tag running state is abnormal in service. |
**Example**
......@@ -2297,6 +2304,13 @@ Formats this tag as an NDEF tag, writes an NDEF message to the NDEF tag, and the
| ------------------ | --------------------------|
| callback: AsyncCallback\<void> | Callback invoked to return the result.|
**Error codes**
For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ID| Error Message|
| ------- | -------|
| 3100201 | Tag running state is abnormal in service. |
**Example**
......
......@@ -31,7 +31,7 @@ Sets the visible status of the mouse pointer. This API uses an asynchronous call
```js
try {
pointer.setPointerVisible(true, (error) => {
pointer.setPointerVisible(true, (error: Error) => {
if (error) {
console.log(`Set pointer visible failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
return;
......@@ -123,7 +123,7 @@ Checks the visible status of the mouse pointer. This API uses a promise to retur
```js
try {
pointer.isPointerVisible().then((visible) => {
pointer.isPointerVisible().then((visible: boolean) => {
console.log(`Get pointer visible success, visible: ${JSON.stringify(visible)}`);
});
} catch (error) {
......@@ -152,7 +152,7 @@ Sets the mouse movement speed. This API uses an asynchronous callback to return
```js
try {
pointer.setPointerSpeed(5, (error) => {
pointer.setPointerSpeed(5, (error: Error) => {
if (error) {
console.log(`Set pointer speed failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
return;
......@@ -218,7 +218,7 @@ Obtains the mouse movement speed. This API uses an asynchronous callback to retu
```js
try {
pointer.getPointerSpeed((error, speed) => {
pointer.getPointerSpeed((error: Error, speednumber) => {
if (error) {
console.log(`Get pointer speed failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
return;
......@@ -250,7 +250,7 @@ Obtains the mouse movement speed. This API uses a promise to return the result.
```js
try {
pointer.getPointerSpeed().then(speed => {
pointer.getPointerSpeed().then(speed: number => {
console.log(`Get pointer speed success, speed: ${JSON.stringify(speed)}`);
});
} catch (error) {
......@@ -279,7 +279,7 @@ Sets the status of the mouse hover scroll switch. This API uses an asynchronous
```js
try {
pointer.setHoverScrollState(true, (error) => {
pointer.setHoverScrollState(true, (error: Error) => {
if (error) {
console.log(`Set the mouse hover scroll failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
return;
......@@ -345,7 +345,7 @@ Obtains the status of the mouse hover scroll switch. This API uses an asynchrono
```js
try {
pointer.getHoverScrollState((error, state) => {
pointer.getHoverScrollState((error: Error, state: boolean) => {
console.log(`Get the mouse hover scroll success, state: ${JSON.stringify(state)}`);
});
} catch (error) {
......@@ -373,7 +373,7 @@ Obtains the status of the mouse hover scroll switch. This API uses a promise to
```js
try {
pointer.getHoverScrollState().then((state) => {
pointer.getHoverScrollState().then((state: Boolean) => {
console.log(`Get the mouse hover scroll success, state: ${JSON.stringify(state)}`);
});
} catch (error) {
......@@ -402,7 +402,7 @@ Sets the primary button of the mouse. This API uses an asynchronous callback to
```js
try {
pointer.setMousePrimaryButton(pointer.PrimaryButton.RIGHT, (error) => {
pointer.setMousePrimaryButton(pointer.PrimaryButton.RIGHT, (error: Error) => {
if (error) {
console.log(`Set mouse primary button failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
return;
......@@ -656,9 +656,9 @@ Obtains the mouse pointer style. This API uses an asynchronous callback to retur
**Example**
```js
import window from '@ohos.window';
window.getLastWindow(this.context, (error, win) => {
import { BusinessError } from '@ohos.base';
let context = getContext(this);
window.getLastWindow(context, (error: BusinessError, win: window.Window) => {
if (error.code) {
console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(error));
return;
......@@ -669,7 +669,7 @@ window.getLastWindow(this.context, (error, win) => {
return;
}
try {
pointer.getPointerStyle(windowId, (error, style) => {
pointer.getPointerStyle(windowId, (error: Error, style: pointer.PointerStyle) => {
console.log(`Get pointer style success, style: ${JSON.stringify(style)}`);
});
} catch (error) {
......@@ -701,9 +701,9 @@ Obtains the mouse pointer style. This API uses a promise to return the result.
**Example**
```js
import window from '@ohos.window';
window.getLastWindow(this.context, (error, win) => {
import { BusinessError } from '@ohos.base';
let context = getContext(this);
window.getLastWindow(context, (error: BusinessError, win: window.Window) => {
if (error.code) {
console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(error));
return;
......@@ -714,7 +714,7 @@ window.getLastWindow(this.context, (error, win) => {
return;
}
try {
pointer.getPointerStyle(windowId).then((style) => {
pointer.getPointerStyle(windowId).then((style: pointer.PointerStyle) => {
console.log(`Get pointer style success, style: ${JSON.stringify(style)}`);
});
} catch (error) {
......@@ -875,7 +875,7 @@ Sets the scroll switch of the touchpad. This API uses an asynchronous callback t
```js
try {
pointer.setTouchpadScrollSwitch(true, (error) => {
pointer.setTouchpadScrollSwitch(true, (error: Error) => {
if (error) {
console.log(`setTouchpadScrollSwitch failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
return;
......@@ -941,7 +941,7 @@ Obtains the scroll switch status of the touchpad. This API uses an asynchronous
```js
try {
pointer.getTouchpadScrollSwitch ((error, state) => {
pointer.getTouchpadScrollSwitch ((error: Error, state: Boolean) => {
console.log(`getTouchpadScrollSwitch success, state: ${JSON.stringify(state)}`);
});
} catch (error) {
......@@ -969,7 +969,7 @@ Obtains the scroll switch status of the touchpad. This API uses a promise to ret
```js
try {
pointer.getTouchpadScrollSwitch().then((state) => {
pointer.getTouchpadScrollSwitch().then((state: Boolean) => {
console.log(`getTouchpadScrollSwitch success, state: ${JSON.stringify(state)}`);
});
} catch (error) {
......@@ -1064,7 +1064,7 @@ Obtains the scroll direction of the touchpad. This API uses an asynchronous call
```js
try {
pointer.getTouchpadScrollSwitch ((error, state) => {
pointer.getTouchpadScrollSwitch ((error: Error, state: Boolean) => {
console.log(`getTouchpadScrollDirection success, state: ${JSON.stringify(state)}`);
});
} catch (error) {
......@@ -1092,7 +1092,7 @@ Obtains the scroll direction of the touchpad. This API uses a promise to return
```js
try {
pointer.getTouchpadScrollDirection().then((state) => {
pointer.getTouchpadScrollDirection().then((state: Boolean) => {
console.log(`getTouchpadScrollDirection success, state: ${JSON.stringify(state)}`);
});
} catch (error) {
......@@ -1121,7 +1121,7 @@ Sets the tap switch of the touchpad. This API uses an asynchronous callback to r
```js
try {
pointer.setTouchpadTapSwitch(true, (error) => {
pointer.setTouchpadTapSwitch(true, (error: Error) => {
if (error) {
console.log(`setTouchpadTapSwitch failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
return;
......@@ -1215,7 +1215,7 @@ Obtains the tap switch status of the touchpad. This API uses a promise to return
```js
try {
pointer.getTouchpadTapSwitch().then((state) => {
pointer.getTouchpadTapSwitch().then((state: Boolean) => {
console.log(`getTouchpadTapSwitch success, state: ${JSON.stringify(state)}`);
});
} catch (error) {
......@@ -1310,7 +1310,7 @@ Obtains the cursor moving speed of the touchpad. This API uses an asynchronous c
```js
try {
pointer.getTouchpadPointerSpeed((error, speed) => {
pointer.getTouchpadPointerSpeed((error: Error, speed: number) => {
console.log(`getTouchpadPointerSpeed success, speed: ${JSON.stringify(speed)}`);
});
} catch (error) {
......@@ -1338,7 +1338,7 @@ Obtains the cursor moving speed of the touchpad. This API uses a promise to retu
```js
try {
pointer.getTouchpadPointerSpeed().then((speed) => {
pointer.getTouchpadPointerSpeed().then((speed: number) => {
console.log(`getTouchpadPointerSpeed success, speed: ${JSON.stringify(speed)}`);
});
} catch (error) {
......@@ -1367,7 +1367,7 @@ Sets the pinch switch of the touchpad. This API uses an asynchronous callback to
```js
try {
pointer.setTouchpadTapSwitch(true, (error) => {
pointer.setTouchpadTapSwitch(true, (error: Error) => {
if (error) {
console.log(`setTouchpadPinchSwitch failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
return;
......@@ -1490,7 +1490,7 @@ Sets the multi-finger swipe switch of the touchpad. This API uses an asynchronou
```js
try {
pointer.setTouchpadSwipeSwitch(true, (error) => {
pointer.setTouchpadSwipeSwitch(true, (error: Error) => {
if (error) {
console.log(`setTouchpadSwipeSwitch failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
return;
......@@ -1584,7 +1584,7 @@ Obtains the multi-finger swipe switch status of the touchpad. This API uses a pr
```js
try {
pointer.getTouchpadSwipeSwitch().then((state) => {
pointer.getTouchpadSwipeSwitch().then((state: boolean) => {
console.log(`getTouchpadSwipeSwitch success, state: ${JSON.stringify(state)}`);
});
} catch (error) {
......@@ -1691,7 +1691,7 @@ Obtains the shortcut menu type of the touchpad. This API uses an asynchronous ca
```js
try {
pointer.getTouchpadRightClickType((error, type) => {
pointer.getTouchpadRightClickType((error: Error, type: pointer.RightClickType) => {
console.log(`getTouchpadRightClickType success, type: ${JSON.stringify(type)}`);
});
} catch (error) {
......@@ -1869,7 +1869,7 @@ Obtains the pointer size. This API uses a promise to return the result.
```js
try {
pointer.getPointerSize().then((size) => {
pointer.getPointerSize().then((size: number) => {
console.log(`getPointerSize success, size: ${JSON.stringify(size)}`);
});
} catch (error) {
......@@ -1925,7 +1925,7 @@ Sets the pointer color. This API uses an asynchronous callback to return the res
```js
try {
pointer.setPointerColor(0xF6C800, (error) => {
pointer.setPointerColor(0xF6C800, (error: Error) => {
if (error) {
console.log(`setPointerColor failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
return;
......
......@@ -62,7 +62,7 @@
- 应用组件跨设备交互(流转)
- [流转概述](inter-device-interaction-hop-overview.md)
- [跨端迁移](hop-cross-device-migration.md)
- [多端协同(仅对系统应用开放)](hop-multi-device-collaboration.md)
- [多端协同](hop-multi-device-collaboration.md)
- [订阅系统环境变量的变化](subscribe-system-environment-variable-changes.md)
- 了解进程模型
- [进程模型概述](process-model-stage.md)
......
......@@ -53,27 +53,48 @@
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
function FunACall(data) {
// 获取call事件中传递的所有参数
console.info('FunACall param:' + JSON.stringify(data.readString()));
return null;
}
function FunBCall(data) {
console.info('FunBCall param:' + JSON.stringify(data.readString()));
return null;
import Base from '@ohos.base'
import rpc from '@ohos.rpc';
import Want from '@ohos.app.ability.Want';
import AbilityConstant from '@ohos.app.ability.AbilityConstant';
class MyParcelable implements rpc.Parcelable {
num: number;
str: string;
constructor(num: number, str: string) {
this.num = num;
this.str = str;
}
marshalling(messageSequence: rpc.MessageSequence): boolean {
messageSequence.writeInt(this.num);
messageSequence.writeString(this.str);
return true;
}
unmarshalling(messageSequence: rpc.MessageSequence): boolean {
this.num = messageSequence.readInt();
this.str = messageSequence.readString();
return true;
}
}
export default class CameraAbility extends UIAbility {
// 如果UIAbility第一次启动,在收到call事件后会触发onCreate生命周期回调
onCreate(want, launchParam) {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
try {
// 监听call事件所需的方法
this.callee.on('funA', FunACall);
this.callee.on('funB', FunBCall);
this.callee.on('funA', (data: rpc.MessageSequence) => {
// 获取call事件中传递的所有参数
console.info('FunACall param:' + JSON.stringify(data.readString()));
return new MyParcelable(1, 'aaa');
});
this.callee.on('funB', (data: rpc.MessageSequence) => {
// 获取call事件中传递的所有参数
console.info('FunACall param:' + JSON.stringify(data.readString()));
return new MyParcelable(2, 'bbb');
});
} catch (err) {
console.error(`Failed to register callee on. Cause: ${JSON.stringify(err)}`);
console.error(`Failed to register callee on. Cause: ${JSON.stringify(err as Base.BusinessError)}`);
}
}
......@@ -85,7 +106,7 @@
this.callee.off('funA');
this.callee.off('funB');
} catch (err) {
console.error(`Failed to register callee off. Cause: ${JSON.stringify(err)}`);
console.error(`Failed to register callee off. Cause: ${JSON.stringify(err as Base.BusinessError)}`);
}
}
};
......
......@@ -52,10 +52,10 @@
let formData = new Map<Object, string>();
formData.set('title', 'Title Update.'); // 和卡片布局中对应
formData.set('detail', 'Description update success.'); // 和卡片布局中对应
let formInfo = formBindingData.createFormBindingData(formData)
formProvider.updateForm(formId, formInfo).then((data) => {
console.info('FormAbility updateForm success.' + JSON.stringify(data));
})
let formInfo: formBindingData.FormBindingData = formBindingData.createFormBindingData(formData);
formProvider.updateForm(formId, formInfo).then(() => {
console.info('FormAbility updateForm success.');
});
}
...
......
......@@ -54,26 +54,29 @@
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import window from '@ohos.window';
import Want from '@ohos.app.ability.Want';
import Base from '@ohos.base';
import AbilityConstant from '@ohos.app.ability.AbilityConstant';
let selectPage = "";
let currentWindowStage = null;
let selectPage: string = "";
let currentWindowStage: window.WindowStage | null = null;
export default class EntryAbility extends UIAbility {
// 如果UIAbility第一次启动,在收到Router事件后会触发onCreate生命周期回调
onCreate(want, launchParam) {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
// 获取router事件中传递的targetPage参数
console.info("onCreate want:" + JSON.stringify(want));
if (want.parameters.params !== undefined) {
let params = JSON.parse(want.parameters.params);
if (want.parameters?.params !== undefined) {
let params: Record<string, string> = JSON.parse(JSON.stringify(want.parameters?.params));
console.info("onCreate router targetPage:" + params.targetPage);
selectPage = params.targetPage;
}
}
// 如果UIAbility已在后台运行,在收到Router事件后会触发onNewWant生命周期回调
onNewWant(want, launchParam) {
onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam) {
console.info("onNewWant want:" + JSON.stringify(want));
if (want.parameters.params !== undefined) {
let params = JSON.parse(want.parameters.params);
if (want.parameters?.params !== undefined) {
let params: Record<string, string> = JSON.parse(JSON.stringify(want.parameters?.params));
console.info("onNewWant router targetPage:" + params.targetPage);
selectPage = params.targetPage;
}
......@@ -81,9 +84,9 @@
this.onWindowStageCreate(currentWindowStage);
}
}
onWindowStageCreate(windowStage: window.WindowStage) {
let targetPage;
let targetPage: string;
// 根据传递的targetPage不同,选择拉起不同的页面
switch (selectPage) {
case 'funA':
......@@ -98,7 +101,7 @@
if (currentWindowStage === null) {
currentWindowStage = windowStage;
}
windowStage.loadContent(targetPage, (err, data) => {
windowStage.loadContent(targetPage, (err: Base.BusinessError) => {
if (err && err.code) {
console.info('Failed to load the content. Cause: %{public}s', JSON.stringify(err));
return;
......
......@@ -44,30 +44,33 @@
import formBindingData from '@ohos.app.form.formBindingData';
import formProvider from '@ohos.app.form.formProvider';
import formInfo from '@ohos.app.form.formInfo';
import AbilityConstant from '@ohos.app.ability.AbilityConstant';
import Want from '@ohos.app.ability.Want';
import Base from '@ohos.base'
export default class EntryAbility extends UIAbility {
// 如果UIAbility第一次启动,在收到Router事件后会触发onCreate生命周期回调
onCreate(want, launchParam) {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
this.handleFormRouterEvent(want);
}
// 如果UIAbility已在后台运行,在收到Router事件后会触发onNewWant生命周期回调
onNewWant(want, launchParam) {
onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam) {
this.handleFormRouterEvent(want);
}
handleFormRouterEvent(want) {
handleFormRouterEvent(want: Want) {
console.info('Want:' + JSON.stringify(want));
if (want.parameters[formInfo.FormParam.IDENTITY_KEY] !== undefined) {
let curFormId = want.parameters[formInfo.FormParam.IDENTITY_KEY];
let message = JSON.parse(want.parameters.params).detail;
if (want.parameters && want.parameters[formInfo.FormParam.IDENTITY_KEY] !== undefined) {
let curFormId = JSON.stringify(want.parameters[formInfo.FormParam.IDENTITY_KEY]);
let message: string = JSON.parse(JSON.stringify(want.parameters.params)).detail;
console.info(`UpdateForm formId: ${curFormId}, message: ${message}`);
let formData = {
let formData: Record<string, string> = {
"detail": message + ': UIAbility.', // 和卡片布局中对应
};
let formMsg = formBindingData.createFormBindingData(formData)
formProvider.updateForm(curFormId, formMsg).then((data) => {
console.info('updateForm success.' + JSON.stringify(data));
}).catch((error) => {
}).catch((error: Base.BusinessError) => {
console.error('updateForm failed:' + JSON.stringify(error));
})
}
......@@ -83,18 +86,21 @@
```ts
import formBindingData from '@ohos.app.form.formBindingData';
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
import Want from '@ohos.app.ability.Want';
export default class EntryFormAbility extends FormExtensionAbility {
onAddForm(want) {
let formId = want.parameters["ohos.extra.param.key.form_identity"];
let dataObj1 = {
"formId": formId
};
onAddForm(want: Want) {
let dataObj1: Record<string, string> | undefined;
if (want.parameters && want.parameters["ohos.extra.param.key.form_identity"] != undefined) {
let formId: string = JSON.parse(JSON.stringify(want.parameters["ohos.extra.param.key.form_identity"]));
dataObj1 = {
"formId": formId
};
}
let obj1 = formBindingData.createFormBindingData(dataObj1);
return obj1;
}
...
...
};
```
......@@ -138,40 +144,63 @@
import UIAbility from '@ohos.app.ability.UIAbility';
import formBindingData from '@ohos.app.form.formBindingData';
import formProvider from '@ohos.app.form.formProvider';
import Want from '@ohos.app.ability.Want';
import Base from '@ohos.base'
import rpc from '@ohos.rpc';
import AbilityConstant from '@ohos.app.ability.AbilityConstant';
const MSG_SEND_METHOD: string = 'funA';
class MyParcelable implements rpc.Parcelable {
num: number;
str: string;
constructor(num: number, str: string) {
this.num = num;
this.str = str;
}
marshalling(messageSequence: rpc.MessageSequence): boolean {
messageSequence.writeInt(this.num);
messageSequence.writeString(this.str);
return true;
}
unmarshalling(messageSequence: rpc.MessageSequence): boolean {
this.num = messageSequence.readInt();
this.str = messageSequence.readString();
return true;
}
}
// 在收到call事件后会触发callee监听的方法
function FunACall(data) {
let FunACall = (data: rpc.MessageSequence) => {
// 获取call事件中传递的所有参数
let params = JSON.parse(data.readString())
let params: Record<string, string> = JSON.parse(data.readString())
if (params.formId !== undefined) {
let curFormId = params.formId;
let message = params.detail;
let curFormId: string = params.formId;
let message: string = params.detail;
console.info(`UpdateForm formId: ${curFormId}, message: ${message}`);
let formData = {
let formData: Record<string, string> = {
"detail": message
};
let formMsg = formBindingData.createFormBindingData(formData)
let formMsg: formBindingData.FormBindingData = formBindingData.createFormBindingData(formData);
formProvider.updateForm(curFormId, formMsg).then((data) => {
console.info('updateForm success.' + JSON.stringify(data));
}).catch((error) => {
}).catch((error: Base.BusinessError) => {
console.error('updateForm failed:' + JSON.stringify(error));
})
}
return null;
return new MyParcelable(1, 'aaa');
}
export default class EntryAbility extends UIAbility {
// 如果UIAbility第一次启动,call事件后会触发onCreate生命周期回调
onCreate(want, launchParam) {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
console.info('Want:' + JSON.stringify(want));
try {
// 监听call事件所需的方法
// 监听call事件所需的方法
this.callee.on(MSG_SEND_METHOD, FunACall);
} catch (error) {
console.info(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`)
console.info(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error as Base.BusinessError)}`)
}
}
...
}
```
\ No newline at end of file
......@@ -14,31 +14,34 @@
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
import request from '@ohos.request';
import fs from '@ohos.file.fs';
import Want from '@ohos.app.ability.Want';
import Base from '@ohos.base';
import fileFs from '@ohos.file.fs';
export default class EntryFormAbility extends FormExtensionAbility {
...
// 在添加卡片时,打开一个本地图片并将图片内容传递给卡片页面显示
onAddForm(want) {
// 假设在当前卡片应用的tmp目录下有一个本地图片:head.PNG
let tempDir = this.context.getApplicationContext().tempDir;
// 打开本地图片并获取其打开后的fd
let file;
try {
file = fs.openSync(tempDir + '/' + 'head.PNG');
} catch (e) {
console.error(`openSync failed: ${JSON.stringify(e)}`);
}
let formData = {
'text': 'Image: Bear',
'imgName': 'imgBear',
'formImages': {
'imgBear': file.fd
},
'loaded': true
}
// 将fd封装在formData中并返回至卡片页面
return formBindingData.createFormBindingData(formData);
}
onAddForm(want: Want) {
// 假设在当前卡片应用的tmp目录下有一个本地图片:head.PNG
let tempDir = this.context.getApplicationContext().tempDir;
// 打开本地图片并获取其打开后的fd
let file: fileFs.File;
let formData = new Map<string, Object>();
formData.set('text', 'Image: Bear');
formData.set('imgName', 'imgBear');
formData.set('loaded', true);
try {
file = fs.openSync(tempDir + '/' + 'head.PNG');
let imgBear: Record<string, number> = {
'imgBear': file.fd
}
formData.set('formImages', imgBear);
} catch (e) {
console.error(`openSync failed: ${JSON.stringify(e as Base.BusinessError)}`);
}
// 将fd封装在formData中并返回至卡片页面
return formBindingData.createFormBindingData(formData);
}
...
}
......@@ -46,67 +49,67 @@
3. 在EntryFormAbility中的onFormEvent生命周期回调中实现网络文件的刷新
```ts
import formBindingData from '@ohos.app.form.formBindingData';
import formProvider from '@ohos.app.form.formProvider';
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
import request from '@ohos.request';
import fs from '@ohos.file.fs';
```ts
import formBindingData from '@ohos.app.form.formBindingData';
import formProvider from '@ohos.app.form.formProvider';
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
import request from '@ohos.request';
import fs from '@ohos.file.fs';
import Base from '@ohos.base';
import fileFs from '@ohos.file.fs';
export default class EntryFormAbility extends FormExtensionAbility {
// 在卡片页面触发message事件时,下载一个网络图片,并将网络图片内容传递给卡片页面显示
onFormEvent(formId, message) {
let formInfo = formBindingData.createFormBindingData({
'text': '刷新中...'
})
formProvider.updateForm(formId, formInfo)
// 注意:FormExtensionAbility在触发生命周期回调时被拉起,仅能在后台存在5秒
// 建议下载能快速下载完成的小文件,如在5秒内未下载完成,则此次网络图片无法刷新至卡片页面上
let netFile = 'https://xxxx/xxxx.png'; // 需要在此处使用真实的网络图片下载链接
let tempDir = this.context.getApplicationContext().tempDir;
let fileName = 'file' + Date.now();
let tmpFile = tempDir + '/' + fileName;
request.downloadFile(this.context, {
url: netFile, filePath: tmpFile, enableMetered: true, enableRoaming: true
}).then((task) => {
task.on('complete', function callback() {
console.info('ArkTSCard download complete:' + tmpFile);
let file;
try {
file = fs.openSync(tmpFile);
} catch (e) {
console.error(`openSync failed: ${JSON.stringify(e)}`);
}
let fileInfo = {};
fileInfo[fileName] = file.fd;
let formData = {
'text': 'Image:' + fileName,
'imgName': fileName,
'formImages': fileInfo,
'loaded': true
};
let formInfo = formBindingData.createFormBindingData(formData)
formProvider.updateForm(formId, formInfo).then((data) => {
console.info('FormAbility updateForm success.' + JSON.stringify(data));
}).catch((error) => {
console.error('FormAbility updateForm failed: ' + JSON.stringify(error));
})
})
task.on('fail', function callBack(err) {
console.info('ArkTSCard download task failed. Cause:' + err);
let formInfo = formBindingData.createFormBindingData({
'text': '刷新失败'
})
formProvider.updateForm(formId, formInfo)
});
}).catch((err) => {
console.error('Failed to request the download. Cause: ' + JSON.stringify(err));
});
}
...
};
```
export default class EntryFormAbility extends FormExtensionAbility {
// 在卡片页面触发message事件时,下载一个网络图片,并将网络图片内容传递给卡片页面显示
onFormEvent(formId: string, message: string) {
let formInfo = formBindingData.createFormBindingData({
'text': '刷新中...'
})
formProvider.updateForm(formId, formInfo)
// 注意:FormExtensionAbility在触发生命周期回调时被拉起,仅能在后台存在5秒
// 建议下载能快速下载完成的小文件,如在5秒内未下载完成,则此次网络图片无法刷新至卡片页面上
let netFile = 'https://xxxx/xxxx.png'; // 需要在此处使用真实的网络图片下载链接
let tempDir = this.context.getApplicationContext().tempDir;
let fileName = 'file' + Date.now();
let tmpFile = tempDir + '/' + fileName;
request.downloadFile(this.context, {
url: netFile, filePath: tmpFile, enableMetered: true, enableRoaming: true
}).then((task) => {
task.on('complete', () => {
console.info('ArkTSCard download complete:' + tmpFile);
let file: fileFs.File;
let formData = new Map<string, Object>();
try {
file = fs.openSync(tmpFile);
formData.set('text', 'Image: Bear' + fileName);
formData.set('imgName', 'imgBear' + fileName);
formData.set('loaded', true);
let imgBear: Record<string, number> = {
'imgBear': file.fd
};
formData.set('formImages', imgBear);
} catch (e) {
console.error(`openSync failed: ${JSON.stringify(e as Base.BusinessError)}`);
}
let formInfo = formBindingData.createFormBindingData(formData);
formProvider.updateForm(formId, formInfo).then(() => {
console.info('FormAbility updateForm success.');
}).catch((error: Base.BusinessError) => {
console.error('FormAbility updateForm failed: ' + JSON.stringify(error));
});
})
task.on('fail', (err: number) => {
console.info('ArkTSCard download task failed. Cause:' + err);
let formInfo = formBindingData.createFormBindingData({
'text': '刷新失败'
})
formProvider.updateForm(formId, formInfo)
});
}).catch((err: Base.BusinessError) => {
console.error('Failed to request the download. Cause: ' + JSON.stringify(err));
});
}
};
```
4. 在卡片页面通过Image组件展示EntryFormAbility传递过来的卡片内容。
......
......@@ -20,74 +20,72 @@
import formBindingData from '@ohos.app.form.formBindingData';
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
import formProvider from '@ohos.app.form.formProvider';
import { Configuration } from '@ohos.app.ability.Configuration';
import Want from '@ohos.app.ability.Want';
import formInfo from '@ohos.app.form.formInfo';
import Base from '@ohos.base';
export default class EntryFormAbility extends FormExtensionAbility {
onAddForm(want) {
console.info('[EntryFormAbility] onAddForm');
// 在入参want中可以取出卡片的唯一标识:formId
let formId: string = want.parameters[formInfo.FormParam.IDENTITY_KEY];
// 使用方创建卡片时触发,提供方需要返回卡片数据绑定类
let obj = {
'title': 'titleOnAddForm',
'detail': 'detailOnAddForm'
};
let formData = formBindingData.createFormBindingData(obj);
return formData;
}
onCastToNormalForm(formId) {
// Called when the form provider is notified that a temporary form is successfully
// converted to a normal form.
// 使用方将临时卡片转换为常态卡片触发,提供方需要做相应的处理
console.info(`[EntryFormAbility] onCastToNormalForm, formId: ${formId}`);
}
onUpdateForm(formId) {
// 若卡片支持定时更新/定点更新/卡片使用方主动请求更新功能,则提供方需要重写该方法以支持数据更新
console.info('[EntryFormAbility] onUpdateForm');
let obj = {
'title': 'titleOnUpdateForm',
'detail': 'detailOnUpdateForm'
};
let formData = formBindingData.createFormBindingData(obj);
formProvider.updateForm(formId, formData).catch((err) => {
if (err) {
// 异常分支打印
console.error(`[EntryFormAbility] Failed to updateForm. Code: ${err.code}, message: ${err.message}`);
return;
}
});
}
onChangeFormVisibility(newStatus) {
// Called when the form provider receives form events from the system.
// 需要配置formVisibleNotify为true,且为系统应用才会回调
console.info('[EntryFormAbility] onChangeFormVisibility');
}
onFormEvent(formId, message) {
// Called when a specified message event defined by the form provider is triggered.
// 若卡片支持触发事件,则需要重写该方法并实现对事件的触发
console.info('[EntryFormAbility] onFormEvent');
}
onRemoveForm(formId) {
// Called to notify the form provider that a specified form has been destroyed.
// 当对应的卡片删除时触发的回调,入参是被删除的卡片ID
console.info('[EntryFormAbility] onRemoveForm');
}
onConfigurationUpdate(config) {
// 当系统配置信息置更新时触发的回调
console.info('[EntryFormAbility] configurationUpdate:' + JSON.stringify(config));
}
onAcquireFormState(want) {
// Called to return a {@link FormState} object.
// 卡片提供方接收查询卡片状态通知接口,默认返回卡片初始状态。
return formInfo.FormState.READY;
}
}
onAddForm(want: Want) {
console.info('[EntryFormAbility] onAddForm');
// 使用方创建卡片时触发,提供方需要返回卡片数据绑定类
let obj: Record<string, string> = {
'title': 'titleOnAddForm',
'detail': 'detailOnAddForm'
};
let formData = formBindingData.createFormBindingData(obj);
return formData;
}
onCastToNormalForm(formId: string) {
// Called when the form provider is notified that a temporary form is successfully
// converted to a normal form.
// 使用方将临时卡片转换为常态卡片触发,提供方需要做相应的处理
console.info(`[EntryFormAbility] onCastToNormalForm, formId: ${formId}`);
}
onUpdateForm(formId: string) {
// 若卡片支持定时更新/定点更新/卡片使用方主动请求更新功能,则提供方需要重写该方法以支持数据更新
console.info('[EntryFormAbility] onUpdateForm');
let obj: Record<string, string> = {
'title': 'titleOnUpdateForm',
'detail': 'detailOnUpdateForm'
};
let formData = formBindingData.createFormBindingData(obj);
formProvider.updateForm(formId, formData).catch((err: Base.BusinessError) => {
console.error(`[EntryFormAbility] Failed to updateForm. Code: ${err.code}, message: ${err.message}`);
});
}
onChangeFormVisibility(newStatus: Record<string, number>) {
// Called when the form provider receives form events from the system.
// 需要配置formVisibleNotify为true,且为系统应用才会回调
console.info('[EntryFormAbility] onChangeFormVisibility');
}
onFormEvent(formId: string, message: string) {
// Called when a specified message event defined by the form provider is triggered.
// 若卡片支持触发事件,则需要重写该方法并实现对事件的触发
console.info('[EntryFormAbility] onFormEvent');
}
onRemoveForm(formId: string) {
// Called to notify the form provider that a specified form has been destroyed.
// 当对应的卡片删除时触发的回调,入参是被删除的卡片ID
console.info('[EntryFormAbility] onRemoveForm');
}
onConfigurationUpdate(config: Configuration) {
// 当系统配置信息置更新时触发的回调
console.info('[EntryFormAbility] configurationUpdate:' + JSON.stringify(config));
}
onAcquireFormState(want: Want) {
// Called to return a {@link FormState} object.
// 卡片提供方接收查询卡片状态通知接口,默认返回卡片初始状态。
return formInfo.FormState.READY;
}
}
```
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册