提交 2552043e 编写于 作者: X xsz233

Merge branch 'master' of gitee.com:xsz233/new_doc

Signed-off-by: Nxsz233 <xushizhe@huawei.com>
......@@ -24,6 +24,12 @@
- [Multi-HAP Usage Rules](quick-start/multi-hap-rules.md)
- [Multi-HAP Operation Mechanism and Data Communication Modes](quick-start/multi-hap-principles.md)
- [Application Installation and Uninstallation Process](quick-start/application-package-install-uninstall.md)
- Shared Package
- [Shared Package Overview](quick-start/shared-guide.md)
- [HAR](quick-start/har-package.md)
- HSP
- [In-Application HSP Development](quick-start/in-app-hsp.md)
- [Inter-Application HSP Development (for System Applications Only)](quick-start/cross-app-hsp.md)
- Application Configuration Files in Stage Model
- [Application Configuration File Overview (Stage Model)](quick-start/application-configuration-file-overview-stage.md)
- [app.json5 Configuration File](quick-start/app-configuration-file.md)
......@@ -36,18 +42,44 @@
- [Resource Categories and Access](quick-start/resource-categories-and-access.md)
- Learning ArkTS
- [Getting Started with ArkTS](quick-start/arkts-get-started.md)
- ArkTS Syntax (Declarative UI)
- [Basic UI Description](quick-start/arkts-basic-ui-description.md)
- State Management
- [Basic Concepts](quick-start/arkts-state-mgmt-concepts.md)
- [State Management with Page-level Variables](quick-start/arkts-state-mgmt-page-level.md)
- [State Management with Application-level Variables](quick-start/arkts-state-mgmt-application-level.md)
- [Dynamic UI Element Building](quick-start/arkts-dynamic-ui-elememt-building.md)
- [Rendering Control](quick-start/arkts-rendering-control.md)
- [Restrictions and Extensions](quick-start/arkts-restrictions-and-extensions.md)
- Basic Syntax
- [Basic Syntax Overview](quick-start/arkts-basic-syntax-overview.md)
- [Declarative UI Description](quick-start/arkts-declarative-ui-description.md)
- Custom Component
- [Creating a Custom Component](quick-start/arkts-create-custom-components.md)
- [Page and Custom Component Lifecycle](quick-start/arkts-page-custom-components-lifecycle.md)
- [\@Builder: Custom Builder Function](quick-start/arkts-builder.md)
- [\@BuilderParam: @Builder Function Reference](quick-start/arkts-builderparam.md)
- [\@Styles: Definition of Resusable Styles](quick-start/arkts-style.md)
- [\@Extend: Extension of Built-in Components](quick-start/arkts-extend.md)
- [stateStyles: Polymorphic Style](quick-start/arkts-statestyles.md)
- State Management
- [State Management Overview](quick-start/arkts-state-management-overview.md)
- Component State Management
- [\@State: State Owned by Component](quick-start/arkts-state.md)
- [\@Prop: One-Way Synchronization from Parent to Child Components](quick-start/arkts-prop.md)
- [\@Link: Two-Way Synchronization Between Parent and Child Components](quick-start/arkts-link.md)
- [\@Provide and \@Consume: Two-Way Synchronization with Descendant Components](quick-start/arkts-provide-and-consume.md)
- [\@Observed and \@ObjectLink: Observing Attribute Changes in Nested Class Objects](quick-start/arkts-observed-and-objectlink.md)
- Application State Management
- [Application State Management Overview](quick-start/arkts-application-state-management-overview.md)
- [LocalStorage: UI State Storage](quick-start/arkts-localstorage.md)
- [AppStorage: Application-wide UI State Storage](quick-start/arkts-appstorage.md)
- [PersistentStorage: Application State Persistence](quick-start/arkts-persiststorage.md)
- [Environment: Device Environment Query](quick-start/arkts-environment.md)
- Other State Management Features
- [Overview of Other State Management Features](quick-start/arkts-other-state-mgmt-functions-overview.md)
- [\@Watch: Getting Notified of State Variable Changes](quick-start/arkts-watch.md)
- [$$ Syntax: Two-Way Synchronization of Built-in Components](quick-start/arkts-two-way-sync.md)
- Rendering Control
- [Rendering Control Overview](quick-start/arkts-rendering-control-overview.md)
- [if/else: Conditional Rendering](quick-start/arkts-rendering-control-ifelse.md)
- [ForEach: Rendering of Repeated Content](quick-start/arkts-rendering-control-foreach.md)
- [LazyForEach: Lazy Data Loading](quick-start/arkts-rendering-control-lazyforeach.md)
- Development
- [Application Models](application-models/Readme-EN.md)
- [UI Development](ui/Readme-EN.md)
- [Web](web/Readme-EN.md)
- [Notification](notification/Readme-EN.md)
- [Window Manager](windowmanager/Readme-EN.md)
- [WebGL](webgl/Readme-EN.md)
......@@ -81,8 +113,10 @@
- [ArkTS and JS APIs](reference/apis/Readme-EN.md)
- [Error Codes](reference/errorcodes/Readme-EN.md)
- Native APIs
- [Native APIs](reference/native-apis/Readme-EN.md)
- [Standard Libraries](reference/native-lib/third_party_libc/musl.md)
- [Node_API](reference/native-lib/third_party_napi/napi.md)
- [FAQs](faqs/Readme-EN.md)
- Contribution
- [How to Contribute](../contribute/documentation-contribution.md)
<!--no_check-->
\ No newline at end of file
......@@ -5,7 +5,7 @@
- [Overview of Application Data Persistence](app-data-persistence-overview.md)
- [Persisting Preferences Data](data-persistence-by-preferences.md)
- [Persisting KV Store Data](data-persistence-by-kv-store.md)
- [Persisting RDB Store Data] (data-persistence-by-rdb-store.md)
- [Persisting RDB Store Data](data-persistence-by-rdb-store.md)
- Distributed Application Data Synchronization
- [Distributed Application Data Synchronization Overview](sync-app-data-across-devices-overview.md)
- [Cross-Device Synchronization of KV Stores](data-sync-of-kv-store.md)
......@@ -16,7 +16,7 @@
- [Database Backup and Restoration](data-backup-and-restore.md)
- [Database Encryption](data-encryption.md)
- [Access Control by Device and Data Level](access-control-by-device-and-data-level.md)
- Cross-Application Data Sharing (Available Only for System Applications)
- Cross-Application Data Sharing (for System Applications Only)
- [Cross-Application Data Sharing Overview](share-device-data-across-apps-overview.md)
- [Sharing Data Using DataShareExtensionAbility](share-data-by-datashareextensionability.md)
- [Sharing Data in Silent Access](share-data-by-silent-access.md)
......@@ -23,7 +23,8 @@ When an asynchronous callback is used, the return value can be processed directl
| API | Description |
| ------------------------------ | ------------------------------------------------------------ |
| onUnhandledException(errMsg: string): void | Called when an application generates an uncaught exception after being registered.|
| onUnhandledException(errMsg: string): void | Called when an uncaught exception is reported after the application is registered.|
| onException?(errObject: Error): void | Called when an application exception is reported to the JavaScript layer after the application is registered.|
### Result Codes for Unregistering an Observer
......@@ -43,6 +44,13 @@ let registerId = -1;
let callback = {
onUnhandledException: function (errMsg) {
console.log(errMsg);
},
onException: function (errorObj) {
console.log('onException, name: ', errorObj.name);
console.log('onException, message: ', errorObj.message);
if (typeof(errorObj.stack) === 'string') {
console.log('onException, stack: ', errorObj.stack);
}
}
}
......
# File
# File Management
- [File Management Overview](file-management-overview.md)
- Application File
......@@ -20,4 +20,4 @@
- Distributed File System
- [Distributed File System Overview](distributed-fs-overview.md)
- [Setting the Security Level of a Distributed File](set-security-label.md)
- [Access Files Across Devices](file-access-across-devices.md)
- [Accessing Files Across Devices](file-access-across-devices.md)
......@@ -73,7 +73,7 @@ The following figure shows the application file directories. The path of a file
| distributedfiles | distributedFilesDir | Distributed file directory| Directory in **el2** for saving the application files that can be directly accessed across devices.<br>This directory is cleared when the application is uninstalled.|
| files | filesDir | Application file directory| Directory for saving the application's persistent files on the device.<br>This directory is cleared when the application is uninstalled.|
| cache | cacheDir | Application cache file directory| Directory for caching the downloaded files of the application or saving the cache files regenerated on the device.<br>This directory is automatically cleared when the size of the **cache** directory reaches the quota or the system storage space reaches a certain threshold. The user can also clear this directory by using a system space management application. <br>The application needs to check whether the file still exists and determine whether to cache the file again.|
| preferences | preferencesDir | Preferences file directory| Directory for saving common application configuration and user preference data managed by using database APIs.<br>This directory is cleared when the application is uninstalled. For details, see [Data Persistence by User Preferences](../database/data-persistence-by-preferences.md).|
| preferences | preferencesDir | Preferences file directory| Directory for saving common application configuration and user preference data managed by using database APIs.<br>This directory is cleared when the application is uninstalled. For details, see [Persisting Preferences Data](../database/data-persistence-by-preferences.md).|
| temp | tempDir | Temporary file directory| Directory for saving the files generated and required during the application's runtime on the device. <br>This directory is cleared when the application exits.|
The application file paths are used in the following scenarios:
......@@ -92,5 +92,3 @@ The following figure shows the application file directories. The path of a file
Used to store application preferences data, including preference files and configuration files. This directory applied to storing only a small amount of data.
- Temporary file directory<br>
Used to store temporarily generated data of an application, including cached database data and images, temporary log files, downloaded application installation package files. The data stored in this directory is deleted after being used.
<!--no_check-->
\ No newline at end of file
# Access Files Across Devices
# Accessing Files Across Devices
The distributed file system provides cross-device file access capabilities for applications. For the same application installed on multiple devices, you can implement read and write of the files in the application's distributed directory (**/data/storage/el2/distributedfiles/**) across devices by using [ohos.file.fs](app-file-access.md). For example, device A and device B are installed with the same application. After device A and device B are connected to form a Virtual Device, the application on device A can access the files of the same application on Device B. What you need to do is place the files to the distributed directory.
......
......@@ -23,6 +23,3 @@ The file systems can be classified into the following types based on the file st
**Figure 1** Files in an OS
![File classification model](figures/file-classification-model.png)
<!--no_check-->
\ No newline at end of file
# Setting the Security Level of a Distributed File
The security capabilities vary with devices. For example, small embedded devices provide fewer security capabilities than tablets. The security requirements also vary with data. For example, personal health information and bank card information are not expected to be accessed by devices of lower security levels. OpenHarmony provides a complete set of standards for data and device classification and custom data transfer policies for different devices. For details, see [Data and Device Security Classification](../database/access-control-by-device-and-data-level.md).
The security capabilities vary with devices. For example, small embedded devices provide fewer security capabilities than tablets. The security requirements also vary with data. For example, personal health information and bank card information are not expected to be accessed by devices of lower security levels. OpenHarmony provides a complete set of standards for data and device classification and custom data transfer policies for different devices. For details, see [Data Security Labels and Device Security Levels](../database/access-control-by-device-and-data-level.md).
## Available APIs
......@@ -39,4 +39,3 @@ securityLabel.setSecurityLabel(filePath, 's0').then(() => {
console.error(`Failed to setSecurityLabel. Code: ${err.code}, message: ${err.message}`);
});
```
<!--no_check-->
\ No newline at end of file
......@@ -45,11 +45,11 @@
- [Session Management](camera-session-management.md)
- [Camera Preview](camera-preview.md)
- [Camera Photographing](camera-shooting.md)
- [Video Recording](camera-recording.md)
- [Camera Recording](camera-recording.md)
- [Camera Metadata](camera-metadata.md)
- Best Practices
- [Camera Photographing Sample](camera-shooting-case.md)
- [Video Recording Sample](camera-recording-case.md)
- [Camera Recording Sample](camera-recording-case.md)
- Image
- [Image Overview](image-overview.md)
- [Image Decoding](image-decoding.md)
......
# Video Recording Sample
# Camera Recording Sample
## Development Process
......
# Video Recording
# Camera Recording
Video recording is also an important function of the camera application. Video recording is the process of cyclic capturing of frames. To smooth videos, you can follow step 4 in [Camera Photographing](camera-shooting.md) to set the resolution, flash, focal length, photo quality, and rotation angle.
......
......@@ -237,7 +237,7 @@
- [@ohos.file.environment (Directory Environment Capability)](js-apis-file-environment.md)
- [@ohos.file.fileAccess (User File Access and Management)](js-apis-fileAccess.md)
- [@ohos.file.fileExtensionInfo (User File Extension Information)](js-apis-fileExtensionInfo.md)
- [@ohos.file.fileUri (File URI)](js-apis-file-fileUri.md)
- [@ohos.file.fileuri (File URI)](js-apis-file-fileuri.md)
- [@ohos.file.fs (File Management)](js-apis-file-fs.md)
- [@ohos.file.hash (File Hash Processing)](js-apis-file-hash.md)
- [@ohos.file.picker (File Picker)](js-apis-file-picker.md)
......
# @ohos.application.uriPermissionManager (URI Permission Management)
> **NOTE**
>
> The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version.
The **uriPermissionManager** module provides APIs for granting permissions on a file to or revoking the granted permission from an application. The file is identified by a uniform resource identifier (URI).
## Modules to Import
```js
import UriPermissionManager from '@ohos.application.uriPermissionManager';
```
## uriPermissionManager.grantUriPermission
grantUriPermission(uri: string, flag: wantConstant.Flags, accessTokenId: number, callback: AsyncCallback&lt;number&gt;): void
Grants permission on the file of the specified URI to an application. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| uri | string | Yes| URI of the file, for example, **fileshare:///com.samples.filesharetest.FileShare/person/10**.|
| flag | [wantConstant.Flags](js-apis-ability-wantConstant.md#wantconstantflags) | Yes| Read or write permission on the file to grant.|
| targetBundleName | string | Yes| Bundle name of the application, to which the permission is granted.|
| callback | AsyncCallback&lt;number&gt; | Yes| Callback invoked to return the result. If the operation is successful, **0** is returned; otherwise, **-1** is returned.|
**Example**
```js
import WantConstant from '@ohos.ability.wantConstant';
let targetBundleName = 'com.example.test_case1'
let uri = "fileshare:///com.samples.filesharetest.FileShare/person/10"
uriPermissionManager.grantUriPermission(uri, WantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION, targetBundleName, (result) => {
console.log("result.code = " + result.code)
})
```
## uriPermissionManager.grantUriPermission
grantUriPermission(uri: string, flag: wantConstant.Flags, accessTokenId: number): Promise&lt;number&gt;
Grants permission on the file of the specified URI to an application. This API uses a promise to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| uri | string | Yes| URI of the file, for example, **fileshare:///com.samples.filesharetest.FileShare/person/10**.|
| flag | [wantConstant.Flags](js-apis-ability-wantConstant.md#wantconstantflags) | Yes| Read or write permission on the file to grant.|
| targetBundleName | string | Yes| Bundle name of the application, to which the permission is granted.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;number&gt; | Promise used to return the result. If the operation is successful, **0** is returned; otherwise, **-1** is returned.|
**Example**
```js
import WantConstant from '@ohos.ability.wantConstant';
let targetBundleName = 'com.example.test_case1'
let uri = "fileshare:///com.samples.filesharetest.FileShare/person/10"
uriPermissionManager.grantUriPermission(uri, wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION, targetBundleName)
.then((data) => {
console.log('Verification succeeded.' + data)
}).catch((error) => {
console.log('Verification failed.');
})
```
## uriPermissionManager.revokeUriPermission
revokeUriPermission(uri: string, accessTokenId: number, callback: AsyncCallback&lt;number&gt;): void
Revokes the permission on the file of the specified URI from an application. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| uri | string | Yes| URI of the file, for example, **fileshare:///com.samples.filesharetest.FileShare/person/10**.|
| targetBundleName | string | Yes| Bundle name of the application, from which the permission is revoked.|
| callback | AsyncCallback&lt;number&gt; | Yes| Callback invoked to return the result. If the operation is successful, **0** is returned; otherwise, **-1** is returned.|
**Example**
```js
import WantConstant from '@ohos.ability.wantConstant';
let targetBundleName = 'com.example.test_case1'
let URI = "fileshare:///com.samples.filesharetest.FileShare/person/10"
uriPermissionManager.revokeUriPermission(uri, targetBundleName, (result) => {
console.log("result.code = " + result.code)
})
```
## uriPermissionManager.revokeUriPermission
revokeUriPermission(uri: string, flag: wantConstant.Flags, accessTokenId: number): Promise&lt;number&gt;
Revokes the permission on the file of the specified URI from an application. This API uses a promise to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| uri | string | Yes| URI of the file, for example, **fileshare:///com.samples.filesharetest.FileShare/person/10**.|
| targetBundleName | string | Yes| Bundle name of the application, from which the permission is revoked.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;number&gt; | Promise used to return the result. If the operation is successful, **0** is returned; otherwise, **-1** is returned.|
**Example**
```js
import WantConstant from '@ohos.ability.wantConstant';
let targetBundleName = 'com.example.test_case1'
let uri = "fileshare:///com.samples.filesharetest.FileShare/person/10"
uriPermissionManager.revokeUriPermission(uri, targetBundleName)
.then((data) => {
console.log('Verification succeeded.' + data)
}).catch((error) => {
console.log('Verification failed.');
})
```
......@@ -436,7 +436,7 @@ Allows an application to obtain the sensitive permissions that have been granted
## ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS_EXTENSION
Allows an application to set attributes for the applications of other users.
Allows an application to set the attributes of applications of other users.
**Permission level**: system_core
......@@ -496,7 +496,7 @@ Allows an application to read data from a gyroscope sensor or uncalibrated gyros
## ohos.permission.INSTALL_BUNDLE
Allows an application to install and uninstall other applications.
Allows an application to install and uninstall other applications (except enterprise InHouse applications).
**Permission level**: system_core
......@@ -974,6 +974,26 @@ Allows the device administrator to set bundle installation policies.
**Enable via ACL**: TRUE
## ohos.permission.ENTERPRISE_SET_NETWORK
Allows the device administrator application to set network information.
**Permission level**: system_basic
**Authorization mode**: system_grant
**Enable via ACL**: TRUE
## ohos.permission.ENTERPRISE_MANAGE_SET_APP_RUNNING_POLICY
Allows the device administrator application to set application running policies.
**Permission level**: system_basic
**Authorization mode**: system_grant
**Enable via ACL**: TRUE
## ohos.permission.NFC_TAG
Allows an application to read NFC tag information.
......@@ -1146,7 +1166,7 @@ Allows an application to add, remove, and modify call logs.
## ohos.permission.WRITE_CONTACTS
Allows an application to add, remove, and modify contacts.
Allows an application to add, remove, and modify Contacts.
**Permission level**: system_basic
......@@ -1500,7 +1520,7 @@ Allows an application to manage private credentials and query certificate status
## ohos.permission.ACCESS_PUSH_SERVICE
Allows an application to to access the Ability of the push service.
Allows an application to access the Ability of the push service.
**Permission level**: system_basic
......@@ -1628,6 +1648,26 @@ Allows an application to have backup and restore capabilities.
**Enable via ACL**: TRUE
## ohos.permission.CLOUDFILE_SYNC_MANAGER
Allows an application to obtain the device-cloud synchronization management capability.
**Permission level**: system_basic
**Authorization mode**: system_grant
**Enable via ACL**: TRUE
## ohos.permission.CLOUDFILE_SYNC
Allows an application to perform device-cloud synchronization.
**Permission level**: system_basic
**Authorization mode**: system_grant
**Enable via ACL**: TRUE
## ohos.permission.FILE_ACCESS_MANAGER
Allows a file management application to access user data files through the FAF.
......@@ -1640,7 +1680,7 @@ Allows a file management application to access user data files through the FAF.
## ohos.permission.MANAGE_AUDIO_CONFIG
Allows an application to to mute microphones globally.
Allows an application to mute microphones globally.
**Permission level**: system_basic
......@@ -1757,3 +1797,83 @@ Allows an application to use ultrasonic sensing.
**Authorization mode**: system_grant
**Enable ACL**: FALSE
## ohos.permission.INSTALL_ENTERPRISE_BUNDLE
Allows an application to install and uninstall enterprise InHouse applications.
**Permission level**: system_core
**Authorization mode**: system_grant
**Enable via ACL**: TRUE
## ohos.permission.PROXY_AUTHORIZATION_URI
Allows the application proxy to authorize the URI.
**Permission level**: system_basic
**Authorization mode**: system_grant
**Enable ACL**: FALSE
## ohos.permission.GET_INSTALLED_BUNDLE_LIST
Allows an application to obtain the list of installed applications.
**Permission level**: system_basic
**Authorization mode**: user_grant
**Enable via ACL**: TRUE
## ohos.permission.MANAGE_DISTRIBUTED_ACCOUNTS
Allows an application to manage distributed account information.
**Permission level**: system_basic
**Authorization mode**: system_grant
**Enable via ACL**: TRUE
## ohos.permission.GET_DISTRIBUTED_ACCOUNTS
Allows an application to obtain distributed account information.
**Permission level**: system_basic
**Authorization mode**: system_grant
**Enable via ACL**: TRUE
## ohos.permission.GET_LOCAL_ACCOUNTS
Allows an application to obtain local account information.
**Permission level**: system_basic
**Authorization mode**: system_grant
**Enable via ACL**: TRUE
## ohos.permission.READ_HIVIEW_SYSTEM
Allows an application to access HiView data.
**Permission level**: system_basic
**Authorization mode**: system_grant
**Enable via ACL**: TRUE
## ohos.permission.WRITE_HIVIEW_SYSTEM
Allows an application to modify HiView data.
**Permission level**: system_basic
**Authorization mode**: system_grant
**Enable via ACL**: TRUE
# Web
- [Web Component Overview](web-component-overview.md)
- [Loading Pages by Using the Web Component](web-page-loading-with-web-components.md)
- Setting Basic Attributes and Events
- [Setting the Dark Mode](web-set-dark-mode.md)
- [Uploading Files](web-file-upload.md)
- [Opening Pages in a New Window](web-open-in-new-window.md)
- [Managing Location Permissions](web-geolocation-permission.md)
- Using Frontend Page JavaScript Code on the Application
- [Invoking Frontend Page Functions on the Application](web-in-app-frontend-page-function-invoking.md)
- [Invoking Application Functions on the Frontend Page](web-in-page-app-function-invoking.md)
- [Establishing a Data Channel Between the Application and Frontend Page](web-app-page-data-channel.md)
- [Managing Page Redirection and Browsing History Navigation](web-redirection-and-browsing-history-mgmt.md)
- [Managing Cookies and Data Storage](web-cookie-and-data-storage-mgmt.md)
- [Customizing Page Request Responses](web-resource-interception-request-mgmt.md)
- [Debugging Frontend Pages by Using DevTools](web-debugging-with-devtools.md)
# Establishing a Data Channel Between the Application and the Frontend Page
The [createWebMessagePorts()](../reference/apis/js-apis-webview.md#createwebmessageports) API allows you to create message ports to implement communication between the application and frontend page.
In the following example, **createWebMessagePorts** is used to create message ports on the application and [postMessage()](../reference/apis/js-apis-webview.md#postmessage) is used to forward one of the message ports to the frontend page so that the application and frontend page can exchange messages with each other over the port.
- Application code:
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
ports: web_webview.WebMessagePort[];
@State sendFromEts: string = 'Send this message from ets to HTML';
@State receivedFromHtml: string = 'Display received message send from HTML';
build() {
Column() {
// Display the content received from the HTML side.
Text(this.receivedFromHtml)
// Send the content in the text box to the HTML side.
TextInput({placeholder: 'Send this message from ets to HTML'})
.onChange((value: string) => {
this.sendFromEts = value;
})
Button('postMessage')
.onClick(() => {
try {
// 1. Create two message ports.
this.ports = this.controller.createWebMessagePorts();
// 2. Register a callback for the message port (for example, port 1) on the application.
this.ports[1].onMessageEvent((result: web_webview.WebMessage) => {
let msg = 'Got msg from HTML:';
if (typeof(result) === 'string') {
console.info(`received string message from html5, string is: ${result}`);
msg = msg + result;
} else if (typeof(result) === 'object') {
if (result instanceof ArrayBuffer) {
console.info(`received arraybuffer from html5, length is: ${result.byteLength}`);
msg = msg + 'lenght is ' + result.byteLength;
} else {
console.info('not support');
}
} else {
console.info('not support');
}
this.receivedFromHtml = msg;
})
// 3. Send the other message port (for example, port 0) to the HTML side, which then saves the message port.
this.controller.postMessage('__init_port__', [this.ports[0]], '*');
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
// 4. Use the message port on the application to send messages to the message port that has been sent to the HTML side.
Button('SendDataToHTML')
.onClick(() => {
try {
if (this.ports && this.ports[1]) {
this.ports[1].postMessageEvent(this.sendFromEts);
} else {
console.error(`ports is null, Please initialize first`);
}
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: $rawfile('xxx.html'), controller: this.controller })
}
}
}
```
- Frontend page code:
```html
<!--xxx.html-->
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebView Message Port Demo</title>
</head>
<script>
var h5Port;
var output = document.querySelector('.output');
window.addEventListener('message', function (event) {
if (event.data === '__init_port__') {
if (event.ports[0] !== null) {
h5Port = event.ports[0]; // 1. Save the port sent from the eTS side.
h5Port.onmessage = function (event) {
// 2. Receive messages sent from the eTS side.
var msg = 'Got message from ets:';
var result = event.data;
if (typeof(result) === 'string') {
console.info(`received string message from html5, string is: ${result}`);
msg = msg + result;
} else if (typeof(result) === 'object') {
if (result instanceof ArrayBuffer) {
console.info(`received arraybuffer from html5, length is:` ${result.byteLength}`);
msg = msg + 'lenght is ' + result.byteLength;
} else {
console.info('not support');
}
} else {
console.info('not support');
}
output.innerHTML = msg;
}
}
}
})
// 3. Use H5Port to send messages to the eTS side.
function PostMsgToEts(data) {
if (h5Port) {
h5Port.postMessage(data);
} else {
console.error('h5Port is null, Please initialize first');
}
}
</script>
<body>
<h1>WebView Message Port Demo</h1>
<div>
<input type="button" value="SendToEts" onclick="PostMsgToEts(msgFromJS.value);"/><br/>
<input id="msgFromJS" type="text" value="send this message from HTML to ets"/><br/>
</div>
<p class="output">display received message send from ets</p>
</body>
</html>
```
# Web Component Overview
In addition to displaying web page content on applications, the **Web** component provides you with some other helpful functions, including:
- **Page loading**: provides a full set of basic frontend page loading capabilities, which allow you to load network pages, local pages, and HTML text data.
- **Page interaction**: supports a wide range of page interaction modes, which allow you to set the dark mode for frontend pages, load pages in a new window, manage location permissions and cookies, and use frontend page JavaScript code on the application.
- **Page debugging**: uses DevTools to debug frontend pages.
To help you better understand the features of the **Web** component, the following sections will exemplify use of the **Web** component in common application scenarios.
# Managing Cookies and Data Storage
## Cookie Management
A cookie is a segment of data sent from the server to the client to uniquely identify a user during network access. The client may hold the data and provide it to the server at later interactions so that the server can quickly identify the client identity and status.
The **Web** component provides the **WebCookieManager** class for you to manage cookie information, which is stored in the **/proc/{pid}/root/data/storage/el2/base/cache/web/Cookiesd** file in the application sandbox path.
The following uses [setCookie()](../reference/apis/js-apis-webview.md#setcookie) as an example to describe how to set a cookie's value to **test** for **www.example.com**. For details about functions and usage of other APIs, see [WebCookieManager()](../reference/apis/js-apis-webview.md#webcookiemanager).
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('setCookie')
.onClick(() => {
try {
web_webview.WebCookieManager.setCookie('https://www.example.com', 'value=test');
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
## Cache and Storage Management
Network resource requests are relatively time-consuming during website access. You can use store resources locally by means of cache and Dom Storage to fasten the access to the same website.
### Cache
Use [cacheMode()](../reference/arkui-ts/ts-basic-components-web.md#cachemode) to configure the cache mode for page resources. Four cache modes are supported:
- **Default**: Page resources in a cache that has not expired are preferentially used. If the cache does not exist, page resources are obtained from the network.
- **None**: Page resources are loaded from the cache. If the cache does not exist, page resources are obtained from the network.
- **Online**: Page resources are not loaded from the cache. All resources are obtained from the network.
- **Only**: Page resources are only loaded from the cache.
In the following example, the cache mode is set to **None**.
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
@State mode: CacheMode = CacheMode.None;
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
.cacheMode(this.mode)
}
}
}
```
To obtain up-to-date resources, you can use [removeCache()](../reference/apis/js-apis-webview.md#removecache) to clear cached resources. The sample code is as follows:
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
@State mode: CacheMode = CacheMode.None;
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('removeCache')
.onClick(() => {
try {
// If this parameter is set to true, the cache in both the ROM and RAM is cleared. If this parameter is set to false, only the cache in the RAM is cleared.
this.controller.removeCache(true);
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
.cacheMode(this.mode)
}
}
}
```
### Dom Storage
Dom Storage falls into Session Storage and Local Storage. Wherein, Session Storage applies to the temporary data, and its data storage and release follow the session lifecycle; Local Storage applies to the persistent data, which is flushed to the application directory. In both storage modes, data is stored in a form of key-value pair, and is usually used when a page that needs to be stored on the client is accessed. You can use [domStorageAccess()](../reference/arkui-ts/ts-basic-components-web.md#domstorageaccess) to enable Dom Storage. The following is the sample code:
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
.domStorageAccess(true)
}
}
}
```
# Debugging Frontend Pages by Using DevTools
The **Web** component supports debugging of web frontend pages by using DevTools, a web frontend development and debugging tool that allows you to debug an application's frontend pages on a PC. Before you do this, use [setWebDebuggingAccess()](../reference/apis/js-apis-webview.md#setwebdebuggingaccess) to enable frontend page debugging for the **Web** component.
To use DevTools for frontend page debugging, perform the following steps:
1. Enable web frontend page debugging in the application code.
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
aboutToAppear() {
// Enable web frontend page debugging.
web_webview.WebviewController.setWebDebuggingAccess(true);
}
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
2. Connect your device to a PC, and configure port mapping on the PC as follows:
```
// Configure port mapping.
hdc fport tcp:9222 tcp:9222
// View port mapping.
hdc fport ls
```
3. Enter **chrome://inspect/\#devices** in the address box of the Chrome browser on the PC. Once the device is identified, you can get started with page debugging. The debugging effect is as follows:
**Figure 1** Page debugging effect
![debug-effect](figures/debug-effect.png)
# Uploading Files
The **Web** component supports file uploading on a frontend page. You can use [onShowFileSelector()](../reference/arkui-ts/ts-basic-components-web.md#onshowfileselector9) to process file upload requests sent from a frontend page.
In the following example, when a user clicks the **Upload** button on the frontend page, the application receives a file upload request through [onShowFileSelector()](../reference/arkui-ts/ts-basic-components-web.md#onshowfileselector9), which carries the path of the local file to be uploaded.
- Application code:
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController()
build() {
Column() {
// Load the local.html page.
Web({ src: $rawfile('local.html'), controller: this.controller })
.onShowFileSelector((event) => {
// Set the path of the local file to be uploaded.
let fileList: Array<string> = [
'xxx/test.png',
]
event.result.handleFileList(fileList)
return true;
})
}
}
}
```
- Code of the **local.html** page:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Document</title>
</head>
<body>
<!-- Click the Upload button -->
<input type="file" value="file"></br>
</body>
</html>
```
# Managing Location Permissions
The **Web** component provides the location permission management capability. You can use [onGeolocationShow()](../reference/arkui-ts/ts-basic-components-web.md#ongeolocationshow) to manage the location permission specific to a website. Based on the API response, the **Web** component determines whether to grant the location permission to the frontend page. To obtain the device location, you need to declare the [ohos.permission.LOCATION](../security/accesstoken-guidelines.md) permission.
In the following example, when a user clicks the **Get Location** button on the frontend page, the **Web** component notifies the application of the location permission request in a pop-up window.
- Frontend page code:
```html
<!DOCTYPE html>
<html>
<body>
<p id="locationInfo">Location information</p>
<button onclick="getLocation()">Get Location</button>
<script>
var locationInfo=document.getElementById("locationInfo");
function getLocation(){
if (navigator.geolocation) {
<!-- Access to the device location by the frontend page -->
navigator.geolocation.getCurrentPosition(showPosition);
}
}
function showPosition(position){
locationInfo.innerHTML="Latitude: " + position.coords.latitude + "<br />Longitude: " + position.coords.longitude;
}
</script>
</body>
</html>
```
- Application code:
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Web({ src:$rawfile('getLocation.html'), controller:this.controller })
.geolocationAccess(true)
.onGeolocationShow((event) => { // Notification of the location permission request
AlertDialog.show({
title: 'Location Permission',
message:'Grant access to the device location?',
primaryButton: {
value: 'cancel',
action: () => {
event.geolocation.invoke(event.origin, false, false); // Deny access to the device location.
}
},
secondaryButton: {
value: 'ok',
action: () => {
event.geolocation.invoke(event.origin, true, false); // Allow access to the device location.
}
},
cancel: () => {
event.geolocation.invoke(event.origin, false, false); // Deny access to the device location.
}
})
})
}
}
}
```
# Invoking Frontend Page Functions on the Application
You can call [runJavaScript()](../reference/apis/js-apis-webview.md#runjavascript) on an application to call JavaScript functions of frontend pages.
In the following example, when a user clicks the **runJavaScript** button on the application, the **htmlTest()** API of the frontend page will be triggered.
- Frontend page code:
```html
<!-- index.html -->
<!DOCTYPE html>
<html>
<body>
<script>
function htmlTest() {
console.info('JavaScript Hello World! ');
}
</script>
</body>
</html>
```
- Application code:
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
webviewController: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Web({ src: $rawfile('index.html'), controller: this.webviewController})
Button('runJavaScript')
.onClick(() => {
this.webviewController.runJavaScript('htmlTest()');
})
}
}
}
```
# Invoking Application Functions on the Frontend Page
You can use the **Web** component to register application code with frontend pages. After the registration is done, frontend pages can use the registered object names to call application functions.
Two methods are available for registering the application code:<br>Call [javaScriptProxy()](../reference/arkui-ts/ts-basic-components-web.md#javascriptproxy) during **Web** component initialization.<br> Call [registerJavaScriptProxy()](../reference/apis/js-apis-webview.md#registerjavascriptproxy) after **Web** component initialization.
The following example registers the **test()** function with the frontend page. This way, the **test()** function can be triggered and run on the frontend page.
- Sample code for using [javaScriptProxy()](../reference/arkui-ts/ts-basic-components-web.md#javascriptproxy):
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
webviewController: web_webview.WebviewController = new web_webview.WebviewController();
// Declare the object to be registered.
testObj = {
test: () => {
return 'ArkTS Hello World!';
}
}
build() {
Column() {
// Load the local index.html page.
Web({ src: $rawfile('index.html'), controller: this.webviewController})
// Inject the object to the web client.
.javaScriptProxy({
object: this.testObj,
name: "testObjName",
methodList: ["test"],
controller: this.webviewController
})
}
}
}
```
- Sample code for using [registerJavaScriptProxy()](../reference/apis/js-apis-webview.md#registerjavascriptproxy):
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct Index {
webviewController: web_webview.WebviewController = new web_webview.WebviewController();
testObj = {
test: (data) => {
return "ArkUI Web Component";
},
toString: () => {
console.info('Web Component toString');
}
}
build() {
Column() {
Button('refresh')
.onClick(() => {
try {
this.webviewController.refresh();
} catch (error) {
console.error(`Errorcode: ${error.code}, Message: ${error.message}`);
}
})
Button('Register JavaScript To Window')
.onClick(() => {
try {
this.webviewController.registerJavaScriptProxy(this.testObj, "objName", ["test", "toString"]);
} catch (error) {
console.error(`Errorcode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: $rawfile('index.html'), controller: this.webviewController })
}
}
}
```
> **NOTE**
>
> If you use [registerJavaScriptProxy()](../reference/apis/js-apis-webview.md#registerjavascriptproxy) to register a function, call **[refresh()]**(../reference/apis/js-apis-webview.md#refresh) for the function to take effect.
- Sample code for invoking application functions on the **index.htm** frontend page:
```html
<!-- index.html -->
<!DOCTYPE html>
<html>
<body>
<button type="button" onclick="callArkTS()">Click Me!</button>
<p id="demo"></p>
<script>
function callArkTS() {
let str = testObjName.test();
document.getElementById("demo").innerHTML = str;
console.info('ArkTS Hello World! :' + str);
}
</script>
</body>
</html>
```
# Opening Pages in a New Window
The **Web** component provides the capability of opening pages in a new window. You can call [multiWindowAccess()](../reference/arkui-ts/ts-basic-components-web.md#multiwindowaccess9) to specify whether to allow a web page to be opened in a new window. When a new window is opened in the **Web** component, the application will receive a window opening event through [onWindowNew()](../reference/arkui-ts/ts-basic-components-web.md#onwindownew9). You need to add the code for processing the window opening request in the event callback.
> **NOTE**
>
> - If [allowWindowOpenMethod()](../reference/arkui-ts/ts-basic-components-web.md#allowwindowopenmethod10) is set to **true**, you can open a new window in the frontend page by invoking its JavaScript functions.
>
> - If you do not want to open a new window in [onWindowNew()](../reference/arkui-ts/ts-basic-components-web.md#onwindownew9), set the return value of [ControllerHandler.setWebController()](../reference/arkui-ts/ts-basic-components-web.md#setwebcontroller9) to **null**.
In the following example, when a user clicks the **Open Page in New Window** button, the application receives a window opening event in the [onWindowNew()](../reference/arkui-ts/ts-basic-components-web.md#onwindownew9) callback.
- Application code:
For details about how to create a window, see [Web Development Examples] (https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/Web/Browser).
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Web({ src:$rawfile("window.html"), controller: this.controller })
.multiWindowAccess(true)
.onWindowNew((event) => {
console.info("onWindowNew...");
var popController: web_webview.WebviewController = new web_webview.WebviewController();
// Create a window, associate it with popController, and have popController returned to the Web component. If you do not need to open a new window, set the return value to event.handler.setWebController(null).
event.handler.setWebController(popController);
})
}
}
}
```
- Code of the **window.html** page:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>WindowEvent</title>
</head>
<body>
<input type="button" value="Open Page in New Window" onclick="OpenNewWindow()">
<script type="text/javascript">
function OpenNewWindow()
{
let openedWindow = window.open("about:blank", "", "location=no,status=no,scrollvars=no");
if (openedWindow) {
openedWindow.document.body.write("<p>This is my window</p>");
} else {
log.innerHTML = "window.open failed";
}
}
</script>
</body>
</html>
```
# Loading Pages by Using the Web Component
Page loading is a basic function of the **Web** component. Depending on the data source, page loading falls into three types: loading of network pages, loading of local pages, and loading of HTML rich text data.
If acquisition of network resources is involved in page loading, you need to declare the [ohos.permission.INTERNET](../security/accesstoken-guidelines.md) permission.
## Loading Network Pages
You can specify the default network page to be loaded when creating a **Web** component. After the default network page is loaded, call [loadUrl()](../reference/apis/js-apis-webview.md#loadurl) if you want to change the network page displayed by the **Web** component.
In the following example, after the **www.example.com** page is loaded by the **Web** component, **loadUrl** is called to change the displayed page to **www.example1.com**.
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
webviewController: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('loadUrl')
.onClick(() => {
try {
// Upon button clicking, call loadUrl to redirect to www.example1.com.
this.webviewController.loadUrl('www.example1.com');
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
// When creating a Web component, set the default network page to be loaded to www.example.com.
Web({ src: 'www.example.com', controller: this.webviewController})
}
}
}
```
## Loading Local Pages
Local page files are stored in the application's **rawfile** directory. You can specify the local page to be loaded by default when creating a **Web** component. After page loading is complete, you can call [loadUrl()](../reference/apis/js-apis-webview.md#loadurl) to change the displayed page of the **Web** component.
The following example shows how to load a local page file.
- Local page file in the application's resources/rawfile directory:
**Figure 1** Path of local page files
![resource-path](figures/resource-path.png)
- Application code:
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
webviewController: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('loadUrl')
.onClick(() => {
try {
// Upon button clicking, call loadUrl to redirect to local1.html.
this.webviewController.loadUrl($rawfile("local1.html"));
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
// When creating a Web component, load the local.html file through $rawfile.
Web({ src: $rawfile("local.html"), controller: this.webviewController })
}
}
}
```
- Code of the **local.html** page:
```html
<!-- local.html -->
<!DOCTYPE html>
<html>
<body>
<p>Hello World</p>
</body>
</html>
```
## Loading HTML Rich Text Data
The **Web** component provides the [loadData()](../reference/apis/js-apis-webview.md#loaddata) API for you to load HTML rich text data. This API is applicable if you want to display some page sections instead of the entire page.
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('loadData')
.onClick(() => {
try {
// Upon button clicking, call loadData to load HTML rich text data.
this.controller.loadData(
'<html><body bgcolor=\"white\">Source:<pre>source</pre></body></html>',
'text/html',
'UTF-8'
);
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
// When creating a Web component, set the default network page to be loaded to www.example.com.
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
# Managing Page Redirection and Browsing History Navigation
## History Navigation
When a user clicks a web page link on the frontend page, the **Web** component automatically opens and loads the target website by default. When the current page is assigned a new loading link, the address of the accessed web page is automatically recorded. You can call [forward()](../reference/apis/js-apis-webview.md#forward) or [backward()](../reference/apis/js-apis-webview.md#backward) to browse the previous or next history record.
In the following example, when a user clicks the button, **backward()** is called to go back to the previous page.
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
webviewController: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('loadData')
.onClick(() => {
if (this.webviewController.accessBackward()) {
this.webviewController.backward();
return true;
}
})
Web({ src: 'https://www.example.com/cn/', controller: this.webviewController})
}
}
}
```
If a previous record exists, [accessBackward()](../reference/apis/js-apis-webview.md#accessbackward) will return **true**. Similarly, you can call [accessForward()](../reference/apis/js-apis-webview.md#accessforward) to check whether a next record exists. If you skip the check, [forward()](../reference/apis/js-apis-webview.md#forward) and [backward()](../reference/apis/js-apis-webview.md#backward) will not trigger any action if the user has navigated to the end of history records.
## Page Redirection
The **Web** component provides the [onUrlLoadIntercept()](../reference/arkui-ts/ts-basic-components-web.md#onurlloadintercept) API to redirect you from one page to another.
In the following example, the frontend page **route.html** is loaded on to the application home page **Index.ets**, and the user is redirected to the application page **ProfilePage.ets** when clicking the link on the **route.html** page.
- Code of the **index.ets** page:
```ts
// index.ets
import web_webview from '@ohos.web.webview';
import router from '@ohos.router';
@Entry
@Component
struct WebComponent {
webviewController: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Web({ src: $rawfile('route.html'), controller: this.webviewController })
.onUrlLoadIntercept((event) => {
let url: string = event.data as string;
if (url.indexOf('native://') === 0) {
// Redirect to another page.
router.pushUrl({ url:url.substring(9) })
return true;
}
return false;
})
}
}
}
```
- Code of the **route.html** page:
```html
<!-- route.html -->
<!DOCTYPE html>
<html>
<body>
<div>
<a href="native://pages/ProfilePage">My Profile</a>
</div>
</body>
</html>
```
- Code of the **ProfilePage.ets** page:
```ts
@Entry
@Component
struct ProfilePage {
@State message: string = 'Hello World';
build() {
Column() {
Text(this.message)
.fontSize(20)
}
}
}
```
## Cross-Application Redirection
The **Web** component supports redirection from one application to another.
In the following example, when a user clicks the link on the frontend page **call.html**, the user will be redirected to the dial screen of the phone app.
- Application code:
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
import call from '@ohos.telephony.call';
@Entry
@Component
struct WebComponent {
webviewController: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Web({ src: $rawfile('xxx.html'), controller: this.webviewController})
.onUrlLoadIntercept((event) => {
let url: string = event.data as string;
// Check whether the link is redirecting to the dial screen of the phone app.
if (url.indexOf('tel://') === 0) {
// Redirect to the dial screen.
call.makeCall(url.substring(6), (err) => {
if (!err) {
console.info('make call succeeded.');
} else {
console.info('make call fail, err is:' + JSON.stringify(err));
}
});
return true;
}
return false;
})
}
}
}
```
- Code of the **call.html** page:
```html
<!-- call.html -->
<!DOCTYPE html>
<html>
<body>
<div>
<a href="tel://xxx xxxx xxx">Dial number</a>
</div>
</body>
</html>
```
# Customizing Page Request Responses
The **Web** component supports customization of the response to intercepted page requests. You can call [onInterceptRequest()](../reference/arkui-ts/ts-basic-components-web.md#oninterceptrequest9) to customize web page responses, file resource responses, etc.
When a resource loading request is initiated on a web page, the application layer will receive the request. The application layer then constructs a local resource response and sends it to the web kernel. On receiving the response, the web kernel parses the response and loads page resources accordingly.
In the following example, the **Web** component intercepts the web page request **https://www.intercept.com/test.html** and constructs a custom response in the application code.
- Code of the **example.html** page:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>example</title>
</head>
<body>
<!-- Page resource request ->
<a href="https://www.intercept.com/test.html">intercept test!</a>
</body>
</html>
```
- Application code:
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController()
responseResource: WebResourceResponse = new WebResourceResponse()
// Customize a response.
@State webData: string = '<!DOCTYPE html>\n' +
'<html>\n'+
'<head>\n'+
'<title>intercept test</title>\n'+
'</head>\n'+
'<body>\n'+
'<h1>intercept ok</h1>\n'+
'</body>\n'+
'</html>'
build() {
Column() {
Web({ src: $rawfile('example.html'), controller: this.controller })
.onInterceptRequest((event) => {
console.info('url:' + event.request.getRequestUrl());
// Intercept the web page request.
if (event.request.getRequestUrl() !== 'https://www.intercept.com/test.html') {
return null;
}
// Construct a custom response.
this.responseResource.setResponseData(this.webData);
this.responseResource.setResponseEncoding('utf-8');
this.responseResource.setResponseMimeType('text/html');
this.responseResource.setResponseCode(200);
this.responseResource.setReasonMessage('OK');
return this.responseResource;
})
}
}
}
```
# Setting the Dark Mode
The **Web** component allows you to set the dark mode for frontend pages.
- Call [darkMode()](../reference/arkui-ts/ts-basic-components-web.md#darkmode9) to configure an expected dark mode. [WebDarkMode.Off](../reference/arkui-ts/ts-basic-components-web.md#webdarkmode9) indicates that the dark mode is disabled. [WebDarkMode.On](../reference/arkui-ts/ts-basic-components-web.md#webdarkmode9) indicates that the dark mode is enabled and its setting follows the frontend page. [WebDarkMode.Auto](../reference/arkui-ts/ts-basic-components-web.md#webdarkmode9) indicates that the dark mode is enabled and its setting follows the system.
In the following example, the dark mode setting is configured to follow the system by using [darkMode()](../reference/arkui-ts/ts-basic-components-web.md#darkmode9).
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
@State mode: WebDarkMode = WebDarkMode.Auto;
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
.darkMode(this.mode)
}
}
}
```
- Call [forceDarkAccess()](../reference/arkui-ts/ts-basic-components-web.md#forcedarkaccess9) to forcibly set the dark mode for the frontend page and configure its setting not to follow the frontend page or system. In this mode, you need to specify **WebDarkMode.On** when calling **darkMode()**.
In the following example, [forceDarkAccess()](../reference/arkui-ts/ts-basic-components-web.md#forcedarkaccess9) is used to forcibly set the dark mode for the frontend page.
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
@State mode: WebDarkMode = WebDarkMode.On;
@State access: boolean = true;
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
.darkMode(this.mode)
.forceDarkAccess(this.access)
}
}
}
```
......@@ -720,6 +720,41 @@
- [Lifecycle Definition](reference/arkui-js/js-components-custom-lifecycle.md)
- [Dynamic Component Creation](reference/arkui-js/js-components-create-elements.md)
- [Data Type Attributes](reference/arkui-js/js-appendix-types.md)
- JavaScript-compatible Web-like Development Paradigm (ArkUI.Lite)
- Framework Overview
- [File Organization](js-framework-file.md)
- ["js" Tag](js-framework-js-tag.md)
- [app.js](js-framework-js-file.md)
- Syntax
- [HML](js-framework-syntax-hml.md)
- [CSS](js-framework-syntax-css.md)
- [JavaScript](js-framework-syntax-js.md)
- Universal Component Information
- [Universal Events](js-common-events.md)
- [Universal Attributes](js-common-attributes.md)
- [Universal Styles](js-common-styles.md)
- [Animation Styles](js-components-common-animation.md)
- Container Components
- [div](js-components-container-div.md)
- [list](js-components-container-list.md)
- [list-item](js-components-container-list-item.md)
- [stack](js-components-container-stack.md)
- [swiper](js-components-container-swiper.md)
- Basic Components
- [chart](js-components-basic-chart.md)
- [image](js-components-basic-image.md)
- [image-animator](js-components-basic-image-animator.md)
- [input](js-components-basic-input.md)
- [marquee](js-components-basic-marquee.md)
- [picker-view](js-components-basic-picker-view.md)
- [progress](js-components-basic-progress.md)
- [qrcode](js-components-basic-qrcode.md)
- [slider](js-components-basic-slider.md)
- [switch](js-components-basic-switch.md)
- [text](js-components-basic-text.md)
- Canvas Components
- [canvas](js-components-canvas-canvas.md)
- [CanvasRenderingContext2D](js-components-canvas-canvasrenderingcontext2d.md)
- JS Service Widget UI Components
- JS Service Widget UI Framework
- [File Organization](reference/js-service-widget-ui/js-service-widget-file.md)
......@@ -922,6 +957,7 @@
- [@ohos.curves (Interpolation Calculation)](reference/apis/js-apis-curve.md)
- [@ohos.matrix4 (Matrix Transformation)](reference/apis/js-apis-matrix4.md)
- [@ohos.mediaquery (Media Query)](reference/apis/js-apis-mediaquery.md)
- [@ohos.pluginComponent (PluginComponentManager)](reference/apis/js-apis-plugincomponent.md)
- [@ohos.promptAction (Prompt)](reference/apis/js-apis-promptAction.md)
- [@ohos.router (Page Routing)](reference/apis/js-apis-router.md)
- Graphics
......@@ -1132,6 +1168,7 @@
- [@ohos.systemParameter (System Parameter)](reference/apis/js-apis-system-parameter.md)
- [@ohos.systemTime (System Time and Time Zone)](reference/apis/js-apis-system-time.md)
- [@ohos.usb (USB Management)](reference/apis/js-apis-usb-deprecated.md)
- [@ohos.usbV9 (USB Management)](reference/apis/js-apis-usb.md)
- [@system.app (Application Context)](reference/apis/js-apis-system-app.md)
- [@system.battery (Battery Information)](reference/apis/js-apis-system-battery.md)
- [@system.bluetooth (Bluetooth)](reference/apis/js-apis-system-bluetooth.md)
......@@ -1252,6 +1289,104 @@
- Test
- [UiTest Error Codes](reference/errorcodes/errorcode-uitest.md)
- Native APIs
- Modules
- [Native XComponent](reference/native-apis/_o_h___native_x_component.md)
- [HiLog](reference/native-apis/_hi_log.md)
- [NativeWindow](reference/native-apis/_native_window.md)
- [OH_NativeBuffer](reference/native-apis/_o_h___native_buffer.md)
- [Drawing](reference/native-apis/_drawing.md)
- [OH_NativeImage](reference/native-apis/_o_h___native_image.md)
- [NativeVsync](reference/native-apis/_native_vsync.md)
- [Image](reference/native-apis/image.md)
- [Rawfile](reference/native-apis/rawfile.md)
- [MindSpore](reference/native-apis/_mind_spore.md)
- [NeuralNeworkRuntime](reference/native-apis/_neural_nework_runtime.md)
- [AudioDecoder](reference/native-apis/_audio_decoder.md)
- [AudioEncoder](reference/native-apis/_audio_encoder.md)
- [CodecBase](reference/native-apis/_codec_base.md)
- [VideoDecoder](reference/native-apis/_video_decoder.md)
- [VideoEncoder](reference/native-apis/_video_encoder.md)
- [Core](reference/native-apis/_core.md)
- [HuksKeyApi](reference/native-apis/_huks_key_api.md)
- [HuksParamSetApi](reference/native-apis/_huks_param_set_api.md)
- [HuksTypeApi](reference/native-apis/_huks_type_api.md)
- Head Files
- [drawing_bitmap.h](reference/native-apis/drawing__bitmap_8h.md)
- [drawing_brush.h](reference/native-apis/drawing__brush_8h.md)
- [drawing_canvas.h](reference/native-apis/drawing__canvas_8h.md)
- [drawing_color.h](reference/native-apis/drawing__color_8h.md)
- [drawing_font_collection.h](reference/native-apis/drawing__font__collection_8h.md)
- [drawing_path.h](reference/native-apis/drawing__path_8h.md)
- [drawing_pen.h](reference/native-apis/drawing__pen_8h.md)
- [drawing_text_declaration.h](reference/native-apis/drawing__text__declaration_8h.md)
- [drawing_text_typography.h](reference/native-apis/drawing__text__typography_8h.md)
- [drawing_types.h](reference/native-apis/drawing__types_8h.md)
- [external_window.h](reference/native-apis/external__window_8h.md)
- [image_pixel_map_napi.h](reference/native-apis/image__pixel__map__napi_8h.md)
- [log.h](reference/native-apis/log_8h.md)
- [native_buffer.h](reference/native-apis/native__buffer_8h.md)
- [native_image.h](reference/native-apis/native__image_8h.md)
- [native_interface_xcomponent.h](reference/native-apis/native__interface__xcomponent_8h.md)
- [native_vsync.h](reference/native-apis/native__vsync_8h.md)
- [raw_dir.h](reference/native-apis/raw__dir_8h.md)
- [raw_file_manager.h](reference/native-apis/raw__file__manager_8h.md)
- [raw_file.h](reference/native-apis/raw__file_8h.md)
- [context.h](reference/native-apis/context_8h.md)
- [data_type.h](reference/native-apis/data__type_8h.md)
- [format.h](reference/native-apis/format_8h.md)
- [model.h](reference/native-apis/model_8h.md)
- [status.h](reference/native-apis/status_8h.md)
- [tensor.h](reference/native-apis/tensor_8h.md)
- [types.h](reference/native-apis/types_8h.md)
- [neural_network_runtime_type.h](reference/native-apis/neural__network__runtime__type_8h.md)
- [neural_network_runtime.h](reference/native-apis/neural__network__runtime_8h.md)
- [native_avcodec_audiodecoder.h](reference/native-apis/native__avcodec__audiodecoder_8h.md)
- [native_avcodec_audioencoder.h](reference/native-apis/native__avcodec__audioencoder_8h.md)
- [native_avcodec_base.h](reference/native-apis/native__avcodec__base_8h.md)
- [native_avcodec_videodecoder.h](reference/native-apis/native__avcodec__videodecoder_8h.md)
- [native_avcodec_videoencoder.h](reference/native-apis/native__avcodec__videoencoder_8h.md)
- [native_averrors.h](reference/native-apis/native__averrors_8h.md)
- [native_avformat.h](reference/native-apis/native__avformat_8h.md)
- [native_avmemory.h](reference/native-apis/native__avmemory_8h.md)
- [native_huks_api.h](reference/native-apis/native__huks__api_8h.md)
- [native_huks_param.h](reference/native-apis/native__huks__param_8h.md)
- [native_huks_type.h](reference/native-apis/native__huks__type_8h.md)
- Structs
- [OH_Drawing_BitmapFormat](reference/native-apis/_o_h___drawing___bitmap_format.md)
- [OH_NativeBuffer_Config](reference/native-apis/_o_h___native_buffer___config.md)
- [OH_NativeXComponent_Callback](reference/native-apis/_o_h___native_x_component___callback.md)
- [OH_NativeXComponent_MouseEvent](reference/native-apis/_o_h___native_x_component___mouse_event.md)
- [OH_NativeXComponent_MouseEvent_Callback](reference/native-apis/_o_h___native_x_component___mouse_event___callback.md)
- [OH_NativeXComponent_TouchEvent](reference/native-apis/_o_h___native_x_component___touch_event.md)
- [OH_NativeXComponent_TouchPoint](reference/native-apis/_o_h___native_x_component___touch_point.md)
- [OHExtDataHandle](reference/native-apis/_o_h_ext_data_handle.md)
- [OHHDRMetaData](reference/native-apis/_o_h_h_d_r_meta_data.md)
- [OhosPixelMapCreateOps](reference/native-apis/_ohos_pixel_map_create_ops.md)
- [OhosPixelMapInfo](reference/native-apis/_ohos_pixel_map_info.md)
- [RawFileDescriptor](reference/native-apis/_raw_file_descriptor.md)
- [Region](reference/native-apis/_region.md)
- [Rect](reference/native-apis/_rect.md)
- [OH_AI_CallBackParam](reference/native-apis/_o_h___a_i___call_back_param.md)
- [OH_AI_ShapeInfo](reference/native-apis/_o_h___a_i___shape_info.md)
- [OH_AI_TensorHandleArray](reference/native-apis/_o_h___a_i___tensor_handle_array.md)
- [OH_NN_Memory](reference/native-apis/_o_h___n_n___memory.md)
- [OH_NN_QuantParam](reference/native-apis/_o_h___n_n___quant_param.md)
- [OH_NN_Tensor](reference/native-apis/_o_h___n_n___tensor.md)
- [OH_NN_UInt32Array](reference/native-apis/_o_h___n_n___u_int32_array.md)
- [OH_AVCodecAsyncCallback](reference/native-apis/_o_h___a_v_codec_async_callback.md)
- [OH_AVCodecBufferAttr](reference/native-apis/_o_h___a_v_codec_buffer_attr.md)
- [OH_Huks_Blob](reference/native-apis/_o_h___huks___blob.md)
- [OH_Huks_CertChain](reference/native-apis/_o_h___huks___cert_chain.md)
- [OH_Huks_KeyInfo](reference/native-apis/_o_h___huks___key_info.md)
- [OH_Huks_KeyMaterial25519](reference/native-apis/_o_h___huks___key_material25519.md)
- [OH_Huks_KeyMaterialDh](reference/native-apis/_o_h___huks___key_material_dh.md)
- [OH_Huks_KeyMaterialDsa](reference/native-apis/_o_h___huks___key_material_dsa.md)
- [OH_Huks_KeyMaterialEcc](reference/native-apis/_o_h___huks___key_material_ecc.md)
- [OH_Huks_KeyMaterialRsa](reference/native-apis/_o_h___huks___key_material_rsa.md)
- [OH_Huks_Param](reference/native-apis/_o_h___huks___param.md)
- [OH_Huks_ParamSet](reference/native-apis/_o_h___huks___param_set.md)
- [OH_Huks_PubKeyInfo](reference/native-apis/_o_h___huks___pub_key_info.md)
- [OH_Huks_Result](reference/native-apis/_o_h___huks___result.md)
- Standard Libraries Supported by Native APIs
- [Node_API](reference/native-lib/third_party_napi/napi.md)
- [libuv](reference/native-lib/third_party_libuv/libuv.md)
......@@ -1281,3 +1416,4 @@
- [Usage of Third- and Fourth-Party Libraries](faqs/faqs-third-party-library.md)
- [IDE Usage](faqs/faqs-ide.md)
- [Development Board](faqs/faqs-development-board.md)
<!--no_check-->
......@@ -8,6 +8,7 @@ By default, OpenHarmony provides the battery level based on the current battery
### Constraints
The configuration path for battery level customization is subject to the [configuration policy](https://gitee.com/openharmony/customization_config_policy). In this development guide, `/vendor` is used as an example of the configuration path. During actual development, you need to modify the customization path based on the product configuration policy.
## How to Develop
......@@ -36,7 +37,7 @@ The following uses [DAYU200](https://gitee.com/openharmony/vendor_hihope/tree/ma
├── battery_config.json
```
3. Write the custom `battery_config.json` file by referring to the `battery_config.json` file in the default folder of battery level configuration. For example:
3. Write the custom `battery_config.json` file by referring to the [battery_config.json](https://gitee.com/openharmony/powermgr_battery_manager/blob/master/services/native/profile/battery_config.json) file in the default folder of battery level configuration. For example:
```json
{
......@@ -54,7 +55,7 @@ The following uses [DAYU200](https://gitee.com/openharmony/vendor_hihope/tree/ma
**Table 1** Battery level configuration
| Battery Bevel| Battery Volume| Description|
| Battery Level| Battery Volume| Description|
| -------- | -------- | -------- |
| shutdown | 5 | Power-off battery level|
| critical | 10 | Extremely low battery level|
......@@ -65,7 +66,7 @@ The following uses [DAYU200](https://gitee.com/openharmony/vendor_hihope/tree/ma
| full | 100 | Full battery level|
4. Write the `BUILD.gn` file by referring to the `BUILD.gn` in the default folder of battery level configuration to pack the `battery_config.json` file to the `//vendor/etc/battery` directory. The configuration is as follows:
4. Write the `BUILD.gn` file by referring to the [BUILD.gn](https://gitee.com/openharmony/powermgr_battery_manager/blob/master/services/native/profile/BUILD.gn) file in the default folder of battery level configuration to pack the `battery_config.json` file to the `//vendor/etc/battery` directory. The configuration is as follows:
```shell
import("//build/ohos.gni") # Reference build/ohos.gni.
......@@ -292,6 +293,8 @@ The following uses [DAYU200](https://gitee.com/openharmony/vendor_hihope/tree/ma
## Reference
During development, you can refer to the [default battery level configuration](https://gitee.com/openharmony/powermgr_battery_manager/blob/master/services/native/profile/battery_config.json), as shown below:
```json
{
"soc": {
......@@ -306,4 +309,4 @@ During development, you can refer to the [default battery level configuration](h
}
```
Packing path: `/system/etc/battery`
Packing path: /system/etc/battery
......@@ -8,6 +8,7 @@ OpenHarmony provides the battery level and LED color mapping by default. Some pr
### Constraints
The configuration path for battery level customization is subject to the [configuration policy](https://gitee.com/openharmony/customization_config_policy). In this development guide, `/vendor` is used as an example of the configuration path. During actual development, you need to modify the customization path based on the product configuration policy.
## How to Develop
......@@ -36,7 +37,7 @@ The following uses [DAYU200](https://gitee.com/openharmony/vendor_hihope/tree/ma
├── battery_config.json
```
3. Write the custom `battery_config.json` file by referring to the `battery_config.json` file in the default folder of battery level and LED color mapping configuration. For example:
3. Write the custom `battery_config.json` file by referring to the [battery_config.json](https://gitee.com/openharmony/powermgr_battery_manager/blob/master/services/native/profile/battery_config.json) file in the default folder of battery level and LED color mapping configuration. For example:
```json
{
......@@ -57,18 +58,23 @@ The following uses [DAYU200](https://gitee.com/openharmony/vendor_hihope/tree/ma
}
```
**Table 1** Description of the battery level and LED color mapping configuration
**Table 1** Description of battery levels
| Item| Description|
| Battery Level| Description|
| -------- | -------- |
| low | Low battery level|
| normal | Normal battery level|
| high | High battery level|
**Table 2** Configuration items for the battery level range and LED color
| Configuration Item| Description|
| -------- | -------- |
| soc | Battery level range|
| rgb | LED RGB combination|
4. Write the `BUILD.gn` file by referring to the `BUILD.gn` in the default folder of battery level and LED color mapping configuration to pack the `battery_config.json` file to the `//vendor/etc/battery` directory. The configuration is as follows:
4. Write the `BUILD.gn` file by referring to the [BUILD.gn](https://gitee.com/openharmony/powermgr_battery_manager/blob/master/services/native/profile/BUILD.gn) file in the default folder of battery level and LED color mapping configuration to pack the `battery_config.json` file to the `//vendor/etc/battery` directory. The configuration is as follows:
```shell
import("//build/ohos.gni") # Reference build/ohos.gni.
......@@ -207,6 +213,8 @@ The following uses [DAYU200](https://gitee.com/openharmony/vendor_hihope/tree/ma
## Reference
During development, you can refer to the [default battery level and LED color mapping configuration](https://gitee.com/openharmony/powermgr_battery_manager/blob/master/services/native/profile/battery_config.json), as shown below:
```json
{
"light": {
......@@ -226,4 +234,4 @@ During development, you can refer to the [default battery level and LED color ma
}
```
Packing path: `/system/etc/battery`
Packing path: /system/etc/battery
......@@ -195,7 +195,7 @@
- OpenHarmony Third-Party Components
- [OpenHarmony Third-Party Components](third-party-components/third-party-components-introduction.md)
- [Using OpenHarmony JS and TS Third-Party Components](third-party-components/npm-third-party-guide.md)
- [Using OpenHarmony JS and TS Third-Party Components](third-party-components/ohpm-third-party-guide.md)
- Contribution
- [How to Contribute](contribute/how-to-contribute.md)
......
......@@ -12,10 +12,16 @@ OpenHarmony系统预置的播控中心,作为媒体会话控制方与音视频
## 接口说明
媒体会话控制方使用的关键接口如下表所示。接口返回值有两种返回形式:callback和promise,下表中为callback形式接口,promise和callback只是返回值方式不一样,功能相同。
媒体会话控制方使用的关键接口包括两类:
1. 直接通过import得到的AVSessionManager来调用,例如接口`AVSessionManager.createController(sessionId)`
2. 通过AVSessionController对象来调用,例如接口`controller.getAVPlaybackState()`
异步的JavaScript接口返回值有两种返回形式:callback和promise,本说明仅提供callback形式接口,promise和callback只是返回值方式不一样,功能相同。
更多API说明请参见[API文档](../reference/apis/js-apis-avsession.md)
### 直接通过AVSessionManager调用的接口
| 接口名 | 说明 |
| -------- | -------- |
| getAllSessionDescriptors(callback: AsyncCallback&lt;Array&lt;Readonly&lt;AVSessionDescriptor&gt;&gt;&gt;): void | 获取系统中所有媒体会话的描述符。 |
......@@ -27,6 +33,25 @@ OpenHarmony系统预置的播控中心,作为媒体会话控制方与音视频
| sendControlCommand(command: AVControlCommand, callback: AsyncCallback&lt;void&gt;): void | 通过会话对应的AVSessionController向会话发送播控命令。 |
| sendSystemControlCommand(command: AVControlCommand, callback: AsyncCallback&lt;void&gt;): void | 向置顶会话发送播控命令。 |
### 通过AVSessionController对象调用的接口
| 接口名 | 说明 |
| -------- | -------- |
| getAVPlaybackState(callback: AsyncCallback&lt;AVPlaybackState&gt;): void | 获取当前会话播放状态相关信息。 |
| getAVMetadata(callback: AsyncCallback&lt;AVMetadata&gt;): void | 获取会话元数据。 |
| getOutputDevice(callback: AsyncCallback&lt;OutputDeviceInfo&gt;): void | 获取播放设备信息。 |
| sendAVKeyEvent(event: KeyEvent, callback: AsyncCallback&lt;void&gt;): void | 发送按键事件到会话。|
| getLaunchAbility(callback: AsyncCallback&lt;WantAgent&gt;): void | 获取应用在会话中保存的WantAgent对象。 |
| isActive(callback: AsyncCallback&lt;boolean&gt;): void | 判断会话是否被激活。 |
| destroy(callback: AsyncCallback&lt;void&gt;): void | 销毁当前控制器,销毁后当前控制器不再可用。 |
| getValidCommands(callback: AsyncCallback&lt;Array&lt;AVControlCommandType&gt;&gt;): void | 获取会话支持的有效命令。 |
| sendControlCommand(command: AVControlCommand, callback: AsyncCallback&lt;void&gt;): void | 通过会话控制器发送命令到其对应的会话。 |
| sendCommonCommand(command: string, args: {[key: string]: Object}, callback: AsyncCallback&lt;void&gt;): void<sup>10+<sup> | 通过会话控制器发送自定义命令到其对应的会话。 |
| getAVQueueItems(callback: AsyncCallback&lt;Array&lt;AVQueueItem&gt;&gt;): void<sup>10+<sup> | 获取当前播放列表相关信息。 |
| getAVQueueTitle(callback: AsyncCallback&lt;string&gt;): void<sup>10+<sup> | 获取当前播放列表的名称。 |
| skipToQueueItem(itemId: number, callback: AsyncCallback&lt;void&gt;): void<sup>10+<sup> | 设置指定播放列表单项的ID,发送给session端处理,session端可以选择对这个单项歌曲进行播放。 |
| getExtras(callback: AsyncCallback&lt;{[key: string]: Object}&gt;): void<sup>10+<sup> | 获取媒体提供方设置的自定义媒体数据包。 |
## 开发步骤
系统应用作为媒体会话控制方接入媒体会话的基本步骤如下所示:
......@@ -48,11 +73,11 @@ OpenHarmony系统预置的播控中心,作为媒体会话控制方与音视频
AVSessionManager.createController(descriptor.sessionId).then((controller) => {
g_controller.push(controller);
}).catch((err) => {
console.error(`createController : ERROR : ${err.message}`);
console.error(`Failed to create controller. Code: ${err.code}, message: ${err.message}`);
});
});
}).catch((err) => {
console.error(`getAllSessionDescriptors : ERROR : ${err.message}`);
console.error(`Failed to get all session descriptors. Code: ${err.code}, message: ${err.message}`);
});
```
......@@ -74,7 +99,7 @@ OpenHarmony系统预置的播控中心,作为媒体会话控制方与音视频
AVSessionManager.createController(session.sessionId).then((controller) => {
g_controller.push(controller);
}).catch((err) => {
console.info(`createController : ERROR : ${err.message}`);
console.error(`Failed to create controller. Code: ${err.code}, message: ${err.message}`);
});
});
......@@ -103,7 +128,7 @@ OpenHarmony系统预置的播控中心,作为媒体会话控制方与音视频
// 注册服务异常监听
AVSessionManager.on('sessionServiceDie', () => {
// 服务端异常,应用清理资源
console.info("服务端异常");
console.info(`服务端异常`);
})
```
......@@ -117,6 +142,10 @@ OpenHarmony系统预置的播控中心,作为媒体会话控制方与音视频
- validCommandChange:媒体会话支持的有效命令变化事件。
- outputDeviceChange:播放设备变化事件。
- sessionDestroy:媒体会话销毁事件。
- sessionEvent: 媒体会话自定义事件变化事件。
- extrasChange:媒体会话自定义数据包变化事件。
- queueItemsChange: 媒体会话自定义播放列表变化事件。
- queueTitleChange: 媒体会话自定义播放列表的名称变化事件。
媒体会话控制方可以根据实际需要监听对应的事件。
......@@ -124,18 +153,18 @@ OpenHarmony系统预置的播控中心,作为媒体会话控制方与音视频
// 注册会话激活状态变更监听
controller.on('activeStateChange', (isActive) => {
if (isActive) {
console.info("控制器卡片按键高亮");
console.info(`控制器卡片按键高亮`);
} else {
console.info("控制器卡片按键变更为无效");
console.info(`控制器卡片按键变更为无效`);
}
});
// 注册会话销毁监听
controller.on('sessionDestroy', () => {
console.info('on sessionDestroy : SUCCESS ');
info(`on sessionDestroy : SUCCESS `);
controller.destroy().then(() => {
console.info('destroy : SUCCESS ');
console.info(`destroy : SUCCESS`);
}).catch((err) => {
console.info(`destroy : ERROR :${err.message}`);
console.error(`Failed to destroy session. Code: ${err.code}, message: ${err.message}`);
});
});
......@@ -164,6 +193,22 @@ OpenHarmony系统预置的播控中心,作为媒体会话控制方与音视频
controller.on('outputDeviceChange', (device) => {
console.info(`on outputDeviceChange device isRemote : ${device.isRemote}`);
});
// 注册会话自定义事件变更监听
controller.on('sessionEvent', (eventName, eventArgs) => {
console.info(`Received new session event, event name is ${eventName}, args are ${JSON.stringify(eventArgs)}`);
});
// 注册会话自定义媒体数据包变更监听
controller.on('extrasChange', (extras) => {
console.info(`Received custom media packet, packet data is ${JSON.stringify(extras)}`);
});
// 注册会话自定义播放列表变更监听
controller.on('queueItemsChange', (items) => {
console.info(`Caught queue items change, items length is ${items.length}`);
});
// 注册会话自定义播放标题变更监听
controller.on('queueTitleChange', (title) => {
console.info(`Caught queue title change, title is ${title}`);
});
```
4. 获取媒体会话提供方传递的媒体信息,可以用于界面展示,例如在播控中心展示当前播放的曲目及对应的播放状态。
......@@ -186,6 +231,24 @@ OpenHarmony系统预置的播控中心,作为媒体会话控制方与音视频
let avPlaybackState: AVSessionManager.AVPlaybackState = await controller.getAVPlaybackState();
console.info(`get playbackState by controller : ${avPlaybackState.state}`);
console.info(`get favoriteState by controller : ${avPlaybackState.isFavorite}`);
// 获取session的播放列表信息
let queueItems: Array<AVSessionManager.AVQueueItem> = await controller.getAVQueueItems();
console.info(`get queueItems length by controller : ${queueItems.length}`);
// 获取session的播放标题信息
let queueTitle: string = await controller.getAVQueueTitle();
console.info(`get queueTitle by controller : ${queueTitle}`);
// 获取session的自定义媒体数据包
let extras: any = await controller.getExtras();
console.info(`get custom media packets by controller : ${JSON.stringify(extras)}`);
// 获取session对应应用提供的ability信息
let agent: WantAgent = await controller.getLaunchAbility();
console.info(`get want agent info by controller : ${JSON.stringify(agent)}`);
// 获取session的当前播放位置信息
let currentTime: number = controller.getRealPlaybackPositionSync();
console.info(`get current playback time by controller : ${currentTime}`);
// 获取session支持的有效命令
let validCommands: Array<AVSessionManager.AVControlCommandType> = await controller.getValidCommands();
console.info(`get valid commands by controller : ${JSON.stringify(validCommands)}`);
}
```
......@@ -193,7 +256,6 @@ OpenHarmony系统预置的播控中心,作为媒体会话控制方与音视频
作为媒体会话提供方的音视频应用在监听到相关的播控命令事件后,在相应的逻辑中可以完成对应的操作动作。
```ts
async sendCommandToSessionByController() {
// 假设我们已经有了一个对应session的controller,如何创建controller可以参考之前的案例
......@@ -222,6 +284,23 @@ OpenHarmony系统预置的播控中心,作为媒体会话控制方与音视频
let avCommand: AVSessionManager.AVControlCommand = {command:'playNext'};
controller.sendControlCommand(avCommand);
}
// 下发自定义控制命令
let commandName: string = 'custom command';
let args = {
command : 'This is my custom command'
}
await controller.sendCommonCommand(commandName, args).then(() => {
console.info(`SendCommonCommand successfully`);
}).catch((err) => {
console.error(`Failed to send common command. Code: ${err.code}, message: ${err.message}`);
})
// 设置指定播放列表单项的ID,供session选择播放
let queueItemId: number = 0;
await controller.skipToQueueItem(queueItemId).then(() => {
console.info(`SkipToQueueItem successfully`);
}).catch((err) => {
console.error(`Failed to skip to queue item. Code: ${err.code}, message: ${err.message}`);
});
}
```
......@@ -235,9 +314,9 @@ OpenHarmony系统预置的播控中心,作为媒体会话控制方与音视频
// 销毁当前的controller,销毁后这个controller将不在可用
controller.destroy(function (err) {
if (err) {
console.info(`Destroy controller ERROR : code: ${err.code}, message: ${err.message}`);
console.error(`Failed to destroy controller. Code: ${err.code}, message: ${err.message}`);
} else {
console.info('Destroy controller SUCCESS');
console.info(`Destroy controller SUCCESS`);
}
});
}
......
......@@ -6,7 +6,7 @@
- 媒体会话元数据(AVMetadata): 用于描述媒体数据相关属性,包含标识当前媒体的ID(assetId),上一首媒体的ID(previousAssetId),下一首媒体的ID(nextAssetId),标题(title),专辑作者(author),专辑名称(album),词作者(writer),媒体时长(duration)等属性。
- 媒体播放状态(AVPlaybackState):用于描述媒体播放状态的相关属性,包含当前媒体的播放状态(state)、播放位置(position)、播放倍速(speed)、缓冲时间(bufferedTime)、循环模式(loopMode)、是否收藏(isFavorite)等属性。
- 媒体播放状态(AVPlaybackState):用于描述媒体播放状态的相关属性,包含当前媒体的播放状态(state)、播放位置(position)、播放倍速(speed)、缓冲时间(bufferedTime)、循环模式(loopMode)、是否收藏(isFavorite)、正在播放的媒体Id(activeItemId)、自定义媒体数据(extras)等属性。
## 接口说明
......@@ -21,8 +21,14 @@
| setAVPlaybackState(state: AVPlaybackState, callback: AsyncCallback&lt;void&gt;): void | 设置媒体会话播放状态。 |
| setLaunchAbility(ability: WantAgent, callback: AsyncCallback&lt;void&gt;): void | 设置启动UIAbility。 |
| getController(callback: AsyncCallback&lt;AVSessionController&gt;): void | 获取当前会话自身控制器。 |
| getOutputDevice(callback: AsyncCallback&lt;OutputDeviceInfo&gt;): void | 获取播放设备相关信息。 |
| activate(callback: AsyncCallback&lt;void&gt;): void | 激活媒体会话。 |
| deactivate(callback: AsyncCallback&lt;void&gt;): void | 禁用当前会话。 |
| destroy(callback: AsyncCallback&lt;void&gt;): void | 销毁媒体会话。 |
| setAVQueueItems(items: Array&lt;AVQueueItem&gt;, callback: AsyncCallback&lt;void&gt;): void <sup>10+<sup> | 设置媒体播放列表。 |
| setAVQueueTitle(title: string, callback: AsyncCallback&lt;void&gt;): void<sup>10+<sup> | 设置媒体播放列表名称。 |
| dispatchSessionEvent(event: string, args: {[key: string]: Object}, callback: AsyncCallback&lt;void&gt;): void<sup>10+<sup> | 设置会话内自定义事件。 |
| setExtras(extras: {[key: string]: Object}, callback: AsyncCallback&lt;void&gt;): void<sup>10+<sup> | 设置键值对形式的自定义媒体数据包。|
## 开发步骤
......@@ -31,11 +37,20 @@
1. 通过AVSessionManager的方法创建并激活媒体会话。
```ts
// 创建媒体会话需要获取应用的上下文(context)。开发者可以在应用的EntryAbility文件中设置一个全局变量来存储应用的上下文
export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) {
globalThis.context = this.context; // 设置一个全局变量globalThis.context来存储应用的上下文
}
// 其它EntryAbility类的方法
}
// 开始创建并激活媒体会话
import AVSessionManager from '@ohos.multimedia.avsession'; //导入AVSessionManager模块
// 创建session
async createSession() {
let session: AVSessionManager.AVSession = await AVSessionManager.createAVSession(this.context, 'SESSION_NAME', 'audio');
let session: AVSessionManager.AVSession = await AVSessionManager.createAVSession(globalThis.context, 'SESSION_NAME', 'audio');
session.activate();
console.info(`session create done : sessionId : ${session.sessionId}`);
}
......@@ -50,18 +65,18 @@
```ts
async setSessionInfo() {
// 假设已经创建了一个session,如何创建session可以参考之前的案例
let session: AVSessionManager.AVSession = ALLREADY_CREATE_A_SESSION;
let session: AVSessionManager.AVSession = ALREADY_CREATE_A_SESSION;
// 播放器逻辑··· 引发媒体信息与播放状态的变更
// 设置必要的媒体信息
let metadata: AVSessionManager.AVMetadata = {
assetId: "0",
title: "TITLE",
artist: "ARTIST"
assetId: '0',
title: 'TITLE',
artist: 'ARTIST'
};
session.setAVMetadata(metadata).then(() => {
console.info('SetAVMetadata successfully');
console.info(`SetAVMetadata successfully`);
}).catch((err) => {
console.info(`SetAVMetadata BusinessError: code: ${err.code}, message: ${err.message}`);
console.error(`Failed to set AVMetadata. Code: ${err.code}, message: ${err.message}`);
});
// 简单设置一个播放状态 - 暂停 未收藏
let playbackState: AVSessionManager.AVPlaybackState = {
......@@ -70,9 +85,9 @@
};
session.setAVPlaybackState(playbackState, function (err) {
if (err) {
console.info(`SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
console.error(`Failed to set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
} else {
console.info('SetAVPlaybackState successfully');
console.info(`SetAVPlaybackState successfully`);
}
});
}
......@@ -82,69 +97,171 @@
设置UIAbility时通过WantAgent接口实现,更多关于WantAgent的信息请参考[WantAgent](../reference/apis/js-apis-app-ability-wantAgent.md)
```ts
import WantAgent from "@ohos.app.ability.wantAgent";
import wantAgent from "@ohos.app.ability.wantAgent";
```
```ts
// 假设已经创建了一个session,如何创建session可以参考之前的案例
let session: AVSessionManager.AVSession = ALLREADY_CREATE_A_SESSION;
let session: AVSessionManager.AVSession = ALREADY_CREATE_A_SESSION;
let wantAgentInfo: {
wants: [
{
bundleName: "com.example.musicdemo",
abilityName: "com.example.musicdemo.MainAbility"
bundleName: 'com.example.musicdemo',
abilityName: 'com.example.musicdemo.MainAbility'
}
],
operationType: WantAgent.OperationType.START_ABILITIES,
operationType: wantAgent.OperationType.START_ABILITIES,
requestCode: 0,
wantAgentFlags: [WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
}
wantAgent.getWantAgent(wantAgentInfo).then((agent) => {
session.setLaunchAbility(agent);
})
```
4. 设置一个即时的自定义会话事件,以供媒体控制方接收到事件后进行相应的操作。
> **说明:**<br>
> 通过dispatchSessionEvent方法设置的数据不会保存在会话对象或AVSession服务中。
```ts
// 假设已经创建了一个session,如何创建session可以参考 "1. 通过AVSessionManager的方法创建并激活媒体会话"
let session: AVSessionManager.AVSession = ALREADY_CREATE_A_SESSION;
let eventName = 'dynamic_lyric';
let args = {
lyric : 'This is my lyric'
}
WantAgent.getWantAgent(wantAgentInfo).then((agent) => {
session.setLaunchAbility(agent)
await session.dispatchSessionEvent(eventName, args).then(() => {
console.info(`Dispatch session event successfully`);
}).catch((err) => {
console.error(`Failed to dispatch session event. Code: ${err.code}, message: ${err.message}`);
})
```
4. 注册播控命令事件监听,便于响应用户通过媒体会话控制方,例如播控中心,下发的播控命令。
5. 设置与当前会话相关的自定义媒体数据包,以供媒体控制方接收到事件后进行相应的操作。
> **说明:**<br>
> 通过setExtras方法设置的数据包会被存储在AVSession服务中,数据的生命周期与会话一致;会话对应的Controller可以使用getExtras来获取该数据。
```ts
// 假设已经创建了一个session,如何创建session可以参考之前的案例
let session: AVSessionManager.AVSession = ALREADY_CREATE_A_SESSION;
let extras = {
extra : 'This is my custom meida packet'
}
await session.setExtras(extras).then(() => {
console.info(`Set extras successfully`);
}).catch((err) => {
console.error(`Failed to set extras. Code: ${err.code}, message: ${err.message}`);
})
```
6. 注册播控命令事件监听,便于响应用户通过媒体会话控制方,例如播控中心,下发的播控命令。
在session侧注册的监听分为`固定播控命令``高级播控事件`两种。
4.1 固定控制命令的监听
> **说明:**
>
> 媒体会话提供方在注册相关播控命令事件监听时,监听的事件会在媒体会话控制方的getValidCommands()方法中体现,即媒体会话控制方会认为对应的方法有效,进而根据需要触发相应的事件。为了保证媒体会话控制方下发的播控命令可以被正常执行,媒体会话提供方请勿进行无逻辑的空实现监听。
> 媒体会话提供方在注册相关固定播控命令事件监听时,监听的事件会在媒体会话控制方的getValidCommands()方法中体现,即媒体会话控制方会认为对应的方法有效,进而根据需要触发相应的事件。为了保证媒体会话控制方下发的播控命令可以被正常执行,媒体会话提供方请勿进行无逻辑的空实现监听。
Session侧的固定播控命令主要包括播放、暂停、上一首、下一首等基础操作命令,详细介绍请参见[AVControlCommand](../reference/apis/js-apis-avsession.md)
```ts
async setListenerForMesFromController() {
// 假设已经创建了一个session,如何创建session可以参考之前的案例
let session: AVSessionManager.AVSession = ALLREADY_CREATE_A_SESSION;
let session: AVSessionManager.AVSession = ALREADY_CREATE_A_SESSION;
// 一般在监听器中会对播放器做相应逻辑处理
// 不要忘记处理完后需要通过set接口同步播放相关信息,参考上面的用例
session.on('play', () => {
console.info('on play , do play task');
console.info(`on play , do play task`);
// do some tasks ···
});
session.on('pause', () => {
console.info('on pause , do pause task');
console.info(`on pause , do pause task`);
// do some tasks ···
});
session.on('stop', () => {
console.info('on stop , do stop task');
console.info(`on stop , do stop task`);
// do some tasks ···
});
session.on('playNext', () => {
console.info('on playNext , do playNext task');
console.info(`on playNext , do playNext task`);
// do some tasks ···
});
session.on('playPrevious', () => {
console.info('on playPrevious , do playPrevious task');
console.info(`on playPrevious , do playPrevious task`);
// do some tasks ···
});
session.on('fastForward', () => {
console.info(`on fastForward , do fastForward task`);
// do some tasks ···
});
session.on('rewind', () => {
console.info(`on rewind , do rewind task`);
// do some tasks ···
});
session.on('seek', (time) => {
console.info(`on seek , the seek time is ${time}`);
// do some tasks ···
});
session.on('setSpeed', (speed) => {
console.info(`on setSpeed , the speed is ${speed}`);
// do some tasks ···
});
session.on('setLoopMode', (mode) => {
console.info(`on setLoopMode , the loop mode is ${mode}`);
// do some tasks ···
});
session.on('toggleFavorite', (assetId) => {
console.info(`on toggleFavorite , the target asset Id is ${assetId}`);
// do some tasks ···
});
}
```
4.2 高级播控事件的监听
Session侧的可以注册的高级播控事件主要包括:
- skipToQueueItem: 播放列表其中某项被选中的事件。
- handleKeyEvent: 按键事件。
- outputDeviceChange: 播放设备变化的事件。
- commonCommand: 自定义控制命令变化的事件。
```ts
async setListenerForMesFromController() {
// 假设已经创建了一个session,如何创建session可以参考之前的案例
let session: AVSessionManager.AVSession = ALREADY_CREATE_A_SESSION;
// 一般在监听器中会对播放器做相应逻辑处理
// 不要忘记处理完后需要通过set接口同步播放相关信息,参考上面的用例
session.on('skipToQueueItem', (itemId) => {
console.info(`on skipToQueueItem , do skip task`);
// do some tasks ···
});
session.on('handleKeyEvent', (event) => {
console.info(`on handleKeyEvent , the event is ${JSON.stringify(event)}`);
// do some tasks ···
});
session.on('outputDeviceChange', (device) => {
console.info(`on outputDeviceChange , the device info is ${JSON.stringify(device)}`);
// do some tasks ···
});
session.on('commonCommand', (commandString, args) => {
console.info(`on commonCommand , command is ${commandString}, args are ${JSON.stringify(args)}`);
// do some tasks ···
});
}
```
5. 获取当前媒体会话自身的控制器,与媒体会话对应进行通信交互。
7. 获取当前媒体会话自身的控制器,与媒体会话对应进行通信交互。
```ts
async createControllerFromSession() {
// 假设已经创建了一个session,如何创建session可以参考之前的案例
let session: AVSessionManager.AVSession = ALLREADY_CREATE_A_SESSION;
let session: AVSessionManager.AVSession = ALREADY_CREATE_A_SESSION;
// 通过已有session获取一个controller对象
let controller: AVSessionManager.AVSessionController = await session.getController();
......@@ -163,13 +280,13 @@
}
```
6. 音视频应用在退出,并且不需要继续播放时,及时取消监听以及销毁媒体会话释放资源。
8. 音视频应用在退出,并且不需要继续播放时,及时取消监听以及销毁媒体会话释放资源。
取消播控命令监听的示例代码如下所示 :
```ts
async unregisterSessionListener() {
// 假设已经创建了一个session,如何创建session可以参考之前的案例
let session: AVSessionManager.AVSession = ALLREADY_CREATE_A_SESSION;
let session: AVSessionManager.AVSession = ALREADY_CREATE_A_SESSION;
// 取消指定session下的相关监听
session.off('play');
......@@ -177,6 +294,10 @@
session.off('stop');
session.off('playNext');
session.off('playPrevious');
session.off('skipToQueueItem');
session.off('handleKeyEvent');
session.off('outputDeviceChange');
session.off('commonCommand');
}
```
......@@ -185,13 +306,13 @@
```ts
async destroySession() {
// 假设已经创建了一个session,如何创建session可以参考之前的案例
let session: AVSessionManager.AVSession = ALLREADY_CREATE_A_SESSION;
let session: AVSessionManager.AVSession = ALREADY_CREATE_A_SESSION;
// 主动销毁已创建的session
session.destroy(function (err) {
if (err) {
console.info(`Destroy BusinessError: code: ${err.code}, message: ${err.message}`);
console.error(`Failed to destroy session. Code: ${err.code}, message: ${err.message}`);
} else {
console.info('Destroy : SUCCESS ');
console.info(`Destroy : SUCCESS `);
}
});
}
......
......@@ -36,15 +36,15 @@
let audioDevices;
await audioRoutingManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data) => {
audioDevices = data;
console.info('Promise returned to indicate that the device list is obtained.');
console.info(`Promise returned to indicate that the device list is obtained.`);
}).catch((err) => {
console.info(`getDevices : ERROR : ${err.message}`);
console.error(`Failed to get devices. Code: ${err.code}, message: ${err.message}`);
});
AVSessionManager.castAudio('all', audioDevices).then(() => {
console.info('createController : SUCCESS');
console.info(`createController : SUCCESS`);
}).catch((err) => {
console.info(`createController : ERROR : ${err.message}`);
console.error(`Failed to cast audio. Code: ${err.code}, message: ${err.message}`);
});
```
......
......@@ -25,7 +25,7 @@
- 系统组件:ArkUI框架中默认内置的基础和容器组件,可直接被开发者调用,比如示例中的Column、Text、Divider、Button。
- 属性方法:组件可以通过链式调用配置多项属性,如fontSize()、width()、height()、color()等。
- 属性方法:组件可以通过链式调用配置多项属性,如fontSize()、width()、height()、backgroundColor()等。
- 事件方法:组件可以通过链式调用设置多个事件的响应逻辑,如跟随在Button后面的onClick()。
......
......@@ -122,7 +122,7 @@ struct ParentComponent {
- 不支持静态函数。
- 成员函数的访问始终是私有的,仅能定义private。定义访问权限是可选的,其他访问权限会带来语法错误
- 成员函数的访问始终是私有的。
自定义组件可以包含成员变量,成员变量具有以下约束:
......
......@@ -104,7 +104,7 @@ Column() {
## 配置事件
事件方法以“.”链式调用的方式配置系统组件支持的事件,建议每个属性方法单独写一行。
事件方法以“.”链式调用的方式配置系统组件支持的事件,建议每个事件方法单独写一行。
- 使用lambda表达式配置组件的事件方法。
......
......@@ -15,7 +15,7 @@
-\@Observed装饰的类,可以被观察到属性的变化;
- 子组件中\@ObjectLink装饰器装饰的状态变量用于接\@Observed装饰的类的实例,和父组件中对应的状态变量建立双向数据绑定。这个实例可以是数组中的被\@Observed装饰的项,或者是class object中是属性,这个属性同样也需要被\@Observed装饰。
- 子组件中\@ObjectLink装饰器装饰的状态变量用于接\@Observed装饰的类的实例,和父组件中对应的状态变量建立双向数据绑定。这个实例可以是数组中的被\@Observed装饰的项,或者是class object中是属性,这个属性同样也需要被\@Observed装饰。
- 单独使用\@Observed是没有任何作用的,需要搭配\@ObjectLink或者[\@Prop](arkts-prop.md)使用。
......@@ -111,7 +111,7 @@ this.b.b = 5
this.b.a.c = 5
```
\@ObjectLink:\@ObjectLink只能接\@Observed装饰class的实例,可以观察到:
\@ObjectLink:\@ObjectLink只能接\@Observed装饰class的实例,可以观察到:
- 其属性的数值的变化,其中属性是指Object.keys(observedObject)返回的所有属性,示例请参考[嵌套对象](#嵌套对象)
......@@ -122,7 +122,7 @@ this.b.a.c = 5
1. 初始渲染:
1. \@Observed装饰的class的实例会被不透明的代理对象包装,代理了class上的属性的setter和getter方法
2. 子组件中\@ObjectLink装饰的从父组件初始化,接\@Observed装饰的class的实例,\@ObjectLink的包装类会将自己注册给\@Observed class。
2. 子组件中\@ObjectLink装饰的从父组件初始化,接\@Observed装饰的class的实例,\@ObjectLink的包装类会将自己注册给\@Observed class。
2. 属性更新:当\@Observed装饰的class属性改变时,会走到代理的setter和getter,然后遍历依赖它的\@ObjectLink包装类,通知数据更新。
......
......@@ -19,7 +19,7 @@
- [onBackPress](../reference/arkui-ts/ts-custom-component-lifecycle.md#onbackpress):当用户点击返回按钮时触发。
组件生命周期,即一般用\@Component装饰的自定义组件,提供以下生命周期接口:
组件生命周期,即一般用\@Component装饰的自定义组件的生命周期,提供以下生命周期接口:
- [aboutToAppear](../reference/arkui-ts/ts-custom-component-lifecycle.md#abouttoappear):组件即将出现时回调该接口,具体时机为在创建自定义组件的新实例后,在执行其build()函数之前执行。
......@@ -134,7 +134,7 @@ struct MyComponent {
Child()
}
// this.showChild为false,删除Child子组件,执行Child aboutToDisappear
Button('create or delete Child').onClick(() => {
Button('delete Child').onClick(() => {
this.showChild = false;
})
// push到Page2页面,执行onPageHide
......@@ -168,7 +168,7 @@ struct Child {
```
以上示例中,Index页面包含两个自定义组件,一个是被\@Entry装饰的MyComponent,也是页面的入口组件,即页面的根节点;一个是Child,是MyComponent的子组件。只有\@Entry装饰的节点才可以生效页面的生命周期方法,所以MyComponent中声明了当前Index页面的页面生命周期函数。MyComponent和其子组件Child也同时声明了组件的生命周期函数。
以上示例中,Index页面包含两个自定义组件,一个是被\@Entry装饰的MyComponent,也是页面的入口组件,即页面的根节点;一个是Child,是MyComponent的子组件。只有\@Entry装饰的节点才可以生效页面的生命周期方法,所以MyComponent中声明了当前Index页面的页面生命周期函数。MyComponent和其子组件Child也同时声明了组件的生命周期函数。
- 应用冷启动的初始化流程为:MyComponent aboutToAppear --&gt; MyComponent build --&gt; Child aboutToAppear --&gt; Child build --&gt; Child build执行完毕 --&gt; MyComponent build执行完毕 --&gt; Index onPageShow。
......
......@@ -75,15 +75,17 @@ interface DataChangeListener {
}
```
| 接口声明 | 参数类型 | 说明 |
| ---------------------------------------- | -------------------------------------- | ---------------------------------------- |
| onDataReloaded():&nbsp;void | - | 通知组件重新加载所有数据。 |
| onDataAdded(index:&nbsp;number):void | number | 通知组件index的位置有数据添加。<br/>index:数据添加位置的索引值 |
| onDataMoved(from:&nbsp;number,&nbsp;to:&nbsp;number):&nbsp;void | from:&nbsp;number,<br/>to:&nbsp;number | 通知组件数据有移动。<br/>from:&nbsp;数据移动起始位置,to:&nbsp;数据移动目标位置。<br/>**说明:**<br/>数据移动前后键值要保持不变,如果键值有变化,应使用删除数据和新增数据接口。 |
| onDataChanged(index:&nbsp;number):&nbsp;void | number | 通知组件index的位置有数据有变化。<br/>index:数据变化监听器。 |
| onDataAdd(index:&nbsp;number):&nbsp;void | number | 通知组件index的位置有数据添加。<br/>index:数据添加位置的索引值 |
| onDataMove(from:&nbsp;number,&nbsp;to:&nbsp;number):&nbsp;void | from:&nbsp;number,<br/>to:&nbsp;number | 通知组件数据有移动。<br/>from:&nbsp;数据移动起始位置,to:&nbsp;数据移动目标位置。<br/>**说明:**<br/>数据移动前后键值要保持不变,如果键值有变化,应使用删除数据和新增数据接口。 |
| onDataChanged(index:&nbsp;number):&nbsp;void | number | 通知组件index的位置有数据有变化。<br/>index:数据变化位置的索引值 |
| 接口声明 | 参数类型 | 说明 |
| ------------------------------------------------------------ | -------------------------------------- | ------------------------------------------------------------ |
| onDataReloaded():&nbsp;void | - | 通知组件重新加载所有数据。 |
| onDataAdded(index:&nbsp;number):void<sup>(deprecated)</sup> | number | 通知组件index的位置有数据添加。<br/>从API 8开始,建议使用onDataAdd。<br/>index:数据添加位置的索引值 |
| onDataMoved(from:&nbsp;number,&nbsp;to:&nbsp;number):&nbsp;void<sup>(deprecated)</sup> | from:&nbsp;number,<br/>to:&nbsp;number | 通知组件数据有移动。<br/>从API 8开始,建议使用onDataMove。<br/>from:&nbsp;数据移动起始位置,to:&nbsp;数据移动目标位置。<br/>**说明:**<br/>数据移动前后键值要保持不变,如果键值有变化,应使用删除数据和新增数据接口。 |
| onDataDeleted(index: number):void<sup>(deprecated)</sup> | number | 通知组件删除index位置的数据并刷新LazyForEach的展示内容。<br/>从API 8开始,建议使用onDataDelete。<br/>index:数据删除位置的索引值 |
| onDataChanged(index:&nbsp;number):&nbsp;void<sup>(deprecated)</sup> | number | 通知组件index的位置有数据有变化。<br/>从API 8开始,建议使用onDataChange。<br/>index:数据变化监听器。 |
| onDataAdd(index:&nbsp;number):&nbsp;void<sup>8+</sup> | number | 通知组件index的位置有数据添加。<br/>index:数据添加位置的索引值 |
| onDataMove(from:&nbsp;number,&nbsp;to:&nbsp;number):&nbsp;void<sup>8+</sup> | from:&nbsp;number,<br/>to:&nbsp;number | 通知组件数据有移动。<br/>from:&nbsp;数据移动起始位置,to:&nbsp;数据移动目标位置。<br/>**说明:**<br/>数据移动前后键值要保持不变,如果键值有变化,应使用删除数据和新增数据接口。 |
| onDataDelete(index: number):void<sup>8+</sup> | number | 通知组件删除index位置的数据并刷新LazyForEach的展示内容。<br/>index:数据删除位置的索引值<br/>**说明:** <br/>需要保证dataSource中的对应数据已经在调用onDataDelete前删除,否则页面渲染将出现未定义的行为。 |
| onDataChange(index:&nbsp;number):&nbsp;void<sup>8+</sup> | number | 通知组件index的位置有数据有变化。<br/>index:数据变化位置的索引值 |
## 使用限制
......
......@@ -106,6 +106,10 @@ ArkUI提供了多种装饰器,通过使用这些装饰器,状态变量不仅
- \@ObjectLink:\@ObjectLink装饰的变量接收\@Observed装饰的class的实例,应用于观察多层嵌套场景,和父组件的数据源构建双向同步。
> **说明:**
>
> 仅[\@Observed/\@ObjectLink](arkts-observed-and-objectlink.md)可以观察嵌套场景,其他的状态变量仅能观察第一层,详情见各个装饰器章节的“观察变化和行为表现”小节。
[管理应用拥有的状态](arkts-application-state-management-overview.md),即图中Application级别的状态管理:
......
......@@ -231,11 +231,11 @@ struct MyComponent {
Text(`${this.title.value}`)
Button(`Click to change title`).onClick(() => {
// @State变量的更新将触发上面的Text组件内容更新
this.title.value = this.title.value === 'Hello ArkUI' ? 'Hello World' : 'HelloArkUI';
this.title.value = this.title.value === 'Hello ArkUI' ? 'Hello World' : 'Hello ArkUI';
})
Button(`Click to increase count=${this.count}`).onClick(() => {
// @State变量的更新将触发上面的Text组件内容更新
// @State变量的更新将触发该Button组件的内容更新
this.count += this.increaseBy;
})
}
......
......@@ -296,7 +296,7 @@ OpenHarmony系统对无图标应用严格管控。如果HAP中没有配置入口
| [launchType](../application-models/uiability-launch-type.md) | 标识当前UIAbility组件的启动模式,可选标签值:<br/>-&nbsp;multiton:标准实例模式,每次启动创建一个新的实例。<br/>-&nbsp;singleton:单实例模式,仅第一次启动创建新实例。<br/>-&nbsp;specified:指定实例模式,运行时由开发者决定是否创建新实例。 | 字符串 | 可缺省,该标签缺省为“singleton”。 |
| description | 标识当前UIAbility组件的描述信息,标签值是字符串类型(最长255字节)或对描述内容的资源索引,要求采用资源索引方式,以支持多语言。 | 字符串 | 该标签可缺省,缺省值为空。 |
| icon | 标识当前UIAbility组件的图标,标签值为图标资源文件的索引。 | 字符串 | 该标签可缺省,缺省值为空。<br/>如果UIAbility被配置为MainElement,该标签必须配置。 |
| label | 标识当前UIAbility组件对用户显示的名称,标签值配置为该名称的资源索引以支持多语言。<br/>如果UIAbility被配置当前Module的mainElement时,该标签必须配置,且应用内唯一。 | 字符串 | 该标签不可缺省。 |
| label | 标识当前UIAbility组件对用户显示的名称,标签值配置为该名称的资源索引以支持多语言。 | 字符串 | 该标签可缺省,缺省值为空。<br/>如果UIAbility被配置为MainElement,该标签必须配置。 |
| permissions | 标识当前UIAbility组件自定义的权限信息。当其他应用访问该UIAbility时,需要申请相应的权限信息。<br/>一个数组元素为一个权限名称。通常采用反向域名格式(最大255字节),取值为系统预定义的权限。 | 字符串数组 | 该标签可缺省,缺省值为空。 |
| [metadata](#metadata标签) | 标识当前UIAbility组件的元信息。 | 对象数组 | 该标签可缺省,缺省值为空。 |
| exported | 标识当前UIAbility组件是否可以被其他应用调用。<br/>-&nbsp;true:表示可以被其他应用调用。<br/>-&nbsp;false:表示不可以被其他应用调用。 | 布尔值 | 该标签可缺省,缺省值为false。 |
......@@ -802,8 +802,8 @@ dependencies标签示例:
| 属性名称 | 含义 | 数据类型 | 是否可缺省 |
| ----------- | ------------------------------ | -------- | ---------- |
| uri | 标识用于访问该数据代理的uri,不同的数据代理配置的uri不可重复,且需要满足`datashareproxy://当前应用包名/xxx`的格式。 | 字符串 | 不可缺省。 |
| requiredReadPermission | 标识从该数据代理中读取数据所需要的权限,非系统应用配置的权限的等级需为system_basic或system_core,系统应用可以不配置权限,且权限的等级没有限制。权限等级可以参考[权限列表](../security/permission-list.md) | 字符串 | 可缺省,缺省值为空。 |
| requiredWritePermission | 标识向该数据代理中读取数据所需要的权限。非系统应用配置的权限的等级需为system_basic或system_core,系统应用可以不配置权限,且权限的等级没有限制。权限等级可以参考[权限列表](../security/permission-list.md) | 字符串 | 可缺省,缺省值为空。 |
| requiredReadPermission | 标识从该数据代理中读取数据所需要的权限,非系统应用配置的权限的等级需为system_basic或system_core,系统应用可以不配置权限,且权限的等级没有限制。权限等级可以参考[权限列表](../security/permission-list.md) | 字符串 | 可缺省,缺省值为空。 |
| requiredWritePermission | 标识向该数据代理中读取数据所需要的权限。非系统应用配置的权限的等级需为system_basic或system_core,系统应用可以不配置权限,且权限的等级没有限制。权限等级可以参考[权限列表](../security/permission-list.md) | 字符串 | 可缺省,缺省值为空。 |
| [metadata](#metadata标签) | 标识该数据代理的元信息,只支持配置name和resource字段。 | 对象 | 可缺省,缺省值为空。 |
proxyDatas标签示例:
......
......@@ -261,7 +261,7 @@ OpenHarmony系统对无图标应用严格管控。如果HAP中没有配置入口
| name | 标识Ability名称。取值可采用反向域名方式表示,由包名和类名组成,如"com.example.myapplication.EntryAbility";也可采用"."开头的类名方式表示,如".EntryAbility"。<br/>Ability的名称,需在一个应用的范围内保证唯一。说明:在使用DevEco&nbsp;Studio新建项目时,默认生成首个Ability的配置,即"config.json"中"EntryAbility"的配置。如使用其他IDE工具,可自定义名称。该标签最大长度为127个字节。 | 字符串 | 不可缺省 |
| description | 标识对Ability的描述。取值可以是描述性内容,也可以是对描述性内容的资源索引,以支持多语言。该标签最大长度为255个字节。 | 字符串 | 可缺省,缺省值为空。 |
| icon | 标识Ability图标资源文件的索引。取值示例:$media:ability_icon。如果在该Ability的skills属性中,actions的取值包含&nbsp;"action.system.home",entities取值中包含"entity.system.home",则该Ability的icon将同时作为应用的icon。如果存在多个符合条件的Ability,则取位置靠前的Ability的icon作为应用的icon。<br/>说明:应用的"icon"和"label"是用户可感知配置项,需要区别于当前所有已有的应用"icon"或"label"(至少有一个不同)。 | 字符串 | 可缺省,缺省值为空。 |
| label | 标识Ability对用户显示的名称。取值可以是Ability名称,也可以是对该名称的资源索引,以支持多语言。如果在该Ability的skills属性中,actions的取值包含&nbsp;"action.system.home",entities取值中包含"entity.system.home",则该Ability的label将同时作为应用的label。如果存在多个符合条件的Ability,则取位置靠前的Ability的label作为应用的label。<br/>说明:&nbsp;应用的"icon"和"label"是用户可感知配置项,需要区别于当前所有已有的应用"icon"或"label"(至少有一个不同)。该标签为资源文件中定义的字符串的引用,或以"{}"包括的字符串。该标签最大长度为255个字节。 | 字符串 | 可缺省,缺省值为空。 |
| label | 标识Ability对用户显示的名称。取值是对该名称的资源索引,支持多语言,例:$string:ability_label。如果在该Ability的skills属性中,actions的取值包含&nbsp;"action.system.home",entities取值中包含"entity.system.home",则该Ability的label将同时作为应用的label。如果存在多个符合条件的Ability,则取位置靠前的Ability的label作为应用的label。<br/>说明:&nbsp;应用的"icon"和"label"是用户可感知配置项,需要区别于当前所有已有的应用"icon"或"label"(至少有一个不同)。该标签为资源文件中定义的字符串的引用,或以"{}"包括的字符串。该标签最大长度为255个字节。 | 字符串 | 可缺省,缺省值为空。 |
| uri | 标识Ability的统一资源标识符。该标签最大长度为255个字节。 | 字符串 | 可缺省,对于data类型的Ability不可缺省。 |
| launchType | 标识Ability的启动模式,支持"standard"和"singleton"两种模式:<br/>standard:表示该Ability可以有多实例。该模式适用于大多数应用场景。<br/>singleton:表示该Ability在所有任务栈中仅可以有一个实例。例如,具有全局唯一性的呼叫来电界面即采用"singleton"模式。该标签仅适用于默认设备、平板、智慧屏、车机、智能穿戴。 | 字符串 | 可缺省,缺省值为"singleton"。 |
| visible | 标识Ability是否可以被其他应用调用。<br/>true:可以被其他应用调用。<br/>false:不能被其他应用调用。 | 布尔类型 | 可缺省,缺省值为"false"。 |
......
......@@ -314,8 +314,6 @@
- [Timer (定时器)](js-apis-timer.md)
- application
- [AccessibilityExtensionContext (辅助功能扩展上下文)](js-apis-inner-application-accessibilityExtensionContext.md)
- imf
- [InputMethodCommon](js-apis-inputmethod-InputMethodCommon.md)
- 设备管理
- [@ohos.batteryInfo (电量信息)](js-apis-battery-info.md)
......@@ -356,8 +354,9 @@
- 定制管理
- [@ohos.configPolicy (配置策略)](js-apis-configPolicy.md)
- [@ohos.enterprise.accountManager (帐户管理)](js-apis-enterprise-accountManager.md)
- [@ohos.enterprise.bundleManager (包管理)](js-apis-enterprise-bundleManager.md)
- [@ohos.enterprise.adminManager (企业设备管理)](js-apis-enterprise-adminManager.md)
- [@ohos.enterprise.applicationManager (应用管理)](js-apis-enterprise-applicationManager.md)
- [@ohos.enterprise.bundleManager (包管理)](js-apis-enterprise-bundleManager.md)
- [@ohos.enterprise.dateTimeManager (系统时间管理)](js-apis-enterprise-dateTimeManager.md)
- [@ohos.enterprise.deviceControl (设备控制管理)](js-apis-enterprise-deviceControl.md)
- [@ohos.enterprise.deviceInfo (设备信息管理)](js-apis-enterprise-deviceInfo.md)
......
......@@ -145,6 +145,29 @@ Extension生命周期回调,如果是connectAbility拉起的服务,会在onC
}
```
如果生成返回值RemoteObject依赖一个异步接口,可以使用异步生命周期:
```ts
import rpc from '@ohos.rpc';
class StubTest extends rpc.RemoteObject{
constructor(des) {
super(des);
}
onConnect(code, data, reply, option) {
}
}
async function getDescriptor() {
// 调用异步函数...
return "asyncTest"
}
class ServiceExt extends ServiceExtension {
async onConnect(want) {
console.log(`onConnect , want: ${want.abilityName}`);
let descriptor = await getDescriptor();
return new StubTest(descriptor);
}
}
```
## ServiceExtensionAbility.onDisconnect
......@@ -172,6 +195,17 @@ Extension的生命周期回调,客户端执行断开连接服务时回调。
}
```
在执行完onDisconnect生命周期回调后,应用可能会退出,从而可能导致onDisconnect中的异步函数未能正确执行,比如异步写入数据库。可以使用异步生命周期,以确保异步onDisconnect完成后再继续后续的生命周期。
```ts
class ServiceExt extends ServiceExtension {
async onDisconnect(want) {
console.log('onDisconnect, want: ${want.abilityName}');
// 调用异步函数...
}
}
```
## ServiceExtensionAbility.onReconnect
onReconnect(want: Want): void;
......
......@@ -132,6 +132,7 @@ UIAbility生命周期回调,在销毁时回调,执行资源清理等操作
**示例:**
```ts
class MyUIAbility extends UIAbility {
onDestroy() {
......@@ -140,6 +141,16 @@ UIAbility生命周期回调,在销毁时回调,执行资源清理等操作
}
```
在执行完onDestroy生命周期回调后,应用可能会退出,从而可能导致onDestroy中的异步函数未能正确执行,比如异步写入数据库。可以使用异步生命周期,以确保异步onDestroy完成后再继续后续的生命周期。
```ts
class MyUIAbility extends UIAbility {
async onDestroy() {
console.log('onDestroy');
// 调用异步函数...
}
}
```
## UIAbility.onForeground
......
# @ohos.enterprise.applicationManager(应用管理)
本模块提供应用管理能力,包括添加应用运行黑名单、获取应用运行黑名单、移除应用运行黑名单等。仅企业设备管理员应用才能调用。
> **说明:**
>
> 本模块首批接口从API version 10开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 导入模块
```js
import applicationManager from '@ohos.enterprise.applicationManager';
```
## applicationManager.addDisallowedRunningBundles
addDisallowedRunningBundles(admin: Want, appIds: Array\<string>, callback: AsyncCallback&lt;void&gt;): void;
指定设备管理员应用添加应用运行黑名单接口,使用callback形式返回是否添加成功。添加至黑名单的应用不允许在管理员用户下运行,否则允许运行。
**需要权限:** ohos.permission.ENTERPRISE_MANAGE_SET_APP_RUNNING_POLICY
**系统能力:** SystemCapability.Customization.EnterpriseDeviceManager
**系统API**: 此接口为系统接口。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------- | ---- | ------------------------------- |
| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 |
| appIds | Array&lt;string&gt; | 是 | 应用运行的黑名单。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。当接口调用成功,err为null,否则为错误对象。 |
**错误码**
以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-enterpriseDeviceManager.md)
| 错误码ID | 错误信息 |
| ------- | ---------------------------------------------------------------------------- |
| 9200001 | the application is not an administrator of the device. |
| 9200002 | the administrator application does not have permission to manage the device. |
**示例:**
```js
let wantTemp = {
bundleName: "com.example.myapplication",
abilityName: "EntryAbility",
};
let appIds = {"com.example.myapplication"};
applicationManager.addDisallowedRunningBundles(wantTemp, appIds, (error) => {
if (error != null) {
console.log("error code:" + error.code + " error message:" + error.message);
}
});
```
## applicationManager.addDisallowedRunningBundles
addDisallowedRunningBundles(admin: Want, appIds: Array\<string>, userId: number, callback: AsyncCallback&lt;void&gt;): void;
指定设备管理员应用添加应用运行黑名单接口,使用callback形式返回是否添加成功。添加至黑名单的应用不允许在指定用户(通过userId指定)下运行,否则允许运行。
**需要权限:** ohos.permission.ENTERPRISE_MANAGE_SET_APP_RUNNING_POLICY
**系统能力:** SystemCapability.Customization.EnterpriseDeviceManager
**系统API**: 此接口为系统接口。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ----- | ----------------------------------- | ---- | ------- |
| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 |
| appIds | Array&lt;string&gt; | 是 | 应用运行的黑名单。 |
| userId | number | 是 | 用户ID。默认值:调用方所在用户,取值范围:大于等于0。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数,当接口调用成功,err为null,否则为错误对象。 |
**错误码**
以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-enterpriseDeviceManager.md)
| 错误码ID | 错误信息 |
| ------- | ---------------------------------------------------------------------------- |
| 9200001 | the application is not an administrator of the device. |
| 9200002 | the administrator application does not have permission to manage the device. |
**示例:**
```js
let wantTemp = {
bundleName: "com.example.myapplication",
abilityName: "EntryAbility",
};
let appIds = {"com.example.myapplication"};
applicationManager.addDisallowedRunningBundles(wantTemp, appIds, 100, (error) => {
if (error != null) {
console.log("error code:" + error.code + " error message:" + error.message);
}
});
```
## applicationManager.addDisallowedRunningBundles
addDisallowedRunningBundles(admin: Want, appIds: Array\<string>, userId?: number): Promise&lt;void&gt;;
指定设备管理员应用添加应用运行黑名单接口,使用promise形式返回是否添加成功。如果调用接口时传入了可选参数userId,则添加至黑名单的应用不允许在指定用户下运行,如果调用接口时没有传入参数userId,则添加至黑名单的应用不允许在当前用户下运行。
**需要权限:** ohos.permission.ENTERPRISE_MANAGE_SET_APP_RUNNING_POLICY
**系统能力:** SystemCapability.Customization.EnterpriseDeviceManager
**系统API**: 此接口为系统接口。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ----- | ----------------------------------- | ---- | ------- |
| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 |
| appIds | Array&lt;string&gt; | 是 | 应用运行的黑名单。 |
| userId | number | 否 | 用户ID。默认值:调用方所在用户,取值范围:大于等于0。 |
**返回值:**
| 类型 | 说明 |
| --------------------- | ------------------------- |
| Promise&lt;void&gt; | 无返回结果的Promise对象。当指定设备管理员应用添加应用运行黑名单失败时会抛出错误对象。 |
**错误码**
以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-enterpriseDeviceManager.md)
| 错误码ID | 错误信息 |
| ------- | ---------------------------------------------------------------------------- |
| 9200001 | the application is not an administrator of the device. |
| 9200002 | the administrator application does not have permission to manage the device. |
**示例:**
```js
let wantTemp = {
bundleName: "com.example.myapplication",
abilityName: "EntryAbility",
};
let appIds = {"com.example.myapplication"};
applicationManager.addDisallowedRunningBundles(wantTemp, appIds, 100).then(() => {
console.log("success");
}).catch(error => {
console.log("error code:" + error.code + " error message:" + error.message);
});
```
## applicationManager.removeDisallowedRunningBundles
removeDisallowedRunningBundles(admin: Want, appIds: Array\<string>, callback: AsyncCallback&lt;void&gt;): void;
指定设备管理员应用移除应用运行黑名单接口,使用callback形式返回移除结果。在黑名单存在的情况下,在应用运行黑名单中的应用不允许在当前用户下运行。
**需要权限:** ohos.permission.ENTERPRISE_MANAGE_SET_APP_RUNNING_POLICY
**系统能力:** SystemCapability.Customization.EnterpriseDeviceManager
**系统API**: 此接口为系统接口。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------- | ---- | ------------------------------- |
| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 |
| appIds | Array&lt;string&gt; | 是 | 应用运行的黑名单。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。当接口调用成功,err为null,否则为错误对象。 |
**错误码**
以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-enterpriseDeviceManager.md)
| 错误码ID | 错误信息 |
| ------- | ---------------------------------------------------------------------------- |
| 9200001 | the application is not an administrator of the device. |
| 9200002 | the administrator application does not have permission to manage the device. |
**示例:**
```js
let wantTemp = {
bundleName: "com.example.myapplication",
abilityName: "EntryAbility",
};
let appIds = {"com.example.myapplication"};
applicationManager.removeDisallowedRunningBundles(wantTemp, appIds, (error) => {
if (error != null) {
console.log("error code:" + error.code + " error message:" + error.message);
}
});
```
## applicationManager.removeDisallowedRunningBundles
removeDisallowedRunningBundles(admin: Want, appIds: Array\<string>, userId: number, callback: AsyncCallback&lt;void&gt;): void;
指定设备管理员应用移除应用运行黑名单接口,使用callback形式返回移除结果。在黑名单存在的情况下,在应用运行黑名单中的应用不允许在指定用户(通过userId指定)下运行。
**需要权限:** ohos.permission.ENTERPRISE_MANAGE_SET_APP_RUNNING_POLICY
**系统能力:** SystemCapability.Customization.EnterpriseDeviceManager
**系统API**: 此接口为系统接口。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ----- | ----------------------------------- | ---- | ------- |
| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 |
| appIds | Array&lt;string&gt; | 是 | 应用运行的黑名单。 |
| userId | number | 是 | 用户ID。默认值:调用方所在用户,取值范围:大于等于0。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。当接口调用成功,err为null,否则为错误对象。 |
**错误码**
以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-enterpriseDeviceManager.md)
| 错误码ID | 错误信息 |
| ------- | ---------------------------------------------------------------------------- |
| 9200001 | the application is not an administrator of the device. |
| 9200002 | the administrator application does not have permission to manage the device. |
**示例:**
```js
let wantTemp = {
bundleName: "com.example.myapplication",
abilityName: "EntryAbility",
};
let appIds = {"com.example.myapplication"};
applicationManager.removeDisallowedRunningBundles(wantTemp, appIds, 100, (error) => {
if (error != null) {
console.log("error code:" + error.code + " error message:" + error.message);
}
});
```
## applicationManager.removeDisallowedRunningBundles
removeDisallowedRunningBundles(admin: Want, appIds: Array\<string>, userId?: number): Promise&lt;void&gt;;
指定设备管理员应用移除应用运行黑名单接口,使用promise形式返回移除结果。在黑名单存在的情况下,如果调用接口时传入参数userId,则在应用运行黑名单中的应用不允许在指定用户下运行,如果调用接口时没有传入参数userId,则在应用运行黑名单中的应用不允许在当前用户下运行。
**需要权限:** ohos.permission.ENTERPRISE_MANAGE_SET_APP_RUNNING_POLICY
**系统能力:** SystemCapability.Customization.EnterpriseDeviceManager
**系统API**: 此接口为系统接口。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ----- | ----------------------------------- | ---- | ------- |
| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 |
| appIds | Array&lt;string&gt; | 是 | 应用运行的黑名单。 |
| userId | number | 否 | 用户ID。默认值:调用方所在用户,取值范围:大于等于0。 |
**返回值:**
| 类型 | 说明 |
| --------------------- | ------------------------- |
| Promise&lt;void&gt; | 无返回结果的Promise对象。当指定设备管理员应用移除应用运行黑名单失败时会抛出错误对象。 |
**错误码**
以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-enterpriseDeviceManager.md)
| 错误码ID | 错误信息 |
| ------- | ---------------------------------------------------------------------------- |
| 9200001 | the application is not an administrator of the device. |
| 9200002 | the administrator application does not have permission to manage the device. |
**示例:**
```js
let wantTemp = {
bundleName: "com.example.myapplication",
abilityName: "EntryAbility",
};
let appIds = {"com.example.myapplication"};
applicationManager.removeDisallowedRunningBundles(wantTemp, appIds, 100).then(() => {
console.log("success");
}).catch(error => {
console.log("error code:" + error.code + " error message:" + error.message);
});
```
## applicationManager.getDisallowedRunningBundles
getDisallowedRunningBundles(admin: Want, callback: AsyncCallback&lt;Array&lt;string&gt;&gt;): void;
指定管理员应用获取管理员用户下的应用运行黑名单接口,使用callback形式返回获取应用运行黑名单。
**需要权限:** ohos.permission.ENTERPRISE_MANAGE_SET_APP_RUNNING_POLICY
**系统能力:** SystemCapability.Customization.EnterpriseDeviceManager
**系统API**: 此接口为系统接口。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------- | ---- | ------------------------------- |
| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 |
| callback | AsyncCallback&lt;Array&lt;string&gt;&gt; | 是 | 回调函数,当接口调用成功,err为null,否则为错误对象。 |
**错误码**
以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-enterpriseDeviceManager.md)
| 错误码ID | 错误信息 |
| ------- | ---------------------------------------------------------------------------- |
| 9200001 | the application is not an administrator of the device. |
| 9200002 | the administrator application does not have permission to manage the device. |
**示例:**
```js
let wantTemp = {
bundleName: "com.example.myapplication",
abilityName: "EntryAbility",
};
applicationManager.getDisallowedRunningBundles(wantTemp, (error) => {
if (error != null) {
console.log("error code:" + error.code + " error message:" + error.message);
}
});
```
## applicationManager.getDisallowedRunningBundles
getDisallowedRunningBundles(admin: Want, userId: number, callback: AsyncCallback&lt;Array&lt;string&gt;&gt;): void;
指定管理员应用获取指定用户(通过userId指定)下的应用运行黑名单接口,使用callback形式返回获取应用运行黑名单。
**需要权限:** ohos.permission.ENTERPRISE_MANAGE_SET_APP_RUNNING_POLICY
**系统能力:** SystemCapability.Customization.EnterpriseDeviceManager
**系统API**: 此接口为系统接口。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------- | ---- | ------------------------------- |
| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 |
| userId | number | 是 | 用户ID。默认值:调用方所在用户,取值范围:大于等于0。 |
| callback | AsyncCallback&lt;Array&lt;string&gt;&gt; | 是 | 回调函数,当接口调用成功,err为null,否则为错误对象。 |
**错误码**
以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-enterpriseDeviceManager.md)
| 错误码ID | 错误信息 |
| ------- | ---------------------------------------------------------------------------- |
| 9200001 | the application is not an administrator of the device. |
| 9200002 | the administrator application does not have permission to manage the device. |
**示例:**
```js
let wantTemp = {
bundleName: "com.example.myapplication",
abilityName: "EntryAbility",
};
applicationManager.getDisallowedRunningBundles(wantTemp, 100, (error) => {
if (error != null) {
console.log("error code:" + error.code + " error message:" + error.message);
}
});
```
## applicationManager.getDisallowedRunningBundles
getDisallowedRunningBundles(admin: Want, userId?: number): Promise&lt;Array&lt;string&gt;&gt;;
如果调用接口时传入参数userId,指定管理员应用获取指定用户下应用运行黑名单接口,如果调用接口时没有传入参数userId,指定管理员应用获取当前用户下应用运行黑名单接口,使用promise形式返回获取应用运行黑名单。
**需要权限:** ohos.permission.ENTERPRISE_MANAGE_SET_APP_RUNNING_POLICY
**系统能力:** SystemCapability.Customization.EnterpriseDeviceManager
**系统API**: 此接口为系统接口。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ----- | ----------------------------------- | ---- | ------- |
| admin | [Want](js-apis-app-ability-want.md) | 是 | 设备管理员应用。 |
| userId | number | 否 | 用户ID。默认值:调用方所在用户,取值范围:大于等于0。 |
**返回值:**
| 类型 | 说明 |
| --------------------- | ------------------------- |
| Promise&lt;Array&lt;string&gt;&gt; | Promise对象,返回管理员用户下的应用运行黑名单。 |
**错误码**
以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-enterpriseDeviceManager.md)
| 错误码ID | 错误信息 |
| ------- | ---------------------------------------------------------------------------- |
| 9200001 | the application is not an administrator of the device. |
| 9200002 | the administrator application does not have permission to manage the device. |
**示例:**
```js
let wantTemp = {
bundleName: "com.example.myapplication",
abilityName: "EntryAbility",
};
applicationManager.getDisallowedRunningBundles(wantTemp, 100).then(() => {
console.log("success");
}).catch(error => {
console.log("error code:" + error.code + " error message:" + error.message);
});
```
# InputMethodCommon
> **说明:**
> 本模块首批接口从API version 10 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
输入法框架接口定义的公共属性信息。
## Direction
光标移动方向类型枚举。
**系统能力:** SystemCapability.MiscServices.InputMethodFramework
| 名称 | 值 | 说明 |
| ------------ | ---- | ---------- |
| CURSOR_UP | 1 | 光标上移。 |
| CURSOR_DOWN | 2 | 光标下移。 |
| CURSOR_LEFT | 3 | 光标左移。 |
| CURSOR_RIGHT | 4 | 光标右移。 |
## Range
描述选中文本的范围。
**系统能力:** SystemCapability.MiscServices.InputMethodFramework
| 名称 | 类型 | 可读 | 可写 | 说明 |
| ----- | ------ | ---- | ---- | ---------------------------------- |
| start | number | 是 | 是 | 选中文本的首字符在编辑框的索引值。 |
| end | number | 是 | 是 | 选中文本的末字符在编辑框的索引值。 |
## Movement
描述进行选中文本动作时光标移动的方向。
**系统能力:** SystemCapability.MiscServices.InputMethodFramework
| 名称 | 类型 | 可读 | 可写 | 说明 |
| --------- | ----------------------- | ---- | ---- | ---------------------------------- |
| direction | [Direction](#direction) | 是 | 是 | 进行选中文本动作时光标移动的方向。 |
......@@ -38,9 +38,9 @@ Extension生命周期回调,在拉起Extension输入法应用时调用,执
```js
class InputMethodExt extends InputMethodExtensionAbility {
onCreate(want) {
console.log('onCreate, want:' + want.abilityName);
}
onCreate(want) {
console.log('onCreate, want:' + want.abilityName);
}
}
```
......@@ -56,8 +56,8 @@ Extension生命周期回调,在销毁输入法应用时回调,执行资源
```js
class InputMethodExt extends InputMethodExtensionAbility {
onDestroy() {
console.log('onDestroy');
}
onDestroy() {
console.log('onDestroy');
}
}
```
......@@ -21,9 +21,9 @@ import InputMethodExtensionContext from '@ohos.InputMethodExtensionContext';
```js
import InputMethodExtensionAbility from '@ohos.InputMethodExtensionAbility';
class EntryAbility extends InputMethodExtensionAbility {
onCreate() {
let context = this.context;
}
onCreate() {
let context = this.context;
}
}
```
......@@ -44,8 +44,8 @@ destroy(callback: AsyncCallback\<void>): void
**示例:**
```js
this.context.destroy((err) => {
console.log('destroy result:' + JSON.stringify(err));
this.context.destroy(() => {
console.log('Succeeded in destroying context.');
});
```
......@@ -67,8 +67,6 @@ destroy(): Promise\<void>;
```js
this.context.destroy().then(() => {
console.log('Succeed in destoring context.');
}).catch((error) => {
console.log('Failed to destory context: ' + JSON.stringify(error));
console.log('Succeed in destroying context.');
});
```
......@@ -123,7 +123,7 @@ install(hapFilePaths: Array&lt;string&gt;, installParam: InstallParam, callback:
| 17700041 | Failed to install because enterprise device management disallow install. |
| 17700042 | Failed to install the HAP because of incorrect URI in the data proxy. |
| 17700043 | Failed to install the HAP because of low APL in the non-system data proxy (required APL: system_basic or system_core). |
| 17700044 | Failed to install because the isolationMode does not match the system. |
| 17700044 | Failed to install the HAP because the isolationMode configured is not supported. |
**示例:**
......@@ -189,7 +189,7 @@ install(hapFilePaths: Array&lt;string&gt;, callback: AsyncCallback&lt;void&gt;):
| 17700041 | Failed to install because enterprise device management disallow install. |
| 17700042 | Failed to install the HAP because of incorrect URI in the data proxy. |
| 17700043 | Failed to install the HAP because of low APL in the non-system data proxy (required APL: system_basic or system_core). |
| 17700044 | Failed to install because the isolationMode does not match the system. |
| 17700044 | Failed to install the HAP because the isolationMode configured is not supported. |
**示例:**
......@@ -259,7 +259,7 @@ install(hapFilePaths: Array\<string\>, installParam?: InstallParam) : Promise\<v
| 17700041 | Failed to install because enterprise device management disallow install. |
| 17700042 | Failed to install the HAP because of incorrect URI in the data proxy. |
| 17700043 | Failed to install the HAP because of low APL in the non-system data proxy (required APL: system_basic or system_core). |
| 17700044 | Failed to install because the isolationMode does not match the system. |
| 17700044 | Failed to install the HAP because the isolationMode configured is not supported. |
**示例:**
......
......@@ -1613,7 +1613,7 @@ resume(callback: AsyncCallback&lt;void&gt;): void
| enableMetered | boolean | 否 | 设置是否允许在按流量计费的连接下下载(默认使用false)。<br/>-&nbsp;true:是<br/>-&nbsp;false:否 |
| enableRoaming | boolean | 否 | 设置是否允许在漫游网络中下载(默认使用false)。 <br/>-&nbsp;true:是<br/>-&nbsp;false:否|
| description | string | 否 | 设置下载会话的描述。 |
| filePath<sup>7+</sup> | string | 否 | 设置下载路径。<br/>-&nbsp;filePath:'/data/storage/el2/base/haps/entry/files/test.txt':将文件存储在绝对路径下。<br/>-&nbsp;FA模型下使用[context](js-apis-inner-app-context.md#contextgetcachedir) 获取应用存储路径,比如:\`${featureAbility.getContext().getFilesDir()}/test.txt\`,并将文件存储在此路径下。<br/>-&nbsp;Stage模型下使用[AbilityContext](js-apis-inner-application-context.md) 类获取文件路径,比如:\`${globalThis.abilityContext.tempDir}/test.txt\`,并将文件存储在此路径下。|
| filePath<sup>7+</sup> | string | 否 | 设置下载路径。<br/>-&nbsp;FA模型下使用[context](js-apis-inner-app-context.md#contextgetcachedir) 获取应用存储路径,比如:\`${featureAbility.getContext().getFilesDir()}/test.txt\`,并将文件存储在此路径下。<br/>-&nbsp;Stage模型下使用[AbilityContext](js-apis-inner-application-context.md) 类获取文件路径,比如:\`${globalThis.abilityContext.tempDir}/test.txt\`,并将文件存储在此路径下。|
| networkType | number | 否 | 设置允许下载的网络类型(默认使用NETWORK_MOBILE&NETWORK_WIFI)。<br/>-&nbsp;NETWORK_MOBILE:0x00000001<br/>-&nbsp;NETWORK_WIFI:0x00010000|
| title | string | 否 | 设置下载任务名称。 |
| background<sup>9+</sup> | boolean | 否 | 后台任务通知开关,开启后可在通知中显示下载状态(默认使用false)。 |
......
......@@ -1570,9 +1570,9 @@ FA卡片的使用信息的属性集合。
| 名称 | 类型 | 必填 | 说明 |
| --------------------- | ------ | ---- | ---------------------------------------- |
| bundleName | string | | 应用包名。 |
| eventId | number | | 应用事件类型。 |
| eventOccurredTime | number | | 应用事件发生的时间戳。 |
| bundleName | string | | 应用包名。 |
| eventId | number | | 应用事件类型。 |
| eventOccurredTime | number | | 应用事件发生的时间戳。 |
| appGroup | number | 否 | 应用程序的使用优先级组。|
| indexOfLink | string | 否 | 快捷方式id。|
| nameOfClass | string | 否 | 类名。|
......
......@@ -659,7 +659,7 @@ import router from '@ohos.router'
struct Second {
private content: string = "这是第二页"
@State text: string = router.getParams()['text']
@State data: any = router.getParams()['data']
@State data: object = router.getParams()['data']
@State secondData : string = ''
build() {
......@@ -670,7 +670,7 @@ struct Second {
Text(this.text)
.fontSize(30)
.onClick(()=>{
this.secondData = (this.data.array[1]).toString()
this.secondData = (this.data.['array'][1]).toString()
})
.margin({top:20})
Text(`第一页传来的数值:${this.secondData}`)
......
......@@ -4250,7 +4250,7 @@ static saveCookieAsync(callback: AsyncCallback\<void>): void
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------- | ---- | :------------------------------------------------- |
| callback | AsyncCallback\<void> | 是 | 返回cookie是否成功保存的布尔值作为回调函数的入参。 |
| callback | AsyncCallback\<void> | 是 | callback回调,用于获取cookie是否成功保存。 |
**示例:**
......
......@@ -2701,7 +2701,7 @@ try {
### off('avoidAreaChange')<sup>9+</sup>
off(type: 'avoidAreaChange', callback: Callback&lt;{AvoidAreaType, AvoidArea}&gt;): void
off(type: 'avoidAreaChange', callback?: Callback&lt;{AvoidAreaType, AvoidArea}&gt;): void
关闭系统规避区变化的监听。
......@@ -3471,7 +3471,7 @@ let colorSpace = windowClass.getWindowColorSpace();
setWindowBackgroundColor(color: string): void
设置窗口的背景色。Stage模型下,该接口需要在[loadContent](#loadcontent9)后使用。
设置窗口的背景色。Stage模型下,该接口需要在[loadContent()](#loadcontent9)[setUIContent()](#setuicontent9)调用生效后使用。
**系统能力:** SystemCapability.WindowManager.WindowManager.Core
......@@ -6024,7 +6024,7 @@ promise.then((data)=> {
setBackgroundColor(color: string, callback: AsyncCallback&lt;void&gt;): void
设置窗口的背景色,使用callback异步回调。Stage模型下,该接口需要在[loadContent](#loadcontent9)[setUIContent()](#setuicontent9)后使用。
设置窗口的背景色,使用callback异步回调。Stage模型下,该接口需要在[loadContent()](#loadcontent9)[setUIContent()](#setuicontent9)调用生效后使用。
> **说明:**
>
......@@ -6056,7 +6056,7 @@ windowClass.setBackgroundColor(color, (err) => {
setBackgroundColor(color: string): Promise&lt;void&gt;
设置窗口的背景色,使用Promise异步回调。Stage模型下,该接口需要在[loadContent](#loadcontent9)[setUIContent()](#setuicontent9)后使用。
设置窗口的背景色,使用Promise异步回调。Stage模型下,该接口需要在[loadContent()](#loadcontent9)[setUIContent()](#setuicontent9)调用生效后使用。
> **说明:**
>
......
......@@ -41,7 +41,7 @@ Checkbox(options?:&nbsp;{name?: string, group?: string })
| 名称 | 功能描述 |
| -------------------------------------------- | ------------------------------------------------------------ |
| onChange(callback: (value: boolean) => void) | 当选中状态发生变化时,触发该回调。(只有手动触发且Checkbox状态改变时才会触发onChange回调)<br>- value为true时,表示已选中。<br>- value为false时,表示未选中。<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 |
| onChange(callback: (value: boolean) => void) | 当选中状态发生变化时,触发该回调。<br>- value为true时,表示已选中。<br>- value为false时,表示未选中。<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 |
## MarkStyle<sup>10+</sup>对象说明
......
......@@ -41,7 +41,7 @@ CheckboxGroup(options?: { group?: string })
| 名称 | 功能描述 |
| -------- | -------- |
| onChange (callback: (event: [CheckboxGroupResult](#checkboxgroupresult对象说明)) => void ) |CheckboxGroup的选中状态或群组内的Checkbox的选中状态发生变化时,触发回调。(只有手动触发且Checkbox或CheckboxGroup状态改变时才会触发onChange回调)<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。|
| onChange (callback: (event: [CheckboxGroupResult](#checkboxgroupresult对象说明)) => void ) |CheckboxGroup的选中状态或群组内的Checkbox的选中状态发生变化时,触发回调。<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。|
## CheckboxGroupResult对象说明
......
......@@ -16,12 +16,12 @@ Search(options?: { value?: string; placeholder?: ResourceStr; icon?: string; con
**参数:**
| 参数名 | 参数类型 | 必填 | 参数描述 |
| ----------- | ---------------- | ---- | ------------------------------------------------------------ |
| value | string | 否 | 设置当前显示的搜索文本内容。 |
| 参数名 | 参数类型 | 必填 | 参数描述 |
| ----------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ |
| value | string | 否 | 设置当前显示的搜索文本内容。 |
| placeholder | [ResourceStr](ts-types.md#resourcestr)<sup>10+</sup> | 否 | 设置无输入时的提示文本。 |
| icon | string | 否 | 设置搜索图标路径,默认使用系统搜索图标,图标支持的图源格式: svg、jpg和png。 |
| controller | SearchController | 否 | 设置Search组件控制器。 |
| icon | string | 否 | 设置搜索图标路径,默认使用系统搜索图标。<br/>图标所支持的图片类型能力参考[Image](ts-basic-components-image.md)组件。 |
| controller | SearchController | 否 | 设置Search组件控制器。 |
## 属性
......
......@@ -5,6 +5,8 @@
> **说明:**
>
> 该组件从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
>
> 该组件从API Version 10开始支持继承父组件Text的属性,即如果子组件未设置属性且父组件设置属性,则继承父组件设置的属性。支持继承的属性包括:fontColor、fontSize、fontStyle、fontWeight、decoration、letterSpacing、textCase、lineHeight、fontfamily。
## 子组件
......
......@@ -718,8 +718,6 @@ textZoomAtio(textZoomAtio: number)
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
......@@ -1420,8 +1418,10 @@ onAlert(callback: (event?: { url: string; message: string; result: JsResult }) =
controller: web_webview.WebviewController = new web_webview.WebviewController()
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
Web({ src: $rawfile("xxx.html"), controller: this.controller })
.onAlert((event) => {
console.log("event.url:" + event.url)
console.log("event.message:" + event.message)
AlertDialog.show({
title: 'onAlert',
message: 'text',
......@@ -1448,6 +1448,25 @@ onAlert(callback: (event?: { url: string; message: string; result: JsResult }) =
}
```
```
<!--xxx.html-->
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" charset="utf-8">
</head>
<body>
<h1>WebView onAlert Demo</h1>
<button onclick="myFunction()">Click here</button>
<script>
function myFunction() {
alert("Hello World");
}
</script>
</body>
</html>
```
### onBeforeUnload
onBeforeUnload(callback: (event?: { url: string; message: string; result: JsResult }) => boolean)
......@@ -1481,7 +1500,7 @@ onBeforeUnload(callback: (event?: { url: string; message: string; result: JsResu
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
Web({ src: $rawfile("xxx.html"), controller: this.controller })
.onBeforeUnload((event) => {
console.log("event.url:" + event.url)
console.log("event.message:" + event.message)
......@@ -1511,6 +1530,25 @@ onBeforeUnload(callback: (event?: { url: string; message: string; result: JsResu
}
```
```
<!--xxx.html-->
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" charset="utf-8">
</head>
<body onbeforeunload="return myFunction()">
<h1>WebView onBeforeUnload Demo</h1>
<a href="https://www.example.com">Click here</a>
<script>
function myFunction() {
return "onBeforeUnload Event";
}
</script>
</body>
</html>
```
### onConfirm
onConfirm(callback: (event?: { url: string; message: string; result: JsResult }) => boolean)
......@@ -1544,11 +1582,10 @@ onConfirm(callback: (event?: { url: string; message: string; result: JsResult })
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
Web({ src: $rawfile("xxx.html"), controller: this.controller })
.onConfirm((event) => {
console.log("event.url:" + event.url)
console.log("event.message:" + event.message)
console.log("event.result:" + event.result)
AlertDialog.show({
title: 'onConfirm',
message: 'text',
......@@ -1575,6 +1612,34 @@ onConfirm(callback: (event?: { url: string; message: string; result: JsResult })
}
```
```
<!--xxx.html-->
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" charset="utf-8">
</head>
<body>
<h1>WebView onConfirm Demo</h1>
<button onclick="myFunction()">Click here</button>
<p id="demo"></p>
<script>
function myFunction() {
let x;
let r = confirm("click button!");
if (r == true) {
x = "ok";
} else {
x = "cancel";
}
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>
```
### onPrompt<sup>9+</sup>
onPrompt(callback: (event?: { url: string; message: string; value: string; result: JsResult }) => boolean)
......@@ -1606,7 +1671,7 @@ onPrompt(callback: (event?: { url: string; message: string; value: string; resul
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
Web({ src: $rawfile("xxx.html"), controller: this.controller })
.onPrompt((event) => {
console.log("url:" + event.url)
console.log("message:" + event.message)
......@@ -1623,7 +1688,7 @@ onPrompt(callback: (event?: { url: string; message: string; value: string; resul
secondaryButton: {
value: 'ok',
action: () => {
event.result.handleConfirm()
event.result.handlePromptConfirm(event.value)
}
},
cancel: () => {
......@@ -1637,6 +1702,30 @@ onPrompt(callback: (event?: { url: string; message: string; value: string; resul
}
```
```
<!--xxx.html-->
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" charset="utf-8">
</head>
<body>
<h1>WebView onPrompt Demo</h1>
<button onclick="myFunction()">Click here</button>
<p id="demo"></p>
<script>
function myFunction() {
let message = prompt("Message info", "Hello World");
if (message != null && message != "") {
document.getElementById("demo").innerHTML = message;
}
}
</script>
</body>
</html>
```
### onConsole
onConsole(callback: (event?: { message: ConsoleMessage }) => boolean)
......@@ -1690,6 +1779,7 @@ onDownloadStart(callback: (event?: { url: string, userAgent: string, contentDisp
| 参数名 | 参数类型 | 参数描述 |
| ------------------ | ------------- | ----------------------------------- |
| url | string | 文件下载的URL。 |
| userAgent | string | 用于下载的用户代理。 |
| contentDisposition | string | 服务器返回的 Content-Disposition响应头,可能为空。 |
| mimetype | string | 服务器返回内容媒体类型(MIME)信息。 |
| contentLength | contentLength | 服务器返回文件的长度。 |
......
......@@ -40,9 +40,9 @@ RenderingContextSettings(antialias?: boolean)
| 名称 | 类型 | 描述 |
| ----------------------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| [fillStyle](#fillstyle) | string&nbsp;\|&nbsp;[CanvasGradient](ts-components-canvas-canvasgradient.md)&nbsp;\|&nbsp;[CanvasPattern](#canvaspattern) | 指定绘制的填充色。<br/>-&nbsp;类型为string时,表示设置填充区域的颜色。<br/>-&nbsp;类型为CanvasGradient时,表示渐变对象,使用[createLinearGradient](#createlineargradient)方法创建。<br/>-&nbsp;类型为CanvasPattern时,使用[createPattern](#createpattern)方法创建。<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 |
| [fillStyle](#fillstyle) | string&nbsp;\|number<sup>10+</sup>&nbsp;\|[CanvasGradient](ts-components-canvas-canvasgradient.md)&nbsp;\|&nbsp;[CanvasPattern](#canvaspattern) | 指定绘制的填充色。<br/>-&nbsp;类型为string时,表示设置填充区域的颜色。<br/>- 类型为number时,表示设置填充区域的颜色。<br/>-&nbsp;类型为CanvasGradient时,表示渐变对象,使用[createLinearGradient](#createlineargradient)方法创建。<br/>-&nbsp;类型为CanvasPattern时,使用[createPattern](#createpattern)方法创建。<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 |
| [lineWidth](#linewidth) | number | 设置绘制线条的宽度。 |
| [strokeStyle](#strokestyle) | string&nbsp;\|&nbsp;[CanvasGradient](ts-components-canvas-canvasgradient.md)&nbsp;\|&nbsp;[CanvasPattern](#canvaspattern) | 设置描边的颜色。<br/>-&nbsp;类型为string时,表示设置描边使用的颜色。<br/>-&nbsp;类型为CanvasGradient时,表示渐变对象,使用[createLinearGradient](#createlineargradient)方法创建。<br/>-&nbsp;类型为CanvasPattern时,使用[createPattern](#createpattern)方法创建。<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 |
| [strokeStyle](#strokestyle) | string&nbsp;\|number<sup>10+</sup>&nbsp;\|[CanvasGradient](ts-components-canvas-canvasgradient.md)&nbsp;\|&nbsp;[CanvasPattern](#canvaspattern) | 设置描边的颜色。<br/>-&nbsp;类型为string时,表示设置描边使用的颜色。<br/>- 类型为number时,表示设置描边使用的颜色。<br/>-&nbsp;类型为CanvasGradient时,表示渐变对象,使用[createLinearGradient](#createlineargradient)方法创建。<br/>-&nbsp;类型为CanvasPattern时,使用[createPattern](#createpattern)方法创建。<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 |
| [lineCap](#linecap) | CanvasLineCap | 指定线端点的样式,可选值为:<br/>-&nbsp;'butt':线端点以方形结束。<br/>-&nbsp;'round':线端点以圆形结束。<br/>-&nbsp;'square':线端点以方形结束,该样式下会增加一个长度和线段厚度相同,宽度是线段厚度一半的矩形。<br/>默认值:'butt'<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 |
| [lineJoin](#linejoin) | CanvasLineJoin | 指定线段间相交的交点样式,可选值为:<br/>-&nbsp;'round':在线段相连处绘制一个扇形,扇形的圆角半径是线段的宽度。<br/>-&nbsp;'bevel':在线段相连处使用三角形为底填充,&nbsp;每个部分矩形拐角独立。<br/>-&nbsp;'miter':在相连部分的外边缘处进行延伸,使其相交于一点,形成一个菱形区域,该属性可以通过设置miterLimit属性展现效果。<br/>默认值:'miter'<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 |
| [miterLimit](#miterlimit) | number | 设置斜接面限制值,该值指定了线条相交处内角和外角的距离。 <br/>默认值:10<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 |
......@@ -2715,4 +2715,4 @@ struct CanvasExample {
一个Object对象, 通过[createPattern](#createpattern)方法创建。
从API version 9开始,该接口支持在ArkTS卡片中使用。
\ No newline at end of file
从API version 9开始,该接口支持在ArkTS卡片中使用。
......@@ -48,8 +48,8 @@ Swiper(controller?: SwiperController)
| indicatorStyle<sup>8+</sup> | {<br/>left?:&nbsp;[Length](ts-types.md#length),<br/>top?:&nbsp;[Length](ts-types.md#length),<br/>right?:&nbsp;[Length](ts-types.md#length),<br/>bottom?:&nbsp;[Length](ts-types.md#length),<br/>size?:&nbsp;[Length](ts-types.md#length),<br/>mask?:&nbsp;boolean,<br/>color?:&nbsp;[ResourceColor](ts-types.md),<br/>selectedColor?:&nbsp;[ResourceColor](ts-types.md)<br/>} | 设置导航点样式:<br/>\- left: 设置导航点距离Swiper组件左边的距离。<br/>\- top: 设置导航点距离Swiper组件顶部的距离。<br/>\- right: 设置导航点距离Swiper组件右边的距离。<br/>\- bottom: 设置导航点距离Swiper组件底部的距离。<br/>\- size: 设置导航点的直径。<br/>\- mask: 设置是否显示导航点蒙层样式。<br/>\- color: 设置导航点的颜色。<br/>\- selectedColor: 设置选中的导航点的颜色。 |
| displayCount<sup>8+</sup> | number\|string | 设置一页内元素显示个数。<br/>默认值:1<br/>**说明:** <br/>字符串类型仅支持设置为'auto',显示效果同SwiperDisplayMode.AutoLinear。<br/>使用number类型时,子组件按照主轴均分Swiper宽度(减去displayCount-1的itemSpace)的方式进行主轴拉伸(收缩)布局。 |
| effectMode<sup>8+</sup> | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | 滑动效果,目前支持的滑动效果参见EdgeEffect的枚举说明。<br/>默认值:EdgeEffect.Spring<br/>**说明:** <br/>控制器接口调用时不生效回弹。 |
| nextMargin<sup>10+</sup> | <br/>[Length](ts-types.md#length)<br/> | 后边距,用于露出后一项的一小部分。<br/>默认值:0<br/>**说明:** <br/>>仅当SwiperDisplayMode为STRETCH模式时生效。当cachedCount设置值小于等于0时,此时会露出后一项的一小部分,但无法加载子组件。当displayCount设置为1时,此参数设置无效。 |
| prevMargin<sup>10+</sup> | <br/>[Length](ts-types.md#length)<br/> | 前边距,用于露出前一项的一小部分。<br/>默认值:0<br/>**说明:** <br/>仅当SwiperDisplayMode为STRETCH模式时生效。当cachedCount设置值小于等于0时,此时会露出前一项的一小部分,但无法加载子组件。当displayCount设置为1时,此参数设置无效。 |
| nextMargin<sup>10+</sup> | <br/>[Length](ts-types.md#length)<br/> | 后边距,用于露出后一项的一小部分。<br/>默认值:0<br/>**说明:** <br/>仅当SwiperDisplayMode为STRETCH模式时生效。当cachedCount设置值小于等于0时,此时会露出后一项的一小部分,但无法加载子组件。 |
| prevMargin<sup>10+</sup> | <br/>[Length](ts-types.md#length)<br/> | 前边距,用于露出前一项的一小部分。<br/>默认值:0<br/>**说明:** <br/>仅当SwiperDisplayMode为STRETCH模式时生效。当cachedCount设置值小于等于0时,此时会露出前一项的一小部分,但无法加载子组件。 |
## SwiperDisplayMode枚举说明
......
......@@ -22,12 +22,12 @@ Video(value: {src?: string | Resource, currentProgressRate?: number | string | P
**参数:**
| 参数名 | 参数类型 | 必填 | 参数描述 |
| ------------------- | ---------------------------------------- | ---- | ---------------------------------------- |
| src | string \| [Resource](ts-types.md) | 否 | 视频播放源的路径,支持本地视频路径和网络路径。<br>支持在resources下面的video或rawfile文件夹里放置媒体资源。<br>支持dataability://的路径前缀,用于访问通过Data Ability提供的视频路径,具体路径信息详见 [DataAbility说明](../../application-models/dataability-overview.md)<br/>**说明:**<br/>视频支持的格式是:mp4、mkv、webm、TS。 |
| currentProgressRate | number&nbsp;\|&nbsp;string&nbsp;\|&nbsp;PlaybackSpeed<sup>8+</sup> | 否 | 视频播放倍速。<br/>**说明:**<br/>number取值仅支持:0.75,1.0,1.25,1.75,2.0。<br/>默认值:1.0 \| PlaybackSpeed.Speed_Forward_1_00_X |
| previewUri | string&nbsp;\|&nbsp;PixelMap<sup>8+</sup>&nbsp;\|&nbsp;[Resource](ts-types.md) | 否 | 视频未播放时的预览图片路径。 |
| controller | [VideoController](#videocontroller) | 否 | 设置视频控制器。 |
| 参数名 | 参数类型 | 必填 | 参数描述 |
| ------------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| src | string \| [Resource](ts-types.md) | 否 | 视频播放源的路径,支持本地视频路径和网络路径。<br>支持在resources下面的video或rawfile文件夹里放置媒体资源。<br>支持dataability://的路径前缀,用于访问通过Data Ability提供的视频路径,具体路径信息详见 [DataAbility说明](../../application-models/dataability-overview.md)<br/>**说明:**<br/>视频支持的格式是:mp4、mkv、webm、TS。 |
| currentProgressRate | number&nbsp;\|&nbsp;string&nbsp;\|&nbsp;PlaybackSpeed<sup>8+</sup> | 否 | 视频播放倍速。<br/>**说明:**<br/>number取值仅支持:0.75,1.0,1.25,1.75,2.0。<br/>默认值:1.0 \| PlaybackSpeed.Speed_Forward_1_00_X |
| previewUri | string&nbsp;\|PixelMap&nbsp;\|&nbsp;[Resource](ts-types.md) | 否 | 视频未播放时的预览图片路径。(暂不支持PixelMap类型) |
| controller | [VideoController](#videocontroller) | 否 | 设置视频控制器。 |
## PlaybackSpeed<sup>8+</sup>枚举说明
......@@ -55,16 +55,16 @@ Video(value: {src?: string | Resource, currentProgressRate?: number | string | P
除支持[通用事件](ts-universal-events-click.md)外,还支持以下事件:
| 名称 | 功能描述 |
| ---------------------------------------- | ---------------------------------------- |
| onStart(event:()&nbsp;=&gt;&nbsp;void) | 播放时触发该事件。 |
| onPause(event:()&nbsp;=&gt;&nbsp;void) | 暂停时触发该事件。 |
| onFinish(event:()&nbsp;=&gt;&nbsp;void) | 播放结束时触发该事件。 |
| onError(event:()&nbsp;=&gt;&nbsp;void) | 播放失败时触发该事件。 |
| 名称 | 功能描述 |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| onStart(event:()&nbsp;=&gt;&nbsp;void) | 播放时触发该事件。 |
| onPause(event:()&nbsp;=&gt;&nbsp;void) | 暂停时触发该事件。 |
| onFinish(event:()&nbsp;=&gt;&nbsp;void) | 播放结束时触发该事件。 |
| onError(event:()&nbsp;=&gt;&nbsp;void) | 播放失败时触发该事件。 |
| onPrepared(callback:(event?:&nbsp;{&nbsp;duration:&nbsp;number&nbsp;})&nbsp;=&gt;&nbsp;void) | 视频准备完成时触发该事件,通过duration可以获取视频时长,单位为秒(s)。 |
| onSeeking(callback:(event?:&nbsp;{&nbsp;time:&nbsp;number&nbsp;})&nbsp;=&gt;&nbsp;void) | 操作进度条过程时上报时间信息,单位为s。 |
| onSeeked(callback:(event?:&nbsp;{&nbsp;time:&nbsp;number&nbsp;})&nbsp;=&gt;&nbsp;void) | 操作进度条完成后,上报播放时间信息,单位为s。 |
| onUpdate(callback:(event?:&nbsp;{&nbsp;time:&nbsp;number&nbsp;})&nbsp;=&gt;&nbsp;void) | 播放进度变化时触发该事件,单位为s,更新时间间隔为250ms。 |
| onSeeking(callback:(event?:&nbsp;{&nbsp;time:&nbsp;number&nbsp;})&nbsp;=&gt;&nbsp;void) | 操作进度条过程时上报时间信息,单位为s。 |
| onSeeked(callback:(event?:&nbsp;{&nbsp;time:&nbsp;number&nbsp;})&nbsp;=&gt;&nbsp;void) | 操作进度条完成后,上报播放时间信息,单位为s。 |
| onUpdate(callback:(event?:&nbsp;{&nbsp;time:&nbsp;number&nbsp;})&nbsp;=&gt;&nbsp;void) | 播放进度变化时触发该事件,单位为s |
| onFullscreenChange(callback:(event?:&nbsp;{&nbsp;fullscreen:&nbsp;boolean&nbsp;})&nbsp;=&gt;&nbsp;void) | 在全屏播放与非全屏播放状态之间切换时触发该事件,返回值为true表示进入全屏播放状态,为false则表示非全屏播放。 |
......
......@@ -27,9 +27,9 @@ OffscreenCanvasRenderingContext2D(width: number, height: number, setting: Render
| 名称 | 类型 | 描述 |
| ----------------------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| [fillStyle](#fillstyle) | string&nbsp;\|&nbsp;[CanvasGradient](ts-components-canvas-canvasgradient.md)&nbsp;\|&nbsp;[CanvasPattern](#canvaspattern) | 指定绘制的填充色。<br/>-&nbsp;类型为string时,表示设置填充区域的颜色。<br/>-&nbsp;类型为CanvasGradient时,表示渐变对象,使用[createLinearGradient](#createlineargradient)方法创建。<br/>-&nbsp;类型为CanvasPattern时,使用[createPattern](#createpattern)方法创建。<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 |
| [fillStyle](#fillstyle) | string&nbsp;\|number<sup>10+</sup>&nbsp;\|[CanvasGradient](ts-components-canvas-canvasgradient.md)&nbsp;\|&nbsp;[CanvasPattern](#canvaspattern) | 指定绘制的填充色。<br/>-&nbsp;类型为string时,表示设置填充区域的颜色。<br/>- 类型为number时,表示设置填充区域的颜色。<br/>-&nbsp;类型为CanvasGradient时,表示渐变对象,使用[createLinearGradient](#createlineargradient)方法创建。<br/>-&nbsp;类型为CanvasPattern时,使用[createPattern](#createpattern)方法创建。<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 |
| [lineWidth](#linewidth) | number | 设置绘制线条的宽度。<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 |
| [strokeStyle](#strokestyle) | string&nbsp;\|&nbsp;[CanvasGradient](ts-components-canvas-canvasgradient.md)&nbsp;\|&nbsp;[CanvasPattern](#canvaspattern) | 设置描边的颜色。<br/>-&nbsp;类型为string时,表示设置描边使用的颜色。<br/>-&nbsp;类型为CanvasGradient时,表示渐变对象,使用[createLinearGradient](#createlineargradient)方法创建。<br/>-&nbsp;类型为CanvasPattern时,使用[createPattern](#createpattern)方法创建。<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 |
| [strokeStyle](#strokestyle) | string&nbsp;\|number<sup>10+</sup>&nbsp;\|[CanvasGradient](ts-components-canvas-canvasgradient.md)&nbsp;\|&nbsp;[CanvasPattern](#canvaspattern) | 设置描边的颜色。<br/>-&nbsp;类型为string时,表示设置描边使用的颜色。<br/>- 类型为number时,表示设置描边使用的颜色。<br/>-&nbsp;类型为CanvasGradient时,表示渐变对象,使用[createLinearGradient](#createlineargradient)方法创建。<br/>-&nbsp;类型为CanvasPattern时,使用[createPattern](#createpattern)方法创建。<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 |
| [lineCap](#linecap) | CanvasLineCap | 指定线端点的样式,可选值为:<br/>-&nbsp;'butt':线端点以方形结束。<br/>-&nbsp;'round':线端点以圆形结束。<br/>-&nbsp;'square':线端点以方形结束,该样式下会增加一个长度和线段厚度相同,宽度是线段厚度一半的矩形。<br/>-&nbsp;默认值:'butt'。<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 |
| [lineJoin](#linejoin) | CanvasLineJoin | 指定线段间相交的交点样式,可选值为:<br/>-&nbsp;'round':在线段相连处绘制一个扇形,扇形的圆角半径是线段的宽度。<br/>-&nbsp;'bevel':在线段相连处使用三角形为底填充,&nbsp;每个部分矩形拐角独立。<br/>-&nbsp;'miter':在相连部分的外边缘处进行延伸,使其相交于一点,形成一个菱形区域,该属性可以通过设置miterLimit属性展现效果。<br/>-&nbsp;默认值:'miter'。<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 |
| [miterLimit](#miterlimit) | number | 设置斜接面限制值,该值指定了线条相交处内角和外角的距离。 <br/>-&nbsp;默认值:10。<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 |
......@@ -2868,4 +2868,4 @@ struct OffscreenCanvasConicGradientPage {
一个Object对象, 通过[createPattern](#createpattern)方法创建。
从API version 9开始,该接口支持在ArkTS卡片中使用。
\ No newline at end of file
从API version 9开始,该接口支持在ArkTS卡片中使用。
......@@ -39,7 +39,7 @@ requestFocus(value: string): boolean
> **说明:**
>
> 支持焦点控制的组件:Button、Text、Image、List、Grid。焦点事件当前仅支持在真机上显示运行效果。
> 支持焦点控制的组件:TextInput、TextArea、Search、Button、Text、Image、List、Grid。焦点事件当前仅支持在真机上显示运行效果。
## 示例
......
......@@ -12,12 +12,12 @@
| 名称 | 参数说明 | 描述 |
| -------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| width | [Length](ts-types.md#length) | 设置组件自身的宽度,缺省时使用元素自身内容需要的宽度。若子组件的宽大于父组件的宽,则会画出父组件的范围。<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 |
| height | [Length](ts-types.md#length) | 设置组件自身的高度,缺省时使用元素自身内容需要的高度。若子组件的高大于父组件的高,则会画出父组件的范围。<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 |
| size | {<br/>width?:&nbsp;[Length](ts-types.md#length),<br/>height?:&nbsp;[Length](ts-types.md#length)<br/>} | 设置高宽尺寸。<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 |
| padding | [Padding](ts-types.md#padding)&nbsp;\|&nbsp;[Length](ts-types.md#length) | 设置内边距属性。<br/>参数为Length类型时,四个方向内边距同时生效。<br>默认值:0 <br>padding设置百分比时,上下左右内边距均以父容器的width作为基础值。<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 |
| margin | [Margin](ts-types.md#margin)&nbsp;\|&nbsp;[Length](ts-types.md#length) | 设置外边距属性。<br/>参数为Length类型时,四个方向外边距同时生效。<br>默认值:0 <br>margin设置百分比时,上下左右外边距均以父容器的width作为基础值。<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 |
| constraintSize | {<br/>minWidth?:&nbsp;[Length](ts-types.md#length),<br/>maxWidth?:&nbsp;[Length](ts-types.md#length),<br/>minHeight?:&nbsp;[Length](ts-types.md#length),<br/>maxHeight?:&nbsp;[Length](ts-types.md#length)<br/>} | 设置约束尺寸,组件布局时,进行尺寸范围限制。constraintSize的优先级高于Width和Height。若设置的minWidth大于maxWidth,则minWidth生效,minHeight与maxHeight同理。<br>默认值:<br>{<br/>minWidth:&nbsp;0,<br/>maxWidth:&nbsp;Infinity,<br/>minHeight:&nbsp;0,<br/>maxHeight:&nbsp;Infinity<br/>}<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 |
| width | [Length](ts-types.md#length) | 设置组件自身的宽度,缺省时使用元素自身内容需要的宽度。若子组件的宽大于父组件的宽,则会画出父组件的范围。<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。<br />从API version 10开始,该接口支持calc计算特性。 |
| height | [Length](ts-types.md#length) | 设置组件自身的高度,缺省时使用元素自身内容需要的高度。若子组件的高大于父组件的高,则会画出父组件的范围。<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。<br />从API version 10开始,该接口支持calc计算特性。 |
| size | {<br/>width?:&nbsp;[Length](ts-types.md#length),<br/>height?:&nbsp;[Length](ts-types.md#length)<br/>} | 设置高宽尺寸。<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。<br />从API version 10开始,该接口支持calc计算特性。 |
| padding | [Padding](ts-types.md#padding)&nbsp;\|&nbsp;[Length](ts-types.md#length) | 设置内边距属性。<br/>参数为Length类型时,四个方向内边距同时生效。<br>默认值:0 <br>padding设置百分比时,上下左右内边距均以父容器的width作为基础值。<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。<br />从API version 10开始,该接口支持calc计算特性。 |
| margin | [Margin](ts-types.md#margin)&nbsp;\|&nbsp;[Length](ts-types.md#length) | 设置外边距属性。<br/>参数为Length类型时,四个方向外边距同时生效。<br>默认值:0 <br>margin设置百分比时,上下左右外边距均以父容器的width作为基础值。<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。<br />从API version 10开始,该接口支持calc计算特性。 |
| constraintSize | {<br/>minWidth?:&nbsp;[Length](ts-types.md#length),<br/>maxWidth?:&nbsp;[Length](ts-types.md#length),<br/>minHeight?:&nbsp;[Length](ts-types.md#length),<br/>maxHeight?:&nbsp;[Length](ts-types.md#length)<br/>} | 设置约束尺寸,组件布局时,进行尺寸范围限制。constraintSize的优先级高于Width和Height。若设置的minWidth大于maxWidth,则minWidth生效,minHeight与maxHeight同理。<br>默认值:<br>{<br/>minWidth:&nbsp;0,<br/>maxWidth:&nbsp;Infinity,<br/>minHeight:&nbsp;0,<br/>maxHeight:&nbsp;Infinity<br/>}<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。<br />从API version 10开始,该接口支持calc计算特性。 |
| layoutWeight | number&nbsp;\|&nbsp;string | 父容器尺寸确定时,设置了layoutWeight属性的子元素与兄弟元素占主轴尺寸按照权重进行分配,忽略元素本身尺寸设置,表示自适应占满剩余空间。<br>默认值:0<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。<br/>**说明:**<br/>仅在Row/Column/Flex布局中生效。<br/>可选值为大于等于0的数字,或者可以转换为数字的字符串。 |
......
......@@ -576,7 +576,7 @@ Failed to install the HAP because of low APL in the non-system data proxy (requi
## 17700044 安装包设置的多进程配置项与系统配置项设置矛盾
**错误信息**<br/>
Failed to install the HAP because the isolationMode does not match the system.
Failed to install the HAP because the isolationMode configured is not supported.
**错误描述**<br/>
安装应用时,设置的isolationMode与系统配置项所允许的系统配置项矛盾。
......
......@@ -58,23 +58,23 @@ Input method client error.
重新将输入法应用与三方应用进行绑定:将三方应用后台进程杀死,重新启动三方应用,通过点击对话框等方式触发输入法键盘的显示,若键盘正常显示,则问题解决。
## 12800004 按键事件处理异常
## 12800004 不是输入法应用
**错误信息**
Key event processing error.
Not an input method extension.
**错误描述**
按键事件异常时,系统会报此错误码。
其他应用调用了仅支持输入法应用调用的接口时,系统会报此错误码。
**可能原因**
按键事件分发、消费、监听异常时会报错
在其他应用中调用了仅支持输入法应用调用的接口
**处理步骤**
在输入法应用中调用此接口。
## 12800005 配置固化失败
......@@ -146,4 +146,22 @@ Input method manager service error.
**处理步骤**
通过ps -A|grep inputmethod查看是否存在输入法服务的进程号,如果存在,则服务正常。
\ No newline at end of file
通过ps -A|grep inputmethod查看是否存在输入法服务的进程号,如果存在,则服务正常。
## 12800009 输入法客户端未绑定
**错误信息**
Input method client is detached.
**错误描述**
当前应用未绑定输入法应用。
**可能原因**
当前应用在没有绑定输入法的情况下执行了比如showTextInput、hideTextInput等操作。
**处理步骤**
先执行attach接口操作即可。
\ No newline at end of file
......@@ -3,6 +3,7 @@
提供获取pixelmap的数据和信息的接口方法。
使用该文件下接口,需要依赖:libpixelmap_ndk.z.so
@Syscap SystemCapability.Multimedia.Image
......
......@@ -1836,7 +1836,7 @@
**授权方式**:system_grant
**ACL使能**:TURE
**ACL使能**:TRUE
## ohos.permission.GET_DISTRIBUTED_ACCOUNTS
......@@ -1846,7 +1846,7 @@
**授权方式**:system_grant
**ACL使能**:TURE
**ACL使能**:TRUE
## ohos.permission.GET_LOCAL_ACCOUNTS
......@@ -1856,7 +1856,7 @@
**授权方式**:system_grant
**ACL使能**:TURE
**ACL使能**:TRUE
## ohos.permission.READ_HIVIEW_SYSTEM
......
......@@ -7,7 +7,7 @@
| 动画类型 | 特点 |
| ---- | ---------------------------------------- |
| 显式动画 | 闭包内的变化均会触发动画,包括由数据变化引起的组件的增删、组件属性的变化等,可以做较为复杂的动画。 | 较复杂的动画场景 |
| 属性动画 | 动画设置简单,属性变化时自动触发动画。 |
| 属性动画 | 动画设置简单,属性变化时自动触发动画。 |
## 使用显式动画产生布局更新动画
......@@ -226,9 +226,9 @@ struct LayoutChange2 {
.height(this.myHeight)
// animation只对其上面的type、width、height属性生效,时长为1000ms,曲线为Ease
.animation({ duration: 1000, curve: Curve.Ease })
// animation对下面的backgroundColor、margin属性不生效
.backgroundColor(this.myColor)
.margin(20)
// animation对下面的backgroundColor、margin属性不生效
Button("area: click me")
.fontSize(12)
......
......@@ -219,54 +219,6 @@ struct MyComponent {
![flex1](figures/flex1.PNG)
## 设置List组件的宽高
开发者在使用Scroll容器组件嵌套List子组件时,若不指定List的宽高尺寸,则默认全部加载,如下所示:
```ts
@Entry
@Component
struct MyComponent {
private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
build() {
Scroll() {
List() {
ForEach(this.arr, (item) => {
ListItem() {
Text(`item value: ${item}`).fontSize(30).margin({ left: 10 })
}.height(100)
}, (item) => item.toString())
}
}.backgroundColor(Color.Pink)
}
}
```
因此,在这种场景下建议开发者设置List子组件的宽高,如下所示:
```ts
@Entry
@Component
struct MyComponent {
private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
build() {
Scroll() {
List() {
ForEach(this.arr, (item) => {
ListItem() {
Text(`item value: ${item}`).fontSize(30).margin({ left: 10 })
}.height(100)
}, (item) => item.toString())
}.width('100%').height(500)
}.backgroundColor(Color.Pink)
}
}
```
![list1](figures/list1.gif)
## 减少应用滑动白块
应用通过增大List/Grid控件的cachedCount参数,调整UI的加载范围。cachedCount表示屏幕外List/Grid预加载item的个数。
......
......@@ -17,7 +17,7 @@
## 实现思路
如图,我们分上下两层、左右两侧建立4个文本组件(下文用A、B、C、D代称),左右两侧分别代表打开书籍的左右两面,上下两层堆叠放置。
如图,分上下两层、左右两侧建立4个文本组件(下文用A、B、C、D代称),左右两侧分别代表打开书籍的左右两面,上下两层堆叠放置。
当B沿旋转轴旋转180度覆盖在A上时,就体现为翻页效果。一个翻页动作的完成包括以下几步:
1. B沿旋转轴旋转180度。
......@@ -33,10 +33,11 @@
## 开发步骤
1. 创建文本组件
首先,我们看到动效中用到了4个文本组件,我们可以定义一个文本组件,然后对其进行重复调用。创建时我们为其添加[rotate](../application-dev/reference/arkui-ts/ts-universal-attributes-transformation.md)属性,用来控制组件的旋转。
由于各组件旋转的角度和旋转中心不同,需要父组件在调用时传入对应的参数,所以我们为对应变量添加[@Prop](../application-dev/quick-start/arkts-prop.md)装饰器,用来控制变量传递。具体代码如下:
```
1. 创建文本组件。
动效中用到了4个文本组件,因此可以先定义一个文本组件,然后对其进行重复调用。同时为文本组件添加[rotate](../application-dev/reference/arkui-ts/ts-universal-attributes-transformation.md)属性,用来控制组件的旋转。
由于各组件旋转的角度和旋转中心不同,需要父组件在调用时传入对应的参数,所以需要为对应变量添加[@Prop](../application-dev/quick-start/arkts-prop.md)装饰器,用来控制变量传递。具体代码如下:
```ts
@Component
struct BookCard{
// 为变量添加@Prop装饰器,用于接收父组件的动态传参
......@@ -67,9 +68,10 @@
}
}
```
2. 创建父组件框架
由于文本组件分为上下两层,所以我们在父组件中采用[Stack](../application-dev/reference/arkui-ts/ts-container-stack.md)组件进行层叠布局。同时使用[Divider](../application-dev/reference/arkui-ts/ts-basic-components-divider.md)组件作为书籍两个页面间的分隔线。具体代码如下:
```
2. 创建父组件框架。
由于文本组件分为上下两层,所以在父组件中采用[Stack](../application-dev/reference/arkui-ts/ts-container-stack.md)组件进行层叠布局。同时使用[Divider](../application-dev/reference/arkui-ts/ts-basic-components-divider.md)组件作为书籍两个页面间的分隔线。具体代码如下:
```ts
@Entry
@Component
struct BookAnimation {
......@@ -102,14 +104,14 @@
}
```
3. 添加翻页动效
3. 添加翻页动效
最后我们通过以下几点来为静态的组件添加动效:
最后通过以下几点来为静态的组件添加动效:
- 根据**实现思路**章节的分析,在父组件中定义对应的变量,并在调用子组件时分别传入子组件。
- 自定义book_animate函数,在其中使用animateTo方法添加动画效果,同时控制动画的时长,以及动画过程中各元素状态的改变。
- 在[aboutToAppear](../application-dev/reference/arkui-ts/ts-custom-component-lifecycle.md#abouttoappear)方法中,使用[setInterval](../application-dev/reference/apis/js-apis-timer.md)方法重复调用book_animate函数,以实现连续翻页动效。
具体代码如下:
```
```ts
@Entry
@Component
struct BookAnimation {
......@@ -177,11 +179,11 @@
}
}
```
通过以上步骤我们就可以实现翻页动效了。
通过以上步骤就可以实现翻页动效了。
## 完整代码
示例完整代码如下:
```
```ts
@Component
struct BookCard{
@Prop num:number
......
# 如何为同一组件在不同场景下绑定不同的业务逻辑
## 场景介绍
我们在应用开发过程中经常遇到这样的场景:在不同的地方需要呈现同样的UI效果,为了简化处理,我们往往会把对应的UI元素封装成自定义组件,然后在用到的地方进行调用。但是,通常情况下,UI展示往往伴随着动态交互,而且在不同场景下需要做不同的交互处理。
在应用开发过程中经常遇到这样的场景:在不同的地方需要呈现同样的UI效果,为了简化处理,往往会把对应的UI元素封装成自定义组件,然后在用到的地方进行调用。但是,通常情况下,UI展示往往伴随着动态交互,而且在不同场景下需要做不同的交互处理。
*比如:A、B两个页面都有返回按钮,但是在A页面中点击返回按钮是返回上一页,在B页面点击返回按钮是直接退出当前应用。同样是点击返回按钮,但是业务处理逻辑是不同的。*
那么在不同场景下调用同一组件的时候如何实现不同的交互逻辑呢?这就引出了本文要讲的内容。
## 实现思路
要使同一组件实现不同效果,我们很容易就想到通过变量传参进行控制,而不是直接在程序中采用固定值,这样我们就可以根据不同场景传入不同参数从而实现不同效果。
我们通常使用传参的方式改变组件的属性,比如:大小、边框、背景色、字体等等,同样的,我们也可以通过传参的方式改变组件绑定的业务逻辑,只不过,此时我们传入的是方法,然后在对应方法中写入具体的业务逻辑
要使同一组件实现不同效果,我们很容易就想到通过变量传参进行控制,而不是直接在程序中采用固定值,这样就可以根据不同场景传入不同参数从而实现不同效果。
通过传参的方式改变组件的属性,比如:大小、边框、背景色、字体等等,同样的,也可以通过传参的方式改变组件绑定的业务逻辑,只不过此时传入的是含有业务逻辑的方法
接下来我们用一个简单的例子讲解如何实现。
## 开发示例
本示例将在一个页面中两次引用同一个按钮,然后为两次引用加入不同的处理逻辑,第一次引用中,点击按钮跳转到‘’Hello World!’‘页面;第二次引用中,点击按钮跳转到’‘Hello ArkTS!’‘页面。
本示例将在一个页面中两次引用同一个按钮,然后为两次引用加入不同的处理逻辑,第一次引用中,点击按钮跳转到“Hello World!”页面;第二次引用中,点击按钮跳转到“Hello ArkTS!”页面。
### 环境要求
- IDE:DevEco Studio 3.1 Beta1
......@@ -20,7 +21,8 @@
### 开发步骤
1. 创建按钮组件
首先,让我们创建被引用的按钮组件。
首先,创建被引用的按钮组件。
这里需要注意的是,由于按钮要绑定不同的处理逻辑,所以我们在点击事件中不要写入固定的处理逻辑,而是传入一个自定义的空方法,该方法的逻辑在父组件中实现,然后传入。具体代码如下:
```ts
@Component
......@@ -41,6 +43,7 @@
```
2. 在父组件中引用按钮组件
接下来,我们在父组件中引用两次第1步中创建的按钮组件。具体代码如下:
```ts
@Entry
......@@ -61,8 +64,9 @@
```
3. 在父组件中传入处理逻辑
以上两步已经把我们的页面框架搭好了,接下来就是给按钮组件传入处理逻辑了,这也是最重要的一步。
我们在第1步中为按钮组件的点击事件绑定了一个空函数,现在我们在父组件中创建一个带有具体处理逻辑的函数,并将其传入按钮组件中。在父组件中可以通过为同一函数传入不同参数来为两个按钮组件绑定不同逻辑,也可以通过不同函数来实现,本例中采用前者进行实现。具体代码如下:
以上两步已经把页面框架搭好了,接下来给按钮组件传入处理逻辑,这也是最重要的一步。
在第1步中为按钮组件的点击事件绑定了一个空函数,现在我们在父组件中创建一个带有具体处理逻辑的函数,并将其传入按钮组件中。在父组件中可以通过为同一函数传入不同参数来为两个按钮组件绑定不同逻辑,也可以通过不同函数来实现,本例中采用前者进行实现。具体代码如下:
```ts
import router from '@ohos.router'
@Entry
......@@ -89,8 +93,8 @@
}
```
通过以上步骤我们实现了在为同一按钮组件绑定不同的业务处理逻辑,接下来就让我们看下效果吧!
注意:文中的‘’Hello World!’‘页面和’‘Hello ArkTS!’‘页面不是本文说明的重点,所以本文中不做开发介绍。
通过以上步骤我们实现了在为同一按钮组件绑定不同的业务处理逻辑,接下来看下效果吧!
注意:文中的“Hello World!”页面和“Hello ArkTS!”页面不是本文说明的重点,所以本文中不做开发介绍。
![相同子组件不同业务逻辑](figures/different-operations-one-component.gif)
......
# 如何按字母分组展示联系人(仅UI)
# 如何按字母分组展示联系人
## 场景说明
在通讯录中,需要将联系人按照姓氏的首字母进行分组排列,从而更方便联系人的查找;联系人列表右侧的字母导航可以随列表的滑动而定位到对应字母处;同时,也可以通过字母导航控制列表跳到指定联系人分组。
本例即为大家介绍如何通过实现上述场景。
本例即为大家介绍如何实现上述场景。
## 效果呈现
本示例最终效果如下:
......@@ -23,7 +23,7 @@
## 开发步骤
针对上述关键特性,具体实现步骤如下:
1、通过Stack、List、ListItemGroup、AlphabetIndexer等关键组件将UI框架搭建起来。
1、通过Stack、List、ListItemGroup、AlphabetIndexer等关键组件将UI框架搭建起来。
先构建列表数据,其中Contact为联系人数据类。
```ts
contactGroups: object[] = [
......@@ -113,7 +113,7 @@ struct ContactList{
![contactframe](figures/contactframe.PNG)
2、接下来我们为UI框架添加逻辑控制。首先,通过List的onScrollIndex事件获取到列表滑动位置的索引,并将索引同步给右侧字母表的selected属性,从而在滑动联系人时,使右侧字母导航随之变动,关键代码如下:
2、接下来为UI框架添加逻辑控制。首先,通过List的onScrollIndex事件获取到列表滑动位置的索引,并将索引同步给右侧字母表的selected属性,从而在滑动联系人时,使右侧字母导航随之变动,关键代码如下:
```ts
...
// 创建动态变量,用于指定字母导航的选择项
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册