diff --git a/.gitattributes b/.gitattributes index f17b2bee513f3dc8a111965f4c58346eaede9b0b..960cfafec9f7bc1b9e713a13c108ee24e26c227e 100644 --- a/.gitattributes +++ b/.gitattributes @@ -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 diff --git a/en/application-dev/file-management/app-file-access.md b/en/application-dev/file-management/app-file-access.md index 4d3a21c0902535a3d81fd4be678973b6e8dfab23..409560fa51a4f22394375b1ce6ab39d58b7d3e08 100644 --- a/en/application-dev/file-management/app-file-access.md +++ b/en/application-dev/file-management/app-file-access.md @@ -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]}`); + } } ``` diff --git a/en/application-dev/file-management/app-file-backup.md b/en/application-dev/file-management/app-file-backup.md index ccfb8641f4db47a71029c2c4591382081aeb0697..e65d2c9e15e12facbbe4ebf56befc29a573d3cb1 100644 --- a/en/application-dev/file-management/app-file-backup.md +++ b/en/application-dev/file-management/app-file-backup.md @@ -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'); } ``` diff --git a/en/application-dev/file-management/app-file-upload-download.md b/en/application-dev/file-management/app-file-upload-download.md index 75fb0646cf2dbfa1422209c4d4b9b176e547f749..d2391e620a8327964010703ad523a30f732aaa10 100644 --- a/en/application-dev/file-management/app-file-upload-download.md +++ b/en/application-dev/file-management/app-file-upload-download.md @@ -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(); +header.set('key1', 'value1'); +header.set('key2', 'value2'); +let files: Array = [ + { filename: 'test.txt', name: 'test', uri: 'internal://cache/test.txt', type: 'txt' } +] +let data: Array = [{ 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) => { 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}`); } ``` diff --git a/en/application-dev/file-management/app-fs-space-statistics.md b/en/application-dev/file-management/app-fs-space-statistics.md index 74ffbc6c6f39441be0a9c0043389458025bc0c0d..ebc0982502719a6d07e98ed5f46329744dfcf55d 100644 --- a/en/application-dev/file-management/app-fs-space-statistics.md +++ b/en/application-dev/file-management/app-fs-space-statistics.md @@ -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
/data/storage/el1/base/haps/entry/cache
/data/storage/el2/base/cache
/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 { diff --git a/en/application-dev/file-management/dev-user-file-manager.md b/en/application-dev/file-management/dev-user-file-manager.md index ffcea027cfc56ad761064bd686f06452bc6be390..4340e26a14d41dab029f75b45dd259015ee67e7d 100644 --- a/en/application-dev/file-management/dev-user-file-manager.md +++ b/en/application-dev/file-management/dev-user-file-manager.md @@ -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.
- 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.
+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 = []; + 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 = []; + 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 = []; + 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); + }; + } ``` diff --git a/en/application-dev/file-management/file-access-across-devices.md b/en/application-dev/file-management/file-access-across-devices.md index 1fefd8c41154597235e718b77309f34c94a36778..caa18468fb0eccd535ebe095ab9c45ab3f7549fb 100644 --- a/en/application-dev/file-management/file-access-across-devices.md +++ b/en/application-dev/file-management/file-access-across-devices.md @@ -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}`); } ``` diff --git a/en/application-dev/file-management/manage-external-storage.md b/en/application-dev/file-management/manage-external-storage.md index b26a17455725e769f41cf1eb2cdc6d214ee3a0e9..24a0a3b112845e47ce2b8e0a9e32d2b53b4b1e3d 100644 --- a/en/application-dev/file-management/manage-external-storage.md +++ b/en/application-dev/file-management/manage-external-storage.md @@ -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.
**diskId**: ID of the disk to which the volume belongs.| -| usual.event.data.VOLUME_UNMOUNTED | **id**: ID of the volume.
**diskId**: ID of the disk to which the volume belongs.
**volumeState**: state of the volume.| -| usual.event.data.VOLUME_MOUNTED | **id**: ID of the volume.
**diskId**: ID of the disk to which the volume belongs.
**volumeState**: state of the volume.
**fsUuid**: universally unique identifier (UUID) of the volume.
**path**: path where the volume is mounted.| -| usual.event.data.VOLUME_BAD_REMOVAL | **id**: ID of the volume.
**diskId**: ID of the disk to which the volume belongs.| -| usual.event.data.VOLUME_EJECT | **id**: ID of the volume.
**diskId**: ID of the disk to which the volume belongs.
**volumeState**: state of the volume.| +| usual.event.data.VOLUME_REMOVED | **id**: ID of the volume.
**diskId**: ID of the disk to which the volume belongs.| +| usual.event.data.VOLUME_UNMOUNTED | **id**: ID of the volume.
**diskId**: ID of the disk to which the volume belongs.
**volumeState**: state of the volume.| +| usual.event.data.VOLUME_MOUNTED | **id**: ID of the volume.
**diskId**: ID of the disk to which the volume belongs.
**volumeState**: state of the volume.
**fsUuid**: universally unique identifier (UUID) of the volume.
**path**: path where the volume is mounted.| +| usual.event.data.VOLUME_BAD_REMOVAL | **id**: ID of the volume.
**diskId**: ID of the disk to which the volume belongs.| +| usual.event.data.VOLUME_EJECT | **id**: ID of the volume.
**diskId**: ID of the disk to which the volume belongs.
**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); } diff --git a/en/application-dev/file-management/save-user-file.md b/en/application-dev/file-management/save-user-file.md index a5cc3306c680ec9f5d1463de940e1844c5692a19..07ef6bc424991b79b8305cd3795534317d00845c 100644 --- a/en/application-dev/file-management/save-user-file.md +++ b/en/application-dev/file-management/save-user-file.md @@ -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; + 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; 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) => { + 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) => { 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'); diff --git a/en/application-dev/file-management/select-user-file.md b/en/application-dev/file-management/select-user-file.md index 041d20f308e47b7757de53a4735958e54bba6f2e..01f074fff61c84ebd1e04885e895a261599d1de7 100644 --- a/en/application-dev/file-management/select-user-file.md +++ b/en/application-dev/file-management/select-user-file.md @@ -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; 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; 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) => { + 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) => { + 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}`); }) ``` diff --git a/en/application-dev/file-management/set-security-label.md b/en/application-dev/file-management/set-security-label.md index 2bf82ab58daa28d82b3c9a7ec2c38162a6ad210c..cb8e133b76f0d5caa0648bd585cd383705f45267 100644 --- a/en/application-dev/file-management/set-security-label.md +++ b/en/application-dev/file-management/set-security-label.md @@ -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}`); }); ``` diff --git a/en/application-dev/file-management/share-app-file.md b/en/application-dev/file-management/share-app-file.md index 76dbcab2a74b6b6a4afdcee72c4535939cf3e0a0..f912565dbd58062f95c88cc35f45c60807a290aa 100644 --- a/en/application-dev/file-management/share-app-file.md +++ b/en/application-dev/file-management/share-app-file.md @@ -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**://<*bundleName*>/<*path*> +**file://**<bundleName>/<path> - **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}`); } } ``` diff --git a/en/application-dev/notification/notification-with-wantagent.md b/en/application-dev/notification/notification-with-wantagent.md index 4a820360cc5f5f1c4ca829a629636dac0a672371..72e845497eac1cff153ebd7bf9d9af069b1bab6f 100644 --- a/en/application-dev/notification/notification-with-wantagent.md +++ b/en/application-dev/notification/notification-with-wantagent.md @@ -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 = { diff --git a/en/application-dev/quick-start/typescript-to-arkts-migration-guide.md b/en/application-dev/quick-start/typescript-to-arkts-migration-guide.md index 29865c79c490f4ad1678034e001b71e1011f1ab3..627a84e3125a9659a90ab945f8f1ecca0b6d15cb 100644 --- a/en/application-dev/quick-start/typescript-to-arkts-migration-guide.md +++ b/en/application-dev/quick-start/typescript-to-arkts-migration-guide.md @@ -19,7 +19,7 @@ categories: PageBreak -# How to Use The Cookbook +# How to Use the Cookbook The main goal of this cookbook is to provide recipes for all partially supported features and explicitly list all unsupported features. @@ -215,19 +215,15 @@ strong positive impact on performance at the cost of low-effort refactoring. ## Semantics of Operators Is Restricted To achieve better performance and encourage developers write clearer code, -ArkTS restricts the semantics of some operators. A couple of examples are -given below, and the full list of restrictions is outlined in [Recipes](#recipes). +ArkTS restricts the semantics of some operators. An example is given below, +and the full list of restrictions is outlined in [Recipes](#recipes). ### Example ```typescript -// Operator `+` is defined for numbers and strings, but not for other types: -class C { - // ... -} -let c1 : C = new C() -let c2 : C = new C() -console.log(c1 + c2) // Compile-time error +// Unary `+` is defined only for numbers, but not for strings: +console.log(+42) // OK +console.log(+"42") // Compile-time error ``` ### Rationale and Impact @@ -358,12 +354,11 @@ console.log(z.get(2)) **See also** * Recipe: Symbol() API is not supported -* Recipe: Attempt to access an undefined property is a compile-time error +* Recipe: Indexed access is not supported for fields * Recipe: delete operator is not supported * Recipe: typeof operator is allowed only in expression contexts * Recipe: in operator is not supported * Recipe: Property-based runtime type checks are not supported -* Recipe: Dynamic property declaration is not supported * Recipe: Usage of standard library is restricted ## Recipe: `Symbol()` API is not supported @@ -378,6 +373,9 @@ because its most popular use cases make no sense in the statically typed environment. In particular, the object layout is defined at compile time, and cannot be changed at runtime. +`Symbol.iterator` and iterable interfaces are not supported either. +Use arrays and library-level containers to iterate over data. + **TypeScript** ```typescript @@ -385,6 +383,26 @@ const sym = Symbol() let o = { [sym]: "value" } + +let obj = { + data: ['a', 'b', 'c'], + [Symbol.iterator]() { + const this_ = this + let index = 0 + return { + next() { + return { + done: index >= this_.data.length, + value: 'name_' + this_.data[index++] + } + } + } + } +} + +for (let t of obj) { + console.log(t) +} ``` **ArkTS** @@ -394,17 +412,21 @@ class SomeClass { public someProperty : string = "" } let o = new SomeClass() + +let arr:string[] = ['a', 'b', 'c'] +for (let t of arr) { + console.log('name_' + t) +} ``` **See also** * Recipe: Objects with property names that are not identifiers are not supported -* Recipe: Attempt to access an undefined property is a compile-time error +* Recipe: Indexed access is not supported for fields * Recipe: delete operator is not supported * Recipe: typeof operator is allowed only in expression contexts * Recipe: in operator is not supported * Recipe: Property-based runtime type checks are not supported -* Recipe: Dynamic property declaration is not supported * Recipe: Usage of standard library is restricted ## Recipe: Private ‘#’ identifiers are not supported @@ -420,7 +442,7 @@ the keyword `private` instead. ```typescript /* - * Such notation for private fields is not supported: + * Such notation for private fields is not supported in ArkTS: class C { #foo: number = 42 } @@ -435,14 +457,14 @@ class C { } ``` -## Recipe: Use unique names for types, namespaces, etc. +## Recipe: Use unique names for types and namespaces. **Rule `arkts-unique-names`** **Severity: error** -Names for types, namespaces and so on must be unique and distinct from other -names, e.g., variable names. +Names for all types (classes, interfaces, enums) and namespaces must be unique +and distinct from other names, e.g., variable names and function names. **TypeScript** @@ -666,7 +688,7 @@ function fn(s: string): SomeObject { **Severity: error** -ArkTS does not allow having sevaral static blocks for class initialization. +ArkTS does not allow having several static blocks for class initialization. Combine static block statements into one static block. **TypeScript** @@ -780,7 +802,7 @@ interface Employee extends Identity, Contact {} **Severity: error** ArkTS does not support type notation using the `this` keyword (for example, -specifying a method's return type `this` is not allowed). Use explicit type +specifying a method’s return type `this` is not allowed). Use explicit type instead. **TypeScript** @@ -836,7 +858,7 @@ type Y = T extends Array ? Item : never **ArkTS** ```typescript -// Provide explicit contraints within type alias +// Provide explicit constraints within type alias type X1 = T // Rewrite with Object. Less type control, need more type checks for safety @@ -960,100 +982,103 @@ type N = number **Severity: error** -ArkTS does not support indexed access for class fields. Use dot notation -instead. An exception are all typed arrays from the standard library +ArkTS does not support dynamic field declaration and access. Declare all +object fields immediately in the class. Access only those class fields +that are either declared in the class, or accessible via inheritance. Accessing +any other fields is prohibited, and causes compile-time errors. + +To access a field, use `obj.field` syntax, indexed access (`obj["field"]`) +is not supported. An exception are all typed arrays from the standard library (for example, `Int32Array`), which support access to their elements through `container[index]` syntax. **TypeScript** ```typescript -class Point {x: number = 0; y: number = 0} +class Point { + x: number = 0 + y: number = 0 +} let p: Point = {x: 1, y: 2} -let x = p["x"] +console.log(p["x"]) + +class Person { + name: string = "" + age: number = 0; // semicolon is required here + [key: string]: string | number +} + +let person: Person = { + name: "John", + age: 30, + email: "***@example.com", + phoneNumber: "18*********", +} ``` **ArkTS** ```typescript -class Point {x: number = 0; y: number = 0} +class Point { + x: number = 0 + y: number = 0 +} let p: Point = {x: 1, y: 2} -let x = p.x +console.log(p.x) + +class Person { + name: string + age: number + email: string + phoneNumber: string + + constructor(name: string, age: number, email: string, + phoneNumber: string) { + this.name = name + this.age = age + this.email = email + this.phoneNumber = phoneNumber + } +} + +let person = new Person("John", 30, "***@example.com", "18*********") +console.log(person["name"]) // Compile-time error +console.log(person.unknownProperty) // Compile-time error let arr = new Int32Array(1) console.log(arr[0]) ``` -## Recipe: Structural identity is not supported +## Recipe: Structural typing is not supported -**Rule `arkts-no-structural-identity`** +**Rule `arkts-no-structural-typing`** **Severity: error** -Currently, ArkTS does not support structural identity, i.e., the compiler +Currently, ArkTS does not support structural typing, i.e., the compiler cannot compare public APIs of two types and decide whether such types are identical. Use other mechanisms (inheritance, interfaces or type aliases) instead. -In the examples below, types `X` and `Y` are equivalent (interchangeble) -in TypeScript, while in ArkTS they are not. - **TypeScript** ```typescript -interface X { - f(): string -} - -interface Y { // Y is equal to X +interface I1 { f(): string } -``` - -**ArkTS** -```typescript -interface X { +interface I2 { // I2 is structurally equivalent to I1 f(): string } -type Y = X // Y is equal to X -``` - -**See also** - -* Recipe: Structural typing is not supported for subtyping / supertyping -* Recipe: Structural typing is not supported for assignability checks -* Recipe: Structural typing is not supported for type inference - -## Recipe: Structural typing is not supported for subtyping / supertyping - -**Rule `arkts-no-structural-subtyping`** - -**Severity: error** - -Currently, ArkTS does not check structural equivalence for type inference, -i.e., the compiler cannot compare public APIs of two types and decide whether -such types are identical. Use other mechanisms (inheritance or interfaces) -instead. - -**TypeScript** - -```typescript class X { - public foo: number - - constructor() { - this.foo = 0 - } + n: number = 0 + s: string = "" } -class Y { - public foo: number - - constructor() { - this.foo = 0 - } +class Y { // Y is structurally equivalent to X + n: number = 0 + s: string = "" } let x = new X() @@ -1064,104 +1089,62 @@ y = x console.log("Assign Y to X") x = y -``` -**ArkTS** - -```typescript -class X { - public foo: number - - constructor() { - this.foo = 0 - } +function foo(x: X) { + console.log(x.n, x.s) } -// Y is derived from X, which explicitly set subtype / supertype relations: -class Y extends X { - constructor() { - super() - } -} - -let x = new X() -let y = new Y() - -console.log("Assign Y to X") -x = y // ok, X is the super class of Y - -// Cannot assign X to Y -//y = x - compile-time error +// X and Y are equivalent because their public API is equivalent. +// Thus the second call is allowed: +foo(new X()) +foo(new Y()) ``` -**See also** - -* Recipe: Structural identity is not supported -* Recipe: Structural typing is not supported for assignability checks -* Recipe: Structural typing is not supported for type inference - -## Recipe: Structural typing is not supported for assignability checks - -**Rule `arkts-no-structural-assignability`** - -**Severity: error** - -Currently, ArkTS does not check structural equivalence when checking if types -are assignable to each other, i.e., the compiler cannot compare public APIs of -two types and decide whether such types are identical. Use other mechanisms -(inheritance or interfaces) instead. - -**TypeScript** +**ArkTS** ```typescript -class X { - public foo: number +interface I1 { + f(): string +} - constructor() { - this.foo = 0 - } +type I2 = I1 // I2 is an alias for I1 + +class B { + n: number = 0 + s: string = "" } -class Y { - public foo: number +// D is derived from B, which explicitly set subtype / supertype relations: +class D extends B { constructor() { - this.foo = 0 + super() } } -let x = new X() -let y = new Y() - -console.log("Assign X to Y") -y = x +let b = new B() +let d = new D() -console.log("Assign Y to X") -x = y -``` +console.log("Assign D to B") +b = d // ok, B is the superclass of D -**ArkTS** +// An attempt to assign b to d will result in a compile-time error: +// d = b -```typescript interface Z { - foo: number + n: number + s: string } // X implements interface Z, which makes relation between X and Y explicit. class X implements Z { - public foo: number - - constructor() { - this.foo = 0 - } + n: number = 0 + s: string = "" } // Y implements interface Z, which makes relation between X and Y explicit. class Y implements Z { - public foo: number - - constructor() { - this.foo = 0 - } + n: number = 0 + s: string = "" } let x: Z = new X() @@ -1172,13 +1155,15 @@ y = x // ok, both are of the same type console.log("Assign Y to X") x = y // ok, both are of the same type -``` -**See also** +function foo(c: Z): void { + console.log(c.n, c.s) +} -* Recipe: Structural identity is not supported -* Recipe: Structural typing is not supported for subtyping / supertyping -* Recipe: Structural typing is not supported for type inference +// X and Y implement the same interface, thus both calls are allowed: +foo(new X()) +foo(new Y()) +``` ## Recipe: Type inference in case of generic function calls is limited @@ -1223,101 +1208,6 @@ function greet(): T { let z = greet() ``` -## Recipe: Structural typing is not supported for type inference - -**Rule `arkts-no-structural-inference`** - -**Severity: error** - -Currently, ArkTS does not support structural typing, i.e., the compiler cannot -compare public APIs of two types and decide whether such types are identical. -Use inheritance and interfaces to specify the relation between the types -explicitly. - -**TypeScript** - -```typescript -class X { - public foo: number - private s: string - - constructor (f: number) { - this.foo = f - this.s = "" - } - - public say(): void { - console.log("X = ", this.foo) - } -} - -class Y { - public foo: number - - constructor (f: number) { - this.foo = f - } - public say(): void { - console.log("Y = ", this.foo) - } -} - -function bar(z: X): void { - z.say() -} - -// X and Y are equivalent because their public API is equivalent. -// Thus the second call is allowed: -bar(new X(1)) -bar(new Y(2) as X) -``` - -**ArkTS** - -```typescript -interface Z { - say(): void -} - -class X implements Z { - public foo: number - private s: string - - constructor (f: number) { - this.foo = f - this.s = "" - } - public say(): void { - console.log("X = ", this.foo) - } -} - -class Y implements Z { - public foo: number - - constructor (f: number) { - this.foo = f - } - public say(): void { - console.log("Y = ", this.foo) - } -} - -function bar(z: Z): void { - z.say() -} - -// X and Y implement the same interface Z, thus both calls are allowed: -bar(new X(1)) -bar(new Y(2)) -``` - -**See also** - -* Recipe: Structural identity is not supported -* Recipe: Structural typing is not supported for subtyping / supertyping -* Recipe: Structural typing is not supported for assignability checks - ## Recipe: RegExp literals are not supported **Rule `arkts-no-regexp-literals`** @@ -1475,7 +1365,7 @@ id_x_y({x: 5, y: 10}) **See also** * Recipe: Object literals cannot be used as type declarations -* Recipe: Array literals must contain elements of only inferrable types +* Recipe: Array literals must contain elements of only inferable types ## Recipe: Object literals cannot be used as type declarations @@ -1513,17 +1403,17 @@ type S = Set **See also** * Recipe: Object literal must correspond to some explicitly declared class or interface -* Recipe: Array literals must contain elements of only inferrable types +* Recipe: Array literals must contain elements of only inferable types -## Recipe: Array literals must contain elements of only inferrable types +## Recipe: Array literals must contain elements of only inferable types -**Rule `arkts-no-noninferrable-arr-literals`** +**Rule `arkts-no-noninferable-arr-literals`** **Severity: error** Basically, ArkTS infers the type of an array literal as a union type of its contents. However, a compile-time error occurs if there is at least one -element with a non-inferrable type (e.g. untyped object literal). +element with a non-inferable type (e.g. untyped object literal). **TypeScript** @@ -1674,57 +1564,6 @@ class C1 implements C { } ``` -## Recipe: Attempt to access an undefined property is a compile-time error - -**Rule `arkts-no-undefined-prop-access`** - -**Severity: error** - -ArkTS supports accessing only those class properties that are either declared -in the class, or accessible via inheritance. Accessing any other properties is -prohibited, and causes compile-time errors. Use proper types to check property -existence during compilation. - -**TypeScript** - -```typescript -let person = {name: "Bob", isEmployee: true} - -let n = person["name"] -let e = person["isEmployee"] -let s = person["office"] // Compile-time error only with noImplicitAny -``` - -**ArkTS** - -```typescript -class Person { - constructor(name: string, isEmployee: boolean) { - this.name = name - this.isEmployee = isEmployee - } - - name: string - isEmployee: boolean -} - -let person = new Person("Bob", true) -let n = person.name -let e = person.isEmployee -let s = person.office // Compile-time error -``` - -**See also** - -* Recipe: Objects with property names that are not identifiers are not supported -* Recipe: Symbol() API is not supported -* Recipe: delete operator is not supported -* Recipe: typeof operator is allowed only in expression contexts -* Recipe: in operator is not supported -* Recipe: Property-based runtime type checks are not supported -* Recipe: Dynamic property declaration is not supported -* Recipe: Usage of standard library is restricted - ## Recipe: Only `as T` syntax is supported for type casts **Rule `arkts-as-casts`** @@ -1892,11 +1731,10 @@ p.y = null * Recipe: Objects with property names that are not identifiers are not supported * Recipe: Symbol() API is not supported -* Recipe: Attempt to access an undefined property is a compile-time error +* Recipe: Indexed access is not supported for fields * Recipe: typeof operator is allowed only in expression contexts * Recipe: in operator is not supported * Recipe: Property-based runtime type checks are not supported -* Recipe: Dynamic property declaration is not supported ## Recipe: `typeof` operator is allowed only in expression contexts @@ -1933,72 +1771,12 @@ let s2: string * Recipe: Objects with property names that are not identifiers are not supported * Recipe: Symbol() API is not supported -* Recipe: Attempt to access an undefined property is a compile-time error +* Recipe: Indexed access is not supported for fields * Recipe: delete operator is not supported * Recipe: in operator is not supported * Recipe: Property-based runtime type checks are not supported -* Recipe: Dynamic property declaration is not supported * Recipe: Usage of standard library is restricted -## Recipe: Binary `+` operator supports implicit casts only for numbers, enums and strings - -**Rule `arkts-no-polymorphic-plus`** - -**Severity: error** - -If one of the operands of the binary `+` operator is of the string type -(including enum string constant), then the other operand can be of any type, -and its value is implicitly converted to string. -Otherwise, ArkTS supports implicit casts with `+` only for numbers and -numeric enum constants. -ArkTS, like TypeScript, does not support the operator `+` for the booleans. -Elsewhere, any form of an explicit cast is required. - -**TypeScript** - -```typescript -enum E { E1, E2 } - -let a = 10 + 32 // 42 -let b = E.E1 + 10 // 10 -let c = 10 + "5" // "105" - -let d = "5" + E.E2 // "51" -let e = "Hello, " + "world!" // "Hello, world!" -let f = "string" + true // "stringtrue" - -let g = (new Object()) + "string" // "[object Object]string" - -let i = true + true // compile-time error -let j = true + 2 // compile-time error -let k = E.E1 + true // compile-time error -``` - -**ArkTS** - -```typescript -enum E { E1, E2 } - -let a = 10 + 32 // 42 -let b = E.E1 + 10 // 10 -let c = 10 + "5" // "105" - -let d = "5" + E.E2 // "51" -let e = "Hello, " + "world!" // "Hello, world!" -let f = "string" + true // "stringtrue" - -let g = (new Object()).toString() + "string" - - -let i = true + true // compile-time error -let j = true + 2 // compile-time error -let k = E.E1 + true // compile-time error -``` - -**See also** - -* Recipe: Unary operators +, - and ~ work only on numbers - ## Recipe: `instanceof` operator is partially supported **Rule `arkts-instanceof-ref-types`** @@ -2076,11 +1854,10 @@ let b = p instanceof Person // true, and "name" is guaranteed to be present * Recipe: Objects with property names that are not identifiers are not supported * Recipe: Symbol() API is not supported -* Recipe: Attempt to access an undefined property is a compile-time error +* Recipe: Indexed access is not supported for fields * Recipe: delete operator is not supported * Recipe: typeof operator is allowed only in expression contexts * Recipe: Property-based runtime type checks are not supported -* Recipe: Dynamic property declaration is not supported * Recipe: Usage of standard library is restricted ## Recipe: Destructuring assignment is not supported @@ -2200,35 +1977,6 @@ let x = zp.x let y = zp.y ``` -## Recipe: Inference of implied types is not supported - -**Rule `arkts-no-implied-inference`** - -**Severity: error** - -Currently, ArkTS does not support inference of implied types. -Use explicit type notation instead. -Use `Object[]` if you need containers that hold data of mixed types. - -**TypeScript** - -```typescript -let [a, b, c] = [1, "hello", true] -``` - -**ArkTS** - -```typescript -let a = 1 -let b = "hello" -let c = true - -let arr: Object[] = [1, "hello", true] -let a1 = arr[0] -let b1 = arr[1] -let c1 = arr[2] -``` - ## Recipe: Type annotation in catch clause is not supported **Rule `arkts-no-types-in-catch`** @@ -2295,23 +2043,6 @@ for (let i = 0; i < a.length; ++i) { **See also** -* Recipe: Iterable interfaces are not supported -* Recipe: for-of is supported only for arrays and strings - -## Recipe: Iterable interfaces are not supported - -**Rule `arkts-no-iterable`** - -**Severity: error** - -ArkTS does not support the `Symbol` API, `Symbol.iterator` and -eventually iterable interfaces. Use arrays and library-level containers to -iterate over data. - -**See also** - -* Recipe: Symbol() API is not supported -* Recipe: for .. in is not supported * Recipe: for-of is supported only for arrays and strings ## Recipe: `for-of` is supported only for arrays and strings @@ -2346,7 +2077,6 @@ for (let n of numbers) { **See also** * Recipe: for .. in is not supported -* Recipe: Iterable interfaces are not supported ## Recipe: Mapped type expression is not supported @@ -2355,7 +2085,7 @@ for (let n of numbers) { **Severity: error** ArkTS does not support mapped types. Use other language idioms and regular -classes to achieve that same behaviour. +classes to achieve that same behavior. **TypeScript** @@ -2390,7 +2120,7 @@ class CFlags { **Severity: error** ArkTS does not support the `with` statement. Use other language idioms -(including fully qualified names of functions) to achieve that same behaviour. +(including fully qualified names of functions) to achieve that same behavior. **TypeScript** @@ -2408,96 +2138,6 @@ let r: number = 42 console.log("Area: ", Math.PI * r * r) ``` -## Recipe: Values computed at runtime are not supported in `case` statements - -**Rule `arkts-no-computed-case`** - -**Severity: error** - -ArkTS supports `case` statements that contain only compile-time values, -top-level scope `const` values, and `static readonly` class fields. -Use `if` statements as an alternative. - -**TypeScript** - -```typescript -let x = 2 -let y = 3 -switch (x) { - case 1: - console.log(1) - break - case 2: - console.log(2) - break - case y: - console.log(y) - break - default: - console.log("other") -} -``` - -**ArkTS** - -```typescript -let x = 2 -switch (x) { - case 1: - console.log(1) - break - case 2: - console.log(2) - break - case 3: - console.log(3) - break - default: - console.log("other") -} -``` - -## Recipe: `switch` statements cannot accept values of arbitrary types - -**Rule `arkts-limited-switch`** - -**Severity: error** - -ArkTS restricts the types that are supported in `switch` statements. In -particular, values of the types `number`, `Number`, `string`, `String` -or `enum` are supported. Use `if` statements in case of unsupported types. - -**TypeScript** - -```typescript -class Point { - x: number = 0 - y: number = 0 -} - -let a = new Point() - -switch (a) { - case null: break - default: console.log("not null") -} -``` - -**ArkTS** - -```typescript -class Point { - x: number = 0 - y: number = 0 -} - -let a = new Point() - -if (a != null) { - console.log("not null") -} -``` - ## Recipe: `throw` statements cannot accept values of arbitrary types **Rule `arkts-limited-throw`** @@ -2668,8 +2308,8 @@ function addNum(a: number, b: number): void { **Severity: error** -ArkTS does not support the usage of `this` inside stand-alone functions. -`this` can be used in methods only. +ArkTS does not support the usage of `this` inside stand-alone functions and +inside static methods. `this` can be used in instance methods only. **TypeScript** @@ -2738,7 +2378,7 @@ for (let num of counter(1, 5)) { ```typescript async function complexNumberProcessing(n : number) : Promise { - // Some complex logic for proccessing the number here + // Some complex logic for processing the number here return n } @@ -2946,7 +2586,7 @@ let p3d = new Point3D({x: 1, y: 2} as Point2D, 3) console.log(p3d.x, p3d.y, p3d.z) ``` -## Recipe: Interface declarations (extends same property) +## Recipe: Interface can not extend interfaces with the same method **Rule `arkts-no-extend-same-prop`** @@ -3049,8 +2689,8 @@ class C implements Mover, Shaker { **Severity: error** -ArkTS does not support merging declratations. Keep all definitions of classes, -interfaces and so on compact in the codebase. +ArkTS does not support merging declarations. Keep all definitions of classes +and interfaces compact in the codebase. **TypeScript** @@ -3175,11 +2815,10 @@ function main(): void { * Recipe: Objects with property names that are not identifiers are not supported * Recipe: Symbol() API is not supported -* Recipe: Attempt to access an undefined property is a compile-time error +* Recipe: Indexed access is not supported for fields * Recipe: delete operator is not supported * Recipe: typeof operator is allowed only in expression contexts * Recipe: in operator is not supported -* Recipe: Dynamic property declaration is not supported * Recipe: Usage of standard library is restricted ## Recipe: Constructor function type is not supported @@ -3232,67 +2871,6 @@ let Impersonizer: PersonCtor = (n: string, a: number): Person => { const person = createPerson(Impersonizer, "John", 30) ``` -## Recipe: Dynamic property declaration is not supported - -**Rule `arkts-no-dyn-prop-decl`** - -**Severity: error** - -ArkTS does not support dynamic property declaration. Declare all object -properties immediately in the class. While replacement for an array of -objects is possible, it is still better to adhere to the static language -paradigm, and declare fields, their names and types explicitly. - -**TypeScript** - -```typescript -class Person { - name: string = "" - age: number = 0; // semicolon is required here - [key: string]: string | number -} - -const person: Person = { - name: "John", - age: 30, - email: "john@example.com", - phoneNumber: 1234567890, -} -``` - -**ArkTS** - -```typescript -class Person { - name: string - age: number - email: string - phoneNumber: number - - constructor(name: string, age: number, email: string, phoneNumber: number) { - this.name = name - this.age = age - this.email = email - this.phoneNumber = phoneNumber - } -} - -function main(): void { - const person: Person = new Person("John", 30, "john@example.com", 1234567890) -} -``` - -**See also** - -* Recipe: Objects with property names that are not identifiers are not supported -* Recipe: Symbol() API is not supported -* Recipe: Attempt to access an undefined property is a compile-time error -* Recipe: delete operator is not supported -* Recipe: typeof operator is allowed only in expression contexts -* Recipe: in operator is not supported -* Recipe: Property-based runtime type checks are not supported -* Recipe: Usage of standard library is restricted - ## Recipe: Enumeration members can be initialized only with compile time expressions of the same type **Rule `arkts-no-enum-mixed-types`** @@ -3347,7 +2925,7 @@ enum E2 { **Severity: error** -ArkTS does not support merging declratations for `enum`. Keep the +ArkTS does not support merging declarations for `enum`. Keep the declaration of each `enum` compact in the codebase. **TypeScript** @@ -3414,7 +2992,7 @@ MyNamespace.x = 2 **Severity: error** -ArkTS does not support statements in namespaces. Use a function to exectute +ArkTS does not support statements in namespaces. Use a function to execute statements. **TypeScript** @@ -3498,7 +3076,7 @@ import "path/to/module" **ArkTS** ```typescript -import * from "path/to/module" +import * as m from "path/to/module" ``` ## Recipe: `import default as ...` is not supported @@ -3591,6 +3169,9 @@ export class C2 { export { Class1 } from "module1" export { C2 as Class2 } from "module1" +// Re-exporting by wild-card is also supported: +// export * from "module1" + // consumer module import { Class1, Class2 } from "module2" ``` @@ -3746,7 +3327,7 @@ declare namespace N { } // Consuming code: -import * from "module" +import * as m from "module" console.log("N.foo called: ", N.foo(42)) ``` @@ -4115,7 +3696,7 @@ function readFileSync(path : string) : number[] { return [] } -function decodeImageSync(contrents : number[]) { +function decodeImageSync(contents : number[]) { // ... } @@ -4347,11 +3928,10 @@ Properties and functions of the global object: `eval`, * Recipe: Objects with property names that are not identifiers are not supported * Recipe: Symbol() API is not supported -* Recipe: Attempt to access an undefined property is a compile-time error +* Recipe: Indexed access is not supported for fields * Recipe: typeof operator is allowed only in expression contexts * Recipe: in operator is not supported * Recipe: Property-based runtime type checks are not supported -* Recipe: Dynamic property declaration is not supported * Recipe: globalThis is not supported ## Recipe: Strict type checking is enforced @@ -4563,3 +4143,4 @@ class C { n: number = 0 } ``` + diff --git a/en/application-dev/reference/apis/js-apis-bluetooth-ble.md b/en/application-dev/reference/apis/js-apis-bluetooth-ble.md index 03c7b7eded3243a25730c8b14b79613315764b1a..3fc732259472842cc9dff52fdeed6d154e99ab4c 100644 --- a/en/application-dev/reference/apis/js-apis-bluetooth-ble.md +++ b/en/application-dev/reference/apis/js-apis-bluetooth-ble.md @@ -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<[CharacteristicWriteRequest](#characteristicwriterequest)> | 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<number>): 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<number> | 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<number>): 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<number> | 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<number>): 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<number> | 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<number> | Yes | Callback invoked to return the number of MTU bytes.| **Example** @@ -2210,7 +2270,7 @@ try { off(type: 'BLEMtuChange', callback?: Callback<number>): 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<number> | 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<number> | No | Callback for the MTU status changes. If this parameter is not set, this API unsubscribes from all callbacks corresponding to **type**.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-cardEmulation.md b/en/application-dev/reference/apis/js-apis-cardEmulation.md index 946ebd2f881fe66a7ec6b0afc8e308d254a6f68c..59bfac2a827d240ed0ffe39fb3a99e5d35bab9b9 100644 --- a/en/application-dev/reference/apis/js-apis-cardEmulation.md +++ b/en/application-dev/reference/apis/js-apis-cardEmulation.md @@ -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.| +## HceService8+ + +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. + +### startHCE8+ + +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.| + +### start9+ + +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. | + +### stopHCE8+ + +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 + +### stop9+ + +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. | + +### on8+ + +on(type: "hceCmd", callback: AsyncCallback): 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 | Yes | Callback invoked to return the APDU, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| + +### sendResponse8+ + +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**.| + +### transmit9+ + +transmit(response: number[]): Promise\; + +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\ | 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. | + +### transmit9+ + +transmit(response: number[], callback: AsyncCallback\): 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\ | 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 diff --git a/en/application-dev/reference/apis/js-apis-commonEventManager.md b/en/application-dev/reference/apis/js-apis-commonEventManager.md index 070fee6a9381edfea0ceaf7758b01f41a137b861..1754dc36d54e935f38b617be757528f45c7fcd17 100644 --- a/en/application-dev/reference/apis/js-apis-commonEventManager.md +++ b/en/application-dev/reference/apis/js-apis-commonEventManager.md @@ -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; } diff --git a/en/application-dev/reference/apis/js-apis-file-fileuri.md b/en/application-dev/reference/apis/js-apis-file-fileuri.md index f713a5d0ee3127642ca2d391b71a7b9b310c2a61..07f3ba2ed6cf1faf8d747236fb7a2a9969130c41 100644 --- a/en/application-dev/reference/apis/js-apis-file-fileuri.md +++ b/en/application-dev/reference/apis/js-apis-file-fileuri.md @@ -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). +## FileUri10+ + +### Attributes + +**System capability**: SystemCapability.FileManagement.AppFileService + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| path10+ | string | Yes| No| Path of the file corresponding to the URI.| +| name10+ | string | Yes| No| Name of the file.| + +### constructor10+ + +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:
- Application sandbox URI: **file://\/\**
- URI of the user's document: **file://docs/storage/Users/currentUser/\**
- URI of the user's media asset: **file://media/\/IMG_DATATIME_ID/\**| + +**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:///data/storage/el2/base/haps/entry/files/test +let fileUriObject = new fileuri.FileUri(uri); +console.info("The name of FileUri is " + fileUriObject.name); +``` + +### toString10+ + +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 diff --git a/en/application-dev/reference/apis/js-apis-file-fs.md b/en/application-dev/reference/apis/js-apis-file-fs.md index 3e783a185818183eb33d3419cf5bbb6f0d47cfa2..02a6ce4e2bcb4684b034fc1191278fd0f3ff34fc 100644 --- a/en/application-dev/reference/apis/js-apis-file-fs.md +++ b/en/application-dev/reference/apis/js-apis-file-fs.md @@ -314,6 +314,7 @@ For details about the error codes, see [Basic File IO Error Codes](../errorcodes console.info("close file failed with error message: " + err.message + ", error code: " + err.code); } else { console.info("close file success"); + fs.closeSync(file); } }); ``` @@ -460,7 +461,7 @@ Copies a directory to the specified directory. This API uses a promise to return | ------ | ------ | ---- | --------------------------- | | src | string | Yes | Application sandbox path of the directory to copy.| | dest | string | Yes | Application sandbox path of the destination directory.| - | mode | number | No | Copy mode. The default value is **0**.
- **0**: Throw an exception if a file conflict occurs.
Throw an exception if there is a directory with the same name in the destination directory and files with the same name exist in the conflicting directory. All the non-conflicting files in the source directory will be moved to the destination directory, and the non-conflicting files in the destination directory will be retained. The **data** attribute in the error returned provides information about the conflicting files in the Array\<[ConflictFiles](#conflictfiles)> format.
- **1**: Forcibly overwrite the files with the same name in the destination directory.
If there is a directory with the same name in the destination directory and files with the same name exist in the conflicting directory, all the files with the same name in the destination directory will be overwritten and the non-conflicting files will be retained.| + | mode | number | No | Copy mode. The default value is **0**.
- **0**: Throw an exception if a file conflict occurs.
Throw an exception if there is a directory with the same name in the destination directory and files with the same name exist in the conflicting directory. All the non-conflicting files in the source directory will be moved to the destination directory, and the non-conflicting files in the destination directory will be retained. The **data** attribute in the error returned provides information about the conflicting files in the Array\<[ConflictFiles](#conflictfiles10)> format.
- **1**: Forcibly overwrite the files with the same name in the destination directory. If there is a directory with the same name in the destination directory and files with the same name exist in the conflicting directory, all the files with the same name in the destination directory will be overwritten and the non-conflicting files will be retained.| **Return value** @@ -494,7 +495,7 @@ For details about the error codes, see [Basic File IO Error Codes](../errorcodes ## fs.copyDir10+ -copyDir(src: string, dest: string, mode?: number, callback: AsyncCallback\): void +copyDir(src: string, dest: string, mode?: number, callback: AsyncCallback\>): void Copies a directory to the specified directory. This API uses an asynchronous callback to return the result. @@ -506,8 +507,8 @@ Copies a directory to the specified directory. This API uses an asynchronous cal | ------ | ------ | ---- | --------------------------- | | src | string | Yes | Application sandbox path of the directory to copy.| | dest | string | Yes | Application sandbox path of the destination directory.| - | mode | number | No | Copy mode. The default value is **0**.
- **0**: Throw an exception if a file conflict occurs.
Throw an exception if there is a directory with the same name in the destination directory and files with the same name exist in the conflicting directory. All the non-conflicting files in the source directory will be moved to the destination directory, and the non-conflicting files in the destination directory will be retained. The **data** attribute in the error returned provides information about the conflicting files in the Array\<[ConflictFiles](#conflictfiles)> format.
- **1**: Forcibly overwrite the files with the same name in the destination directory.
If there is a directory with the same name in the destination directory and files with the same name exist in the conflicting directory, all the files with the same name in the destination directory will be overwritten and the non-conflicting files will be retained.| - | callback | AsyncCallback<void> | Yes | Callback invoked immediately after the directory is copied. | + | mode | number | No | Copy mode. The default value is **0**.
- **0**: Throw an exception if a file conflict occurs.
Throw an exception if there is a directory with the same name in the destination directory and files with the same name exist in the conflicting directory. All the non-conflicting files in the source directory will be moved to the destination directory, and the non-conflicting files in the destination directory will be retained. The **data** attribute in the error returned provides information about the conflicting files in the Array\<[ConflictFiles](#conflictfiles10)> format.
- **1**: Forcibly overwrite the files with the same name in the destination directory. If there is a directory with the same name in the destination directory and files with the same name exist in the conflicting directory, all the files with the same name in the destination directory will be overwritten and the non-conflicting files will be retained.| + | callback | AsyncCallback<void, Array<[ConflictFiles](#conflictfiles10)>> | Yes | Callback invoked immediately after the directory is copied. | **Error codes** @@ -533,6 +534,41 @@ For details about the error codes, see [Basic File IO Error Codes](../errorcodes }); ``` +## fs.dup10+ + +dup(fd: number): File + +Opens a **File** object based on the specified FD. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + + | Name | Type | Mandatory | Description | + | ------ | ------ | ---- | --------------------------- | + | fd | number | Yes | FD of the file.| + +**Return value** + + | Type | Description | + | ------------------- | ---------------------------- | + | [File](#file) | File object opened.| + +**Error codes** + +For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes). + +**Example** + + ```js + // convert fd to file + let fd = 0; // fd comes from other modules + let file = fs.dup(fd); + console.info("The name of the file is " + file.name); + fs.closeSync(file); + ``` + + ## fs.mkdir mkdir(path: string): Promise<void> @@ -644,7 +680,7 @@ Opens a file. This API uses a promise to return the result. File uniform resourc | Type | Description | | --------------------- | ----------- | - | Promise<[File](#file)> | Promise used to return the file object.| + | Promise<[File](#file)> | Promise used to return the **File** object.| **Error codes** @@ -1566,6 +1602,7 @@ For details about the error codes, see [Basic File IO Error Codes](../errorcodes let file = fs.openSync(filePath); fs.fsync(file.fd).then(() => { console.info("Data flushed"); + fs.closeSync(file); }).catch((err) => { console.info("sync data failed with error message: " + err.message + ", error code: " + err.code); }); @@ -1851,7 +1888,7 @@ Lists all files in a folder. This API uses a promise to return the result.
Th | Name | Type | Mandatory | Description | | ------ | ------ | ---- | --------------------------- | - | recursion | boolean | No | Whether to list all files in subfolders recursively. The default value is **false**.| + | recursion | boolean | No | Whether to list all files in subfolders recursively. The default value is **false**. If **recursion** is **false**, the names of the files and folders that meet the specified conditions in the current directory are returned. If **recursion** is **true**, the relative paths (starting with /) of all files that meet the specified conditions in the directory are returned.| | listNum | number | No | Number of file names to list. The default value **0** means to list all files.| | filter | [Filter](#filter) | No | File filtering options. Currently, only the match by file name extension, fuzzy search by file name, and filter by file size or latest modification time are supported.| @@ -1873,7 +1910,7 @@ For details about the error codes, see [Basic File IO Error Codes](../errorcodes "listNum": 0, "filter": { "suffix": [".png", ".jpg", ".jpeg"], - "displayName": ["%abc", "efg%"], + "displayName": ["*abc", "efg*"], "fileSizeOver": 1024, "lastModifiedAfter": new Date().getTime(), } @@ -1911,7 +1948,7 @@ Lists all files in a folder. This API uses an asynchronous callback to return th | Name | Type | Mandatory | Description | | ------ | ------ | ---- | --------------------------- | - | recursion | boolean | No | Whether to list all files in subfolders recursively. The default value is **false**.| + | recursion | boolean | No | Whether to list all files in subfolders recursively. The default value is **false**. If **recursion** is **false**, the names of the files and folders that meet the specified conditions in the current directory are returned. If **recursion** is **true**, the relative paths (starting with /) of all files that meet the specified conditions in the directory are returned.| | listNum | number | No | Number of file names to list. The default value **0** means to list all files.| | filter | [Filter](#filter) | No | File filtering options. Currently, only the match by file name extension, fuzzy search by file name, and filter by file size or latest modification time are supported.| @@ -1927,7 +1964,7 @@ For details about the error codes, see [Basic File IO Error Codes](../errorcodes "listNum": 0, "filter": { "suffix": [".png", ".jpg", ".jpeg"], - "displayName": ["%abc", "efg%"], + "displayName": ["*abc", "efg*"], "fileSizeOver": 1024, "lastModifiedAfter": new Date().getTime(), } @@ -1967,7 +2004,7 @@ Lists all files in a folder synchronously. This API supports recursive listing o | Name | Type | Mandatory | Description | | ------ | ------ | ---- | --------------------------- | - | recursion | boolean | No | Whether to list all files in subfolders recursively. The default value is **false**.| + | recursion | boolean | No | Whether to list all files in subfolders recursively. The default value is **false**. If **recursion** is **false**, the names of the files and folders that meet the specified conditions in the current directory are returned. If **recursion** is **true**, the relative paths (starting with /) of all files that meet the specified conditions in the directory are returned.| | listNum | number | No | Number of file names to list. The default value **0** means to list all files.| | filter | [Filter](#filter) | No | File filtering options. Currently, only the match by file name extension, fuzzy search by file name, and filter by file size or latest modification time are supported.| @@ -1989,7 +2026,7 @@ For details about the error codes, see [Basic File IO Error Codes](../errorcodes "listNum": 0, "filter": { "suffix": [".png", ".jpg", ".jpeg"], - "displayName": ["%abc", "efg%"], + "displayName": ["*abc", "efg*"], "fileSizeOver": 1024, "lastModifiedAfter": new Date().getTime(), } @@ -2015,7 +2052,7 @@ Moves a directory. This API uses a promise to return the result. | ------ | ------ | ---- | --------------------------- | | src | string | Yes | Application sandbox path of the directory to move.| | dest | string | Yes | Application sandbox path of the destination directory.| - | mode | number | No | Mode for moving the directory. The default value is **0**.
- **0**: Throw an exception if a directory conflict occurs.
Throw an exception if there is a directory with the same name in the destination directory.
- **1**: Throw an exception if a file conflict occurs.
Throw an exception if there is a directory with the same name in the destination directory and files with the same name exist in the conflicting directory. All the non-conflicting files in the source directory will be moved to the destination directory, and the non-conflicting files in the destination directory will be retained. The **data** attribute in the error returned provides information about the conflicting files in the Array\<[ConflictFiles](#conflictfiles)> format.
- **2**: Forcibly overwrite the conflicting files in the destination directory.
If there is a directory with the same name in the destination directory and files with the same name exist in the conflicting directory, all the files with the same name in the destination directory will be overwritten and the non-conflicting files will be retained.
- **3**: Forcibly overwrite the conflicting directory.
Move the source directory to the destination directory and overwrite the conflicting directory completely. That is, if there is a directory with the same name in the destination directory, all the original files in that directory will not be retained.| + | mode | number | No | Mode for moving the directory. The default value is **0**.
- **0**: Throw an exception if a directory conflict occurs.
Throw an exception if there is a non-empty directory with the same name in the destination directory.
- **1**: Throw an exception if a file conflict occurs.
Throw an exception if there is a directory with the same name in the destination directory and files with the same name exist in the conflicting directory. All the non-conflicting files in the source directory will be moved to the destination directory, and the non-conflicting files in the destination directory will be retained. The **data** attribute in the error returned provides information about the conflicting files in the Array\<[ConflictFiles](#conflictfiles10)> format.
- **2**: Forcibly overwrite the conflicting files in the destination directory. If there is a directory with the same name in the destination directory and files with the same name exist in the conflicting directory, all the files with the same name in the destination directory will be overwritten and the non-conflicting files will be retained.
- **3**: Forcibly overwrite the conflicting directory.
Move the source directory to the destination directory and overwrite the conflicting directory completely. That is, if there is a directory with the same name in the destination directory, all the original files in that directory will not be retained.| **Return value** @@ -2049,7 +2086,7 @@ For details about the error codes, see [Basic File IO Error Codes](../errorcodes ## fs.moveDir10+ -moveDir(src: string, dest: string, mode?: number, callback: AsyncCallback\): void +moveDir(src: string, dest: string, mode?: number, callback: AsyncCallback\>): void Moves a directory. This API uses an asynchronous callback to return the result. @@ -2061,8 +2098,8 @@ Moves a directory. This API uses an asynchronous callback to return the result. | ------ | ------ | ---- | --------------------------- | | src | string | Yes | Application sandbox path of the source directory.| | dest | string | Yes | Application sandbox path of the destination directory.| - | mode | number | No | Mode for moving the directory. The default value is **0**.
- **0**: Throw an exception if a directory conflict occurs.
Throw an exception if there is a directory with the same name in the destination directory.
- **1**: Throw an exception if a file conflict occurs.
Throw an exception if there is a directory with the same name in the destination directory and files with the same name exist in the conflicting directory. All the non-conflicting files in the source directory will be moved to the destination directory, and the non-conflicting files in the destination directory will be retained. The **data** attribute in the error returned provides information about the conflicting files in the Array\<[ConflictFiles](#conflictfiles)> format.
- **2**: Forcibly overwrite the conflicting files in the destination directory. If there is a directory with the same name in the destination directory and files with the same name exist in the conflicting directory, all the files with the same name in the destination directory will be overwritten and the non-conflicting files will be retained.
- **3**: Forcibly overwrite the conflicting directory.
Move the source directory to the destination directory and overwrite the conflicting directory completely. That is, if there is a directory with the same name in the destination directory, all the original files in that directory will not be retained.| - | callback | AsyncCallback<void> | Yes | Callback invoked when the directory is moved. | + | mode | number | No | Mode for moving the directory. The default value is **0**.
- **0**: Throw an exception if a directory conflict occurs.
Throw an exception if there is a directory with the same name in the destination directory.
- **1**: Throw an exception if a file conflict occurs.
Throw an exception if there is a directory with the same name in the destination directory and files with the same name exist in the conflicting directory. All the non-conflicting files in the source directory will be moved to the destination directory, and the non-conflicting files in the destination directory will be retained. The **data** attribute in the error returned provides information about the conflicting files in the Array\<[ConflictFiles](#conflictfiles10)> format.
- **2**: Forcibly overwrite the conflicting files in the destination directory. If there is a directory with the same name in the destination directory and files with the same name exist in the conflicting directory, all the files with the same name in the destination directory will be overwritten and the non-conflicting files will be retained.
- **3**: Forcibly overwrite the conflicting directory.
Move the source directory to the destination directory and overwrite the conflicting directory completely. That is, if there is a directory with the same name in the destination directory, all the original files in that directory will not be retained.| + | callback | AsyncCallback<void, Array<[ConflictFiles](#conflictfiles10)>> | Yes | Callback invoked when the directory is moved. | **Error codes** @@ -2288,7 +2325,7 @@ For details about the error codes, see [Basic File IO Error Codes](../errorcodes ## fs.createRandomAccessFile10+ -createRandomAccessFile(file: string|File, mode?: string): Promise<RandomAccessFile> +createRandomAccessFile(file: string|File, mode?: number): Promise<RandomAccessFile> Creates a **RandomAccessFile** instance based on the specified file path or file object. This API uses a promise to return the result. @@ -2317,6 +2354,8 @@ For details about the error codes, see [Basic File IO Error Codes](../errorcodes let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); fs.createRandomAccessFile(file).then((randomAccessFile) => { console.info("randomAccessFile fd: " + randomAccessFile.fd); + randomAccessFile.close(); + fs.closeSync(file); }).catch((err) => { console.info("create randomAccessFile failed with error message: " + err.message + ", error code: " + err.code); }); @@ -2325,7 +2364,7 @@ For details about the error codes, see [Basic File IO Error Codes](../errorcodes ## fs.createRandomAccessFile10+ -createRandomAccessFile(file: string|File, mode?: string, callback: AsyncCallback<RandomAccessFile>): void +createRandomAccessFile(file: string|File, mode?: number, callback: AsyncCallback<RandomAccessFile>): void Creates a **RandomAccessFile** instance based on the specified file path or file object. This API uses an asynchronous callback to return the result. @@ -2352,6 +2391,8 @@ For details about the error codes, see [Basic File IO Error Codes](../errorcodes console.info("create randomAccessFile failed with error message: " + err.message + ", error code: " + err.code); } else { console.info("randomAccessFilefile fd: " + randomAccessFile.fd); + randomAccessFile.close(); + fs.closeSync(file); } }); ``` @@ -2359,7 +2400,7 @@ For details about the error codes, see [Basic File IO Error Codes](../errorcodes ## fs.createRandomAccessFileSync10+ -createRandomAccessFileSync(file: string|File, , mode?: string): RandomAccessFile +createRandomAccessFileSync(file: string|File, mode?: number): RandomAccessFile Creates a **RandomAccessFile** instance based on the specified file path or file object. @@ -2386,8 +2427,10 @@ For details about the error codes, see [Basic File IO Error Codes](../errorcodes ```js let filePath = pathDir + "/test.txt"; - let file = fs.openSync(filePath, fileIO.OpenMode.CREATE | fileIO.OpenMode.READ_WRITE); - let randomaccessfile = fileIO.createRandomAccessFileSync(file); + let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); + let randomaccessfile = fs.createRandomAccessFileSync(file); + randomaccessfile.close(); + fs.closeSync(file); ``` ## fs.createStream @@ -3232,7 +3275,7 @@ Synchronously reads data from the stream. | Name | Type | Mandatory | Description | | ------- | ----------- | ---- | ---------------------------------------- | | buffer | ArrayBuffer | Yes | Buffer used to store the file read. | - | options | Object | No | The options are as follows:
- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.
- **offset** (number): start position to read the data. This parameter is optional. By default, data is read from the current position.
| + | options | Object | No | The options are as follows:
- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.
- **offset** (number): start position to read the data. This parameter is optional. By default, data is read from the current position.
| **Return value** @@ -3263,6 +3306,8 @@ Represents a **File** object opened by **open()**. | Name | Type | Readable | Writable | Description | | ---- | ------ | ---- | ---- | ------- | | fd | number | Yes | No | FD of the file.| +| path10+ | string | Yes | No | Path of the file.| +| name10+ | string | Yes | No | Name of the file.| ### lock @@ -3410,6 +3455,7 @@ For details about the error codes, see [Basic File IO Error Codes](../errorcodes let filePath = pathDir + "/test.txt"; let randomAccessFile = fs.createRandomAccessFileSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); randomAccessFile.setFilePointer(1); + randomAccessFile.close(); ``` @@ -3430,7 +3476,7 @@ For details about the error codes, see [Basic File IO Error Codes](../errorcodes ```js let filePath = pathDir + "/test.txt"; let randomAccessFile = fs.createRandomAccessFileSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); - randomAccessFile.closeSync(); + randomAccessFile.close(); ``` ### write10+ @@ -3462,11 +3508,13 @@ For details about the error codes, see [Basic File IO Error Codes](../errorcodes ```js let filePath = pathDir + "/test.txt"; - let file = fs.openSync(fpath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); + let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); let randomaccessfile = fs.createRandomAccessFileSync(file); let bufferLength = 4096; randomaccessfile.write(new ArrayBuffer(bufferLength), { offset: 1, length: 5 }).then((bytesWritten) => { console.info("randomAccessFile bytesWritten: " + bytesWritten); + randomaccessfile.close(); + fs.closeSync(file); }).catch((err) => { console.info("create randomAccessFile failed with error message: " + err.message + ", error code: " + err.code); }); @@ -3497,6 +3545,7 @@ For details about the error codes, see [Basic File IO Error Codes](../errorcodes ```js let filePath = pathDir + "/test.txt"; + let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); let randomAccessFile = fs.createRandomAccessFileSync(file); let bufferLength = 4096; randomAccessFile.write(new ArrayBuffer(bufferLength), { offset: 1 }, function(err, bytesWritten) { @@ -3505,6 +3554,8 @@ For details about the error codes, see [Basic File IO Error Codes](../errorcodes } else { if (bytesWritten) { console.info("write succeed and size is:" + bytesWritten); + randomAccessFile.close(); + fs.closeSync(file); } } }); @@ -3539,8 +3590,10 @@ For details about the error codes, see [Basic File IO Error Codes](../errorcodes ```js let filePath = pathDir + "/test.txt"; - let randomaccessfile= fs.createRandomAccessFileSync(filePath,"r+"); + let randomaccessfile = fs.createRandomAccessFileSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); let bytesWritten = randomaccessfile.writeSync("hello, world", {offset: 5, length: 5, encoding :'utf-8'}); + randomaccessfile.close(); + fs.closeSync(file); ``` ### read10+ @@ -3577,6 +3630,8 @@ For details about the error codes, see [Basic File IO Error Codes](../errorcodes let bufferLength = 4096; randomaccessfile.read(new ArrayBuffer(bufferLength), { offset: 1, length: 5 }).then((readLength) => { console.info("randomAccessFile readLength: " + readLength); + randomaccessfile.close(); + fs.closeSync(file); }).catch((err) => { console.info("create randomAccessFile failed with error message: " + err.message + ", error code: " + err.code); }); @@ -3607,7 +3662,7 @@ For details about the error codes, see [Basic File IO Error Codes](../errorcodes ```js let filePath = pathDir + "/test.txt"; let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); - let randomaccessfile = await fileIO.createRandomAccessFile(file); + let randomaccessfile = fs.createRandomAccessFileSync(file); let length = 20; randomaccessfile.read(new ArrayBuffer(length), { offset: 1, length: 5 }, function (err, readLength) { if (err) { @@ -3615,6 +3670,8 @@ For details about the error codes, see [Basic File IO Error Codes](../errorcodes } else { if (readLength) { console.info("read succeed and size is:" + readLength); + randomaccessfile.close(); + fs.closeSync(file); } } }); @@ -3633,7 +3690,7 @@ Synchronously reads data from a file. | Name | Type | Mandatory | Description | | ------- | ----------- | ---- | ---------------------------------------- | | buffer | ArrayBuffer | Yes | Buffer used to store the file read. | - | options | Object | No | The options are as follows:
- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.
- **offset** (number): start position to read the data (it is determined by **filePointer** plus **offset**). This parameter is optional. By default, data is read from the **filePointer**.
| + | options | Object | No | The options are as follows:
- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.
- **offset** (number): start position to read the data (it is determined by **filePointer** plus **offset**). This parameter is optional. By default, data is read from the **filePointer**.
| **Return value** @@ -3649,10 +3706,12 @@ For details about the error codes, see [Basic File IO Error Codes](../errorcodes ```js let filePath = pathDir + "/test.txt"; - let file = fs.openSync(filePath, fileIO.OpenMode.CREATE | fileIO.OpenMode.READ_WRITE); + let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); let randomaccessfile = fs.createRandomAccessFileSync(file); let length = 4096; let readLength = randomaccessfile.readSync(new ArrayBuffer(length)); + randomaccessfile.close(); + fs.closeSync(file); ``` diff --git a/en/application-dev/reference/apis/js-apis-file-picker.md b/en/application-dev/reference/apis/js-apis-file-picker.md index b8572f3bf4df0d6a60b5f7835ac1bf9346d19b1f..24a39e81bfd42e50489a50fa39bad0a14f8671d3 100644 --- a/en/application-dev/reference/apis/js-apis-file-picker.md +++ b/en/application-dev/reference/apis/js-apis-file-picker.md @@ -8,8 +8,13 @@ ## Modules to Import -```js +> **NOTE** +> +> You need to import the **BusinessError** module if **BusinessError** is used in the sample code. + +```ts import picker from '@ohos.file.picker'; +import { BusinessError } from '@ohos.base'; ``` ## PhotoViewPicker @@ -47,19 +52,20 @@ Selects one or more images or videos in a **photoPicker** page. This API uses a **Example** ```ts -async function example() { +async function example01() { try { let PhotoSelectOptions = new picker.PhotoSelectOptions(); PhotoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE; PhotoSelectOptions.maxSelectNumber = 5; let photoPicker = new picker.PhotoViewPicker(); - photoPicker.select(PhotoSelectOptions).then((PhotoSelectResult) => { + photoPicker.select(PhotoSelectOptions).then((PhotoSelectResult: picker.PhotoSelectResult) => { console.info('PhotoViewPicker.select successfully, PhotoSelectResult uri: ' + JSON.stringify(PhotoSelectResult)); - }).catch((err) => { - console.error('PhotoViewPicker.select failed with err: ' + err); + }).catch((err: BusinessError) => { + console.error('PhotoViewPicker.select failed with err: ' + JSON.stringify(err)); }); - } catch (err) { - console.error('PhotoViewPicker failed with err: ' + err); + } catch (error) { + let err: BusinessError = error as BusinessError; + console.error('PhotoViewPicker failed with err: ' + JSON.stringify(err)); } } ``` @@ -82,21 +88,22 @@ Selects one or more images or videos in a **photoPicker** page. This API uses an **Example** ```ts -async function example() { - try { +async function example02() { + try { let PhotoSelectOptions = new picker.PhotoSelectOptions(); PhotoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE; PhotoSelectOptions.maxSelectNumber = 5; let photoPicker = new picker.PhotoViewPicker(); - photoPicker.select(PhotoSelectOptions, (err, PhotoSelectResult) => { + photoPicker.select(PhotoSelectOptions, (err: BusinessError, PhotoSelectResult: picker.PhotoSelectResult) => { if (err) { - console.error('PhotoViewPicker.select failed with err: ' + err); + console.error('PhotoViewPicker.select failed with err: ' + JSON.stringify(err)); return; } console.info('PhotoViewPicker.select successfully, PhotoSelectResult uri: ' + JSON.stringify(PhotoSelectResult)); }); - } catch (err) { - console.error('PhotoViewPicker failed with err: ' + err); + } catch (error) { + let err: BusinessError = error as BusinessError; + console.error('PhotoViewPicker failed with err: ' + JSON.stringify(err)); } } ``` @@ -118,18 +125,19 @@ Selects one or more images or videos in a **photoPicker** page. This API uses an **Example** ```ts -async function example() { - try { +async function example03() { + try { let photoPicker = new picker.PhotoViewPicker(); - photoPicker.select((err, PhotoSelectResult) => { + photoPicker.select((err: BusinessError, PhotoSelectResult: picker.PhotoSelectResult) => { if (err) { - console.error('PhotoViewPicker.select failed with err: ' + err); + console.error('PhotoViewPicker.select failed with err: ' + JSON.stringify(err)); return; } console.info('PhotoViewPicker.select successfully, PhotoSelectResult uri: ' + JSON.stringify(PhotoSelectResult)); }); - } catch (err) { - console.error('PhotoViewPicker failed with err: ' + err); + } catch (error) { + let err: BusinessError = error as BusinessError; + console.error('PhotoViewPicker failed with err: ' + JSON.stringify(err)); } } ``` @@ -157,18 +165,19 @@ Saves one or more images or videos in a **photoPicker** page. This API uses a pr **Example** ```ts -async function example() { - try { +async function example04() { + try { let PhotoSaveOptions = new picker.PhotoSaveOptions(); PhotoSaveOptions.newFileNames = ['PhotoViewPicker01.jpg', 'PhotoViewPicker01.mp4']; let photoPicker = new picker.PhotoViewPicker(); - photoPicker.save(PhotoSaveOptions).then((PhotoSaveResult) => { + photoPicker.save(PhotoSaveOptions).then((PhotoSaveResult: Array) => { console.info('PhotoViewPicker.save successfully, PhotoSaveResult uri: ' + JSON.stringify(PhotoSaveResult)); - }).catch((err) => { - console.error('PhotoViewPicker.save failed with err: ' + err); + }).catch((err: BusinessError) => { + console.error('PhotoViewPicker.save failed with err: ' + JSON.stringify(err)); }); - } catch (err) { - console.error('PhotoViewPicker failed with err: ' + err); + } catch (error) { + let err: BusinessError = error as BusinessError; + console.error('PhotoViewPicker failed with err: ' + JSON.stringify(err)); } } ``` @@ -191,20 +200,21 @@ Saves one or more images or videos in a **photoPicker** page. This API uses an a **Example** ```ts -async function example() { +async function example05() { try { let PhotoSaveOptions = new picker.PhotoSaveOptions(); PhotoSaveOptions.newFileNames = ['PhotoViewPicker02.jpg','PhotoViewPicker02.mp4']; let photoPicker = new picker.PhotoViewPicker(); - photoPicker.save(PhotoSaveOptions, (err, PhotoSaveResult) => { + photoPicker.save(PhotoSaveOptions, (err: BusinessError, PhotoSaveResult: Array) => { if (err) { - console.error('PhotoViewPicker.save failed with err: ' + err); + console.error('PhotoViewPicker.save failed with err: ' + JSON.stringify(err)); return; } console.info('PhotoViewPicker.save successfully, PhotoSaveResult uri: ' + JSON.stringify(PhotoSaveResult)); }); - } catch (err) { - console.error('PhotoViewPicker failed with err: ' + err); + } catch (error) { + let err: BusinessError = error as BusinessError; + console.error('PhotoViewPicker failed with err: ' + JSON.stringify(err)); } } ``` @@ -226,25 +236,26 @@ Saves one or more images or videos in a **photoPicker** page. This API uses an a **Example** ```ts -async function example() { +async function example06() { try { let photoPicker = new picker.PhotoViewPicker(); - photoPicker.save((err, PhotoSaveResult) => { + photoPicker.save((err: BusinessError, PhotoSaveResult: Array) => { if (err) { - console.error('PhotoViewPicker.save failed with err: ' + err); + console.error('PhotoViewPicker.save failed with err: ' + JSON.stringify(err)); return; } console.info('PhotoViewPicker.save successfully, PhotoSaveResult uri: ' + JSON.stringify(PhotoSaveResult)); }); - } catch (err) { - console.error('PhotoViewPicker failed with err: ' + err); + } catch (error) { + let err: BusinessError = error as BusinessError; + console.error('PhotoViewPicker failed with err: ' + JSON.stringify(err)); } } ``` ## DocumentViewPicker -Provides APIs for selecting and saving non-media files, for example, documents in a variety of formats. Before using the APIs of **DocumentViewPicker**, you need to create a **DocumentViewPicker** instance. +Provides the **DocumentViewPicker** object for selecting and saving documents in different formats. Before using the APIs of **DocumentViewPicker**, you need to create a **DocumentViewPicker** instance. **System capability**: SystemCapability.FileManagement.UserFileService @@ -277,17 +288,18 @@ Selects one or more documents in a **documentPicker** page. This API uses a prom **Example** ```ts -async function example() { +async function example07() { try { let DocumentSelectOptions = new picker.DocumentSelectOptions(); let documentPicker = new picker.DocumentViewPicker(); - documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => { + documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult: Array) => { console.info('DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult)); - }).catch((err) => { - console.error('DocumentViewPicker.select failed with err: ' + err); + }).catch((err: BusinessError) => { + console.error('DocumentViewPicker.select failed with err: ' + JSON.stringify(err)); }); - } catch (err) { - console.error('DocumentViewPicker failed with err: ' + err); + } catch (error) { + let err: BusinessError = error as BusinessError; + console.error('DocumentViewPicker failed with err: ' + JSON.stringify(err)); } } ``` @@ -310,19 +322,20 @@ Selects one or more documents in a **documentPicker** page. This API uses an asy **Example** ```ts -async function example() { +async function example08() { try { let DocumentSelectOptions = new picker.DocumentSelectOptions(); let documentPicker = new picker.DocumentViewPicker(); - documentPicker.select(DocumentSelectOptions, (err, DocumentSelectResult) => { + documentPicker.select(DocumentSelectOptions, (err: BusinessError, DocumentSelectResult: Array) => { if (err) { - console.error('DocumentViewPicker.select failed with err: ' + err); + console.error('DocumentViewPicker.select failed with err: ' + JSON.stringify(err)); return; } console.info('DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult)); }); - } catch (err) { - console.error('DocumentViewPicker failed with err: ' + err); + } catch (error) { + let err: BusinessError = error as BusinessError; + console.error('DocumentViewPicker failed with err: ' + JSON.stringify(err)); } } ``` @@ -344,18 +357,19 @@ Selects one or more documents in a **documentPicker** page. This API uses an asy **Example** ```ts -async function example() { +async function example09() { try { let documentPicker = new picker.DocumentViewPicker(); - documentPicker.select((err, DocumentSelectResult) => { + documentPicker.select((err: BusinessError, DocumentSelectResult: Array) => { if (err) { - console.error('DocumentViewPicker.select failed with err: ' + err); + console.error('DocumentViewPicker.select failed with err: ' + JSON.stringify(err)); return; } console.info('DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult)); }); - } catch (err) { - console.error('DocumentViewPicker failed with err: ' + err); + } catch (error) { + let err: BusinessError = error as BusinessError; + console.error('DocumentViewPicker failed with err: ' + JSON.stringify(err)); } } ``` @@ -384,18 +398,19 @@ Saves one or more documents in a **documentPicker** page. This API uses a promis **Example** ```ts -async function example() { +async function example10() { try { let DocumentSaveOptions = new picker.DocumentSaveOptions(); DocumentSaveOptions.newFileNames = ['DocumentViewPicker01.txt']; let documentPicker = new picker.DocumentViewPicker(); - documentPicker.save(DocumentSaveOptions).then((DocumentSaveResult) => { + documentPicker.save(DocumentSaveOptions).then((DocumentSaveResult: Array) => { console.info('DocumentViewPicker.save successfully, DocumentSaveResult uri: ' + JSON.stringify(DocumentSaveResult)); - }).catch((err) => { - console.error('DocumentViewPicker.save failed with err: ' + err); + }).catch((err: BusinessError) => { + console.error('DocumentViewPicker.save failed with err: ' + JSON.stringify(err)); }); - } catch (err) { - console.error('DocumentViewPicker failed with err: ' + err); + } catch (error) { + let err: BusinessError = error as BusinessError; + console.error('DocumentViewPicker failed with err: ' + JSON.stringify(err)); } } ``` @@ -418,20 +433,21 @@ Saves one or more documents in a **documentPicker** page. This API uses an async **Example** ```ts -async function example() { +async function example11() { try { let DocumentSaveOptions = new picker.DocumentSaveOptions(); DocumentSaveOptions.newFileNames = ['DocumentViewPicker02.txt']; let documentPicker = new picker.DocumentViewPicker(); - documentPicker.save(DocumentSaveOptions, (err, DocumentSaveResult) => { + documentPicker.save(DocumentSaveOptions, (err: BusinessError, DocumentSaveResult: Array) => { if (err) { - console.error('DocumentViewPicker.save failed with err: ' + err); + console.error('DocumentViewPicker.save failed with err: ' + JSON.stringify(err)); return; } console.info('DocumentViewPicker.save successfully, DocumentSaveResult uri: ' + JSON.stringify(DocumentSaveResult)); }); - } catch (err) { - console.error('DocumentViewPicker failed with err: ' + err); + } catch (error) { + let err: BusinessError = error as BusinessError; + console.error('DocumentViewPicker failed with err: ' + JSON.stringify(err)); } } ``` @@ -453,18 +469,19 @@ Saves one or more documents in a **documentPicker** page. This API uses an async **Example** ```ts -async function example() { +async function example12() { try { let documentPicker = new picker.DocumentViewPicker(); - documentPicker.save((err, DocumentSaveResult) => { + documentPicker.save((err: BusinessError, DocumentSaveResult: Array) => { if (err) { - console.error('DocumentViewPicker.save failed with err: ' + err); + console.error('DocumentViewPicker.save failed with err: ' + JSON.stringify(err)); return; } console.info('DocumentViewPicker.save successfully, DocumentSaveResult uri: ' + JSON.stringify(DocumentSaveResult)); }); - } catch (err) { - console.error('DocumentViewPicker failed with err: ' + err); + } catch (error) { + let err: BusinessError = error as BusinessError; + console.error('DocumentViewPicker failed with err: ' + JSON.stringify(err)); } } ``` @@ -504,17 +521,18 @@ Selects one or more audio files in an **audioPicker** page (currently, a **docum **Example** ```ts -async function example() { +async function example13() { try { let AudioSelectOptions = new picker.AudioSelectOptions(); let audioPicker = new picker.AudioViewPicker(); - audioPicker.select(AudioSelectOptions).then((AudioSelectResult) => { + audioPicker.select(AudioSelectOptions).then((AudioSelectResult: Array) => { console.info('AudioViewPicker.select successfully, AudioSelectResult uri: ' + JSON.stringify(AudioSelectResult)); - }).catch((err) => { - console.error('AudioViewPicker.select failed with err: ' + err); + }).catch((err: BusinessError) => { + console.error('AudioViewPicker.select failed with err: ' + JSON.stringify(err)); }); - } catch (err) { - console.error('AudioViewPicker failed with err: ' + err); + } catch (error) { + let err: BusinessError = error as BusinessError; + console.error('AudioViewPicker failed with err: ' + JSON.stringify(err)); } } ``` @@ -537,19 +555,20 @@ Selects one or more audio files in an **audioPicker** page (currently, a **docum **Example** ```ts -async function example() { +async function example14() { try { let AudioSelectOptions = new picker.AudioSelectOptions(); let audioPicker = new picker.AudioViewPicker(); - audioPicker.select(AudioSelectOptions, (err, AudioSelectResult) => { + audioPicker.select(AudioSelectOptions, (err: BusinessError, AudioSelectResult: Array) => { if (err) { - console.error('AudioViewPicker.select failed with err: ' + err); + console.error('AudioViewPicker.select failed with err: ' + JSON.stringify(err)); return; } console.info('AudioViewPicker.select successfully, AudioSelectResult uri: ' + JSON.stringify(AudioSelectResult)); }); - } catch (err) { - console.error('AudioViewPicker failed with err: ' + err); + } catch (error) { + let err: BusinessError = error as BusinessError; + console.error('AudioViewPicker failed with err: ' + JSON.stringify(err)); } } ``` @@ -571,18 +590,19 @@ Selects one or more audio files in an **audioPicker** page (currently, a **docum **Example** ```ts -async function example() { +async function example15() { try { let audioPicker = new picker.AudioViewPicker(); - audioPicker.select((err, AudioSelectResult) => { + audioPicker.select((err: BusinessError, AudioSelectResult: Array) => { if (err) { - console.error('AudioViewPicker.select failed with err: ' + err); + console.error('AudioViewPicker.select failed with err: ' + JSON.stringify(err)); return; } console.info('AudioViewPicker.select successfully, AudioSelectResult uri: ' + JSON.stringify(AudioSelectResult)); }); - } catch (err) { - console.error('AudioViewPicker failed with err: ' + err); + } catch (error) { + let err: BusinessError = error as BusinessError; + console.error('AudioViewPicker failed with err: ' + JSON.stringify(err)); } } ``` @@ -610,18 +630,19 @@ Saves one or more audio files in an **audioPicker** page (currently, a **documen **Example** ```ts -async function example() { +async function example16() { try { let AudioSaveOptions = new picker.AudioSaveOptions(); AudioSaveOptions.newFileNames = ['AudioViewPicker01.mp3']; let audioPicker = new picker.AudioViewPicker(); - audioPicker.save(AudioSaveOptions).then((AudioSaveResult) => { + audioPicker.save(AudioSaveOptions).then((AudioSaveResult: Array) => { console.info('AudioViewPicker.save successfully, AudioSaveResult uri: ' + JSON.stringify(AudioSaveResult)) - }).catch((err) => { - console.error('AudioViewPicker.save failed with err: ' + err); + }).catch((err: BusinessError) => { + console.error('AudioViewPicker.save failed with err: ' + JSON.stringify(err)); }); - } catch (err) { - console.error('AudioViewPicker failed with err: ' + err); + } catch (error) { + let err: BusinessError = error as BusinessError; + console.error('AudioViewPicker failed with err: ' + JSON.stringify(err)); } } ``` @@ -644,20 +665,21 @@ Saves one or more audio files in an **audioPicker** page (currently, a **documen **Example** ```ts -async function example() { +async function example17() { try { let AudioSaveOptions = new picker.AudioSaveOptions(); AudioSaveOptions.newFileNames = ['AudioViewPicker02.mp3']; let audioPicker = new picker.AudioViewPicker(); - audioPicker.save(AudioSaveOptions, (err, AudioSaveResult) => { + audioPicker.save(AudioSaveOptions, (err: BusinessError, AudioSaveResult: Array) => { if (err) { - console.error('AudioViewPicker.save failed with err: ' + err); + console.error('AudioViewPicker.save failed with err: ' + JSON.stringify(err)); return; } console.info('AudioViewPicker.save successfully, AudioSaveResult uri: ' + JSON.stringify(AudioSaveResult)); }); - } catch (err) { - console.error('AudioViewPicker failed with err: ' + err); + } catch (error) { + let err: BusinessError = error as BusinessError; + console.error('AudioViewPicker failed with err: ' + JSON.stringify(err)); } } ``` @@ -679,18 +701,19 @@ Saves one or more audio files in an **audioPicker** page (currently, a **documen **Example** ```ts -async function example() { +async function example18() { try { let audioPicker = new picker.AudioViewPicker(); - audioPicker.save((err, AudioSaveResult) => { + audioPicker.save((err: BusinessError, AudioSaveResult: Array) => { if (err) { - console.error('AudioViewPicker.save failed with err: ' + err); + console.error('AudioViewPicker.save failed with err: ' + JSON.stringify(err)); return; } console.info('AudioViewPicker.save successfully, AudioSaveResult uri: ' + JSON.stringify(AudioSaveResult)); }); - } catch (err) { - console.error('AudioViewPicker failed with err: ' + err); + } catch (error) { + let err: BusinessError = error as BusinessError; + console.error('AudioViewPicker failed with err: ' + JSON.stringify(err)); } } ``` @@ -715,8 +738,8 @@ Defines the options for selecting images or videos. | Name | Type | Mandatory| Description | | ----------------------- | ------------------- | ---- | -------------------------------- | -| MIMEType? | [PhotoViewMIMETypes](#photoviewmimetypes) | No | Available media file types. **IMAGE_VIDEO_TYPE** is used by default.| -| maxSelectNumber? | number | No | Maximum number of media files to select. The default value is **50**, and the maximum value is **500**. | +| MIMEType | [PhotoViewMIMETypes](#photoviewmimetypes) | No | Available media file types. **IMAGE_VIDEO_TYPE** is used by default.| +| maxSelectNumber | number | No | Maximum number of media files to select. The default value is **50**, and the maximum value is **500**. | ## PhotoSelectResult @@ -737,14 +760,20 @@ Defines the options for saving images or videos. | Name | Type | Mandatory| Description | | ----------------------- | ------------------- | ---- | ---------------------------- | -| newFileNames? | Array<string> | No | Names of the files to save. If this parameter is not specified, the user needs to enter the file names.| +| newFileNames | Array<string> | No | Names of the files to save. If this parameter is not specified, the user needs to enter the file names.| ## DocumentSelectOptions -Defines the options for selecting documents. Currently, this parameter cannot be configured. +Defines the options for selecting documents. **System capability**: SystemCapability.FileManagement.UserFileService +| Name | Type | Mandatory| Description | +| ----------------------- | ------------------- | ---- | -------------------------------- | +| maxSelectNumber10+ | number | No | Maximum number of files or directories that can be selected.
Value range: 1–500
Maximum value: **500** | +| defaultFilePathUri10+ | string | No | Path of the file or directory to select.| +| fileSuffixFilters10+ | Array<string> | No | File name extensions of the documents to select.| + ## DocumentSaveOptions Defines the options for saving documents. @@ -753,7 +782,9 @@ Defines the options for saving documents. | Name | Type | Mandatory| Description | | ----------------------- | ------------------- | ---- | ---------------------------- | -| newFileNames? | Array<string> | No | Names of the documents to save. If this parameter is not specified, the user needs to enter the document names. | +| newFileNames | Array<string> | No | Names of the documents to save. If this parameter is not specified, the user needs to enter the document names. | +| defaultFilePathUri10+ | string | No | Path of the file or directory to save.| +| fileSuffixChoices10+ | Array<string> | No | File name extensions of the documents to save.| ## AudioSelectOptions @@ -769,4 +800,4 @@ Defines the options for saving audio files. | Name | Type | Mandatory| Description | | ----------------------- | ------------------- | ---- | ---------------------------- | -| newFileNames? | Array<string> | No | Name of the audio files to save. If this parameter is not specified, the user needs to enter the file names.| +| newFileNames | Array<string> | No | Name of the audio files to save. If this parameter is not specified, the user needs to enter the file names.| diff --git a/en/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventSubscriber.md b/en/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventSubscriber.md index cc3d507ee9d208bc66571ca56daf1cf518c3d5fe..f0d740a85d874d643838135e2bc83232ab86a62d 100644 --- a/en/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventSubscriber.md +++ b/en/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventSubscriber.md @@ -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"); diff --git a/en/application-dev/reference/apis/js-apis-inputconsumer.md b/en/application-dev/reference/apis/js-apis-inputconsumer.md index 4de59dd1322f1cc83203ad38bc63746c81d56e8a..dafc758638557477995f86b78dd065a6e69e2496 100644 --- a/en/application-dev/reference/apis/js-apis-inputconsumer.md +++ b/en/application-dev/reference/apis/js-apis-inputconsumer.md @@ -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); diff --git a/en/application-dev/reference/apis/js-apis-inputdevice.md b/en/application-dev/reference/apis/js-apis-inputdevice.md index b69a4f06be062bf9a06e61ee79c0c5d496749148..65c03cd72ff83527028c273b03a83492ed270db2 100644 --- a/en/application-dev/reference/apis/js-apis-inputdevice.md +++ b/en/application-dev/reference/apis/js-apis-inputdevice.md @@ -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) => { 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) => { 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) => { 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) => { 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; diff --git a/en/application-dev/reference/apis/js-apis-inputmonitor.md b/en/application-dev/reference/apis/js-apis-inputmonitor.md index d6514f42799102b15c8e20a978fe71494c281dfd..a9f075f19b1dab7e8c60d97cf3573951ed6c30b1 100644 --- a/en/application-dev/reference/apis/js-apis-inputmonitor.md +++ b/en/application-dev/reference/apis/js-apis-inputmonitor.md @@ -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; }; diff --git a/en/application-dev/reference/apis/js-apis-nfcTag.md b/en/application-dev/reference/apis/js-apis-nfcTag.md index 07e68bebed8fd58bbf29a1bb6d800b8a5710821c..c5b1ea381c93742da1cb1daa80f31561debe2b35 100644 --- a/en/application-dev/reference/apis/js-apis-nfcTag.md +++ b/en/application-dev/reference/apis/js-apis-nfcTag.md @@ -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 { diff --git a/en/application-dev/reference/apis/js-apis-nfctech.md b/en/application-dev/reference/apis/js-apis-nfctech.md index b4f4905ccc0b3a6310f74ea700d16b3e6df519ea..60036f27371e1cc70b17f2bb7dbf61d169a75e62 100644 --- a/en/application-dev/reference/apis/js-apis-nfctech.md +++ b/en/application-dev/reference/apis/js-apis-nfctech.md @@ -1863,7 +1863,7 @@ The following describes the unique APIs of **MifareUltralightTag**. readMultiplePages(pageIndex: number): Promise\ -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\): 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\ | 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\ | 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** diff --git a/en/application-dev/reference/apis/js-apis-pointer.md b/en/application-dev/reference/apis/js-apis-pointer.md index 39d64c64f8d0f015b44823b5fe87f42f8a06bde2..15d233733a0d8ec8cf9dfe37e2fb2d36a1836439 100644 --- a/en/application-dev/reference/apis/js-apis-pointer.md +++ b/en/application-dev/reference/apis/js-apis-pointer.md @@ -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, speed:number) => { 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; diff --git a/zh-cn/application-dev/application-models/Readme-CN.md b/zh-cn/application-dev/application-models/Readme-CN.md index 2f5d818537a2e5020a0ab1617597d0b14427a5f4..e7482b11c9aafef87d85b70a0359cc97a3b43a3d 100644 --- a/zh-cn/application-dev/application-models/Readme-CN.md +++ b/zh-cn/application-dev/application-models/Readme-CN.md @@ -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) diff --git a/zh-cn/application-dev/application-models/arkts-ui-widget-event-call.md b/zh-cn/application-dev/application-models/arkts-ui-widget-event-call.md index 8a674be2aafc5ed44c8ac330b3cc366f7c470fa2..5613815201cf1a19015f76c1b743c68a838821a3 100644 --- a/zh-cn/application-dev/application-models/arkts-ui-widget-event-call.md +++ b/zh-cn/application-dev/application-models/arkts-ui-widget-event-call.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)}`); } } }; diff --git a/zh-cn/application-dev/application-models/arkts-ui-widget-event-formextensionability.md b/zh-cn/application-dev/application-models/arkts-ui-widget-event-formextensionability.md index 9f82d3bad12319224a1bc3a9aafbff57b97eb2f8..736a4b4a9eba5a2231d2622ce51e397b54d3d329 100644 --- a/zh-cn/application-dev/application-models/arkts-ui-widget-event-formextensionability.md +++ b/zh-cn/application-dev/application-models/arkts-ui-widget-event-formextensionability.md @@ -52,10 +52,10 @@ let formData = new Map(); 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.'); + }); } ... diff --git a/zh-cn/application-dev/application-models/arkts-ui-widget-event-router.md b/zh-cn/application-dev/application-models/arkts-ui-widget-event-router.md index eaaf5cbb7b431a3b3dee53bc4a9696661dfa07c7..45b67e1de66b987783fe0e0faaca0211935829bb 100644 --- a/zh-cn/application-dev/application-models/arkts-ui-widget-event-router.md +++ b/zh-cn/application-dev/application-models/arkts-ui-widget-event-router.md @@ -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 = 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 = 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; diff --git a/zh-cn/application-dev/application-models/arkts-ui-widget-event-uiability.md b/zh-cn/application-dev/application-models/arkts-ui-widget-event-uiability.md index d5e225db93f33277251bbb0e12ad94ccda219c80..35f6b7ff5d882ca5fb0843559b6c60312b58c705 100644 --- a/zh-cn/application-dev/application-models/arkts-ui-widget-event-uiability.md +++ b/zh-cn/application-dev/application-models/arkts-ui-widget-event-uiability.md @@ -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 = { "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 | 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 = 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 = { "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 diff --git a/zh-cn/application-dev/application-models/arkts-ui-widget-image-update.md b/zh-cn/application-dev/application-models/arkts-ui-widget-image-update.md index dacec67a009610221d8d175451261673cae04d79..46fadf04886fc5ee9d646a81819e4d82d7a6bd61 100644 --- a/zh-cn/application-dev/application-models/arkts-ui-widget-image-update.md +++ b/zh-cn/application-dev/application-models/arkts-ui-widget-image-update.md @@ -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(); + formData.set('text', 'Image: Bear'); + formData.set('imgName', 'imgBear'); + formData.set('loaded', true); + try { + file = fs.openSync(tempDir + '/' + 'head.PNG'); + let imgBear: Record = { + '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(); + try { + file = fs.openSync(tmpFile); + formData.set('text', 'Image: Bear' + fileName); + formData.set('imgName', 'imgBear' + fileName); + formData.set('loaded', true); + let imgBear: Record = { + '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传递过来的卡片内容。 diff --git a/zh-cn/application-dev/application-models/arkts-ui-widget-lifecycle.md b/zh-cn/application-dev/application-models/arkts-ui-widget-lifecycle.md index f3c90861a5d6cdd0ab39b940acd7d49defd9a374..bcce41ee8f33b59591b73246faa34e9841349cf6 100644 --- a/zh-cn/application-dev/application-models/arkts-ui-widget-lifecycle.md +++ b/zh-cn/application-dev/application-models/arkts-ui-widget-lifecycle.md @@ -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 = { + '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 = { + '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) { + // 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; + } + } ``` diff --git a/zh-cn/application-dev/application-models/arkts-ui-widget-update-by-proxy.md b/zh-cn/application-dev/application-models/arkts-ui-widget-update-by-proxy.md index 35476c1a8c09c8ef90f41c11359de11c25c81f20..90df64e8f662ead1080155752b03c0a4d8056be2 100644 --- a/zh-cn/application-dev/application-models/arkts-ui-widget-update-by-proxy.md +++ b/zh-cn/application-dev/application-models/arkts-ui-widget-update-by-proxy.md @@ -76,19 +76,22 @@ > key可以是uri也可以是简单字符串,subscriberId默认值为当前formId,实际取值都依赖于数据发布方的定义。 ```ts import formBindingData from '@ohos.app.form.formBindingData'; + import Want from '@ohos.app.ability.Want'; + import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; - let dataShareHelper; - onAddForm(want) { - let formData = {}; - let proxies = [ - { - "key": "detail", - "subscriberId": "11" - } - ] - let formBinding = formBindingData.createFormBindingData(formData); - formBinding["proxies"] = proxies; - return formBinding; + export default class EntryFormAbility extends FormExtensionAbility { + onAddForm(want: Want) { + let formData: Record = {}; + let proxies: formBindingData.ProxyData[] = [ + { + "key": "detail", + "subscriberId": "11" + } + ] + let formBinding = formBindingData.createFormBindingData(formData); + formBinding["proxies"] = proxies; + return formBinding; + } } ``` @@ -151,33 +154,38 @@ ```ts import formBindingData from '@ohos.app.form.formBindingData'; import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; - import dataShare from '@ohos.data.dataShare' - - let dataShareHelper; - onAddForm(want) { - let template = { - predicates : { - "list" : "select type from TBL00 limit 0,1" - }, - scheduler: "" - } - let subscriberId = "111"; - dataShare.createDataShareHelper(this.context, "datashareproxy://com.example.myapplication", {isProxy : true}).then((data) => { - dataShareHelper = data; - dataShareHelper.addTemplate("datashareproxy://com.example.myapplication/test", subscriberId, template); - }) - - let formData = {}; - let proxies = [ - { - "key": "datashareproxy://com.example.myapplication/test", - "subscriberId": subscriberId + import dataShare from '@ohos.data.dataShare'; + import Want from '@ohos.app.ability.Want'; + + let dataShareHelper: dataShare.DataShareHelper; + export default class EntryFormAbility extends FormExtensionAbility { + onAddForm(want: Want) { + let template: dataShare.Template = { + predicates: { + "list": "select type from TBL00 limit 0,1" + }, + scheduler: "" } - ] - let formBinding = formBindingData.createFormBindingData(formData); - formBinding["proxies"] = proxies; + let subscriberId: string = "111"; + dataShare.createDataShareHelper(this.context, "datashareproxy://com.example.myapplication", { + isProxy: true + }).then((data: dataShare.DataShareHelper) => { + dataShareHelper = data; + dataShareHelper.addTemplate("datashareproxy://com.example.myapplication/test", subscriberId, template); + }) - return formBinding; + let formData: Record = {}; + let proxies: formBindingData.ProxyData[] = [ + { + "key": "datashareproxy://com.example.myapplication/test", + "subscriberId": subscriberId + } + ] + let formBinding = formBindingData.createFormBindingData(formData); + formBinding["proxies"] = proxies; + + return formBinding; + } } ``` diff --git a/zh-cn/application-dev/application-models/arkts-ui-widget-update-by-status.md b/zh-cn/application-dev/application-models/arkts-ui-widget-update-by-status.md index fc550230a7a8b1188217f51fcef89f5009aeb400..0c7ef505c34e97f4a91d225cc6ec804040e12ff6 100644 --- a/zh-cn/application-dev/application-models/arkts-ui-widget-update-by-status.md +++ b/zh-cn/application-dev/application-models/arkts-ui-widget-update-by-status.md @@ -96,56 +96,62 @@ import formBindingData from '@ohos.app.form.formBindingData'; import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; import dataPreferences from '@ohos.data.preferences'; + import Want from '@ohos.app.ability.Want'; + import Base from '@ohos.base'; export default class EntryFormAbility extends FormExtensionAbility { - onAddForm(want) { - let formId = want.parameters[formInfo.FormParam.IDENTITY_KEY]; - let isTempCard: boolean = want.parameters[formInfo.FormParam.TEMPORARY_KEY]; - if (isTempCard === false) { // 如果为常态卡片,直接进行信息持久化 - console.info('Not temp card, init db for:' + formId); - let promise = dataPreferences.getPreferences(this.context, 'myStore'); - promise.then(async (storeDB) => { - console.info("Succeeded to get preferences."); - await storeDB.put('A' + formId, 'false'); - await storeDB.put('B' + formId, 'false'); - await storeDB.flush(); - }).catch((err) => { - console.info(`Failed to get preferences. ${JSON.stringify(err)}`); - }) + onAddForm(want: Want) { + let formId: string = ''; + let isTempCard: boolean; + if (want.parameters) { + formId = JSON.stringify(want.parameters[formInfo.FormParam.IDENTITY_KEY]); + isTempCard = want.parameters[formInfo.FormParam.TEMPORARY_KEY] as boolean; + if (isTempCard === false) { // 如果为常态卡片,直接进行信息持久化 + console.info('Not temp card, init db for:' + formId); + let promise: Promise = dataPreferences.getPreferences(this.context, 'myStore'); + promise.then(async (storeDB: dataPreferences.Preferences) => { + console.info("Succeeded to get preferences."); + await storeDB.put('A' + formId, 'false'); + await storeDB.put('B' + formId, 'false'); + await storeDB.flush(); + }).catch((err: Base.BusinessError) => { + console.info(`Failed to get preferences. ${JSON.stringify(err)}`); + }) + } } - let formData = {}; + let formData: Record = {}; return formBindingData.createFormBindingData(formData); } - - onRemoveForm(formId) { + + onRemoveForm(formId: string) { console.info('onRemoveForm, formId:' + formId); let promise = dataPreferences.getPreferences(this.context, 'myStore'); promise.then(async (storeDB) => { console.info("Succeeded to get preferences."); await storeDB.delete('A' + formId); await storeDB.delete('B' + formId); - }).catch((err) => { + }).catch((err: Base.BusinessError) => { console.info(`Failed to get preferences. ${JSON.stringify(err)}`); }) } - + // 如果在添加时为临时卡片,则建议转为常态卡片时进行信息持久化 - onCastToNormalForm(formId) { + onCastToNormalForm(formId: string) { console.info('onCastToNormalForm, formId:' + formId); - let promise = dataPreferences.getPreferences(this.context, 'myStore'); - promise.then(async (storeDB) => { + let promise: Promise = dataPreferences.getPreferences(this.context, 'myStore'); + promise.then(async (storeDB: dataPreferences.Preferences) => { console.info("Succeeded to get preferences."); await storeDB.put('A' + formId, 'false'); await storeDB.put('B' + formId, 'false'); await storeDB.flush(); - }).catch((err) => { + }).catch((err: Base.BusinessError) => { console.info(`Failed to get preferences. ${JSON.stringify(err)}`); }) } - - onUpdateForm(formId) { - let promise = dataPreferences.getPreferences(this.context, 'myStore'); - promise.then(async (storeDB) => { + + onUpdateForm(formId: string) { + let promise: Promise = dataPreferences.getPreferences(this.context, 'myStore'); + promise.then(async (storeDB: dataPreferences.Preferences) => { console.info("Succeeded to get preferences."); let stateA = await storeDB.get('A' + formId, 'false'); let stateB = await storeDB.get('B' + formId, 'false'); @@ -160,18 +166,18 @@ await formProvider.updateForm(formId, formInfo); } console.info(`Update form success stateA:${stateA} stateB:${stateB}.`); - }).catch((err) => { + }).catch((err: Base.BusinessError) => { console.info(`Failed to get preferences. ${JSON.stringify(err)}`); }) } - - onFormEvent(formId, message) { + + onFormEvent(formId: string, message: string) { // 存放卡片状态 console.info('onFormEvent formId:' + formId + 'msg:' + message); - let promise = dataPreferences.getPreferences(this.context, 'myStore'); - promise.then(async (storeDB) => { + let promise: Promise = dataPreferences.getPreferences(this.context, 'myStore'); + promise.then(async (storeDB: dataPreferences.Preferences) => { console.info("Succeeded to get preferences."); - let msg = JSON.parse(message); + let msg: Record = JSON.parse(message); if (msg.selectA != undefined) { console.info('onFormEvent selectA info:' + msg.selectA); await storeDB.put('A' + formId, msg.selectA); @@ -181,7 +187,7 @@ await storeDB.put('B' + formId, msg.selectB); } await storeDB.flush(); - }).catch((err) => { + }).catch((err: Base.BusinessError) => { console.info(`Failed to get preferences. ${JSON.stringify(err)}`); }) } diff --git a/zh-cn/application-dev/application-models/arkts-ui-widget-update-by-time.md b/zh-cn/application-dev/application-models/arkts-ui-widget-update-by-time.md index 853cf48b68af6c9ec58b6110f6e5960c6d9955a3..77981c02fbc07ff5c52e8b888581ba9f0c2a28a3 100644 --- a/zh-cn/application-dev/application-models/arkts-ui-widget-update-by-time.md +++ b/zh-cn/application-dev/application-models/arkts-ui-widget-update-by-time.md @@ -69,11 +69,12 @@ ```ts import formProvider from '@ohos.app.form.formProvider'; + import Base from '@ohos.base'; - let formId = '123456789'; // 实际业务场景需要使用正确的formId + let formId: string = '123456789'; // 实际业务场景需要使用正确的formId try { // 设置过5分钟后更新卡片内容 - formProvider.setFormNextRefreshTime(formId, 5, (err, data) => { + formProvider.setFormNextRefreshTime(formId, 5, (err: Base.BusinessError) => { if (err) { console.error(`Failed to setFormNextRefreshTime. Code: ${err.code}, message: ${err.message}`); return; @@ -82,7 +83,7 @@ } }); } catch (err) { - console.error(`Failed to setFormNextRefreshTime. Code: ${err.code}, message: ${err.message}`); + console.error(`Failed to setFormNextRefreshTime. Code: ${(err as Base.BusinessError).code}, message: ${(err as Base.BusinessError).message}`); } ``` diff --git a/zh-cn/application-dev/application-models/common-event-publish.md b/zh-cn/application-dev/application-models/common-event-publish.md index 57007759a77fdab403d3c16fe60fef53487440f5..5b8c8abacd10496a2ced1b487c74cdb439c081d0 100644 --- a/zh-cn/application-dev/application-models/common-event-publish.md +++ b/zh-cn/application-dev/application-models/common-event-publish.md @@ -27,19 +27,20 @@ ```ts import commonEventManager from '@ohos.commonEventManager'; + import Base from '@ohos.base'; ``` 2. 传入需要发布的事件名称和回调函数,发布事件。 ```ts // 发布公共事件 - commonEventManager.publish("usual.event.SCREEN_OFF", (err) => { + commonEventManager.publish("usual.event.SCREEN_OFF", (err: Base.BusinessError) => { if (err) { console.error(`[CommonEvent] PublishCallBack err=${JSON.stringify(err)}`); } else { console.info(`[CommonEvent] Publish success`); } - }) + }); ``` @@ -51,13 +52,14 @@ ```ts import commonEventManager from '@ohos.commonEventManager'; + import Base from '@ohos.base'; ``` 2. 传入需要发布的事件名称和回调函数,发布事件。 ```ts // 公共事件相关信息 - let options = { + let options: commonEventManager.CommonEventPublishData = { code: 1, // 公共事件的初始代码 data: "initial data", // 公共事件的初始数据 } @@ -67,11 +69,11 @@ ```ts // 发布公共事件 - commonEventManager.publish("usual.event.SCREEN_OFF", options, (err) => { + commonEventManager.publish("usual.event.SCREEN_OFF", options, (err: Base.BusinessError) => { if (err) { console.error('[CommonEvent] PublishCallBack err=' + JSON.stringify(err)); } else { console.info('[CommonEvent] Publish success') } - }) + }); ``` diff --git a/zh-cn/application-dev/application-models/common-event-remove-sticky.md b/zh-cn/application-dev/application-models/common-event-remove-sticky.md index ac4cff82939ccc847ad935ba9448aee617a5b861..0163d7485ce2bac74980fb542e40f5ca9bcb4453 100644 --- a/zh-cn/application-dev/application-models/common-event-remove-sticky.md +++ b/zh-cn/application-dev/application-models/common-event-remove-sticky.md @@ -22,6 +22,7 @@ ```ts import commonEventManager from '@ohos.commonEventManager'; + import Base from '@ohos.base'; ``` 3. 调用[`removeStickyCommonEvent()`](../reference/apis/js-apis-commonEventManager.md#commoneventmanagerremovestickycommonevent10)方法移除对应的粘性公共事件。 @@ -31,7 +32,7 @@ > 移除的粘性公共事件,必须是本应用之前已发布的粘性公共事件,发布粘性公共事件参考[公共事件发布](common-event-publish.md)章节。 ```ts - commonEventManager.removeStickyCommonEvent("sticky_event", (err) => { // sticky_event粘性公共事件名 + commonEventManager.removeStickyCommonEvent("sticky_event", (err: Base.BusinessError) => { // sticky_event粘性公共事件名 if (err) { console.error(`Failed to remove sticky common event. Code is ${err.code}, message is ${err.message}`); return; diff --git a/zh-cn/application-dev/application-models/common-event-static-subscription.md b/zh-cn/application-dev/application-models/common-event-static-subscription.md index 8d850a19c6cb868e161a51c0ac99282b8dd5ca7c..c3f3e3a4a0427e9509e1961095d59e86db6aca6b 100644 --- a/zh-cn/application-dev/application-models/common-event-static-subscription.md +++ b/zh-cn/application-dev/application-models/common-event-static-subscription.md @@ -21,10 +21,11 @@ 开发者可以在[`onReceiveEvent()`](../reference/apis/js-apis-application-staticSubscriberExtensionAbility.md#staticsubscriberextensionabilityonreceiveevent)回调中实现业务逻辑。 ```ts - import StaticSubscriberExtensionAbility from '@ohos.application.StaticSubscriberExtensionAbility' + import StaticSubscriberExtensionAbility from '@ohos.application.StaticSubscriberExtensionAbility'; + import commonEventManager from '@ohos.commonEventManager'; export default class StaticSubscriber extends StaticSubscriberExtensionAbility { - onReceiveEvent(event) { + onReceiveEvent(event: commonEventManager.CommonEventData) { console.info('onReceiveEvent, event: ' + event.event); } } diff --git a/zh-cn/application-dev/application-models/common-event-subscription.md b/zh-cn/application-dev/application-models/common-event-subscription.md index 612cd51e55c02f36086339890564f939ce552f16..9a609c4e1b5663fa150b5f7bc72954df36d5d381 100644 --- a/zh-cn/application-dev/application-models/common-event-subscription.md +++ b/zh-cn/application-dev/application-models/common-event-subscription.md @@ -23,15 +23,16 @@ ```ts import commonEventManager from '@ohos.commonEventManager'; + import Base from '@ohos.base'; ``` 2. 创建订阅者信息,详细的订阅者信息数据类型及包含的参数请见[CommonEventSubscribeInfo](../reference/apis/js-apis-commonEventManager.md#commoneventsubscribeinfo)文档介绍。 ```ts // 用于保存创建成功的订阅者对象,后续使用其完成订阅及退订的动作 - let subscriber = null; + let subscriber: commonEventManager.CommonEventSubscriber | null = null; // 订阅者信息 - let subscribeInfo = { + let subscribeInfo: commonEventManager.CommonEventSubscribeInfo = { events: ["usual.event.SCREEN_OFF"], // 订阅灭屏公共事件 } ``` @@ -40,7 +41,7 @@ ```ts // 创建订阅者回调 - commonEventManager.createSubscriber(subscribeInfo, (err, data) => { + commonEventManager.createSubscriber(subscribeInfo, (err: Base.BusinessError, data: commonEventManager.CommonEventSubscriber) => { if (err) { console.error(`Failed to create subscriber. Code is ${err.code}, message is ${err.message}`); return; @@ -56,7 +57,7 @@ ```ts // 订阅公共事件回调 if (subscriber !== null) { - commonEventManager.subscribe(subscriber, (err, data) => { + commonEventManager.subscribe(subscriber, (err: Base.BusinessError, data: commonEventManager.CommonEventData) => { if (err) { console.error(`Failed to subscribe common event. Code is ${err.code}, message is ${err.message}`); return; diff --git a/zh-cn/application-dev/application-models/common-event-unsubscription.md b/zh-cn/application-dev/application-models/common-event-unsubscription.md index fea148863efaf2155981c17600eacc8524b8e313..394470e592b9f1a5c72e92be35af3f7c11ae77be 100644 --- a/zh-cn/application-dev/application-models/common-event-unsubscription.md +++ b/zh-cn/application-dev/application-models/common-event-unsubscription.md @@ -19,6 +19,7 @@ ```ts import commonEventManager from '@ohos.commonEventManager'; + import Base from '@ohos.base'; ``` 2. 根据[动态订阅公共事件](common-event-subscription.md)章节的步骤来订阅某个事件。 @@ -28,7 +29,7 @@ ```ts // subscriber为订阅事件时创建的订阅者对象 if (subscriber !== null) { - commonEventManager.unsubscribe(subscriber, (err) => { + commonEventManager.unsubscribe(subscriber, (err: Base.BusinessError) => { if (err) { console.error(`[CommonEvent] UnsubscribeCallBack err=${JSON.stringify(err)}`); } else { diff --git a/zh-cn/application-dev/application-models/figures/hop-cross-device-migration.png b/zh-cn/application-dev/application-models/figures/hop-cross-device-migration.png index 6c5c343855af5e4c5d8473d7df26869468c19a0a..0f1a8f1e2ac353c241517fc30934af1fc615de63 100644 Binary files a/zh-cn/application-dev/application-models/figures/hop-cross-device-migration.png and b/zh-cn/application-dev/application-models/figures/hop-cross-device-migration.png differ diff --git a/zh-cn/application-dev/application-models/figures/hop-cross-device-migration1.png b/zh-cn/application-dev/application-models/figures/hop-cross-device-migration1.png index 952218badc407b8bc2470fc1622ae0e607c4bcfb..f77c36aa5967667723fd6011dce815496148f6f3 100644 Binary files a/zh-cn/application-dev/application-models/figures/hop-cross-device-migration1.png and b/zh-cn/application-dev/application-models/figures/hop-cross-device-migration1.png differ diff --git a/zh-cn/application-dev/application-models/figures/hop-cross-device-migration2.png b/zh-cn/application-dev/application-models/figures/hop-cross-device-migration2.png index a81cb2ab08506f4e368c6002be18d6931a056218..86158bc2bcd54b83e8dc73aec204788aab0b95a3 100644 Binary files a/zh-cn/application-dev/application-models/figures/hop-cross-device-migration2.png and b/zh-cn/application-dev/application-models/figures/hop-cross-device-migration2.png differ diff --git a/zh-cn/application-dev/application-models/figures/hop-cross-device-migration3.png b/zh-cn/application-dev/application-models/figures/hop-cross-device-migration3.png index 86158bc2bcd54b83e8dc73aec204788aab0b95a3..d46240bdfae944134af616f655e9bcd4fa9a651b 100644 Binary files a/zh-cn/application-dev/application-models/figures/hop-cross-device-migration3.png and b/zh-cn/application-dev/application-models/figures/hop-cross-device-migration3.png differ diff --git a/zh-cn/application-dev/application-models/figures/hop-cross-device-migration4.png b/zh-cn/application-dev/application-models/figures/hop-cross-device-migration4.png index c743b3d10f8f1fa0a8be76cf10fff219c52d0ebf..12353f3c01b8336e3acfc916ae10411946ba6295 100644 Binary files a/zh-cn/application-dev/application-models/figures/hop-cross-device-migration4.png and b/zh-cn/application-dev/application-models/figures/hop-cross-device-migration4.png differ diff --git a/zh-cn/application-dev/application-models/figures/hop-cross-device-migration5.png b/zh-cn/application-dev/application-models/figures/hop-cross-device-migration5.png index 854af7b632121a52c9e0364efb407b209dfb63bf..bd7fd15ba712854451e4970770c3d27bcb0c451f 100644 Binary files a/zh-cn/application-dev/application-models/figures/hop-cross-device-migration5.png and b/zh-cn/application-dev/application-models/figures/hop-cross-device-migration5.png differ diff --git a/zh-cn/application-dev/application-models/figures/hop-cross-device-migration6.png b/zh-cn/application-dev/application-models/figures/hop-cross-device-migration6.png index 2d38c00bbb5d268b8072dac4b8bf22238bbe869b..45972436d1130be2521b1cbaf4c0dd59b737221d 100644 Binary files a/zh-cn/application-dev/application-models/figures/hop-cross-device-migration6.png and b/zh-cn/application-dev/application-models/figures/hop-cross-device-migration6.png differ diff --git a/zh-cn/application-dev/application-models/figures/hop-cross-device-migration7.png b/zh-cn/application-dev/application-models/figures/hop-cross-device-migration7.png deleted file mode 100644 index e789d748fe97d3c08bfaa6d22cf151bee31eccc9..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/application-models/figures/hop-cross-device-migration7.png and /dev/null differ diff --git a/zh-cn/application-dev/application-models/hop-cross-device-migration.md b/zh-cn/application-dev/application-models/hop-cross-device-migration.md index dabca884bdec8de6584efd27acf9629f1f0c658a..e165e21508a8759056e98f1d73319255cdb5012e 100644 --- a/zh-cn/application-dev/application-models/hop-cross-device-migration.md +++ b/zh-cn/application-dev/application-models/hop-cross-device-migration.md @@ -1,61 +1,52 @@ # 跨端迁移 -## 功能描述 +## 概述 -跨端迁移的主要工作是实现将应用当前任务(包括页面控件状态变量等)迁移到目标设备,能在目标设备上接续。主要功能包括: +在用户使用设备的过程中,当使用情境发生变化时(例如从室内走到户外或者周围有更适合的设备等),之前使用的设备可能已经不适合继续当前的任务,此时,用户可以选择新的设备来继续当前的任务,原设备可按需决定是否退出任务,这个就是跨端迁移的场景。常见的跨端迁移场景实例:在平板上播放的视频,迁移到智慧屏继续播放,从而获得更佳的观看体验;平板上的视频应用退出。在应用开发层面,跨端迁移指在A端运行的UIAbility迁移到B端上,完成迁移后,B端UIAbility继续任务,而A端UIAbility可按需决定是否退出。 -- 支持用户自定义数据存储及恢复。 -- 支持页面路由信息和页面控件状态数据的存储及恢复。 -- 支持应用兼容性检测。 -- 支持应用根据实际使用场景动态设置迁移状态(默认迁移状态为 **ACTIVE** 激活状态)。如编辑类应用在编辑文本的页面下才需要迁移,其他页面不需要迁移,则可以通过[setMissionContinueState](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextsetmissioncontinuestate10)进行控制。 -- 支持应用动态选择是否进行页面栈恢复(默认进行页面栈信息恢复)。如应用希望自定义迁移到其他设备后显示的页面,则可以通过[SUPPORT_CONTINUE_PAGE_STACK_KEY](../reference/apis/js-apis-app-ability-wantConstant.md#wantconstantparams)进行控制。 -- 支持应用动态选择迁移成功后是否退出迁移发起端应用(默认迁移成功后退出迁移发起端应用)。则可以通过[SUPPORT_CONTINUE_SOURCE_EXIT_KEY](../reference/apis/js-apis-app-ability-wantConstant.md#wantconstantparams)进行控制。 +跨端迁移的核心任务是将应用的当前状态(包括页面控件、状态变量等)无缝迁移到另一设备,从而在新设备上无缝接续应用体验。这意味着用户在一台设备上进行的操作可以在另一台设备的相同应用中快速切换并无缝衔接。 +主要功能包括: -## 跨端迁移流程 - -跨端迁移流程如下图所示。 - -**图1** 跨端迁移流程图 -![hop-cross-device-migration](figures/hop-cross-device-migration.png) +- 支持用户自定义数据存储及恢复。 +- 支持页面路由信息和页面控件状态数据的存储及恢复。 -## 约束限制 +- 支持应用兼容性检测。 -- 应用迁移的发起依赖系统应用控制,系统应用开发者可以参考[验证指导中的demo示例](#验证指导)实现相关的控制能力。 -- 跨端迁移要求在同UIAbility之间进行,也就是需要相同的bundleName、abilityName和签名。 -- 为了获得最佳体验,使用wantParam传输的数据建议在100KB以下。 +- 支持应用根据实际使用场景动态设置迁移状态(默认迁移状态为 **ACTIVE** 激活状态)。例如,编辑类应用在编辑文本的页面下才需要迁移,其他页面不需要迁移,则可以通过[`setMissionContinueState`](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextsetmissioncontinuestate10)进行控制。 +- 支持应用动态选择是否进行页面栈恢复(默认进行页面栈信息恢复)。例如,应用希望自定义迁移到其他设备后显示的页面,则可以通过[`SUPPORT_CONTINUE_PAGE_STACK_KEY`](../reference/apis/js-apis-app-ability-wantConstant.md#wantconstantparams)进行控制。 -## 接口说明 +- 支持应用动态选择迁移成功后是否退出迁移源端应用(默认迁移成功后退出迁移源端应用)。可以通过[`SUPPORT_CONTINUE_SOURCE_EXIT_KEY`](../reference/apis/js-apis-app-ability-wantConstant.md#wantconstantparams)进行控制。 -跨端迁移主要接口如下。详细接口介绍请参见[API参考](../reference/apis/js-apis-app-ability-uiAbility.md)。 + > **说明:** + > + > 开发者可以开发具有迁移能力的应用,迁移的触发由系统应用完成。 - **表1** 跨端迁移接口 -| **接口名** | **描述** | -| -------- | -------- | -| onContinue(wantParam : {[key: string]: Object}): OnContinueResult | 迁移发起端在该回调中保存迁移所需要的数据,同时返回是否同意迁移:
- AGREE:表示同意。
- REJECT:表示拒绝:如应用在onContinue中异常会导致钱以后数据恢复时显示异常,则可以建议REJECT。
- MISMATCH:表示版本不匹配:迁移发起端应用可以在onContinue中获取到迁移目标端应用的版本号,进行协商后,如果版本不匹配导致无法迁移,可以返回该错误。 | -| onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void; | 应用迁移目标端为冷启动或多实例应用热启动时,在该回调中完成数据恢复,并触发页面恢复。详见[应用组件启动模式](uiability-launch-type.md) | -| onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void; | 迁移目标端为单实例应用热启动时,在该回调中完成数据恢复,并触发页面恢复。详见[应用组件启动模式](uiability-launch-type.md) | +## 运作机制 +![hop-cross-device-migration](figures/hop-cross-device-migration.png) +1. 在源端,通过`UIAbility`的[`onContinue()`](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncontinue)回调,开发者可以保存待接续的业务数据。例如,在浏览器应用中完成跨端迁移,开发者需要使用[`onContinue()`](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncontinue)回调保存页面URL等业务内容,而系统将自动保存页面状态,如当前浏览进度。 +2. 分布式框架提供了跨设备应用界面、页面栈以及业务数据的保存和恢复机制,它负责将数据从源端发送到对端。 +3. 在对端,同一`UIAbility`可以通过[`onCreate()`](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate)/[`onNewWant()`](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant)接口来恢复业务数据。 -## 开发步骤 -1.需要申请`ohos.permission.DISTRIBUTED_DATASYNC`权限 - -配置方式请参见[配置文件权限声明](../security/accesstoken-guidelines.md#配置文件权限声明)。 +## 约束限制 -2.同时需要在应用首次启动时弹窗向用户申请授权 +- 跨端迁移要求在同一`UIAbility`之间进行,也就是需要相同的`bundleName`、`abilityName`和签名信息。 +- 为了获得最佳体验,使用`wantParam`传输的数据需要控制在100KB以下。 +- 当前部分ArkUI组件支持迁移后,将特定状态恢复到对端设备。详情请见[分布式迁移标识](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-restoreId.md) -使用方式请参见[向用户申请授权](../security/accesstoken-guidelines.md#向用户申请授权)。 +## 开发步骤 -3.在配置文件中配置跨端迁移相关标签字段。 +1. 需要申请`ohos.permission.DISTRIBUTED_DATASYNC`权限,配置方式请参见[配置文件权限声明](../security/accesstoken-guidelines.md#配置文件权限声明)。 -配置应用支持迁移 -在module.json5中配置continuable标签:true表示支持迁移,false表示不支持,默认为false。配置为false的UIAbility将被系统识别为无法迁移。 +2. 同时需要在应用首次启动时弹窗向用户申请授权,使用方式请参见[向用户申请授权](../security/accesstoken-guidelines.md#向用户申请授权)。 +3. 在[module.json5配置文件](../quick-start/module-configuration-file.md)的abilities标签中配置跨端迁移标签`continuable`。 ```json { @@ -64,92 +55,82 @@ "abilities": [ { // ... - "continuable": true, + "continuable": true, // 配置UIAbility支持迁移 } ] } } ``` - 根据需要配置应用启动模式类型,配置详情请参照[UIAbility组件启动模式](uiability-launch-type.md)。 - -4.在发起端UIAbility中实现[onContinue](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncontinue)接口。 - -当应用触发迁移时,[onContinue](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncontinue)接口在发起端被调用,开发者可以在该接口中保存迁移数据,实现应用兼容性检测,决定是否支持此次迁移。 - -- 保存迁移数据:开发者可以将要迁移的数据通过键值对的方式保存在wantParam中。 - -- 应用兼容性检测:开发者可以通过从wantParam中获取目标应用的版本号与本应用版本号做兼容性校验。开发者可以在触发迁移时从`onContinue`接口中`wantParam.version`获取到迁移目标端应用的版本号与迁移发起端应用版本号做兼容校验。 - -- 迁移决策:开发者可以通过onContinue接口的返回值决定是否支持此次迁移,返回值信息见[接口说明](#接口说明)。 - - 示例如下: - - ```ts - import UIAbility from '@ohos.app.ability.UIAbility'; - import AbilityConstant from '@ohos.app.ability.AbilityConstant'; - - export default class EntryAbility extends UIAbility { - onContinue(wantParam: Record) { - console.info(`onContinue version = ${wantParam.version}, targetDevice: ${wantParam.targetDevice}`) // 准备迁移数据 - let continueInput = '迁移的数据'; - if (continueInput) { - // 将要迁移的数据保存在wantParam的自定义字段(如:data)中; - wantParam["data"] = continueInput; - } - console.info(`onContinue input = ${wantParam["data"]}`); - return AbilityConstant.OnContinueResult.AGREE; - } - } - ``` - -5.在Stage模型中,应用在不同启动模式下将调用不同的接口,以恢复数据、加载界面。 - -不同情况下的函数调用如下图所示: - -![hop-cross-device-migration](figures/hop-cross-device-migration1.png) + > **说明:** + > + > 根据需要配置应用启动模式类型,配置详情请参照[UIAbility组件启动模式](uiability-launch-type.md)。 + +4. 在源端`UIAbility`中实现[`onContinue()`](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncontinue)回调。 + + 当`UIAbility`实例触发迁移时,[`onContinue()`](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncontinue)回调在源端被调用,开发者可以在该接口中保存迁移数据,实现应用兼容性检测,决定是否支持此次迁移。 + + - 保存迁移数据:开发者可以将要迁移的数据通过键值对的方式保存在`wantParam`参数中。 + - 应用兼容性检测:开发者可以通过从`wantParam`参数中获取对端应用的版本号与[源端应用版本号](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/faqs/faqs-bundle-management.md)做兼容性校验。开发者可以在触发迁移时从[`onContinue()`](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncontinue)回调中`wantParam.version`获取到迁移对端应用的版本号与迁移源端应用版本号做兼容校验。 + - 迁移决策:开发者可以通过[`onContinue()`](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncontinue)回调的返回值决定是否支持此次迁移。 + + ```ts + import UIAbility from '@ohos.app.ability.UIAbility'; + import AbilityConstant from '@ohos.app.ability.AbilityConstant'; + + export default class EntryAbility extends UIAbility { + onContinue(wantParam: Record):AbilityConstant.OnContinueResult { + let version = wantParam.version; + let targetDevice = wantParam.targetDevice; + console.info(`onContinue version = ${version}, targetDevice: ${targetDevice}`); // 准备迁移数据 + + // 获取源端版本号 + let versionSrc: number = -1; // 请填充具体获取版本号的代码 + + // 兼容性校验 + if (version !== versionSrc) { + // 在兼容性校验不通过时返回MISMATCH + return AbilityConstant.OnContinueResult.MISMATCH; + } + + // 将要迁移的数据保存在wantParam的自定义字段(例如data)中 + const continueInput = '迁移的数据'; + wantParam['data'] = continueInput; + + return AbilityConstant.OnContinueResult.AGREE; + } + } + ``` -在目标端设备UIAbility中实现onCreate与onNewWant接口,恢复迁移数据。 - -- onCreate实现示例 - - 目标端设备上,在onCreate中根据launchReason判断该次启动是否为迁移LaunchReason.CONTINUATION。 - - 开发者可以从want中获取保存的迁移数据。 - - 完成数据恢复后,开发者需要调用restoreWindowStage来触发页面恢复:包括页面栈信息。 - - ```ts - import UIAbility from '@ohos.app.ability.UIAbility'; - import AbilityConstant from '@ohos.app.ability.AbilityConstant'; - import Want from '@ohos.app.ability.Want'; - - export default class EntryAbility extends UIAbility { - storage : LocalStorage = new LocalStorage(); - onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { - console.info(`EntryAbility onCreate ${AbilityConstant.LaunchReason.CONTINUATION}`) - if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) { - // 将上述的保存的数据取出恢复 - let continueInput = ''; - if (want.parameters != undefined) { - continueInput = JSON.stringify(want.parameters.data); - console.info(`continue input ${continueInput}`) - } - // 将数据显示当前页面 - this.context.restoreWindowStage(this.storage); - } - } - } - ``` -- 如果是单实例应用,需要额外实现onNewWant接口,实现方式与onCreate的实现相同。 - - 在onNewWant中判断迁移场景,恢复数据,并触发页面恢复 - - ```ts - import UIAbility from '@ohos.app.ability.UIAbility'; - import AbilityConstant from '@ohos.app.ability.AbilityConstant'; - import Want from '@ohos.app.ability.Want'; - - export default class EntryAbility extends UIAbility { - storage : LocalStorage = new LocalStorage(); - onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void { - console.info(`EntryAbility onNewWant ${AbilityConstant.LaunchReason.CONTINUATION}`) +5. 源端设备`UIAbility`实例在冷启动和热启动情况下分别会调用不同的接口来恢复数据和加载UI。 + 在对端设备的`UIAbility`中,需要实现[`onCreate()`](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate)/[`onNewWant()`](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant)接口来恢复迁移数据。 + + 通过在[`onCreate()`](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate)/[`onNewWant()`](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant)回调中检查`launchReason`,可以判断此次启动是否有迁移触发。开发者可以从`want`中获取之前保存的迁移数据,并在数据恢复后调用`restoreWindowStage()`来触发页面恢复,包括页面栈信息。 + + ```ts + import UIAbility from '@ohos.app.ability.UIAbility'; + import AbilityConstant from '@ohos.app.ability.AbilityConstant'; + import Want from '@ohos.app.ability.Want'; + + export default class EntryAbility extends UIAbility { + storage : LocalStorage = new LocalStorage(); + + onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { + console.info('EntryAbility onCreate') + if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) { + // 将上述的保存的数据取出恢复 + let continueInput = ''; + if (want.parameters != undefined) { + continueInput = JSON.stringify(want.parameters.data); + console.info(`continue input ${continueInput}`) + } + // 将数据显示当前页面 + this.context.restoreWindowStage(this.storage); + } + } + + onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void { + console.info('EntryAbility onNewWant') if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) { // get user data from want params let continueInput = ''; @@ -160,33 +141,29 @@ this.context.restoreWindowStage(this.storage); } } - } - ``` - - + } + ``` -## 迁移功能可选配置 +## 可选配置迁移能力 -### 1.动态配置迁移能力 +### 动态配置迁移能力 -从API 10 起,提供了支持动态配置迁移能力的功能。即应用可以根据实际使用场景,在需要迁移功能时,设置开启应用迁移能力;在业务不需要迁移时,则可以关闭迁移能力。开发者可以通过调用[setMissionContinueState](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextsetmissioncontinuestate10)接口对迁移能力进行设置。默认状态下,可迁移应用的迁移能力为**ACTIVE**状态,即迁移能力开启,可以迁移。 +从API version 10开始,提供了支持动态配置迁移能力的功能。即应用可以根据实际使用场景,在需要迁移时开启应用迁移能力;在业务不需要迁移时则可以关闭迁移能力。 -| 接口状态值 | 含义 | -| :------------------------------------- | ---------------------- | -| AbilityConstant.ContinueState.ACTIVE | 应用当前可迁移能力开启 | -| AbilityConstant.ContinueState.INACTIVE | 应用当前可迁移能力关闭 | +开发者可以通过调用[`setMissionContinueState()`](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextsetmissioncontinuestate10)接口对迁移能力进行设置。默认状态下,应用的迁移能力为**ACTIVE**状态,即迁移能力开启,可以迁移。 **设置迁移能力的时机** 迁移能力的改变可以根据实际业务需求和代码实现,发生在应用生命周期的绝大多数时机。本文介绍常用的几种配置方式。 -在ability的onCreate函数中调用接口,可以在应用创建时设置应用的迁移状态。 +在`UIAbility`的[`onCreate()`](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate)回调中调用接口,可以在应用创建时设置应用的迁移状态。 ```ts // EntryAbility.ets import UIAbility from '@ohos.app.ability.UIAbility'; import AbilityConstant from '@ohos.app.ability.AbilityConstant'; import Want from '@ohos.app.ability.Want'; + export default class EntryAbility extends UIAbility { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { // ... @@ -198,12 +175,12 @@ export default class EntryAbility extends UIAbility { } ``` -在页面的onPageShow函数中调用接口,可以设置单个页面出现时应用的迁移状态。 +在页面的`onPageShow()`回调中调用接口,可以设置单个页面出现时应用的迁移状态。 ```ts // PageName.ets import AbilityConstant from '@ohos.app.ability.AbilityConstant'; -import common from '@ohos.app.ability.common' +import common from '@ohos.app.ability.common'; @Entry @Component struct PageName { @@ -215,18 +192,19 @@ struct PageName { onPageShow(){ // 进入该页面时,将应用设置为可迁移状态 this.context.setMissionContinueState(AbilityConstant.ContinueState.ACTIVE, (result) => { - console.info('setMissionContinueState ACTIVE result: ', JSON.stringify(result)); + console.info(`setMissionContinueState ACTIVE result: ${JSON.stringify(result)}`); }); } } ``` -在某个组件的触发事件中设置应用迁移能力。如下例中,使用 **Button** 组件的 **onClick** 事件,触发迁移能力的改变。 +在某个组件的触发事件中设置应用迁移能力。 ```ts // PageName.ets import AbilityConstant from '@ohos.app.ability.AbilityConstant'; -import common from '@ohos.app.ability.common' +import common from '@ohos.app.ability.common'; + @Entry @Component struct PageName { @@ -234,11 +212,11 @@ struct PageName { build() { // ... Button() { - //... + // ... }.onClick(()=>{ - //点击该按钮时,将应用设置为可迁移状态 + // 点击该按钮时,将应用设置为可迁移状态 this.context.setMissionContinueState(AbilityConstant.ContinueState.ACTIVE, (result) => { - console.info('setMissionContinueState ACTIVE result: ', JSON.stringify(result)); + console.info(`setMissionContinueState ACTIVE result: ${JSON.stringify(result)}`); }); }) } @@ -247,28 +225,30 @@ struct PageName { **保证迁移连续性** -由于迁移加载时,目标端拉起的应用可能执行过自己的迁移状态设置命令(如:冷启动时目标端在onCreate中设置了 **INACTIVE** ;热启动时对端已打开了不可迁移的页面,迁移状态为 **INACTIVE** 等情况)。为了保证迁移过后的应用依然具有可以迁移回发起端的能力,应在 onCreate和onNewWant的迁移调用判断中,将迁移状态设置为 **ACTIVE** 。 +由于迁移加载时,对端拉起的应用可能执行过自己的迁移状态设置命令(例如,冷启动时对端在[`onCreate()`](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate)中设置了 **INACTIVE** ;热启动时对端已打开了不可迁移的页面,迁移状态为 **INACTIVE** 等情况)。为了保证迁移过后的应用依然具有可以迁移回源端的能力,应在 [`onCreate()`](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate)/[`onNewWant()`](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant)的迁移调用判断中,将迁移状态设置为 **ACTIVE** 。 ```ts // EntryAbility.ets import UIAbility from '@ohos.app.ability.UIAbility'; import AbilityConstant from '@ohos.app.ability.AbilityConstant'; import Want from '@ohos.app.ability.Want'; + export default class EntryAbility extends UIAbility { // ... onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { // ... // 调用原因为迁移时,设置状态为可迁移,应对冷启动情况 this.context.setMissionContinueState(AbilityConstant.ContinueState.INACTIVE, (result) => { - console.info(`setMissionContinueState: ${JSON.stringify(result)}`); + console.info(`setMissionContinueState INACTIVE result: ${JSON.stringify(result)}`); }); } + onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void { // ... // 调用原因为迁移时,设置状态为可迁移,应对热启动情况 if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) { this.context.setMissionContinueState(AbilityConstant.ContinueState.ACTIVE, (result) => { - console.info('setMissionContinueState ACTIVE result: ', JSON.stringify(result)); + console.info(`setMissionContinueState ACTIVE result: ${JSON.stringify(result)}`); }); } } @@ -276,63 +256,62 @@ export default class EntryAbility extends UIAbility { } ``` +### 按需迁移页面栈 +支持应用动态选择是否进行页面栈恢复(默认进行页面栈信息恢复)。如果应用不想使用系统默认恢复的页面栈,则可以设置不进行页面栈迁移,而需要在`onWindowStageRestore()`设置迁移后进入的页面,参数定义见[SUPPORT_CONTINUE_PAGE_STACK_KEY](../reference/apis/js-apis-app-ability-wantConstant.md#wantconstantparams)。 -### 2.按需迁移页面栈 +应用在源端的页面栈中存在Index和Second路由,而在对端恢复时不需要按照源端页面栈进行恢复,需要恢复到指定页面。 -支持应用动态选择是否进行页面栈恢复(默认进行页面栈信息恢复)。如果应用不想使用系统默认恢复的页面栈,则可以设置不进行页面栈迁移,而需要在`onWindowStageRestore`设置迁移后进入的页面,参数定义见[SUPPORT_CONTINUE_PAGE_STACK_KEY](../reference/apis/js-apis-app-ability-wantConstant.md#wantconstantparams)。 +例如,`UIAbility`迁移不需要自动迁移页面栈信息。 -应用在发起端的页面栈中存在Index和Second路由,而在目标端恢复时不需要按照发起端页面栈进行恢复,需要恢复到指定页面。 +```ts +// EntryAbility.ets +import UIAbility from '@ohos.app.ability.UIAbility'; +import AbilityConstant from '@ohos.app.ability.AbilityConstant'; +import wantConstant from '@ohos.app.ability.wantConstant'; +import window from '@ohos.window'; -- 示例:应用迁移不需要自动迁移页面栈信息 +export default class EntryAbility extends UIAbility { + // ... + + onContinue(wantParam: Record) { + console.info(`onContinue version = ${wantParam.version}, targetDevice: ${wantParam.targetDevice}`); + wantParam[wantConstant.Params.SUPPORT_CONTINUE_PAGE_STACK_KEY] = false; + return AbilityConstant.OnContinueResult.AGREE; + } - ```ts - // EntryAbility.ets - import UIAbility from '@ohos.app.ability.UIAbility'; - import AbilityConstant from '@ohos.app.ability.AbilityConstant'; - import wantConstant from '@ohos.app.ability.wantConstant'; - import window from '@ohos.window'; - export default class EntryAbility extends UIAbility { - // ... - onContinue(wantParam: Record) { - console.info(`onContinue version = ${wantParam.version}, targetDevice: ${wantParam.targetDevice}`); - wantParam[wantConstant.Params.SUPPORT_CONTINUE_PAGE_STACK_KEY] = false; - return AbilityConstant.OnContinueResult.AGREE; + onWindowStageRestore(windowStage: window.WindowStage) { + // 若不需要自动迁移页面栈信息,则需要在此处设置应用迁移后进入的页面 + windowStage.loadContent('pages/Index', (err, data) => { + if (err.code) { + return; } - // ... - onWindowStageRestore(windowStage: window.WindowStage) { - // 若不需要自动迁移页面栈信息,则需要在此处设置应用迁移后进入的页面 - windowStage.loadContent('pages/Index', (err, data) => { - if (err.code) { - console.info('Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); - return; - } - console.info('Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? ''); - }); - } - } - ``` + }); + } +} +``` -### 3.按需退出 +### 按需退出 -支持应用动态选择迁移成功后是否退出迁移发起端应用(默认迁移成功后退出迁移发起端应用)。如果应用不想让系统自动退出迁移发起端应用,则可以设置不退出,参数定义见[SUPPORT_CONTINUE_SOURCE_EXIT_KEY](../reference/apis/js-apis-app-ability-wantConstant.md#wantconstantparams)。 +支持应用动态选择迁移成功后是否退出迁移源端应用(默认迁移成功后退出迁移源端应用)。如果应用不想让系统自动退出迁移源端应用,则可以设置不退出,参数定义见[SUPPORT_CONTINUE_SOURCE_EXIT_KEY](../reference/apis/js-apis-app-ability-wantConstant.md#wantconstantparams)。 -- 示例:应用迁移设置不需要迁移成功后退出迁移发起端应用 +示例:`UIAbility`设置迁移成功后,源端不需要退出迁移应用。 - ```ts - import UIAbility from '@ohos.app.ability.UIAbility'; - import AbilityConstant from '@ohos.app.ability.AbilityConstant'; - import wantConstant from '@ohos.app.ability.wantConstant'; - export default class EntryAbility extends UIAbility { - // ... - onContinue(wantParam: Record) { - console.info(`onContinue version = ${wantParam.version}, targetDevice: ${wantParam.targetDevice}`); - wantParam[wantConstant.Params.SUPPORT_CONTINUE_SOURCE_EXIT_KEY] = false; - return AbilityConstant.OnContinueResult.AGREE; - } - // ... - } - ``` +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import AbilityConstant from '@ohos.app.ability.AbilityConstant'; +import wantConstant from '@ohos.app.ability.wantConstant'; + +export default class EntryAbility extends UIAbility { + // ... + + onContinue(wantParam: Record) { + console.info(`onContinue version = ${wantParam.version}, targetDevice: ${wantParam.targetDevice}`); + wantParam[wantConstant.Params.SUPPORT_CONTINUE_SOURCE_EXIT_KEY] = false; + return AbilityConstant.OnContinueResult.AGREE; + } +} +``` ## 验证指导 @@ -344,54 +323,42 @@ export default class EntryAbility extends UIAbility { public-SDK不支持开发者使用所有的系统API,例如:全局任务中心使用的[**@ohos.distributedDeviceManager**](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-distributedDeviceManager.md)不包括在public_SDK中。因此为了正确编译安装全局任务中心,开发者需要替换full-SDK,具体操作可参见[替换指南](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/faqs/full-sdk-switch-guide.md)。 -**说明**:本文中的截图仅为参考,具体的显示界面请以实际使用的DevEco Studio和SDK的版本为准。 +> **说明**: +> +> 本文中的截图仅为参考,具体的显示界面请以实际使用的DevEco Studio和SDK的版本为准。 #### **下载MissionCenter_Demo[示例代码](https://gitee.com/openharmony/ability_dmsfwk/tree/master/services/dtbschedmgr/test/missionCenterDemo/dmsDemo/entry/src/main)** #### **编译工程文件** -**新建OpenHarmony 空的工程,找到对应的文件夹替换下载文件** - -![hop-cross-device-migration](figures/hop-cross-device-migration2.png) +​ a.新建OpenHarmony 空的工程,找到对应的文件夹替换下载文件 +![hop-cross-device-migration](figures/hop-cross-device-migration1.png) -**自动签名,编译安装。** +​ b.自动签名,编译安装。 ​ DevEco的自动签名模板默认签名权限为normal级。而本应用设计到ohos.permission.MANAGE_MISSIONS权限为system_core级别。自动生成的签名无法获得足够的权限,所以需要将权限升级为system_core级别,然后签名。 -**系统权限设置**(以api10目录为例): 将Sdk目录下的openharmony\api版本(如:10)\toolchains\lib\UnsgnedReleasedProfileTemplate.json文件中的"apl":"normal_core"改为"apl":"system_core"。 - -①点击file->Project Structrue - -![hop-cross-device-migration](figures/hop-cross-device-migration3.png) - -②点击Signing Configs 点击OK - -![hop-cross-device-migration](figures/hop-cross-device-migration4.png) - -③连接开发板运行生成demo。 - -### 2.设备组网 - -①打开A,B两设备的计算器 - -②点击右上角箭头选择B设备 - -③在B设备选择信任设备,弹出PIN码 - -④在A设备输入PIN码 - -⑤已组网成功,验证方法:在A设备输入数字,B设备同步出现则证明组网成功 - -### 3.发起迁移 - -1.在B设备打开多设备协同权限的应用,A设备打开全局任务中心demo,A设备出现A设备名称(即:本机:OpenHarmony 3.2)和B设备名称(OpenHarmony 3.2)。 +​ c.系统权限设置(以api10目录为例): 将Sdk目录下的openharmony\api版本(如:10)\toolchains\lib\UnsgnedReleasedProfileTemplate.json文件中的"apl":"normal_core"改为"apl":"system_core"。 -![hop-cross-device-migration](figures/hop-cross-device-migration5.png) +1. 点击file->Project Structrue。 + ![hop-cross-device-migration](figures/hop-cross-device-migration2.png) +2. 点击Signing Configs 点击OK。 + ![hop-cross-device-migration](figures/hop-cross-device-migration3.png) +3. 连接开发板运行生成demo。 -2.点击B设备名称,然后出现B设备的应用。 +### 2. 设备组网 -![hop-cross-device-migration](figures/hop-cross-device-migration6.png) +1. 打开A,B两设备的计算器。 +2. 点击右上角箭头选择B设备。 +3. 在B设备选择信任设备,弹出PIN码。 +4. 在A设备输入PIN码。 +5. 已组网成功,验证方法:在A设备输入数字,B设备同步出现则证明组网成功。 -3.最后将应用拖拽到A设备名称处,A设备应用被拉起,B设备应用退出。 +### 3. 发起迁移 -![hop-cross-device-migration](figures/hop-cross-device-migration7.png) +1. 在B设备打开多设备协同权限的应用,A设备打开全局任务中心demo,A设备出现A设备名称(即:本机:OpenHarmony 3.2)和B设备名称(OpenHarmony 3.2)。 + ![hop-cross-device-migration](figures/hop-cross-device-migration4.png) +2. 点击B设备名称,然后出现B设备的应用。 + ![hop-cross-device-migration](figures/hop-cross-device-migration5.png) +3. 最后将应用拖拽到A设备名称处,A设备应用被拉起,B设备应用退出。 + ![hop-cross-device-migration](figures/hop-cross-device-migration6.png) diff --git a/zh-cn/application-dev/application-models/inputmethodextentionability.md b/zh-cn/application-dev/application-models/inputmethodextentionability.md index 517d12bae8fdbc56a3dbfe405936981c6f43caaf..9d01ef462f77b9708e1f46568ba317639934924a 100644 --- a/zh-cn/application-dev/application-models/inputmethodextentionability.md +++ b/zh-cn/application-dev/application-models/inputmethodextentionability.md @@ -61,13 +61,13 @@ export default class InputDemoService extends InputMethodExtensionAbility { - onCreate(want: Want) { - keyboardController.onCreate(this.context); // 初始化窗口并注册对输入法框架的事件监听 + onCreate(want: Want): void { + keyboardController.onCreate(this.context); // 初始化窗口并注册对输入法框架的事件监听 } - onDestroy() { + onDestroy(): void { console.log("onDestroy."); - this.keyboardController.onDestroy(); // 销毁窗口并去注册事件监听 + keyboardController.onDestroy(); // 销毁窗口并去注册事件监听 } } ``` @@ -78,7 +78,7 @@ import common from '@ohos.app.ability.common'; import display from '@ohos.display'; import inputMethodEngine from '@ohos.inputMethodEngine'; - import InputMethodExtensionContext from '@ohos.inputMethodExtensionContext'; + import InputMethodExtensionContext from '@ohos.InputMethodExtensionContext'; // 调用输入法框架的getInputMethodAbility方法获取实例,并由此实例调用输入法框架功能接口 const inputMethodAbility: inputMethodEngine.InputMethodAbility = inputMethodEngine.getInputMethodAbility(); @@ -95,13 +95,13 @@ public onCreate(context: InputMethodExtensionContext): void { this.mContext = context; - this.initWindow(); // 初始化窗口 - this.registerListener(); // 注册对输入法框架的事件监听 + this.initWindow(); // 初始化窗口 + this.registerListener(); // 注册对输入法框架的事件监听 } - public onDestroy(): void // 应用生命周期销毁 + public onDestroy(): void // 应用生命周期销毁 { - this.unRegisterListener(); // 去注册事件监听 + this.unRegisterListener(); // 去注册事件监听 if(this.panel) { // 销毁窗口 this.panel.hide(); inputMethodAbility.destroyPanel(this.panel); @@ -123,7 +123,7 @@ } } - private initWindow(): void // 初始化窗口 + private initWindow(): void // 初始化窗口 { if(this.mContext === undefined) { return; @@ -150,18 +150,18 @@ private registerListener(): void { - this.registerInputListener(); // 注册对输入法框架服务的监听 + this.registerInputListener(); // 注册对输入法框架服务的监听 ... // 注册隐藏键盘事件监听等 } - private registerInputListener(): void { // 注册对输入法框架服务的开启及停止事件监听 + private registerInputListener(): void { // 注册对输入法框架服务的开启及停止事件监听 inputMethodAbility.on('inputStart', (kbController, textInputClient) => { - this.textInputClient = textInputClient; // 此为输入法客户端实例,由此调用输入法框架提供给输入法应用的功能接口 - this.boardController = kbController; + this.textInputClient = textInputClient; // 此为输入法客户端实例,由此调用输入法框架提供给输入法应用的功能接口 + this.keyboardController = kbController; }) inputMethodAbility.on('inputStop', () => { - this.onDestroy(); // 销毁KeyboardController + this.onDestroy(); // 销毁KeyboardController }); } @@ -232,7 +232,7 @@ @Component struct keyItem { - private keyValue: sourceListType + private keyValue: sourceListType = numberSourceListData[0]; @State keyBgc: string = "#fff" @State keyFontColor: string = "#000" @@ -283,9 +283,9 @@ build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceEvenly }) { Flex({ justifyContent: FlexAlign.SpaceBetween }) { - ForEach(this.numberList, (item: sourceListType) => { // 数字键盘第一行 + ForEach(this.numberList, (item: sourceListType) => { // 数字键盘第一行 keyItem({ keyValue: item }) - }, (item: sourceListType): sourceListType => item.content); + }, (item: sourceListType) => item.content); } .padding({ top: "2%" }) .width("96%") diff --git a/zh-cn/application-dev/application-models/start-page.md b/zh-cn/application-dev/application-models/start-page.md index ca1ce7a7ec6681573a77fb3e24bca499a529e23b..87e721fd6c871824e3b6e2c82df2f5087a37bdc2 100644 --- a/zh-cn/application-dev/application-models/start-page.md +++ b/zh-cn/application-dev/application-models/start-page.md @@ -30,7 +30,7 @@ async function restartAbility() { 在目标端PageAbility的onNewWant回调中获取包含页面信息的want参数: ```ts -import Want from '@ohos.app.ability.Want'; +// GlobalContext.ts 构造单例对象 export class GlobalContext { private constructor() {} private static instance: GlobalContext; @@ -51,6 +51,11 @@ export class GlobalContext { this._objects.set(key, objectClass); } } +``` + +```ts +import Want from '@ohos.application.Want'; +import { GlobalContext } from './GlobalContext'; export default class EntryAbility{ onNewWant(want: Want) { @@ -63,8 +68,9 @@ export default class EntryAbility{ 在目标端页面的自定义组件中获取包含页面信息的want参数并根据uri做路由处理: ```ts +import Want from '@ohos.application.Want'; import router from '@ohos.router'; -import { GlobalContext } from '../GlobalContext' +import { GlobalContext } from '../GlobalContext'; @Entry @Component @@ -73,10 +79,12 @@ struct Index { onPageShow() { console.info('Index onPageShow') - let newWant: Want = GlobalContext.getContext().getObject("newWant") - if (newWant.hasOwnProperty("page")) { - router.push({ url: newWant.page }); - GlobalContext.getContext().setObject("newWant", undefined) + let newWant = GlobalContext.getContext().getObject("newWant") as Want + if (newWant.parameters) { + if (newWant.parameters.page) { + router.push({ url: newWant.parameters.page }); + GlobalContext.getContext().setObject("newWant", undefined) + } } } @@ -160,7 +168,7 @@ export default class EntryAbility { if (want.parameters) { if (want.parameters.page) { router.push({ - url: want.parameters.page + url: want.parameters.page as string }) } } diff --git a/zh-cn/application-dev/arkts-utils/async-concurrency-overview.md b/zh-cn/application-dev/arkts-utils/async-concurrency-overview.md index c0d45f2b7fbf7c189b138bbb39f4d7a6dc90ed11..755e4526b6aae564fd80393dbfb2dfca198611a7 100644 --- a/zh-cn/application-dev/arkts-utils/async-concurrency-overview.md +++ b/zh-cn/application-dev/arkts-utils/async-concurrency-overview.md @@ -16,7 +16,7 @@ Promise有三种状态:pending(进行中)、fulfilled(已完成)和rej 最基本的用法是通过构造函数实例化一个Promise对象,同时传入一个带有两个参数的函数,通常称为executor函数。executor函数接收两个参数:resolve和reject,分别表示异步操作成功和失败时的回调函数。例如,以下代码创建了一个Promise对象并模拟了一个异步操作: -```js +```ts const promise: Promise = new Promise((resolve: Function, reject: Function) => { setTimeout(() => { const randomNumber: number = Math.random(); @@ -26,7 +26,7 @@ setTimeout(() => { reject(new Error('Random number is too small')); } }, 1000); -} +}) ``` 上述代码中,setTimeout函数模拟了一个异步操作,并在1秒钟后随机生成一个数字。如果随机数大于0.5,则执行resolve回调函数并将随机数作为参数传递;否则执行reject回调函数并传递一个错误对象作为参数。 @@ -34,11 +34,13 @@ setTimeout(() => { Promise对象创建后,可以使用then方法和catch方法指定fulfilled状态和rejected状态的回调函数。then方法可接受两个参数,一个处理fulfilled状态的函数,另一个处理rejected状态的函数。只传一个参数则表示状态改变就执行,不区分状态结果。使用catch方法注册一个回调函数,用于处理“失败”的结果,即捕获Promise的状态改变为rejected状态或操作失败抛出的异常。例如: -```js -promise.then(result => { - console.info(`Random number is ${result}`); -}).catch(error => { - console.error(error.message); +```ts +import { BusinessError } from '@ohos.base'; + +promise.then((result: number) => { + console.info(`Random number is ${result}`); +}).catch((error: BusinessError) => { + console.error(error.message); }); ``` @@ -54,7 +56,7 @@ async函数是一个返回Promise对象的函数,用于表示一个异步操 下面是一个使用async/await的例子,其中模拟了一个异步操作,该操作会在3秒钟后返回一个字符串。 -```js +```ts async function myAsyncFunction(): Promise { const result: string = await new Promise((resolve: Function) => { setTimeout(() => { @@ -72,7 +74,7 @@ myAsyncFunction(); 需要注意的是,由于要等待异步操作完成,因此需要将整个操作包在async函数中。除了在async函数中使用await外,还可以使用try/catch块来捕获异步操作中的异常。 -```js +```ts async function myAsyncFunction(): Promise { try { const result: string = await new Promise((resolve: Function) => { diff --git a/zh-cn/application-dev/arkts-utils/cpu-intensive-task-development.md b/zh-cn/application-dev/arkts-utils/cpu-intensive-task-development.md index f2f4b93b648745f755689490510e5cca65620f54..be192804f758feb83d01c627b47487eae059cafb 100644 --- a/zh-cn/application-dev/arkts-utils/cpu-intensive-task-development.md +++ b/zh-cn/application-dev/arkts-utils/cpu-intensive-task-development.md @@ -19,7 +19,6 @@ CPU密集型任务是指需要占用系统资源处理大量计算能力的任 3. 结果数组汇总处理。 - ```ts import taskpool from '@ohos.taskpool'; @@ -58,8 +57,8 @@ struct Index { .fontSize(50) .fontWeight(FontWeight.Bold) .onClick(() => { - let data: ArrayBuffer; - histogramStatistic(data); + let buffer: ArrayBuffer = new ArrayBuffer(24); + histogramStatistic(buffer); }) } .width('100%') @@ -80,107 +79,105 @@ struct Index { 2. 在主线程中通过调用ThreadWorker的[constructor()](../reference/apis/js-apis-worker.md#constructor9)方法创建Worker对象,当前线程为宿主线程。 - ```js - import worker from '@ohos.worker'; + ```ts + import worker from '@ohos.worker'; - const workerInstance: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/MyWorker.ts'); - ``` + const workerInstance: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/MyWorker.ts'); + ``` 3. 在宿主线程中通过调用[onmessage()](../reference/apis/js-apis-worker.md#onmessage9)方法接收Worker线程发送过来的消息,并通过调用[postMessage()](../reference/apis/js-apis-worker.md#postmessage9)方法向Worker线程发送消息。 例如向Worker线程发送训练和预测的消息,同时接收Worker线程发送回来的消息。 - - ```js - // 接收Worker子线程的结果 - workerInstance.onmessage = function(e) { + ```ts + import worker from '@ohos.worker'; + + const workerInstance: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/MyWorker.ts'); + + // 接收Worker子线程的结果 + workerInstance.onmessage = (() => { console.info('MyWorker.ts onmessage'); // 在Worker线程中进行耗时操作 - } - - workerInstance.onerror = function (d) { + }) + + workerInstance.onerror = (() => { // 接收Worker子线程的错误信息 - } + }) + + // 向Worker子线程发送训练消息 + workerInstance.postMessage({ 'type': 0 }); + // 向Worker子线程发送预测消息 + workerInstance.postMessage({ 'type': 1, 'value': [90, 5] }); + ``` - // 向Worker子线程发送训练消息 - workerInstance.postMessage({ 'type': 0 }); - // 向Worker子线程发送预测消息 - workerInstance.postMessage({ 'type': 1, 'value': [90, 5] }); - ``` 4. 在MyWorker.ts文件中绑定Worker对象,当前线程为Worker线程。 - ```js + ```ts import worker, { ThreadWorkerGlobalScope, MessageEvents, ErrorEvent } from '@ohos.worker'; let workerPort: ThreadWorkerGlobalScope = worker.workerPort; ``` 5. 在Worker线程中通过调用[onmessage()](../reference/apis/js-apis-worker.md#onmessage9-1)方法接收宿主线程发送的消息内容,并通过调用[postMessage()](../reference/apis/js-apis-worker.md#postmessage9-2)方法向宿主线程发送消息。 - 例如在Worker线程中定义预测模型及其训练过程,同时与主线程进行信息交互。 - - - ```js - import worker, { ThreadWorkerGlobalScope, MessageEvents, ErrorEvent } from '@ohos.worker'; - - let workerPort: ThreadWorkerGlobalScope = worker.workerPort; - - // 定义训练模型及结果 - let result; - - // 定义预测函数 - function predict(x) { + 例如在Worker线程中定义预测模型及其训练过程,同时与主线程进行信息交互。 + + ```ts + import worker, { ThreadWorkerGlobalScope, MessageEvents, ErrorEvent } from '@ohos.worker'; + let workerPort: ThreadWorkerGlobalScope = worker.workerPort; + // 定义训练模型及结果 + let result: Array; + // 定义预测函数 + function predict(x: number): number { return result[x]; - } - - // 定义优化器训练过程 - function optimize() { - result = {}; - } - - // Worker线程的onmessage逻辑 - workerPort.onmessage = (e: MessageEvents): void => { + } + // 定义优化器训练过程 + function optimize(): void { + result = []; + } + // Worker线程的onmessage逻辑 + workerPort.onmessage = (e: MessageEvents): void => { // 根据传输的数据的type选择进行操作 - switch (e.data.type) { - case 0: - // 进行训练 - optimize(); - // 训练之后发送主线程训练成功的消息 - workerPort.postMessage({ type: 'message', value: 'train success.' }); - break; - case 1: - // 执行预测 - const output = predict(e.data.value); - // 发送主线程预测的结果 - workerPort.postMessage({ type: 'predict', value: output }); - break; - default: - workerPort.postMessage({ type: 'message', value: 'send message is invalid' }); - break; + switch (e.data.type as number) { + case 0: + // 进行训练 + optimize(); + // 训练之后发送主线程训练成功的消息 + workerPort.postMessage({ type: 'message', value: 'train success.' }); + break; + case 1: + // 执行预测 + const output: number = predict(e.data.value as number); + // 发送主线程预测的结果 + workerPort.postMessage({ type: 'predict', value: output }); + break; + default: + workerPort.postMessage({ type: 'message', value: 'send message is invalid' }); + break; } - } - ``` + } + ``` 6. 在Worker线程中完成任务之后,执行Worker线程销毁操作。销毁线程的方式主要有两种:根据需要可以在宿主线程中对Worker线程进行销毁;也可以在Worker线程中主动销毁Worker线程。 - 在宿主线程中通过调用[onexit()](../reference/apis/js-apis-worker.md#onexit9)方法定义Worker线程销毁后的处理逻辑。 + 在宿主线程中通过调用[onexit()](../reference/apis/js-apis-worker.md#onexit9)方法定义Worker线程销毁后的处理逻辑。 - ```js - // Worker线程销毁后,执行onexit回调方法 - workerInstance.onexit = function() { + ```ts + // Worker线程销毁后,执行onexit回调方法 + workerInstance.onexit = (): void => { console.info("main thread terminate"); - } - ``` - - 方式一:在宿主线程中通过调用[terminate()](../reference/apis/js-apis-worker.md#terminate9)方法销毁Worker线程,并终止Worker接收消息。 - - ```js - // 销毁Worker线程 - workerInstance.terminate(); - ``` - - 方式二:在Worker线程中通过调用[close()](../reference/apis/js-apis-worker.md#close9)方法主动销毁Worker线程,并终止Worker接收消息。 - - ```js - // 销毁线程 - workerPort.close(); - ``` + } + ``` + + 方式一:在宿主线程中通过调用[terminate()](../reference/apis/js-apis-worker.md#terminate9)方法销毁Worker线程,并终止Worker接收息。 + + ```ts + // 销毁Worker线程 + workerInstance.terminate(); + ``` + + 方式二:在Worker线程中通过调用[close()](../reference/apis/js-apis-worker.md#close9)方法主动销毁Worker线程,并终止Worker接收消息。 + + ```ts + // 销毁线程 + workerPort.close(); + ``` \ No newline at end of file diff --git a/zh-cn/application-dev/arkts-utils/io-intensive-task-development.md b/zh-cn/application-dev/arkts-utils/io-intensive-task-development.md index 1a29cc3e008f82e62df89809d981980a5d8c426f..10f0a6ef0351296d2944ee82caac0ba4f5141808 100644 --- a/zh-cn/application-dev/arkts-utils/io-intensive-task-development.md +++ b/zh-cn/application-dev/arkts-utils/io-intensive-task-development.md @@ -8,46 +8,49 @@ I/O密集型任务的性能重点通常不在于CPU的处理能力,而在于I/ 1. 定义并发函数,内部密集调用I/O能力。 - - ```ts - import fs from '@ohos.file.fs'; - import { BusinessError } from '@ohos.base'; - - // 定义并发函数,内部密集调用I/O能力 - // 写入文件的实现 - async function write(data: string, filePath: string): Promise { - let file: fs.File = await fs.open(filePath, fs.OpenMode.READ_WRITE); - await fs.write(file.fd, data); - fs.close(file); - } - - @Concurrent - async function concurrentTest(fileList: string[]): Promise { - // 循环写文件操作 - for (let i: number = 0; i < fileList.length; i++) { - write('Hello World!', fileList[i]).then(() => { - console.info(`Succeeded in writing the file. FileList: ${fileList[i]}`); - }).catch((err: BusinessError) => { - console.error(`Failed to write the file. Code is ${err.code}, message is ${err.message}`) - return false; - }) + ```ts + // a.ts + import fs from '@ohos.file.fs'; + + // 定义并发函数,内部密集调用I/O能力 + // 写入文件的实现 + export async function write(data: string, filePath: string): Promise { + let file: fs.File = await fs.open(filePath, fs.OpenMode.READ_WRITE); + await fs.write(file.fd, data); + fs.close(file); + } + ``` + + ```ts + import { write } from './a' + import { BusinessError } from '@ohos.base'; + + @Concurrent + async function concurrentTest(fileList: string[]): Promise { + // 循环写文件操作 + for (let i: number = 0; i < fileList.length; i++) { + write('Hello World!', fileList[i]).then(() => { + console.info(`Succeeded in writing the file. FileList: ${fileList[i]}`); + }).catch((err: BusinessError) => { + console.error(`Failed to write the file. Code is ${err.code}, message is ${err.message}`) + return false; + }) + } + return true; } - return true; - } - ``` + ``` 2. 使用TaskPool执行包含密集I/O的并发函数:通过调用[execute()](../reference/apis/js-apis-taskpool.md#taskpoolexecute)方法执行任务,并在回调中进行调度结果处理。示例中的filePath1和filePath2的获取方式请参见[获取应用文件路径](../application-models/application-context-stage.md#获取应用文件路径)。 - ```ts - import taskpool from '@ohos.taskpool'; - - let filePath1: string = ...; // 应用文件路径 - let filePath2: string = ...; - - // 使用TaskPool执行包含密集I/O的并发函数 - // 数组较大时,I/O密集型任务任务分发也会抢占主线程,需要使用多线程能力 - taskpool.execute(concurrentTest, [filePath1, filePath2]).then(() => { - // 调度结果处理 - console.info(`The result: ${ret}`); - }) - ``` + ```ts + import taskpool from '@ohos.taskpool'; + + let filePath1: string = "path1"; // 应用文件路径 + let filePath2: string = "path2"; + + // 使用TaskPool执行包含密集I/O的并发函数 + // 数组较大时,I/O密集型任务任务分发也会抢占主线程,需要使用多线程能力 + taskpool.execute(concurrentTest, [filePath1, filePath2]).then(() => { + // 调度结果处理 + }) + ``` diff --git a/zh-cn/application-dev/arkts-utils/linear-container.md b/zh-cn/application-dev/arkts-utils/linear-container.md index 088b6c7272ff42d1e2a5c345a1e6edb8d4f223a4..7491babe88177aec71d3400f37b8feab0d38e1c9 100644 --- a/zh-cn/application-dev/arkts-utils/linear-container.md +++ b/zh-cn/application-dev/arkts-utils/linear-container.md @@ -198,7 +198,7 @@ Stack进行增、删、改、查操作的常用API如下: 此处列举常用的线性容器ArrayList、Vector、Deque、Stack、List的使用示例,包括导入模块、增加元素、访问元素及修改等操作。示例代码如下所示: -```js +```ts // ArrayList import ArrayList from '@ohos.util.ArrayList'; // 导入ArrayList模块 diff --git a/zh-cn/application-dev/arkts-utils/multi-thread-concurrency-overview.md b/zh-cn/application-dev/arkts-utils/multi-thread-concurrency-overview.md index 31271ee693b9b8314bb15612c09953dfb14a6123..5e33544e5df3064615e7a5fe3f98f3821a911964 100644 --- a/zh-cn/application-dev/arkts-utils/multi-thread-concurrency-overview.md +++ b/zh-cn/application-dev/arkts-utils/multi-thread-concurrency-overview.md @@ -27,7 +27,7 @@ Actor并发模型作为基于消息通信并发模型的典型代表,不需要 可转移对象(Transferable object)传输采用地址转移进行序列化,不需要内容拷贝,会将ArrayBuffer的所有权转移给接收该ArrayBuffer的线程,转移后该ArrayBuffer在发送它的线程中变为不可用,不允许再访问。 -```js +```ts // 定义可转移对象 let buffer: ArrayBuffer = new ArrayBuffer(100); ``` @@ -42,7 +42,7 @@ let buffer: ArrayBuffer = new ArrayBuffer(100); SharedArrayBuffer对象存储的数据在同时被修改时,需要通过原子操作保证其同步性,即下个操作开始之前务必需要等到上个操作已经结束。 -```js +```ts // 定义可共享对象,可以使用Atomics进行操作 let sharedBuffer: SharedArrayBuffer = new SharedArrayBuffer(1024); ``` diff --git a/zh-cn/application-dev/arkts-utils/nonlinear-container.md b/zh-cn/application-dev/arkts-utils/nonlinear-container.md index 0b35b767bfc04b89746bfb32bb1057f4b93844d3..098b1d79ae0a61d213d797453a2076e82d5862bc 100644 --- a/zh-cn/application-dev/arkts-utils/nonlinear-container.md +++ b/zh-cn/application-dev/arkts-utils/nonlinear-container.md @@ -212,7 +212,7 @@ PlainArray进行增、删、改、查操作的常用API如下: 此处列举常用的非线性容器HashMap、TreeMap、LightWeightMap、PlainArray的使用示例,包括导入模块、增加元素、访问元素及修改等操作,示例代码如下所示: -```js +```ts // HashMap import HashMap from '@ohos.util.HashMap'; // 导入HashMap模块 diff --git a/zh-cn/application-dev/arkts-utils/single-io-development.md b/zh-cn/application-dev/arkts-utils/single-io-development.md index 6b551373ead8957fd162150b6e28be6a185feee7..533fd02d80336bc16e69e2aebbc824029cd0add6 100644 --- a/zh-cn/application-dev/arkts-utils/single-io-development.md +++ b/zh-cn/application-dev/arkts-utils/single-io-development.md @@ -6,25 +6,23 @@ Promise和async/await提供异步并发能力,适用于单次I/O任务的场 1. 实现单次I/O任务逻辑。 - ```js - import fs from '@ohos.file.fs'; - import { BusinessError } from '@ohos.base'; - - async function write(data: string, filePath: string): Promise { - let file: fs.File = await fs.open(filePath, fs.OpenMode.READ_WRITE); - fs.write(file.fd, data).then((writeLen: number) => { - fs.close(file); - }).catch((err: BusinessError) => { - console.error(`Failed to write data. Code is ${err.code}, message is ${err.message}`); - }) - } - ``` - + ```ts + import fs from '@ohos.file.fs'; + import { BusinessError } from '@ohos.base'; + async function write(data: string, filePath: string): Promise { + let file: fs.File = await fs.open(filePath, fs.OpenMode.READ_WRITE); + fs.write(file.fd, data).then((writeLen: number) => { + fs.close(file); + }).catch((err: BusinessError) => { + console.error(`Failed to write data. Code is ${err.code}, message is ${err.message}`); + }) + } + ``` 2. 采用异步能力调用单次I/O任务。示例中的filePath的获取方式请参见[获取应用文件路径](../application-models/application-context-stage.md#获取应用文件路径)。 - ```js - let filePath: string = ...; // 应用文件路径 - write('Hello World!', filePath).then(() => { - console.info('Succeeded in writing data.'); - }) - ``` + ```ts + let filePath: string = "path"; // 应用文件路径 + write('Hello World!', filePath).then(() => { + console.info('Succeeded in writing data.'); + }) + ``` diff --git a/zh-cn/application-dev/arkts-utils/sync-task-development.md b/zh-cn/application-dev/arkts-utils/sync-task-development.md index 6fbb549708694a312d6b349c80051a8dfc9a04f6..72b28a43253eea2e431f6d1e129e425361b05809 100644 --- a/zh-cn/application-dev/arkts-utils/sync-task-development.md +++ b/zh-cn/application-dev/arkts-utils/sync-task-development.md @@ -39,6 +39,7 @@ export default class Handle { } ``` + 业务使用TaskPool调用相关同步方法的代码。 @@ -52,8 +53,6 @@ import Handle from './Handle'; // 返回静态句柄 function func(num: number): boolean { // 调用静态类对象中实现的同步等待调用 Handle.syncSet(num); - // 或者调用单例对象中实现的同步等待调用 - Handle.getInstance().syncGet(); return true; } @@ -95,75 +94,76 @@ struct Index { 1. 在主线程中创建Worker对象,同时接收Worker线程发送回来的消息。 - ```js - import worker from '@ohos.worker'; - - @Entry - @Component - struct Index { - @State message: string = 'Hello World'; - - build() { - Row() { - Column() { - Text(this.message) - .fontSize(50) - .fontWeight(FontWeight.Bold) - .onClick(() => { - let w: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/MyWorker.ts'); - w.onmessage = function (d) { - // 接收Worker子线程的结果 - } - w.onerror = function (d) { - // 接收Worker子线程的错误信息 - } - // 向Worker子线程发送Set消息 - w.postMessage({'type': 0, 'data': 'data'}) - // 向Worker子线程发送Get消息 - w.postMessage({'type': 1}) - // 销毁线程 - w.terminate() - }) - } - .width('100%') - } - .height('100%') - } - } - ``` + ```ts + import worker from '@ohos.worker'; + + @Entry + @Component + struct Index { + @State message: string = 'Hello World'; + + build() { + Row() { + Column() { + Text(this.message) + .fontSize(50) + .fontWeight(FontWeight.Bold) + .onClick(() => { + let w: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/MyWorker.ts'); + w.onmessage = () => { + // 接收Worker子线程的结果 + } + w.onerror = () => { + // 接收Worker子线程的错误信息 + } + // 向Worker子线程发送Set消息 + w.postMessage({'type': 0, 'data': 'data'}) + // 向Worker子线程发送Get消息 + w.postMessage({'type': 1}) + // 销毁线程 + w.terminate() + }) + } + .width('100%') + } + .height('100%') + } + } + ``` -2. 在Worker线程中绑定Worker对象,同时处理同步任务逻辑。 - ```js - // handle.ts代码 - export default class Handle { - syncGet() { - return; - } +2. 在Worker线程中绑定Worker对象,同时处理同步任务逻辑。 - syncSet(num: number) { - return; - } - } - - // Worker.ts代码 - import worker, { ThreadWorkerGlobalScope, MessageEvents } from '@ohos.worker'; - import Handle from './handle.ts' // 返回句柄 - - var workerPort : ThreadWorkerGlobalScope = worker.workerPort; - - // 无法传输的句柄,所有操作依赖此句柄 - var handler = new Handle() - - // Worker线程的onmessage逻辑 - workerPort.onmessage = function(e : MessageEvents) { - switch (e.data.type) { - case 0: - handler.syncSet(e.data.data); - workerPort.postMessage('success set'); - case 1: - handler.syncGet(); - workerPort.postMessage('success get'); + ```ts + // handle.ts代码 + export default class Handle { + syncGet() { + return; + } + + syncSet(num: number) { + return; + } + } + + // Worker.ts代码 + import worker, { ThreadWorkerGlobalScope, MessageEvents } from '@ohos.worker'; + import Handle from './handle.ts' // 返回句柄 + + var workerPort : ThreadWorkerGlobalScope = worker.workerPort; + + // 无法传输的句柄,所有操作依赖此句柄 + var handler = new Handle() + + // Worker线程的onmessage逻辑 + workerPort.onmessage = (e : MessageEvents): void => { + switch (e.data.type as number) { + case 0: + handler.syncSet(e.data.data); + workerPort.postMessage('success set'); + case 1: + handler.syncGet(); + workerPort.postMessage('success get'); } - } - ``` + } + ``` diff --git a/zh-cn/application-dev/arkts-utils/taskpool-vs-worker.md b/zh-cn/application-dev/arkts-utils/taskpool-vs-worker.md index a4f0cd4d8dcdfb711dfda59dcdd9a814a4ef5abd..ece6fcee2057df515ccfed5d606609808de215cf 100644 --- a/zh-cn/application-dev/arkts-utils/taskpool-vs-worker.md +++ b/zh-cn/application-dev/arkts-utils/taskpool-vs-worker.md @@ -100,23 +100,21 @@ TaskPool支持开发者在主线程封装任务抛给任务队列,系统选择 当使用Worker模块具体功能时,均需先构造Worker实例对象,其构造函数与API版本相关。 -```js +```ts // API 9及之后版本使用: -const worker1: worker.ThreadWorker = new worker.ThreadWorker(scriptURL); +const worker1: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/MyWorker.ts'); // API 8及之前版本使用: -const worker1: worker.ThreadWorker = new worker.Worker(scriptURL); +const worker2: worker.Worker = new worker.Worker('entry/ets/workers/MyWorker.ts'); ``` 构造函数需要传入Worker的路径(scriptURL),Worker文件存放位置默认路径为Worker文件所在目录与pages目录属于同级。 **Stage模型** - 构造函数中的scriptURL示例如下: - -```js +```ts // 写法一 // Stage模型-目录同级(entry模块下,workers目录与pages目录同级) const worker1: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/MyWorker.ts', {name:"first worker in Stage model"}); @@ -149,7 +147,7 @@ const worker4: worker.ThreadWorker = new worker.ThreadWorker('@bundle:com.exampl 构造函数中的scriptURL示例如下: -```js +```ts // FA模型-目录同级(entry模块下,workers目录与pages目录同级) const worker1: worker.ThreadWorker = new worker.ThreadWorker('workers/worker.js', {name:'first worker in FA model'}); // FA模型-目录不同级(entry模块下,workers目录与pages目录的父目录同级) diff --git a/zh-cn/application-dev/arkts-utils/xml-conversion.md b/zh-cn/application-dev/arkts-utils/xml-conversion.md index 100d5112be1a49659fd1a0ca85633922100637f7..789ab6dad59254831792bf1624f37ed5fb916c0f 100644 --- a/zh-cn/application-dev/arkts-utils/xml-conversion.md +++ b/zh-cn/application-dev/arkts-utils/xml-conversion.md @@ -18,15 +18,15 @@ XML解析及转换需要确保传入的XML数据符合标准格式。 1. 引入模块。 - ```js + ```ts import convertxml from '@ohos.convertxml'; ``` 2. 输入待转换的XML,设置转换选项。 - ```js + ```ts let xml: string = - '' + + '' + '' + ' Happy' + ' Work' + @@ -62,7 +62,7 @@ XML解析及转换需要确保传入的XML数据符合标准格式。 3. 调用转换函数,打印结果。 - ```js + ```ts let conv: convertxml.ConvertXML = new convertxml.ConvertXML(); let result: object = conv.convertToJSObject(xml, options); let strRes: string = JSON.stringify(result); // 将js对象转换为json字符串,用于显式输出 @@ -71,7 +71,6 @@ XML解析及转换需要确保传入的XML数据符合标准格式。 输出结果如下所示: - ```js strRes: {"_declaration":{"_attributes":{"version":"1.0","encoding":"utf-8"}},"_elements":[{"_type":"element","_name":"note", diff --git a/zh-cn/application-dev/arkts-utils/xml-generation.md b/zh-cn/application-dev/arkts-utils/xml-generation.md index 60edf5c6d3681f09547c7676bb526349c13b1488..afe0deca6abdcb9eaa4f2fe7de9b9baeacbac6fd 100644 --- a/zh-cn/application-dev/arkts-utils/xml-generation.md +++ b/zh-cn/application-dev/arkts-utils/xml-generation.md @@ -24,14 +24,14 @@ XML模块的API接口可以参考[@ohos.xml](../reference/apis/js-apis-xml.md) 1. 引入模块。 - ```js + ```ts import xml from '@ohos.xml'; import util from '@ohos.util'; ``` 2. 创建缓冲区,构造XmlSerializer对象(可以基于Arraybuffer构造XmlSerializer对象, 也可以基于DataView构造XmlSerializer对象)。 - ```js + ```ts // 1.基于Arraybuffer构造XmlSerializer对象 let arrayBuffer: ArrayBuffer = new ArrayBuffer(2048); // 创建一个2048字节的缓冲区 let thatSer: xml.XmlSerializer = new xml.XmlSerializer(arrayBuffer); // 基于Arraybuffer构造XmlSerializer对象 @@ -44,7 +44,7 @@ XML模块的API接口可以参考[@ohos.xml](../reference/apis/js-apis-xml.md) 3. 调用XML元素生成函数。 - ```js + ```ts thatSer.setDeclaration(); // 写入xml的声明 thatSer.startElement('bookstore'); // 写入元素开始标记 thatSer.startElement('book'); // 嵌套元素开始标记 @@ -65,7 +65,7 @@ XML模块的API接口可以参考[@ohos.xml](../reference/apis/js-apis-xml.md) 4. 使用Uint8Array操作Arraybuffer,调用TextDecoder对Uint8Array解码后输出。 - ```js + ```ts let view: Uint8Array = new Uint8Array(arrayBuffer); // 使用Uint8Array读取arrayBuffer的数据 let textDecoder: util.TextDecoder = util.TextDecoder.create(); // 调用util模块的TextDecoder类 let res: string = textDecoder.decodeWithStream(view); // 对view解码 @@ -74,7 +74,6 @@ XML模块的API接口可以参考[@ohos.xml](../reference/apis/js-apis-xml.md) 输出结果如下: - - ```js + ``` \r\n \r\n Everyday\r\n Giada\r\n 2005\r\n \r\n ``` diff --git a/zh-cn/application-dev/arkts-utils/xml-parsing.md b/zh-cn/application-dev/arkts-utils/xml-parsing.md index 5df577246c928a0896f3062d961c46330e3d7945..bff61b63f8be6b947e8f84dc109f9215ba510d01 100644 --- a/zh-cn/application-dev/arkts-utils/xml-parsing.md +++ b/zh-cn/application-dev/arkts-utils/xml-parsing.md @@ -29,111 +29,109 @@ XML模块提供XmlPullParser类对XML文件解析,输入为含有XML文本的A 1. 引入模块。 - ```js - import xml from '@ohos.xml'; - import util from '@ohos.util'; // 需要使用util模块函数对文件编码 - ``` + ```ts + import xml from '@ohos.xml'; + import util from '@ohos.util'; // 需要使用util模块函数对文件编码 + ``` 2. 对XML文件编码后调用XmlPullParser。 可以基于ArrayBuffer构造XmlPullParser对象, 也可以基于DataView构造XmlPullParser对象。 - - ```js - let strXml: string = - '' + - '' + - 'Play' + - 'Work' + - ''; - let textEncoder: util.TextEncoder = new util.TextEncoder(); - let arrBuffer: Uint8Array = textEncoder.encodeInto(strXml); // 对数据编码,防止包含中文字符乱码 - // 1.基于ArrayBuffer构造XmlPullParser对象 - let that: xml.XmlPullParser = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8'); - - // 2.基于DataView构造XmlPullParser对象 - let dataView: DataView = new DataView(arrBuffer.buffer); - let that: xml.XmlPullParser = new xml.XmlPullParser(dataView, 'UTF-8'); - ``` + ```ts + let strXml: string = + '' + + '' + + 'Play' + + 'Work' + + ''; + let textEncoder: util.TextEncoder = new util.TextEncoder(); + let arrBuffer: Uint8Array = textEncoder.encodeInto(strXml); // 对数据编码,防止包含中文字符乱码 + // 1.基于ArrayBuffer构造XmlPullParser对象 + let that: xml.XmlPullParser = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8'); + + // 2.基于DataView构造XmlPullParser对象 + let dataView: DataView = new DataView(arrBuffer.buffer); + let that: xml.XmlPullParser = new xml.XmlPullParser(dataView, 'UTF-8'); + ``` 3. 自定义回调函数,本例直接打印出标签及标签值。 - ```js - let str: string = ''; - function func(name: string, value: string): boolean { - str = name + value; - console.info(str); - return true; //true:继续解析 false:停止解析 - } - ``` + ```ts + let str: string = ''; + function func(name: string, value: string): boolean { + str = name + value; + console.info(str); + return true; //true:继续解析 false:停止解析 + } + ``` 4. 设置解析选项,调用parse函数。 - ```js - let options: xml.ParseOptions = {supportDoctype:true, ignoreNameSpace:true, tagValueCallbackFunction:func}; - that.parse(options); - ``` + ```ts + let options: xml.ParseOptions = {supportDoctype:true, ignoreNameSpace:true, tagValueCallbackFunction:func}; + that.parse(options); + ``` - 输出结果如下所示: + 输出结果如下所示: + + ``` + note + title + Play + title + lens + Work + lens + note + ``` - ```js - note - title - Play - title - lens - Work - lens - note - ``` ## 解析XML属性和属性值 1. 引入模块。 - ```js - import xml from '@ohos.xml'; - import util from '@ohos.util'; // 需要使用util模块函数对文件编码 - ``` + ```ts + import xml from '@ohos.xml'; + import util from '@ohos.util'; // 需要使用util模块函数对文件编码 + ``` 2. 对XML文件编码后调用XmlPullParser。 - ```js - let strXml: string = - '' + - '' + - ' Play' + - ' Happy' + - ' Work' + - ''; - let textEncoder: util.TextEncoder = new util.TextEncoder(); - let arrBuffer: Uint8Array = textEncoder.encodeInto(strXml); // 对数据编码,防止包含中文字符乱码 - let that: xml.XmlPullParser = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8'); - ``` + ```ts + let strXml: string = + '' + + '' + + ' Play' + + ' Happy' + + ' Work' + + ''; + let textEncoder: util.TextEncoder = new util.TextEncoder(); + let arrBuffer: Uint8Array = textEncoder.encodeInto(strXml); // 对数据编码,防止包含中文字符乱码 + let that: xml.XmlPullParser = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8'); + ``` 3. 自定义回调函数,本例直接打印出属性及属性值。 - ```js - let str: string = ''; - function func(name: string, value: string): boolean { - str += name + ' ' + value + ' '; - return true; // true:继续解析 false:停止解析 - } - ``` + ```ts + let str: string = ''; + function func(name: string, value: string): boolean { + str += name + ' ' + value + ' '; + return true; // true:继续解析 false:停止解析 + } + ``` 4. 设置解析选项,调用parse函数。 - ```js - let options: xml.ParseOptions = {supportDoctype:true, ignoreNameSpace:true, attributeValueCallbackFunction:func}; - that.parse(options); - console.info(str); // 一次打印出所有的属性及其值 - ``` + ```ts + let options: xml.ParseOptions = {supportDoctype:true, ignoreNameSpace:true, attributeValueCallbackFunction:func}; + that.parse(options); + console.info(str); // 一次打印出所有的属性及其值 + ``` 输出结果如下所示: - - - ```js + ``` importance high logged true // note节点的属性及属性值 ``` @@ -142,54 +140,55 @@ XML模块提供XmlPullParser类对XML文件解析,输入为含有XML文本的A 1. 引入模块。 - ```js - import xml from '@ohos.xml'; - import util from '@ohos.util'; // 需要使用util模块函数对文件编码 - ``` + ```ts + import xml from '@ohos.xml'; + import util from '@ohos.util'; // 需要使用util模块函数对文件编码 + ``` 2. 对XML文件编码后调用XmlPullParser。 - ```js - let strXml: string = - '' + - '' + - 'Play' + - ''; - let textEncoder: util.TextEncoder = new util.TextEncoder(); - let arrBuffer: Uint8Array = textEncoder.encodeInto(strXml); // 对数据编码,防止包含中文字符乱码 - let that: xml.XmlPullParser = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8'); - ``` + ```ts + let strXml: string = + '' + + '' + + 'Play' + + ''; + let textEncoder: util.TextEncoder = new util.TextEncoder(); + let arrBuffer: Uint8Array = textEncoder.encodeInto(strXml); // 对数据编码,防止包含中文字符乱码 + let that: xml.XmlPullParser = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8'); + ``` 3. 自定义回调函数,本例直接打印元素事件类型及元素深度。 - ```js - let str: string = ''; - function func(name: string, value: xml.ParseInfo): boolean { - str = name + ' ' + value.getDepth(); // getDepth 获取元素的当前深度 - console.info(str) - return true; //true:继续解析 false:停止解析 - } - ``` + ```ts + let str: string = ''; + function func(name: xml.EventType, value: xml.ParseInfo): boolean { + str = name + ' ' + value.getDepth(); // getDepth 获取元素的当前深度 + console.info(str) + return true; //true:继续解析 false:停止解析 + } + ``` 4. 设置解析选项,调用parse函数。 - ```js - let options: xml.ParseOptions = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func}; - that.parse(options); - ``` + ```ts + let options: xml.ParseOptions = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func}; + that.parse(options); + ``` 输出结果如下所示: + ``` + 0 0 // 0: 对应事件类型 START_DOCUMENT值为0 0:起始深度为0 + 2 1 // 2: 对应事件类型START_TAG值为2 1:深度为1 + 2 2 // 2:对应事件类型START_TAG值为2 2:深度为2 + 4 2 // 4:Play对应事件类型TEXT值为4 2:深度为2 + 3 2 // 3:对应事件类型END_TAG值为3 2:深度为2 + 3 1 // 3:对应事件类型END_TAG值为3 1:深度为1(与) + 1 0 // 1:对应事件类型END_DOCUMENT值为1 0:深度为0 + ``` + - ```js - 0 0 // 0: 对应事件类型START_DOCUMENT值为0 0:起始深度为0 - 2 1 // 2: 对应事件类型START_TAG值为2 1:深度为1 - 2 2 // 2:对应事件类型START_TAG值为2 2:深度为2 - 4 2 // 4:Play对应事件类型TEXT值为4 2:深度为2 - 3 2 // 3:对应事件类型END_TAG值为3 2:深度为2 - 3 1 // 3:对应事件类型END_TAG值为3 1:深度为1(与) - 1 0 // 1:对应事件类型END_DOCUMENT值为1 0:深度为0 - ``` ## 场景示例 @@ -197,7 +196,7 @@ XML模块提供XmlPullParser类对XML文件解析,输入为含有XML文本的A 此处以调用所有解析选项为例,提供解析XML标签、属性和事件类型的开发示例。 -```js +```ts import xml from '@ohos.xml'; import util from '@ohos.util'; @@ -218,13 +217,13 @@ function tagFunc(name: string, value: string): boolean { return true; } -function attFunc(name: string, value: string): boolean { +function attFunc(name: xml.EventType, value: string): boolean { str = name + ' ' + value; console.info('attri-' + str); return true; } -function tokenFunc(name: string, value: xml.ParseInfo): boolean { +function tokenFunc(name: xml.EventType, value: xml.ParseInfo): boolean { str = name + ' ' + value.getDepth(); console.info('token-' + str); return true; @@ -238,33 +237,31 @@ let options: xml.ParseOptions = { tokenValueCallbackFunction: tokenFunc }; that.parse(options); - ``` 输出结果如下所示: - -```js -tag- -token-0 0 -tag-book -attri-category COOKING -token-2 1 -tag-title -attri-lang en -token-2 2 -tag-Everyday -token-4 2 -tag-title -token-3 2 -tag-author -token-2 2 -tag-Giada -token-4 2 -tag-author -token-3 2 -tag-book -token-3 1 -tag- -token-1 0 -``` + ``` + tag- + token-0 0 + tag-book + attri-category COOKING + token-2 1 + tag-title + attri-lang en + token-2 2 + tag-Everyday + token-4 2 + tag-title + token-3 2 + tag-author + token-2 2 + tag-Giada + token-4 2 + tag-author + token-3 2 + tag-book + token-3 1 + tag- + token-1 0 + ``` diff --git a/zh-cn/application-dev/database/data-persistence-by-preferences.md b/zh-cn/application-dev/database/data-persistence-by-preferences.md index c5a6f64a0c47e540aa14b3ca85f04d106db1ef7e..92404f30ca3d461456a516394946455d48f870e8 100644 --- a/zh-cn/application-dev/database/data-persistence-by-preferences.md +++ b/zh-cn/application-dev/database/data-persistence-by-preferences.md @@ -47,7 +47,7 @@ 1. 导入`@ohos.data.preferences`模块。 - ```js + ```ts import dataPreferences from '@ohos.data.preferences'; ``` @@ -56,7 +56,7 @@ Stage模型示例: - ```js + ```ts import UIAbility from '@ohos.app.ability.UIAbility'; import { BusinessError } from '@ohos.base'; import window from '@ohos.window'; @@ -73,7 +73,9 @@ // 请确保获取到Preferences实例后,再进行相关数据操作 }) } catch (err) { - console.error(`Failed to get preferences. Code:${err.code},message:${err.message}`); + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`Failed to get preferences. Code:${code},message:${message}`); } } } @@ -82,7 +84,7 @@ FA模型示例: - ```js + ```ts import featureAbility from '@ohos.ability.featureAbility'; import { BusinessError } from '@ohos.base'; @@ -99,7 +101,9 @@ // 请确保获取到Preferences实例后,再进行相关数据操作 }) } catch (err) { - console.error(`Failed to get preferences. Code is ${err.code},message:${err.message}`); + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`Failed to get preferences. Code is ${code},message:${message}`); } ``` @@ -114,7 +118,7 @@ 示例代码如下所示: - ```js + ```ts try { if (preferences.hasSync('startup')) { console.info("The key 'startup' is contained."); @@ -124,7 +128,9 @@ preferences.putSync('startup', 'auto'); } } catch (err) { - console.error(`Failed to check the key 'startup'. Code:${err.code}, message:${err.message}`); + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`Failed to check the key 'startup'. Code:${code}, message:${message}`); } ``` @@ -132,12 +138,14 @@ 使用getSync()方法获取数据,即指定键对应的值。如果值为null或者非默认值类型,则返回默认数据。示例代码如下所示: - ```js + ```ts try { let val = preferences.getSync('startup', 'default'); console.info(`Succeeded in getting value of 'startup'. val: ${val}.`); } catch (err) { - console.error(`Failed to get value of 'startup'. Code:${err.code}, message:${err.message}`); + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`Failed to get value of 'startup'. Code:${code}, message:${message}`); } ``` @@ -146,11 +154,13 @@ 使用deleteSync()方法删除指定键值对,示例代码如下所示: - ```js + ```ts try { preferences.deleteSync('startup'); } catch (err) { - console.error(`Failed to delete the key 'startup'. Code:${err.code}, message:${err.message}`); + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`Failed to delete the key 'startup'. Code:${code}, message:${message}`); } ``` @@ -158,7 +168,7 @@ 应用存入数据到Preferences实例后,可以使用flush()方法实现数据持久化。示例代码如下所示: - ```js + ```ts try { preferences.flush((err: BusinessError) => { if (err) { @@ -168,7 +178,9 @@ console.info('Succeeded in flushing.'); }) } catch (err) { - console.error(`Failed to flush. Code:${err.code}, message:${err.message}`); + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`Failed to flush. Code:${code}, message:${message}`); } ``` @@ -176,7 +188,7 @@ 应用订阅数据变更需要指定observer作为回调方法。订阅的Key值发生变更后,当执行flush()方法时,observer被触发回调。示例代码如下所示: - ```js + ```ts interface observer { key: string } @@ -213,7 +225,7 @@ 示例代码如下所示: - ```js + ```ts try { dataPreferences.deletePreferences(this.context, 'myStore', (err: BusinessError) => { if (err) { @@ -223,7 +235,9 @@ console.info('Succeeded in deleting preferences.'); }) } catch (err) { - console.error(`Failed to delete preferences. Code:${err.code}, message:${err.message}`); + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`Failed to delete preferences. Code:${code}, message:${message}`); } ``` diff --git a/zh-cn/application-dev/database/data-sync-of-distributed-data-object.md b/zh-cn/application-dev/database/data-sync-of-distributed-data-object.md index 8f3cca0be0fac2dc1ec8bb1e1d7738309c914d68..cc81d2ab8e00d0d6061bd2ebc9b531440aba907e 100644 --- a/zh-cn/application-dev/database/data-sync-of-distributed-data-object.md +++ b/zh-cn/application-dev/database/data-sync-of-distributed-data-object.md @@ -115,6 +115,7 @@ ## 接口说明 以下是分布式对象跨设备数据同步功能的相关接口,大部分为异步接口。异步接口均有callback和Promise两种返回形式,下表均以callback形式为例,更多接口及使用方式请见[分布式数据对象](../reference/apis/js-apis-data-distributedobject.md)。 +本模块接口仅支持在JS文件中使用。 | 接口名称 | 描述 | | -------- | -------- | @@ -151,26 +152,17 @@ // 导入模块 import distributedDataObject from '@ohos.data.distributedDataObject'; import UIAbility from '@ohos.app.ability.UIAbility'; - import { BusinessError } from '@ohos.base'; - import window from '@ohos.window'; - - interface sourceObject{ - name: string, - age: number, - isVis: boolean - parent: { [key: string]: string }, - list: { [key: string]: string }[] - } + class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage: window.WindowStage) { - let source: sourceObject = { + onWindowStageCreate(windowStage) { + // 创建对象,该对象包含4个属性类型:string、number、boolean和Object + let localObject = distributedDataObject.create(this.context, { name: 'jack', age: 18, isVis: false, parent: { mother: 'jack mom', father: 'jack Dad' }, list: [{ mother: 'jack mom' }, { father: 'jack Dad' }] - } - let localObject: distributedDataObject.DataObject = distributedDataObject.create(this.context, source); + }); } } ``` @@ -184,43 +176,34 @@ import featureAbility from '@ohos.ability.featureAbility'; // 获取context let context = featureAbility.getContext(); - interface sourceObject{ - name: string, - age: number, - isVis: boolean - parent: { [key: string]: string }, - list: { [key: string]: string }[] - } - let source: sourceObject = { + // 创建对象,该对象包含4个属性类型:string、number、boolean和Object + let localObject = distributedDataObject.create(context, { name: 'jack', age: 18, isVis: false, parent: { mother: 'jack mom', father: 'jack Dad' }, list: [{ mother: 'jack mom' }, { father: 'jack Dad' }] - } - // 创建对象,该对象包含4个属性类型:string、number、boolean和Object - let localObject: distributedDataObject.DataObject = distributedDataObject.create(context, source); + }); ``` 4. 加入同步组网。同步组网中的数据对象分为发起方和被拉起方。 ```js // 设备1加入sessionId - let sessionId: string = '123456'; + let sessionId = '123456'; localObject.setSessionId(sessionId); // 和设备1协同的设备2加入同一个session // 创建对象,该对象包含4个属性类型:string、number、boolean和Object - let remoteSource: sourceObject = { + let remoteObject = distributedDataObject.create(this.context, { name: undefined, age: undefined, // undefined表示数据来自对端 isVis: true, parent: undefined, list: undefined - } - let remoteObject: distributedDataObject.DataObject = distributedDataObject.create(this.context, remoteSource); + }); // 收到status上线后remoteObject同步数据,即name变成jack,age是18 remoteObject.setSessionId(sessionId); ``` @@ -228,19 +211,18 @@ 5. 监听对象数据变更。可监听对端数据的变更,以callback作为变更回调实例。 ```js - interface ChangeCallback { - sessionId: string, - fields: Array - } + function changeCallback(sessionId, changeData) { + console.info(`change: ${sessionId}`); - localObject.on("change", (changeData:ChangeCallback) => { - console.info("change" + changeData.sessionId); - if (changeData.fields != null && changeData.fields != undefined) { - for (let index: number = 0; index < changeData.fields.length; index++) { - console.info(`The element ${localObject[changeData.fields[index]]} changed.`); - } + if (changeData !== null && changeData !== undefined) { + changeData.forEach(element => { + console.info(`The element ${localObject[element]} changed.`); + }); } - }); + } + + // 发起方要在changeCallback里刷新界面,则需要将正确的this绑定给changeCallback + localObject.on("change", this.changeCallback.bind(this)); ``` 6. 修改对象属性,对象属性支持基本类型(数字类型、布尔类型、字符串类型)以及复杂类型(数组、基本类型嵌套等)。 @@ -275,14 +257,7 @@ ```js // 删除变更回调changeCallback - localObject.off('change',(changeData: ChangeCallback) => { - console.info("change" + changeData.sessionId); - if (changeData.fields != null && changeData.fields != undefined) { - for (let index: number = 0; index < changeData.fields.length; index++) { - console.info("changed !" + changeData.fields[index] + " " + g_object[changeData.fields[index]]); - } - } - }); + localObject.off('change', this.changeCallback); // 删除所有的变更回调 localObject.off('change'); ``` @@ -290,32 +265,27 @@ 9. 监听分布式数据对象的上下线。可以监听对端分布式数据对象的上下线。 ```js - interface onStatusCallback { - sessionId: string, - networkId: string, - status: 'online' | 'offline' + function statusCallback(sessionId, networkId, status) { + // 业务处理 } - localObject.on('status', (statusCallback: onStatusCallback) => { - console.info("status changed " + statusCallback.sessionId + " " + statusCallback.status + " " + statusCallback.networkId); - // 业务处理 - }); + localObject.on('status', this.statusCallback); ``` 10. 保存和撤回已保存的数据对象。 ```js // 保存数据对象,如果应用退出后组网内设备需要恢复对象数据时调用 - localObject.save("local").then((result: distributedDataObject.SaveSuccessResponse) => { + localObject.save('local').then((result) => { console.info(`Succeeded in saving. SessionId:${result.sessionId},version:${result.version},deviceId:${result.deviceId}`); - }).catch((err: BusinessError) => { + }).catch((err) => { console.error(`Failed to save. Code:${err.code},message:${err.message}`); }); // 撤回保存的数据对象 - localObject.revokeSave().then((result: distributedDataObject.RevokeSaveSuccessResponse) => { + localObject.revokeSave().then((result) => { console.info(`Succeeded in revokeSaving. Session:${result.sessionId}`); - }).catch((err: BusinessError) => { + }).catch((err) => { console.error(`Failed to revokeSave. Code:${err.code},message:${err.message}`); }); ``` @@ -323,16 +293,8 @@ 11. 删除监听分布式数据对象的上下线。可以指定删除监听的上下线回调;也可以不指定,这将会删除该分布式数据对象的所有上下线回调。 ```js - interface offStatusCallback { - sessionId: string, - deviceId: string, - status: 'online' | 'offline' - } // 删除上下线回调statusCallback - localObject.off('status', (statusCallback: offStatusCallback) => { - console.info("status changed " + statusCallback.sessionId + " " + statusCallback.status + " " + statusCallback.deviceId); - // 业务处理 - }); + localObject.off('status', this.statusCallback); // 删除所有的上下线回调 localObject.off('status'); ``` @@ -341,7 +303,7 @@ ```js localObject.setSessionId(() => { - console.info('leave all session.'); + console.info('leave all session.'); }); ``` diff --git a/zh-cn/application-dev/database/share-data-by-datashareextensionability.md b/zh-cn/application-dev/database/share-data-by-datashareextensionability.md index bda623ca8a2e402873f7727414d82128817b22e8..0a344286a5295e078d620acd500c5e13221b4be0 100644 --- a/zh-cn/application-dev/database/share-data-by-datashareextensionability.md +++ b/zh-cn/application-dev/database/share-data-by-datashareextensionability.md @@ -60,36 +60,34 @@ 3. 在DataShareExtAbility.ts文件中,导入 `@ohos.application.DataShareExtensionAbility`模块,开发者可根据应用需求选择性重写其业务实现。例如数据提供方只提供插入、删除和查询服务,则可只重写这些接口,并导入对应的基础依赖模块。 - ```js + ```ts import Extension from '@ohos.application.DataShareExtensionAbility'; - import rdb from '@ohos.data.relationalStore'; import dataSharePredicates from '@ohos.data.dataSharePredicates'; import relationalStore from '@ohos.data.relationalStore'; import Want from '@ohos.app.ability.Want'; + import { BusinessError } from '@ohos.base' ``` 4. 数据提供方的业务实现由开发者自定义。例如可以通过数据库、读写文件或访问网络等各方式实现数据提供方的数据存储。 - ```js + ```ts const DB_NAME = 'DB00.db'; const TBL_NAME = 'TBL00'; const DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " - + TBL_NAME - + ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, isStudent BOOLEAN, Binary BINARY)'; - + + TBL_NAME + + ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, isStudent BOOLEAN, Binary BINARY)'; + let rdbStore: relationalStore.RdbStore; let result: string; - + export default class DataShareExtAbility extends Extension { - private rdbStore_: relationalStore.RdbStore; - // 重写onCreate接口 onCreate(want: Want, callback: Function) { result = this.context.cacheDir + '/datashare.txt'; // 业务实现使用RDB - rdb.getRdbStore(this.context, { + relationalStore.getRdbStore(this.context, { name: DB_NAME, - securityLevel: rdb.SecurityLevel.S1 + securityLevel: relationalStore.SecurityLevel.S1 }, (err, data) => { rdbStore = data; rdbStore.executeSql(DDL_TBL_CREATE, [], (err) => { @@ -100,7 +98,7 @@ } }); } - + // 重写query接口 query(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array, callback: Function) { if (predicates === null || predicates === undefined) { @@ -116,7 +114,9 @@ } }); } catch (err) { - console.error(`Failed to query. Code:${err.code},message:${err.message}`); + let code = (err as BusinessError).code; + let message = (err as BusinessError).message + console.error(`Failed to query. Code:${code},message:${message}`); } } // 可根据应用需求,选择性重写各个接口 @@ -186,7 +186,7 @@ 1. 导入基础依赖包。 - ```js + ```ts import UIAbility from '@ohos.app.ability.UIAbility'; import dataShare from '@ohos.data.dataShare'; import dataSharePredicates from '@ohos.data.dataSharePredicates'; @@ -196,17 +196,17 @@ 2. 定义与数据提供方通信的URI字符串。 - ```js + ```ts // 作为参数传递的URI,与module.json5中定义的URI的区别是多了一个"/",是因为作为参数传递的URI中,在第二个与第三个"/"中间,存在一个DeviceID的参数 let dseUri = ('datashareproxy://com.samples.datasharetest.DataShare'); ``` 3. 创建工具接口类对象。 - ```js - let dsHelper: dataShare.DataShareHelper; + ```ts + let dsHelper: dataShare.DataShareHelper | undefined = undefined; let abilityContext: Context; - + export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage: window.WindowStage) { abilityContext = this.context; @@ -219,7 +219,7 @@ 4. 获取到接口类对象后,便可利用其提供的接口访问提供方提供的服务,如进行数据的增删改查等。 - ```js + ```ts // 构建一条数据 let key1 = 'name'; let key2 = 'age'; @@ -236,22 +236,24 @@ let updateBucket: ValuesBucket = { key1: valueName2, key2: valueAge2, key3: valueIsStudent2, key4: valueBinary }; let predicates = new dataSharePredicates.DataSharePredicates(); let valArray = ['*']; - // 插入一条数据 - dsHelper.insert(dseUri, valuesBucket, (err, data) => { - console.info(`dsHelper insert result:${data}`); - }); - // 更新数据 - dsHelper.update(dseUri, predicates, updateBucket, (err, data) => { - console.info(`dsHelper update result:${data}`); - }); - // 查询数据 - dsHelper.query(dseUri, predicates, valArray, (err, data) => { - console.info(`dsHelper query result:${data}`); - }); - // 删除指定的数据 - dsHelper.delete(dseUri, predicates, (err, data) => { - console.info(`dsHelper delete result:${data}`); - }); + if (dsHelper != undefined) { + // 插入一条数据 + (dsHelper as dataShare.DataShareHelper).insert(dseUri, valuesBucket, (err, data) => { + console.info(`dsHelper insert result:${data}`); + }); + // 更新数据 + (dsHelper as dataShare.DataShareHelper).update(dseUri, predicates, updateBucket, (err, data) => { + console.info(`dsHelper update result:${data}`); + }); + // 查询数据 + (dsHelper as dataShare.DataShareHelper).query(dseUri, predicates, valArray, (err, data) => { + console.info(`dsHelper query result:${data}`); + }); + // 删除指定的数据 + (dsHelper as dataShare.DataShareHelper).delete(dseUri, predicates, (err, data) => { + console.info(`dsHelper delete result:${data}`); + }); + } ``` ## 相关实例 diff --git a/zh-cn/application-dev/device/pointerstyle-guidelines.md b/zh-cn/application-dev/device/pointerstyle-guidelines.md index 0f3d451f1a58ab65fb8770a0bcb8319b72d32c80..fabac3d7c470187cbde5df5ef12b302f400f243d 100644 --- a/zh-cn/application-dev/device/pointerstyle-guidelines.md +++ b/zh-cn/application-dev/device/pointerstyle-guidelines.md @@ -87,7 +87,7 @@ window.getLastWindow(this.context, (error, windowClass) => { console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(error)); return; } - var windowId = windowClass.getWindowProperties().id; + let windowId = windowClass.getWindowProperties().id; if (windowId < 0) { console.log(`Invalid windowId`); return; @@ -107,7 +107,7 @@ window.getLastWindow(this.context, (error, windowClass) => { console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(error)); return; } - var windowId = windowClass.getWindowProperties().id; + let windowId = windowClass.getWindowProperties().id; if (windowId < 0) { console.log(`Invalid windowId`); return; diff --git a/zh-cn/application-dev/device/stationary-guidelines.md b/zh-cn/application-dev/device/stationary-guidelines.md index 190881fe356452c6c3cadb14b8aecbb6efe4fbd8..80b3f018ce0a83a0e62da1735f170c400453232f 100644 --- a/zh-cn/application-dev/device/stationary-guidelines.md +++ b/zh-cn/application-dev/device/stationary-guidelines.md @@ -47,6 +47,7 @@ ```ts import stationary from '@ohos.stationary'; + import { BusinessError } from '@ohos.base'; let reportLatencyNs = 1000000000; try { stationary.on('still', stationary.ActivityEvent.ENTER, reportLatencyNs, (data) => { @@ -62,6 +63,7 @@ ```ts import stationary from '@ohos.stationary'; + import { BusinessError } from '@ohos.base'; try { stationary.once('still', (data) => { console.log('data='+ JSON.stringify(data)); @@ -76,6 +78,7 @@ ```ts import stationary from '@ohos.stationary'; + import { BusinessError } from '@ohos.base'; try { stationary.off('still', stationary.ActivityEvent.ENTER, (data) => { console.log('data='+ JSON.stringify(data)); diff --git a/zh-cn/application-dev/dfx/hiappevent-guidelines.md b/zh-cn/application-dev/dfx/hiappevent-guidelines.md index 865455e43d7dc69b8a1a19a4f73f826246cfd00f..5b98b330611163a36630aa01b37c4066b6ee5d51 100644 --- a/zh-cn/application-dev/dfx/hiappevent-guidelines.md +++ b/zh-cn/application-dev/dfx/hiappevent-guidelines.md @@ -47,53 +47,54 @@ HiAppEvent是在系统层面为应用开发者提供的一种事件打点机制 1. 新建一个ArkTS应用工程,编辑工程中的“entry > src > main > ets > entryability > EntryAbility.ts” 文件,在onCreate函数中添加对用户点击按钮事件的订阅,完整示例代码如下: - ```js + ```ts + import AbilityConstant from '@ohos.app.ability.AbilityConstant'; + import hiAppEvent from '@ohos.hiviewdfx.hiAppEvent'; import hilog from '@ohos.hilog'; import UIAbility from '@ohos.app.ability.UIAbility'; - import Window from '@ohos.window' - import hiAppEvent from '@ohos.hiviewdfx.hiAppEvent' + import Want from '@ohos.app.ability.Want'; + import window from '@ohos.window'; export default class EntryAbility extends UIAbility { - onCreate(want, launchParam) { - hilog.isLoggable(0x0000, 'testTag', hilog.LogLevel.INFO); - hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate'); - hilog.info(0x0000, 'testTag', '%{public}s', 'want param:' + JSON.stringify(want) ?? ''); - hilog.info(0x0000, 'testTag', '%{public}s', 'launchParam:' + JSON.stringify(launchParam) ?? ''); + onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { + hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate'); - hiAppEvent.addWatcher({ - // 开发者可以自定义观察者名称,系统会使用名称来标识不同的观察者 - name: "watcher1", - // 开发者可以订阅感兴趣的应用事件,此处是订阅了按钮事件 - appEventFilters: [{ domain: "button" }], - // 开发者可以设置订阅回调触发的条件,此处是设置为事件打点数量满足1个 - triggerCondition: { row: 1 }, - // 开发者可以自行实现订阅回调函数,以便对订阅获取到的事件打点数据进行自定义处理 - onTrigger: function (curRow, curSize, holder) { - // 返回的holder对象为null,表示订阅过程发生异常,因此在记录错误日志后直接返回 - if (holder == null) { - hilog.error(0x0000, 'testTag', "HiAppEvent holder is null") - return - } - let eventPkg = null - // 根据设置阈值大小(默认为512KB)去获取订阅事件包,直到将订阅数据全部取出 - // 返回的事件包对象为null,表示当前订阅数据已被全部取出,此次订阅回调触发结束 - while ((eventPkg = holder.takeNext()) != null) { - // 开发者可以对事件包中的事件打点数据进行自定义处理,此处是将事件打点数据打印在日志中 - hilog.info(0x0000, 'testTag', `HiAppEvent eventPkg.packageId=%{public}d`, eventPkg.packageId) - hilog.info(0x0000, 'testTag', `HiAppEvent eventPkg.row=%{public}d`, eventPkg.row) - hilog.info(0x0000, 'testTag', `HiAppEvent eventPkg.size=%{public}d`, eventPkg.size) - for (const eventInfo of eventPkg.data) { - hilog.info(0x0000, 'testTag', `HiAppEvent eventPkg.info=%{public}s`, eventInfo) - } - } - } - }) - } + hiAppEvent.addWatcher({ + // 开发者可以自定义观察者名称,系统会使用名称来标识不同的观察者 + name: "watcher1", + // 开发者可以订阅感兴趣的应用事件,此处是订阅了按钮事件 + appEventFilters: [{ domain: "button" }], + // 开发者可以设置订阅回调触发的条件,此处是设置为事件打点数量满足1个 + triggerCondition: { row: 1 }, + // 开发者可以自行实现订阅回调函数,以便对订阅获取到的事件打点数据进行自定义处理 + onTrigger: (curRow: number, curSize: number, holder: hiAppEvent.AppEventPackageHolder) => { + // 返回的holder对象为null,表示订阅过程发生异常,因此在记录错误日志后直接返回 + if (holder == null) { + hilog.error(0x0000, 'testTag', "HiAppEvent holder is null"); + return; + } + hilog.info(0x0000, 'testTag', `HiAppEvent onTrigger: curRow=%{public}d, curSize=%{public}d`, curRow, curSize); + let eventPkg: hiAppEvent.AppEventPackage | null = null; + // 根据设置阈值大小(默认为512KB)去获取订阅事件包,直到将订阅数据全部取出 + // 返回的事件包对象为null,表示当前订阅数据已被全部取出,此次订阅回调触发结束 + while ((eventPkg = holder.takeNext()) != null) { + // 开发者可以对事件包中的事件打点数据进行自定义处理,此处是将事件打点数据打印在日志中 + hilog.info(0x0000, 'testTag', `HiAppEvent eventPkg.packageId=%{public}d`, eventPkg.packageId); + hilog.info(0x0000, 'testTag', `HiAppEvent eventPkg.row=%{public}d`, eventPkg.row); + hilog.info(0x0000, 'testTag', `HiAppEvent eventPkg.size=%{public}d`, eventPkg.size); + for (const eventInfo of eventPkg.data) { + hilog.info(0x0000, 'testTag', `HiAppEvent eventPkg.info=%{public}s`, eventInfo); + } + } + } + }); + } } 2. 编辑工程中的“entry > src > main > ets > pages > Index.ets” 文件,添加一个按钮并在其onClick函数中进行事件打点,以记录按钮点击事件,完整示例代码如下: - ```js + ```ts + import { BusinessError } from 'ohos.base' import hiAppEvent from '@ohos.hiviewdfx.hiAppEvent' import hilog from '@ohos.hilog' @@ -111,7 +112,8 @@ HiAppEvent是在系统层面为应用开发者提供的一种事件打点机制 Button("writeTest").onClick(()=>{ // 在按钮点击函数中进行事件打点,以记录按钮点击事件 - hiAppEvent.write({ + let eventParams: Record = { 'click_time': 100 }; + let eventInfo: hiAppEvent.AppEventInfo = { // 事件领域定义 domain: "button", // 事件名称定义 @@ -119,12 +121,13 @@ HiAppEvent是在系统层面为应用开发者提供的一种事件打点机制 // 事件类型定义 eventType: hiAppEvent.EventType.BEHAVIOR, // 事件参数定义 - params: { click_time: 100 } - }).then(() => { + params: eventParams, + }; + hiAppEvent.write(eventInfo).then(() => { hilog.info(0x0000, 'testTag', `HiAppEvent success to write event`) - }).catch((err) => { + }).catch((err: BusinessError) => { hilog.error(0x0000, 'testTag', `HiAppEvent err.code: ${err.code}, err.message: ${err.message}`) - }) + }); }) } .width('100%') @@ -137,15 +140,11 @@ HiAppEvent是在系统层面为应用开发者提供的一种事件打点机制 3. 点击IDE界面中的运行按钮,运行应用工程,然后在应用界面中点击按钮“writeTest”,触发一次按钮点击事件打点。 4. 最终,可以在Log窗口看到按钮点击事件打点成功的日志,以及触发订阅回调后对打点事件数据的处理日志: - - ```js - HiAppEvent success to write event - - HiAppEvent eventPkg.packageId=0 - HiAppEvent eventPkg.row=1 - HiAppEvent eventPkg.size=124 - HiAppEvent eventPkg.info={"domain_":"button","name_":"click","type_":4,"time_":1670268234523,"tz_":"+0800","pid_":3295,"tid_":3309,"click_time":100} - ``` +> HiAppEvent success to write event +> HiAppEvent eventPkg.packageId=0 +> HiAppEvent eventPkg.row=1 +> HiAppEvent eventPkg.size=124 +> HiAppEvent eventPkg.info={"domain\_":"button","name\_":"click","type\_":4,"time\_":1670268234523,"tz\_":"+0800","pid\_":3295,"tid\_":3309,"click_time":100} ## 相关实例 diff --git a/zh-cn/application-dev/file-management/photoAccessHelper-notify-guidelines.md b/zh-cn/application-dev/file-management/photoAccessHelper-notify-guidelines.md index a6568e442d847946af56ba3a189f0010c391569c..0a5f460ae3da0b97024ebd4d1cfe5986912c0a4c 100644 --- a/zh-cn/application-dev/file-management/photoAccessHelper-notify-guidelines.md +++ b/zh-cn/application-dev/file-management/photoAccessHelper-notify-guidelines.md @@ -33,29 +33,27 @@ photoAccessHelper提供监听媒体资源变更的接口,供开发者对指定 ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; -let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -predicates.equalTo(photoAccessHelper.ImageVideoKey.DISPLAY_NAME, 'test.jpg'); -let fetchOptions: photoAccessHelper.FetchOptions = { - fetchColumns: [], - predicates: predicates -}; - -try { - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); - let fileAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); - console.info('getAssets fileAsset.uri : ' + fileAsset.uri); - - let onCallback = (changeData:dataSharePredicates.ChangeData) => { - console.info('onCallback successfully, changData: ' + JSON.stringify(changeData)); +async function example() { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + predicates.equalTo(photoAccessHelper.PhotoKeys.DISPLAY_NAME, 'test.jpg'); + let fetchOptions: photoAccessHelper.FetchOptions = { + fetchColumns: [], + predicates: predicates + }; + try { + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); + let fileAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); + console.info('getAssets fileAsset.uri : ' + fileAsset.uri); + let onCallback = (changeData: photoAccessHelper.ChangeData) => { + console.info('onCallback successfully, changData: ' + JSON.stringify(changeData)); + } + phAccessHelper.registerChange(fileAsset.uri, false, onCallback); + await fileAsset.setFavorite(true); + fetchResult.close(); + } catch (err) { + console.error('onCallback failed with err: ' + err); } - phAccessHelper.registerChange(fileAsset.uri, false, onCallback); - - await fileAsset.favorite(true); - fetchResult.close(); -} catch (err) { - console.error('onCallback failed with err: ' + err); } ``` @@ -78,31 +76,31 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; -let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let albumName: photoAccessHelper.AlbumKeys = photoAccessHelper.AlbumKey.ALBUM_NAME; -predicates.equalTo(albumName, 'albumName'); -let fetchOptions: dataSharePredicates.FetchOptions = { - fetchColumns: [], - predicates: predicates -}; - -try { - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, fetchOptions); - let album: photoAccessHelper.Album = await fetchResult.getFirstObject(); - console.info('getAlbums successfullyfully, albumName: ' + album.albumUri); - - let onCallback = (changeData: photoAccessHelper.ChangeData) => { - console.info('onCallback successfully, changData: ' + JSON.stringify(changeData)); +async function example() { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let albumName: photoAccessHelper.AlbumKeys = photoAccessHelper.AlbumKeys.ALBUM_NAME; + predicates.equalTo(albumName, 'albumName'); + let fetchOptions: photoAccessHelper.FetchOptions = { + fetchColumns: [], + predicates: predicates + }; + + try { + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, fetchOptions); + let album: photoAccessHelper.Album = await fetchResult.getFirstObject(); + console.info('getAlbums successfullyfully, albumName: ' + album.albumUri); + + let onCallback = (changeData: photoAccessHelper.ChangeData) => { + console.info('onCallback successfully, changData: ' + JSON.stringify(changeData)); + } + phAccessHelper.registerChange(album.albumUri, false, onCallback); + album.albumName = 'newAlbumName' + Date.now(); + await album.commitModify(); + fetchResult.close(); + } catch (err) { + console.error('onCallback failed with err: ' + err); } - phAccessHelper.registerChange(album.albumUri, false, onCallback); - - album.albumName = 'newAlbumName' + Date.now(); - await album.commitModify(); - fetchResult.close(); -} catch (err) { - console.error('onCallback failed with err: ' + err); } ``` @@ -129,27 +127,26 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; -let onCallback = (changeData: dataSharePredicates.ChangeData) => { - console.info('onCallback successfully, changData: ' + JSON.stringify(changeData)); -} -phAccessHelper.registerChange(photoAccessHelper.DefaultChangeUri.DEFAULT_PHOTO_URI, true, onCallback); - -let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let fetchOptions: photoAccessHelper.FetchOptions = { - fetchColumns: [], - predicates: predicates -}; - -try { - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); - let fileAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); - console.info('getAssets fileAsset.uri : ' + fileAsset.uri); - await fileAsset.favorite(true); - fetchResult.close(); -} catch (err) { - console.error('onCallback failed with err: ' + err); +async function example() { + let onCallback = (changeData: photoAccessHelper.ChangeData) => { + console.info('onCallback successfully, changData: ' + JSON.stringify(changeData)); + } + phAccessHelper.registerChange(photoAccessHelper.DefaultChangeUri.DEFAULT_PHOTO_URI, true, onCallback); + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions: photoAccessHelper.FetchOptions = { + fetchColumns: [], + predicates: predicates + }; + try { + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); + let fileAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); + console.info('getAssets fileAsset.uri : ' + fileAsset.uri); + await fileAsset.setFavorite(true); + fetchResult.close(); + } catch (err) { + console.error('onCallback failed with err: ' + err); + } } ``` @@ -172,33 +169,31 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - -let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -predicates.equalTo(photoAccessHelper.ImageVideoKey.DISPLAY_NAME, 'test.jpg'); -let fetchOptions: photoAccessHelper.FetchOptions = { - fetchColumns: [], - predicates: predicates -}; - -try { - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); - let fileAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); - console.info('getAssets fileAsset.uri : ' + fileAsset.uri); - - let onCallback1 = (changeData: photoAccessHelper.ChangeData) => { - console.info('onCallback1, changData: ' + JSON.stringify(changeData)); - } - let onCallback2 = (changeData: photoAccessHelper.ChangeData) => { - console.info('onCallback2, changData: ' + JSON.stringify(changeData)); + +async function example() { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + predicates.equalTo(photoAccessHelper.PhotoKeys.DISPLAY_NAME, 'test.jpg'); + let fetchOptions: photoAccessHelper.FetchOptions = { + fetchColumns: [], + predicates: predicates + }; + try { + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); + let fileAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); + console.info('getAssets fileAsset.uri : ' + fileAsset.uri); + let onCallback1 = (changeData: photoAccessHelper.ChangeData) => { + console.info('onCallback1, changData: ' + JSON.stringify(changeData)); + } + let onCallback2 = (changeData: photoAccessHelper.ChangeData) => { + console.info('onCallback2, changData: ' + JSON.stringify(changeData)); + } + phAccessHelper.registerChange(fileAsset.uri, false, onCallback1); + phAccessHelper.registerChange(fileAsset.uri, false, onCallback2); + phAccessHelper.unRegisterChange(fileAsset.uri, onCallback1); + await fileAsset.setFavorite(true); + fetchResult.close(); + } catch (err) { + console.error('onCallback failed with err: ' + err); } - phAccessHelper.registerChange(fileAsset.uri, false, onCallback1); - phAccessHelper.registerChange(fileAsset.uri, false, onCallback2); - phAccessHelper.unRegisterChange(fileAsset.uri, onCallback1); - - await fileAsset.favorite(true); - fetchResult.close(); -} catch (err) { - console.error('onCallback failed with err: ' + err); } ``` diff --git a/zh-cn/application-dev/file-management/photoAccessHelper-overview.md b/zh-cn/application-dev/file-management/photoAccessHelper-overview.md index 9ac3deb5f0c76597d9e78415669c40e7d0168bb1..6546d5c56a92465e6eca08704850ed3ea4297032 100644 --- a/zh-cn/application-dev/file-management/photoAccessHelper-overview.md +++ b/zh-cn/application-dev/file-management/photoAccessHelper-overview.md @@ -107,14 +107,12 @@ let phAccessHelper: photoAccessHelper.PhotoAccessHelper = photoAccessHelper.getP export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { let list : Array = ['ohos.permission.READ_IMAGEVIDEO', 'ohos.permission.WRITE_IMAGEVIDEO']; - let permissionRequestResult; let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); atManager.requestPermissionsFromUser(this.context, list, (err, result) => { if (err) { console.error('requestPermissionsFromUserError: ' + JSON.stringify(err)); } else { - permissionRequestResult = result; - console.info('permissionRequestResult: ' + JSON.stringify(permissionRequestResult)); + console.info('permissionRequestResult: ' + JSON.stringify(result)); } }); } diff --git a/zh-cn/application-dev/file-management/photoAccessHelper-resource-guidelines.md b/zh-cn/application-dev/file-management/photoAccessHelper-resource-guidelines.md index a728ea8e283eebd21343551c0030731692ec5069..68c21f740e2a7d18e48da3a56dcf66f06183a7e5 100644 --- a/zh-cn/application-dev/file-management/photoAccessHelper-resource-guidelines.md +++ b/zh-cn/application-dev/file-management/photoAccessHelper-resource-guidelines.md @@ -27,34 +27,24 @@ 下面以查询文件名为'test.jpg'的图片资源为例。 -**开发步骤:** - -创建FetchOptions对象指定检索条件为检索文件名为'test.jpg'的图片。 - ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - -let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -predicates.equalTo(photoAccessHelper.PhotoKeys.DISPLAY_NAME, 'test.jpg'); -let fetchOptions: photoAccessHelper.FetchOptions = { - fetchColumns: [], - predicates: predicates -}; -``` -调用PhotoAccessHelper.getAssets接口获取图片资源。 - -```ts -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - -try { - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); - let fileAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); - console.info('getAssets fileAsset.displayName : ' + fileAsset.displayName); - fetchResult.close(); -} catch (err) { - console.error('getAssets failed with err: ' + err); +async function example() { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + predicates.equalTo(photoAccessHelper.PhotoKeys.DISPLAY_NAME, 'test.jpg'); + let fetchOptions: photoAccessHelper.FetchOptions = { + fetchColumns: [], + predicates: predicates + }; + try { + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); + let fileAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); + console.info('getAssets fileAsset.displayName : ' + fileAsset.displayName); + fetchResult.close(); + } catch (err) { + console.error('getAssets failed with err: ' + err); + } } ``` @@ -64,65 +54,53 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - -let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -predicates.equalTo(photoAccessHelper.PhotoKeys.URI, 'file://media/Photo/1'); -let fetchOptions: photoAccessHelper.FetchOptions = { - fetchColumns: [], - predicates: predicates -}; -``` -调用PhotoAccessHelper.getAssets接口获取图片资源。 +async function example() { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + predicates.equalTo(photoAccessHelper.PhotoKeys.URI, 'file://media/Photo/1'); + let fetchOptions: photoAccessHelper.FetchOptions = { + fetchColumns: [], + predicates: predicates + }; -```ts -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - -try { - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); - let fileAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); - console.info('getAssets fileAsset.uri : ' + fileAsset.uri); - fetchResult.close(); -} catch (err) { - console.error('getAssets failed with err: ' + err); + try { + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); + let fileAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); + console.info('getAssets fileAsset.uri : ' + fileAsset.uri); + fetchResult.close(); + } catch (err) { + console.error('getAssets failed with err: ' + err); + } } ``` - ### 指定文件添加的时间获取图片或视频资源 下面以查询指定添加时间为'2022-06-01'至'2023-06-01'这一年内为例。 ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - -let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let startTime: Number = Date.parse(new Date('2022-06-01').toString()) / 1000; // The value of the start time is the number of seconds elapsed since the Epoch time. -let endTime: Number = Date.parse(new Date('2023-06-01').toString()) / 1000; // The value of the end time is the number of seconds elapsed since the Epoch time. -let date_added: photoAccessHelper.PhotoKeys = photoAccessHelper.PhotoKeys.DATE_ADDED; -predicates.between(date_added, startTime, endTime); -predicates.orderByDesc(date_added); // Sort the obtained records in descending order. -let fetchOptions: photoAccessHelper.FetchOptions = { - fetchColumns: [date_added], // The date_added attribute is not a default option and needs to be added. - predicates: predicates -}; -``` - -调用PhotoAccessHelper.getAssets接口获取图片资源。 -```ts -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - -try { - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); - console.info('getAssets count: ' + fetchResult.getCount()); - let fileAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); - console.info('getAssets fileAsset.displayName : ' + fileAsset.displayName); - fetchResult.close(); -} catch (err) { - console.error('getAssets failed with err: ' + err); +async function example() { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let startTime = Date.parse(new Date('2022-06-01').toString()) / 1000; // 查询起始时间距1970年1月1日的秒数值。 + let endTime = Date.parse(new Date('2023-06-01').toString()) / 1000; // 查询结束时间距1970年1月1日的秒数值。 + let date_added: photoAccessHelper.PhotoKeys = photoAccessHelper.PhotoKeys.DATE_ADDED; + predicates.between(date_added, startTime, endTime); + predicates.orderByDesc(date_added); // 查询结果按照降序排序。 + let fetchOptions: photoAccessHelper.FetchOptions = { + fetchColumns: [date_added], // date_added属性不属于默认查询列,需要自行添加。 + predicates: predicates + }; + try { + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); + console.info('getAssets count: ' + fetchResult.getCount()); + let fileAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); + console.info('getAssets fileAsset.displayName : ' + fileAsset.displayName); + fetchResult.close(); + } catch (err) { + console.error('getAssets failed with err: ' + err); + } } ``` @@ -151,26 +129,27 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; import image from '@ohos.multimedia.image'; -let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let fetchOptions: photoAccessHelper.FetchOptions = { - fetchColumns: [], - predicates: predicates -}; - -try { - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); - let fileAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); - console.info('getAssets fileAsset.displayName : ' + fileAsset.displayName); - let size: image.Size = { width: 720, height: 720 }; - let pixelMap: image.PixelMap = await fileAsset.getThumbnail(size); - let imageInfo: image.ImageInfo = await pixelMap.getImageInfo() - console.info('getThumbnail successful, pixelMap ImageInfo size: ' + JSON.stringify(imageInfo.size)); - fetchResult.close(); -} catch (err) { - console.error('getThumbnail failed with err: ' + err); +async function example() { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions: photoAccessHelper.FetchOptions = { + fetchColumns: [], + predicates: predicates + }; + + try { + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); + let fileAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); + console.info('getAssets fileAsset.displayName : ' + fileAsset.displayName); + let size: image.Size = { width: 720, height: 720 }; + let pixelMap: image.PixelMap = await fileAsset.getThumbnail(size); + let imageInfo: image.ImageInfo = await pixelMap.getImageInfo() + console.info('getThumbnail successful, pixelMap ImageInfo size: ' + JSON.stringify(imageInfo.size)); + fetchResult.close(); + } catch (err) { + console.error('getThumbnail failed with err: ' + err); + } } ``` @@ -193,18 +172,18 @@ try { 2. 调用createAsset接口创建图片资源。 ```ts -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - -try { - let displayName: string = 'testPhoto' + Date.now() + '.jpg'; - let createOption: photoAccessHelper.CreateOptions = { - subType: photoAccessHelper.PhotoSubtype.DEFAULT - }; - - let fileAsset: photoAccessHelper.photoAsset = await phAccessHelper.createAsset(displayName, createOption); - console.info('createAsset successfully, file displayName: ' + fileAsset.displayName); -} catch (err) { - console.error('createAsset failed, message = ', err); +async function example() { + try { + let displayName: string = 'testPhoto' + Date.now() + '.jpg'; + let createOption: photoAccessHelper.PhotoCreateOptions = { + subtype: photoAccessHelper.PhotoSubtype.DEFAULT + }; + + let fileAsset: photoAccessHelper.PhotoAsset = await phAccessHelper.createAsset(displayName, createOption); + console.info('createAsset successfully, file displayName: ' + fileAsset.displayName); + } catch (err) { + console.error('createAsset failed, message = ', err); + } } ``` @@ -233,26 +212,27 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - -let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let fetchOptions: photoAccessHelper.FetchOptions = { - fetchColumns: ['title'], - predicates: predicates -}; -let newTitle = 'newTestPhoto'; - -try { - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); - let fileAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); - let title: photoAccessHelper.PhotoKeys = photoAccessHelper.PhotoKeys.TITLE; - let fileAssetTitle: photoAccessHelper.MemberType = fileAsset.get(title); - console.info('getAssets fileAsset.title : ' + fileAssetTitle); - fileAsset.set(title, newTitle); - await fileAsset.commitModify(); - fetchResult.close(); -} catch (err) { - console.error('commitModify failed with err: ' + err); + +async function example() { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions: photoAccessHelper.FetchOptions = { + fetchColumns: ['title'], + predicates: predicates + }; + let newTitle = 'newTestPhoto'; + + try { + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); + let fileAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); + let title: photoAccessHelper.PhotoKeys = photoAccessHelper.PhotoKeys.TITLE; + let fileAssetTitle: photoAccessHelper.MemberType = fileAsset.get(title); + console.info('getAssets fileAsset.title : ' + fileAssetTitle); + fileAsset.set(title, newTitle); + await fileAsset.commitModify(); + fetchResult.close(); + } catch (err) { + console.error('commitModify failed with err: ' + err); + } } ``` @@ -278,21 +258,22 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - -let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let fetchOptions: photoAccessHelper.FetchOptions = { - fetchColumns: [], - predicates: predicates -}; - -try { - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); - let fileAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); - console.info('getAssets fileAsset.uri : ' + fileAsset.uri); - await phAccessHelper.deleteAssets([fileAsset.uri]); - fetchResult.close(); -} catch (err) { - console.error('deleteAssets failed with err: ' + err); + +async function example() { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions: photoAccessHelper.FetchOptions = { + fetchColumns: [], + predicates: predicates + }; + + try { + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); + let fileAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); + console.info('getAssets fileAsset.uri : ' + fileAsset.uri); + await phAccessHelper.deleteAssets([fileAsset.uri]); + fetchResult.close(); + } catch (err) { + console.error('deleteAssets failed with err: ' + err); + } } ``` diff --git a/zh-cn/application-dev/file-management/photoAccessHelper-systemAlbum-guidelines.md b/zh-cn/application-dev/file-management/photoAccessHelper-systemAlbum-guidelines.md index 11fdee073158b8bddb39d5c8736ef63cad4e37a1..18c3c2b7352d1a48066316be58f7244955a68acb 100644 --- a/zh-cn/application-dev/file-management/photoAccessHelper-systemAlbum-guidelines.md +++ b/zh-cn/application-dev/file-management/photoAccessHelper-systemAlbum-guidelines.md @@ -29,15 +29,15 @@ photoAccessHelper仅提供开发者对收藏夹、视频相册、截屏和录屏 2. 调用getAlbums接口获取收藏夹对象。 ```ts -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - -try { - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.FAVORITE); - let album: photoAccessHelper.Album = await fetchResult.getFirstObject(); - console.info('get favorite Album successfully, albumUri: ' + album.albumUri); - fetchResult.close(); -} catch (err) { - console.error('get favorite Album failed with err: ' + err); +async function example() { + try { + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.FAVORITE); + let album: photoAccessHelper.Album = await fetchResult.getFirstObject(); + console.info('get favorite Album successfully, albumUri: ' + album.albumUri); + fetchResult.close(); + } catch (err) { + console.error('get favorite Album failed with err: ' + err); + } } ``` @@ -60,23 +60,24 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - -let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -predicates.equalTo(photoAccessHelper.ImageVideoKey.DISPLAY_NAME, 'test.jpg'); -let fetchOptions: photoAccessHelper.FetchOptions = { - fetchColumns: [], - predicates: predicates -}; - -try { - let photoFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); - let fileAsset: photoAccessHelper.PhotoAsset = await photoFetchResult.getFirstObject(); - console.info('getAssets fileAsset.displayName : ' + fileAsset.displayName); - let favoriteState = true; - await fileAsset.setFavorite(favoriteState); -} catch (err) { - console.error('setFavorite failed with err: ' + err); + +async function example() { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + predicates.equalTo(photoAccessHelper.PhotoKeys.DISPLAY_NAME, 'test.jpg'); + let fetchOptions: photoAccessHelper.FetchOptions = { + fetchColumns: [], + predicates: predicates + }; + + try { + let photoFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); + let fileAsset: photoAccessHelper.PhotoAsset = await photoFetchResult.getFirstObject(); + console.info('getAssets fileAsset.displayName : ' + fileAsset.displayName); + let favoriteState = true; + await fileAsset.setFavorite(favoriteState); + } catch (err) { + console.error('setFavorite failed with err: ' + err); + } } ``` @@ -100,26 +101,27 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - -let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let fetchOptions: photoAccessHelper.FetchOptions = { - fetchColumns: [], - predicates: predicates -}; - -try { - let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.FAVORITE); - let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); - console.info('get favorite Album successfully, albumUri: ' + album.albumUri); - - let photoFetchResult: photoAccessHelper.FetchResult = await album.getAssets(fetchOptions); - let fileAsset: photoAccessHelper.PhotoAsset = await photoFetchResult.getFirstObject(); - console.info('favorite album getAssets successfully, albumName: ' + fileAsset.displayName); - photoFetchResult.close(); - albumFetchResult.close(); -} catch (err) { - console.error('favorite failed with err: ' + err); + +async function example() { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions: photoAccessHelper.FetchOptions = { + fetchColumns: [], + predicates: predicates + }; + + try { + let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.FAVORITE); + let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); + console.info('get favorite Album successfully, albumUri: ' + album.albumUri); + + let photoFetchResult: photoAccessHelper.FetchResult = await album.getAssets(fetchOptions); + let fileAsset: photoAccessHelper.PhotoAsset = await photoFetchResult.getFirstObject(); + console.info('favorite album getAssets successfully, albumName: ' + fileAsset.displayName); + photoFetchResult.close(); + albumFetchResult.close(); + } catch (err) { + console.error('favorite failed with err: ' + err); + } } ``` @@ -143,28 +145,29 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - -let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let fetchOptions: photoAccessHelper.FetchOptions = { - fetchColumns: [], - predicates: predicates -}; - -try { - let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.FAVORITE); - let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); - console.info('get favorite Album successfully, albumUri: ' + album.albumUri); - - let photoFetchResult: photoAccessHelper.FetchResult = await album.getAssets(fetchOptions); - let fileAsset: photoAccessHelper.PhotoAsset = await photoFetchResult.getFirstObject(); - console.info('favorite album getAssets successfully, albumName: ' + fileAsset.displayName); - let favoriteState = false; - await fileAsset.setFavorite(favoriteState); - photoFetchResult.close(); - albumFetchResult.close(); -} catch (err) { - console.error('setFavorite failed with err: ' + err); + +async function example() { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions: photoAccessHelper.FetchOptions = { + fetchColumns: [], + predicates: predicates + }; + + try { + let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.FAVORITE); + let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); + console.info('get favorite Album successfully, albumUri: ' + album.albumUri); + + let photoFetchResult: photoAccessHelper.FetchResult = await album.getAssets(fetchOptions); + let fileAsset: photoAccessHelper.PhotoAsset = await photoFetchResult.getFirstObject(); + console.info('favorite album getAssets successfully, albumName: ' + fileAsset.displayName); + let favoriteState = false; + await fileAsset.setFavorite(favoriteState); + photoFetchResult.close(); + albumFetchResult.close(); + } catch (err) { + console.error('setFavorite failed with err: ' + err); + } } ``` @@ -187,15 +190,15 @@ try { 2. 调用getAlbums接口获取视频相册。 ```ts -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - -try { - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.VIDEO); - let album: photoAccessHelper.Album = await fetchResult.getFirstObject(); - console.info('get video Album successfully, albumUri: ' + album.albumUri); - fetchResult.close(); -} catch (err) { - console.error('get video Album failed with err: ' + err); +async function example() { + try { + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.VIDEO); + let album: photoAccessHelper.Album = await fetchResult.getFirstObject(); + console.info('get video Album successfully, albumUri: ' + album.albumUri); + fetchResult.close(); + } catch (err) { + console.error('get video Album failed with err: ' + err); + } } ``` @@ -219,26 +222,27 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - -let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let fetchOptions: photoAccessHelper.FetchOptions = { - fetchColumns: [], - predicates: predicates -}; - -try { - let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.VIDEO); - let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); - console.info('get video Album successfully, albumUri: ' + album.albumUri); - - let videoFetchResult: photoAccessHelper.FetchResult = await album.getAssets(fetchOptions); - let fileAsset: photoAccessHelper.PhotoAsset = await videoFetchResult.getFirstObject(); - console.info('video album getAssets successfully, albumName: ' + fileAsset.displayName); - videoFetchResult.close(); - albumFetchResult.close(); -} catch (err) { - console.error('video failed with err: ' + err); + +async function example() { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions: photoAccessHelper.FetchOptions = { + fetchColumns: [], + predicates: predicates + }; + + try { + let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.VIDEO); + let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); + console.info('get video Album successfully, albumUri: ' + album.albumUri); + + let videoFetchResult: photoAccessHelper.FetchResult = await album.getAssets(fetchOptions); + let fileAsset: photoAccessHelper.PhotoAsset = await videoFetchResult.getFirstObject(); + console.info('video album getAssets successfully, albumName: ' + fileAsset.displayName); + videoFetchResult.close(); + albumFetchResult.close(); + } catch (err) { + console.error('video failed with err: ' + err); + } } ``` @@ -261,15 +265,15 @@ try { 2. 调用getAlbums接口获取截屏和录屏相册。 ```ts -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - -try { - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.SCREENSHOT); - let album: photoAccessHelper.Album = await fetchResult.getFirstObject(); - console.info('get screenshot Album successfully, albumUri: ' + album.albumUri); - fetchResult.close(); -} catch (err) { - console.error('get screenshot Album failed with err: ' + err); +async function example() { + try { + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.SCREENSHOT); + let album: photoAccessHelper.Album = await fetchResult.getFirstObject(); + console.info('get screenshot Album successfully, albumUri: ' + album.albumUri); + fetchResult.close(); + } catch (err) { + console.error('get screenshot Album failed with err: ' + err); + } } ``` @@ -293,25 +297,26 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - -let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let fetchOptions: photoAccessHelper.FetchOptions = { - fetchColumns: [], - predicates: predicates -}; - -try { - let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.SCREENSHOT); - let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); - console.info('get screenshot album successfully, albumUri: ' + album.albumUri); - - let screenshotFetchResult: photoAccessHelper.FetchResult = await album.getAssets(fetchOptions); - let fileAsset: photoAccessHelper.PhotoAsset = await screenshotFetchResult.getFirstObject(); - console.info('screenshot album getAssets successfully, albumName: ' + fileAsset.displayName); - screenshotFetchResult.close(); - albumFetchResult.close(); -} catch (err) { - console.error('screenshot album failed with err: ' + err); + +async function example() { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions: photoAccessHelper.FetchOptions = { + fetchColumns: [], + predicates: predicates + }; + + try { + let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.SCREENSHOT); + let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); + console.info('get screenshot album successfully, albumUri: ' + album.albumUri); + + let screenshotFetchResult: photoAccessHelper.FetchResult = await album.getAssets(fetchOptions); + let fileAsset: photoAccessHelper.PhotoAsset = await screenshotFetchResult.getFirstObject(); + console.info('screenshot album getAssets successfully, albumName: ' + fileAsset.displayName); + screenshotFetchResult.close(); + albumFetchResult.close(); + } catch (err) { + console.error('screenshot album failed with err: ' + err); + } } ``` diff --git a/zh-cn/application-dev/file-management/photoAccessHelper-userAlbum-guidelines.md b/zh-cn/application-dev/file-management/photoAccessHelper-userAlbum-guidelines.md index 4ab3997cb988e3e05895c8b4c79595e307d940b4..5206f5cde46589440d7577c93439b30b9c583b5d 100644 --- a/zh-cn/application-dev/file-management/photoAccessHelper-userAlbum-guidelines.md +++ b/zh-cn/application-dev/file-management/photoAccessHelper-userAlbum-guidelines.md @@ -34,14 +34,14 @@ photoAccessHelper提供用户相册相关的接口,供开发者创建、删除 2. 调用createAlbum接口创建相册。 ```ts -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - -try { - let albumName = 'albumName'; - let album: photoAccessHelper.Album = await phAccessHelper.createAlbum(albumName); - console.info('createAlbum successfully, album: ' + album.albumName + ' album uri: ' + album.albumUri); -} catch (err) { - console.error('createAlbum failed with err: ' + err); +async function example() { + try { + let albumName = 'albumName'; + let album: photoAccessHelper.Album = await phAccessHelper.createAlbum(albumName); + console.info('createAlbum successfully, album: ' + album.albumName + ' album uri: ' + album.albumUri); + } catch (err) { + console.error('createAlbum failed with err: ' + err); + } } ``` @@ -64,23 +64,24 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - -let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let albumName: photoAccessHelper.ALBUM_NAME = photoAccessHelper.AlbumKey.ALBUM_NAME; -predicates.equalTo(albumName, 'albumName'); -let fetchOptions: photoAccessHelper.FetchOptions = { - fetchColumns: [], - predicates: predicates -}; - -try { - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, fetchOptions); - let album: photoAccessHelper.Album = await fetchResult.getFirstObject(); - console.info('getAlbums successfully, albumName: ' + album.albumName); - fetchResult.close(); -} catch (err) { - console.error('getAlbums failed with err: ' + err); + +async function example() { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let albumName: photoAccessHelper.AlbumKeys = photoAccessHelper.AlbumKeys.ALBUM_NAME; + predicates.equalTo(albumName, 'albumName'); + let fetchOptions: photoAccessHelper.FetchOptions = { + fetchColumns: [], + predicates: predicates + }; + + try { + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, fetchOptions); + let album: photoAccessHelper.Album = await fetchResult.getFirstObject(); + console.info('getAlbums successfully, albumName: ' + album.albumName); + fetchResult.close(); + } catch (err) { + console.error('getAlbums failed with err: ' + err); + } } ``` @@ -111,25 +112,26 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - -let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let albumName: photoAccessHelper.AlbumKey.ALBUM_NAME = photoAccessHelper.AlbumKey.ALBUM_NAME; -predicates.equalTo(albumName, 'albumName'); -let fetchOptions: photoAccessHelper.FetchOptions = { - fetchColumns: [], - predicates: predicates -}; - -try { - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, fetchOptions); - let album: photoAccessHelper.Album = await fetchResult.getFirstObject(); - console.info('getAlbums successfully, albumName: ' + album.albumName); - album.albumName = 'newAlbumName'; - await album.commitModify(); - fetchResult.close(); -} catch (err) { - console.error('commitModify failed with err: ' + err); + +async function example() { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let albumName: photoAccessHelper.AlbumKeys = photoAccessHelper.AlbumKeys.ALBUM_NAME; + predicates.equalTo(albumName, 'albumName'); + let fetchOptions: photoAccessHelper.FetchOptions = { + fetchColumns: [], + predicates: predicates + }; + + try { + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, fetchOptions); + let album: photoAccessHelper.Album = await fetchResult.getFirstObject(); + console.info('getAlbums successfully, albumName: ' + album.albumName); + album.albumName = 'newAlbumName'; + await album.commitModify(); + fetchResult.close(); + } catch (err) { + console.error('commitModify failed with err: ' + err); + } } ``` @@ -156,34 +158,35 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - -let albumPredicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let albumName: photoAccessHelper.AlbumKey.ALBUM_NAME = photoAccessHelper.AlbumKey.ALBUM_NAME; -albumPredicates.equalTo(albumName, 'albumName'); -let albumFetchOptions: dataSharePredicates.FetchOptions = { - fetchColumns: [], - predicates: albumPredicates -}; - -let photoPredicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let photoFetchOptions: photoAccessHelper.FetchOptions = { - fetchColumns: [], - predicates: photoPredicates -}; - -try { - let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, albumFetchOptions); - let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); - console.info('getAlbums successfully, albumName: ' + album.albumName); - let photoFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(photoFetchOptions); - let fileAsset: photoAccessHelper.PhotoAsset = await photoFetchResult.getFirstObject(); - console.info('getAssets successfully, albumName: ' + fileAsset.displayName); - await album.addAssets([fileAsset]); - albumFetchResult.close(); - photoFetchResult.close(); -} catch (err) { - console.error('addAssets failed with err: ' + err); + +async function example() { + let albumPredicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let albumName: photoAccessHelper.AlbumKeys = photoAccessHelper.AlbumKeys.ALBUM_NAME; + albumPredicates.equalTo(albumName, 'albumName'); + let albumFetchOptions: photoAccessHelper.FetchOptions = { + fetchColumns: [], + predicates: albumPredicates + }; + + let photoPredicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let photoFetchOptions: photoAccessHelper.FetchOptions = { + fetchColumns: [], + predicates: photoPredicates + }; + + try { + let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, albumFetchOptions); + let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); + console.info('getAlbums successfully, albumName: ' + album.albumName); + let photoFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(photoFetchOptions); + let fileAsset: photoAccessHelper.PhotoAsset = await photoFetchResult.getFirstObject(); + console.info('getAssets successfully, albumName: ' + fileAsset.displayName); + await album.addAssets([fileAsset]); + albumFetchResult.close(); + photoFetchResult.close(); + } catch (err) { + console.error('addAssets failed with err: ' + err); + } } ``` @@ -209,33 +212,34 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - -let albumPredicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let albumName = photoAccessHelper.AlbumKey.ALBUM_NAME; -albumPredicates.equalTo(albumName, 'albumName'); -let albumFetchOptions: photoAccessHelper.FetchOptions = { - fetchColumns: [], - predicates: albumPredicates -}; - -let photoPredicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let photoFetchOptions: photoAccessHelper.FetchOptions = { - fetchColumns: [], - predicates: photoPredicates -}; - -try { - let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, albumFetchOptions); - let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); - console.info('getAlbums successfully, albumName: ' + album.albumName); - let photoFetchResult = await album.getAssets(photoFetchOptions); - let fileAsset = await photoFetchResult.getFirstObject(); - console.info('album getAssets successfully, albumName: ' + fileAsset.displayName); - albumFetchResult.close(); - photoFetchResult.close(); -} catch (err) { - console.error('album getAssets failed with err: ' + err); + +async function example() { + let albumPredicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let albumName: photoAccessHelper.AlbumKeys = photoAccessHelper.AlbumKeys.ALBUM_NAME; + albumPredicates.equalTo(albumName, 'albumName'); + let albumFetchOptions: photoAccessHelper.FetchOptions = { + fetchColumns: [], + predicates: albumPredicates + }; + + let photoPredicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let photoFetchOptions: photoAccessHelper.FetchOptions = { + fetchColumns: [], + predicates: photoPredicates + }; + + try { + let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, albumFetchOptions); + let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); + console.info('getAlbums successfully, albumName: ' + album.albumName); + let photoFetchResult = await album.getAssets(photoFetchOptions); + let fileAsset = await photoFetchResult.getFirstObject(); + console.info('album getAssets successfully, albumName: ' + fileAsset.displayName); + albumFetchResult.close(); + photoFetchResult.close(); + } catch (err) { + console.error('album getAssets failed with err: ' + err); + } } ``` @@ -264,34 +268,35 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - -let albumPredicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let albumName: photoAccessHelper.AlbumKey.ALBUM_NAME = photoAccessHelper.AlbumKey.ALBUM_NAME; -albumPredicates.equalTo(albumName, 'albumName'); -let albumFetchOptions: photoAccessHelper.FetchOptions = { - fetchColumns: [], - predicates: albumPredicates -}; - -let photoPredicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let photoFetchOptions: photoAccessHelper.FetchOptions = { - fetchColumns: [], - predicates: photoPredicates -}; - -try { - let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, albumFetchOptions); - let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); - console.info('getAlbums successfully, albumName: ' + album.albumName); - let photoFetchResult = await album.getAssets(photoFetchOptions); - let fileAsset = await photoFetchResult.getFirstObject(); - console.info('album getAssets successfully, albumName: ' + fileAsset.displayName); - await album.removeAssets([fileAsset]); - albumFetchResult.close(); - photoFetchResult.close(); -} catch (err) { - console.error('removeAssets failed with err: ' + err); + +async function example() { + let albumPredicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let albumName: photoAccessHelper.AlbumKeys = photoAccessHelper.AlbumKeys.ALBUM_NAME; + albumPredicates.equalTo(albumName, 'albumName'); + let albumFetchOptions: photoAccessHelper.FetchOptions = { + fetchColumns: [], + predicates: albumPredicates + }; + + let photoPredicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let photoFetchOptions: photoAccessHelper.FetchOptions = { + fetchColumns: [], + predicates: photoPredicates + }; + + try { + let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, albumFetchOptions); + let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); + console.info('getAlbums successfully, albumName: ' + album.albumName); + let photoFetchResult = await album.getAssets(photoFetchOptions); + let fileAsset = await photoFetchResult.getFirstObject(); + console.info('album getAssets successfully, albumName: ' + fileAsset.displayName); + await album.removeAssets([fileAsset]); + albumFetchResult.close(); + photoFetchResult.close(); + } catch (err) { + console.error('removeAssets failed with err: ' + err); + } } ``` @@ -315,23 +320,24 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; -import photoAccessHelper from '@ohos.file.photoAccessHelper'; - -let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let albumName: photoAccessHelper.AlbumKey.ALBUM_NAME = photoAccessHelper.AlbumKey.ALBUM_NAME; -predicates.equalTo(albumName, '%albumName%'); -let fetchOptions: photoAccessHelper.FetchOptions = { - fetchColumns: [], - predicates: predicates -}; - -try { - let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, fetchOptions); - let album: photoAccessHelper.Album = await fetchResult.getFirstObject(); - console.info('getAlbums successfully, albumName: ' + album.albumName); - phAccessHelper.deleteAlbums([album]); - fetchResult.close(); -} catch (err) { - console.error('deleteAlbums failed with err: ' + err); + +async function example() { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let albumName: photoAccessHelper.AlbumKeys = photoAccessHelper.AlbumKeys.ALBUM_NAME; + predicates.equalTo(albumName, '%albumName%'); + let fetchOptions: photoAccessHelper.FetchOptions = { + fetchColumns: [], + predicates: predicates + }; + + try { + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, fetchOptions); + let album: photoAccessHelper.Album = await fetchResult.getFirstObject(); + console.info('getAlbums successfully, albumName: ' + album.albumName); + phAccessHelper.deleteAlbums([album]); + fetchResult.close(); + } catch (err) { + console.error('deleteAlbums failed with err: ' + err); + } } ``` diff --git a/zh-cn/application-dev/media/Readme-CN.md b/zh-cn/application-dev/media/Readme-CN.md index b4dd333e70bfad8a72214ef3b87db4a49fc28e00..0c3491b48c7067adac93aa0d83641b3fecac54cb 100755 --- a/zh-cn/application-dev/media/Readme-CN.md +++ b/zh-cn/application-dev/media/Readme-CN.md @@ -63,7 +63,7 @@ - [拍照实现方案](camera-shooting-case.md) - [录像实现方案](camera-recording-case.md) - [使用人像模式拍照](camera-mode.md) - - [双路预览](dual-channel-preview.md) + - [双路预览](camera-dual-channel-preview.md) - [性能提升方案(仅对系统应用开放)](camera-performance-improvement.md) - 图片 - [图片开发概述](image-overview.md) diff --git a/zh-cn/application-dev/media/audio-effect-management.md b/zh-cn/application-dev/media/audio-effect-management.md index 414fb2aa9f7936a9ef8bedbb2698fd1bb0879f61..1f28fa95e80e1336a3e7550890aba9639043d7e0 100644 --- a/zh-cn/application-dev/media/audio-effect-management.md +++ b/zh-cn/application-dev/media/audio-effect-management.md @@ -6,52 +6,55 @@ 主要包括查询和设置当前音频播放流的音效模式,音效模式包括EFFECT_NONE关闭音效模式和EFFECT_DEFAULT默认音效模式。默认音效模式会根据创建音频流的ContentType和StreamUsage自动加载对应场景的音效。 -### 获取播放实例(示例代码仅支持JS格式) +### 获取播放实例 管理播放实例音效的接口是getAudioEffectMode()查询当前音频播放流的音效模式和setAudioEffectMode(mode: AudioEffectMode)设置当前音频播放流的音效模式,在使用之前,需要使用createAudioRenderer(options: AudioRendererOptions)先创建音频播放流AudioRenderer实例。 1. 步骤一:导入音频接口。 - ```js + ```ts import audio from '@ohos.multimedia.audio'; ``` 2. 步骤二:配置音频渲染参数并创建AudioRenderer实例,音频渲染参数的详细信息可以查看[AudioRendererOptions](../reference/apis/js-apis-audio.md#audiorendereroptions8),创建AudioRenderer实例时会默认挂载EFFECT_DEFAULT模式音效。 - ```js - let audioStreamInfo = { + ```ts + import audio from '@ohos.multimedia.audio'; + import { BusinessError } from '@ohos.base'; + let audioStreamInfo: audio.AudioStreamInfo = { samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, channels: audio.AudioChannel.CHANNEL_1, sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW }; - let audioRendererInfo = { + let audioRendererInfo: audio.AudioRendererInfo = { content: audio.ContentType.CONTENT_TYPE_SPEECH, usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION, rendererFlags: 0 }; - let audioRendererOptions = { + let audioRendererOptions: audio.AudioRendererOptions = { streamInfo: audioStreamInfo, rendererInfo: audioRendererInfo }; - audio.createAudioRenderer(audioRendererOptions, (err, data) => { + audio.createAudioRenderer(audioRendererOptions, (err: BusinessError, data: audio.AudioRenderer) => { if (err) { console.error(`Invoke createAudioRenderer failed, code is ${err.code}, message is ${err.message}`); return; } else { console.info('Invoke createAudioRenderer succeeded.'); - let audioRenderer = data; + let audioRenderer: audio.AudioRenderer = data; } }); ``` -### 查询当前播放实例的音效模式(示例代码仅支持JS格式) +### 查询当前播放实例的音效模式 - ```js - audioRenderer.getAudioEffectMode((err, effectmode) => { + ```ts + import { BusinessError } from '@ohos.base'; + audioRenderer.getAudioEffectMode((err: BusinessError, effectmode: audio.AudioEffectMode) => { if (err) { console.error(`Failed to get params, code is ${err.code}, message is ${err.message}`); return; @@ -61,12 +64,13 @@ }); ``` -### 设置当前播放实例的音效模式(示例代码仅支持JS格式) +### 设置当前播放实例的音效模式 关闭系统音效: - ```js - audioRenderer.setAudioEffectMode(audio.AudioEffectMode.EFFECT_NONE, (err) => { + ```ts + import { BusinessError } from '@ohos.base'; + audioRenderer.setAudioEffectMode(audio.AudioEffectMode.EFFECT_NONE, (err: BusinessError) => { if (err) { console.error(`Failed to set params, code is ${err.code}, message is ${err.message}`); return; @@ -78,8 +82,9 @@ 开启系统音效默认模式: - ```js - audioRenderer.setAudioEffectMode(audio.AudioEffectMode.EFFECT_DEFAULT, (err) => { + ```ts + import { BusinessError } from '@ohos.base'; + audioRenderer.setAudioEffectMode(audio.AudioEffectMode.EFFECT_DEFAULT, (err: BusinessError) => { if (err) { console.error(`Failed to set params, code is ${err.code}, message is ${err.message}`); return; @@ -94,20 +99,21 @@ 主要包括全局音效查询相应StreamUsage对应场景的音效模式。 对于播放音频类的应用,开发者需要关注该应用的音频流使用什么音效模式并做出相应的操作,比如音乐App播放时,应选择音乐场景下的模式。在使用查询接口前,开发者需要使用getStreamManager()创建一个AudioStreamManager音频流管理实例。 -### 获取音频流管理接口(示例代码仅支持JS格式) +### 获取音频流管理接口 1.创建AudioStreamManager实例。在使用AudioStreamManager的API前,需要使用getStreamManager()创建一个AudioStreamManager实例。 - ```js + ```ts import audio from '@ohos.multimedia.audio'; let audioManager = audio.getAudioManager(); let audioStreamManager = audioManager.getStreamManager(); ``` -### 查询对应场景的音效模式(示例代码仅支持JS格式) +### 查询对应场景的音效模式 - ```js - audioStreamManager.getAudioEffectInfoArray(audio.StreamUsage.STREAM_USAGE_MEDIA, async (err, audioEffectInfoArray) => { + ```ts + import { BusinessError } from '@ohos.base'; + audioStreamManager.getAudioEffectInfoArray(audio.StreamUsage.STREAM_USAGE_MEDIA, async (err: BusinessError, audioEffectInfoArray: audio.AudioEffectInfoArray) => { if (err) { console.error('Failed to get effect info array'); return; diff --git a/zh-cn/application-dev/media/camera-dual-channel-preview.md b/zh-cn/application-dev/media/camera-dual-channel-preview.md index bc37733fd0a32d9a26c31e208b494535fbf014dd..c2f688032cb235c7e41831aa47f3bb4d9862dd8b 100644 --- a/zh-cn/application-dev/media/camera-dual-channel-preview.md +++ b/zh-cn/application-dev/media/camera-dual-channel-preview.md @@ -23,23 +23,25 @@ 创建双路预览流的SurfaceId,除XComponent组件的SurfaceId外,还需要使用ImageReceiver组件创建生成的SurfaceId,需要使用image模块提供的接口。 - ```js + ```ts import image from '@ohos.multimedia.image'; ``` 2. 创建ImageReceiver组件Surface。 - ```js - function getImageReceiverSurfaceId() { - let receiver = image.createImageReceiver(640, 480, 4, 8); - console.info('before ImageReceiver check'); - if (receiver !== undefined) { - console.info('ImageReceiver is ok'); - let ImageReceiverSurfaceId = receiver.getReceivingSurfaceId(); - console.info('ImageReceived id: ' + JSON.stringify(ImageReceiverSurfaceId)); - } else { - console.info('ImageReceiver is not ok'); - } + ```ts + async function getImageReceiverSurfaceId(): Promise { + let receiver: image.ImageReceiver = image.createImageReceiver(640, 480, 4, 8); + console.info('before ImageReceiver check'); + let ImageReceiverSurfaceId: string; + if (receiver !== undefined) { + console.info('ImageReceiver is ok'); + let ImageReceiverSurfaceId: string = await receiver.getReceivingSurfaceId(); + console.info(`ImageReceived id: ${ImageReceiverSurfaceId}`); + } else { + console.info('ImageReceiver is not ok'); + } + return ImageReceiverSurfaceId; } ``` @@ -47,27 +49,33 @@ 可参考[相机预览指导文档](camera-preview.md)。 - ```js + ```ets + //xxx.ets // 创建XComponentController - mXComponentController: XComponentController = new XComponentController; - build() { + @Component + struct XComponentPage { + // 创建XComponentController + mXComponentController: XComponentController = new XComponentController; + + build() { Flex() { - // 创建XComponent - XComponent({ - id: '', - type: 'surface', - libraryname: '', - controller: this.mXComponentController - }) - .onLoad(() => { - // 设置Surface宽高(1920*1080),预览尺寸设置参考前面 previewProfilesArray 获取的当前设备所支持的预览分辨率大小去设置 - this.mXComponentController.setXComponentSurfaceSize({surfaceWidth:1920,surfaceHeight:1080}); - // 获取Surface ID - globalThis.XComponentsurfaceId = this.mXComponentController.getXComponentSurfaceId(); + // 创建XComponent + XComponent({ + id: '', + type: 'surface', + libraryname: '', + controller: this.mXComponentController + }) + .onLoad(() => { + // 设置Surface宽高(1920*1080),预览尺寸设置参考前面 previewProfilesArray 获取的当前设备所支持的预览分辨率大小去设置 + this.mXComponentController.setXComponentSurfaceSize({surfaceWidth:1920,surfaceHeight:1080}); + // 获取Surface ID + let surfaceId: string = this.mXComponentController.getXComponentSurfaceId(); }) - .width('100%') - .height('100%') + .width('1920px') + .height('1080px') } + } } ``` @@ -75,83 +83,84 @@ 将步骤2、3生成的两路SurfaceId通过createPreviewOutput方法传递到相机服务,创建两路预览流,其余流程按照正常预览流程开发。 - ```js - let cameraManager = camera.getCameraManager(globalThis.abilityContext); - let CamerasDevices = cameraManager.getSupportedCameras(); // 获取支持的相机设备对象 - - // 正常写法通过下面方式获取实际情况下的profile对象 - // let profiles = await this.cameraManager.getSupportedOutputCapability(CamerasDevices[cameraDeviceIndex]); // 获取对应相机设备profiles - // let previewProfiles = profiles.previewProfiles; - - // 预览流1 - let previewProfilesObj: camera.Profile; - previewProfilesObj.size.width = 640; - previewProfilesObj.size.height = 480; - previewProfilesObj.format = 3; - - // 预览流2 - let previewProfilesObj2: camera.Profile; - previewProfilesObj2.size.width = 640; - previewProfilesObj2.size.height = 480; - previewProfilesObj2.format = 3; - - // 创建 预览流1 输出对象 - let previewOutput = cameraManager.createPreviewOutput(previewProfilesObj, XComponentsurfaceId); - - // 创建 预览流2 输出对象 - let imageReceiverSurfaceId: string = await this.mReceiver.getReceivingSurfaceId(); - let previewOutput2 = cameraManager.createPreviewOutput(previewProfilesObj2, imageReceiverSurfaceId); - - // 创建cameraInput输出对象 - let cameraInput = cameraManager.createCameraInput(CamerasDevices[cameraDeviceIndex]); - - // 打开相机 - await cameraInput.open(); - - // 会话流程 - let captureSession = await cameraManager.createCaptureSession(); - - // 开始配置会话 - captureSession.beginConfig(); - - // 把CameraInput加入到会话 - captureSession.addInput(cameraInput); - - // 把 预览流1 加入到会话 - captureSession.addOutput(previewOutput) - - // 把 预览流2 加入到会话 - captureSession.addOutput(previewOutput2); - - // 提交配置信息 - await captureSession.commitConfig(); - - // 会话开始 - await captureSession.start(); + ```ts + import camera from '@ohos.multimedia.camera'; + + async function createDualChannelPreview(cameraManager: camera.CameraManager, XComponentSurfaceId: string, receiver: image.ImageReceiver): Promise { + let camerasDevices: Array = cameraManager.getSupportedCameras(); // 获取支持的相机设备对象 + + // 获取profile对象 + let profiles: camera.CameraOutputCapability = await this.cameraManager.getSupportedOutputCapability(camerasDevices[0]); // 获取对应相机设备profiles + let previewProfiles: Array = profiles.previewProfiles; + + // 预览流1 + let previewProfilesObj: camera.Profile = previewProfiles[0]; + + // 预览流2 + let previewProfilesObj2: camera.Profile = previewProfiles[0]; + + // 创建 预览流1 输出对象 + let previewOutput: camera.PreviewOutput = cameraManager.createPreviewOutput(previewProfilesObj, XComponentSurfaceId); + + // 创建 预览流2 输出对象 + let imageReceiverSurfaceId: string = await receiver.getReceivingSurfaceId(); + let previewOutput2: camera.PreviewOutput = cameraManager.createPreviewOutput(previewProfilesObj2, imageReceiverSurfaceId); + + // 创建cameraInput对象 + let cameraInput: camera.CameraInput = cameraManager.createCameraInput(camerasDevices[0]); + + // 打开相机 + await cameraInput.open(); + + // 会话流程 + let captureSession: camera.CaptureSession = cameraManager.createCaptureSession(); + + // 开始配置会话 + captureSession.beginConfig(); + + // 把CameraInput加入到会话 + captureSession.addInput(cameraInput); + + // 把 预览流1 加入到会话 + captureSession.addOutput(previewOutput) + + // 把 预览流2 加入到会话 + captureSession.addOutput(previewOutput2); + + // 提交配置信息 + await captureSession.commitConfig(); + + // 会话开始 + await captureSession.start(); + } ``` 5. 通过ImageReceiver实时获取预览图像。 通过ImageReceiver组件中imageArrival事件监听获取底层返回的图像数据,详细的API说明请参考[Image API参考](../reference/apis/js-apis-image.md)。 - ```js - this.receiver.on('imageArrival', () => { - this.receiver.readNextImage((err, nextImage: image.Image) => { - if (err || nextImage === undefined) { - return; - } - nextImage.getComponent(image.ComponentType.JPEG, (errMsg, img) => { - if (errMsg || img === undefined) { - return; + ```ts + import { BusinessError } from '@ohos.base'; + + function onImageArrival(receiver: image.ImageReceiver): void { + receiver.on('imageArrival', () => { + receiver.readNextImage((err: BusinessError, nextImage: image.Image) => { + if (err || nextImage === undefined) { + return; + } + nextImage.getComponent(image.ComponentType.JPEG, (err: BusinessError, imgComponent: image.Component) => { + if (err || imgComponent === undefined) { + return; } - let buffer; - if (img.byteBuffer) { - buffer = img.byteBuffer; + let buffer: ArrayBuffer; + if (imgComponent.byteBuffer) { + buffer = imgComponent.byteBuffer; } else { - return; + return; } // do something...; - }) + }) }) - }) + }) + } ``` diff --git a/zh-cn/application-dev/media/image-transformation-native.md b/zh-cn/application-dev/media/image-transformation-native.md index 1a685f64995ede4febff56e62471f5e237c0ff49..dde48f8602933598ef6a98e448e9c3da9cfbb6dd 100644 --- a/zh-cn/application-dev/media/image-transformation-native.md +++ b/zh-cn/application-dev/media/image-transformation-native.md @@ -108,7 +108,7 @@ @Component struct Index { @State message: string = 'IMAGE' - @State _PixelMap: image.PixelMap = undefined + @State _PixelMap : image.PixelMap | undefined = undefined; build() { Row() { @@ -117,10 +117,10 @@ .fontSize(50) .fontWeight(FontWeight.Bold) .onClick(() => { - const color = new ArrayBuffer(96); - let opts = { alphaType: 0, editable: true, pixelFormat: 4, scaleMode: 1, size: { height: 4, width: 6 } } + const color : ArrayBuffer = new ArrayBuffer(96); + let opts: image.InitializationOptions = { alphaType: 0, editable: true, pixelFormat: 4, scaleMode: 1, size: { height: 4, width: 6 } } image.createPixelMap(color, opts) - .then( pixelmap => { + .then( (pixelmap : image.PixelMap) => { this._PixelMap = pixelmap; }) diff --git a/zh-cn/application-dev/napi/drawing-guidelines.md b/zh-cn/application-dev/napi/drawing-guidelines.md index 1a2a473509f039b13a5affe9ecb6847b77fbee81..2c65e7981d4541741d520d10e5547f11b18968d4 100644 --- a/zh-cn/application-dev/napi/drawing-guidelines.md +++ b/zh-cn/application-dev/napi/drawing-guidelines.md @@ -35,7 +35,7 @@ Native Drawing模块提供了一系列的接口用于基本图形和字体的绘 ## 2D图形绘制开发步骤 -以下步骤描述了在**OpenHarmony**如何使用 **Native Drawing** 模块的画布画笔绘制一个基本的2D图形: +以下步骤描述了如何使用 **Native Drawing** 模块的画布画笔绘制一个基本的2D图形: 1. **创建Bitmap实例**。使用 **drawing_bitmap.h** 的 **OH_Drawing_BitmapCreate** 接口创建一个Bitmap实例 **cBitmap**,并使用 **OH_Drawing_BitmapBuild** 指定其长宽大小和像素格式。 @@ -137,7 +137,7 @@ Native Drawing模块提供了一系列的接口用于基本图形和字体的绘 ## 文本绘制开发步骤 -以下步骤描述了在OpenHarmony中,如何使用**Native Drawing**模块的文字显示功能: +以下步骤描述了如何使用**Native Drawing**模块的文字显示功能: 1. **创建画布和bitmap实例**。 ```c++ diff --git a/zh-cn/application-dev/napi/mindspore-lite-guidelines.md b/zh-cn/application-dev/napi/mindspore-lite-guidelines.md index f0a2a4db4bf4653a1e9cf57f4d775b6aa6e45522..dc189e94acab9d6b5722914bce4b6f4d78145257 100644 --- a/zh-cn/application-dev/napi/mindspore-lite-guidelines.md +++ b/zh-cn/application-dev/napi/mindspore-lite-guidelines.md @@ -265,8 +265,8 @@ int GenerateInputDataWithRandom(OH_AI_TensorHandleArray inputs) { 2. 运行。 - - 使用hdc_std连接rk3568开发板,并将demo和mobilenetv2.ms推送到设备中的相同目录。 - - 使用hdc_std shell进入开发板,并进入demo所在的目录执行如下命令,即可得到结果。 + - 使用hdc_std连接设备,并将demo和mobilenetv2.ms推送到设备中的相同目录。 + - 使用hdc_std shell进入设备,并进入demo所在的目录执行如下命令,即可得到结果。 ```shell ./demo mobilenetv2.ms diff --git a/zh-cn/application-dev/napi/native-buffer-guidelines.md b/zh-cn/application-dev/napi/native-buffer-guidelines.md index 59309b082a1f4781240f08eeb21e84ee973bbfd3..7af175b902f6209242112d0e14cc97dfd76398af 100644 --- a/zh-cn/application-dev/napi/native-buffer-guidelines.md +++ b/zh-cn/application-dev/napi/native-buffer-guidelines.md @@ -2,7 +2,7 @@ ## 场景介绍 -NativeBuffer是`OpenHarmony`提供**共享内存**的模块。开发者可以通过`NativeBuffer`接口实现共享内存的申请、使用、属性查询、释放等操作。 +NativeBuffer是提供**共享内存**的模块。开发者可以通过`NativeBuffer`接口实现共享内存的申请、使用、属性查询、释放等操作。 针对NativeBuffer,常见的开发场景如下: * 通过`NativeBuffer`提供的Native API接口申请`OH_NativeBuffer`实例,获取内存的属性信息,把对应的ION内存映射到进程空间。 @@ -23,7 +23,7 @@ NativeBuffer是`OpenHarmony`提供**共享内存**的模块。开发者可以通 ## 开发步骤 -以下步骤描述了在**OpenHarmony**中如何使用`NativeBuffer`提供的Native API接口,创建`OH_NativeBuffer`实例获取内存的属性信息,并把对应的ION内存映射到进程空间。 +以下步骤描述了如何使用`NativeBuffer`提供的Native API接口,创建`OH_NativeBuffer`实例获取内存的属性信息,并把对应的ION内存映射到进程空间。 **添加动态链接库** diff --git a/zh-cn/application-dev/napi/native-image-guidelines.md b/zh-cn/application-dev/napi/native-image-guidelines.md index c9608b8543235f62099288126d6488427e6135e2..db907bd005b61e3590b8c97de7943604c81d92cb 100644 --- a/zh-cn/application-dev/napi/native-image-guidelines.md +++ b/zh-cn/application-dev/napi/native-image-guidelines.md @@ -2,7 +2,7 @@ ## 场景介绍 -NativeImage是`OpenHarmony`提供**Surface关联OpenGL外部纹理**的模块,表示图形队列的消费者端。开发者可以通过`NativeImage`接口接收和使用`Buffer`,并将`Buffer`关联输出到OpenGL外部纹理。 +NativeImage是提供**Surface关联OpenGL外部纹理**的模块,表示图形队列的消费者端。开发者可以通过`NativeImage`接口接收和使用`Buffer`,并将`Buffer`关联输出到OpenGL外部纹理。 针对NativeImage,常见的开发场景如下: * 通过`NativeImage`提供的Native API接口创建`NativeImage`实例作为消费者端,获取与该实例对应的`NativeWindow`作为生产者端。`NativeWindow`相关接口可用于填充`Buffer`内容并提交,`NativeImage`将`Buffer`内容更新到OpenGL外部纹理上。本模块需要配合NativeWindow、NativeBuffer、EGL、GLES3模块一起使用。 @@ -24,7 +24,7 @@ NativeImage是`OpenHarmony`提供**Surface关联OpenGL外部纹理**的模块, ## 开发步骤 -以下步骤描述了在**OpenHarmony**中如何使用`NativeImage`提供的Native API接口,创建`OH_NativeImage`实例作为消费者端,将数据内容更新到OpenGL外部纹理上。 +以下步骤描述了如何使用`NativeImage`提供的Native API接口,创建`OH_NativeImage`实例作为消费者端,将数据内容更新到OpenGL外部纹理上。 **添加动态链接库** diff --git a/zh-cn/application-dev/napi/native-vsync-guidelines.md b/zh-cn/application-dev/napi/native-vsync-guidelines.md index 9e0c68bd95332241dba2dec9d94552b6f216dbcb..4d48e15d2cfe4507b6c5a200825771343cea05a9 100644 --- a/zh-cn/application-dev/napi/native-vsync-guidelines.md +++ b/zh-cn/application-dev/napi/native-vsync-guidelines.md @@ -17,7 +17,7 @@ NativeVsync模块用来获取系统VSync信号,提供了OH_NativeVSync实例 ## 开发步骤 -以下步骤描述了在**OpenHarmony**中如何使用`NativeVsync`提供的Native API接口,创建和销毁`OH_NativeVsync`实例,以及如何设置VSync回调函数。 +以下步骤描述了如何使用`NativeVsync`提供的Native API接口,创建和销毁`OH_NativeVsync`实例,以及如何设置VSync回调函数。 **添加动态链接库** diff --git a/zh-cn/application-dev/napi/native-window-guidelines.md b/zh-cn/application-dev/napi/native-window-guidelines.md index acdfedde2aea97e7e7c95372ff2e295696ec8323..8b86276da19eae3aa3fbc3ec0020cee611d1b0a4 100644 --- a/zh-cn/application-dev/napi/native-window-guidelines.md +++ b/zh-cn/application-dev/napi/native-window-guidelines.md @@ -2,7 +2,7 @@ ## 场景介绍 -NativeWindow是`OpenHarmony`**本地平台化窗口**,表示图形队列的生产者端。开发者可以通过`NativeWindow`接口进行申请和提交`Buffer`,配置`Buffer`属性信息。 +NativeWindow是**本地平台化窗口**,表示图形队列的生产者端。开发者可以通过`NativeWindow`接口进行申请和提交`Buffer`,配置`Buffer`属性信息。 针对NativeWindow,常见的开发场景如下: * 通过`NativeWindow`提供的Native API接口申请图形`Buffer`,并将生产图形内容写入图形`Buffer`,最终提交`Buffer`到图形队列 @@ -20,7 +20,7 @@ NativeWindow是`OpenHarmony`**本地平台化窗口**,表示图形队列的生 ## 开发步骤 -以下步骤描述了在**OpenHarmony**中如何使用`NativeWindow`提供的Native API接口,申请图形`Buffer`,并将生产图形内容写入图形`Buffer`后,最终提交`Buffer`到图形队列。 +以下步骤描述了如何使用`NativeWindow`提供的Native API接口,申请图形`Buffer`,并将生产图形内容写入图形`Buffer`后,最终提交`Buffer`到图形队列。 **添加动态链接库** diff --git a/zh-cn/application-dev/napi/neural-network-runtime-guidelines.md b/zh-cn/application-dev/napi/neural-network-runtime-guidelines.md index bdde437188c2cc9a9da8ddbdcb2b2eec1056c61b..d05f540dd98779e89b1fa587a6f3b71288e536f5 100644 --- a/zh-cn/application-dev/napi/neural-network-runtime-guidelines.md +++ b/zh-cn/application-dev/napi/neural-network-runtime-guidelines.md @@ -19,7 +19,7 @@ Neural Network Runtime部件的环境要求如下: - 开发环境:Ubuntu 18.04及以上。 - 接入设备:OpenHarmony定义的标准设备,并且系统中内置的硬件加速器驱动,已通过HDI接口对接Neural Network Runtime。 -由于Neural Network Runtime通过OpenHarmony Native API对外开放,需要通过OpenHarmony的Native开发套件编译Neural Network Runtime应用。 +由于Neural Network Runtime通过Native API对外开放,需要通过Native开发套件编译Neural Network Runtime应用。 ### 环境搭建 diff --git a/zh-cn/application-dev/napi/usb-ddk-guidelines.md b/zh-cn/application-dev/napi/usb-ddk-guidelines.md index 9bef6a793dfc93f9dc0cd5763e61157d17fbc7e7..d3d8a45ac970bb9fc35c3cc5a948731765bca31e 100644 --- a/zh-cn/application-dev/napi/usb-ddk-guidelines.md +++ b/zh-cn/application-dev/napi/usb-ddk-guidelines.md @@ -2,7 +2,7 @@ ## 场景介绍 -USB DDK(USB Driver Develop Kit)是OpenHarmony为开发者提供的USB驱动程序开发套件,支持开发者基于用户态,在应用层开发USB设备驱动。提供了一系列主机侧访问设备的接口,包括主机侧打开和关闭接口、管道同步异步读写通信、控制传输、中断传输等。 +USB DDK(USB Driver Develop Kit)是为开发者提供的USB驱动程序开发套件,支持开发者基于用户态,在应用层开发USB设备驱动。提供了一系列主机侧访问设备的接口,包括主机侧打开和关闭接口、管道同步异步读写通信、控制传输、中断传输等。 ## 接口说明 @@ -23,7 +23,7 @@ USB DDK(USB Driver Develop Kit)是OpenHarmony为开发者提供的USB驱动 ## USB DDK开发步骤 -以下步骤描述了在**OpenHarmony**如何使用 **USB DDK**开发USB驱动: +以下步骤描述了如何使用 **USB DDK**开发USB驱动: 1. **获取设备描述符**。使用 **usb_ddk_api.h** 的 **OH_Usb_Init** 接口初始化DDK,并使用 **OH_Usb_GetDeviceDescriptor**获取到设备描述符。 diff --git a/zh-cn/application-dev/napi/vulkan-guidelines.md b/zh-cn/application-dev/napi/vulkan-guidelines.md index bc14fbe7a73ef93eb52de1795bdc6f0d0837b511..95da4d0a4660a3df91725794c4493b4041d89679 100644 --- a/zh-cn/application-dev/napi/vulkan-guidelines.md +++ b/zh-cn/application-dev/napi/vulkan-guidelines.md @@ -16,9 +16,9 @@ Vulkan是一套用来做2D和3D渲染的图形应用程序接口,其中创建V ## 开发步骤 -以下步骤说明了如何在OpenHarmony平台创建一个VkSurfaceKHR对象。 +以下步骤说明了如何创建一个VkSurfaceKHR对象。 -首先,使用OpenHarmony平台扩展的接口,需要定义一个宏`VK_USE_PLATFORM_OHOS`,我们在CMakeLists.txt定义这个宏。 +首先,使用平台扩展的接口,需要定义一个宏`VK_USE_PLATFORM_OHOS`,我们在CMakeLists.txt定义这个宏。 ```txt ADD_DEFINITIONS(-DVK_USE_PLATFORM_OHOS=1) ``` @@ -56,7 +56,7 @@ libvulkan.so std::vector instanceExtensions = { VK_KHR_SURFACE_EXTENSION_NAME, - VK_OHOS_SURFACE_EXTENSION_NAME // OpenHarmony平台的Surface扩展 + VK_OHOS_SURFACE_EXTENSION_NAME // Surface扩展 }; instanceCreateInfo.enabledExtensionCount = static_cast(instanceExtensions.size()); instanceCreateInfo.ppEnabledExtensionNames = instanceExtensions.data(); diff --git a/zh-cn/application-dev/notification/notification-with-wantagent.md b/zh-cn/application-dev/notification/notification-with-wantagent.md index 3cc82b5c38e202d22321874b1b31034fa43ae324..e187b37e95ca008b4f88689a6e53537732dfbf8b 100644 --- a/zh-cn/application-dev/notification/notification-with-wantagent.md +++ b/zh-cn/application-dev/notification/notification-with-wantagent.md @@ -39,7 +39,7 @@ 场景一:创建拉起UIAbility的WantAgent的[WantAgentInfo](../reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md)信息。 ```typescript - let wantAgentObj:WantAgent = null; // 用于保存创建成功的wantAgent对象,后续使用其完成触发的动作。 + let wantAgentObj:WantAgent; // 用于保存创建成功的wantAgent对象,后续使用其完成触发的动作。 // 通过WantAgentInfo的operationType设置动作类型 let wantAgentInfo:wantAgent.WantAgentInfo = { @@ -63,7 +63,7 @@ 场景二:创建发布[公共事件](../application-models/common-event-overview.md)的WantAgent的[WantAgentInfo](../reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md)信息。 ```typescript - let wantAgentObj:WantAgent = null; // 用于保存创建成功的WantAgent对象,后续使用其完成触发的动作。 + let wantAgentObj:WantAgent; // 用于保存创建成功的WantAgent对象,后续使用其完成触发的动作。 // 通过WantAgentInfo的operationType设置动作类型 let wantAgentInfo:wantAgent.WantAgentInfo = { diff --git a/zh-cn/application-dev/performance/improve-application-startup-and-response/improve-application-cold-start-speed.md b/zh-cn/application-dev/performance/improve-application-startup-and-response/improve-application-cold-start-speed.md index dbb87f4612f671489bea67fbee6013e22f6fbb29..daad5a996516e5d43594c3dc08211cb09e937726 100644 --- a/zh-cn/application-dev/performance/improve-application-startup-and-response/improve-application-cold-start-speed.md +++ b/zh-cn/application-dev/performance/improve-application-startup-and-response/improve-application-cold-start-speed.md @@ -69,12 +69,12 @@ OpenHarmony的应用冷启动过程大致可分成以下四个阶段:应用进 aboutToAppear函数会在创建自定义组件实例后,页面绘制之前执行,以下代码在aboutToAppear中对耗时长的计算任务进行了异步处理,避免在该接口执行该耗时操作,不阻塞页面绘制。 -```javascript +```typescript @Entry @Component struct Index { - @State private text: string = undefined; - private count: number = undefined; + @State private text: string = ""; + private count: number = 0; aboutToAppear() { this.computeTaskAsync(); // 异步任务 @@ -100,11 +100,9 @@ struct Index { // 运算任务异步处理 private computeTaskAsync() { - new Promise((resolved, rejected) => { - setTimeout(() => { // 这里使用setTimeout来实现异步延迟运行 - this.computeTask(); - }, 1000) - }) + setTimeout(() => { // 这里使用setTimeout来实现异步延迟运行 + this.computeTask(); + }, 1000) } } ``` \ No newline at end of file diff --git a/zh-cn/application-dev/performance/improve-application-startup-and-response/improve-application-response.md b/zh-cn/application-dev/performance/improve-application-startup-and-response/improve-application-response.md index acd7a634b8855d8de10a7fa0162d27d81f164b32..b21b23596146c7885b6f6a3d7f98b5c7ecc01b70 100644 --- a/zh-cn/application-dev/performance/improve-application-startup-and-response/improve-application-response.md +++ b/zh-cn/application-dev/performance/improve-application-startup-and-response/improve-application-response.md @@ -13,7 +13,7 @@ OpenHarmony提供的Image组件默认生效异步加载特性,当应用在页面上展示一批本地图片的时候,会先显示空白占位块,当图片在其他线程加载完毕后,再替换占位块。这样图片加载就可以不阻塞页面的显示,给用户带来良好的交互体验。因此,只在加载图片耗时比较短的情况下建议下述代码。 -```javascript +```typescript @Entry @Component struct ImageExample1 { @@ -37,10 +37,10 @@ struct ImageExample1 { 建议:在加载图片的耗时比较短的时候,通过异步加载的效果会大打折扣,建议配置Image的syncLoad属性。 -```javascript +```typescript @Entry @Component -struct ImageExample1 { +struct ImageExample2 { build() { Column() { Row() { @@ -63,7 +63,7 @@ struct ImageExample1 { OpenHarmony提供了[TaskPool线程池](../../reference/apis/js-apis-taskpool.md),相比worker线程,TaskPool提供了任务优先级设置、线程池自动管理机制,示例如下: -```javascript +```typescript import taskpool from '@ohos.taskpool'; @Concurrent @@ -78,7 +78,7 @@ function computeTask(arr: string[]): string[] { @Entry @Component -struct AspectRatioExample { +struct AspectRatioExample3 { @State children: string[] = ['1', '2', '3', '4', '5', '6']; aboutToAppear() { @@ -88,8 +88,7 @@ struct AspectRatioExample { async computeTaskInTaskPool() { const param = this.children.slice(); let task = new taskpool.Task(computeTask, param); - // @ts-ignore - this.children = await taskpool.execute(task); + await taskpool.execute(task); } build() { @@ -102,12 +101,12 @@ struct AspectRatioExample { 以下代码展示了将一个长时间执行的非UI任务通过Promise声明成异步任务,主线程可以先进行用户反馈-绘制初始页面。等主线程空闲时,再执行异步任务。等到异步任务运行完毕后,重绘相关组件刷新页面。 -```javascript +```typescript @Entry @Component -struct AspectRatioExample { +struct AspectRatioExample4 { @State private children: string[] = ['1', '2', '3', '4', '5', '6']; - private count: number = undefined; + private count: number = 0; aboutToAppear() { this.computeTaskAsync(); // 调用异步运算函数 @@ -123,11 +122,9 @@ struct AspectRatioExample { } computeTaskAsync() { - new Promise((resolved, rejected) => { - setTimeout(() => { // 这里使用setTimeout来实现异步延迟运行 - this.computeTask(); - }, 1000) - }) + setTimeout(() => { // 这里使用setTimeout来实现异步延迟运行 + this.computeTask(); + }, 1000) } build() { @@ -146,10 +143,10 @@ struct AspectRatioExample { 以下代码的Text('New Page')组件被状态变量isVisible控制,isVisible为true时创建,false时销毁。当isVisible发生变化时,Stack容器内的所有组件都会刷新: -```javascript +```typescript @Entry @Component -struct StackExample { +struct StackExample5 { @State isVisible : boolean = false; build() { @@ -175,10 +172,10 @@ struct StackExample { 建议:对于这种受状态变量控制的组件,在if外套一层容器,减少刷新范围。 -```javascript +```typescript @Entry @Component -struct StackExample { +struct StackExample6 { @State isVisible : boolean = false; build() { @@ -208,11 +205,11 @@ struct StackExample { 反例:this.arr中的每一项元素都被初始化和加载,数组中的元素有10000个,主线程执行耗时长。 -```javascript +```typescript @Entry @Component -struct MyComponent { - @State arr: number[] = Array.from(Array(10000), (v,k) =>k); +struct MyComponent7 { + @State arr: number[] = Array.from(Array(10000), (v,k) =>k); build() { List() { ForEach(this.arr, (item: number) => { @@ -227,7 +224,7 @@ struct MyComponent { 建议:这种情况下用LazyForEach替换ForEach,LazyForEach一般只加载可见的元素,避免一次性初始化和加载所有元素。 -```javascript +```typescript class BasicDataSource implements IDataSource { private listeners: DataChangeListener[] = [] @@ -235,8 +232,8 @@ class BasicDataSource implements IDataSource { return 0 } - public getData(index: number): any { - return undefined + public getData(index: number): string { + return '' } registerDataChangeListener(listener: DataChangeListener): void { @@ -286,13 +283,13 @@ class BasicDataSource implements IDataSource { } class MyDataSource extends BasicDataSource { - private dataArray: string[] = Array.from(Array(10000), (v, k) => k.toString()); + private dataArray: string[] = Array.from(Array(10000), (v, k) => k.toString()); public totalCount(): number { return this.dataArray.length } - public getData(index: number): any { + public getData(index: number): string { return this.dataArray[index] } @@ -318,7 +315,7 @@ struct MyComponent { ListItem() { Text(item).fontSize(20).margin({ left: 10 }) } - }, item => item) + }, (item:string) => item) } } } diff --git a/zh-cn/application-dev/performance/reduce-frame-loss-and-frame-freezing/reduce-animation-frame-loss.md b/zh-cn/application-dev/performance/reduce-frame-loss-and-frame-freezing/reduce-animation-frame-loss.md index caaf5d22815504e5293e0a1a5990ed56a363a9c0..8e677d2e542d663f00b7ffaacc0a5fbab8b140b5 100644 --- a/zh-cn/application-dev/performance/reduce-frame-loss-and-frame-freezing/reduce-animation-frame-loss.md +++ b/zh-cn/application-dev/performance/reduce-frame-loss-and-frame-freezing/reduce-animation-frame-loss.md @@ -6,7 +6,7 @@ 反例:应用使用了自定义动画,动画曲线计算过程很容易引起UI线程高负载,易导致丢帧。 -```javascript +```typescript @Entry @Component struct AttrAnimationExample { @@ -17,8 +17,8 @@ struct AttrAnimationExample { computeSize() { let duration = 2000 let period = 16 - let widthSizeEnd = undefined - let heightSizeEnd = undefined + let widthSizeEnd = 0 + let heightSizeEnd = 0 if (this.flag) { widthSizeEnd = 100 heightSizeEnd = 50 @@ -56,7 +56,7 @@ struct AttrAnimationExample { 建议:通过系统提供的属性动效API实现上述动效功能。 -```javascript +```typescript @Entry @Component struct AttrAnimationExample { @@ -67,7 +67,7 @@ struct AttrAnimationExample { build() { Column() { Button('click me') - .onClick((event: ClickEvent) => { + .onClick((event?: ClickEvent | undefined) => { if (this.flag) { this.widthSize = 100 this.heightSize = 50 @@ -96,7 +96,7 @@ struct AttrAnimationExample { 建议:通过系统提供的显式动效API实现上述动效功能。 -```javascript +```typescript @Entry @Component struct AnimateToExample { @@ -107,7 +107,7 @@ struct AnimateToExample { build() { Column() { Button('click me') - .onClick((event: ClickEvent) => { + .onClick((event?: ClickEvent | undefined) => { if (this.flag) { animateTo({ duration: 2000, // 动画时长 diff --git a/zh-cn/application-dev/performance/reduce-frame-loss-and-frame-freezing/reduce-view-nesting-levels.md b/zh-cn/application-dev/performance/reduce-frame-loss-and-frame-freezing/reduce-view-nesting-levels.md index ab4cf3697a3fdf5a9033019112b9d732ec05a401..c9337880dfaa220cfbac775d5586517ed6458c55 100644 --- a/zh-cn/application-dev/performance/reduce-frame-loss-and-frame-freezing/reduce-view-nesting-levels.md +++ b/zh-cn/application-dev/performance/reduce-frame-loss-and-frame-freezing/reduce-view-nesting-levels.md @@ -6,16 +6,16 @@ 反例:使用了Grid来实现一个网格,但是在外层套了3层stack容器,导致组件刷新和渲染耗时长。 -```javascript +```typescript @Entry @Component -struct AspectRatioExample { - @State children: Number[] = Array.from(Array(900), (v, k) => k); +struct AspectRatioExample12 { + @State children: Number[] = Array.from(Array(900), (v, k) => k); build() { Scroll() { Grid() { - ForEach(this.children, (item) => { + ForEach(this.children, (item:Number[]) => { GridItem() { Stack() { Stack() { @@ -25,7 +25,7 @@ struct AspectRatioExample { } } } - }, item => item) + }, (item:string) => item) } .columnsTemplate('1fr 1fr 1fr 1fr') .columnsGap(0) @@ -38,21 +38,20 @@ struct AspectRatioExample { 建议:通过减少冗余的Stack容器嵌套,每个GridItem的组件数比上面少了3个,缩短了组件刷新与渲染耗时。 -```javascript -// xxx.ets +```typescript @Entry @Component -struct AspectRatioExample { +struct AspectRatioExample11 { @State children: Number[] = Array.from(Array(900), (v, k) => k); build() { Scroll() { Grid() { - ForEach(this.children, (item) => { + ForEach(this.children, (item:Number[]) => { GridItem() { Text(item.toString()) } - }, item => item) + }, (item:string) => item) } .columnsTemplate('1fr 1fr 1fr 1fr') .columnsGap(0) diff --git a/zh-cn/application-dev/quick-start/arkts-prop.md b/zh-cn/application-dev/quick-start/arkts-prop.md index 12b19eac88c0acf63342cc0aeb93cab0f678044c..e32d877edfb3bbb3d2e3f25d6a18407348f69829 100644 --- a/zh-cn/application-dev/quick-start/arkts-prop.md +++ b/zh-cn/application-dev/quick-start/arkts-prop.md @@ -188,7 +188,7 @@ struct ParentComponent { ### 父组件\@State到子组件\@Prop简单数据类型同步 -以下示例是\@State到子组件\@Prop简单数据同步,父组件ParentComponent的状态变量countDownStartValue初始化子组件CountDownComponent中\@Prop装饰的count,点击“Try again”,count的修改仅保留在CountDownComponent 不会同步给父组件CountDownComponent。 +以下示例是\@State到子组件\@Prop简单数据同步,父组件ParentComponent的状态变量countDownStartValue初始化子组件CountDownComponent中\@Prop装饰的count,点击“Try again”,count的修改仅保留在CountDownComponent 不会同步给父组件ParentComponent。 ParentComponent的状态变量countDownStartValue的变化将重置CountDownComponent的count。 diff --git a/zh-cn/application-dev/quick-start/arkts-rendering-control-foreach.md b/zh-cn/application-dev/quick-start/arkts-rendering-control-foreach.md index 2c8efbc10d2ed4eaab9227bf3c90965ed11be90e..d7bc20406b6b98585ca5fdc81614485c756b25b6 100644 --- a/zh-cn/application-dev/quick-start/arkts-rendering-control-foreach.md +++ b/zh-cn/application-dev/quick-start/arkts-rendering-control-foreach.md @@ -36,21 +36,21 @@ ForEach( - itemGenerator函数的调用顺序不一定和数组中的数据项相同,在开发过程中不要假设itemGenerator和keyGenerator函数是否执行及其执行顺序。例如,以下示例可能无法正确运行: - ```ts -let obj: Object -ForEach(anArray.map((item1: Object, index1: number): Object => { - obj.i = index1 + 1 - obj.data = item1 - return obj; - }), -(item: string) => Text(`${item.i}. item.data.label`), -(item: string): string => { - return item.data.id.toString() -}) - ``` - - -## 开发者的建议 + ```ts + let obj: Object + ForEach(anArray.map((item1: Object, index1: number): Object => { + obj.i = index1 + 1 + obj.data = item1 + return obj; + }), + (item: string) => Text(`${item.i}. item.data.label`), + (item: string): string => { + return item.data.id.toString() + }) + ``` + + +## 开发建议 - 建议开发者不要假设项构造函数的执行顺序。执行顺序可能不能是数组中项的排列顺序。 diff --git a/zh-cn/application-dev/quick-start/in-app-hsp.md b/zh-cn/application-dev/quick-start/in-app-hsp.md index d6b6a264c3ba64ed167630eafa71621f7560b514..1cb1d9f4c66b3a9a40bd7f85e0bc43210f01e271 100644 --- a/zh-cn/application-dev/quick-start/in-app-hsp.md +++ b/zh-cn/application-dev/quick-start/in-app-hsp.md @@ -71,7 +71,7 @@ export { MyTitleBar } from './components/MyTitleBar' ### 通过$r访问HSP中资源 在组件中,经常需要使用字符串、图片等资源。HSP中的组件需要使用资源时,一般将其所用资源放在HSP包内,而非放在HSP的使用方处,以符合高内聚低耦合的原则。 -在工程中,常通过`$r`/`$rawfile`的形式引用应用资源。可以用`$r`/`$rawfile`访问本模块`resources`目录下的资源,如访问`resources`目录下定义的图片`src/main/resources/base/media/example.png`时,可以用`$r("app.media.example")`。有关`$r`/`$rawfile`的详细使用方式,请参阅文档[资源分类与访问](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/quick-start/resource-categories-and-access.md)中“资源访问-应用资源”小节。 +在工程中,常通过`$r`/`$rawfile`的形式引用应用资源。可以用`$r`/`$rawfile`访问本模块`resources`目录下的资源,如访问`resources`目录下定义的图片`src/main/resources/base/media/example.png`时,可以用`$r("app.media.example")`。有关`$r`/`$rawfile`的详细使用方式,请参阅文档[资源分类与访问](./resource-categories-and-access.md)中“资源访问-应用资源”小节。 不推荐使用相对路径的方式,容易引用错误路径。例如: 当要引用上述同一图片资源时,在HSP模块中使用`Image("../../resources/base/media/example.png")`,实际上该`Image`组件访问的是HSP调用方(如`entry`)下的资源`entry/src/main/resources/base/media/example.png`。 diff --git a/zh-cn/application-dev/quick-start/typescript-to-arkts-migration-guide.md b/zh-cn/application-dev/quick-start/typescript-to-arkts-migration-guide.md index 9b3f5c465425e460dbc17728550509929aa1ba5e..4497a9775dca7274e4f1f08dd572e8bc85f0a9ed 100644 --- a/zh-cn/application-dev/quick-start/typescript-to-arkts-migration-guide.md +++ b/zh-cn/application-dev/quick-start/typescript-to-arkts-migration-guide.md @@ -3,10 +3,10 @@ 本文通过提供简洁的约束指导如何将标准的TypeScript代码重构为ArkTS代码。尽管ArkTS是基于TypeScript设计的,但出于性能考虑,一些TypeScript的特性被限制了。因此,在ArkTS中,所有的TypeScript特性被分成三类。 1. **完全支持的特性**:原始代码无需任何修改。根据测试,对于已遵循最佳TypeScript实践的项目,代码库中90%到97%的内容可以保持原封不动。 -2. **部分支持的特性**:需小规模的代码重构。例如,必须使用关键字`let`代替`var`来声明变量。注意,根据本文提供的约束进行代码重构后,您的代码仍为有效的TypeScript代码。 +2. **部分支持的特性**:需小规模的代码重构。例如,必须使用关键字`let`代替`var`来声明变量。 3. **不支持的特性**:需大规模的代码重构。例如,不支持`any`类型,所有使用`any`的代码都需要引入显式类型。 -本文将逐一介绍所有部分支持和所有不支持的特性,并提供代码重构的建议。对于没有提到的特性,则说明ArkTS完全支持。 +本文将逐一介绍所有部分支持和所有不支持的特性,并提供代码重构的建议。根据本文提供的约束进行代码重构后代码仍为有效的TypeScript代码。对于没有提到的特性,则说明ArkTS完全支持。 **示例** @@ -49,7 +49,7 @@ ArkTS在设计之初,就确定了如下目标: - ArkTS代码需非常容易阅读和理解,因为代码的阅读频率高于编写频率。 - 以最小功耗快速执行代码,这点对于移动设备(ArkTS的目标设备)来说至关重要。 -静态类型是ArkTS最重要的特性之一。使用静态类型有助于实现上述两个目标。如果程序采用静态类型,即所有类型在编译时都是已知的,那么开发者就能够容易理解代码中使用了哪些数据结构。同时,由于所有类型在程序实际运行前都是已知的,编译器可以提前验证代码的正确性,从而可以减少运行时类型检查项,有助于性能提升。 +静态类型是ArkTS最重要的特性之一。使用静态类型有助于实现上述两个目标。如果程序采用静态类型,即所有类型在编译时都是已知的,那么开发者就能够容易理解代码中使用了哪些数据结构。同时,由于所有类型在程序实际运行前都是已知的,编译器可以提前验证代码的正确性,从而可以减少运行时的类型检查,有助于性能提升。 基于上述考虑,ArkTS中禁止使用`any`类型。 @@ -107,24 +107,24 @@ class Point { // 无法从对象中删除某个属性,从而确保所有Point对象都具有属性x: let p1 = new Point(1.0, 1.0) -delete p1.x // 无论使用TypeScript还是ArkTS,都会产生编译时错误 -delete (p1 as any).x // 使用TypeScript时,不会报错;使用ArkTS时,会产生编译时错误 +delete p1.x // 在TypeScript和ArkTS中,都会产生编译时错误 +delete (p1 as any).x // 在TypeScript中不会报错;在ArkTS中会产生编译时错误 -// Point类没有定义命名为`z`的属性,在程序运行时也无法添加该属性: +// Point类没有定义命名为z的属性,在程序运行时也无法添加该属性: let p2 = new Point(2.0, 2.0) -p2.z = "Label"; // 无论使用TypeScript还是ArkTS,都会产生编译时错误 -(p2 as any).z = "Label" // 使用TypeScript时,不会报错;使用ArkTS时,会产生编译时错误 +p2.z = "Label"; // 在TypeScript和ArkTS中,都会产生编译时错误 +(p2 as any).z = "Label" // 在TypeScript中不会报错;在ArkTS中会产生编译时错误 -// 确保所有Point对象只有属性x和y,并且无法产生一些任意标识符并将其用作新属性: +// 类的定义确保了所有Point对象只有属性x和y,并且无法被添加其他属性: let p3 = new Point(3.0, 3.0) -let prop = Symbol(); // 使用TypeScript时,不会报错;使用ArkTS时,会产生编译时错误 -(p3 as any)[prop] = p3.x // 使用TypeScript时,不会报错;使用ArkTS时,会产生编译时错误 -p3[prop] = p3.x // 无论使用TypeScript还是ArkTS,都会产生编译时错误 +let prop = Symbol(); // 在TypeScript中不会报错;在ArkTS中会产生编译时错误 +(p3 as any)[prop] = p3.x // 在TypeScript中不会报错;在ArkTS中会产生编译时错误 +p3[prop] = p3.x // 在TypeScript和ArkTS中,都会产生编译时错误 -// 确保所有Point对象都具有number类型的属性x和y。因此,无法赋予其他类型的值给该属性: +// 类的定义确保了所有Point对象的属性x和y都具有number类型,因此,无法将其他类型的值赋值给它们: let p4 = new Point(4.0, 4.0) -p4.x = "Hello!"; // 无论使用TypeScript还是ArkTS,都会产生编译时错误 -(p4 as any).x = "Hello!" // 使用TypeScript时,不会报错;使用ArkTS时,会产生编译时错误 +p4.x = "Hello!"; // 在TypeScript和ArkTS中,都会产生编译时错误 +(p4 as any).x = "Hello!" // 在TypeScript中不会报错;在ArkTS中会产生编译时错误 // 使用符合类定义的Point对象: function distance(p1 : Point, p2 : Point) : number { @@ -148,22 +148,18 @@ console.log("Distance between p5 and p6: " + distance(p5, p6)) **示例** ```typescript -// 运算符`+`可以用于数字和字符串,但不能用于其他类型: -class C { - // ... -} -let c1 : C = new C() -let c2 : C = new C() -console.log(c1 + c2) // 编译时报错 +// 一元运算符`+`只能作用于数值类型: +console.log(+42) // 合法运算 +console.log(+"42") // 编译时错误 ``` 使用额外的语义重载语言运算符会增加语言规范的复杂度,而且,开发者还被迫牢记所有可能的例外情况及对应的处理规则。在某些情况下,产生一些不必要的运行时开销。 当前只有不到1%的代码库使用该特性。因此,尽管限制运算符的语义需要重构代码,但重构量很小且非常容易操作,并且,通过重构能使代码更清晰、具备更高性能。 -### (暂时)不支持 structural typing +### 不支持 structural typing -假设两个不相关的类`T`和`U`拥有相同的公共API: +假设两个不相关的类`T`和`U`拥有相同的`public`API: ```typescript class T { @@ -203,8 +199,8 @@ greeter(t) // 是否允许? 换句话说,我们将采取下面哪种方法呢: -- `T`和`U`没有继承关系或没有任何公共接口,但由于它们具有相同的公共API,它们“在某种程度上是相等的”,所以上述两个问题的答案都是“是”; -- `T`和`U`没有继承关系或没有任何公共接口,应当始终被视为完全不同的类型,因此上述两个问题的答案都是“否”。 +- `T`和`U`没有继承关系或没有`implements`相同的接口,但由于它们具有相同的`public`API,它们“在某种程度上是相等的”,所以上述两个问题的答案都是“是”; +- `T`和`U`没有继承关系或没有`implements`相同的接口,应当始终被视为完全不同的类型,因此上述两个问题的答案都是“否”。 采用第一种方法的语言支持structural typing,而采用第二种方法的语言则不支持structural typing。目前TypeScript支持structural typing,而ArkTS不支持。 @@ -254,12 +250,11 @@ console.log(z.get(2)) **相关约束** * 不支持Symbol() API -* 访问未定义的属性将导致编译时错误 +* 不支持通过索引访问字段 * 不支持delete运算符 * 仅允许在表达式中使用typeof运算符 * 不支持in运算符 * 禁止运行时检查对象属性 -* 不支持声明动态属性 * 限制使用标准库 @@ -271,6 +266,8 @@ console.log(z.get(2)) TypeScript中的`Symbol()`API用于在运行时生成唯一的属性名称。由于该API的常见使用场景在静态类型语言中没有意义,因此,ArkTS不支持`Symbol()`API。在ArkTS中,对象布局在编译时就确定了,且不能在运行时被更改。 +ArkTS也不支持`Symbol.iterator`和`Iterable interface`。请使用数组或容器。 + **TypeScript** ```typescript @@ -278,6 +275,26 @@ const sym = Symbol() let o = { [sym]: "value" } + +let obj = { + data: ['a', 'b', 'c'], + [Symbol.iterator]() { + const this_ = this + let index = 0 + return { + next() { + return { + done: index >= this_.data.length, + value: 'name_' + this_.data[index++] + } + } + } + } +} + +for (let t of obj) { + console.log(t) +} ``` **ArkTS** @@ -287,17 +304,21 @@ class SomeClass { public someProperty : string = "" } let o = new SomeClass() + +let arr:string[] = ['a', 'b', 'c'] +for (let t of arr) { + console.log('name_' + t) +} ``` **相关约束** * 仅支持属性名为标识符的对象 -* 访问未定义的属性将导致编译时错误 +* 不支持通过索引访问字段 * 不支持delete运算符 * 仅允许在表达式中使用typeof运算符 * 不支持in运算符 * 禁止运行时检查对象属性 -* 不支持声明动态属性 * 限制使用标准库 ### 不支持以`#`开头的私有字段 @@ -324,13 +345,13 @@ class C { } ``` -### 类型、命名空间等的命名必须唯一 +### 类型、命名空间的命名必须唯一 **规则:**`arkts-unique-names` **级别:错误** -类型、命名空间等的命名必须唯一,且能够与其他名称(例如:变量名)区分开来。 +类型(类、接口、枚举)、命名空间的命名必须唯一,且与其他名称(例如:变量名、函数名)不同。 **TypeScript** @@ -830,97 +851,100 @@ class Point {x: number = 0; y: number = 0} type N = number ``` -### 不支持索引访问字段 +### 不支持通过索引访问字段 **规则:**`arkts-no-props-by-index` **级别:错误** -ArkTS不支持通过索引访问对象的字段。改用点操作符。 +ArkTS不支持动态声明字段,不支持动态访问字段。只能访问已在类中声明或者继承可见的字段,访问其他字段将会造成编译时错误。 +使用点操作符访问字段,例如(`obj.field`),不支持索引访问(`obj[field]`)。 ArkTS支持通过索引访问`TypedArray`(例如`Int32Array`)中的元素。 **TypeScript** ```typescript -class Point {x: number = 0; y: number = 0} +class Point { + x: number = 0 + y: number = 0 +} let p: Point = {x: 1, y: 2} -let x = p["x"] +console.log(p["x"]) + +class Person { + name: string = "" + age: number = 0; + [key: string]: string | number +} + +let person: Person = { + name: "John", + age: 30, + email: "***@example.com", + phoneNumber: "18*********", +} ``` **ArkTS** ```typescript -class Point {x: number = 0; y: number = 0} +class Point { + x: number = 0 + y: number = 0 +} let p: Point = {x: 1, y: 2} -let x = p.x +console.log(p.x) + +class Person { + name: string + age: number + email: string + phoneNumber: string + + constructor(name: string, age: number, email: string, + phoneNumber: string) { + this.name = name + this.age = age + this.email = email + this.phoneNumber = phoneNumber + } +} + +let person = new Person("John", 30, "***@example.com", "18*********") +console.log(person["name"]) // 编译时错误 +console.log(person.unknownProperty) // 编译时错误 let arr = new Int32Array(1) console.log(arr[0]) ``` -### 不支持structural identity +### 不支持structural typing -**规则:**`arkts-no-structural-identity` +**规则:**`arkts-no-structural-typing` **级别:错误** -目前ArkTS不支持structural identity,即编译器无法比较两种类型的公共API并决定它们是否相同。可改用其他机制,例如继承、接口或类型别名。 - -对于下面的示例,类型`X`和`Y`在TypeScript中是等价的(可互换),而在ArkTS中,他们是不等价的。 +ArkTS不支持structural typing,编译器无法比较两种类型的`public`API并决定它们是否相同。使用其他机制,例如继承、接口或类型别名。 **TypeScript** ```typescript -interface X { - f(): string -} - -interface Y { // Y等于X +interface I1 { f(): string } -``` -**ArkTS** - -```typescript -interface X { +interface I2 { // I2等价于I1 f(): string } -type Y = X // Y等于X -``` - -**相关约束** - -* 子类型/父类型不支持structural typing -* 赋值检查不支持structural typing -* 类型推断不支持structural typing - -### 子类型/父类型不支持structural typing - -**规则:**`arkts-no-structural-subtyping` - -**级别:错误** - -当前ArkTS在类型推导时不会检查structural是否相同,即编译器无法比较两种类型的公共API并决定它们是否相同。改用其他机制,例如继承或接口。 - -**TypeScript** - -```typescript class X { - public foo: number - - constructor() { - this.foo = 0 - } + n: number = 0 + s: string = "" } -class Y { - public foo: number - - constructor() { - this.foo = 0 - } +class Y { // Y等价于X + n: number = 0 + s: string = "" } let x = new X() @@ -931,118 +955,80 @@ y = x console.log("Assign Y to X") x = y -``` - -**ArkTS** -```typescript -class X { - public foo: number - - constructor() { - this.foo = 0 - } +function foo(x: X) { + console.log(x.n, x.s) } -// Y从X派生,显式定义继承关系 -class Y extends X { - constructor() { - super() - } -} - -let x = new X() -let y = new Y() - -console.log("Assign Y to X") -x = y // ok, X是Y的父类 - -// 不能将X赋值给Y -// y = x -编译时错误 +// 由于X和Y的API是等价的,所以X和Y是等价的 +foo(new X()) +foo(new Y()) ``` -**相关约束** - -* 不支持structural identity -* 赋值检查不支持structural typing -* 类型推断不支持structural typing - -### 赋值检查不支持structural typing - -**规则:**`arkts-no-structural-assignability` - -**级别:错误** - -当前ArkTS在检查变量是否可相互赋值时不检查结构等价性,即编译器无法比较两种类型的公共API并决定它们是否相同。改用其他机制,例如继承或接口。 - -**TypeScript** +**ArkTS** ```typescript -class X { - public foo: number +interface I1 { + f(): string +} - constructor() { - this.foo = 0 - } +type I2 = I1 // I2是I1的别名 + +class B { + n: number = 0 + s: string = "" } -class Y { - public foo: number +// D是B的继承类,构建了子类型和父类型的关系 +class D extends B { constructor() { - this.foo = 0 + super() } } -let x = new X() -let y = new Y() - -console.log("Assign X to Y") -y = x +let b = new B() +let d = new D() -console.log("Assign Y to X") -x = y -``` +console.log("Assign D to B") +b = d // 合法赋值,因为B是D的父类 -**ArkTS** +// 将b赋值给d将会引起编译时错误 +// d = b -```typescript interface Z { - foo: number + n: number + s: string } -// X实现了接口Z,显式化定义了X和Y之间的关系。 +// 类X implements 接口Z,构建了X和Y的关系 class X implements Z { - public foo: number - - constructor() { - this.foo = 0 - } + n: number = 0 + s: string = "" } -// Y实现了接口Z,显式化定义了X和Y之间的关系。 +// 类Y implements 接口Z,构建了X和Y的关系 class Y implements Z { - public foo: number - - constructor() { - this.foo = 0 - } + n: number = 0 + s: string = "" } let x: Z = new X() let y: Z = new Y() console.log("Assign X to Y") -y = x // ok,两者类型相同 +y = x // 合法赋值,它们是相同的类型 console.log("Assign Y to X") -x = y // ok,两者类型相同 -``` +x = y // 合法赋值,它们是相同的类型 -**相关约束** +function foo(c: Z): void { + console.log(c.n, c.s) +} -* 不支持structural identity -* 子类型/父类型不支持structural typing -* 类型推断不支持structural typing +// 类X和类Y implement 相同的接口,因此下面的两个函数调用都是合法的 +foo(new X()) +foo(new Y()) +``` ### 显式标注泛型函数类型实参,除非可以从参数中推断出类型实参 @@ -1084,105 +1070,13 @@ function greet(): T { let z = greet() ``` -### 类型推断不支持structural typing - -**规则:**`arkts-no-structural-inference` - -**级别:错误** - -当前ArkTS不支持structural typing,即编译器无法比较两种类型的公共API并决定它们是否相同。使用继承和接口显式指定类型之间的关系。 - -**TypeScript** - -```typescript -class X { - public foo: number - private s: string - - constructor (f: number) { - this.foo = f - this.s = "" - } - - public say(): void { - console.log("X = ", this.foo) - } -} - -class Y { - public foo: number - - constructor (f: number) { - this.foo = f - } - public say(): void { - console.log("Y = ", this.foo) - } -} - -function bar(z: X): void { - z.say() -} - -// X和Y具有相同的公共API,因此它们是等价的。 -// 允许第二次调用 -bar(new X(1)) -bar(new Y(2) as X) -``` - -**ArkTS** - -```typescript -interface Z { - say(): void -} - -class X implements Z { - public foo: number - private s: string - - constructor (f: number) { - this.foo = f - this.s = "" - } - public say(): void { - console.log("X = ", this.foo) - } -} - -class Y implements Z { - public foo: number - - constructor (f: number) { - this.foo = f - } - public say(): void { - console.log("Y = ", this.foo) - } -} - -function bar(z: Z): void { - z.say() -} - -// X和Y实现了相同的接口Z,因此两个调用均允许: -bar(new X(1)) -bar(new Y(2)) -``` - -**相关约束** - -* 不支持structural identity -* 子类型/父类型不支持structural typing -* 赋值检查不支持structural typing - ### 不支持使用正则字面量 **规则:**`arkts-no-regexp-literals` **级别:错误** -当前ArkTS不支持正则字面量。改用通过`RegExp()`创建。 +当前ArkTS不支持正则字面量。请使用`RegExp()`创建正则对象。 **TypeScript** @@ -1253,7 +1147,7 @@ function id_x_y(o: Point): Point { return o } -// 因为TS支持structural typing,编译器可以推断p的类型为Point +// TS支持structural typing,可以推断p的类型为Point let p = {x: 5, y: 10} id_x_y(p) @@ -1518,54 +1412,6 @@ class C1 implements C { } ``` -### 访问未定义的属性将导致编译时错误 - -**规则:**`arkts-no-undefined-prop-access` - -**级别:错误** - -ArkTS仅支持访问那些在类中已声明或通过继承可访问的属性。禁止访问任何其他属性,否则会导致编译时错误。使用恰当的类型可以帮助编译期进行类型检查,确定属性是否存在。 - -**TypeScript** - -```typescript -let person = {name: "Bob", isEmployee: true} - -let n = person["name"] -let e = person["isEmployee"] -let s = person["office"] // 只有在开启noImplicitAny选项时会产生编译时错误 -``` - -**ArkTS** - -```typescript -class Person { - constructor(name: string, isEmployee: boolean) { - this.name = name - this.isEmployee = isEmployee - } - - name: string - isEmployee: boolean -} - -let person = new Person("Bob", true) -let n = person.name -let e = person.isEmployee -let s = person.office // 编译时错误 -``` - -**相关约束** - -* 对象的属性名必须是合法的标识符 -* 不支持Symbol() API -* 不支持delete运算符 -* 仅允许在表达式中使用typeof运算符 -* 不支持in运算符 -* 禁止运行时检查对象属性 -* 不支持声明动态属性 -* 限制使用标准库 - ### 类型转换仅支持`as T`语法 **规则:**`arkts-as-casts` @@ -1721,11 +1567,10 @@ p.y = null * 对象的属性名必须是合法的标识符 * 不支持Symbol() API -* 访问未定义的属性将导致编译时错误 +* 不支持通过索引访问字段 * 仅允许在表达式中使用typeof运算符 * 不支持in运算符 * 禁止运行时检查对象属性 -* 不支持声明动态属性 ### 仅允许在表达式中使用`typeof`运算符 @@ -1761,66 +1606,12 @@ let s2: string * 对象的属性名必须是合法的标识符 * 不支持Symbol() API -* 访问未定义的属性将导致编译时错误 +* 不支持通过索引访问字段 * 不支持delete运算符 * 不支持in运算符 * 禁止运行时检查对象属性 -* 不支持声明动态属性 * 限制使用标准库 -### 二元运算符`+`仅支持数字和字符串的隐式转换 - -**规则:**`arkts-no-polymorphic-plus` - -**级别:错误** - -如果二元运算符`+`的一个操作数是`string`类型(包括enum中的`string`),那么另一个操作数可以是任意的类型,在运算时它的值被隐式转换成`string`。在其他情况下,ArkTS只支持`number`和enum中的`number`的隐式转换。 -正如TypeScript一样,ArkTS不支持两个`boolean`类型的值相加。其他情形下,都需要显式转换为字符串。 - -**TypeScript** - -```typescript -enum E { E1, E2 } - -let a = 10 + 32 // 42 -let b = E.E1 + 10 // 10 -let c = 10 + "5" // "105" - -let d = "5" + E.E2 // "51" -let e = "Hello, " + "world!" // "Hello, world!" -let f = "string" + true // "stringtrue" - -let g = (new Object()) + "string" // "[object Object]string" - -let i = true + true // 编译时错误 -let j = true + 2 // 编译时错误 -let k = E.E1 + true // 编译时错误 -``` - -**ArkTS** - -```typescript -enum E { E1, E2 } - -let a = 10 + 32 // 42 -let b = E.E1 + 10 // 10 -let c = 10 + "5" // "105" - -let d = "5" + E.E2 // "51" -let e = "Hello, " + "world!" // "Hello, world!" -let f = "string" + true // "stringtrue" - -let g = (new Object()).toString() + "string" - -let i = true + true // 编译时错误 -let j = true + 2 // 编译时错误 -let k = E.E1 + true // 编译时错误 -``` - -**相关约束** - -* 一元运算符+、-和~仅适用于数值类型 - ### 部分支持`instanceof`运算符 **规则:**`arkts-instanceof-ref-types` @@ -1889,11 +1680,10 @@ let b = p instanceof Person // true,且属性name一定存在 * 对象的属性名必须是合法的标识符 * 不支持Symbol() API -* 访问未定义的属性将导致编译时错误 +* 不支持通过索引访问字段 * 不支持delete运算符 * 仅允许在表达式中使用typeof运算符 * 禁止运行时检查对象属性 -* 不支持声明动态属性 * 限制使用标准库 ### 不支持解构赋值 @@ -2008,33 +1798,6 @@ let x = zp.x let y = zp.y ``` -### 不支持隐含类型的推断 - -**规则:**`arkts-no-implied-inference` - -**级别:错误** - -目前ArkTS不支持隐含类型的推断,改用显式的类型标注。如果容器中有不同类型的数据,请使用`Object[]`。 - -**TypeScript** - -```typescript -let [a, b, c] = [1, "hello", true] -``` - -**ArkTS** - -```typescript -let a = 1 -let b = "hello" -let c = true - -let arr: Object[] = [1, "hello", true] -let a1 = arr[0] -let b1 = arr[1] -let c1 = arr[2] -``` - ### 不支持在catch语句标注类型 **规则:**`arkts-no-types-in-catch` @@ -2097,23 +1860,8 @@ for (let i = 0; i < a.length; ++i) { **相关约束** -* 不支持可迭代接口 * for-of仅适用于数组和字符串 -### 不支持可迭代接口 - -**规则:**`arkts-no-iterable` - -**级别:错误** - -ArkTS不支持`Symbol`API、`Symbol.iterator`和最终可迭代的接口。请使用数组和标准库中的容器。 - -**相关约束** - -* 不支持Symbol() API -* 不支持for .. in -* for-of仅支持数组和字符串 - ### `for-of`仅适用于数组和字符串 **规则:**`arkts-for-of-str-arr` @@ -2144,7 +1892,6 @@ for (let n of numbers) { **相关约束** * 不支持for .. in -* 不支持可迭代接口 ### 不支持映射类型 @@ -2204,92 +1951,6 @@ let r: number = 42 console.log("Area: ", Math.PI * r * r) ``` -### `case`语句仅支持编译期值 - -**规则:**`arkts-no-computed-case` - -**级别:错误** - -在ArkTS中,`case`语句仅支持编译期值,支持`const`常量和`class`的`static readonly`属性。若值无法在编译期确定,请使用`if`语句。 - -**TypeScript** - -```typescript -let x = 2 -let y = 3 -switch (x) { - case 1: - console.log(1) - break - case 2: - console.log(2) - break - case y: - console.log(y) - break - default: - console.log("other") -} -``` - -**ArkTS** - -```typescript -let x = 2 -switch (x) { - case 1: - console.log(1) - break - case 2: - console.log(2) - break - case 3: - console.log(3) - break - default: - console.log("other") -} -``` - -### 限制`switch`语句中表达式的类型 - -**规则:**`arkts-limited-switch` - -**级别:错误** - -ArkTS支持`switch`语句中使用`number`, `Number`, `string`, `String`或者`enum`类型的值。其他情况下请使用`if`语句。 - -**TypeScript** - -```typescript -class Point { - x: number = 0 - y: number = 0 -} - -let a = new Point() - -switch (a) { - case null: break - default: console.log("not null") -} -``` - -**ArkTS** - -```typescript -class Point { - x: number = 0 - y: number = 0 -} - -let a = new Point() - -if (a != null) { - console.log("not null") -} -``` - ### 限制`throw`语句中表达式的类型 **规则:**`arkts-limited-throw` @@ -2453,7 +2114,7 @@ function addNum(a: number, b: number): void { **级别:错误** -ArkTS不支持在函数中使用`this`。只能在方法中使用`this`。 +ArkTS不支持在函数和静态方法中使用`this`。只能在方法中使用`this`。 **TypeScript** @@ -2823,7 +2484,7 @@ class C implements Mover, Shaker { **级别:错误** -ArkTS不支持合并声明。所用类、接口等的声明必须唯一。 +ArkTS不支持类、接口的声明合并。 **TypeScript** @@ -2940,11 +2601,10 @@ function main(): void { * 对象的属性名必须是合法的标识符 * 不支持Symbol() API -* 访问未定义的属性将导致编译时错误 +* 不支持通过索引访问字段 * 不支持delete运算符 * 仅允许运算符typeof在表达式上下文中使用 * 不支持in运算符 -* 不支持声明动态属性 * 限制使用标准库 ### 不支持构造函数类型 @@ -2996,65 +2656,7 @@ let Impersonizer: PersonCtor = (n: string, a: number): Person => { const person = createPerson(Impersonizer, "John", 30) ``` -### 不支持声明动态属性 - -**规则:**`arkts-no-dyn-prop-decl` - -**级别:错误** - -ArkTS不支持声明动态属性。必须在类中声明所有的属性。尽管可以用对象数组来实现动态特性,但更推荐使用静态类型范式来显式声明字段、名称和类型。 - -**TypeScript** - -```typescript -class Person { - name: string = "" - age: number = 0; // 此处需要分号 - [key: string]: string | number -} - -const person: Person = { - name: "John", - age: 30, - email: "***@example.com", - phoneNumber: 18*********, -} -``` - -**ArkTS** - -```typescript -class Person { - name: string - age: number - email: string - phoneNumber: number - - constructor(name: string, age: number, email: string, phoneNumber: number) { - this.name = name - this.age = age - this.email = email - this.phoneNumber = phoneNumber - } -} - -function main(): void { - const person: Person = new Person("John", 30, "***@example.com", 18*********) -} -``` - -**相关约束** - -* 对象的属性名必须是合法的标识符 -* 不支持Symbol() API -* 访问未定义的属性将导致编译时错误 -* 不支持delete运算符 -* 仅允许在表达式中使用typeof运算符 -* 不支持in运算符 -* 禁止运行时检查对象属性 -* 限制使用标准库 - -### 只能使用类型相同的编译期表达式初始化枚举成员 +### 只能使用类型相同的编译时表达式初始化枚举成员 **规则:**`arkts-no-enum-mixed-types` @@ -3304,7 +2906,7 @@ import * as m from "mod" **级别:错误** -ArkTS支持大多数场景下的重导出,例如命名重导出和重命名重导出。不支持`export * as ...`。 +ArkTS支持命名重导出和重命名重导出。支持`export * ...`的语法,不支持`export * as ...`的语法。 **TypeScript** @@ -3341,6 +2943,9 @@ export class Class2 { export { Class1 } from "module1" export { C2 as Class2 } from "module1" +// 支持以下语法 +// export * from "module1" + // consumer模块 import { Class1, Class2 } from "module2" @@ -4061,16 +3666,15 @@ ArkTS不允许使用TypeScript或JavaScript标准库中的某些接口。大部 * 对象的属性名必须是合法的标识符 * 不支持Symbol() API -* 访问未定义的属性将导致编译时错误 +* 不支持通过索引访问字段 * 仅允许在表达式中使用typeof运算符 * 不支持in运算符 * 禁止运行时检查对象属性 -* 不支持声明动态属性 * 不支持globalThis ### 强制开启严格类型检查 -**规则 `arkts-strict-typing`** +**规则:**`arkts-strict-typing` **级别:错误** @@ -4122,7 +3726,7 @@ let n2: number = 0 ### 不允许通过注释关闭类型检查 -**规则 `arkts-strict-typing-required`** +**规则:**`arkts-strict-typing-required` **级别:错误** @@ -4156,7 +3760,7 @@ let s2: string = null // 编译时报错 ### 允许ArkTS代码导入TS代码, 不允许TS代码导入ArkTS代码 -**规则 `arkts-no-ts-deps`** +**规则:**`arkts-no-ts-deps` **级别:错误** @@ -4188,7 +3792,7 @@ import { C } from "lib1" ### 除了ArkUI中的装饰器,不允许使用其他装饰器 -**规则 `arkts-no-decorators-except-arkui`** +**规则:**`arkts-no-decorators-except-arkui` **级别:错误** diff --git a/zh-cn/application-dev/reference/apis/js-apis-ability-ability.md b/zh-cn/application-dev/reference/apis/js-apis-ability-ability.md index ac6dfc795a1f34ed7bf4a47d4e86754910d4c548..4d37c36c8f6c7b809592bebf6f6288925d561cce 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-ability-ability.md +++ b/zh-cn/application-dev/reference/apis/js-apis-ability-ability.md @@ -24,15 +24,17 @@ AbilityResult:SystemCapability.Ability.AbilityBase ConnectOptions:SystemCapability.Ability.AbilityRuntime.Core StartAbilityParameter:SystemCapability.Ability.AbilityRuntime.FAModel +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + | 名称 | 类型 | 描述 | | ----------- | -------------------- | ------------------------------------------------------------ | -| DataAbilityHelper | [DataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) | DataAbilityHelper二级模块。 | -| PacMap | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap) | PacMap二级模块。 | -| DataAbilityOperation | [DataAbilityOperation](js-apis-inner-ability-dataAbilityOperation.md) | DataAbilityOperation二级模块。 | -| DataAbilityResult | [DataAbilityResult](js-apis-inner-ability-dataAbilityResult.md) | DataAbilityResult二级模块。 | -| AbilityResult | [AbilityResult](js-apis-inner-ability-abilityResult.md) | AbilityResult二级模块。 | -| ConnectOptions | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | ConnectOptions二级模块。 | -| StartAbilityParameter | [StartAbilityParameter](js-apis-inner-ability-startAbilityParameter.md) | StartAbilityParameter二级模块。 | +| DataAbilityHelper | [DataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) | DataAbilityHelper二级模块。
SystemCapability.Ability.AbilityRuntime.FAModel | +| PacMap | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap) | PacMap二级模块。
SystemCapability.Ability.AbilityRuntime.FAModel | +| DataAbilityOperation | [DataAbilityOperation](js-apis-inner-ability-dataAbilityOperation.md) | DataAbilityOperation二级模块。
SystemCapability.Ability.AbilityRuntime.FAModel | +| DataAbilityResult | [DataAbilityResult](js-apis-inner-ability-dataAbilityResult.md) | DataAbilityResult二级模块。
SystemCapability.Ability.AbilityRuntime.FAModel | +| AbilityResult | [AbilityResult](js-apis-inner-ability-abilityResult.md) | AbilityResult二级模块。
SystemCapability.Ability.AbilityBase | +| ConnectOptions | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | ConnectOptions二级模块。
SystemCapability.Ability.AbilityRuntime.Core | +| StartAbilityParameter | [StartAbilityParameter](js-apis-inner-ability-startAbilityParameter.md) | StartAbilityParameter二级模块。
ystemCapability.Ability.AbilityRuntime.FAModel | **示例:** ```ts diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-abilityLifecycleCallback.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-abilityLifecycleCallback.md index c2f4832377f640afb63eb7aca88ae223554f66e6..4ebd7260ac550b60845e52c523f06664267f0179 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-abilityLifecycleCallback.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-abilityLifecycleCallback.md @@ -333,7 +333,7 @@ import { GlobalContext } from '../GlobalContext' export default class MySecondAbility extends UIAbility { onDestroy() { let applicationContext = this.context.getApplicationContext(); - let lifecycleId: number = GlobalContext.getContext().getObject("lifecycleId"); + let lifecycleId = GlobalContext.getContext().getObject("lifecycleId") as number; // 3.通过applicationContext注销监听应用内生命周期 applicationContext.off('abilityLifecycle', lifecycleId, (error) => { if (error && error.code !== 0) { diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-applicationStateChangeCallback.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-applicationStateChangeCallback.md index 68e1ff54da71d5237c9bde4cdf6d6e3e69774453..ae43d32c570192d5ce45a3b2e32bf9c1e2e65eb6 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-applicationStateChangeCallback.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-applicationStateChangeCallback.md @@ -27,53 +27,30 @@ onApplicationForeground(): void; import UIAbility from '@ohos.app.ability.UIAbility'; import ApplicationStateChangeCallback from '@ohos.app.ability.ApplicationStateChangeCallback'; -// 构造单例对象 -export class GlobalContext { - private constructor() {} - private static instance: GlobalContext; - private _objects = new Map(); - - public static getContext(): GlobalContext { - if (!GlobalContext.instance) { - GlobalContext.instance = new GlobalContext(); - } - return GlobalContext.instance; - } - - getObject(value: string): Object | undefined { - return this._objects.get(value); - } - - setObject(key: string, objectClass: Object): void { - this._objects.set(key, objectClass); - } -} - let applicationStateChangeCallback: ApplicationStateChangeCallback = { onApplicationForeground() { console.info('applicationStateChangeCallback onApplicationForeground'); + }, + onApplicationBackground() { + console.info('applicationStateChangeCallback onApplicationBackground'); } } -GlobalContext.getContext().setObject("applicationStateChangeCallback", applicationStateChangeCallback); export default class MyAbility extends UIAbility { onCreate() { console.log('MyAbility onCreate'); - GlobalContext.getContext().setObject("applicationContext", this.context.getApplicationContext()); // 1.获取applicationContext - let applicationContext = GlobalContext.getContext().getObject("applicationContext"); + let applicationContext = this.context.getApplicationContext(); // 2.通过applicationContext注册应用前后台状态监听 if (applicationContext != undefined) { - applicationContext.on('applicationStateChange', - GlobalContext.getContext().getObject("applicationStateChangeCallback")); + applicationContext.on('applicationStateChange', applicationStateChangeCallback); } } onDestroy() { - let applicationContext = GlobalContext.getContext().getObject("applicationContext"); + let applicationContext = this.context.getApplicationContext(); // 1.通过applicationContext解除注册应用前后台状态监听 if (applicationContext != undefined) { - applicationContext.off('applicationStateChange', - GlobalContext.getContext().getObject("applicationStateChangeCallback")); + applicationContext.off('applicationStateChange', applicationStateChangeCallback); } } } @@ -93,53 +70,31 @@ onApplicationBackground(): void; import UIAbility from '@ohos.app.ability.UIAbility'; import ApplicationStateChangeCallback from '@ohos.app.ability.ApplicationStateChangeCallback'; -export class GlobalContext { - private constructor() {} - private static instance: GlobalContext; - private _objects = new Map(); - - public static getContext(): GlobalContext { - if (!GlobalContext.instance) { - GlobalContext.instance = new GlobalContext(); - } - return GlobalContext.instance; - } - - getObject(value: string): Object | undefined { - return this._objects.get(value); - } - - setObject(key: string, objectClass: Object): void { - this._objects.set(key, objectClass); - } -} - let applicationStateChangeCallback: ApplicationStateChangeCallback = { + onApplicationForeground() { + console.info('applicationStateChangeCallback onApplicationForeground'); + }, onApplicationBackground() { console.info('applicationStateChangeCallback onApplicationBackground'); } } -GlobalContext.getContext().setObject("applicationStateChangeCallback", applicationStateChangeCallback); export default class MyAbility extends UIAbility { onCreate() { console.log('MyAbility onCreate'); - GlobalContext.getContext().setObject("applicationContext", this.context.getApplicationContext()); // 1.获取applicationContext - let applicationContext = GlobalContext.getContext().getObject("applicationContext"); + let applicationContext = this.context.getApplicationContext(); // 2.通过applicationContext注册应用前后台状态监听 if (applicationContext != undefined) { - applicationContext.on('applicationStateChange', - GlobalContext.getContext().getObject("applicationStateChangeCallback")); + applicationContext.on('applicationStateChange', applicationStateChangeCallback); } console.log('Resgiter applicationStateChangeCallback'); } onDestroy() { - let applicationContext = GlobalContext.getContext().getObject("applicationContext"); + let applicationContext = this.context.getApplicationContext(); // 1.通过applicationContext解除注册应用前后台状态监听 if (applicationContext != undefined) { - applicationContext.off('applicationStateChange', - GlobalContext.getContext().getObject("applicationStateChangeCallback")); + applicationContext.off('applicationStateChange', applicationStateChangeCallback); } } } diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-common.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-common.md index 880d3e02b81c105c2cdeec1bb74f3e61da5eb7c7..5a2f72d2684e110b1d351e14f32f4a2cbce6f40f 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-common.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-common.md @@ -16,8 +16,6 @@ import common from '@ohos.app.ability.common'; **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core -**系统API**:该接口为系统接口,三方应用不支持调用。 - | 名称 | 类型 | 说明 | | ----------- | -------------------- | ------------------------------------------------------------ | | UIAbilityContext | [UIAbilityContext](js-apis-inner-application-uiAbilityContext.md) | UIAbilityContext二级模块。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-dialogRequest.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-dialogRequest.md index 8c9ae7e940cd16af66bdafde39046a8f571822ed..aa3a8bbc88d17431ec10f20e739d99772a8ba53c 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-dialogRequest.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-dialogRequest.md @@ -196,11 +196,29 @@ getRequestCallback(want: Want): RequestCallback } ``` +## WindowRect10+ + +表示模态弹框的属性。 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.Core + +| 名称 | 类型 | 必填 | 说明 | +| ---- | ------ | ---- | --------------------------- | +| left | number | 否 | 弹框边框的左上角的X坐标。 | +| top | number | 否 | 弹框边框的左上角的Y坐标。 | +| width | number | 否 | 弹框的宽度。 | +| height | number | 否 | 弹框的高度。 | + ## RequestInfo 表示发起方请求信息,作为窗口绑定模态弹框的入参。 + **系统能力**:SystemCapability.Ability.AbilityRuntime.Core +| 名称 | 类型 | 必填 | 说明 | +| ------------ | ------------------| ------ | ---------------------- | +| windowRect10+ | windowRect | 否 | 表示模态弹框的位置属性。 | + **示例:** ```ts @@ -313,6 +331,7 @@ getRequestCallback(want: Want): RequestCallback | 名称 | 类型 | 可读 | 可写 | 说明 | | -------- | -------- | -------- | -------- | -------- | | result | [ResultCode](#resultcode) | 是 | 是 | 表示结果码。 | +| want10+ | [ResultWant](js-apis-application-want.md) | 是 | 是 | 表示Want类型信息,如ability名称,包名等。 | ## RequestCallback diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-uiAbility.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-uiAbility.md index 6aa2b5586131d5094ffbd84a50467b25abb90ded..5ab5dac594ca0ad0d78895e4cef4064600de142f 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-uiAbility.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-uiAbility.md @@ -417,6 +417,32 @@ UIAbility生命周期回调,当系统预关闭开关打开后(配置系统 } ``` +## UIAbility.onBackPressed10+ + +onBackPressed(): boolean; + +UIAbility生命周期回调,当UIAbility侧滑返回时触发。根据返回值决定是否销毁UIAbility,默认为销毁UIAbility。 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore + +**返回值:** + +| 类型 | 说明 | +| -- | -- | +| boolean | 返回true表示UIAbility将会被移到后台不销毁,返回false表示UIAbility将正常销毁。 | + +**示例:** + + ```ts + import UIAbility from '@ohos.app.ability.UIAbility'; + + export default class EntryAbility extends UIAbility { + onBackPressed() { + return true; + } + } + ``` + ## Caller 通用组件Caller通信客户端调用接口, 用来向通用组件服务端发送约定数据。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-uiExtensionAbility.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-uiExtensionAbility.md index 2b2332422f59af67c269335da4894a7f42f4af26..30ad67f8596b23441f686abb945c67778ea3063f 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-uiExtensionAbility.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-uiExtensionAbility.md @@ -27,7 +27,7 @@ onCreate(): void UIExtensionAbility创建时回调,执行初始化业务逻辑操作。 -**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore +**系统能力**:SystemCapability.Ability.AbilityRuntime.Core ## UIExtensionAbility.onSessionCreate @@ -35,7 +35,7 @@ onSessionCreate(want: Want, session: UIExtensionContentSession): void 当UIExtensionAbility界面内容对象创建后调用。 -**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore +**系统能力**:SystemCapability.Ability.AbilityRuntime.Core **参数:** @@ -50,7 +50,7 @@ onSessionDestroy(session: UIExtensionContentSession): void 当UIExtensionAbility界面内容对象销毁后调用。 -**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore +**系统能力**:SystemCapability.Ability.AbilityRuntime.Core **参数:** @@ -81,4 +81,4 @@ onDestroy(): void | Promise<void>; UIExtensionAbility生命周期回调,在销毁时回调,执行资源清理等操作。 在执行完onDestroy生命周期回调后,应用可能会退出,从而可能导致onDestroy中的异步函数未能正确执行,比如异步写入数据库。可以使用异步生命周期,以确保异步onDestroy完成后再继续后续的生命周期。 -**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore +**系统能力**:SystemCapability.Ability.AbilityRuntime.Core diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-uiExtensionContentSession.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-uiExtensionContentSession.md index 005e6cb411c81a96ec4b68cb7b1f151900782c69..fa3404f8d936851acef35395ed973c1cfe1721ce 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-uiExtensionContentSession.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-uiExtensionContentSession.md @@ -19,7 +19,7 @@ sendData(data: { [key: string]: Object }): void 发送数据给UIExtensionComponent控件。 -**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore +**系统能力**:SystemCapability.Ability.AbilityRuntime.Core **系统API**:此接口为系统接口,三方应用不支持调用。 @@ -43,7 +43,7 @@ setReceiveDataCallback(callback: (data: { [key: string]: Object }) => void): voi 设置从UIExtensionComponent控件接收数据的回调方法。 -**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore +**系统能力**:SystemCapability.Ability.AbilityRuntime.Core **系统API**:此接口为系统接口,三方应用不支持调用。 @@ -63,11 +63,11 @@ setReceiveDataCallback(callback: (data: { [key: string]: Object }) => void): voi ## UIExtensionContentSession.loadContent -loadContent(path: string, storage?: LocalStorage): Promise<void> +loadContent(path: string, storage?: LocalStorage): void; 为当前UIExtensionComponent控件对应的窗口加载与LocalStorage相关联的具体页面内容。 -**系统能力:** SystemCapability.Ability.AbilityRuntime.AbilityCore +**系统能力:** SystemCapability.Ability.AbilityRuntime.Core **参数:** @@ -153,7 +153,7 @@ setWindowBackgroundColor(color: string): void 设置UIExtensionAbility加载界面的背景色。该接口需要在[loadContent()](#uiextensioncontentsessionloadcontent)调用生效后使用。 -**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore +**系统能力**:SystemCapability.Ability.AbilityRuntime.Core **系统API**:此接口为系统接口,三方应用不支持调用。 @@ -177,7 +177,7 @@ setWindowPrivacyMode(isPrivacyMode: boolean): Promise<void> 设置窗口是否为隐私模式,使用Promise异步回调。设置为隐私模式的窗口,窗口内容将无法被截屏或录屏。 -**系统能力:** SystemCapability.Ability.AbilityRuntime.AbilityCore +**系统能力:** SystemCapability.Ability.AbilityRuntime.Core **需要权限:** ohos.permission.PRIVACY_WINDOW @@ -199,7 +199,7 @@ setWindowPrivacyMode(isPrivacyMode: boolean, callback: AsyncCallback<void> 设置窗口是否为隐私模式,使用callback异步回调。设置为隐私模式的窗口,窗口内容将无法被截屏或录屏。 -**系统能力:** SystemCapability.Ability.AbilityRuntime.AbilityCore +**系统能力:** SystemCapability.Ability.AbilityRuntime.Core **需要权限:** ohos.permission.PRIVACY_WINDOW diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-form-formBindingData.md b/zh-cn/application-dev/reference/apis/js-apis-app-form-formBindingData.md index 4ad0a2001a45441a96f0c6e45ea97b9d80f35ed3..60c53272db71956d3b1c6acd689ee97e805c4fa5 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-form-formBindingData.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-form-formBindingData.md @@ -63,15 +63,16 @@ createFormBindingData(obj?: Object | string): FormBindingData ```ts import formBindingData from '@ohos.app.form.formBindingData'; import fs from '@ohos.file.fs'; +import Base from '@ohos.base'; try { let fd = fs.openSync('/path/to/form.png'); - let createFormBindingDataParam = new Map() - let formImagesParam = new Map() - formImagesParam.set('image', fd) - createFormBindingDataParam.set("name", '21°') - createFormBindingDataParam.set('formImages', formImagesParam) + let createFormBindingDataParam = new Map(); + let formImagesParam = new Map(); + formImagesParam.set('image', fd); + createFormBindingDataParam.set("name", '21°'); + createFormBindingDataParam.set('formImages', formImagesParam); formBindingData.createFormBindingData(createFormBindingDataParam); } catch (error) { diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-form-formExtensionAbility.md b/zh-cn/application-dev/reference/apis/js-apis-app-form-formExtensionAbility.md index 446d85a6dcd666ea58022ef5008831a0cd4fa589..86abfa81a63d77293777f56f3a2fd5b7231d4f4d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-form-formExtensionAbility.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-form-formExtensionAbility.md @@ -51,7 +51,7 @@ import Want from '@ohos.app.ability.Want'; export default class MyFormExtensionAbility extends FormExtensionAbility { onAddForm(want: Want) { console.log(`FormExtensionAbility onAddForm, want: ${want.abilityName}`); - let dataObj1 = new Map(); + let dataObj1 = new Map(); dataObj1.set('temperature', '11c'); dataObj1.set('time', '11:00'); @@ -107,20 +107,19 @@ onUpdateForm(formId: string): void import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; import formBindingData from '@ohos.app.form.formBindingData'; import formProvider from '@ohos.app.form.formProvider'; +import Base from '@ohos.base'; export default class MyFormExtensionAbility extends FormExtensionAbility { onUpdateForm(formId: string) { console.log(`FormExtensionAbility onUpdateForm, formId: ${formId}`); - class createFormBindingDataParam { - temperature: string - time: string - } let obj2 = formBindingData.createFormBindingData({ temperature: '22c', time: '22:00' - } as createFormBindingDataParam); + }); formProvider.updateForm(formId, obj2).then((data) => { console.log(`FormExtensionAbility context updateForm, data: ${data}`); + }).catch((error: Base.BusinessError) => { + console.error(`FormExtensionAbility context updateForm failed, data: ${error}`); }); } }; @@ -146,6 +145,7 @@ onChangeFormVisibility(newStatus: { [key: string]: number }): void import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; import formBindingData from '@ohos.app.form.formBindingData'; import formProvider from '@ohos.app.form.formProvider'; +import Base from '@ohos.base'; // 由于arkTs中无Object.keys,且无法使用for..in... // 若报arkTs问题,请将此方法单独抽离至一个ts文件中并暴露,在需要用到的ets文件中引入使用 @@ -155,23 +155,21 @@ function getObjKeys(obj: Object): string[] { } export default class MyFormExtensionAbility extends FormExtensionAbility { - onChangeFormVisibility(newStatus) { + onChangeFormVisibility(newStatus: Record) { console.log(`FormExtensionAbility onChangeFormVisibility, newStatus: ${newStatus}`); - class createFormBindingDataParam { - temperature: string - time: string - } let obj2 = formBindingData.createFormBindingData({ temperature: '22c', time: '22:00' - } as createFormBindingDataParam); - - for (let key in newStatus) { - console.log(`FormExtensionAbility onChangeFormVisibility, key: ${key}, value= ${newStatus[key]}`); - formProvider.updateForm(key, obj2).then((data) => { - console.log(`FormExtensionAbility context updateForm, data: ${data}`); - }).catch((error) => { - console.error(`Operation updateForm failed. Cause: ${error}`); + }); + + let keys: string[] = getObjKeys(newStatus); + + for (let i: number = 0; i < keys.length; i++) { + console.log(`FormExtensionAbility onChangeFormVisibility, key: ${keys[i]}, value= ${newStatus[keys[i]]}`); + formProvider.updateForm(keys[i], obj2).then(() => { + console.log(`FormExtensionAbility context updateForm`); + }).catch((error: Base.BusinessError) => { + console.error(`Operation updateForm failed. Cause: ${JSON.stringify(error)}`); }); } } @@ -317,9 +315,9 @@ import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; export default class MyFormExtensionAbility extends FormExtensionAbility { onShareForm(formId: string) { console.log(`FormExtensionAbility onShareForm, formId: ${formId}`); - let wantParams = { + let wantParams: Record = { 'temperature': '20', - 'time': '2022-8-8 09:59',s + 'time': '2022-8-8 09:59', }; return wantParams; } @@ -355,8 +353,8 @@ import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; export default class MyFormExtensionAbility extends FormExtensionAbility { onAcquireFormData(formId: string) { - console.log('FormExtensionAbility onAcquireFormData, formId: ${formId}'); - let wantParams = { + console.log(`FormExtensionAbility onAcquireFormData, formId: ${formId}`); + let wantParams: Record = { 'temperature': '20', 'time': '2022-8-8 09:59', }; diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-form-formHost.md b/zh-cn/application-dev/reference/apis/js-apis-app-form-formHost.md index 107e2bbf0c8b6b388ea3bcf8e3133d5d97dffe72..55bcc30739bc7c7ab9d90d00d6ac6279089fdde2 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-form-formHost.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-form-formHost.md @@ -11,7 +11,6 @@ formHost模块提供了卡片使用方相关接口的能力,包括对使用方 ```ts import formHost from '@ohos.app.form.formHost'; -import Base from '@ohos.base'; ``` ## deleteForm @@ -50,6 +49,7 @@ deleteForm(formId: string, callback: AsyncCallback<void>): void ```ts import formHost from '@ohos.app.form.formHost'; +import Base from '@ohos.base'; try { let formId: string = '12400633174999288'; @@ -61,7 +61,7 @@ try { } }); } catch (error) { - console.error(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message}`); } ``` @@ -107,16 +107,17 @@ deleteForm(formId: string): Promise<void> ```ts import formHost from '@ohos.app.form.formHost'; +import Base from '@ohos.base'; try { let formId: string = '12400633174999288'; formHost.deleteForm(formId).then(() => { console.log('formHost deleteForm success'); }).catch((error: Base.BusinessError) => { - console.error('formHost deleteForm, error: ${JSON.stringify(error)}'); + console.error(`formHost deleteForm, error: ${JSON.stringify(error)}`); }); } catch(error) { - console.error(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message}`); } ``` @@ -156,6 +157,7 @@ releaseForm(formId: string, callback: AsyncCallback<void>): void ```ts import formHost from '@ohos.app.form.formHost'; +import Base from '@ohos.base'; try { let formId: string = '12400633174999288'; @@ -165,7 +167,7 @@ try { } }); } catch(error) { - console.error(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message}`); } ``` @@ -206,6 +208,7 @@ releaseForm(formId: string, isReleaseCache: boolean, callback: AsyncCallback< ```ts import formHost from '@ohos.app.form.formHost'; +import Base from '@ohos.base'; try { let formId: string = '12400633174999288'; @@ -215,7 +218,7 @@ try { } }); } catch(error) { - console.error(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message}`); } ``` @@ -261,6 +264,7 @@ releaseForm(formId: string, isReleaseCache?: boolean): Promise<void> ```ts import formHost from '@ohos.app.form.formHost'; +import Base from '@ohos.base'; try { let formId: string = '12400633174999288'; @@ -270,7 +274,7 @@ try { console.error(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.error(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message}`); } ``` @@ -310,6 +314,7 @@ requestForm(formId: string, callback: AsyncCallback<void>): void ```ts import formHost from '@ohos.app.form.formHost'; +import Base from '@ohos.base'; try { let formId: string = '12400633174999288'; @@ -319,7 +324,7 @@ try { } }); } catch(error) { - console.error(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message}`); } ``` @@ -364,6 +369,7 @@ requestForm(formId: string): Promise<void> ```ts import formHost from '@ohos.app.form.formHost'; +import Base from '@ohos.base'; try { let formId: string = '12400633174999288'; @@ -373,7 +379,7 @@ try { console.error(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.error(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message}`); } ``` @@ -414,6 +420,7 @@ castToNormalForm(formId: string, callback: AsyncCallback<void>): void ```ts import formHost from '@ohos.app.form.formHost'; +import Base from '@ohos.base'; try { let formId: string = '12400633174999288'; @@ -423,7 +430,7 @@ try { } }); } catch(error) { - console.error(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message}`); } ``` @@ -468,6 +475,7 @@ castToNormalForm(formId: string): Promise<void> ```ts import formHost from '@ohos.app.form.formHost'; +import Base from '@ohos.base'; try { let formId: string = '12400633174999288'; @@ -477,7 +485,7 @@ try { console.error(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.error(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message}`); } ``` @@ -515,6 +523,7 @@ notifyVisibleForms(formIds: Array<string>, callback: AsyncCallback<void ```ts import formHost from '@ohos.app.form.formHost'; +import Base from '@ohos.base'; try { let formId: string[] = ['12400633174999288']; @@ -524,7 +533,7 @@ try { } }); } catch(error) { - console.error(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message}`); } ``` @@ -567,6 +576,7 @@ notifyVisibleForms(formIds: Array<string>): Promise<void> ```ts import formHost from '@ohos.app.form.formHost'; +import Base from '@ohos.base'; try { let formId: string[] = ['12400633174999288']; @@ -576,7 +586,7 @@ try { console.error(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.error(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message}`); } ``` @@ -614,6 +624,7 @@ notifyInvisibleForms(formIds: Array<string>, callback: AsyncCallback<vo ```ts import formHost from '@ohos.app.form.formHost'; +import Base from '@ohos.base'; try { let formId: string[] = ['12400633174999288']; @@ -623,7 +634,7 @@ try { } }); } catch(error) { - console.error(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message}`); } ``` @@ -666,6 +677,7 @@ notifyInvisibleForms(formIds: Array<string>): Promise<void> ```ts import formHost from '@ohos.app.form.formHost'; +import Base from '@ohos.base'; try { let formId: string[] = ['12400633174999288']; @@ -675,7 +687,7 @@ try { console.error(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.error(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message}`); } ``` @@ -714,6 +726,7 @@ enableFormsUpdate(formIds: Array<string>, callback: AsyncCallback<void& ```ts import formHost from '@ohos.app.form.formHost'; +import Base from '@ohos.base'; try { let formId: string[] = ['12400633174999288']; @@ -723,7 +736,7 @@ try { } }); } catch(error) { - console.error(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message}`); } ``` @@ -767,6 +780,7 @@ enableFormsUpdate(formIds: Array<string>): Promise<void> ```ts import formHost from '@ohos.app.form.formHost'; +import Base from '@ohos.base'; try { let formId: string[] = ['12400633174999288']; @@ -776,7 +790,7 @@ try { console.error(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.error(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message}`); } ``` @@ -816,6 +830,7 @@ disableFormsUpdate(formIds: Array<string>, callback: AsyncCallback<void ```ts import formHost from '@ohos.app.form.formHost'; +import Base from '@ohos.base'; try { let formId: string[] = ['12400633174999288']; @@ -825,7 +840,7 @@ try { } }); } catch(error) { - console.error(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message}`); } ``` @@ -870,6 +885,7 @@ disableFormsUpdate(formIds: Array<string>): Promise<void> ```ts import formHost from '@ohos.app.form.formHost'; +import Base from '@ohos.base'; try { let formId: string[] = ['12400633174999288']; @@ -879,7 +895,7 @@ try { console.error(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.error(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message}`); } ``` @@ -910,6 +926,7 @@ isSystemReady(callback: AsyncCallback<void>): void ```ts import formHost from '@ohos.app.form.formHost'; +import Base from '@ohos.base'; try { formHost.isSystemReady((error: Base.BusinessError) => { @@ -918,7 +935,7 @@ try { } }); } catch(error) { - console.error(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message}`); } ``` @@ -948,6 +965,7 @@ isSystemReady(): Promise<void> ```ts import formHost from '@ohos.app.form.formHost'; +import Base from '@ohos.base'; try { formHost.isSystemReady().then(() => { @@ -956,7 +974,7 @@ try { console.error(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.error(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message}`); } ``` @@ -994,6 +1012,7 @@ getAllFormsInfo(callback: AsyncCallback<Array<formInfo.FormInfo>>): ```ts import formHost from '@ohos.app.form.formHost'; import formInfo from '@ohos.app.form.formInfo'; +import Base from '@ohos.base'; try { formHost.getAllFormsInfo((error: Base.BusinessError, data: formInfo.FormInfo[]) => { @@ -1004,7 +1023,7 @@ try { } }); } catch(error) { - console.error(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message}`); } ``` @@ -1041,6 +1060,7 @@ getAllFormsInfo(): Promise<Array<formInfo.FormInfo>> ```ts import formHost from '@ohos.app.form.formHost'; import formInfo from '@ohos.app.form.formInfo'; +import Base from '@ohos.base'; try { formHost.getAllFormsInfo().then((data: formInfo.FormInfo[]) => { @@ -1049,7 +1069,7 @@ try { console.error(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.error(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message}`); } ``` @@ -1089,6 +1109,7 @@ getFormsInfo(bundleName: string, callback: AsyncCallback<Array<formInfo.Fo ```ts import formHost from '@ohos.app.form.formHost'; import formInfo from '@ohos.app.form.formInfo'; +import Base from '@ohos.base'; try { formHost.getFormsInfo('com.example.ohos.formjsdemo', (error: Base.BusinessError, data: formInfo.FormInfo[]) => { @@ -1099,7 +1120,7 @@ try { } }); } catch(error) { - console.error(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message}`); } ``` @@ -1140,6 +1161,7 @@ getFormsInfo(bundleName: string, moduleName: string, callback: AsyncCallback< ```ts import formHost from '@ohos.app.form.formHost'; import formInfo from '@ohos.app.form.formInfo'; +import Base from '@ohos.base'; try { formHost.getFormsInfo('com.example.ohos.formjsdemo', 'entry', (error: Base.BusinessError, data: formInfo.FormInfo[]) => { @@ -1150,7 +1172,7 @@ try { } }); } catch(error) { - console.error(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message}`); } ``` @@ -1196,6 +1218,7 @@ getFormsInfo(bundleName: string, moduleName?: string): Promise<Array<formI ```ts import formHost from '@ohos.app.form.formHost'; import formInfo from '@ohos.app.form.formInfo'; +import Base from '@ohos.base'; try { formHost.getFormsInfo('com.example.ohos.formjsdemo', 'entry').then((data: formInfo.FormInfo[]) => { @@ -1204,7 +1227,7 @@ try { console.error(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.error(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message}`); } ``` @@ -1242,6 +1265,7 @@ deleteInvalidForms(formIds: Array<string>, callback: AsyncCallback<numb ```ts import formHost from '@ohos.app.form.formHost'; +import Base from '@ohos.base'; try { let formIds: string[] = new Array('12400633174999288', '12400633174999289'); @@ -1253,7 +1277,7 @@ try { } }); } catch(error) { - console.error(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message}`); } ``` @@ -1296,6 +1320,7 @@ deleteInvalidForms(formIds: Array<string>): Promise<number> ```ts import formHost from '@ohos.app.form.formHost'; +import Base from '@ohos.base'; try { let formIds: string[] = new Array('12400633174999288', '12400633174999289'); @@ -1305,7 +1330,7 @@ try { console.error(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.error(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message}`); } ``` @@ -1346,6 +1371,7 @@ acquireFormState(want: Want, callback: AsyncCallback<formInfo.FormStateInfo&g import formHost from '@ohos.app.form.formHost'; import Want from '@ohos.app.ability.Want'; import formInfo from '@ohos.app.form.formInfo'; +import Base from '@ohos.base'; let want: Want = { 'deviceId': '', @@ -1366,7 +1392,7 @@ try { } }); } catch(error) { - console.error(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message}`); } ``` @@ -1412,6 +1438,7 @@ acquireFormState(want: Want): Promise<formInfo.FormStateInfo> import formHost from '@ohos.app.form.formHost'; import Want from '@ohos.app.ability.Want'; import formInfo from '@ohos.app.form.formInfo'; +import Base from '@ohos.base'; let want: Want = { 'deviceId': '', @@ -1430,7 +1457,7 @@ try { console.error(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.error(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message}`); } ``` @@ -1538,6 +1565,7 @@ notifyFormsVisible(formIds: Array<string>, isVisible: boolean, callback: A ```ts import formHost from '@ohos.app.form.formHost'; +import Base from '@ohos.base'; let formIds: string[] = new Array('12400633174999288', '12400633174999289'); try { @@ -1547,7 +1575,7 @@ try { } }); } catch(error) { - console.error(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message}`); } ``` @@ -1592,6 +1620,7 @@ notifyFormsVisible(formIds: Array<string>, isVisible: boolean): Promise< ```ts import formHost from '@ohos.app.form.formHost'; +import Base from '@ohos.base'; let formIds: string[] = new Array('12400633174999288', '12400633174999289'); try { @@ -1601,7 +1630,7 @@ try { console.error(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.error(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message}`); } ``` @@ -1641,6 +1670,7 @@ notifyFormsEnableUpdate(formIds: Array<string>, isEnableUpdate: boolean, c ```ts import formHost from '@ohos.app.form.formHost'; +import Base from '@ohos.base'; let formIds: string[] = new Array('12400633174999288', '12400633174999289'); try { @@ -1650,7 +1680,7 @@ try { } }); } catch(error) { - console.error(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message}`); } ``` @@ -1695,6 +1725,7 @@ notifyFormsEnableUpdate(formIds: Array<string>, isEnableUpdate: boolean): ```ts import formHost from '@ohos.app.form.formHost'; +import Base from '@ohos.base'; let formIds: string[] = new Array('12400633174999288', '12400633174999289'); try { @@ -1704,7 +1735,7 @@ try { console.error(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.error(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message}`); } ``` ## shareForm @@ -1743,6 +1774,7 @@ shareForm(formId: string, deviceId: string, callback: AsyncCallback<void>) ```ts import formHost from '@ohos.app.form.formHost'; +import Base from '@ohos.base'; let formId: string = '12400633174999288'; let deviceId: string = 'EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2'; @@ -1753,7 +1785,7 @@ try { } }); } catch(error) { - console.error(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message}`); } ``` @@ -1798,6 +1830,7 @@ shareForm(formId: string, deviceId: string): Promise<void> ```ts import formHost from '@ohos.app.form.formHost'; +import Base from '@ohos.base'; let formId: string = '12400633174999288'; let deviceId: string = 'EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2'; @@ -1808,7 +1841,7 @@ try { console.error(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.error(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message}`); } ``` @@ -1847,6 +1880,7 @@ notifyFormsPrivacyProtected(formIds: Array\, isProtected: boolean, callb ```ts import formHost from '@ohos.app.form.formHost'; +import Base from '@ohos.base'; let formIds: string[] = new Array('12400633174999288', '12400633174999289'); try { @@ -1856,7 +1890,7 @@ try { } }); } catch(error) { - console.error(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message}`); } ``` @@ -1898,6 +1932,7 @@ notifyFormsPrivacyProtected(formIds: Array\, isProtected: boolean): Pro ```ts import formHost from '@ohos.app.form.formHost'; +import Base from '@ohos.base'; let formIds: string[] = new Array('12400633174999288', '12400633174999289'); try { @@ -1907,7 +1942,7 @@ try { console.error(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.error(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message}`); } ``` @@ -1955,7 +1990,7 @@ try { } }); } catch(error) { - console.error(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message}`); } ``` @@ -1996,6 +2031,7 @@ acquireFormData(formId: string): Promise<{[key: string]: Object}>; ```ts import formHost from '@ohos.app.form.formHost'; +import Base from '@ohos.base'; let formId: string = '12400633174999288'; try { @@ -2005,6 +2041,6 @@ try { console.error(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.error(`catch error, code: ${error.code}, message: ${error.message}`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message}`); } ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-form-formProvider.md b/zh-cn/application-dev/reference/apis/js-apis-app-form-formProvider.md index 1fbd76de0921498c621ad515db8ad57d30cdbf26..1fb2cfb923f9df82c12a8e5922d59f81bd884450 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-form-formProvider.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-form-formProvider.md @@ -9,7 +9,6 @@ FormProvider模块提供了卡片提供方相关接口的能力,开发者在 ```ts import formProvider from '@ohos.app.form.formProvider'; -import Base from '@ohos.base'; ``` ## setFormNextRefreshTime @@ -46,6 +45,8 @@ setFormNextRefreshTime(formId: string, minute: number, callback: AsyncCallback&l **示例:** ```ts +import Base from '@ohos.base'; + let formId: string = '12400633174999288'; try { formProvider.setFormNextRefreshTime(formId, 5, (error: Base.BusinessError) => { @@ -56,7 +57,7 @@ try { console.log(`formProvider setFormNextRefreshTime success`); }); } catch (error) { - console.error(`catch error, code: ${error.code}, message: ${error.message})`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message})`); } ``` @@ -99,6 +100,8 @@ setFormNextRefreshTime(formId: string, minute: number): Promise<void> **示例:** ```ts +import Base from '@ohos.base'; + let formId: string = '12400633174999288'; try { formProvider.setFormNextRefreshTime(formId, 5).then(() => { @@ -107,7 +110,7 @@ try { console.error(`promise error, code: ${error.code}, message: ${error.message})`); }); } catch (error) { - console.error(`catch error, code: ${error.code}, message: ${error.message})`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message})`); } ``` @@ -145,18 +148,14 @@ updateForm(formId: string, formBindingData: formBindingData.FormBindingData,call ```ts import formBindingData from '@ohos.app.form.formBindingData'; +import Base from '@ohos.base'; let formId: string = '12400633174999288'; try { - class createFormBindingDataParamType { - temperature: string - time: string - } - let createFormBindingDataParam: createFormBindingDataParamType = { - temperature:'22c', - time:'22:00' - }; - let obj = formBindingData.createFormBindingData(createFormBindingDataParam); + let obj: formBindingData.FormBindingData = formBindingData.createFormBindingData({ + temperature: '22c', + time: '22:00' + }); formProvider.updateForm(formId, obj, (error: Base.BusinessError) => { if (error) { console.error(`callback error, code: ${error.code}, message: ${error.message})`); @@ -165,7 +164,7 @@ try { console.log(`formProvider updateForm success`); }); } catch (error) { - console.error(`catch error, code: ${error.code}, message: ${error.message})`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message})`); } ``` @@ -208,25 +207,21 @@ updateForm(formId: string, formBindingData: formBindingData.FormBindingData): Pr ```ts import formBindingData from '@ohos.app.form.formBindingData'; +import Base from '@ohos.base'; let formId: string = '12400633174999288'; -class createFormBindingDataParamType { - temperature: string - time: string - } - let createFormBindingDataParam: createFormBindingDataParamType = { - temperature:'22c', - time:'22:00' - }; -let obj = formBindingData.createFormBindingData(createFormBindingDataParam); +let obj: formBindingData.FormBindingData = formBindingData.createFormBindingData({ + temperature: '22c', + time: '22:00' +}); try { formProvider.updateForm(formId, obj).then(() => { console.log(`formProvider updateForm success`); }).catch((error: Base.BusinessError) => { - console.error(`promise error, code: ${error.code}, message: ${error.message})`); + console.error(`promise error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message})`); }); } catch (error) { - console.error(`catch error, code: ${error.code}, message: ${error.message})`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message})`); } ``` @@ -267,7 +262,7 @@ try { console.log(`formProvider getFormsInfo, data: ${JSON.stringify(data)}`); }); } catch (error) { - console.error(`catch error, code: ${error.code}, message: ${error.message})`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message})`); } ``` ## getFormsInfo @@ -314,7 +309,7 @@ try { console.log(`formProvider getFormsInfo, data: ${JSON.stringify(data)}`); }); } catch (error) { - console.error(`catch error, code: ${error.code}, message: ${error.message})`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message})`); } ``` @@ -353,6 +348,7 @@ getFormsInfo(filter?: formInfo.FormInfoFilter): Promise<Array<formInfo.For ```ts import formInfo from '@ohos.app.form.formInfo'; +import Base from '@ohos.base'; const filter: formInfo.FormInfoFilter = { // get info of forms belong to module entry. @@ -365,7 +361,7 @@ try { console.error(`promise error, code: ${error.code}, message: ${error.message})`); }); } catch (error) { - console.error(`catch error, code: ${error.code}, message: ${error.message})`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message})`); } ``` @@ -404,6 +400,7 @@ requestPublishForm(want: Want, formBindingData: formBindingData.FormBindingData, ```ts import formBindingData from '@ohos.app.form.formBindingData'; import Want from '@ohos.app.ability.Want'; +import Base from '@ohos.base'; let want: Want = { abilityName: 'FormAbility', @@ -414,24 +411,19 @@ let want: Want = { } }; try { - class createFormBindingDataParamType { - temperature: string - time: string - } - let createFormBindingDataParam: createFormBindingDataParamType = { - temperature:'22c', - time:'22:00' - }; - let obj = formBindingData.createFormBindingData(createFormBindingDataParam); + let obj: formBindingData.FormBindingData = formBindingData.createFormBindingData({ + temperature: '22c', + time: '22:00' + }); formProvider.requestPublishForm(want, obj, (error: Base.BusinessError, data: string) => { if (error) { - console.error(`callback error, code: ${error.code}, message: ${error.message})`); + console.error(`callback error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message})`); return; } console.log('formProvider requestPublishForm, form ID is: ${JSON.stringify(data)}'); }); } catch (error) { - console.error(`catch error, code: ${error.code}, message: ${error.message})`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message})`); } ``` @@ -468,6 +460,7 @@ requestPublishForm(want: Want, callback: AsyncCallback<string>): void ```ts import Want from '@ohos.app.ability.Want'; +import Base from '@ohos.base'; let want: Want = { abilityName: 'FormAbility', @@ -486,7 +479,7 @@ try { console.log(`formProvider requestPublishForm, form ID is: ${JSON.stringify(data)}`); }); } catch (error) { - console.error(`catch error, code: ${error.code}, message: ${error.message})`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message})`); } ``` @@ -529,6 +522,7 @@ requestPublishForm(want: Want, formBindingData?: formBindingData.FormBindingData ```ts import Want from '@ohos.app.ability.Want'; +import Base from '@ohos.base'; let want: Want = { abilityName: 'FormAbility', @@ -545,7 +539,7 @@ try { console.error(`promise error, code: ${error.code}, message: ${error.message})`); }); } catch (error) { - console.error(`catch error, code: ${error.code}, message: ${error.message})`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message})`); } ``` @@ -580,6 +574,7 @@ isRequestPublishFormSupported(callback: AsyncCallback<boolean>): void ```ts import Want from '@ohos.app.ability.Want'; +import Base from '@ohos.base'; try { formProvider.isRequestPublishFormSupported((error: Base.BusinessError, isSupported: boolean) => { @@ -604,13 +599,13 @@ try { console.log(`formProvider requestPublishForm, form ID is: ${JSON.stringify(data)}`); }); } catch (error) { - console.error(`catch error, code: ${error.code}, message: ${error.message})`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message})`); } } } }); } catch (error) { - console.error(`catch error, code: ${error.code}, message: ${error.message})`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message})`); } ``` @@ -644,6 +639,7 @@ isRequestPublishFormSupported(): Promise<boolean> ```ts import Want from '@ohos.app.ability.Want'; +import Base from '@ohos.base'; try { formProvider.isRequestPublishFormSupported().then((isSupported: boolean) => { @@ -663,13 +659,13 @@ try { console.error(`promise error, code: ${error.code}, message: ${error.message})`); }); } catch (error) { - console.error(`catch error, code: ${error.code}, message: ${error.message})`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message})`); } } }).catch((error: Base.BusinessError) => { console.error(`promise error, code: ${error.code}, message: ${error.message})`); }); } catch (error) { - console.error(`catch error, code: ${error.code}, message: ${error.message})`); + console.error(`catch error, code: ${(error as Base.BusinessError).code}, message: ${(error as Base.BusinessError).message})`); } ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-configuration.md b/zh-cn/application-dev/reference/apis/js-apis-application-configuration.md index c2b16b57feadc0d6729f03423c094f32b5f15000..f3d3bf1f5c87454c69759e7fc95c59eda3f350af 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-configuration.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-configuration.md @@ -13,6 +13,8 @@ import Configuration from '@ohos.application.Configuration'; ``` +## 属性 + **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase | 名称 | 类型 | 可读 | 可写 | 说明 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md b/zh-cn/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md index f5d7aedb0301474bb718e08b12e0d8dbd32d50a1..ae21d12824c4638f112b6fbe86aef0d9fc99cc8f 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md @@ -43,31 +43,32 @@ DataShare客户端连接DataShareExtensionAbility服务端时,服务端回调 **示例:** ```ts -import rdb from '@ohos.data.relationalStore'; +import relationalStore from '@ohos.data.relationalStore' +import Want from '@ohos.app.ability.Want' let DB_NAME = 'DB00.db'; let TBL_NAME = 'TBL00'; let DDL_TBL_CREATE = 'CREATE TABLE IF NOT EXISTS ' - + TBL_NAME - + ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)'; + + TBL_NAME + + ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)'; let rdbStore: relationalStore.RdbStore; export default class DataShareExtAbility extends DataShareExtensionAbility { - onCreate(want: Want, callback: Function) { - rdb.getRdbStore(this.context, { - name: DB_NAME, - securityLevel: rdb.SecurityLevel.S1 - }, (err, data) => { - console.info(`getRdbStore done, data : ${data}`); - rdbStore = data; - rdbStore.executeSql(DDL_TBL_CREATE, [], (err) => { - console.error(`executeSql done, error message : ${err}`); - }); - if (callback) { - callback(); - } - }); - } + onCreate(want: Want, callback: Function) { + relationalStore.getRdbStore(this.context, { + name: DB_NAME, + securityLevel: relationalStore.SecurityLevel.S1 + }, (err, data) => { + console.info(`getRdbStore done, data : ${data}`); + rdbStore = data; + rdbStore.executeSql(DDL_TBL_CREATE, [], (err) => { + console.error(`executeSql done, error message : ${err}`); + }); + if (callback) { + callback(); + } + }); + } }; ``` @@ -90,29 +91,25 @@ insert?(uri: string, valueBucket: ValuesBucket, callback: AsyncCallback<numbe **示例:** ```ts -import rdb from '@ohos.data.relationalStore'; +import relationalStore from '@ohos.data.relationalStore' import { ValuesBucket } from '@ohos.data.ValuesBucket' -let DB_NAME = 'DB00.db'; let TBL_NAME = 'TBL00'; -let DDL_TBL_CREATE = 'CREATE TABLE IF NOT EXISTS ' - + TBL_NAME - + ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)'; let rdbStore: relationalStore.RdbStore; export default class DataShareExtAbility extends DataShareExtensionAbility { - insert(uri: string, valueBucket: ValuesBucket, callback: Function) { - if (valueBucket === null) { - console.error('invalid valueBuckets'); - return; - } - rdbStore.insert(TBL_NAME, valueBucket, (err, ret) => { - console.info(`callback ret: ${ret}`); - if (callback !== undefined) { - callback(err, ret); - } - }); + insert(uri: string, valueBucket: ValuesBucket, callback: Function) { + if (valueBucket === null) { + console.error('invalid valueBuckets'); + return; } + rdbStore.insert(TBL_NAME, valueBucket, (err, ret) => { + console.info(`callback ret: ${ret}`); + if (callback !== undefined) { + callback(err, ret); + } + }); + } }; ``` @@ -136,28 +133,24 @@ update?(uri: string, predicates: dataSharePredicates.DataSharePredicates, valueB **示例:** ```ts -import rdb from '@ohos.data.relationalStore'; +import relationalStore from '@ohos.data.relationalStore'; import dataSharePredicates from '@ohos.data.dataSharePredicates'; import { ValuesBucket } from '@ohos.data.ValuesBucket' -let DB_NAME = 'DB00.db'; let TBL_NAME = 'TBL00'; -let DDL_TBL_CREATE = 'CREATE TABLE IF NOT EXISTS ' - + TBL_NAME - + ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)'; let rdbStore: relationalStore.RdbStore; export default class DataShareExtAbility extends DataShareExtensionAbility { - update(uri: string, predicates: dataSharePredicates.DataSharePredicates, valueBucket: ValuesBucket, callback: Function) { - if (predicates === null || predicates === undefined) { - return; - } - rdbStore.update(TBL_NAME, valueBucket, predicates, (err, ret) => { - if (callback !== undefined) { - callback(err, ret); - } - }); + update(uri: string, predicates: dataSharePredicates.DataSharePredicates, valueBucket: ValuesBucket, callback: Function) { + if (predicates === null || predicates === undefined) { + return; } + rdbStore.update(TBL_NAME, valueBucket, predicates, (err, ret) => { + if (callback !== undefined) { + callback(err, ret); + } + }); + } }; ``` @@ -180,27 +173,23 @@ delete?(uri: string, predicates: dataSharePredicates.DataSharePredicates, callba **示例:** ```ts -import rdb from '@ohos.data.relationalStore'; +import relationalStore from '@ohos.data.relationalStore'; import dataSharePredicates from '@ohos.data.dataSharePredicates'; -let DB_NAME = 'DB00.db'; let TBL_NAME = 'TBL00'; -let DDL_TBL_CREATE = 'CREATE TABLE IF NOT EXISTS ' - + TBL_NAME - + ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)'; let rdbStore: relationalStore.RdbStore; export default class DataShareExtAbility extends DataShareExtensionAbility { - delete(uri: string, predicates: dataSharePredicates.DataSharePredicates, callback: Function) { - if (predicates === null || predicates === undefined) { - return; - } - rdbStore.delete(TBL_NAME, predicates, (err, ret) => { - if (callback !== undefined) { - callback(err, ret); - } - }); + delete(uri: string, predicates: dataSharePredicates.DataSharePredicates, callback: Function) { + if (predicates === null || predicates === undefined) { + return; } + rdbStore.delete(TBL_NAME, predicates, (err, ret) => { + if (callback !== undefined) { + callback(err, ret); + } + }); + } }; ``` @@ -224,30 +213,26 @@ query?(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns **示例:** ```ts -import rdb from '@ohos.data.relationalStore'; +import relationalStore from '@ohos.data.relationalStore'; import dataSharePredicates from '@ohos.data.dataSharePredicates'; -let DB_NAME = 'DB00.db'; let TBL_NAME = 'TBL00'; -let DDL_TBL_CREATE = 'CREATE TABLE IF NOT EXISTS ' - + TBL_NAME - + ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)'; let rdbStore: relationalStore.RdbStore; export default class DataShareExtAbility extends DataShareExtensionAbility { - query(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array, callback: Function) { - if (predicates === null || predicates === undefined) { - return; - } - rdbStore.query(TBL_NAME, predicates, columns, (err, resultSet) => { - if (resultSet !== undefined) { - console.info(`resultSet.rowCount: ${resultSet.rowCount}`); - } - if (callback !== undefined) { - callback(err, resultSet); - } - }); + query(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array, callback: Function) { + if (predicates === null || predicates === undefined) { + return; } + rdbStore.query(TBL_NAME, predicates, columns, (err, resultSet) => { + if (resultSet !== undefined) { + console.info(`resultSet.rowCount: ${resultSet.rowCount}`); + } + if (callback !== undefined) { + callback(err, resultSet); + } + }); + } }; ``` @@ -270,14 +255,10 @@ batchInsert?(uri: string, valueBuckets: Array<ValuesBucket>, callback: Asy **示例:** ```ts -import rdb from '@ohos.data.relationalStore'; +import relationalStore from '@ohos.data.relationalStore'; import { ValuesBucket } from '@ohos.data.ValuesBucket' -let DB_NAME = 'DB00.db'; let TBL_NAME = 'TBL00'; -let DDL_TBL_CREATE = 'CREATE TABLE IF NOT EXISTS ' - + TBL_NAME - + ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)'; let rdbStore: relationalStore.RdbStore; export default class DataShareExtAbility extends DataShareExtensionAbility { @@ -313,6 +294,8 @@ normalizeUri?(uri: string, callback: AsyncCallback<string>): void **示例:** ```ts +import { BusinessError } from '@ohos.base' + export default class DataShareExtAbility extends DataShareExtensionAbility { normalizeUri(uri: string, callback: Function) { let key = 'code'; @@ -346,6 +329,8 @@ denormalizeUri?(uri: string, callback: AsyncCallback<string>): void **示例:** ```ts +import { BusinessError } from '@ohos.base' + export default class DataShareExtAbility extends DataShareExtensionAbility { denormalizeUri(uri: string, callback: Function) { let key = 'code'; diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-formBindingData.md b/zh-cn/application-dev/reference/apis/js-apis-application-formBindingData.md index 40a9952eb8887299476380badd48ee8ff4a39136..8e839bf40752eccfb7565a375115737cb3c413b6 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-formBindingData.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-formBindingData.md @@ -50,6 +50,7 @@ createFormBindingData(obj?: Object | string): FormBindingData ```ts import formBindingData from '@ohos.application.formBindingData'; import fs from '@ohos.file.fs'; +import Base from '@ohos.base'; try { let fd = fs.openSync('/path/to/form.png'); @@ -61,6 +62,6 @@ try { formBindingData.createFormBindingData(createFormBindingDataParam); } catch (error) { - console.error('catch error, error: ${JSON.stringify(error)}'); + console.error(`catch error, error: ${JSON.stringify(error as Base.BusinessError)}`); } ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-formHost.md b/zh-cn/application-dev/reference/apis/js-apis-application-formHost.md index 3929632886844574e65e673b441be97b715edb46..3ee1aa5ca975c3e087ead700db9d5e98e498a75a 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-formHost.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-formHost.md @@ -12,7 +12,6 @@ formHost模块提供了卡片使用方相关接口的能力,包括对使用方 ```ts import formHost from '@ohos.application.formHost'; -import Base from '@ohos.base'; ``` ## deleteForm @@ -38,9 +37,9 @@ deleteForm(formId: string, callback: AsyncCallback<void>): void import formHost from '@ohos.application.formHost'; let formId: string = '12400633174999288'; -formHost.deleteForm(formId, (error, data) => { +formHost.deleteForm(formId, (error: Base.BusinessError) => { if (error.code) { - console.error('formHost deleteForm, error: ${JSON.stringify(error)}'); + console.error(`formHost deleteForm, error: ${JSON.stringify(error)}`); } }); ``` @@ -71,6 +70,7 @@ deleteForm(formId: string): Promise<void> ```ts import formHost from '@ohos.application.formHost'; +import Base from '@ohos.base'; let formId: string = '12400633174999288'; formHost.deleteForm(formId).then(() => { @@ -101,6 +101,7 @@ releaseForm(formId: string, callback: AsyncCallback<void>): void ```ts import formHost from '@ohos.application.formHost'; +import Base from '@ohos.base'; let formId: string = '12400633174999288'; formHost.releaseForm(formId, (error: Base.BusinessError) => { @@ -134,6 +135,7 @@ releaseForm(formId: string, isReleaseCache: boolean, callback: AsyncCallback< ```ts import formHost from '@ohos.application.formHost'; +import Base from '@ohos.base'; let formId: string = '12400633174999288'; formHost.releaseForm(formId, true, (error: Base.BusinessError) => { @@ -172,6 +174,7 @@ releaseForm(formId: string, isReleaseCache?: boolean): Promise<void> ```ts import formHost from '@ohos.application.formHost'; +import Base from '@ohos.base'; let formId: string = '12400633174999288'; formHost.releaseForm(formId, true).then(() => { @@ -202,6 +205,7 @@ requestForm(formId: string, callback: AsyncCallback<void>): void ```ts import formHost from '@ohos.application.formHost'; +import Base from '@ohos.base'; let formId: string = '12400633174999288'; formHost.requestForm(formId, (error: Base.BusinessError) => { @@ -237,6 +241,7 @@ requestForm(formId: string): Promise<void> ```ts import formHost from '@ohos.application.formHost'; +import Base from '@ohos.base'; let formId: string = '12400633174999288'; formHost.requestForm(formId).then(() => { @@ -267,6 +272,7 @@ castTempForm(formId: string, callback: AsyncCallback<void>): void ```ts import formHost from '@ohos.application.formHost'; +import Base from '@ohos.base'; let formId: string = '12400633174999288'; formHost.castTempForm(formId, (error: Base.BusinessError) => { @@ -302,6 +308,7 @@ castTempForm(formId: string): Promise<void> ```ts import formHost from '@ohos.application.formHost'; +import Base from '@ohos.base'; let formId: string = '12400633174999288'; formHost.castTempForm(formId).then(() => { @@ -332,11 +339,12 @@ notifyVisibleForms(formIds: Array<string>, callback: AsyncCallback<void ```ts import formHost from '@ohos.application.formHost'; +import Base from '@ohos.base'; let formId: string[] = ['12400633174999288']; formHost.notifyVisibleForms(formId, (error: Base.BusinessError) => { if (error.code) { - console.error('formHost notifyVisibleForms, error: ${JSON.stringify(error)}'); + console.error(`formHost notifyVisibleForms, error: ${JSON.stringify(error)}`); } }); ``` @@ -367,6 +375,7 @@ notifyVisibleForms(formIds: Array<string>): Promise<void> ```ts import formHost from '@ohos.application.formHost'; +import Base from '@ohos.base'; let formId: string[] = ['12400633174999288']; formHost.notifyVisibleForms(formId).then(() => { @@ -397,6 +406,7 @@ notifyInvisibleForms(formIds: Array<string>, callback: AsyncCallback<vo ```ts import formHost from '@ohos.application.formHost'; +import Base from '@ohos.base'; let formId: string[] = ['12400633174999288']; formHost.notifyInvisibleForms(formId, (error: Base.BusinessError) => { @@ -432,6 +442,7 @@ notifyInvisibleForms(formIds: Array<string>): Promise<void> ```ts import formHost from '@ohos.application.formHost'; +import Base from '@ohos.base'; let formId: string[] = ['12400633174999288']; formHost.notifyInvisibleForms(formId).then(() => { @@ -462,6 +473,7 @@ enableFormsUpdate(formIds: Array<string>, callback: AsyncCallback<void& ```ts import formHost from '@ohos.application.formHost'; +import Base from '@ohos.base'; let formId: string[] = ['12400633174999288']; formHost.enableFormsUpdate(formId, (error: Base.BusinessError) => { @@ -497,6 +509,7 @@ enableFormsUpdate(formIds: Array<string>): Promise<void> ```ts import formHost from '@ohos.application.formHost'; +import Base from '@ohos.base'; let formId: string[] = ['12400633174999288']; formHost.enableFormsUpdate(formId).then(() => { @@ -527,6 +540,7 @@ disableFormsUpdate(formIds: Array<string>, callback: AsyncCallback<void ```ts import formHost from '@ohos.application.formHost'; +import Base from '@ohos.base'; let formId: string[] = ['12400633174999288']; formHost.disableFormsUpdate(formId, (error: Base.BusinessError) => { @@ -562,6 +576,7 @@ disableFormsUpdate(formIds: Array<string>): Promise<void> ```ts import formHost from '@ohos.application.formHost'; +import Base from '@ohos.base'; let formId: string[] = ['12400633174999288']; formHost.disableFormsUpdate(formId).then(() => { @@ -589,6 +604,7 @@ isSystemReady(callback: AsyncCallback<void>): void ```ts import formHost from '@ohos.application.formHost'; +import Base from '@ohos.base'; let formId: string = '12400633174999288'; formHost.isSystemReady((error: Base.BusinessError) => { @@ -616,6 +632,7 @@ isSystemReady(): Promise<void> ```ts import formHost from '@ohos.application.formHost'; +import Base from '@ohos.base'; let formId: string = '12400633174999288'; formHost.isSystemReady().then(() => { @@ -646,6 +663,7 @@ getAllFormsInfo(callback: AsyncCallback<Array<formInfo.FormInfo>>): ```ts import formHost from '@ohos.application.formHost'; import formInfo from '@ohos.app.form.formInfo'; +import Base from '@ohos.base'; formHost.getAllFormsInfo((error: Base.BusinessError, data: formInfo.FormInfo[]) => { if (error.code) { @@ -677,6 +695,7 @@ getAllFormsInfo(): Promise<Array<formInfo.FormInfo>> ```ts import formHost from '@ohos.application.formHost'; import formInfo from '@ohos.app.form.formInfo'; + import Base from '@ohos.base'; formHost.getAllFormsInfo().then((data: formInfo.FormInfo[]) => { console.log('formHost getAllFormsInfo data: ${JSON.stringify(data)}'); @@ -707,6 +726,7 @@ getFormsInfo(bundleName: string, callback: AsyncCallback<Array<formInfo.Fo ```ts import formHost from '@ohos.application.formHost'; import formInfo from '@ohos.app.form.formInfo'; +import Base from '@ohos.base'; formHost.getFormsInfo('com.example.ohos.formjsdemo', (error: Base.BusinessError, data: formInfo.FormInfo[]) => { if (error.code) { @@ -740,6 +760,7 @@ getFormsInfo(bundleName: string, moduleName: string, callback: AsyncCallback< ```ts import formHost from '@ohos.application.formHost'; import formInfo from '@ohos.app.form.formInfo'; +import Base from '@ohos.base'; formHost.getFormsInfo('com.example.ohos.formjsdemo', 'entry', (error: Base.BusinessError, data: formInfo.FormInfo[]) => { if (error.code) { @@ -777,6 +798,8 @@ getFormsInfo(bundleName: string, moduleName?: string): Promise<Array<formI ```ts import formHost from '@ohos.application.formHost'; + import Base from '@ohos.base'; + formHost.getFormsInfo('com.example.ohos.formjsdemo', 'entry').then((data: formInfo.FormInfo[]) => { console.log(`formHost getFormsInfo, data: ${JSON.stringify(data)}`); @@ -806,6 +829,7 @@ deleteInvalidForms(formIds: Array<string>, callback: AsyncCallback<numb ```ts import formHost from '@ohos.application.formHost'; +import Base from '@ohos.base'; let formIds: string[] = new Array('12400633174999288', '12400633174999289'); formHost.deleteInvalidForms(formIds, (error: Base.BusinessError, data: number) => { @@ -843,6 +867,7 @@ deleteInvalidForms(formIds: Array<string>): Promise<number> ```ts import formHost from '@ohos.application.formHost'; +import Base from '@ohos.base'; let formIds: string[] = new Array('12400633174999288', '12400633174999289'); formHost.deleteInvalidForms(formIds).then((data: number) => { @@ -875,6 +900,7 @@ acquireFormState(want: Want, callback: AsyncCallback<formInfo.FormStateInfo&g import formHost from '@ohos.application.formHost'; import Want from '@ohos.app.ability.Want'; import formInfo from '@ohos.app.form.formInfo'; +import Base from '@ohos.base'; let want: Want = { 'deviceId': '', @@ -923,6 +949,7 @@ acquireFormState(want: Want): Promise<formInfo.FormStateInfo> import formHost from '@ohos.application.formHost'; import Want from '@ohos.app.ability.Want'; import formInfo from '@ohos.app.form.formInfo'; +import Base from '@ohos.base'; let want: Want = { 'deviceId': '', @@ -1013,6 +1040,7 @@ notifyFormsVisible(formIds: Array<string>, isVisible: boolean, callback: A ```ts import formHost from '@ohos.application.formHost'; +import Base from '@ohos.base'; let formIds: string[]= new Array('12400633174999288', '12400633174999289'); formHost.notifyFormsVisible(formIds, true, (error: Base.BusinessError) => { @@ -1049,6 +1077,7 @@ notifyFormsVisible(formIds: Array<string>, isVisible: boolean): Promise< ```ts import formHost from '@ohos.application.formHost'; +import Base from '@ohos.base'; let formIds: string[] = new Array('12400633174999288', '12400633174999289'); formHost.notifyFormsVisible(formIds, true).then(() => { @@ -1080,6 +1109,7 @@ notifyFormsEnableUpdate(formIds: Array<string>, isEnableUpdate: boolean, c ```ts import formHost from '@ohos.application.formHost'; +import Base from '@ohos.base'; let formIds: string[] = new Array('12400633174999288', '12400633174999289'); formHost.notifyFormsEnableUpdate(formIds, true, (error: Base.BusinessError) => { @@ -1116,6 +1146,7 @@ notifyFormsEnableUpdate(formIds: Array<string>, isEnableUpdate: boolean): ```ts import formHost from '@ohos.application.formHost'; +import Base from '@ohos.base'; let formIds: string[] = new Array('12400633174999288', '12400633174999289'); formHost.notifyFormsEnableUpdate(formIds, true).then(() => { diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-formProvider.md b/zh-cn/application-dev/reference/apis/js-apis-application-formProvider.md index 372a6268be56f63b0ff8a2a21f6c75000da4f2c6..8e36e4548d02a45dc4745fd2a537f6799c01e560 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-formProvider.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-formProvider.md @@ -10,7 +10,6 @@ FormProvider模块提供了卡片提供方相关接口的能力,开发者在 ```ts import formProvider from '@ohos.application.formProvider'; -import Base from '@ohos.base' ``` ## setFormNextRefreshTime @@ -32,6 +31,8 @@ setFormNextRefreshTime(formId: string, minute: number, callback: AsyncCallback&l **示例:** ```ts + import Base from '@ohos.base' + let formId: string = '12400633174999288'; formProvider.setFormNextRefreshTime(formId, 5, (error: Base.BusinessError) => { if (error.code) { @@ -64,6 +65,8 @@ setFormNextRefreshTime(formId: string, minute: number): Promise<void> **示例:** ```ts + import Base from '@ohos.base' + let formId: string = '12400633174999288'; formProvider.setFormNextRefreshTime(formId, 5).then(() => { console.log('formProvider setFormNextRefreshTime success'); @@ -92,17 +95,13 @@ updateForm(formId: string, formBindingData: formBindingData.FormBindingData,call ```ts import formBindingData from '@ohos.app.form.formBindingData'; + import Base from '@ohos.base' - let formId = '12400633174999288'; - class createBindingDataType { - temperature: string - time: string - }; - let createBindingDataParam: createBindingDataType = { - temperature:'22c', - time:'22:00' - }; - let obj = formBindingData.createFormBindingData(createBindingDataParam); + let formId: string = '12400633174999288'; + let obj = formBindingData.createFormBindingData({ + temperature: '22c', + time: '22:00' + }); formProvider.updateForm(formId, obj, (error: Base.BusinessError) => { if (error.code) { console.error(`formProvider updateForm, error: ${JSON.stringify(error)}`); @@ -135,17 +134,13 @@ updateForm(formId: string, formBindingData: formBindingData.FormBindingData): Pr ```ts import formBindingData from '@ohos.application.formBindingData'; + import Base from '@ohos.base' let formId: string = '12400633174999288'; - class createBindingDataType { - temperature: string - time: string - }; - let createBindingDataParam: createBindingDataType = { - temperature:'22c', - time:'22:00' - }; - let obj = formBindingData.createFormBindingData(createBindingDataParam); + let obj = formBindingData.createFormBindingData({ + temperature: '22c', + time: '22:00' + }); formProvider.updateForm(formId, obj).then(() => { console.log('formProvider updateForm success'); }).catch((error: Base.BusinessError) => { diff --git a/zh-cn/application-dev/reference/apis/js-apis-arkui-UIContext.md b/zh-cn/application-dev/reference/apis/js-apis-arkui-UIContext.md index 3afa6875ef4da55e55ca6ac98f4203e53f2bb6ff..2799f8a52efa6f14a85b6cd3f95d0ad9baae3f1b 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-arkui-UIContext.md +++ b/zh-cn/application-dev/reference/apis/js-apis-arkui-UIContext.md @@ -585,7 +585,9 @@ getSystemFontList(): Array\ ```ts import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; let font:Font|undefined = uiContext.getFont(); -font.getSystemFontList() +if(font){ + font.getSystemFontList() +} ``` ### getFontByName @@ -613,7 +615,9 @@ getFontByName(fontName: string): font.FontInfo ```ts import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; let font:Font|undefined = uiContext.getFont(); -font.getFontByName('Sans Italic') +if(font){ + font.getFontByName('Sans Italic') +} ``` ## ComponentUtils @@ -753,7 +757,7 @@ pushUrl(options: router.RouterOptions): Promise<void> ```ts import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; import { BusinessError } from '@ohos.base'; -let router = uiContext.getRouter(); +let router:Router = uiContext.getRouter(); try { router.pushUrl({ url: 'pages/routerpage2', @@ -801,7 +805,7 @@ pushUrl(options: router.RouterOptions, callback: AsyncCallback<void>): voi ```ts import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; import { BusinessError } from '@ohos.base'; -let router = uiContext.getRouter(); +let router:Router = uiContext.getRouter(); router.pushUrl({ url: 'pages/routerpage2', params: { @@ -970,7 +974,7 @@ replaceUrl(options: router.RouterOptions): Promise<void> ```ts import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; import { BusinessError } from '@ohos.base'; -let router = uiContext.getRouter(); +let router:Router = uiContext.getRouter(); try { router.replaceUrl({ url: 'pages/detail', @@ -1014,7 +1018,7 @@ replaceUrl(options: router.RouterOptions, callback: AsyncCallback<void>): ```ts import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; import { BusinessError } from '@ohos.base'; -let router = uiContext.getRouter(); +let router:Router = uiContext.getRouter(); router.replaceUrl({ url: 'pages/detail', params: { @@ -1173,7 +1177,7 @@ pushNamedRoute(options: router.NamedRouterOptions): Promise<void> ```ts import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; import { BusinessError } from '@ohos.base'; -let router = uiContext.getRouter(); +let router:Router = uiContext.getRouter(); try { router.pushNamedRoute({ name: 'myPage', @@ -1221,7 +1225,7 @@ pushNamedRoute(options: router.NamedRouterOptions, callback: AsyncCallback<vo ```ts import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; import { BusinessError } from '@ohos.base'; -let router = uiContext.getRouter(); +let router:Router = uiContext.getRouter(); router.pushNamedRoute({ name: 'myPage', params: { @@ -1389,7 +1393,7 @@ replaceNamedRoute(options: router.NamedRouterOptions): Promise<void> ```ts import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; import { BusinessError } from '@ohos.base'; -let router = uiContext.getRouter(); +let router:Router = uiContext.getRouter(); try { router.replaceNamedRoute({ name: 'myPage', @@ -1433,7 +1437,7 @@ replaceNamedRoute(options: router.NamedRouterOptions, callback: AsyncCallback< ```ts import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; import { BusinessError } from '@ohos.base'; -let router = uiContext.getRouter(); +let router:Router = uiContext.getRouter(); router.replaceNamedRoute({ name: 'myPage', params: { diff --git a/zh-cn/application-dev/reference/apis/js-apis-audio.md b/zh-cn/application-dev/reference/apis/js-apis-audio.md index eaff3e7155873d448913a4442093a304267d0f2b..bd51282cd1e8c2a3316a1e97820fb1007d9110e2 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-audio.md +++ b/zh-cn/application-dev/reference/apis/js-apis-audio.md @@ -14,7 +14,7 @@ ## 导入模块 -```js +```ts import audio from '@ohos.multimedia.audio'; ``` @@ -28,7 +28,7 @@ import audio from '@ohos.multimedia.audio'; **示例:** -```js +```ts import audio from '@ohos.multimedia.audio'; const localNetworkId = audio.LOCAL_NETWORK_ID; @@ -51,8 +51,8 @@ getAudioManager(): AudioManager | [AudioManager](#audiomanager) | 音频管理类。 | **示例:** -```js -let audioManager = audio.getAudioManager(); +```ts +let audioManager: audio.AudioManager = audio.getAudioManager(); ``` ## audio.createAudioRenderer8+ @@ -72,24 +72,24 @@ createAudioRenderer(options: AudioRendererOptions, callback: AsyncCallback\ **示例:** -```js +```ts import fs from '@ohos.file.fs'; import audio from '@ohos.multimedia.audio'; +import { BusinessError } from '@ohos.base'; -let audioStreamInfo = { +let audioStreamInfo: audio.AudioStreamInfo = { samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, channels: audio.AudioChannel.CHANNEL_1, sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW } -let audioRendererInfo = { +let audioRendererInfo: audio.AudioRendererInfo = { content: audio.ContentType.CONTENT_TYPE_SPEECH, usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION, rendererFlags: 0 } -let audioRendererOptions = { +let audioRendererOptions: audio.AudioRendererOptions = { streamInfo: audioStreamInfo, rendererInfo: audioRendererInfo } -let audioRenderer; +let audioRenderer: audio.AudioRenderer; audio.createAudioRenderer(audioRendererOptions).then((data) => { audioRenderer = data; console.info('AudioFrameworkRenderLog: AudioRenderer Created : Success : Stream Type: SUCCESS'); -}).catch((err) => { +}).catch((err: BusinessError) => { console.error(`AudioFrameworkRenderLog: AudioRenderer Created : ERROR : ${err}`); }); ``` @@ -176,21 +177,21 @@ createAudioCapturer(options: AudioCapturerOptions, callback: AsyncCallback