diff --git a/en/application-dev/application-models/application-context-stage.md b/en/application-dev/application-models/application-context-stage.md index cc19530d99ca4bf2005fcb4b5084c9e83b445193..3fc6df944c5b9b137c585f59a8f83cd61db226f9 100644 --- a/en/application-dev/application-models/application-context-stage.md +++ b/en/application-dev/application-models/application-context-stage.md @@ -3,7 +3,7 @@ ## Overview -[Context](../reference/apis/js-apis-inner-application-context.md) is the context of an object in an application. It provides basic information about the application, for example, **resourceManager**, **applicationInfo**, **dir** (application development path), and **area** (encrypted area). It also provides basic methods such as **createBundleContext()** and **getApplicationContext()**. The UIAbility component and ExtensionAbility derived class components have their own **Context** classes, for example, the base class **Context**, **ApplicationContext**, **AbilityStageContext**, **UIAbilityContext**, **ExtensionContext**, and **ServiceExtensionContext**. +[Context](../reference/apis/js-apis-inner-application-context.md) is the context of an object in an application. It provides basic information about the application, for example, **resourceManager**, **applicationInfo**, **dir** (application development path), and **area** (encryption level). It also provides basic methods such as **createBundleContext()** and **getApplicationContext()**. The UIAbility component and ExtensionAbility derived class components have their own **Context** classes, for example, the base class **Context**, **ApplicationContext**, **AbilityStageContext**, **UIAbilityContext**, **ExtensionContext**, and **ServiceExtensionContext**. - The figure below illustrates the inheritance relationship of contexts. @@ -71,7 +71,7 @@ This topic describes how to use the context in the following scenarios: - [Obtaining the Application Development Path](#obtaining-the-application-development-path) -- [Obtaining and Modifying Encryption Areas](#obtaining-and-modifying-encryption-areas) +- [Obtaining and Modifying Encryption Levels](#obtaining-and-modifying-encryption-levels) - [Creating Context of Another Application or Module](#creating-context-of-another-application-or-module) - [Subscribing to UIAbility Lifecycle Changes in a Process](#subscribing-to-uiability-lifecycle-changes-in-a-process) @@ -144,19 +144,19 @@ export default class EntryAbility extends UIAbility { > > The sample code obtains the sandbox path of the application development path. The absolute path can be obtained by running the **find / -name ** command in the hdc shell after file creation or modification. -### Obtaining and Modifying Encryption Areas +### Obtaining and Modifying Encryption Levels -Encrypting application files enhances data security by preventing files from unauthorized access. Different application files require different levels of protection. For private files, such as alarms and wallpapers, the application must place them in the device-level encryption area (EL1) to ensure that they can be accessed before the user enters the password. For sensitive files, such as personal privacy data, the application must place them in the user-level encryption area (EL2). +Encrypting application files enhances data security by preventing files from unauthorized access. Different application files require different levels of protection. For private files, such as alarms and wallpapers, the application must place them in a directory with the device-level encryption (EL1) to ensure that they can be accessed before the user enters the password. For sensitive files, such as personal privacy data, the application must place them in a directory with the user-level encryption (EL2). -In practice, you need to select a proper encrypted area based on scenario-specific requirements to protect application data security. The proper use of EL1 and the EL2 can efficiently improve the security. +In practice, you need to select a proper encryption level based on scenario-specific requirements to protect application data security. The proper use of EL1 and the EL2 can efficiently improve the security. > **NOTE** > -> - AreaMode.EL1: device-level encryption area, which is accessible after the device is powered on. +> - AreaMode.EL1: device-level encryption. Directories with this encryption level are accessible after the device is powered on. > -> - AreaMode.EL2: user-level encryption area, which is accessible only after the device is powered on and the password is entered (for the first time). +> - AreaMode.EL2: user-level encryption. Directories with this encryption level are accessible only after the device is powered on and the password is entered (for the first time). -You can obtain and set the encryption area by reading and writing the [area attribute in Context](../reference/apis/js-apis-inner-application-context.md). +You can obtain and set the encryption level by reading and writing the [area attribute in Context](../reference/apis/js-apis-inner-application-context.md). ```ts import UIAbility from '@ohos.app.ability.UIAbility'; diff --git a/en/application-dev/media/av-overview.md b/en/application-dev/media/av-overview.md index eb0ea76dbfa90a3d3e3dd13e98ecf40876714310..e2d68235e51d790ab047e8e9e0348b4245971515 100644 --- a/en/application-dev/media/av-overview.md +++ b/en/application-dev/media/av-overview.md @@ -17,11 +17,14 @@ Before developing an audio feature, especially before implementing audio data pr Before developing features related to audio and video playback, you are advised to understand the following concepts: - Playback process: network protocol > container format > audio and video codec > graphics/audio rendering + - Network protocols: HLS, HTTP, HTTPS, and more + - Container formats: MP4, MKV, MPEG-TS, WebM, and more + - Encoding formats: H.263/H.264/H.265, MPEG4/MPEG2, and more -## Introduction to Audio Streams +## Introduction to Audio Streams An audio stream is an independent audio data processing unit that has a specific audio format and audio usage scenario information. The audio stream can be used in playback and recording scenarios, and supports independent volume adjustment and audio device routing. @@ -29,20 +32,20 @@ The basic audio stream information is defined by [AudioStreamInfo](../reference/ ### Audio Stream Usage Scenario Information -In addition to the basic information (which describes only audio data), an audio stream has usage scenario information. This is because audio streams differ in the volume, device routing, and concurrency policy. The system chooses an appropriate processing policy for an audio stream based on the usage scenario information, thereby delivering the optimal user experience. +In addition to the basic information (which describes only audio data), an audio stream has usage scenario information. This is because audio streams differ in the volume, device routing, and concurrency policy. The system chooses an appropriate processing policy for an audio stream based on the usage scenario information, thereby delivering better user experience. - Playback scenario - -Information about the audio playback scenario is defined by using [StreamUsage](../reference/apis/js-apis-audio.md#streamusage) and [ContentType](../reference/apis/js-apis-audio.md#contenttype). - -- **StreamUsage** specifies the usage type of an audio stream, for example, used for media, voice communication, voice assistant, notification, and ringtone. - -- **ContentType** specifies the content type of data in an audio stream, for example, speech, music, movie, notification tone, and ringtone. - + + Information about the audio playback scenario is defined by using [StreamUsage](../reference/apis/js-apis-audio.md#streamusage) and [ContentType](../reference/apis/js-apis-audio.md#contenttype). + +- **StreamUsage** specifies the usage type of an audio stream, for example, used for media, voice communication, voice assistant, notification, and ringtone. + +- **ContentType** specifies the content type of data in an audio stream, for example, speech, music, movie, notification tone, and ringtone. + - Recording scenario - -Information about the audio stream recording scenario is defined by [SourceType](../reference/apis/js-apis-audio.md#sourcetype8). - + + Information about the audio stream recording scenario is defined by [SourceType](../reference/apis/js-apis-audio.md#sourcetype8). + **SourceType** specifies the recording source type of an audio stream, including the mic source, voice recognition source, and voice communication source. ## Supported Audio Formats @@ -58,9 +61,9 @@ The sampling rate varies according to the device type. - Mono and stereo are supported. For details, see [AudioChannel](../reference/apis/js-apis-audio.md#audiochannel8). - The following sampling formats are supported: U8 (unsigned 8-bit integer), S16LE (signed 16-bit integer, little endian), S24LE (signed 24-bit integer, little endian), S32LE (signed 32-bit integer, little endian), and F32LE (signed 32-bit floating point number, little endian). For details, see [AudioSampleFormat](../reference/apis/js-apis-audio.md#audiosampleformat8). - -Due to system restrictions, only some devices support the sampling formats S24LE, S32LE, and F32LE. - + + Due to system restrictions, only some devices support the sampling formats S24LE, S32LE, and F32LE. + Little endian means that the most significant byte is stored at the largest memory address and the least significant byte of data is stored at the smallest. This storage mode effectively combines the memory address with the bit weight of the data. Specifically, the largest memory address has a high weight, and the smallest memory address has a low weight. The audio and video formats supported by the APIs of the media module are described in [AVPlayer and AVRecorder](avplayer-avrecorder-overview.md). diff --git a/en/application-dev/quick-start/arkts-appstorage.md b/en/application-dev/quick-start/arkts-appstorage.md index 1bfc8360ff33c8377d1e5d476d0e2de777ee0f72..2f11d6b826d0a0e280c3efdc00905e509fb0e9f6 100644 --- a/en/application-dev/quick-start/arkts-appstorage.md +++ b/en/application-dev/quick-start/arkts-appstorage.md @@ -16,7 +16,7 @@ AppStorage is a singleton LocalStorage object that is created by the UI framewor UI components synchronize application state attributes with the AppStorage. Implementation of application business logic can access AppStorage as well. -Selected state attributes of AppStorage can be synched with different data sources or data sinks. Those data sources and sinks can be on a local or remote device, and have different capabilities, such as data persistence (see [PersistentStorage](arkts-persiststorage.md)). These data sources and sinks are implemented in the business logic, separate from the UI. Link those AppStorage attributes to [@StorageProp](#storageprop) and [@StorageLink](#storagelink) whose values should be kept until application re-start. +Selected state attributes of AppStorage can be synced with different data sources or data sinks. Those data sources and sinks can be on a local or remote device, and have different capabilities, such as data persistence (see [PersistentStorage](arkts-persiststorage.md)). These data sources and sinks are implemented in the business logic, separate from the UI. Link those AppStorage attributes to [@StorageProp](#storageprop) and [@StorageLink](#storagelink) whose values should be kept until application re-start. ## \@StorageProp diff --git a/en/application-dev/quick-start/arkts-localstorage.md b/en/application-dev/quick-start/arkts-localstorage.md index ab289b9e6e2fc62aa0c51c7dea3bd1cebc24cf7c..3c3e4853f8aac66be1afc1ef47d295ecc7528830 100644 --- a/en/application-dev/quick-start/arkts-localstorage.md +++ b/en/application-dev/quick-start/arkts-localstorage.md @@ -35,7 +35,8 @@ LocalStorage provides two decorators based on the synchronization type of the co ## Restrictions -Once created, the type of a named attribute cannot be changed. Subsequent calls to **Set** must set a value of same type. +- Once created, the type of a named attribute cannot be changed. Subsequent calls to **Set** must set a value of same type. +- LocalStorage provides page-level storage. The [GetShared](../reference/arkui-ts/ts-state-management.md#getshared9) API can only obtain the LocalStorage instance transferred through [windowStage.loadContent](../reference/apis/js-apis-window.md#loadcontent9) in the current stage. Otherwise, **undefined** is returned. Example: [Sharing a LocalStorage Instance from UIAbility to One or More Pages](#sharing-a-localstorage-instance-from-uiability-to-one-or-more-pages). ## \@LocalStorageProp @@ -51,7 +52,7 @@ When a custom component is initialized, the \@LocalStorageProp(key)/\@LocalStora > Since API version 9, this decorator is supported in ArkTS widgets. -By decorating a variable with \@LocalStorageProp(key), a one-way data synchronization is established with the attribute with the given key in LocalStorage. A local change can be made, but it will not besynchronized to LocalStorage. An update to the attribute with the given key in LocalStorage will overwrite local changes. +By decorating a variable with \@LocalStorageProp(key), a one-way data synchronization is established with the attribute with the given key in LocalStorage. A local change can be made, but it will not be synchronized to LocalStorage. An update to the attribute with the given key in LocalStorage will overwrite local changes. ### Rules of Use @@ -127,7 +128,7 @@ By decorating a variable with \@LocalStorageProp(key), a one-way data synchroniz | Transfer/Access | Description | | ---------- | ---------------------------------------- | | Initialization and update from the parent component| Forbidden.| -| Subnode initialization | Supported; can be used to initialize a n \@State, \@Link, \@Prop, or \@Provide decorated variable in the child component.| +| Subnode initialization | Supported; can be used to initialize an \@State, \@Link, \@Prop, or \@Provide decorated variable in the child component.| | Access | None. | diff --git a/en/application-dev/quick-start/arkts-prop.md b/en/application-dev/quick-start/arkts-prop.md index 53463650284130c31e9761ea59cc303b36be0dd2..ca1ac8c34cdd8fb1f783cdadac3a219bfcc05548 100644 --- a/en/application-dev/quick-start/arkts-prop.md +++ b/en/application-dev/quick-start/arkts-prop.md @@ -15,17 +15,17 @@ For an \@Prop decorated variable, the value synchronization is uni-directional f - An @Prop variable is allowed to be modified locally, but the change does not propagate back to its parent component. -- Whenever that data source changes, the @Prop decorated variable gets updated, and any locally made changes are overwritten. +- Whenever that data source changes, the @Prop decorated variable gets updated, and any locally made changes are overwritten. In other words, the value synchronization is from the parent component to the (owning) child component, but not from the other way around. ## Rules of Use -| \@Prop Decorator| Description | -| ----------- | ---------------------------------------- | -| Decorator parameters | None. | -| Synchronization type | One-way: from the data source provided by the parent component to the @Prop decorated variable.| -| Allowed variable types | string, number, boolean, or enum type.
**any** is not supported. The **undefined** and **null** values are not allowed.
The type must be specified.
Negative examples:
CompA ({ aProp: undefined })
CompA ({ aProp: null })
The type must be the same as that of the [data source](arkts-state-management-overview.md#basic-concepts). There are three cases (\@State is used as an example of the data source):
- The type of the \@Prop decorated variable is the same as that of the state variable of the parent component, that is, \@Prop: S and \@State: S. For an example, see [Simple Type @Prop Synced from @State in Parent Component](#simple-type-prop-synced-from-state-in-parent-component).
- When the state variable of the parent component is an array, the type of the \@Prop decorated variable is the same as that of the array item of the state variable of the parent component, that is, \@Prop: S and \@State: Array\. For examples, see [Simple Type @Prop Synched from @State Array Item in Parent Component](#simple-type-prop-synched-from-state-array-item-in-parent-component).
- When the state variable of the parent component is Object or class, the type of the \@Prop decorated variableis the same as the attribute type of the state variable of the parent component, that is, \@Prop: S and \@State: { propA: S }. For examples, see [Class Object Type @Prop Synchedd from @State Class Object Property in Parent Component](#class-object-type-prop-synchedd-from-state-class-object-property-in-parent-component).| -| Initial value for the decorated variable | Local initialization is allowed. | +| \@Prop Decorator | Description | +| ------------------ | ------------------------------------------------------------ | +| Decorator parameters | None. | +| Synchronization type | One-way: from the data source provided by the parent component to the @Prop decorated variable. For details about the scenarios of nested types, see [Observed Changes](#observed-changes).| +| Allowed variable types| Object, class, string, number, Boolean, enum, and array of these types.
**any** is not supported. A combination of simple and complex types is not supported. The **undefined** and **null** values are not allowed.
The type must be specified.
**NOTE**
The Length, ResourceStr, and ResourceColor types are a combination of simple and complex types and therefore not supported.
Negative examples:
CompA ({ aProp: undefined })
CompA ({ aProp: null })
The type must be the same as that of the [data source](arkts-state-management-overview.md#basic-concepts). There are three cases:
- Synchronizing the \@Prop decorated variable from an \@State or other decorated variable. Example: [Simple Type @Prop Synced from @State in Parent Component](#simple-type-prop-synced-from-state-in-parent-component).
- Synchronizing the \@Prop decorated variable from the item of an \@State or other decorated array. Example: [Simple Type @Prop Synced from @State Array Item in Parent Component](#simple-type-prop-synced-from-state-array-item-in-parent-component).
- Synchronizing the \@Prop decorated variable from a state attribute of the Object or class type in the parent component. Example: [Class Object Type @Prop Synced from @State Class Object Attribute in Parent Component](#class-object-type-prop-synced-from-state-class-object-attribute-in-parent-component).| +| Initial value for the decorated variable| Local initialization is allowed. | ## Variable Transfer/Access Rules @@ -50,24 +50,89 @@ For an \@Prop decorated variable, the value synchronization is uni-directional f \@Prop decorated variables can observe the following changes: -- When the decorated variable is of the string, number, Boolean, or enum type, its value change can be observed. +- When the decorated variable is of the Object, class, string, number, Boolean, or enum type, its value change can be observed. ```ts // Simple type @Prop count: number; // The value assignment can be observed. this.count = 1; + // Complex type + @Prop count: Model; + // The value assignment can be observed. + this.title = new Model('Hi'); ``` +When the decorated variable is of the Object or class type, the value changes of attributes at the first layer can be observed, that is, the attributes that **Object.keys(observedObject)** returns. + +``` +class ClassA { + public value: string; + constructor(value: string) { + this.value = value; + } +} +class Model { + public value: string; + public a: ClassA; + constructor(value: string, a: ClassA) { + this.value = value; + this.a = a; + } +} + +@Prop title: Model; +// The value changes at the first layer can be observed. +this.title.value = 'Hi' +// The value changes at the second layer cannot be observed. +this.title.a.value = 'ArkUi' +``` + +In the scenarios of nested objects, if a class is decorated by \@Observed, the value changes of the class attribute can be observed. + +``` +@Observed +class ClassA { + public value: string; + constructor(value: string) { + this.value = value; + } +} +class Model { + public value: string; + public a: ClassA; + constructor(value: string, a: ClassA) { + this.value = value; + this.a = a; + } +} +@Prop title: Model; +// The value changes at the first layer can be observed. +this.title.value = 'Hi' +// The value change of the ClassA attribute can be observed because ClassA is decorated by @Observed. this.title.a.value = 'ArkUi'. +``` + +When the decorated variable is of the array type, the value assignment, addition, deletion, and updates of array items can be observed. + +``` +// When the object decorated by @State is an array +@Prop title: string[] +// The value assignment of the array itself can be observed. +this.title = ['1'] +// The value assignment of array items can be observed. +this.title[0] = '2' +// The deletion of array items can be observed. +this.title.pop() +// The addition of array items can be observed. +this.title.push('3') +``` + For synchronization between \@State and \@Prop decorated variables: - The value of an \@State decorated variable in the parent component initializes an \@Prop decorated variable in the child component. The \@State decorated variable also updates the @Prop decorated variable whenever the value of the former changes. - - Changes to the @Prop decorated variable do not affect the value of its source @State decorated variable. - - In addition to \@State, the source can also be decorated with \@Link or \@Prop, where the mechanisms for syncing the \@Prop would be the same. - -- The type of the source and the @Prop decorated variable must be the same. +- The source and \@Prop decorated variable must be of the same type. The \@Prop decorated variable can be of simple and class types. ### Framework Behavior @@ -146,16 +211,16 @@ In the preceding example: 1. On initial render, when the **CountDownComponent** child component is created, its @Prop decorated **count** variable is initialized from the \@State decorated **countDownStartValue** variable in the **ParentComponent**. -2. When the "+1" or "-1" button is touched, the @State decorated **countDownStartValue** of the **ParentComponent** changes. This will cause the **ParentComponent** to re-render. At the minumum, the **CountDownComponent** will be updated because of the changed **count** variable value. +2. When the "+1" or "-1" button is touched, the @State decorated **countDownStartValue** of the **ParentComponent** changes. This will cause the **ParentComponent** to re-render. At the minimum, the **CountDownComponent** will be updated because of the changed **count** variable value. 3. Because of the changed **count** variable value, the **CountDownComponent** child component will re-render. At a minimum, the **if** statement's conditions (**this.counter> 0**) is-evaluated and the **\** child component inside the **if** would be updated. -4. When **Try again** in the **CountDownComponent** child component is touched, the value of the **count** variable is modified, but the change remains within the child component and does not affect the **countDownStartValue** in the parenet component. +4. When **Try again** in the **CountDownComponent** child component is touched, the value of the **count** variable is modified, but the change remains within the child component and does not affect the **countDownStartValue** in the parent component. 5. Updating **countDownStartValue** will overwrite the local value changes of the @Prop decorated **count** in the **CountDownComponent** child component. -### Simple Type @Prop Synched from @State Array Item in Parent Component +### Simple Type @Prop Synced from @State Array Item in Parent Component The \@State decorated array an array item in the parent component can be used as data source to initialize and update a @Prop decorated variable. In the following example, the \@State decorated array **arr** in the parent component **Index** initializes the \@Prop decorated **value** variable in the child component **Child**. @@ -240,7 +305,7 @@ After **replace entire arr** is clicked, the following information is displayed: ``` -- Changes made in the **Child** component are not synchronized to the parent component **Index**. Therefore, even if the values of the six intances of the **Child** component are 7, the value of **this.arr** in the **Index** component is still **[1,2,3]**. +- Changes made in the **Child** component are not synchronized to the parent component **Index**. Therefore, even if the values of the six instances of the **Child** component are 7, the value of **this.arr** in the **Index** component is still **[1,2,3]**. - After **replace entire arr** is clicked, if **this.arr[0] == 1** is true, **this.arr** is set to **[3, 4, 5]**. @@ -250,9 +315,11 @@ After **replace entire arr** is clicked, the following information is displayed: - The change of **this.arr** causes **ForEach** to update: The array item with the ID **3** is retained in this update, array items with IDs **1** and **2** are deleted, and array items with IDs **4** and **5** are added. The array before and after the update is **[1, 2, 3]** and **[3, 4, 5]**, respectively. This implies that the **Child** instance generated for item **3** will be moved to the first place, but not updated. In this case, the component value corresponding to **3** is **7**, and the final render result of **ForEach** is **7**, **4**, and **5**. -### Class Object Type @Prop Synchedd from @State Class Object Property in Parent Component +### Class Object Type @Prop Synced from @State Class Object Attribute in Parent Component -In a library with one book and two users, each user can mark the book as read, but this does not affect the other user reader. Technically speaking, local changes to the \@Prop decorated **book** object do not sync back to the @State decorated **book** in the **Library** component. +In a library with one book and two users, each user can mark the book as read, and the marking does not affect the other user reader. Technically speaking, local changes to the \@Prop decorated **book** object do not sync back to the @State decorated **book** in the **Library** component. + +In this example, the \@Observed decorator can be applied to the **book** class, but it is not mandatory. It is only needed for nested structures. This will be further explained in [Class Type @Prop Synced from @State Array Item in Parent Component](#class-type-prop-synced-from-state-array-item-in-parent-component). ```ts @@ -269,14 +336,14 @@ class Book { @Component struct ReaderComp { - @Prop title: string; - @Prop readIt: boolean; + @Prop book: Book; build() { Row() { - Text(this.title) - Text(`... ${this.readIt ? 'I have read' : 'I have not read it'}`) - .onClick(() => this.readIt = true) + Text(this.book.title) + Text(`...has${this.book.pages} pages!`) + Text(`...${this.book.readIt ? "I have read" : 'I have not read it'}`) + .onClick(() => this.book.readIt = true) } } } @@ -288,21 +355,107 @@ struct Library { build() { Column() { - ReaderComp({ title: this.book.title, readIt: this.book.readIt }) - ReaderComp({ title: this.book.title, readIt: this.book.readIt }) + ReaderComp({ book: this.book }) + ReaderComp({ book: this.book }) + } + } +} +``` + +### Class Type @Prop Synced from @State Array Item in Parent Component + +In the following example, an attribute of the **Book** object in the \@State decorated **allBooks** array is changed, but the system does not respond when **Mark read for everyone** is clicked. This is because the attribute is a nested attribute of the second layer, and the \@State decorator can observe only the attribute of the first layer. Therefore, the framework does not update **ReaderComp**. + +``` +let nextId: number = 1; + +// @Observed +class Book { + public id: number; + public title: string; + public pages: number; + public readIt: boolean = false; + + constructor(title: string, pages: number) { + this.id = nextId++; + this.title = title; + this.pages = pages; + } +} + +@Component +struct ReaderComp { + @Prop book: Book; + + build() { + Row() { + Text(this.book.title) + Text(`...has${this.book.pages} pages!`) + Text(`...${this.book.readIt ? "I have read" : 'I have not read it'}`) + .onClick(() => this.book.readIt = true) + } + } +} + +@Entry +@Component +struct Library { + @State allBooks: Book[] = [new Book("100 secrets of C++", 765), new Book("Effective C++", 651), new Book("The C++ programming language", 1765)]; + + build() { + Column() { + Text('library`s all time favorite') + ReaderComp({ book: this.allBooks[2] }) + Divider() + Text('Books on loaan to a reader') + ForEach(this.allBooks, book => { + ReaderComp({ book: book }) + }, + book => book.id) + Button('Add new') + .onClick(() => { + this.allBooks.push(new Book("The C++ Standard Library", 512)); + }) + Button('Remove first book') + .onClick(() => { + this.allBooks.shift(); + }) + Button("Mark read for everyone") + .onClick(() => { + this.allBooks.forEach((book) => book.readIt = true) + }) } } } ``` + To observe the attribute of the **Book** object, you must use \@Observed to decorate the **Book** class. Note that the \@Prop decorated state variable in the child component is one-way synchronized from the data source of the parent component. This means that, the changes of the \@Prop decorated **book** in **ReaderComp** is not synchronized to the parent **library** component. The parent component triggers UI re-rendering only when the value is updated (compared with the last state). + +``` +@Observed +class Book { + public id: number; + public title: string; + public pages: number; + public readIt: boolean = false; + + constructor(title: string, pages: number) { + this.id = nextId++; + this.title = title; + this.pages = pages; + } +} +``` + +All instances of the \@Observed decorated class are wrapped with an opaque proxy object. This proxy can detect all attribute changes inside the wrapped object. If any attribute change happens, the proxy notifies the \@Prop, and the \@Prop value will be updated. -### Simple Type @Prop with Local Initialization and No Sync from Parent Parent +### Simple Type @Prop with Local Initialization and No Sync from Parent Component To enable an \@Component decorated component to be reusable, \@Prop allows for optional local initialization. This makes the synchronization with a variable in the parent component a choice, rather than mandatory. Providing a data source in the parent component is optional only when local initialization is provided for the \@Prop decorated variable. The following example includes two @Prop decorated variables in child component. -- The @Prop decorated variable **customCounter** has no local initialization, and therefore it requires a synchronization source in its parent component. When the source value changes, the @Prop decorated variable is udpated. +- The @Prop decorated variable **customCounter** has no local initialization, and therefore it requires a synchronization source in its parent component. When the source value changes, the @Prop decorated variable is updated. - The @Prop decorated variable **customCounter2** has local initialization. In this case, specifying a synchronization source in the parent component is allowed but not mandatory. @@ -351,13 +504,13 @@ struct MainProgram { Row() { Column() - // customCounter must be initialized from the parent component due to lack of local initialization. Here, customCounter2 does not need to be initialized. - MyComponent({ customCounter: this.mainCounter }) - // customCounter2 of the child component can also be initialized from the parent component. The value from the parent component overwrites the locally assigned value of customCounter2 during initialization. - MyComponent({ customCounter: this.mainCounter, customCounter2: this.mainCounter }) - }.width('40%') + // customCounter must be initialized from the parent component due to lack of local initialization. Here, customCounter2 does not need to be initialized. + MyComponent({ customCounter: this.mainCounter }) + // customCounter2 of the child component can also be initialized from the parent component. The value from the parent component overwrites the locally assigned value of customCounter2 during initialization. + MyComponent({ customCounter: this.mainCounter, customCounter2: this.mainCounter }) + }.width('40%') } } } ``` - \ No newline at end of file + diff --git a/en/application-dev/reference/apis/js-apis-app-ability-abilityLifecycleCallback.md b/en/application-dev/reference/apis/js-apis-app-ability-abilityLifecycleCallback.md index 28c0772d7d5718cd328f318535bb276ff32550cf..d82597dc6483390fc59d404982760621b8ad62bd 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-abilityLifecycleCallback.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-abilityLifecycleCallback.md @@ -7,14 +7,12 @@ The **AbilityLifecycleCallback** module defines the callbacks to receive lifecyc > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs of this module can be used only in the stage model. - ## Modules to Import ```ts import AbilityLifecycleCallback from '@ohos.app.ability.AbilityLifecycleCallback'; ``` - ## AbilityLifecycleCallback.onAbilityCreate onAbilityCreate(ability: UIAbility): void; diff --git a/en/application-dev/reference/apis/js-apis-app-ability-appRecovery.md b/en/application-dev/reference/apis/js-apis-app-ability-appRecovery.md index d86ca90a4576fbb67816f93749b75b670c6f24a2..ebe37268a6ef9deab92d6e5d3108e573a352214f 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-appRecovery.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-appRecovery.md @@ -11,7 +11,6 @@ The **appRecovery** module provides APIs for recovering faulty applications. import appRecovery from '@ohos.app.ability.appRecovery'; ``` - ## appRecovery.RestartFlag Enumerates the application restart flags. This enum is used as an input parameter of [enableAppRecovery](#apprecoveryenableapprecovery). @@ -174,9 +173,17 @@ Saves the ability state, which will be used for recovery. This API can be used t ```ts import appRecovery from '@ohos.app.ability.appRecovery'; -onBackground() { - hilog.info(0x0000, '[demo]', '%{public}s', 'EntryAbility onBackground'); - appRecovery.saveAppState(this.context) +let observer = { + onUnhandledException(errorMsg) { + console.log('onUnhandledException, errorMsg: ', errorMsg); + appRecovery.saveAppState(this.context); + } +}; + +try { + errorManager.on('error', observer); +} catch (paramError) { + console.error('error: ${paramError.code}, ${paramError.message}'); } ``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-contextConstant.md b/en/application-dev/reference/apis/js-apis-app-ability-contextConstant.md index 0c39c8fa01fe62a537614287f3d27645c8b0f354..080128ea94047b001ed5d0a5f5414ac0172c6b3a 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-contextConstant.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-contextConstant.md @@ -1,10 +1,11 @@ # @ohos.app.ability.contextConstant (ContextConstant) -The **ContextConstant** module defines context-related enums. Currently, it defines only the enum of data encryption levels. +The **ContextConstant** module defines context-related enums. Currently, it defines only the enum of encryption levels. > **NOTE** -> +> > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> > The APIs of this module can be used only in the stage model. ## Modules to Import @@ -21,5 +22,5 @@ You can obtain the value of this constant by calling the **ContextConstant.AreaM | Name| Value| Description| | -------- | -------- | -------- | -| EL1 | 0 | Device-level encryption area, which is accessible after the device is powered on.| -| EL2 | 1 | User-level encryption area, which is accessible only after the device is powered on and the password is entered (for the first time).| +| EL1 | 0 | Device-level encryption. Directories with this encryption level are accessible after the device is powered on.| +| EL2 | 1 | User-level encryption. Directories with this encryption level are accessible only after the device is powered on and the password is entered (for the first time).| diff --git a/en/application-dev/reference/apis/js-apis-enterprise-bundleManager.md b/en/application-dev/reference/apis/js-apis-enterprise-bundleManager.md index 813f551a9fa9aca4363acd222686fe4a5b728b0e..a58e574b6f4bc653e354f294b02b6c653020cebe 100644 --- a/en/application-dev/reference/apis/js-apis-enterprise-bundleManager.md +++ b/en/application-dev/reference/apis/js-apis-enterprise-bundleManager.md @@ -5,6 +5,7 @@ The **bundleManager** module provides APIs for bundle management, including addi > **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 APIs of this module can be called only after a [device administrator application](js-apis-enterprise-adminManager.md#adminmanagerenableadmin) is enabled. ## Modules to Import @@ -16,7 +17,7 @@ import bundleManager from '@ohos.enterprise.bundleManager'; addAllowedInstallBundles(admin: Want, appIds: Array\, callback: AsyncCallback<void>): void; -Adds a list of bundles that are allowed to be installed by the administrator for an enterprise device administrator application. This API uses an asynchronous callback to return the result. +Adds a list of bundles that are allowed to be installed by the current administrator for an enterprise device administrator application. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.ENTERPRISE_SET_BUNDLE_INSTALL_POLICY @@ -38,8 +39,8 @@ For details about the error codes, see [Enterprise Device Management Error Codes | ID| Error Message | | ------- | ---------------------------------------------------------------------------- | -| 9200003 | the administrator ability component is invalid. | -| 9200007 | the system ability work abnormally. | +| 9200001 | the application is not an administrator of the device. | +| 9200002 | the administrator application does not have permission to manage the device. | **Example:** @@ -48,9 +49,9 @@ let wantTemp = { bundleName: "com.example.myapplication", abilityName: "EntryAbility", }; -let appIds = {"com.example.myapplication"}; +let appIds = ["com.example.myapplication"]; -bundleManager.AddAllowedInstallBundles(wantTemp, appIds, (error) => { +bundleManager.addAllowedInstallBundles(wantTemp, appIds, (error) => { if (error != null) { console.log("error code:" + error.code + " error message:" + error.message); } @@ -61,7 +62,7 @@ bundleManager.AddAllowedInstallBundles(wantTemp, appIds, (error) => { addAllowedInstallBundles(admin: Want, appIds: Array\, userId: number, callback: AsyncCallback<void>): void; -Adds a list of bundles that are allowed to be installed by the specified user for an enterprise device administrator application. This API uses an asynchronous callback to return the result. +Adds a list of bundles that are allowed to be installed by the given user (specified by **userId**) for an enterprise device administrator application. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.ENTERPRISE_SET_BUNDLE_INSTALL_POLICY @@ -84,8 +85,8 @@ For details about the error codes, see [Enterprise Device Management Error Codes | ID| Error Message | | ------- | ---------------------------------------------------------------------------- | -| 9200003 | the administrator ability component is invalid. | -| 9200007 | the system ability work abnormally. | +| 9200001 | the application is not an administrator of the device. | +| 9200002 | the administrator application does not have permission to manage the device. | **Example:** @@ -94,9 +95,9 @@ let wantTemp = { bundleName: "com.example.myapplication", abilityName: "EntryAbility", }; -let appIds = {"com.example.myapplication"}; +let appIds = ["com.example.myapplication"]; -bundleManager.AddAllowedInstallBundles(wantTemp, appIds, 100, (error) => { +bundleManager.addAllowedInstallBundles(wantTemp, appIds, 100, (error) => { if (error != null) { console.log("error code:" + error.code + " error message:" + error.message); } @@ -107,7 +108,7 @@ bundleManager.AddAllowedInstallBundles(wantTemp, appIds, 100, (error) => { addAllowedInstallBundles(admin: Want, appIds: Array\, userId?: number): Promise<void>; -Adds a list of bundles that are allowed to be installed by the administrator (if **userId** is not passed in) or the specified user (if **userId** is passed in) for an enterprise device administrator application. This API uses a promise to return the result. +Adds a list of bundles that are allowed to be installed by the current administrator (if **userId** is not passed in) or the given user (if **userId** is passed in) for an enterprise device administrator application. This API uses a promise to return the result. **Required permissions**: ohos.permission.ENTERPRISE_SET_BUNDLE_INSTALL_POLICY @@ -135,8 +136,8 @@ For details about the error codes, see [Enterprise Device Management Error Codes | ID| Error Message | | ------- | ---------------------------------------------------------------------------- | -| 9200003 | the administrator ability component is invalid. | -| 9200007 | the system ability work abnormally. | +| 9200001 | the application is not an administrator of the device. | +| 9200002 | the administrator application does not have permission to manage the device. | **Example:** @@ -145,7 +146,7 @@ let wantTemp = { bundleName: "com.example.myapplication", abilityName: "EntryAbility", }; -let appIds = {"com.example.myapplication"}; +let appIds = ["com.example.myapplication"]; bundleManager.addAllowedInstallBundles(wantTemp, appIds, 100).then(() => { console.log("success"); @@ -158,7 +159,7 @@ bundleManager.addAllowedInstallBundles(wantTemp, appIds, 100).then(() => { removeAllowedInstallBundles(admin: Want, appIds: Array\, callback: AsyncCallback<void>): void; -Removes a list of bundles that are allowed to be installed by the administrator for an enterprise device administrator application. The bundles removed from the list can no longer be installed. This API uses an asynchronous callback to return the result. +Removes a list of bundles that are allowed to be installed by the current administrator for an enterprise device administrator application. The bundles removed from the list can no longer be installed. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.ENTERPRISE_SET_BUNDLE_INSTALL_POLICY @@ -180,8 +181,8 @@ For details about the error codes, see [Enterprise Device Management Error Codes | ID| Error Message | | ------- | ---------------------------------------------------------------------------- | -| 9200003 | the administrator ability component is invalid. | -| 9200007 | the system ability work abnormally. | +| 9200001 | the application is not an administrator of the device. | +| 9200002 | the administrator application does not have permission to manage the device. | **Example:** @@ -190,7 +191,7 @@ let wantTemp = { bundleName: "com.example.myapplication", abilityName: "EntryAbility", }; -let appIds = {"com.example.myapplication"}; +let appIds = ["com.example.myapplication"]; bundleManager.removeAllowedInstallBundles(wantTemp, appIds, (error) => { if (error != null) { @@ -203,7 +204,7 @@ bundleManager.removeAllowedInstallBundles(wantTemp, appIds, (error) => { removeAllowedInstallBundles(admin: Want, appIds: Array\, userId: number, callback: AsyncCallback<void>): void; -Removes a list of bundles that are allowed to be installed by the specified user for an enterprise device administrator application. The bundles removed from the list can no longer be installed. This API uses an asynchronous callback to return the result. +Removes a list of bundles that are allowed to be installed by the given user (specified by **userId**) for an enterprise device administrator application. The bundles removed from the list can no longer be installed. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.ENTERPRISE_SET_BUNDLE_INSTALL_POLICY @@ -226,8 +227,8 @@ For details about the error codes, see [Enterprise Device Management Error Codes | ID| Error Message | | ------- | ---------------------------------------------------------------------------- | -| 9200003 | the administrator ability component is invalid. | -| 9200007 | the system ability work abnormally. | +| 9200001 | the application is not an administrator of the device. | +| 9200002 | the administrator application does not have permission to manage the device. | **Example:** @@ -236,7 +237,7 @@ let wantTemp = { bundleName: "com.example.myapplication", abilityName: "EntryAbility", }; -let appIds = {"com.example.myapplication"}; +let appIds = ["com.example.myapplication"]; bundleManager.removeAllowedInstallBundles(wantTemp, appIds, 100, (error) => { if (error != null) { @@ -249,7 +250,7 @@ bundleManager.removeAllowedInstallBundles(wantTemp, appIds, 100, (error) => { removeAllowedInstallBundles(admin: Want, appIds: Array\, userId?: number): Promise<void>; -Removes a list of bundles that are allowed to be installed by the administrator (if **userId** is not passed in) or the specified user (if **userId** is passed in) for an enterprise device administrator application. The bundles removed from the list can no longer be installed. This API uses a promise to return the result. +Removes a list of bundles that are allowed to be installed by the current administrator (if **userId** is not passed in) or the given user (if **userId** is passed in) for an enterprise device administrator application. The bundles removed from the list can no longer be installed. This API uses a promise to return the result. **Required permissions**: ohos.permission.ENTERPRISE_SET_BUNDLE_INSTALL_POLICY @@ -277,8 +278,8 @@ For details about the error codes, see [Enterprise Device Management Error Codes | ID| Error Message | | ------- | ---------------------------------------------------------------------------- | -| 9200003 | the administrator ability component is invalid. | -| 9200007 | the system ability work abnormally. | +| 9200001 | the application is not an administrator of the device. | +| 9200002 | the administrator application does not have permission to manage the device. | **Example:** @@ -287,7 +288,7 @@ let wantTemp = { bundleName: "com.example.myapplication", abilityName: "EntryAbility", }; -let appIds = {"com.example.myapplication"}; +let appIds = ["com.example.myapplication"]; bundleManager.removeAllowedInstallBundles(wantTemp, appIds, 100).then(() => { console.log("success"); @@ -300,7 +301,7 @@ bundleManager.removeAllowedInstallBundles(wantTemp, appIds, 100).then(() => { getAllowedInstallBundles(admin: Want, callback: AsyncCallback<Array<string>>): void; -Obtains the list of bundles that are allowed to be installed by the administrator for an enterprise device administrator application. This API uses an asynchronous callback to return the result. +Obtains the list of bundles that are allowed to be installed by the current administrator for an enterprise device administrator application. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.ENTERPRISE_SET_BUNDLE_INSTALL_POLICY @@ -321,8 +322,8 @@ For details about the error codes, see [Enterprise Device Management Error Codes | ID| Error Message | | ------- | ---------------------------------------------------------------------------- | -| 9200003 | the administrator ability component is invalid. | -| 9200007 | the system ability work abnormally. | +| 9200001 | the application is not an administrator of the device. | +| 9200002 | the administrator application does not have permission to manage the device. | **Example:** @@ -343,7 +344,7 @@ bundleManager.getAllowedInstallBundles(wantTemp, (error) => { getAllowedInstallBundles(admin: Want, userId: number, callback: AsyncCallback<Array<string>>): void; -Obtains the list of bundles that are allowed to be installed by the specified user for an enterprise device administrator application. This API uses an asynchronous callback to return the result. +Obtains the list of bundles that are allowed to be installed by the given user (specified by **userId**) for an enterprise device administrator application. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.ENTERPRISE_SET_BUNDLE_INSTALL_POLICY @@ -365,8 +366,8 @@ For details about the error codes, see [Enterprise Device Management Error Codes | ID| Error Message | | ------- | ---------------------------------------------------------------------------- | -| 9200003 | the administrator ability component is invalid. | -| 9200007 | the system ability work abnormally. | +| 9200001 | the application is not an administrator of the device. | +| 9200002 | the administrator application does not have permission to manage the device. | **Example:** @@ -387,7 +388,7 @@ bundleManager.getAllowedInstallBundles(wantTemp, 100, (error) => { getAllowedInstallBundles(admin: Want, userId?: number): Promise<Array<string>>; -Obtains the list of bundles that are allowed to be installed for an enterprise device administrator application. This API uses a promise to return the result. +Obtains the list of bundles that are allowed to be installed by the current administrator (if **userId** is not passed in) or the given user (if **userId** is passed in) for an enterprise device administrator application. This API uses a promise to return the result. **Required permissions**: ohos.permission.ENTERPRISE_SET_BUNDLE_INSTALL_POLICY @@ -414,8 +415,8 @@ For details about the error codes, see [Enterprise Device Management Error Codes | ID| Error Message | | ------- | ---------------------------------------------------------------------------- | -| 9200003 | the administrator ability component is invalid. | -| 9200007 | the system ability work abnormally. | +| 9200001 | the application is not an administrator of the device. | +| 9200002 | the administrator application does not have permission to manage the device. | **Example:** @@ -430,3 +431,421 @@ bundleManager.getAllowedInstallBundles(wantTemp, 100).then(() => { console.log("error code:" + error.code + " error message:" + error.message); }); ``` + +## bundleManager.addDisallowedInstallBundles + +addDisallowedInstallBundles(admin: Want, appIds: Array\, callback: AsyncCallback<void>): void; + +Adds a list of bundles that are not allowed to be installed by the current administrator for an enterprise device administrator application. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.ENTERPRISE_SET_BUNDLE_INSTALL_POLICY + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ------------------------------- | +| admin | [Want](js-apis-app-ability-want.md) | Yes | Target enterprise device administrator application. | +| appIds | Array<string> | Yes | Bundles to be added to the disallowed bundle list. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md). + +| ID| Error Message | +| ------- | ---------------------------------------------------------------------------- | +| 9200001 | the application is not an administrator of the device. | +| 9200002 | the administrator application does not have permission to manage the device. | + +**Example:** + +```js +let wantTemp = { + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", +}; +let appIds = ["com.example.myapplication"]; + +bundleManager.addDisallowedInstallBundles(wantTemp, appIds, (error) => { + if (error != null) { + console.log("error code:" + error.code + " error message:" + error.message); + } +}); +``` + +## bundleManager.addDisallowedInstallBundles + +addDisallowedInstallBundles(admin: Want, appIds: Array\, userId: number, callback: AsyncCallback<void>): void; + +Adds a list of bundles that are not allowed to be installed by the given user (specified by **userId**) for an enterprise device administrator application. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.ENTERPRISE_SET_BUNDLE_INSTALL_POLICY + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ----------------------------------- | ---- | ------- | +| admin | [Want](js-apis-app-ability-want.md) | Yes | Target enterprise device administrator application. | +| appIds | Array<string> | Yes | Bundles to be added to the disallowed bundle list. | +| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md). + +| ID| Error Message | +| ------- | ---------------------------------------------------------------------------- | +| 9200001 | the application is not an administrator of the device. | +| 9200002 | the administrator application does not have permission to manage the device. | + +**Example:** + +```js +let wantTemp = { + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", +}; +let appIds = ["com.example.myapplication"]; + +bundleManager.addDisallowedInstallBundles(wantTemp, appIds, 100, (error) => { + if (error != null) { + console.log("error code:" + error.code + " error message:" + error.message); + } +}); +``` + +## bundleManager.addDisallowedInstallBundles + +addDisallowedInstallBundles(admin: Want, appIds: Array\, userId?: number): Promise<void>; + +Adds a list of bundles that are not allowed to be installed by the current administrator (if **userId** is not passed in) or the given user (if **userId** is passed in) for an enterprise device administrator application. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.ENTERPRISE_SET_BUNDLE_INSTALL_POLICY + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ----------------------------------- | ---- | ------- | +| admin | [Want](js-apis-app-ability-want.md) | Yes | Target enterprise device administrator application. | +| appIds | Array<string> | Yes | Bundles to be added to the disallowed bundle list. | +| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0.| + +**Return value** + +| Type | Description | +| --------------------- | ------------------------- | +| Promise<void> | Promise that returns no value. If the operation fails, an error object is thrown. | + +**Error codes** + +For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md). + +| ID| Error Message | +| ------- | ---------------------------------------------------------------------------- | +| 9200001 | the application is not an administrator of the device. | +| 9200002 | the administrator application does not have permission to manage the device. | + +**Example:** + +```js +let wantTemp = { + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", +}; +let appIds = ["com.example.myapplication"]; + +bundleManager.addDisallowedInstallBundles(wantTemp, appIds, 100).then(() => { + console.log("success"); +}).catch(error => { + console.log("error code:" + error.code + " error message:" + error.message); +}); +``` + +## bundleManager.removeDisallowedInstallBundles + +removeDisallowedInstallBundles(admin: Want, appIds: Array\, callback: AsyncCallback<void>): void; + +Removes a list of bundles that are not allowed to be installed by the current administrator for an enterprise device administrator application. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.ENTERPRISE_SET_BUNDLE_INSTALL_POLICY + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ------------------------------- | +| admin | [Want](js-apis-app-ability-want.md) | Yes | Target enterprise device administrator application. | +| appIds | Array<string> | Yes | Bundles to be removed from the disallowed bundle list. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md). + +| ID| Error Message | +| ------- | ---------------------------------------------------------------------------- | +| 9200001 | the application is not an administrator of the device. | +| 9200002 | the administrator application does not have permission to manage the device. | + +**Example:** + +```js +let wantTemp = { + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", +}; +let appIds = ["com.example.myapplication"]; + +bundleManager.removeDisallowedInstallBundles(wantTemp, appIds, (error) => { + if (error != null) { + console.log("error code:" + error.code + " error message:" + error.message); + } +}); +``` + +## bundleManager.removeDisallowedInstallBundles + +removeAllowedInstallBundles(admin: Want, appIds: Array\, userId: number, callback: AsyncCallback<void>): void; + +Removes a list of bundles that are not allowed to be installed by the given user (specified by **userId**) for an enterprise device administrator application. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.ENTERPRISE_SET_BUNDLE_INSTALL_POLICY + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ----------------------------------- | ---- | ------- | +| admin | [Want](js-apis-app-ability-want.md) | Yes | Target enterprise device administrator application. | +| appIds | Array<string> | Yes | Bundles to be removed from the disallowed bundle list. | +| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md). + +| ID| Error Message | +| ------- | ---------------------------------------------------------------------------- | +| 9200001 | the application is not an administrator of the device. | +| 9200002 | the administrator application does not have permission to manage the device. | + +**Example:** + +```js +let wantTemp = { + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", +}; +let appIds = ["com.example.myapplication"]; + +bundleManager.removeDisallowedInstallBundles(wantTemp, appIds, 100, (error) => { + if (error != null) { + console.log("error code:" + error.code + " error message:" + error.message); + } +}); +``` + +## bundleManager.removeDisallowedInstallBundles + +removeDisallowedInstallBundles(admin: Want, appIds: Array\, userId?: number): Promise<void>; + +Removes a list of bundles that are not allowed to be installed by the current administrator (if **userId** is not passed in) or the given user (if **userId** is passed in) for an enterprise device administrator application. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.ENTERPRISE_SET_BUNDLE_INSTALL_POLICY + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ----------------------------------- | ---- | ------- | +| admin | [Want](js-apis-app-ability-want.md) | Yes | Target enterprise device administrator application. | +| appIds | Array\<string> | Yes | Bundles to be removed from the disallowed bundle list. | +| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0.| + +**Return value** + +| Type | Description | +| --------------------- | ------------------------- | +| Promise<void> | Promise that returns no value. If the operation fails, an error object is thrown. | + +**Error codes** + +For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md). + +| ID| Error Message | +| ------- | ---------------------------------------------------------------------------- | +| 9200001 | the application is not an administrator of the device. | +| 9200002 | the administrator application does not have permission to manage the device. | + +**Example:** + +```js +let wantTemp = { + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", +}; +let appIds = ["com.example.myapplication"]; + +bundleManager.removeDisallowedInstallBundles(wantTemp, appIds, 100).then(() => { + console.log("success"); +}).catch(error => { + console.log("error code:" + error.code + " error message:" + error.message); +}); +``` + +## bundleManager.getDisallowedInstallBundles + +getDisallowedInstallBundles(admin: Want, callback: AsyncCallback<Array<string>>): void; + +Obtains the list of bundles that are not allowed to be installed by the current administrator for an enterprise device administrator application. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.ENTERPRISE_SET_BUNDLE_INSTALL_POLICY + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ------------------------------- | +| admin | [Want](js-apis-app-ability-want.md) | Yes | Target enterprise device administrator application. | +| callback | AsyncCallback<Array<string>> | Yes | Callback used to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object. | + +**Error codes** + +For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md). + +| ID| Error Message | +| ------- | ---------------------------------------------------------------------------- | +| 9200001 | the application is not an administrator of the device. | +| 9200002 | the administrator application does not have permission to manage the device. | + +**Example:** + +```js +let wantTemp = { + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", +}; + +bundleManager.getDisallowedInstallBundles(wantTemp, (error) => { + if (error != null) { + console.log("error code:" + error.code + " error message:" + error.message); + } +}); +``` + +## bundleManager.getDisallowedInstallBundles + +getDisallowedInstallBundles(admin: Want, userId: number, callback: AsyncCallback<Array<string>>): void; + +Obtains the list of bundles that are not allowed to be installed by the given user (specified by **userId**) for an enterprise device administrator application. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.ENTERPRISE_SET_BUNDLE_INSTALL_POLICY + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ------------------------------- | +| admin | [Want](js-apis-app-ability-want.md) | Yes | Target enterprise device administrator application. | +| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0.| +| callback | AsyncCallback<Array<string>> | Yes | Callback used to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object. | + +**Error codes** + +For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md). + +| ID| Error Message | +| ------- | ---------------------------------------------------------------------------- | +| 9200001 | the application is not an administrator of the device. | +| 9200002 | the administrator application does not have permission to manage the device. | + +**Example:** + +```js +let wantTemp = { + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", +}; + +bundleManager.getDisallowedInstallBundles(wantTemp, 100, (error) => { + if (error != null) { + console.log("error code:" + error.code + " error message:" + error.message); + } +}); +``` + +## bundleManager.getDisallowedInstallBundles + +getDisallowedInstallBundles(admin: Want, userId?: number): Promise<Array<string>>; + +Obtains the list of bundles that are not allowed to be installed by the current administrator (if **userId** is not passed in) or the given user (if **userId** is passed in) for an enterprise device administrator application. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.ENTERPRISE_SET_BUNDLE_INSTALL_POLICY + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ----------------------------------- | ---- | ------- | +| admin | [Want](js-apis-app-ability-want.md) | Yes | Target enterprise device administrator application.| +| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0.| + +**Return value** + +| Type | Description | +| --------------------- | ------------------------- | +| Promise<Array<string>> | Promise used to return the allowed bundle list.| + +**Error codes** + +For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md). + +| ID| Error Message | +| ------- | ---------------------------------------------------------------------------- | +| 9200001 | the application is not an administrator of the device. | +| 9200002 | the administrator application does not have permission to manage the device. | + +**Example:** + +```js +let wantTemp = { + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", +}; +bundleManager.getDisallowedInstallBundles(wantTemp, 100).then(() => { + console.log("success"); +}).catch(error => { + console.log("error code:" + error.code + " error message:" + error.message); +}); diff --git a/en/application-dev/reference/apis/js-apis-inner-ability-abilityResult.md b/en/application-dev/reference/apis/js-apis-inner-ability-abilityResult.md index 13573de144bf718175bf6690408f7f52c388a8fc..6723f4116a43b6aee237e07c0db6984ed91278a6 100644 --- a/en/application-dev/reference/apis/js-apis-inner-ability-abilityResult.md +++ b/en/application-dev/reference/apis/js-apis-inner-ability-abilityResult.md @@ -1,14 +1,20 @@ # AbilityResult -The **AbilityResult** module defines the result code and data returned when an ability is terminated after being started. You can use [startAbilityForResult](js-apis-ability-featureAbility.md#featureabilitystartabilityforresult7) to obtain the **AbilityResult** object returned after the started ability is terminated. The startedability returns the **AbilityResult** object by calling [terminateSelfWithResult](js-apis-ability-featureAbility.md#featureabilityterminateselfwithresult7). +The **AbilityResult** module defines the result code and data returned when an ability is terminated after being started. You can use [startAbilityForResult](js-apis-ability-featureAbility.md#featureabilitystartabilityforresult7) to obtain the **AbilityResult** object returned after the started ability is terminated. The started ability returns the **AbilityResult** object by calling [terminateSelfWithResult](js-apis-ability-featureAbility.md#featureabilityterminateselfwithresult7). > **NOTE** > > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +## Modules to Import + +```ts +import ability from '@ohos.ability.ability'; +``` + **System capability**: SystemCapability.Ability.AbilityBase | Name | Readable | Writable | Type | Mandatory| Description | | ----------- | -------- |-------- | -------------------- | ---- | ------------------------------------------------------------ | -| resultCode | Yes | Yes | number | Yes | Result code returned after the started ability is terminated. | -| want | Yes | Yes | [Want](./js-apis-app-ability-want.md) | No | Data returned after the started ability is terminated. | +| resultCode | Yes | Yes | number | Yes | Result code returned after the started ability is terminated. | +| want | Yes | Yes | [Want](./js-apis-app-ability-want.md) | No | Data returned after the started ability is terminated.| diff --git a/en/application-dev/reference/apis/js-apis-inner-ability-connectOptions.md b/en/application-dev/reference/apis/js-apis-inner-ability-connectOptions.md index d311a6c175a5bea86be8635cf032839552b998f9..edfc9b732c956deed3257032d9983eab3d86a095 100644 --- a/en/application-dev/reference/apis/js-apis-inner-ability-connectOptions.md +++ b/en/application-dev/reference/apis/js-apis-inner-ability-connectOptions.md @@ -2,6 +2,16 @@ **ConnectOptions** can be used as an input parameter to receive status changes during the connection to a background service. For example, it is used as an input parameter of [connectServiceExtensionAbility](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextconnectserviceextensionability) to connect to a ServiceExtensionAbility. +> **NOTE** +> +> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```ts +import common from '@ohos.app.ability.common'; +``` + **System capability**: SystemCapability.Ability.AbilityRuntime.Core | Name | Type | Mandatory | Description | @@ -18,7 +28,7 @@ abilityName: 'MyAbility' }; - let connectOptions = { + let connectOptions: common.ConnectOptions = { onConnect(elementName, remote) { console.log('onConnect elementName: ${elementName}'); }, diff --git a/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityOperation.md b/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityOperation.md index 48be29362cfae78060f98aa2440a442e89ea2715..1037dfe2d682cd0cf579d457ee3f8f642b048fdc 100644 --- a/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityOperation.md +++ b/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityOperation.md @@ -7,6 +7,12 @@ The **DataAbilityOperation** module defines the operation on DataAbilities. It c > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs of this module can be used only in the FA model. +## Modules to Import + +```ts +import ability from '@ohos.ability.ability'; +``` + **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel | Name | Template | Mandatory| Description | diff --git a/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityResult.md b/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityResult.md index 6dffdaefc00b58a14fce5820b969866b3c564a0b..2a3cb7f384319fdc99f72e52e6e952eff951f7bb 100644 --- a/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityResult.md +++ b/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityResult.md @@ -7,6 +7,12 @@ The **DataAbilityResult** module defines the operation result on DataAbilities. > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs of this module can be used only in the FA model. +## Modules to Import + +```ts +import ability from '@ohos.ability.ability'; +``` + **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel | Name | Type | Mandatory | Description | @@ -22,7 +28,7 @@ import featureAbility from '@ohos.ability.featureAbility'; // Perform database operations in batches. function executeBatchOperation() { let dataAbilityUri = ('dataability:///com.example.myapplication.TestDataAbility'); - let DAHelper; + let DAHelper: ability.DataAbilityHelper; try { DAHelper = featureAbility.acquireDataAbilityHelper(dataAbilityUri); if (DAHelper === null) { @@ -61,7 +67,7 @@ function executeBatchOperation() { try { DAHelper.executeBatch(dataAbilityUri, operations).then((data) => { for (let i = 0; i < data.length; i++) { - let dataAbilityResult = data[i]; + let dataAbilityResult: ability.DataAbilityResult = data[i]; console.log('dataAbilityResult.uri: ${dataAbilityResult.uri}'); console.log('dataAbilityResult.count: ${dataAbilityResult.count}'); } diff --git a/en/application-dev/reference/apis/js-apis-inner-ability-startAbilityParameter.md b/en/application-dev/reference/apis/js-apis-inner-ability-startAbilityParameter.md index 80fcf902d83b94b26cd7f667d971855d4be959b9..44903a992f5a319f13049ffe682962214ebfd7be 100644 --- a/en/application-dev/reference/apis/js-apis-inner-ability-startAbilityParameter.md +++ b/en/application-dev/reference/apis/js-apis-inner-ability-startAbilityParameter.md @@ -7,6 +7,12 @@ The **StartAbilityParameter** module defines the parameters for starting an abil > The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs of this module can be used only in the FA model. +## Modules to Import + +```ts +import ability from '@ohos.ability.ability'; +``` + **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel | Name | Type | Mandatory | Description | @@ -30,7 +36,7 @@ let abilityStartSetting ={ [featureAbility.AbilityStartSetting.DISPLAY_ID_KEY] : 1, }; -let startAbilityParameter = { +let startAbilityParameter: ability.StartAbilityParameter = { want : Want, abilityStartSetting : abilityStartSetting }; diff --git a/en/application-dev/reference/apis/js-apis-inner-ability-want.md b/en/application-dev/reference/apis/js-apis-inner-ability-want.md index 0eebe1059e031d66c7353b26ea8812b0c48e04a6..f8823b905ffe42199ec68fb57b052bd0af65e08e 100644 --- a/en/application-dev/reference/apis/js-apis-inner-ability-want.md +++ b/en/application-dev/reference/apis/js-apis-inner-ability-want.md @@ -6,6 +6,12 @@ Want is a carrier for information transfer between objects (application componen > > The APIs of this module are supported since API version 6 and deprecated since API version 9. You are advised to use [@ohos.app.ability.Want](js-apis-app-ability-want.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. +## Modules to Import + +```ts +import Want from '@ohos.app.ability.Want'; +``` + **System capability**: SystemCapability.Ability.AbilityBase | Name | Type | Mandatory| Description | @@ -17,7 +23,7 @@ Want is a carrier for information transfer between objects (application componen | type | string | No | MIME type, that is, the type of the file to open, for example, **'text/xml'** and **'image/*'**. For details about the MIME type definition, see https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com. | | flags | number | No | How the **Want** object will be handled. By default, numbers are passed in. For details, see [flags](js-apis-ability-wantConstant.md#wantconstantflags).| | action | string | No | Action to take, such as viewing and sharing application details. In implicit Want, you can define this field and use it together with **uri** or **parameters** to specify the operation to be performed on the data. For details, see [action](js-apis-ability-wantConstant.md#wantconstantaction). For details about the definition and matching rules of implicit Want, see [Matching Rules of Explicit Want and Implicit Want](../../application-models/explicit-implicit-want-mappings.md). | -| parameters | {[key: string]: Object} | No | Want parameters in the form of custom key-value (KV) pairs. By default, the following keys are carried:
- **ohos.aafwk.callerPid**: PID of the caller.
- **ohos.aafwk.param.callerToken**: token of the caller.
**ohos.aafwk.param.callerUid**: UID in [bundleInfo](js-apis-bundle-BundleInfo.md#bundleinfo), that is, the application UID in the bundle information.
- **component.startup.newRules**: whether to enable the new control rule.
- **moduleName**: module name of the caller. No matter what this field is set to, the correct module name will be sent to the peer.
- **ohos.dlp.params.sandbox**: available only for DLP files. | +| parameters | {[key: string]: Object} | No | Want parameters in the form of custom key-value (KV) pairs. By default, the following keys are carried:
- **ohos.aafwk.callerPid**: PID of the caller.
- **ohos.aafwk.param.callerToken**: token of the caller.
- **ohos.aafwk.param.callerUid**: UID in [bundleInfo](js-apis-bundle-BundleInfo.md#bundleinfo), that is, the application UID in the bundle information.
- **component.startup.newRules**: whether to enable the new control rule.
- **moduleName**: module name of the caller. No matter what this field is set to, the correct module name will be sent to the peer.
- **ohos.dlp.params.sandbox**: available only for DLP files. | | entities | Array\ | No | Additional category information (such as browser and video player) of the target ability. It is a supplement to **action** in implicit Want and is used to filter ability types. For details, see [entity](js-apis-app-ability-wantConstant.md#wantconstantentity). | | moduleName9+ | string | No | Module to which the ability belongs.| @@ -68,5 +74,4 @@ Want is a carrier for information transfer between objects (application componen - For more details and examples, see [Want](../../application-models/want-overview.md). - - + diff --git a/en/application-dev/reference/apis/js-apis-inner-app-appVersionInfo.md b/en/application-dev/reference/apis/js-apis-inner-app-appVersionInfo.md index 39c846bb6e96a2e8db53b71c6685e3e1ce3a4579..f5da165225786f606479e470a72b7ae99d894b72 100644 --- a/en/application-dev/reference/apis/js-apis-inner-app-appVersionInfo.md +++ b/en/application-dev/reference/apis/js-apis-inner-app-appVersionInfo.md @@ -6,6 +6,12 @@ The **AppVersionInfo** module defines the application version information. You c > > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +## Modules to Import + +```ts +import featureAbility from '@ohos.ability.featureAbility'; +``` + **System capability**: SystemCapability.Ability.AbilityRuntime.Core | Name | Type | Readable| Writable| Description | diff --git a/en/application-dev/reference/apis/js-apis-inner-app-context.md b/en/application-dev/reference/apis/js-apis-inner-app-context.md index 79fcf1af73e773ca24167bef9f2aa4052d5293a2..fede557dd4f36f6b03c5cca1fc13f1d59e7fcaf8 100644 --- a/en/application-dev/reference/apis/js-apis-inner-app-context.md +++ b/en/application-dev/reference/apis/js-apis-inner-app-context.md @@ -8,13 +8,19 @@ The **Context** module provides context for abilities or applications. It allows > > The APIs of this module can be used only in the FA model. +## Modules to Import + +```ts +import featureAbility from '@ohos.ability.featureAbility'; +``` + ## Usage The **Context** object is created in a **featureAbility** and returned through its [getContext](js-apis-ability-featureAbility.md#featureabilitygetcontext) API. Therefore, you must import the **@ohos.ability.featureAbility** package before using the **Context** module. An example is as follows: ```ts import featureAbility from '@ohos.ability.featureAbility'; -let context = featureAbility.getContext(); +let context: featureAbility.Context = featureAbility.getContext(); context.getOrCreateLocalDir().then((data) => { console.info('getOrCreateLocalDir data: ${JSON.stringify(data)}'); }); @@ -40,7 +46,7 @@ If this API is called for the first time, a root directory will be created. ```ts import featureAbility from '@ohos.ability.featureAbility'; -let context = featureAbility.getContext(); +let context: featureAbility.Context = featureAbility.getContext(); context.getOrCreateLocalDir((error, data)=>{ if (error && error.code !== 0) { console.error('getOrCreateLocalDir fail, error: ${JSON.stringify(error)}'); @@ -72,7 +78,7 @@ If this API is called for the first time, a root directory will be created. ```ts import featureAbility from '@ohos.ability.featureAbility'; -let context = featureAbility.getContext(); +let context: featureAbility.Context = featureAbility.getContext(); context.getOrCreateLocalDir().then((data) => { console.info('getOrCreateLocalDir data: ${JSON.stringify(data)}'); }); @@ -99,7 +105,7 @@ Verifies whether a specific PID and UID have the given permission. This API uses ```ts import featureAbility from '@ohos.ability.featureAbility'; import bundle from '@ohos.bundle.bundleManager'; -let context = featureAbility.getContext(); +let context: featureAbility.Context = featureAbility.getContext(); bundle.getBundleInfo('com.context.test', 1, (err, datainfo) =>{ context.verifyPermission('com.example.permission', {uid:datainfo.appInfo.uid}, (error, data) =>{ if (error && error.code !== 0) { @@ -133,7 +139,7 @@ Verifies whether the current PID and UID have the given permission. This API use ```ts import featureAbility from '@ohos.ability.featureAbility'; -let context = featureAbility.getContext(); +let context: featureAbility.Context = featureAbility.getContext(); context.verifyPermission('com.example.permission', (error, data) =>{ if (error && error.code !== 0) { console.error('verifyPermission fail, error: ${JSON.stringify(error)}'); @@ -168,7 +174,7 @@ Verifies whether a specific PID and UID have the given permission. This API uses ```ts import featureAbility from '@ohos.ability.featureAbility'; -let context = featureAbility.getContext(); +let context: featureAbility.Context = featureAbility.getContext(); let Permission = {pid:1}; context.verifyPermission('com.context.permission',Permission).then((data) => { console.info('verifyPermission data: ${JSON.stringify(data)}'); @@ -197,7 +203,7 @@ Requests certain permissions from the system. This API uses an asynchronous call ```ts import featureAbility from '@ohos.ability.featureAbility'; -let context = featureAbility.getContext(); +let context: featureAbility.Context = featureAbility.getContext(); context.requestPermissionsFromUser( ['com.example.permission1', 'com.example.permission2', @@ -241,7 +247,7 @@ Requests certain permissions from the system. This API uses a promise to return ```ts import featureAbility from '@ohos.ability.featureAbility'; -let context = featureAbility.getContext(); +let context: featureAbility.Context = featureAbility.getContext(); context.requestPermissionsFromUser( ['com.example.permission1', 'com.example.permission2', @@ -274,7 +280,7 @@ Obtains information about the current application. This API uses an asynchronous ```ts import featureAbility from '@ohos.ability.featureAbility'; -let context = featureAbility.getContext(); +let context: featureAbility.Context = featureAbility.getContext(); context.getApplicationInfo((error, data) => { if (error && error.code !== 0) { console.error('getApplicationInfo fail, error: ${JSON.stringify(error)}'); @@ -304,7 +310,7 @@ Obtains information about the current application. This API uses a promise to re ```ts import featureAbility from '@ohos.ability.featureAbility'; -let context = featureAbility.getContext(); +let context: featureAbility.Context = featureAbility.getContext(); context.getApplicationInfo().then((data) => { console.info('getApplicationInfo data: ${JSON.stringify(data)}'); }); @@ -330,7 +336,7 @@ Obtains the bundle name of this ability. This API uses an asynchronous callback ```ts import featureAbility from '@ohos.ability.featureAbility'; -let context = featureAbility.getContext(); +let context: featureAbility.Context = featureAbility.getContext(); context.getBundleName((error, data) => { if (error && error.code !== 0) { console.error('getBundleName fail, error: ${JSON.stringify(error)}'); @@ -360,7 +366,7 @@ Obtains the bundle name of this ability. This API uses a promise to return the r ```ts import featureAbility from '@ohos.ability.featureAbility'; -let context = featureAbility.getContext(); +let context: featureAbility.Context = featureAbility.getContext(); context.getBundleName().then((data) => { console.info('getBundleName data: ${JSON.stringify(data)}'); }); @@ -384,7 +390,7 @@ Obtains the display orientation of this ability. This API uses an asynchronous c ```ts import featureAbility from '@ohos.ability.featureAbility'; -let context = featureAbility.getContext(); +let context: featureAbility.Context = featureAbility.getContext(); context.getDisplayOrientation((error, data) => { if (error && error.code !== 0) { console.error('getDisplayOrientation fail, error: ${JSON.stringify(error)}'); @@ -412,7 +418,7 @@ Obtains the display orientation of this ability. This API uses a promise to retu ```ts import featureAbility from '@ohos.ability.featureAbility'; -let context = featureAbility.getContext(); +let context: featureAbility.Context = featureAbility.getContext(); context.getDisplayOrientation().then((data) => { console.info('getDisplayOrientation data: ${JSON.stringify(data)}'); }); @@ -436,7 +442,7 @@ Obtains the external cache directory of the application. This API uses an asynch ```ts import featureAbility from '@ohos.ability.featureAbility'; -let context = featureAbility.getContext(); +let context: featureAbility.Context = featureAbility.getContext(); context.getExternalCacheDir((error, data) => { if (error && error.code !== 0) { console.error('getExternalCacheDir fail, error: ${JSON.stringify(error)}'); @@ -464,7 +470,7 @@ Obtains the external cache directory of the application. This API uses a promise ```ts import featureAbility from '@ohos.ability.featureAbility'; -let context = featureAbility.getContext(); +let context: featureAbility.Context = featureAbility.getContext(); context.getExternalCacheDir().then((data) => { console.info('getExternalCacheDir data: ${JSON.stringify(data)}'); }); @@ -490,7 +496,7 @@ Sets the display orientation for this ability. This API uses an asynchronous cal ```ts import featureAbility from '@ohos.ability.featureAbility'; import bundle from '@ohos.bundle'; -let context = featureAbility.getContext(); +let context: featureAbility.Context = featureAbility.getContext(); let orientation = bundle.DisplayOrientation.UNSPECIFIED; context.setDisplayOrientation(orientation, (error) => { console.error('setDisplayOrientation fail, error: ${JSON.stringify(error)}'); @@ -517,18 +523,19 @@ Sets the display orientation for this ability. This API uses a promise to return ```ts import featureAbility from '@ohos.ability.featureAbility'; import bundle from '@ohos.bundle'; -let context = featureAbility.getContext(); +let context: featureAbility.Context = featureAbility.getContext(); let orientation = bundle.DisplayOrientation.UNSPECIFIED; context.setDisplayOrientation(orientation).then((data) => { console.info('setDisplayOrientation data: ${JSON.stringify(data)}'); }); ``` -## Context.setShowOnLockScreen7+ +## Context.setShowOnLockScreen(deprecated) setShowOnLockScreen(show: boolean, callback: AsyncCallback\): void Sets whether to show this feature at the top of the lock screen so that the feature remains activated. This API uses an asynchronous callback to return the result. +> This API is deprecated since API version 9. You are advised to use [window.setShowOnLockScreen](js-apis-window.md#setShowOnLockScreen9). **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -543,18 +550,19 @@ Sets whether to show this feature at the top of the lock screen so that the feat ```ts import featureAbility from '@ohos.ability.featureAbility'; -let context = featureAbility.getContext(); +let context: featureAbility.Context = featureAbility.getContext(); let show = true; context.setShowOnLockScreen(show, (error) => { console.error('setShowOnLockScreen fail, error: ${JSON.stringify(error)}'); }); ``` -## Context.setShowOnLockScreen7+ +## Context.setShowOnLockScreen(deprecated) setShowOnLockScreen(show: boolean): Promise\; Sets whether to show this feature at the top of the lock screen so that the feature remains activated. This API uses a promise to return the result. +> This API is deprecated since API version 9. You are advised to use [window.setShowOnLockScreen](js-apis-window.md#setShowOnLockScreen9). **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -574,7 +582,7 @@ Sets whether to show this feature at the top of the lock screen so that the feat ```ts import featureAbility from '@ohos.ability.featureAbility'; -let context = featureAbility.getContext(); +let context: featureAbility.Context = featureAbility.getContext(); let show = true; context.setShowOnLockScreen(show).then((data) => { console.info('setShowOnLockScreen data: ${JSON.stringify(data)}'); @@ -600,7 +608,7 @@ Sets whether to wake up the screen when this feature is restored. This API uses ```ts import featureAbility from '@ohos.ability.featureAbility'; -let context = featureAbility.getContext(); +let context: featureAbility.Context = featureAbility.getContext(); let wakeUp = true; context.setWakeUpScreen(wakeUp, (error) => { console.error('setWakeUpScreen fail, error: ${JSON.stringify(error)}'); @@ -609,7 +617,7 @@ context.setWakeUpScreen(wakeUp, (error) => { ## Context.setWakeUpScreen7+ -setWakeUpScreen(wakeUp: boolean): Promise\; +setWakeUpScreen(wakeUp: boolean): Promise\; Sets whether to wake up the screen when this feature is restored. This API uses a promise to return the result. @@ -631,7 +639,7 @@ Sets whether to wake up the screen when this feature is restored. This API uses ```ts import featureAbility from '@ohos.ability.featureAbility'; -let context = featureAbility.getContext(); +let context: featureAbility.Context = featureAbility.getContext(); let wakeUp = true; context.setWakeUpScreen(wakeUp).then((data) => { console.info('setWakeUpScreen data: ${JSON.stringify(data)}'); @@ -659,7 +667,7 @@ Obtains information about the current process, including the PID and process nam ```ts import featureAbility from '@ohos.ability.featureAbility'; -let context = featureAbility.getContext(); +let context: featureAbility.Context = featureAbility.getContext(); context.getProcessInfo((error, data) => { if (error && error.code !== 0) { console.error('getProcessInfo fail, error: ${JSON.stringify(error)}'); @@ -689,7 +697,7 @@ Obtains information about the current process, including the PID and process nam ```ts import featureAbility from '@ohos.ability.featureAbility'; -let context = featureAbility.getContext(); +let context: featureAbility.Context = featureAbility.getContext(); context.getProcessInfo().then((data) => { console.info('getProcessInfo data: ${JSON.stringify(data)}'); }); @@ -717,7 +725,7 @@ This API is available only to Page abilities. ```ts import featureAbility from '@ohos.ability.featureAbility'; -let context = featureAbility.getContext(); +let context: featureAbility.Context = featureAbility.getContext(); context.getElementName((error, data) => { if (error && error.code !== 0) { console.error('getElementName fail, error: ${JSON.stringify(error)}'); @@ -749,7 +757,7 @@ This API is available only to Page abilities. ```ts import featureAbility from '@ohos.ability.featureAbility'; -let context = featureAbility.getContext(); +let context: featureAbility.Context = featureAbility.getContext(); context.getElementName().then((data) => { console.info('getElementName data: ${JSON.stringify(data)}'); }); @@ -773,7 +781,7 @@ Obtains the name of the current process. This API uses an asynchronous callback ```ts import featureAbility from '@ohos.ability.featureAbility'; -let context = featureAbility.getContext(); +let context: featureAbility.Context = featureAbility.getContext(); context.getProcessName((error, data) => { if (error && error.code !== 0) { console.error('getProcessName fail, error: ${JSON.stringify(error)}'); @@ -803,7 +811,7 @@ Obtains the name of the current process. This API uses a promise to return the r ```ts import featureAbility from '@ohos.ability.featureAbility'; -let context = featureAbility.getContext(); +let context: featureAbility.Context = featureAbility.getContext(); context.getProcessName().then((data) => { console.info('getProcessName data: ${JSON.stringify(data)}'); }); @@ -829,7 +837,7 @@ Obtains the bundle name of the caller ability. This API uses an asynchronous cal ```ts import featureAbility from '@ohos.ability.featureAbility'; -let context = featureAbility.getContext(); +let context: featureAbility.Context = featureAbility.getContext(); context.getCallingBundle((error, data) => { if (error && error.code !== 0) { console.error('getCallingBundle fail, error: ${JSON.stringify(error)}'); @@ -859,7 +867,7 @@ Obtains the bundle name of the caller ability. This API uses a promise to return ```ts import featureAbility from '@ohos.ability.featureAbility'; -let context = featureAbility.getContext(); +let context: featureAbility.Context = featureAbility.getContext(); context.getCallingBundle().then((data) => { console.info('getCallingBundle data: ${JSON.stringify(data)}'); }); @@ -883,7 +891,7 @@ Obtains the cache directory of the application in the internal storage. This API ```ts import featureAbility from '@ohos.ability.featureAbility'; -let context = featureAbility.getContext(); +let context: featureAbility.Context = featureAbility.getContext(); context.getCacheDir((error, data) => { if (error && error.code !== 0) { console.error('getCacheDir fail, error: ${JSON.stringify(error)}'); @@ -911,7 +919,7 @@ Obtains the cache directory of the application in the internal storage. This API ```ts import featureAbility from '@ohos.ability.featureAbility'; -let context = featureAbility.getContext(); +let context: featureAbility.Context = featureAbility.getContext(); context.getCacheDir().then((data) => { console.info('getCacheDir data: ${JSON.stringify(data)}'); }); @@ -935,7 +943,7 @@ Obtains the file directory of the application in the internal storage. This API ```ts import featureAbility from '@ohos.ability.featureAbility'; -let context = featureAbility.getContext(); +let context: featureAbility.Context = featureAbility.getContext(); context.getFilesDir((error, data) => { if (error && error.code !== 0) { console.error('getFilesDir fail, error: ${JSON.stringify(error)}'); @@ -963,7 +971,7 @@ Obtains the file directory of the application in the internal storage. This API ```ts import featureAbility from '@ohos.ability.featureAbility'; -let context = featureAbility.getContext(); +let context: featureAbility.Context = featureAbility.getContext(); context.getFilesDir().then((data) => { console.info('getFilesDir data: ${JSON.stringify(data)}'); }); @@ -989,7 +997,7 @@ If the distributed file path does not exist, the system will create one and retu ```ts import featureAbility from '@ohos.ability.featureAbility'; -let context = featureAbility.getContext(); +let context: featureAbility.Context = featureAbility.getContext(); context.getOrCreateDistributedDir((error, data) => { if (error && error.code !== 0) { console.error('getOrCreateDistributedDir fail, error: ${JSON.stringify(error)}'); @@ -1019,7 +1027,7 @@ If the distributed file path does not exist, the system will create one and retu ```ts import featureAbility from '@ohos.ability.featureAbility'; -let context = featureAbility.getContext(); +let context: featureAbility.Context = featureAbility.getContext(); context.getOrCreateDistributedDir().then((data) => { console.info('getOrCreateDistributedDir data: ${JSON.stringify(data)}'); }); @@ -1043,7 +1051,7 @@ Obtains the application type. This API uses an asynchronous callback to return t ```ts import featureAbility from '@ohos.ability.featureAbility'; -let context = featureAbility.getContext(); +let context: featureAbility.Context = featureAbility.getContext(); context.getAppType((error, data) => { if (error && error.code !== 0) { console.error('getAppType fail, error: ${JSON.stringify(error)}'); @@ -1071,7 +1079,7 @@ Obtains the application type. This API uses a promise to return the result. ```ts import featureAbility from '@ohos.ability.featureAbility'; -let context = featureAbility.getContext(); +let context: featureAbility.Context = featureAbility.getContext(); context.getAppType().then((data) => { console.info('getAppType data: ${JSON.stringify(data)}'); }); @@ -1095,7 +1103,7 @@ Obtains the **ModuleInfo** object of the application. This API uses an asynchron ```ts import featureAbility from '@ohos.ability.featureAbility'; -let context = featureAbility.getContext(); +let context: featureAbility.Context = featureAbility.getContext(); context.getHapModuleInfo((error, data) => { if (error && error.code !== 0) { console.error('getHapModuleInfo fail, error: ${JSON.stringify(error)}'); @@ -1123,7 +1131,7 @@ Obtains the **ModuleInfo** object of the application. This API uses a promise to ```ts import featureAbility from '@ohos.ability.featureAbility'; -let context = featureAbility.getContext(); +let context: featureAbility.Context = featureAbility.getContext(); context.getHapModuleInfo().then((data) => { console.info('getHapModuleInfo data: ${JSON.stringify(data)}'); }); @@ -1147,7 +1155,7 @@ Obtains the version information of the application. This API uses an asynchronou ```ts import featureAbility from '@ohos.ability.featureAbility'; -let context = featureAbility.getContext(); +let context: featureAbility.Context = featureAbility.getContext(); context.getAppVersionInfo((error, data) => { if (error && error.code !== 0) { console.error('getAppVersionInfo fail, error: ${JSON.stringify(error)}'); @@ -1175,7 +1183,7 @@ Obtains the version information of the application. This API uses a promise to r ```ts import featureAbility from '@ohos.ability.featureAbility'; -let context = featureAbility.getContext(); +let context: featureAbility.Context = featureAbility.getContext(); context.getAppVersionInfo().then((data) => { console.info('getAppVersionInfo data: ${JSON.stringify(data)}'); }); @@ -1199,7 +1207,7 @@ Obtains information about this ability. This API uses an asynchronous callback t ```ts import featureAbility from '@ohos.ability.featureAbility'; -let context = featureAbility.getContext(); +let context: featureAbility.Context = featureAbility.getContext(); context.getAbilityInfo((error, data) => { if (error && error.code !== 0) { console.error('getAbilityInfo fail, error: ${JSON.stringify(error)}'); @@ -1227,7 +1235,7 @@ Obtains information about this ability. This API uses a promise to return the re ```ts import featureAbility from '@ohos.ability.featureAbility'; -let context = featureAbility.getContext(); +let context: featureAbility.Context = featureAbility.getContext(); context.getAbilityInfo().then((data) => { console.info('getAbilityInfo data: ${JSON.stringify(data)}'); }); @@ -1251,7 +1259,7 @@ Obtains the context of the application. ```ts import featureAbility from '@ohos.ability.featureAbility'; -let context = featureAbility.getContext().getApplicationContext(); +let context: featureAbility.Context = featureAbility.getContext().getApplicationContext(); ``` ## Context.isUpdatingConfigurations7+ @@ -1272,7 +1280,7 @@ Checks whether the configuration of this ability is being updated. This API uses ```ts import featureAbility from '@ohos.ability.featureAbility'; -let context = featureAbility.getContext(); +let context: featureAbility.Context = featureAbility.getContext(); context.isUpdatingConfigurations((error, data) => { if (error && error.code !== 0) { console.error('isUpdatingConfigurations fail, error: ${JSON.stringify(error)}'); @@ -1300,7 +1308,7 @@ Checks whether the configuration of this ability is being updated. This API uses ```ts import featureAbility from '@ohos.ability.featureAbility'; -let context = featureAbility.getContext(); +let context: featureAbility.Context = featureAbility.getContext(); context.isUpdatingConfigurations().then((data) => { console.info('isUpdatingConfigurations data: ${JSON.stringify(data)}'); }); @@ -1324,7 +1332,7 @@ Notifies the system of the time required to draw this page function. This API us ```ts import featureAbility from '@ohos.ability.featureAbility'; -let context = featureAbility.getContext(); +let context: featureAbility.Context = featureAbility.getContext(); context.printDrawnCompleted((err) => { console.error('printDrawnCompleted err: ${JSON.stringify(err)}'); }); @@ -1348,7 +1356,7 @@ Notifies the system of the time required to draw this page function. This API us ```ts import featureAbility from '@ohos.ability.featureAbility'; -let context = featureAbility.getContext(); +let context: featureAbility.Context = featureAbility.getContext(); context.printDrawnCompleted().then((data) => { console.info('printDrawnCompleted data: ${JSON.stringify(data)}'); }); diff --git a/en/application-dev/reference/apis/js-apis-inner-app-processInfo.md b/en/application-dev/reference/apis/js-apis-inner-app-processInfo.md index 886cc755ef0939723d9c23bc612fe37ce0f7bc55..6bc1f2037c669246c759e7a54b7c92739391c1b3 100644 --- a/en/application-dev/reference/apis/js-apis-inner-app-processInfo.md +++ b/en/application-dev/reference/apis/js-apis-inner-app-processInfo.md @@ -6,6 +6,12 @@ The **ProcessInfo** module defines process information. You can use [getProcessI > > The initial APIs of this module are supported since API version 7. The APIs of this module can be used only in the FA model. Newly added APIs will be marked with a superscript to indicate their earliest API version. +## Modules to Import + +```ts +import featureAbility from '@ohos.ability.featureAbility'; +``` + **System capability**: SystemCapability.Ability.AbilityRuntime.Core | Name| Type| Readable| Writable| Description| diff --git a/en/application-dev/reference/apis/js-apis-inner-application-abilityDelegatorArgs.md b/en/application-dev/reference/apis/js-apis-inner-application-abilityDelegatorArgs.md index b6c5bc7be8e686a99baf3211f06f12bb48818c9a..ef67bdbbda3fa866d75305c18c310dbc810ca35f 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-abilityDelegatorArgs.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-abilityDelegatorArgs.md @@ -6,6 +6,12 @@ The **AbilityDelegatorArgs** module provides APIs to obtain an **AbilityDelegato > > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +## Modules to Import + +```ts +import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; +``` + ## Usage An **AbilityDelegatorArgs** object is obtained by calling [getArguments](js-apis-app-ability-abilityDelegatorRegistry.md#abilitydelegatorregistrygetarguments) in **AbilityDelegatorRegistry**. @@ -28,5 +34,5 @@ Describes the ability delegator arguments. ```ts import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; -let args = AbilityDelegatorRegistry.getArguments(); +let args: AbilityDelegatorRegistry.AbilityDelegatorArgs = AbilityDelegatorRegistry.getArguments(); ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-abilityStageContext.md b/en/application-dev/reference/apis/js-apis-inner-application-abilityStageContext.md index 4d537d507764cd540e122beebd995f442d3a00fc..bb9604b2a9c095b74b91905c7090c4249b94a970 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-abilityStageContext.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-abilityStageContext.md @@ -9,6 +9,12 @@ This module provides APIs for accessing a specific ability stage. You can use th > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs of this module can be used only in the stage model. +## Modules to Import + +```ts +import common from '@ohos.app.ability.common'; +``` + ## Usage The ability stage context is obtained through an **AbilityStage** instance. diff --git a/en/application-dev/reference/apis/js-apis-inner-application-abilityStageMonitor.md b/en/application-dev/reference/apis/js-apis-inner-application-abilityStageMonitor.md index c462bb3e3e3ee33d99a8e84db77ff656e4bdc80c..8e55c316de31c1bc20b5b13bf5e25ebc7315db2f 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-abilityStageMonitor.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-abilityStageMonitor.md @@ -2,13 +2,16 @@ The **AbilityStageMonitor** module provides conditions for matching **AbilityStage** instances. The most recently matched **AbilityStage** instance is saved in an **AbilityStageMonitor** instance. +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. **System capability**: SystemCapability.Ability.AbilityRuntime.Core | Name | Type | Readable| Writable| Description | | ------------------------------------------------------------ | -------- | ---- | ---- | ------------------------------------------------------------ | -| moduleName9+ | string | Yes | Yes | Module name of the **AbilityStage** instance.| -| srcEntrance9+ | string | Yes | Yes | Source path of the **AbilityStage** instance.| +| moduleName | string | Yes | Yes | Module name of the **AbilityStage** instance.| +| srcEntrance | string | Yes | Yes | Source path of the **AbilityStage** instance.| **Example** ```ts diff --git a/en/application-dev/reference/apis/js-apis-inner-application-abilityStateData.md b/en/application-dev/reference/apis/js-apis-inner-application-abilityStateData.md index eb539bd981610af81a6e9598bcab3da8dc3f9279..89737dea1984d4dbb8b5e46df6738b4dbb869e63 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-abilityStateData.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-abilityStateData.md @@ -2,17 +2,27 @@ The **AbilityStateData** module defines the ability state information, which can be obtained through the **onAbilityStateChanged** lifecycle callback of [ApplicationStateObserver](js-apis-inner-application-applicationStateObserver.md). The callback can be invoked after a lifecycle change listener is registered through [registerApplicationStateObserver](js-apis-application-appManager.md#appmanagerregisterapplicationstateobserver8). +> **NOTE** +> +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```ts +import appManager from '@ohos.application.appManager'; +``` + **System capability**: SystemCapability.Ability.AbilityRuntime.Core | Name | Type | Readable| Writable| Description | | ----------------------- | ---------| ---- | ---- | ------------------------- | -| pid8+ | number | Yes | No | Process ID. | -| bundleName8+ | string | Yes | No | Bundle name. | -| abilityName8+ | string | Yes | No | Ability name. | -| uid8+ | number | Yes | No | User ID. | -| state8+ | number | Yes | No | [Ability state](#ability-states). | +| pid | number | Yes | No | Process ID. | +| bundleName | string | Yes | No | Bundle name. | +| abilityName | string | Yes | No | Ability name. | +| uid | number | Yes | No | User ID. | +| state | number | Yes | No | [Ability state](#ability-states). | | moduleName9+ | string | Yes | No | Name of the HAP file to which the ability belongs. | -| abilityType8+ | number | Yes | No | [Ability type](#ability-types), which can be **page** or **service**.| +| abilityType | number | Yes | No | [Ability type](#ability-types), which can be **page** or **service**.| #### Ability States @@ -29,7 +39,7 @@ The **AbilityStateData** module defines the ability state information, which can #### Ability Types -| Value | Status | Description | +| Value | State | Description | | ---- | ------- | --------------------- | | 0 | UNKNOWN | Unknown type. | | 1 | PAGE | Ability that has the UI. | diff --git a/en/application-dev/reference/apis/js-apis-inner-application-applicationContext.md b/en/application-dev/reference/apis/js-apis-inner-application-applicationContext.md index 10dd9ae0285353e3feca2647ff4eee0dfce490b6..919496b065589319786d31e236fe1530fd175605 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-applicationContext.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-applicationContext.md @@ -7,12 +7,18 @@ The **ApplicationContext** module provides application-level context. You can us > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs of this module can be used only in the stage model. +## Modules to Import + +```ts +import common from '@ohos.app.ability.common'; +``` + ## Usage Before calling any APIs in **ApplicationContext**, obtain an **ApplicationContext** instance through the **context** instance. ```ts -let applicationContext = this.context.getApplicationContext(); +let applicationContext: common.ApplicationContext = this.context.getApplicationContext(); ``` ## ApplicationContext.on(type: 'abilityLifecycle', callback: AbilityLifecycleCallback) @@ -303,7 +309,6 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error **Example** ```ts -let applicationContext = this.context.getApplicationContext(); applicationContext.getRunningProcessInformation().then((data) => { console.log('The process running information is: ${JSON.stringify(data)}'); }).catch((error) => { @@ -341,7 +346,6 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error **Example** ```ts -let applicationContext = this.context.getApplicationContext(); applicationContext.getRunningProcessInformation((err, data) => { if (err) { console.error('getRunningProcessInformation faile, err: ${JSON.stringify(err)}'); @@ -376,7 +380,6 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error **Example** ```ts -let applicationContext = this.context.getApplicationContext(); applicationContext.killAllProcesses(); ``` @@ -405,7 +408,6 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error **Example** ```ts -let applicationContext = this.context.getApplicationContext(); applicationContext.killAllProcesses(error => { if (error) { console.error('killAllProcesses fail, error: ${JSON.stringify(error)}'); diff --git a/en/application-dev/reference/apis/js-apis-inner-application-applicationStateObserver.md b/en/application-dev/reference/apis/js-apis-inner-application-applicationStateObserver.md index 336811e398b21be7ac11e73047fdee15be67fedc..1e12c17c771021d8bd6dc8f0a38bde2de6d079fc 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-applicationStateObserver.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-applicationStateObserver.md @@ -2,22 +2,30 @@ The **ApplicationStateObserver** module defines an observer to listen for application state changes. It can be used as an input parameter in [registerApplicationStateObserver](js-apis-application-appManager.md#appmanagerregisterapplicationstateobserver8) to listen for lifecycle changes of the current application. +> **NOTE** +> +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```ts +import appManager from '@ohos.app.ability.appManager'; +``` + **System capability**: SystemCapability.Ability.AbilityRuntime.Core **System API**: This is a system API and cannot be called by third-party applications. | Name | | Type | Readable| Writable| Description | | ----------------------- | ---------| ---- | ---- | ------------------------- | ------------------------- | -| onForegroundApplicationChanged8+ | [AppStateData](js-apis-inner-application-appStateData.md) | AsyncCallback\ | Yes | No | Callback invoked when the foreground or background state of an application changes. | -| onAbilityStateChanged8+ | [AbilityStateData](js-apis-inner-application-abilityStateData.md) | AsyncCallback\ | Yes | No | Callback invoked when the ability state changes. | -| onProcessCreated8+ | [ProcessData](js-apis-inner-application-processData.md) | AsyncCallback\ | Yes | No | Callback invoked when a process is created. | -| onProcessDied8+ | [ProcessData](js-apis-inner-application-processData.md) | AsyncCallback\ | Yes | No | Callback invoked when a process is destroyed. | -| onProcessStateChanged8+ | [ProcessData](js-apis-inner-application-processData.md) | AsyncCallback\ | Yes | No | Callback invoked when the process state is changed. | +| onForegroundApplicationChanged | [AppStateData](js-apis-inner-application-appStateData.md) | AsyncCallback\ | Yes | No | Callback invoked when the foreground or background state of an application changes. | +| onAbilityStateChanged | [AbilityStateData](js-apis-inner-application-abilityStateData.md) | AsyncCallback\ | Yes | No | Callback invoked when the ability state changes. | +| onProcessCreated | [ProcessData](js-apis-inner-application-processData.md) | AsyncCallback\ | Yes | No | Callback invoked when a process is created. | +| onProcessDied | [ProcessData](js-apis-inner-application-processData.md) | AsyncCallback\ | Yes | No | Callback invoked when a process is destroyed. | +| onProcessStateChanged9+ | [ProcessData](js-apis-inner-application-processData.md) | AsyncCallback\ | Yes | No | Callback invoked when the process state is changed. | **Example** ```ts -import appManager from '@ohos.app.ability.appManager'; - let applicationStateObserver = { onForegroundApplicationChanged(appStateData) { console.log('onForegroundApplicationChanged appStateData: ${JSON.stringify(appStateData)}'); diff --git a/en/application-dev/reference/apis/js-apis-inner-application-baseContext.md b/en/application-dev/reference/apis/js-apis-inner-application-baseContext.md index f30e7733060ad505d88ad80fab618133c2a3b35e..707731bd3f213efe3a631dbdfb36baa465f91493 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-baseContext.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-baseContext.md @@ -6,6 +6,12 @@ > > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +## Modules to Import + +```ts +import common from '@ohos.app.ability.common'; +``` + **System capability**: SystemCapability.Ability.AbilityRuntime.Core | Name | Type | Readable | Writable | Description | diff --git a/en/application-dev/reference/apis/js-apis-inner-application-context.md b/en/application-dev/reference/apis/js-apis-inner-application-context.md index 62222885a9b1b8c78ae99db942cc64c6b0a372a1..a34482389fe63c18abc5c183d92a86cd7600732c 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-context.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-context.md @@ -29,7 +29,7 @@ import common from '@ohos.app.ability.common'; | bundleCodeDir | string | Yes | No | Bundle code directory. Do not access resource files by concatenating paths. Use the [resourceManager API](js-apis-resource-manager.md) instead.| | distributedFilesDir | string | Yes | No | Distributed file directory.| | eventHub | [EventHub](js-apis-inner-application-eventHub.md) | Yes | No | Event hub that implements event subscription, unsubscription, and triggering.| -| area | contextConstant.[AreaMode](js-apis-app-ability-contextConstant.md) | Yes | No | Area in which the file to be access is located.| +| area | contextConstant.[AreaMode](js-apis-app-ability-contextConstant.md) | Yes | No | Encryption level of the directory. | ## Context.createBundleContext @@ -41,6 +41,8 @@ Creates the context based on the bundle name. **System capability**: SystemCapability.Ability.AbilityRuntime.Core +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Type | Mandatory | Description | @@ -103,6 +105,8 @@ Creates the context based on the bundle name and module name. **System capability**: SystemCapability.Ability.AbilityRuntime.Core +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Type | Mandatory | Description | diff --git a/en/application-dev/reference/apis/js-apis-inner-application-errorObserver.md b/en/application-dev/reference/apis/js-apis-inner-application-errorObserver.md index 095529fabba54410949261e8ed9d64da620a4d89..b70c2abaad5f58b0dfe9d1dd03bbd3295aee4056 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-errorObserver.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-errorObserver.md @@ -2,6 +2,10 @@ The **ErrorObserver** module defines an observer to listen for application errors. It can be used as an input parameter in [ErrorManager.on](js-apis-app-ability-errorManager.md#errormanageron) to listen for errors that occur in the current application. +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + ## Modules to Import ```ts @@ -40,7 +44,7 @@ try { } ``` -## ErrorObserver.onException +## ErrorObserver.onException10+ onException?(errObject: Error): void; diff --git a/en/application-dev/reference/apis/js-apis-inner-application-eventHub.md b/en/application-dev/reference/apis/js-apis-inner-application-eventHub.md index cda73945ba6930d438635761e0924559261a281a..624cd79718a4bee0bdb65b5aa6f8f44dd49d7c93 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-eventHub.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-eventHub.md @@ -7,6 +7,12 @@ The **EventHub** module provides APIs to subscribe to, unsubscribe from, and tri > - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > - The APIs of this module can be used only in the stage model. +## Modules to Import + +```ts +import common from '@ohos.app.ability.common'; +``` + ## Usage Before using any APIs in the **EventHub**, you must obtain an **EventHub** instance through the member variable **context** of the **UIAbility** instance. diff --git a/en/application-dev/reference/apis/js-apis-inner-application-extensionContext.md b/en/application-dev/reference/apis/js-apis-inner-application-extensionContext.md index e4d28bb0823439d40b84be13c98a0b9758493a08..a79bf5961f6b46f9a113d4aa8d513724ed025f67 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-extensionContext.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-extensionContext.md @@ -9,6 +9,12 @@ This module provides APIs for accessing resources of a specific Extension abilit > - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > - The APIs of this module can be used only in the stage model. +## Modules to Import + +```ts +import common from '@ohos.app.ability.common'; +``` + ## Attributes **System capability**: SystemCapability.Ability.AbilityRuntime.Core diff --git a/en/application-dev/reference/apis/js-apis-inner-application-formExtensionContext.md b/en/application-dev/reference/apis/js-apis-inner-application-formExtensionContext.md index 4c84a0f8437779210bae784388d805d57b443508..e387ee397adb445f618c1a1df687b4f47b4d8cf5 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-formExtensionContext.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-formExtensionContext.md @@ -23,7 +23,7 @@ Before using the **ServiceExtensionContext** module, you must first obtain a **F import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; import formBindingData from '@ohos.app.form.formBindingData'; -export default class MyFormExtensionAbility extends FormExtensionAbility { +class MyFormExtensionAbility extends FormExtensionAbility { onAddForm(want) { let formContext = this.context; // Obtain a FormExtensionContext instance. // ... diff --git a/en/application-dev/reference/apis/js-apis-inner-application-missionInfo.md b/en/application-dev/reference/apis/js-apis-inner-application-missionInfo.md index 326e60a897a1d7b63149edb7e3303ddedc10319a..a9d9ff2f5515b3ab7487d9236dae5fa055504cad 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-missionInfo.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-missionInfo.md @@ -2,6 +2,10 @@ The **MissionInfo** module defines detailed information about a mission. The information can be obtained through [getMissionInfo](js-apis-app-ability-missionManager.md#missionmanagergetmissioninfo). +> **NOTE** +> +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. + ## Modules to Import ```ts diff --git a/en/application-dev/reference/apis/js-apis-inner-application-missionListener.md b/en/application-dev/reference/apis/js-apis-inner-application-missionListener.md index 9386b6f5b9b84129d6db9e86f944f01cf679d538..4dfb8ed40af7b3198d395fc3f1ddbb2e369077e7 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-missionListener.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-missionListener.md @@ -2,6 +2,16 @@ The **MissionListener** module defines the listeners used to observe the mission status. The listeners can be registered by using [on](js-apis-app-ability-missionManager.md#missionmanageron). +> **NOTE** +> +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```ts +import missionManager from '@ohos.app.ability.missionManager'; +``` + **System capability**: SystemCapability.Ability.AbilityRuntime.Mission | Name | Type | Mandatory| Description | @@ -10,9 +20,9 @@ The **MissionListener** module defines the listeners used to observe the mission | onMissionDestroyed | function | No | Called when the system destroys the mission.| | onMissionSnapshotChanged | function | No | Called when the system updates the mission snapshot.| | onMissionMovedToFront | function | No | Called when the system moves the mission to the foreground.| -| onMissionLabelUpdated | function | No | Called when the system updates the mission label.| -| onMissionIconUpdated | function | No | Called when the system updates the mission icon.| -| onMissionClosed | function | No | Called when the system closes the mission.| +| onMissionLabelUpdated9+ | function | No | Called when the system updates the mission label.| +| onMissionIconUpdated9+ | function | No | Called when the system updates the mission icon.| +| onMissionClosed9+ | function | No | Called when the system closes the mission.| **Example** ```ts diff --git a/en/application-dev/reference/apis/js-apis-inner-application-processData.md b/en/application-dev/reference/apis/js-apis-inner-application-processData.md index 076fdb4f2c0310aa9d53e8d303258672a8afc8e7..16427a352dc32cca383fdca9e6615b08b602a3f0 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-processData.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-processData.md @@ -2,22 +2,32 @@ The **ProcessData** module defines process data. If a lifecycle change listener is registered by calling [registerApplicationStateObserver](js-apis-application-appManager.md#appmanagerregisterapplicationstateobserver8), the **onProcessCreated** callback in [ApplicationStateObserver](js-apis-inner-application-applicationStateObserver.md) is invoked when the lifecycle of an application or ability changes. +> **NOTE** +> +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```ts +import appManager from '@ohos.application.appManager'; +``` + **System capability**: SystemCapability.Ability.AbilityRuntime.Core **System API**: This is a system API and cannot be called by third-party applications. | Name | Type | Readable| Writable| Description | | ----------------------- | ---------| ---- | ---- | ------------------------- | -| pid8+ | number | Yes | No | Process ID. | -| bundleName8+ | string | Yes | No | Bundle name of the application. | -| uid8+ | number | Yes | No | UID of the application. | +| pid | number | Yes | No | Process ID. | +| bundleName | string | Yes | No | Bundle name of the application. | +| uid | number | Yes | No | UID of the application. | | isContinuousTask9+ | boolean | Yes | No | Whether the task is a continuous task. The value **true** means that the task is a continuous task, and **false** means the opposite. | | isKeepAlive9+ | boolean | Yes | No | Whether the process is a resident task. The value **true** means that the process is a resident, and **false** means the opposite. | | state9+ | number | Yes | No | Application state. The value can be **0** (newly created), **2** (foreground), **4** (background), or **5** (terminated). | **Example** ```ts -import appManager from '@ohos.app.ability.appManager'; +import appManager from '@ohos.application.appManager'; let applicationStateObserver = { onForegroundApplicationChanged(appStateData) { diff --git a/en/application-dev/reference/apis/js-apis-inner-application-processRunningInfo.md b/en/application-dev/reference/apis/js-apis-inner-application-processRunningInfo.md index b1441077dc9b63aafab110388ad11114aa62796a..b746fcbf38ed136584c7c413ef9cb1fdd6c582d2 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-processRunningInfo.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-processRunningInfo.md @@ -6,6 +6,12 @@ The **ProcessRunningInfo** module defines the running information of a process. > - The APIs provided by this module are deprecated since API version 9. You are advised to use [ProcessInformation9+](js-apis-inner-application-processInformation.md) instead. > - The initial APIs of this module are supported since API version 8. +## Modules to Import + +```ts +import appManager from '@ohos.app.ability.appManager'; +``` + ## Attributes **System capability**: SystemCapability.Ability.AbilityRuntime.Mission diff --git a/en/application-dev/reference/apis/js-apis-inner-application-serviceExtensionContext.md b/en/application-dev/reference/apis/js-apis-inner-application-serviceExtensionContext.md index 476d143241154b165388a743950ed0d8f5afa48d..38928f42669eb30db5746d2c68037aff2961870f 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-serviceExtensionContext.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-serviceExtensionContext.md @@ -9,6 +9,12 @@ You can use the APIs of this module to start, terminate, connect, and disconnect > - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > - The APIs of this module can be used only in the stage model. +## Modules to Import + +```ts +import common from '@ohos.app.ability.common'; +``` + ## Usage Before using the **ServiceExtensionContext** module, you must define a child class that inherits from **ServiceExtensionAbility**. @@ -1348,3 +1354,208 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error console.error('error.code: ${paramError.code}, error.message: ${paramError.message}'); } ``` +## UIAbilityContext.startRecentAbility + +startRecentAbility(want: Want, callback: AsyncCallback<void<): void; + +Starts an ability. If the ability has multiple instances, the latest instance is started. This API uses an asynchronous callback to return the result. + +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **exported** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000010 | The call with the continuation flag is forbidden. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16000053 | The ability is not on the top of the UI. | +| 16000055 | Installation-free timed out. | +| 16200001 | The caller has been released. | + +**Example** + + ```ts +let want = { + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility' +}; + +try { + this.context.startRecentAbility(want, (err) => { + if (err.code) { + // Process service logic errors. + console.error(`startRecentAbility failed, code is ${err.code}, message is ${err.message}`); + return; + } + // Carry out normal service processing. + console.info('startRecentAbility succeed'); + }); +} catch (err) { + // Process input parameter errors. + console.error(`startRecentAbility failed failed, code is ${err.code}, message is ${err.message}`); +} + ``` +## UIAbilityContext.startRecentAbility + +startRecentAbility(want: Want, options: StartOptions, callback: AsyncCallback<void<): void; + +Starts an ability with the start options specified. If the ability has multiple instances, the latest instance is started. This API uses an asynchronous callback to return the result. +You can use this API to carry start options. + +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **exported** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| options | [StartOptions](js-apis-app-ability-startOptions.md) | Yes| Parameters used for starting the ability.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000010 | The call with the continuation flag is forbidden. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16000053 | The ability is not on the top of the UI. | +| 16000055 | Installation-free timed out. | +| 16200001 | The caller has been released. | + +**Example** + + ```ts +let want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility' +}; +let options = { + windowMode: 0 +}; + +try { + this.context.startRecentAbility(want, options, (err) => { + if (err.code) { + // Process service logic errors. + console.error(`startRecentAbility failed, code is ${err.code}, message is ${err.message}`); + return; + } + // Carry out normal service processing. + console.info('startRecentAbility succeed'); + }); +} catch (err) { + // Process input parameter errors. + console.error(`startRecentAbility failed failed, code is ${err.code}, message is ${err.message}`); +} + ``` +## UIAbilityContext.startRecentAbility + +startRecentAbility(want: Want, options?: StartOptions): Promise<void<; + +Starts an ability. If the ability has multiple instances, the latest instance is started. +This API uses a promise to return the result. + +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **exported** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| options | [StartOptions](js-apis-app-ability-startOptions.md) | No| Parameters used for starting the ability.| + +**Error codes** + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000010 | The call with the continuation flag is forbidden. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16000053 | The ability is not on the top of the UI. | +| 16000055 | Installation-free timed out. | +| 16200001 | The caller has been released. | + +**Example** + + ```ts +let want = { + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility' +}; +let options = { + windowMode: 0, +}; + +try { + this.context.startRecentAbility(want, options) + .then(() => { + // Carry out normal service processing. + console.info('startRecentAbility succeed'); + }) + .catch((err) => { + // Process service logic errors. + console.error(`startRecentAbility failed, code is ${err.code}, message is ${err.message}`); + }); +} catch (err) { + // Process input parameter errors. + console.error(`startRecentAbility failed, code is ${err.code}, message is ${err.message}`); +} + ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md b/en/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md index 59edfc898f6c32815b3926c9775913351dc476e9..cbfec0e2905afa5cf03244d67504ec9628a36c45 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md @@ -7,6 +7,12 @@ > - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > - The APIs of this module can be used only in the stage model. +## Modules to Import + +```ts +import common from '@ohos.app.ability.common'; +``` + ## Attributes **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -361,7 +367,7 @@ try { // Carry out normal service processing. console.info('startAbilityForResult succeed'); }); -} catch (paramError) { +} catch (err) { // Process input parameter errors. console.error(`startAbilityForResult failed, code is ${err.code}, message is ${err.message}`); } @@ -779,7 +785,7 @@ try { // Process service logic errors. console.error(`startServiceExtensionAbility failed, code is ${err.code}, message is ${err.message}`); }); -} catch (paramError) { +} catch (err) { // Process input parameter errors. console.error(`startServiceExtensionAbility failed, code is ${err.code}, message is ${err.message}`); } @@ -1391,6 +1397,7 @@ let want = { bundleName: 'com.example.myapplication', abilityName: 'ServiceExtensionAbility' }; +let commRemote; let options = { onConnect(elementName, remote) { commRemote = remote; @@ -1460,6 +1467,7 @@ let want = { abilityName: 'ServiceExtensionAbility' }; let accountId = 100; +let commRemote; let options = { onConnect(elementName, remote) { commRemote = remote; @@ -1516,6 +1524,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error ```ts // connection is the return value of connectServiceExtensionAbility. let connection = 1; +let commRemote; try { this.context.disconnectServiceExtensionAbility(connection, (err) => { @@ -1564,6 +1573,24 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error ```ts // connection is the return value of connectServiceExtensionAbility. let connection = 1; +let commRemote; + +try { + this.context.disconnectServiceExtensionAbility(connection, (err) => { + commRemote = null; + if (err.code) { + // Process service logic errors. + console.error(`disconnectServiceExtensionAbility failed, code is ${err.code}, message is ${err.message}`); + return; + } + // Carry out normal service processing. + console.info('disconnectServiceExtensionAbility succeed'); + }); +} catch (err) { + commRemote = null; + // Process input parameter errors. + console.error(`disconnectServiceExtensionAbility failed, code is ${err.code}, message is ${err.message}`); +} try { this.context.disconnectServiceExtensionAbility(connection, (err) => { @@ -1677,11 +1704,11 @@ try { // Carry out normal service processing. caller = obj; console.info('startAbilityByCall succeed'); - }).catch((error) => { + }).catch((err) => { // Process service logic errors. console.error(`startAbilityByCall failed, code is ${err.code}, message is ${err.message}`); }); -} catch (paramError) { +} catch (err) { // Process input parameter errors. console.error(`startAbilityByCall failed, code is ${err.code}, message is ${err.message}`); } @@ -2065,6 +2092,8 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error **Example** ```ts + import image from '@ohos.multimedia.image'; + let imagePixelMap; let color = new ArrayBuffer(0); let initializationOptions = { @@ -2283,5 +2312,210 @@ try { } catch (err) { // Process input parameter errors. console.error(`requestDialogService failed, code is ${err.code}, message is ${err.message}`); +} + ``` + ## UIAbilityContext.startRecentAbility + +startRecentAbility(want: Want, callback: AsyncCallback<void<): void; + +Starts an ability. If the ability has multiple instances, the latest instance is started. This API uses an asynchronous callback to return the result. + +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **exported** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000010 | The call with the continuation flag is forbidden. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16000053 | The ability is not on the top of the UI. | +| 16000055 | Installation-free timed out. | +| 16200001 | The caller has been released. | + +**Example** + + ```ts +let want = { + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility' +}; + +try { + this.context.startRecentAbility(want, (err) => { + if (err.code) { + // Process service logic errors. + console.error(`startRecentAbility failed, code is ${err.code}, message is ${err.message}`); + return; + } + // Carry out normal service processing. + console.info('startRecentAbility succeed'); + }); +} catch (err) { + // Process input parameter errors. + console.error(`startRecentAbility failed failed, code is ${err.code}, message is ${err.message}`); +} + ``` +## UIAbilityContext.startRecentAbility + +startRecentAbility(want: Want, options: StartOptions, callback: AsyncCallback<void<): void; + +Starts an ability with the start options specified. If the ability has multiple instances, the latest instance is started. This API uses an asynchronous callback to return the result. +You can use this API to carry start options. + +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **exported** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| options | [StartOptions](js-apis-app-ability-startOptions.md) | Yes| Parameters used for starting the ability.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000010 | The call with the continuation flag is forbidden. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16000053 | The ability is not on the top of the UI. | +| 16000055 | Installation-free timed out. | +| 16200001 | The caller has been released. | + +**Example** + + ```ts +let want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility' +}; +let options = { + windowMode: 0 +}; + +try { + this.context.startRecentAbility(want, options, (err) => { + if (err.code) { + // Process service logic errors. + console.error(`startRecentAbility failed, code is ${err.code}, message is ${err.message}`); + return; + } + // Carry out normal service processing. + console.info('startRecentAbility succeed'); + }); +} catch (err) { + // Process input parameter errors. + console.error(`startRecentAbility failed failed, code is ${err.code}, message is ${err.message}`); +} + ``` +## UIAbilityContext.startRecentAbility + +startRecentAbility(want: Want, options?: StartOptions): Promise<void<; + +Starts an ability. If the ability has multiple instances, the latest instance is started. +This API uses a promise to return the result. + +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **exported** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| options | [StartOptions](js-apis-app-ability-startOptions.md) | No| Parameters used for starting the ability.| + +**Error codes** + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000010 | The call with the continuation flag is forbidden. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16000053 | The ability is not on the top of the UI. | +| 16000055 | Installation-free timed out. | +| 16200001 | The caller has been released. | + +**Example** + + ```ts +let want = { + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility' +}; +let options = { + windowMode: 0, +}; + +try { + this.context.startRecentAbility(want, options) + .then(() => { + // Carry out normal service processing. + console.info('startRecentAbility succeed'); + }) + .catch((err) => { + // Process service logic errors. + console.error(`startRecentAbility failed, code is ${err.code}, message is ${err.message}`); + }); +} catch (err) { + // Process input parameter errors. + console.error(`startRecentAbility failed, code is ${err.code}, message is ${err.message}`); } ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-wantAgent-triggerInfo.md b/en/application-dev/reference/apis/js-apis-inner-wantAgent-triggerInfo.md index 5ca299f0ad5f9df4f5b460b30e9e34c7dad82d5d..6b90099bbdef7f61042528281dc947b6fdc43c92 100644 --- a/en/application-dev/reference/apis/js-apis-inner-wantAgent-triggerInfo.md +++ b/en/application-dev/reference/apis/js-apis-inner-wantAgent-triggerInfo.md @@ -2,6 +2,16 @@ The **TriggerInfo** module defines the information required for triggering the WantAgent. The information is used as an input parameter of [trigger](js-apis-app-ability-wantAgent.md#wantagenttrigger). +> **NOTE** +> +> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```ts +import wantAgent from '@ohos.app.ability.wantAgent'; +``` + **System capability**: SystemCapability.Ability.AbilityRuntime.Core | Name | Type | Mandatory| Description | diff --git a/en/application-dev/reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md b/en/application-dev/reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md index 289a5ebef3d8095fd599e630e0236935551246d1..cffcba65b1f1a6975024b080a20f078d1ee2f176 100644 --- a/en/application-dev/reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md +++ b/en/application-dev/reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md @@ -2,6 +2,16 @@ The **WantAgentInfo** module defines the information required for triggering a **WantAgent** object. The information can be used as an input parameter in [getWantAgent](js-apis-app-ability-wantAgent.md#wantagentgetwantagent) to obtain a specified **WantAgent** object. +> **NOTE** +> +> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```ts +import wantAgent from '@ohos.app.ability.wantAgent'; +``` + **System capability**: SystemCapability.Ability.AbilityRuntime.Core | Name | Type | Mandatory| Description | diff --git a/en/application-dev/reference/apis/js-apis-media.md b/en/application-dev/reference/apis/js-apis-media.md index 75b5cba5c965dfdcf9d149b0b69d0077022162cf..52178a666aa9ef29b878cd2b1978c3ab3ca3d163 100644 --- a/en/application-dev/reference/apis/js-apis-media.md +++ b/en/application-dev/reference/apis/js-apis-media.md @@ -46,15 +46,15 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco **Example** ```js -let avPlayer +let avPlayer; media.createAVPlayer((error, video) => { - if (video != null) { - avPlayer = video; - console.info('createAVPlayer success'); - } else { - console.info(`createAVPlayer fail, error:${error}`); - } + if (video != null) { + avPlayer = video; + console.info('createAVPlayer success'); + } else { + console.error(`createAVPlayer fail, error message:${error.message}`); + } }); ``` @@ -83,17 +83,17 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco **Example** ```js -let avPlayer +let avPlayer; media.createAVPlayer().then((video) => { - if (video != null) { - avPlayer = video; - console.info('createAVPlayer success'); - } else { - console.info('createAVPlayer fail'); - } + if (video != null) { + avPlayer = video; + console.info('createAVPlayer success'); + } else { + console.error('createAVPlayer fail'); + } }).catch((error) => { - console.info(`AVPlayer catchCallback, error:${error}`); + console.error(`AVPlayer catchCallback, error message:${error.message}`); }); ``` @@ -123,15 +123,15 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco **Example** ```js -let avRecorder +let avRecorder; media.createAVRecorder((error, recorder) => { - if (recorder != null) { - avRecorder = recorder; - console.info('createAVRecorder success'); - } else { - console.info(`createAVRecorder fail, error:${error}`); - } + if (recorder != null) { + avRecorder = recorder; + console.info('createAVRecorder success'); + } else { + console.error(`createAVRecorder fail, error message:${error.message}`); + } }); ``` @@ -161,17 +161,17 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco **Example** ```js -let avRecorder +let avRecorder; media.createAVRecorder().then((recorder) => { - if (recorder != null) { - avRecorder = recorder; - console.info('createAVRecorder success'); - } else { - console.info('createAVRecorder fail'); - } + if (recorder != null) { + avRecorder = recorder; + console.info('createAVRecorder success'); + } else { + console.error('createAVRecorder fail'); + } }).catch((error) => { - console.info(`createAVRecorder catchCallback, error:${error}`); + console.error(`createAVRecorder catchCallback, error message:${error.message}`); }); ``` @@ -203,15 +203,15 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco **Example** ```js -let videoRecorder +let videoRecorder; media.createVideoRecorder((error, video) => { - if (video != null) { - videoRecorder = video; - console.info('video createVideoRecorder success'); - } else { - console.info(`video createVideoRecorder fail, error:${error}`); - } + if (video != null) { + videoRecorder = video; + console.info('video createVideoRecorder success'); + } else { + console.error(`video createVideoRecorder fail, error message:${error.message}`); + } }); ``` @@ -243,17 +243,17 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco **Example** ```js -let videoRecorder +let videoRecorder; media.createVideoRecorder().then((video) => { - if (video != null) { - videoRecorder = video; - console.info('video createVideoRecorder success'); - } else { - console.info('video createVideoRecorder fail'); - } + if (video != null) { + videoRecorder = video; + console.info('video createVideoRecorder success'); + } else { + console.error('video createVideoRecorder fail'); + } }).catch((error) => { - console.info(`video catchCallback, error:${error}`); + console.error(`video catchCallback, error message:${error.message}`); }); ``` @@ -360,15 +360,15 @@ For details about the audio and video playback demo, see [Audio Playback](../../ | Name | Type | Readable| Writable| Description | | --------------------------------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | | url9+ | string | Yes | Yes | URL of the media asset. It is a static attribute and can be set only when the AVPlayer is in the idle state.
The video formats MP4, MPEG-TS, WebM, and MKV are supported.
The audio formats M4A, AAC, MP3, OGG, and WAV are supported.
**Examples of supported URLs**:
1. FD: fd://xx
![](figures/en-us_image_url.png)
2. HTTP: http://xx
3. HTTPS: https://xx
4. HLS: http://xx or https://xx| -| fdSrc9+ | [AVFileDescriptor](#avfiledescriptor9) | Yes | Yes | FD of the media asset. It is a static attribute and can be set only when the AVPlayer is in the idle state.
This attribute is required when media assets of an application are continuously stored in a file.
**Example:**
Assume that a media file that stores continuous assets consists of the following:
Video 1 (address offset: 0, byte length: 100)
Video 2 (address offset: 101; byte length: 50)
Video 3 (address offset: 151, byte length: 150)
1. To play video 1: AVFileDescriptor {fd = resource handle; offset = 0; length = 100; }
2. To play video 2: AVFileDescriptor {fd = resource handle; offset = 101; length = 50; }
3. To play video 3: AVFileDescriptor {fd = resource handle; offset = 151; length = 150; }
To play an independent media file, use **src=fd://xx**.| -| dataSrc10+ | [AVDataSrcDescriptor](#avdatasrcdescriptor10) | Yes | Yes | Descriptor of a streaming media asset. It is a static attribute and can be set only when the AVPlayer is in the idle state.
Use scenario: An application starts playing a media file while the file is still being downloaded from the remote to the local host.
**Example:**
A user is obtaining an audio and video file from a remote server and wants to play the downloaded file content. To implement this scenario, do as follows:
1. Obtain the total file size, in bytes. If the total size cannot be obtained or the live mode is expected, set **fileSize** to **-1**.
2. Implement the **func** callback to fill in data. If **fileSize** is **-1**, the format of **func** is **func(buffer: ArrayBuffer, length: number)**; otherwise, the format is **func(buffer: ArrayBuffer, length: number, pos: number)**.
3. Set **AVDataSrcDescriptor {fileSize = size, callback = func}**.| +| fdSrc9+ | [AVFileDescriptor](#avfiledescriptor9) | Yes | Yes | FD of the media asset. It is a static attribute and can be set only when the AVPlayer is in the idle state.
This attribute is required when media assets of an application are continuously stored in a file.
The video formats MP4, MPEG-TS, WebM, and MKV are supported.
The audio formats M4A, AAC, MP3, OGG, and WAV are supported.
**Example:**
Assume that a media file that stores continuous assets consists of the following:
Video 1 (address offset: 0, byte length: 100)
Video 2 (address offset: 101; byte length: 50)
Video 3 (address offset: 151, byte length: 150)
1. To play video 1: AVFileDescriptor {fd = resource handle; offset = 0; length = 100; }
2. To play video 2: AVFileDescriptor {fd = resource handle; offset = 101; length = 50; }
3. To play video 3: AVFileDescriptor {fd = resource handle; offset = 151; length = 150; }
To play an independent media file, use **src=fd://xx**.| +| dataSrc10+ | [AVDataSrcDescriptor](#avdatasrcdescriptor10) | Yes | Yes | Descriptor of a streaming media asset. It is a static attribute and can be set only when the AVPlayer is in the idle state.
Use scenario: An application starts playing a media file while the file is still being downloaded from the remote to the local host.
The video formats MP4, MPEG-TS, WebM, and MKV are supported.
The audio formats M4A, AAC, MP3, OGG, and WAV are supported.
**Example:**
A user is obtaining an audio and video file from a remote server and wants to play the downloaded file content. To implement this scenario, do as follows:
1. Obtain the total file size, in bytes. If the total size cannot be obtained, set **fileSize** to **-1**.
2. Implement the **func** callback to fill in data. If **fileSize** is **-1**, the format of **func** is **func(buffer: ArrayBuffer, length: number)**, and the AVPlayer obtains data in sequence; otherwise, the format is **func(buffer: ArrayBuffer, length: number, pos: number)**, and the AVPlayer seeks and obtains data in the required positions.
3. Set **AVDataSrcDescriptor {fileSize = size, callback = func}**.
**Notes:**
If the media file to play is in MP4/M4A format, ensure that the **moov** field (specifying the media information) is before the **mdat** field (specifying the media data) or the fields before the **moov** field is less than 10 MB. Otherwise, the parsing fails and the media file cannot be played.| | surfaceId9+ | string | Yes | Yes | Video window ID. By default, there is no video window. It is a static attribute and can be set only when the AVPlayer is in the initialized state.
It is used to render the window for video playback and therefore is not required in audio-only playback scenarios.
**Example:**
[Create a surface ID through XComponent](../arkui-ts/ts-basic-components-xcomponent.md#getxcomponentsurfaceid).| -| loop9+ | boolean | Yes | Yes | Whether to loop playback. The value **true** means to loop playback, and **false** (default) means the opposite. It is a dynamic attribute
and can be set only when the AVPlayer is in the prepared, playing, paused, or completed state.| +| loop9+ | boolean | Yes | Yes | Whether to loop playback. The value **true** means to loop playback, and **false** (default) means the opposite. It is a dynamic attribute
and can be set only when the AVPlayer is in the prepared, playing, paused, or completed state.
This setting is not supported in the live mode.| | videoScaleType9+ | [VideoScaleType](#videoscaletype9) | Yes | Yes | Video scaling type. The default value is **VIDEO_SCALE_TYPE_FIT_CROP**. It is a dynamic attribute
and can be set only when the AVPlayer is in the prepared, playing, paused, or completed state.| | audioInterruptMode9+ | [audio.InterruptMode](js-apis-audio.md#interruptmode9) | Yes | Yes | Audio interruption mode. The default value is **SHARE_MODE**. It is a dynamic attribute
and can be set only when the AVPlayer is in the prepared, playing, paused, or completed state.| | audioRendererInfo10+ | [audio.AudioRendererInfo](js-apis-audio.md#audiorendererinfo8) | Yes | Yes | Audio renderer information. The default value of **contentType** is **CONTENT_TYPE_MUSIC**, and the default value of **streamUsage** is **STREAM_USAGE_MEDIA**.
It can be set only when the AVPlayer is in the initialized state.| | state9+ | [AVPlayerState](#avplayerstate9) | Yes | No | AVPlayer state. It can be used as a query parameter when the AVPlayer is in any state. | -| currentTime9+ | number | Yes | No | Current video playback position, in ms. It can be used as a query parameter when the AVPlayer is in the prepared, playing, paused, or completed state.
The value **-1** indicates an invalid value.| +| currentTime9+ | number | Yes | No | Current video playback position, in ms. It can be used as a query parameter when the AVPlayer is in the prepared, playing, paused, or completed state.
The value **-1** indicates an invalid value.
In the live mode, **-1** is returned by default.| | duration9+ | number | Yes | No | Video duration, in ms. It can be used as a query parameter when the AVPlayer is in the prepared, playing, paused, or completed state.
The value **-1** indicates an invalid value.
In live streaming scenarios, **-1** is returned by default.| | width9+ | number | Yes | No | Video width, in pixels. It can be used as a query parameter when the AVPlayer is in the prepared, playing, paused, or completed state.
The value **0** indicates an invalid value.| | height9+ | number | Yes | No | Video height, in pixels. It can be used as a query parameter when the AVPlayer is in the prepared, playing, paused, or completed state.
The value **0** indicates an invalid value.| @@ -396,38 +396,38 @@ Subscribes to AVPlayer state changes. ```js avPlayer.on('stateChange', async (state, reason) => { - switch (state) { - case 'idle': - console.info('state idle called') - break; - case 'initialized': - console.info('initialized prepared called') - break; - case 'prepared': - console.info('state prepared called') - break; - case 'playing': - console.info('state playing called') - break; - case 'paused': - console.info('state paused called') - break; - case 'completed': - console.info('state completed called') - break; - case 'stopped': - console.info('state stopped called') - break; - case 'released': - console.info('state released called') - break; - case 'error': - console.info('state error called') - break; - default: - console.info('unkown state :' + state) - break; - } + switch (state) { + case 'idle': + console.info('state idle called') + break; + case 'initialized': + console.info('initialized prepared called') + break; + case 'prepared': + console.info('state prepared called') + break; + case 'playing': + console.info('state playing called') + break; + case 'paused': + console.info('state paused called') + break; + case 'completed': + console.info('state completed called') + break; + case 'stopped': + console.info('state stopped called') + break; + case 'released': + console.info('state released called') + break; + case 'error': + console.info('state error called') + break; + default: + console.info('unkown state :' + state) + break; + } }) ``` @@ -484,8 +484,8 @@ The AVPlayer provides the following error types: ```js avPlayer.on('error', (error) => { - console.info('error happened,and error message is :' + error.message) - console.info('error happened,and error code is :' + error.code) + console.error('error happened,and error message is :' + error.message) + console.error('error happened,and error code is :' + error.code) }) ``` @@ -536,11 +536,11 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco ```js avPlayer.prepare((err) => { - if (err == null) { - console.info('prepare success'); - } else { - console.error('prepare filed,error message is :' + err.message) - } + if (err == null) { + console.info('prepare success'); + } else { + console.error('prepare filed,error message is :' + err.message) + } }) ``` @@ -571,9 +571,9 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco ```js avPlayer.prepare().then(() => { - console.info('prepare success'); + console.info('prepare success'); }, (err) => { - console.error('prepare filed,error message is :' + err.message) + console.error('prepare filed,error message is :' + err.message) }) ``` @@ -603,11 +603,11 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco ```js avPlayer.play((err) => { - if (err == null) { - console.info('play success'); - } else { - console.error('play filed,error message is :' + err.message) - } + if (err == null) { + console.info('play success'); + } else { + console.error('play filed,error message is :' + err.message) + } }) ``` @@ -637,9 +637,9 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco ```js avPlayer.play().then(() => { - console.info('play success'); + console.info('play success'); }, (err) => { - console.error('play filed,error message is :' + err.message) + console.error('play filed,error message is :' + err.message) }) ``` @@ -669,11 +669,11 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco ```js avPlayer.pause((err) => { - if (err == null) { - console.info('pause success'); - } else { - console.error('pause filed,error message is :' + err.message) - } + if (err == null) { + console.info('pause success'); + } else { + console.error('pause filed,error message is :' + err.message) + } }) ``` @@ -703,9 +703,9 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco ```js avPlayer.pause().then(() => { - console.info('pause success'); + console.info('pause success'); }, (err) => { - console.error('pause filed,error message is :' + err.message) + console.error('pause filed,error message is :' + err.message) }) ``` @@ -735,11 +735,11 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco ```js avPlayer.stop((err) => { - if (err == null) { - console.info('stop success'); - } else { - console.error('stop filed,error message is :' + err.message) - } + if (err == null) { + console.info('stop success'); + } else { + console.error('stop filed,error message is :' + err.message) + } }) ``` @@ -769,9 +769,9 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco ```js avPlayer.stop().then(() => { - console.info('stop success'); + console.info('stop success'); }, (err) => { - console.error('stop filed,error message is :' + err.message) + console.error('stop filed,error message is :' + err.message) }) ``` @@ -801,11 +801,11 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco ```js avPlayer.reset((err) => { - if (err == null) { - console.info('reset success'); - } else { - console.error('reset filed,error message is :' + err.message) - } + if (err == null) { + console.info('reset success'); + } else { + console.error('reset filed,error message is :' + err.message) + } }) ``` @@ -835,9 +835,9 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco ```js avPlayer.reset().then(() => { - console.info('reset success'); + console.info('reset success'); }, (err) => { - console.error('reset filed,error message is :' + err.message) + console.error('reset filed,error message is :' + err.message) }) ``` @@ -867,11 +867,11 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco ```js avPlayer.release((err) => { - if (err == null) { - console.info('reset success'); - } else { - console.error('release filed,error message is :' + err.message) - } + if (err == null) { + console.info('reset success'); + } else { + console.error('release filed,error message is :' + err.message) + } }) ``` @@ -901,9 +901,9 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco ```js avPlayer.release().then(() => { - console.info('release success'); + console.info('release success'); }, (err) => { - console.error('release filed,error message is :' + err.message) + console.error('release filed,error message is :' + err.message) }) ``` @@ -932,22 +932,22 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco **Example** ```js -printfDescription(obj) { - for (let item in obj) { - let property = obj[item]; - console.info('audio key is ' + item); - console.info('audio value is ' + property); - } +function printfDescription(obj) { + for (let item in obj) { + let property = obj[item]; + console.info('audio key is ' + item); + console.info('audio value is ' + property); + } } avPlayer.getTrackDescription((error, arrList) => { - if ((arrList) != null) { - for (let i = 0; i < arrList.length; i++) { - printfDescription(arrList[i]); - } - } else { - console.log(`video getTrackDescription fail, error:${error}`); + if ((arrList) != null) { + for (let i = 0; i < arrList.length; i++) { + printfDescription(arrList[i]); } + } else { + console.log(`video getTrackDescription fail, error:${error}`); + } }); ``` @@ -978,24 +978,24 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco ```js let arrayDescription; -printfDescription(obj) { - for (let item in obj) { - let property = obj[item]; - console.info('audio key is ' + item); - console.info('audio value is ' + property); - } +function printfDescription(obj) { + for (let item in obj) { + let property = obj[item]; + console.info('audio key is ' + item); + console.info('audio value is ' + property); + } } avPlayer.getTrackDescription().then((arrList) => { - if (arrList != null) { - arrayDescription = arrList; - } else { - console.log('video getTrackDescription fail'); - } + if (arrList != null) { + arrayDescription = arrList; + } else { + console.log('video getTrackDescription fail'); + } }).catch((error) => { - console.info(`video catchCallback, error:${error}`); + console.info(`video catchCallback, error:${error}`); }); for (let i = 0; i < arrayDescription.length; i++) { - printfDescription(arrayDescription[i]); + printfDescription(arrayDescription[i]); } ``` @@ -1004,6 +1004,7 @@ for (let i = 0; i < arrayDescription.length; i++) { seek(timeMs: number, mode?:SeekMode): void Seeks to the specified playback position. This API can be called only when the AVPlayer is in the prepared, playing, paused, or completed state. You can check whether the seek operation takes effect by subscribing to the [seekDone](#seekDone_on) event. +This API is not supported in the live mode. **System capability**: SystemCapability.Multimedia.Media.AVPlayer @@ -1012,7 +1013,7 @@ Seeks to the specified playback position. This API can be called only when the A | Name| Type | Mandatory| Description | | ------ | ---------------------- | ---- | ------------------------------------------------------------ | | timeMs | number | Yes | Position to seek to, in ms. The value range is [0, [duration](#avplayer_duration)].| -| mode | [SeekMode](#seekmode8) | No | Seek mode based on the video I frame. **Set this parameter only for video playback.** | +| mode | [SeekMode](#seekmode8) | No | Seek mode based on the video I frame. The default value is **SEEK_PREV_SYNC**. **Set this parameter only for video playback.**| **Example** @@ -1040,7 +1041,7 @@ Subscribes to the event to check whether the seek operation takes effect. ```js avPlayer.on('seekDone', (seekDoneTime:number) => { - console.info('seekDone success,and seek time is:' + seekDoneTime) + console.info('seekDone success,and seek time is:' + seekDoneTime) }) ``` @@ -1069,6 +1070,7 @@ avPlayer.off('seekDone') setSpeed(speed: PlaybackSpeed): void Sets the playback speed. This API can be called only when the AVPlayer is in the prepared, playing, paused, or completed state. You can check whether the setting takes effect by subscribing to the [speedDone](#speedDone_on) event. +This API is not supported in the live mode. **System capability**: SystemCapability.Multimedia.Media.AVPlayer @@ -1103,7 +1105,7 @@ Subscribes to the event to check whether the playback speed is successfully set. ```js avPlayer.on('speedDone', (speed:number) => { - console.info('speedDone success,and speed value is:' + speed) + console.info('speedDone success,and speed value is:' + speed) }) ``` @@ -1167,7 +1169,7 @@ Subscribes to the event to check whether the bit rate is successfully set. ```js avPlayer.on('bitrateDone', (bitrate:number) => { - console.info('bitrateDone success,and bitrate value is:' + bitrate) + console.info('bitrateDone success,and bitrate value is:' + bitrate) }) ``` @@ -1210,7 +1212,7 @@ Subscribes to available bit rates of HLS streams. This event is reported only af ```js avPlayer.on('availableBitrates', (bitrates: Array) => { - console.info('availableBitrates success,and availableBitrates length is:' + bitrates.length) + console.info('availableBitrates success,and availableBitrates length is:' + bitrates.length) }) ``` @@ -1274,7 +1276,7 @@ Subscribes to the event to check whether the volume is successfully set. ```js avPlayer.on('volumeChange', (vol:number) => { - console.info('volumeChange success,and new volume is :' + vol) + console.info('volumeChange success,and new volume is :' + vol) }) ``` @@ -1317,7 +1319,7 @@ Subscribes to the event that indicates the end of the stream being played. If ** ```js avPlayer.on('endOfStream', () => { - console.info('endOfStream success') + console.info('endOfStream success') }) ``` @@ -1346,6 +1348,7 @@ avPlayer.off('endOfStream') on(type: 'timeUpdate', callback: Callback\): void Subscribes to playback position changes. It is used to refresh the current position of the progress bar. By default, this event is reported every 1 second. However, it is reported immediately upon a successful seek operation. +The **'timeUpdate'** event is not supported in the live mode. **System capability**: SystemCapability.Multimedia.Media.AVPlayer @@ -1360,7 +1363,7 @@ Subscribes to playback position changes. It is used to refresh the current posit ```js avPlayer.on('timeUpdate', (time:number) => { - console.info('timeUpdate success,and new time is :' + time) + console.info('timeUpdate success,and new time is :' + time) }) ``` @@ -1389,6 +1392,7 @@ avPlayer.off('timeUpdate') on(type: 'durationUpdate', callback: Callback\): void Subscribes to media asset duration changes. It is used to refresh the length of the progress bar. By default, this event is reported once when the AVPlayer switches to the prepared state. However, it can be repeatedly reported for special streams that trigger duration changes. +The **'durationUpdate'** event is not supported in the live mode. **System capability**: SystemCapability.Multimedia.Media.AVPlayer @@ -1403,7 +1407,7 @@ Subscribes to media asset duration changes. It is used to refresh the length of ```js avPlayer.on('durationUpdate', (duration) => { - console.info('durationUpdate success,new duration is :' + duration) + console.info('durationUpdate success,new duration is :' + duration) }) ``` @@ -1446,7 +1450,7 @@ Subscribes to audio and video buffer changes. This subscription is supported onl ```js avPlayer.on('bufferingUpdate', (infoType: media.BufferingInfoType, value: number) => { - console.info('bufferingUpdate success,and infoType value is:' + infoType + ', value is :' + value) + console.info('bufferingUpdate success,and infoType value is:' + infoType + ', value is :' + value) }) ``` @@ -1489,7 +1493,7 @@ Subscribes to the event that indicates rendering starts for the first frame. Thi ```js avPlayer.on('startRenderFrame', () => { - console.info('startRenderFrame success') + console.info('startRenderFrame success') }) ``` @@ -1532,7 +1536,7 @@ Subscribes to video size (width and height) changes. This subscription is suppor ```js avPlayer.on('videoSizeChange', (width: number, height: number) => { - console.info('videoSizeChange success,and width is:' + width + ', height is :' + height) + console.info('videoSizeChange success,and width is:' + width + ', height is :' + height) }) ``` @@ -1577,7 +1581,7 @@ Subscribes to the audio interruption event. When multiple audio and video assets import audio from '@ohos.multimedia.audio'; avPlayer.on('audioInterrupt', (info: audio.InterruptEvent) => { - console.info('audioInterrupt success,and InterruptEvent info is:' + info) + console.info('audioInterrupt success,and InterruptEvent info is:' + info) }) ``` @@ -1690,19 +1694,19 @@ Defines media information in key-value mode. ```js import media from '@ohos.multimedia.media' function printfItemDescription(obj, key) { - let property = obj[key]; - console.info('audio key is ' + key); // Specify a key. For details about the keys, see [MediaDescriptionKey]. - console.info('audio value is ' + property); // Obtain the value of the key. The value can be any type. For details about the types, see [MediaDescriptionKey]. + let property = obj[key]; + console.info('audio key is ' + key); // Specify a key. For details about the keys, see [MediaDescriptionKey]. + console.info('audio value is ' + property); // Obtain the value of the key. The value can be any type. For details about the types, see [MediaDescriptionKey]. } let audioPlayer = media.createAudioPlayer(); audioPlayer.getTrackDescription((error, arrList) => { - if (arrList != null) { - for (let i = 0; i < arrList.length; i++) { - printfItemDescription(arrList[i], media.MediaDescriptionKey.MD_KEY_TRACK_TYPE); // Print the MD_KEY_TRACK_TYPE value of each track. - } - } else { - console.log(`audio getTrackDescription fail, error:${error}`); + if (arrList != null) { + for (let i = 0; i < arrList.length; i++) { + printfItemDescription(arrList[i], media.MediaDescriptionKey.MD_KEY_TRACK_TYPE); // Print the MD_KEY_TRACK_TYPE value of each track. } + } else { + console.log(`audio getTrackDescription fail, error:${error}`); + } }); ``` @@ -1761,32 +1765,32 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco ```js // Configure the parameters based on those supported by the hardware device. let AVRecorderProfile = { - audioBitrate : 48000, - audioChannels : 2, - audioCodec : media.CodecMimeType.AUDIO_AAC, - audioSampleRate : 48000, - fileFormat : media.ContainerFormatType.CFT_MPEG_4, - videoBitrate : 2000000, - videoCodec : media.CodecMimeType.VIDEO_AVC, - videoFrameWidth : 640, - videoFrameHeight : 480, - videoFrameRate : 30 + audioBitrate : 48000, + audioChannels : 2, + audioCodec : media.CodecMimeType.AUDIO_AAC, + audioSampleRate : 48000, + fileFormat : media.ContainerFormatType.CFT_MPEG_4, + videoBitrate : 2000000, + videoCodec : media.CodecMimeType.VIDEO_AVC, + videoFrameWidth : 640, + videoFrameHeight : 480, + videoFrameRate : 30 } let AVRecorderConfig = { - audioSourceType : media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC, - videoSourceType : media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV, - profile : AVRecorderProfile, - url : 'fd://', // Before passing in an FD to this parameter, the file must be created by the caller and granted with the read and write permissions. Example value: eg.fd://45. - rotation: 0, // The value can be 0, 90, 180, or 270. If any other value is used, prepare() reports an error. - location : { latitude : 30, longitude : 130 } + audioSourceType : media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC, + videoSourceType : media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV, + profile : AVRecorderProfile, + url : 'fd://', // Before passing in an FD to this parameter, the file must be created by the caller and granted with the read and write permissions. Example value: eg.fd://45. + rotation: 0, // The value can be 0, 90, 180, or 270. If any other value is used, prepare() reports an error. + location : { latitude : 30, longitude : 130 } } avRecorder.prepare(AVRecorderConfig, (err) => { - if (err == null) { - console.info('prepare success'); - } else { - console.info('prepare failed and error is ' + err.message); - } + if (err == null) { + console.info('prepare success'); + } else { + console.error('prepare failed and error is ' + err.message); + } }) ``` @@ -1832,30 +1836,30 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco ```js // Configure the parameters based on those supported by the hardware device. let AVRecorderProfile = { - audioBitrate : 48000, - audioChannels : 2, - audioCodec : media.CodecMimeType.AUDIO_AAC, - audioSampleRate : 48000, - fileFormat : media.ContainerFormatType.CFT_MPEG_4, - videoBitrate : 2000000, - videoCodec : media.CodecMimeType.VIDEO_AVC, - videoFrameWidth : 640, - videoFrameHeight : 480, - videoFrameRate : 30 + audioBitrate : 48000, + audioChannels : 2, + audioCodec : media.CodecMimeType.AUDIO_AAC, + audioSampleRate : 48000, + fileFormat : media.ContainerFormatType.CFT_MPEG_4, + videoBitrate : 2000000, + videoCodec : media.CodecMimeType.VIDEO_AVC, + videoFrameWidth : 640, + videoFrameHeight : 480, + videoFrameRate : 30 } let AVRecorderConfig = { - audioSourceType : media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC, - videoSourceType : media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV, - profile : AVRecorderProfile, - url : 'fd://', // Before passing in an FD to this parameter, the file must be created by the caller and granted with the read and write permissions. Example value: eg.fd://45. - rotation: 0, // The value can be 0, 90, 180, or 270. If any other value is used, prepare() reports an error. - location : { latitude : 30, longitude : 130 } + audioSourceType : media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC, + videoSourceType : media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV, + profile : AVRecorderProfile, + url : 'fd://', // Before passing in an FD to this parameter, the file must be created by the caller and granted with the read and write permissions. Example value: eg.fd://45. + rotation: 0, // The value can be 0, 90, 180, or 270. If any other value is used, prepare() reports an error. + location : { latitude : 30, longitude : 130 } } avRecorder.prepare(AVRecorderConfig).then(() => { - console.info('prepare success'); + console.info('prepare success'); }).catch((err) => { - console.info('prepare failed and catch error is ' + err.message); + console.error('prepare failed and catch error is ' + err.message); }); ``` @@ -1894,12 +1898,12 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco let surfaceID = null; // The surfaceID is transferred to the camera API to create a videoOutput instance. avRecorder.getInputSurface((err, surfaceId) => { - if (err == null) { - console.info('getInputSurface success'); - surfaceID = surfaceId; - } else { - console.info('getInputSurface failed and error is ' + err.message); - } + if (err == null) { + console.info('getInputSurface success'); + surfaceID = surfaceId; + } else { + console.error('getInputSurface failed and error is ' + err.message); + } }); ``` @@ -1938,10 +1942,10 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco let surfaceID = null; // The surfaceID is transferred to the camera API to create a videoOutput instance. avRecorder.getInputSurface().then((surfaceId) => { - console.info('getInputSurface success'); - surfaceID = surfaceId; + console.info('getInputSurface success'); + surfaceID = surfaceId; }).catch((err) => { - console.info('getInputSurface failed and catch error is ' + err.message); + console.error('getInputSurface failed and catch error is ' + err.message); }); ``` @@ -1975,11 +1979,11 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco ```js avRecorder.start((err) => { - if (err == null) { - console.info('start AVRecorder success'); - } else { - console.info('start AVRecorder failed and error is ' + err.message); - } + if (err == null) { + console.info('start AVRecorder success'); + } else { + console.error('start AVRecorder failed and error is ' + err.message); + } }); ``` @@ -2013,9 +2017,9 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco ```js avRecorder.start().then(() => { - console.info('start AVRecorder success'); + console.info('start AVRecorder success'); }).catch((err) => { - console.info('start AVRecorder failed and catch error is ' + err.message); + console.error('start AVRecorder failed and catch error is ' + err.message); }); ``` @@ -2049,11 +2053,11 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco ```js avRecorder.pause((err) => { - if (err == null) { - console.info('pause AVRecorder success'); - } else { - console.info('pause AVRecorder failed and error is ' + err.message); - } + if (err == null) { + console.info('pause AVRecorder success'); + } else { + console.error('pause AVRecorder failed and error is ' + err.message); + } }); ``` @@ -2087,9 +2091,9 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco ```js avRecorder.pause().then(() => { - console.info('pause AVRecorder success'); + console.info('pause AVRecorder success'); }).catch((err) => { - console.info('pause AVRecorder failed and catch error is ' + err.message); + console.error('pause AVRecorder failed and catch error is ' + err.message); }); ``` @@ -2123,11 +2127,11 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco ```js avRecorder.resume((err) => { - if (err == null) { - console.info('resume AVRecorder success'); - } else { - console.info('resume AVRecorder failed and error is ' + err.message); - } + if (err == null) { + console.info('resume AVRecorder success'); + } else { + console.error('resume AVRecorder failed and error is ' + err.message); + } }); ``` @@ -2161,9 +2165,9 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco ```js avRecorder.resume().then(() => { - console.info('resume AVRecorder success'); + console.info('resume AVRecorder success'); }).catch((err) => { - console.info('resume AVRecorder failed and catch error is ' + err.message); + console.error('resume AVRecorder failed and catch error is ' + err.message); }); ``` @@ -2199,11 +2203,11 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco ```js avRecorder.stop((err) => { - if (err == null) { - console.info('stop AVRecorder success'); - } else { - console.info('stop AVRecorder failed and error is ' + err.message); - } + if (err == null) { + console.info('stop AVRecorder success'); + } else { + console.error('stop AVRecorder failed and error is ' + err.message); + } }); ``` @@ -2239,9 +2243,9 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco ```js avRecorder.stop().then(() => { - console.info('stop AVRecorder success'); + console.info('stop AVRecorder success'); }).catch((err) => { - console.info('stop AVRecorder failed and catch error is ' + err.message); + console.error('stop AVRecorder failed and catch error is ' + err.message); }); ``` @@ -2274,11 +2278,11 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco ```js avRecorder.reset((err) => { - if (err == null) { - console.info('reset AVRecorder success'); - } else { - console.info('reset AVRecorder failed and error is ' + err.message); - } + if (err == null) { + console.info('reset AVRecorder success'); + } else { + console.error('reset AVRecorder failed and error is ' + err.message); + } }); ``` @@ -2311,9 +2315,9 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco ```js avRecorder.reset().then(() => { - console.info('reset AVRecorder success'); + console.info('reset AVRecorder success'); }).catch((err) => { - console.info('reset AVRecorder failed and catch error is ' + err.message); + console.error('reset AVRecorder failed and catch error is ' + err.message); }); ``` @@ -2345,11 +2349,11 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco ```js avRecorder.release((err) => { - if (err == null) { - console.info('release AVRecorder success'); - } else { - console.info('release AVRecorder failed and error is ' + err.message); - } + if (err == null) { + console.info('release AVRecorder success'); + } else { + console.error('release AVRecorder failed and error is ' + err.message); + } }); ``` @@ -2381,9 +2385,9 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco ```js avRecorder.release().then(() => { - console.info('release AVRecorder success'); + console.info('release AVRecorder success'); }).catch((err) => { - console.info('release AVRecorder failed and catch error is ' + err.message); + console.error('release AVRecorder failed and catch error is ' + err.message); }); ``` @@ -2406,7 +2410,7 @@ Subscribes to AVRecorder state changes. An application can subscribe to only one ```js avRecorder.on('stateChange', async (state, reason) => { - console.info('case state has changed, new state is :' + state + ',and new reason is : ' + reason); + console.info('case state has changed, new state is :' + state + ',and new reason is : ' + reason); }); ``` @@ -2460,7 +2464,7 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco ```js avRecorder.on('error', (err) => { - console.info('case avRecorder.on(error) called, errMessage is ' + err.message); + console.error('case avRecorder.on(error) called, errMessage is ' + err.message); }); ``` @@ -2521,8 +2525,8 @@ Describes the audio and video recording parameters. | videoSourceType | [VideoSourceType](#videosourcetype9) | No | Type of the video source to record. This parameter is mandatory for video recording. | | profile | [AVRecorderProfile](#avrecorderprofile9) | Yes | Recording profile. This parameter is mandatory. | | url | string | Yes | Recording output URL: fd://xx (fd number).
![img](figures/en-us_image_url.png)
This parameter is mandatory.| -| rotation | number | No | Rotation angle of the recorded video. The value can only be 0, 90, 180, or 270. | -| location | [Location](#location) | No | Geographical location of the recorded video. | +| rotation | number | No | Rotation angle of the recorded video. The value can only be 0 (default), 90, 180, or 270. | +| location | [Location](#location) | No | Geographical location of the recorded video. By default, the geographical location information is not recorded. | The **audioSourceType** and **videoSourceType** parameters are used to distinguish audio-only recording, video-only recording, and audio and video recording. For audio-only recording, set only **audioSourceType**. For video-only recording, set only **videoSourceType**. For audio and video recording, set both **audioSourceType** and **videoSourceType**. @@ -2642,34 +2646,34 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco ```js // Configure the parameters based on those supported by the hardware device. let videoProfile = { - audioBitrate : 48000, - audioChannels : 2, - audioCodec : 'audio/mp4a-latm', - audioSampleRate : 48000, - fileFormat : 'mp4', - videoBitrate : 2000000, - videoCodec : 'video/avc', - videoFrameWidth : 640, - videoFrameHeight : 480, - videoFrameRate : 30 + audioBitrate : 48000, + audioChannels : 2, + audioCodec : 'audio/mp4a-latm', + audioSampleRate : 48000, + fileFormat : 'mp4', + videoBitrate : 2000000, + videoCodec : 'video/avc', + videoFrameWidth : 640, + videoFrameHeight : 480, + videoFrameRate : 30 } let videoConfig = { - audioSourceType : 1, - videoSourceType : 0, - profile : videoProfile, - url : 'fd://xx', // The file must be created by the caller and granted with proper permissions. - orientationHint : 0, - location : { latitude : 30, longitude : 130 }, + audioSourceType : 1, + videoSourceType : 0, + profile : videoProfile, + url : 'fd://xx', // The file must be created by the caller and granted with proper permissions. + orientationHint : 0, + location : { latitude : 30, longitude : 130 }, } // asyncallback videoRecorder.prepare(videoConfig, (err) => { - if (err == null) { - console.info('prepare success'); - } else { - console.info('prepare failed and error is ' + err.message); - } + if (err == null) { + console.info('prepare success'); + } else { + console.error('prepare failed and error is ' + err.message); + } }) ``` @@ -2713,32 +2717,32 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco ```js // Configure the parameters based on those supported by the hardware device. let videoProfile = { - audioBitrate : 48000, - audioChannels : 2, - audioCodec : 'audio/mp4a-latm', - audioSampleRate : 48000, - fileFormat : 'mp4', - videoBitrate : 2000000, - videoCodec : 'video/avc', - videoFrameWidth : 640, - videoFrameHeight : 480, - videoFrameRate : 30 + audioBitrate : 48000, + audioChannels : 2, + audioCodec : 'audio/mp4a-latm', + audioSampleRate : 48000, + fileFormat : 'mp4', + videoBitrate : 2000000, + videoCodec : 'video/avc', + videoFrameWidth : 640, + videoFrameHeight : 480, + videoFrameRate : 30 } let videoConfig = { - audioSourceType : 1, - videoSourceType : 0, - profile : videoProfile, - url : 'fd://xx', // The file must be created by the caller and granted with proper permissions. - orientationHint : 0, - location : { latitude : 30, longitude : 130 }, + audioSourceType : 1, + videoSourceType : 0, + profile : videoProfile, + url : 'fd://xx', // The file must be created by the caller and granted with proper permissions. + orientationHint : 0, + location : { latitude : 30, longitude : 130 }, } // promise videoRecorder.prepare(videoConfig).then(() => { - console.info('prepare success'); + console.info('prepare success'); }).catch((err) => { - console.info('prepare failed and catch error is ' + err.message); + console.error('prepare failed and catch error is ' + err.message); }); ``` @@ -2778,12 +2782,12 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco // asyncallback let surfaceID = null; // Surface ID passed to the external system. videoRecorder.getInputSurface((err, surfaceId) => { - if (err == null) { - console.info('getInputSurface success'); - surfaceID = surfaceId; - } else { - console.info('getInputSurface failed and error is ' + err.message); - } + if (err == null) { + console.info('getInputSurface success'); + surfaceID = surfaceId; + } else { + console.error('getInputSurface failed and error is ' + err.message); + } }); ``` @@ -2823,10 +2827,10 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco // promise let surfaceID = null; // Surface ID passed to the external system. videoRecorder.getInputSurface().then((surfaceId) => { - console.info('getInputSurface success'); - surfaceID = surfaceId; + console.info('getInputSurface success'); + surfaceID = surfaceId; }).catch((err) => { - console.info('getInputSurface failed and catch error is ' + err.message); + console.error('getInputSurface failed and catch error is ' + err.message); }); ``` @@ -2863,11 +2867,11 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco ```js // asyncallback videoRecorder.start((err) => { - if (err == null) { - console.info('start videorecorder success'); - } else { - console.info('start videorecorder failed and error is ' + err.message); - } + if (err == null) { + console.info('start videorecorder success'); + } else { + console.error('start videorecorder failed and error is ' + err.message); + } }); ``` @@ -2904,9 +2908,9 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco ```js // promise videoRecorder.start().then(() => { - console.info('start videorecorder success'); + console.info('start videorecorder success'); }).catch((err) => { - console.info('start videorecorder failed and catch error is ' + err.message); + console.error('start videorecorder failed and catch error is ' + err.message); }); ``` @@ -2943,11 +2947,11 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco ```js // asyncallback videoRecorder.pause((err) => { - if (err == null) { - console.info('pause videorecorder success'); - } else { - console.info('pause videorecorder failed and error is ' + err.message); - } + if (err == null) { + console.info('pause videorecorder success'); + } else { + console.error('pause videorecorder failed and error is ' + err.message); + } }); ``` @@ -2984,9 +2988,9 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco ```js // promise videoRecorder.pause().then(() => { - console.info('pause videorecorder success'); + console.info('pause videorecorder success'); }).catch((err) => { - console.info('pause videorecorder failed and catch error is ' + err.message); + console.error('pause videorecorder failed and catch error is ' + err.message); }); ``` @@ -3021,11 +3025,11 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco ```js // asyncallback videoRecorder.resume((err) => { - if (err == null) { - console.info('resume videorecorder success'); - } else { - console.info('resume videorecorder failed and error is ' + err.message); - } + if (err == null) { + console.info('resume videorecorder success'); + } else { + console.error('resume videorecorder failed and error is ' + err.message); + } }); ``` @@ -3060,9 +3064,9 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco ```js // promise videoRecorder.resume().then(() => { - console.info('resume videorecorder success'); + console.info('resume videorecorder success'); }).catch((err) => { - console.info('resume videorecorder failed and catch error is ' + err.message); + console.error('resume videorecorder failed and catch error is ' + err.message); }); ``` @@ -3099,11 +3103,11 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco ```js // asyncallback videoRecorder.stop((err) => { - if (err == null) { - console.info('stop videorecorder success'); - } else { - console.info('stop videorecorder failed and error is ' + err.message); - } + if (err == null) { + console.info('stop videorecorder success'); + } else { + console.error('stop videorecorder failed and error is ' + err.message); + } }); ``` @@ -3140,9 +3144,9 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco ```js // promise videoRecorder.stop().then(() => { - console.info('stop videorecorder success'); + console.info('stop videorecorder success'); }).catch((err) => { - console.info('stop videorecorder failed and catch error is ' + err.message); + console.error('stop videorecorder failed and catch error is ' + err.message); }); ``` @@ -3175,11 +3179,11 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco ```js // asyncallback videoRecorder.release((err) => { - if (err == null) { - console.info('release videorecorder success'); - } else { - console.info('release videorecorder failed and error is ' + err.message); - } + if (err == null) { + console.info('release videorecorder success'); + } else { + console.error('release videorecorder failed and error is ' + err.message); + } }); ``` @@ -3212,9 +3216,9 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco ```js // promise videoRecorder.release().then(() => { - console.info('release videorecorder success'); + console.info('release videorecorder success'); }).catch((err) => { - console.info('release videorecorder failed and catch error is ' + err.message); + console.error('release videorecorder failed and catch error is ' + err.message); }); ``` @@ -3250,11 +3254,11 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco ```js // asyncallback videoRecorder.reset((err) => { - if (err == null) { - console.info('reset videorecorder success'); - } else { - console.info('reset videorecorder failed and error is ' + err.message); - } + if (err == null) { + console.info('reset videorecorder success'); + } else { + console.error('reset videorecorder failed and error is ' + err.message); + } }); ``` @@ -3290,9 +3294,9 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco ```js // promise videoRecorder.reset().then(() => { - console.info('reset videorecorder success'); + console.info('reset videorecorder success'); }).catch((err) => { - console.info('reset videorecorder failed and catch error is ' + err.message); + console.error('reset videorecorder failed and catch error is ' + err.message); }); ``` @@ -3325,7 +3329,7 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco ```js // This event is reported when an error occurs during the retrieval of videoRecordState. videoRecorder.on('error', (error) => { // Set the 'error' event callback. - console.info(`audio error called, error: ${error}`); + console.error(`audio error called, error: ${error}`); }) ``` @@ -3359,9 +3363,9 @@ Describes the video recording parameters. | audioSourceType | [AudioSourceType](#audiosourcetype9) | Yes | Type of the audio source for video recording. | | videoSourceType | [VideoSourceType](#videosourcetype9) | Yes | Type of the video source for video recording. | | profile | [VideoRecorderProfile](#videorecorderprofile9) | Yes | Video recording profile. | -| rotation | number | No | Rotation angle of the recorded video. | -| location | [Location](#location) | No | Geographical location of the recorded video. | -| url | string | Yes | Video output URL. Supported: fd://xx (fd number)
![](figures/en-us_image_url.png) | +| rotation | number | No | Rotation angle of the recorded video. The value can only be 0 (default), 90, 180, or 270. | +| location | [Location](#location) | No | Geographical location of the recorded video. By default, the geographical location information is not recorded. | +| url | string | Yes | Video output URL. Supported: fd://xx (fd number)
![](figures/en-us_image_url.png) | ## VideoRecorderProfile9+ @@ -3429,15 +3433,15 @@ Creates a **VideoPlayer** instance. This API uses an asynchronous callback to re **Example** ```js -let videoPlayer +let videoPlayer; media.createVideoPlayer((error, video) => { - if (video != null) { - videoPlayer = video; - console.info('video createVideoPlayer success'); - } else { - console.info(`video createVideoPlayer fail, error:${error}`); - } + if (video != null) { + videoPlayer = video; + console.info('video createVideoPlayer success'); + } else { + console.error(`video createVideoPlayer fail, error:${error}`); + } }); ``` @@ -3462,17 +3466,17 @@ Creates a **VideoPlayer** instance. This API uses a promise to return the result **Example** ```js -let videoPlayer +let videoPlayer; media.createVideoPlayer().then((video) => { - if (video != null) { - videoPlayer = video; - console.info('video createVideoPlayer success'); - } else { - console.info('video createVideoPlayer fail'); - } + if (video != null) { + videoPlayer = video; + console.info('video createVideoPlayer success'); + } else { + console.error('video createVideoPlayer fail'); + } }).catch((error) => { - console.info(`video catchCallback, error:${error}`); + console.error(`video catchCallback, error:${error}`); }); ``` @@ -3558,7 +3562,7 @@ Starts to play an audio asset. This API can be called only after the [dataLoad]( ```js audioPlayer.on('play', () => { // Set the 'play' event callback. - console.log('audio play success'); + console.log('audio play success'); }); audioPlayer.play(); ``` @@ -3575,7 +3579,7 @@ Pauses audio playback. ```js audioPlayer.on('pause', () => { // Set the 'pause' event callback. - console.log('audio pause success'); + console.log('audio pause success'); }); audioPlayer.pause(); ``` @@ -3592,7 +3596,7 @@ Stops audio playback. ```js audioPlayer.on('stop', () => { // Set the 'stop' event callback. - console.log('audio stop success'); + console.log('audio stop success'); }); audioPlayer.stop(); ``` @@ -3609,7 +3613,7 @@ Resets the audio asset to be played. ```js audioPlayer.on('reset', () => { // Set the 'reset' event callback. - console.log('audio reset success'); + console.log('audio reset success'); }); audioPlayer.reset(); ``` @@ -3632,11 +3636,11 @@ Seeks to the specified playback position. ```js audioPlayer.on('timeUpdate', (seekDoneTime) => { // Set the 'timeUpdate' event callback. - if (seekDoneTime == null) { - console.info('audio seek fail'); - return; - } - console.log('audio seek success. seekDoneTime: ' + seekDoneTime); + if (seekDoneTime == null) { + console.info('audio seek fail'); + return; + } + console.log('audio seek success. seekDoneTime: ' + seekDoneTime); }); audioPlayer.seek(30000); // Seek to 30000 ms. ``` @@ -3659,7 +3663,7 @@ Sets the volume. ```js audioPlayer.on('volumeChange', () => { // Set the 'volumeChange' event callback. - console.log('audio volumeChange success'); + console.log('audio volumeChange success'); }); audioPlayer.setVolume(1); // Set the volume to 100%. ``` @@ -3697,21 +3701,21 @@ Obtains the audio track information. This API uses an asynchronous callback to r ```js function printfDescription(obj) { - for (let item in obj) { - let property = obj[item]; - console.info('audio key is ' + item); - console.info('audio value is ' + property); - } + for (let item in obj) { + let property = obj[item]; + console.info('audio key is ' + item); + console.info('audio value is ' + property); + } } audioPlayer.getTrackDescription((error, arrList) => { - if (arrList != null) { - for (let i = 0; i < arrList.length; i++) { - printfDescription(arrList[i]); - } - } else { - console.log(`audio getTrackDescription fail, error:${error}`); + if (arrList != null) { + for (let i = 0; i < arrList.length; i++) { + printfDescription(arrList[i]); } + } else { + console.log(`audio getTrackDescription fail, error:${error}`); + } }); ``` @@ -3733,25 +3737,25 @@ Obtains the audio track information. This API uses a promise to return the resul ```js function printfDescription(obj) { - for (let item in obj) { - let property = obj[item]; - console.info('audio key is ' + item); - console.info('audio value is ' + property); - } + for (let item in obj) { + let property = obj[item]; + console.info('audio key is ' + item); + console.info('audio value is ' + property); + } } let arrayDescription = null audioPlayer.getTrackDescription().then((arrList) => { - if (arrList != null) { - arrayDescription = arrList; - } else { - console.log('audio getTrackDescription fail'); - } + if (arrList != null) { + arrayDescription = arrList; + } else { + console.log('audio getTrackDescription fail'); + } }).catch((error) => { - console.info(`audio catchCallback, error:${error}`); + console.info(`audio catchCallback, error:${error}`); }); for (let i = 0; i < arrayDescription.length; i++) { - printfDescription(arrayDescription[i]); + printfDescription(arrayDescription[i]); } ``` @@ -3774,8 +3778,8 @@ Subscribes to the audio buffering update event. This API works only under online ```js audioPlayer.on('bufferingUpdate', (infoType, value) => { - console.log('audio bufferingInfo type: ' + infoType); - console.log('audio bufferingInfo value: ' + value); + console.log('audio bufferingInfo type: ' + infoType); + console.log('audio bufferingInfo value: ' + value); }); ``` @@ -3801,40 +3805,40 @@ import fs from '@ohos.file.fs'; let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. - console.info('audio set source success'); - audioPlayer.play(); // Start the playback and trigger the 'play' event callback. + console.info('audio set source success'); + audioPlayer.play(); // Start the playback and trigger the 'play' event callback. }); audioPlayer.on('play', () => { // Set the 'play' event callback. - console.info('audio play success'); - audioPlayer.seek(30000); // Call the seek() API and trigger the 'timeUpdate' event callback. + console.info('audio play success'); + audioPlayer.seek(30000); // Call the seek() API and trigger the 'timeUpdate' event callback. }); audioPlayer.on('pause', () => { // Set the 'pause' event callback. - console.info('audio pause success'); - audioPlayer.stop(); // Stop the playback and trigger the 'stop' event callback. + console.info('audio pause success'); + audioPlayer.stop(); // Stop the playback and trigger the 'stop' event callback. }); audioPlayer.on('reset', () => { // Set the 'reset' event callback. - console.info('audio reset success'); - audioPlayer.release(); // Release the AudioPlayer instance. - audioPlayer = undefined; + console.info('audio reset success'); + audioPlayer.release(); // Release the AudioPlayer instance. + audioPlayer = undefined; }); audioPlayer.on('timeUpdate', (seekDoneTime) => { // Set the 'timeUpdate' event callback. - if (seekDoneTime == null) { - console.info('audio seek fail'); - return; - } - console.info('audio seek success, and seek time is ' + seekDoneTime); - audioPlayer.setVolume(0.5); // Set the volume to 50% and trigger the 'volumeChange' event callback. + if (seekDoneTime == null) { + console.info('audio seek fail'); + return; + } + console.info('audio seek success, and seek time is ' + seekDoneTime); + audioPlayer.setVolume(0.5); // Set the volume to 50% and trigger the 'volumeChange' event callback. }); audioPlayer.on('volumeChange', () => { // Set the 'volumeChange' event callback. - console.info('audio volumeChange success'); - audioPlayer.pause(); // Pause the playback and trigger the 'pause' event callback. + console.info('audio volumeChange success'); + audioPlayer.pause(); // Pause the playback and trigger the 'pause' event callback. }); audioPlayer.on('finish', () => { // Set the 'finish' event callback. - console.info('audio play finish'); - audioPlayer.stop(); // Stop the playback and trigger the 'stop' event callback. + console.info('audio play finish'); + audioPlayer.stop(); // Stop the playback and trigger the 'stop' event callback. }); audioPlayer.on('error', (error) => { // Set the 'error' event callback. - console.info(`audio error called, error: ${error}`); + console.error(`audio error called, error: ${error}`); }); // Set the FD (local playback) of the audio file selected by the user. @@ -3842,13 +3846,13 @@ let fdPath = 'fd://'; // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/accounts/account_0/appdata" command. let path = '/data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3'; fs.open(path).then((file) => { - fdPath = fdPath + '' + file.fd; - console.info('open fd success fd is' + fdPath); - audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback. + fdPath = fdPath + '' + file.fd; + console.info('open fd success fd is' + fdPath); + audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback. }, (err) => { - console.info('open fd failed err is' + err); + console.info('open fd failed err is' + err); }).catch((err) => { - console.info('open fd failed err is' + err); + console.info('open fd failed err is' + err); }); ``` @@ -3871,11 +3875,11 @@ Subscribes to the **'timeUpdate'** event. This event is reported every second wh ```js audioPlayer.on('timeUpdate', (newTime) => { // Set the 'timeUpdate' event callback. - if (newTime == null) { - console.info('audio timeUpadate fail'); - return; - } - console.log('audio timeUpadate success. seekDoneTime: ' + newTime); + if (newTime == null) { + console.info('audio timeUpadate fail'); + return; + } + console.log('audio timeUpadate success. seekDoneTime: ' + newTime); }); audioPlayer.play(); // The 'timeUpdate' event is triggered when the playback starts. ``` @@ -3899,7 +3903,7 @@ Subscribes to audio playback error events. After an error event is reported, you ```js audioPlayer.on('error', (error) => { // Set the 'error' event callback. - console.info(`audio error called, error: ${error}`); + console.error(`audio error called, error: ${error}`); }); audioPlayer.setVolume(3); // Set volume to an invalid value to trigger the 'error' event. ``` @@ -3969,11 +3973,11 @@ Sets **SurfaceId**. This API uses an asynchronous callback to return the result. ```js let surfaceId = null; videoPlayer.setDisplaySurface(surfaceId, (err) => { - if (err == null) { - console.info('setDisplaySurface success!'); - } else { - console.info('setDisplaySurface fail!'); - } + if (err == null) { + console.info('setDisplaySurface success!'); + } else { + console.error('setDisplaySurface fail!'); + } }); ``` @@ -4004,9 +4008,9 @@ Sets **SurfaceId**. This API uses a promise to return the result. ```js let surfaceId = null; videoPlayer.setDisplaySurface(surfaceId).then(() => { - console.info('setDisplaySurface success'); + console.info('setDisplaySurface success'); }).catch((error) => { - console.info(`video catchCallback, error:${error}`); + console.error(`video catchCallback, error:${error}`); }); ``` @@ -4028,11 +4032,11 @@ Prepares for video playback. This API uses an asynchronous callback to return th ```js videoPlayer.prepare((err) => { - if (err == null) { - console.info('prepare success!'); - } else { - console.info('prepare fail!'); - } + if (err == null) { + console.info('prepare success!'); + } else { + console.error('prepare fail!'); + } }); ``` @@ -4054,9 +4058,9 @@ Prepares for video playback. This API uses a promise to return the result. ```js videoPlayer.prepare().then(() => { - console.info('prepare success'); + console.info('prepare success'); }).catch((error) => { - console.info(`video catchCallback, error:${error}`); + console.error(`video catchCallback, error:${error}`); }); ``` @@ -4078,11 +4082,11 @@ Starts to play video assets. This API uses an asynchronous callback to return th ```js videoPlayer.play((err) => { - if (err == null) { - console.info('play success!'); - } else { - console.info('play fail!'); - } + if (err == null) { + console.info('play success!'); + } else { + console.error('play fail!'); + } }); ``` @@ -4104,9 +4108,9 @@ Starts to play video assets. This API uses a promise to return the result. ```js videoPlayer.play().then(() => { - console.info('play success'); + console.info('play success'); }).catch((error) => { - console.info(`video catchCallback, error:${error}`); + console.error(`video catchCallback, error:${error}`); }); ``` @@ -4128,11 +4132,11 @@ Pauses video playback. This API uses an asynchronous callback to return the resu ```js videoPlayer.pause((err) => { - if (err == null) { - console.info('pause success!'); - } else { - console.info('pause fail!'); - } + if (err == null) { + console.info('pause success!'); + } else { + console.info('pause fail!'); + } }); ``` @@ -4154,9 +4158,9 @@ Pauses video playback. This API uses a promise to return the result. ```js videoPlayer.pause().then(() => { - console.info('pause success'); + console.info('pause success'); }).catch((error) => { - console.info(`video catchCallback, error:${error}`); + console.error(`video catchCallback, error:${error}`); }); ``` @@ -4178,11 +4182,11 @@ Stops video playback. This API uses an asynchronous callback to return the resul ```js videoPlayer.stop((err) => { - if (err == null) { - console.info('stop success!'); - } else { - console.info('stop fail!'); - } + if (err == null) { + console.info('stop success!'); + } else { + console.error('stop fail!'); + } }); ``` @@ -4204,9 +4208,9 @@ Stops video playback. This API uses a promise to return the result. ```js videoPlayer.stop().then(() => { - console.info('stop success'); + console.info('stop success'); }).catch((error) => { - console.info(`video catchCallback, error:${error}`); + console.error(`video catchCallback, error:${error}`); }); ``` @@ -4228,11 +4232,11 @@ Resets the video asset to be played. This API uses an asynchronous callback to r ```js videoPlayer.reset((err) => { - if (err == null) { - console.info('reset success!'); - } else { - console.info('reset fail!'); - } + if (err == null) { + console.info('reset success!'); + } else { + console.error('reset fail!'); + } }); ``` @@ -4254,9 +4258,9 @@ Resets the video asset to be played. This API uses a promise to return the resul ```js videoPlayer.reset().then(() => { - console.info('reset success'); + console.info('reset success'); }).catch((error) => { - console.info(`video catchCallback, error:${error}`); + console.error(`video catchCallback, error:${error}`); }); ``` @@ -4280,11 +4284,11 @@ Seeks to the specified playback position. The previous key frame at the specifie ```js let seekTime = 5000; videoPlayer.seek(seekTime, (err, result) => { - if (err == null) { - console.info('seek success!'); - } else { - console.info('seek fail!'); - } + if (err == null) { + console.info('seek success!'); + } else { + console.error('seek fail!'); + } }); ``` @@ -4310,11 +4314,11 @@ Seeks to the specified playback position. This API uses an asynchronous callback import media from '@ohos.multimedia.media' let seekTime = 5000; videoPlayer.seek(seekTime, media.SeekMode.SEEK_NEXT_SYNC, (err, result) => { - if (err == null) { - console.info('seek success!'); - } else { - console.info('seek fail!'); - } + if (err == null) { + console.info('seek success!'); + } else { + console.error('seek fail!'); + } }); ``` @@ -4331,7 +4335,7 @@ Seeks to the specified playback position. If **mode** is not specified, the prev | Name| Type | Mandatory| Description | | ------ | ---------------------- | ---- | ------------------------------------------------------------ | | timeMs | number | Yes | Position to seek to, in ms. The value range is [0, duration].| -| mode | [SeekMode](#seekmode8) | No | Seek mode. | +| mode | [SeekMode](#seekmode8) | No | Seek mode based on the video I frame. The default value is **SEEK_PREV_SYNC**. | **Return value** @@ -4345,15 +4349,15 @@ Seeks to the specified playback position. If **mode** is not specified, the prev import media from '@ohos.multimedia.media' let seekTime = 5000; videoPlayer.seek(seekTime).then((seekDoneTime) => { // seekDoneTime indicates the position after the seek operation is complete. - console.info('seek success'); + console.info('seek success'); }).catch((error) => { - console.info(`video catchCallback, error:${error}`); + console.error(`video catchCallback, error:${error}`); }); videoPlayer.seek(seekTime, media.SeekMode.SEEK_NEXT_SYNC).then((seekDoneTime) => { - console.info('seek success'); + console.info('seek success'); }).catch((error) => { - console.info(`video catchCallback, error:${error}`); + console.error(`video catchCallback, error:${error}`); }); ``` @@ -4377,11 +4381,11 @@ Sets the volume. This API uses an asynchronous callback to return the result. ```js let vol = 0.5; videoPlayer.setVolume(vol, (err, result) => { - if (err == null) { - console.info('setVolume success!'); - } else { - console.info('setVolume fail!'); - } + if (err == null) { + console.info('setVolume success!'); + } else { + console.error('setVolume fail!'); + } }); ``` @@ -4410,9 +4414,9 @@ Sets the volume. This API uses a promise to return the result. ```js let vol = 0.5; videoPlayer.setVolume(vol).then(() => { - console.info('setVolume success'); + console.info('setVolume success'); }).catch((error) => { - console.info(`video catchCallback, error:${error}`); + console.error(`video catchCallback, error:${error}`); }); ``` @@ -4434,11 +4438,11 @@ Releases the video playback resources. This API uses an asynchronous callback to ```js videoPlayer.release((err) => { - if (err == null) { - console.info('release success!'); - } else { - console.info('release fail!'); - } + if (err == null) { + console.info('release success!'); + } else { + console.error('release fail!'); + } }); ``` @@ -4460,9 +4464,9 @@ Releases the video playback resources. This API uses a promise to return the res ```js videoPlayer.release().then(() => { - console.info('release success'); + console.info('release success'); }).catch((error) => { - console.info(`video catchCallback, error:${error}`); + console.error(`video catchCallback, error:${error}`); }); ``` @@ -4484,21 +4488,21 @@ Obtains the video track information. This API uses an asynchronous callback to r ```js function printfDescription(obj) { - for (let item in obj) { - let property = obj[item]; - console.info('video key is ' + item); - console.info('video value is ' + property); - } + for (let item in obj) { + let property = obj[item]; + console.info('video key is ' + item); + console.info('video value is ' + property); + } } videoPlayer.getTrackDescription((error, arrList) => { - if ((arrList) != null) { - for (let i = 0; i < arrList.length; i++) { - printfDescription(arrList[i]); - } - } else { - console.log(`video getTrackDescription fail, error:${error}`); + if ((arrList) != null) { + for (let i = 0; i < arrList.length; i++) { + printfDescription(arrList[i]); } + } else { + console.log(`video getTrackDescription fail, error:${error}`); + } }); ``` @@ -4520,25 +4524,25 @@ Obtains the video track information. This API uses a promise to return the resul ```js function printfDescription(obj) { - for (let item in obj) { - let property = obj[item]; - console.info('video key is ' + item); - console.info('video value is ' + property); - } + for (let item in obj) { + let property = obj[item]; + console.info('video key is ' + item); + console.info('video value is ' + property); + } } let arrayDescription; videoPlayer.getTrackDescription().then((arrList) => { - if (arrList != null) { - arrayDescription = arrList; - } else { - console.log('video getTrackDescription fail'); - } + if (arrList != null) { + arrayDescription = arrList; + } else { + console.log('video getTrackDescription fail'); + } }).catch((error) => { - console.info(`video catchCallback, error:${error}`); + console.info(`video catchCallback, error:${error}`); }); for (let i = 0; i < arrayDescription.length; i++) { - printfDescription(arrayDescription[i]); + printfDescription(arrayDescription[i]); } ``` @@ -4564,11 +4568,11 @@ import media from '@ohos.multimedia.media' let speed = media.PlaybackSpeed.SPEED_FORWARD_2_00_X; videoPlayer.setSpeed(speed, (err, result) => { - if (err == null) { - console.info('setSpeed success!'); - } else { - console.info('setSpeed fail!'); - } + if (err == null) { + console.info('setSpeed success!'); + } else { + console.error('setSpeed fail!'); + } }); ``` @@ -4599,9 +4603,9 @@ import media from '@ohos.multimedia.media' let speed = media.PlaybackSpeed.SPEED_FORWARD_2_00_X; videoPlayer.setSpeed(speed).then(() => { - console.info('setSpeed success'); + console.info('setSpeed success'); }).catch((error) => { - console.info(`video catchCallback, error:${error}`); + console.error(`video catchCallback, error:${error}`); }); ``` @@ -4624,7 +4628,7 @@ Subscribes to the video playback completion event. ```js videoPlayer.on('playbackCompleted', () => { - console.info('playbackCompleted success!'); + console.info('playbackCompleted success!'); }); ``` @@ -4647,8 +4651,8 @@ Subscribes to the video buffering update event. Only network playback supports t ```js videoPlayer.on('bufferingUpdate', (infoType, value) => { - console.log('video bufferingInfo type: ' + infoType); - console.log('video bufferingInfo value: ' + value); + console.log('video bufferingInfo type: ' + infoType); + console.log('video bufferingInfo value: ' + value); }); ``` @@ -4671,7 +4675,7 @@ Subscribes to the frame rendering start event. ```js videoPlayer.on('startRenderFrame', () => { - console.info('startRenderFrame success!'); + console.info('startRenderFrame success!'); }); ``` @@ -4694,8 +4698,8 @@ Subscribes to the video width and height change event. ```js videoPlayer.on('videoSizeChanged', (width, height) => { - console.log('video width is: ' + width); - console.log('video height is: ' + height); + console.log('video width is: ' + width); + console.log('video height is: ' + height); }); ``` @@ -4718,7 +4722,7 @@ Subscribes to video playback error events. After an error event is reported, you ```js videoPlayer.on('error', (error) => { // Set the 'error' event callback. - console.info(`video error called, error: ${error}`); + console.error(`video error called, error: ${error}`); }); videoPlayer.url = 'fd://error'; // Set an incorrect URL to trigger the 'error' event. ``` @@ -4770,16 +4774,16 @@ Prepares for recording. ```js let audioRecorderConfig = { - audioEncoder : media.AudioEncoder.AAC_LC, - audioEncodeBitRate : 22050, - audioSampleRate : 22050, - numberOfChannels : 2, - format : media.AudioOutputFormat.AAC_ADTS, - uri : 'fd://1', // The file must be created by the caller and granted with proper permissions. - location : { latitude : 30, longitude : 130}, + audioEncoder : media.AudioEncoder.AAC_LC, + audioEncodeBitRate : 22050, + audioSampleRate : 22050, + numberOfChannels : 2, + format : media.AudioOutputFormat.AAC_ADTS, + uri : 'fd://1', // The file must be created by the caller and granted with proper permissions. + location : { latitude : 30, longitude : 130}, } audioRecorder.on('prepare', () => { // Set the 'prepare' event callback. - console.log('prepare success'); + console.log('prepare success'); }); audioRecorder.prepare(audioRecorderConfig); ``` @@ -4797,7 +4801,7 @@ Starts audio recording. This API can be called only after the [prepare](#audiore ```js audioRecorder.on('start', () => { // Set the 'start' event callback. - console.log('audio recorder start success'); + console.log('audio recorder start success'); }); audioRecorder.start(); ``` @@ -4814,7 +4818,7 @@ Pauses audio recording. This API can be called only after the [start](#audioreco ```js audioRecorder.on('pause', () => { // Set the 'pause' event callback. - console.log('audio recorder pause success'); + console.log('audio recorder pause success'); }); audioRecorder.pause(); ``` @@ -4831,7 +4835,7 @@ Resumes audio recording. This API can be called only after the [pause](#audiorec ```js audioRecorder.on('resume', () => { // Set the 'resume' event callback. - console.log('audio recorder resume success'); + console.log('audio recorder resume success'); }); audioRecorder.resume(); ``` @@ -4848,7 +4852,7 @@ Stops audio recording. ```js audioRecorder.on('stop', () => { // Set the 'stop' event callback. - console.log('audio recorder stop success'); + console.log('audio recorder stop success'); }); audioRecorder.stop(); ``` @@ -4865,7 +4869,7 @@ Releases the audio recording resources. ```js audioRecorder.on('release', () => { // Set the 'release' event callback. - console.log('audio recorder release success'); + console.log('audio recorder release success'); }); audioRecorder.release(); audioRecorder = undefined; @@ -4885,7 +4889,7 @@ Before resetting audio recording, you must call [stop()](#audiorecorder_stop) to ```js audioRecorder.on('reset', () => { // Set the 'reset' event callback. - console.log('audio recorder reset success'); + console.log('audio recorder reset success'); }); audioRecorder.reset(); ``` @@ -4910,38 +4914,38 @@ Subscribes to the audio recording events. ```js let audioRecorder = media.createAudioRecorder(); // Create an AudioRecorder instance. let audioRecorderConfig = { - audioEncoder : media.AudioEncoder.AAC_LC, - audioEncodeBitRate : 22050, - audioSampleRate : 22050, - numberOfChannels : 2, - format : media.AudioOutputFormat.AAC_ADTS, - uri : 'fd://xx', // The file must be created by the caller and granted with proper permissions. - location : { latitude : 30, longitude : 130}, + audioEncoder : media.AudioEncoder.AAC_LC, + audioEncodeBitRate : 22050, + audioSampleRate : 22050, + numberOfChannels : 2, + format : media.AudioOutputFormat.AAC_ADTS, + uri : 'fd://xx', // The file must be created by the caller and granted with proper permissions. + location : { latitude : 30, longitude : 130}, } audioRecorder.on('error', (error) => { // Set the 'error' event callback. - console.info(`audio error called, error: ${error}`); + console.info(`audio error called, error: ${error}`); }); audioRecorder.on('prepare', () => { // Set the 'prepare' event callback. - console.log('prepare success'); - audioRecorder.start(); // Start recording and trigger the 'start' event callback. + console.log('prepare success'); + audioRecorder.start(); // Start recording and trigger the 'start' event callback. }); audioRecorder.on('start', () => { // Set the 'start' event callback. - console.log('audio recorder start success'); + console.log('audio recorder start success'); }); audioRecorder.on('pause', () => { // Set the 'pause' event callback. - console.log('audio recorder pause success'); + console.log('audio recorder pause success'); }); audioRecorder.on('resume', () => { // Set the 'resume' event callback. - console.log('audio recorder resume success'); + console.log('audio recorder resume success'); }); audioRecorder.on('stop', () => { // Set the 'stop' event callback. - console.log('audio recorder stop success'); + console.log('audio recorder stop success'); }); audioRecorder.on('release', () => { // Set the 'release' event callback. - console.log('audio recorder release success'); + console.log('audio recorder release success'); }); audioRecorder.on('reset', () => { // Set the 'reset' event callback. - console.log('audio recorder reset success'); + console.log('audio recorder reset success'); }); audioRecorder.prepare(audioRecorderConfig) // Set recording parameters and trigger the 'prepare' event callback. ``` @@ -4965,16 +4969,16 @@ Subscribes to audio recording error events. After an error event is reported, yo ```js let audioRecorderConfig = { - audioEncoder : media.AudioEncoder.AAC_LC, - audioEncodeBitRate : 22050, - audioSampleRate : 22050, - numberOfChannels : 2, - format : media.AudioOutputFormat.AAC_ADTS, - uri : 'fd://xx', // The file must be created by the caller and granted with proper permissions. - location : { latitude : 30, longitude : 130}, + audioEncoder : media.AudioEncoder.AAC_LC, + audioEncodeBitRate : 22050, + audioSampleRate : 22050, + numberOfChannels : 2, + format : media.AudioOutputFormat.AAC_ADTS, + uri : 'fd://xx', // The file must be created by the caller and granted with proper permissions. + location : { latitude : 30, longitude : 130}, } audioRecorder.on('error', (error) => { // Set the 'error' event callback. - console.info(`audio error called, error: ${error}`); + console.error(`audio error called, error: ${error}`); }); audioRecorder.prepare(audioRecorderConfig); // Do no set any parameter in prepare and trigger the 'error' event callback. ``` diff --git a/en/application-dev/reference/apis/js-apis-screen-lock.md b/en/application-dev/reference/apis/js-apis-screen-lock.md index e399c34b8d29b71e3e1697dcd0778c648e744bb7..e633bf43d4a8879701dd4d3f63f66f51a0f20425 100644 --- a/en/application-dev/reference/apis/js-apis-screen-lock.md +++ b/en/application-dev/reference/apis/js-apis-screen-lock.md @@ -94,7 +94,7 @@ For details about the error codes, see [Screen Lock Management Error Codes](../e | ID| Error Message| | -------- | ---------------------------------------- | -| 13200002 | The screenlock management service is abnormal. | +| 13200002 | the screenlock management service is abnormal. | **Example** @@ -130,7 +130,7 @@ For details about the error codes, see [Screen Lock Management Error Codes](../e | ID| Error Message| | -------- | ---------------------------------------- | -| 13200002 | The screenlock management service is abnormal. | +| 13200002 | the screenlock management service is abnormal. | **Example** @@ -166,7 +166,7 @@ For details about the error codes, see [Screen Lock Management Error Codes](../e | ID| Error Message| | -------- | ---------------------------------------- | -| 13200002 | The screenlock management service is abnormal. | +| 13200002 | the screenlock management service is abnormal. | **Example** @@ -204,7 +204,7 @@ For details about the error codes, see [Screen Lock Management Error Codes](../e | ID| Error Message| | -------- | ---------------------------------------- | -| 13200002 | The screenlock management service is abnormal. | +| 13200002 | the screenlock management service is abnormal. | **Example** @@ -246,7 +246,7 @@ For details about the error codes, see [Screen Lock Management Error Codes](../e | ID| Error Message| | -------- | ---------------------------------------- | -| 13200002 | The screenlock management service is abnormal. | +| 13200002 | the screenlock management service is abnormal. | **Example** @@ -286,7 +286,7 @@ For details about the error codes, see [Screen Lock Management Error Codes](../e | ID| Error Message| | -------- | ---------------------------------------- | -| 13200002 | The screenlock management service is abnormal. | +| 13200002 |the screenlock management service is abnormal. | **Example** @@ -325,6 +325,14 @@ Sends an event to the screen lock service. This API uses a promise to return the | ----------------- | ---------------------------------------------- | | Promise\ | Promise used to return the result. The **value** true means that the event is sent successfully, and **false** means the opposite.| +**Error codes** + +For details about the error codes, see [Screen Lock Management Error Codes](../errorcodes/errorcode-screenlock.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 13200002 | the screenlock management service is abnormal. | + **Example** ```js diff --git a/en/application-dev/reference/apis/js-apis-screen.md b/en/application-dev/reference/apis/js-apis-screen.md index cc887122bc052addffca28197c745e52a6555807..055787cc06b2653390f1ffe66ac7d1733ec508f4 100644 --- a/en/application-dev/reference/apis/js-apis-screen.md +++ b/en/application-dev/reference/apis/js-apis-screen.md @@ -224,6 +224,89 @@ try { }; ``` +## screen.stopExpand10+ + +stopExpand(expandScreen:Array<number>, callback: AsyncCallback<void>): void + +Stops the expanded mode. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| ------------ | --------------------------- | --- | -------------------------------------------------------------- | +| expandScreen | Array<number> | Yes | IDs of the expanded screens. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the expanded mode is stopped, **err** is **undefined**; otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | ----------------------- | +| 1400001 | Invalid display or screen. | + +**Example** + +```js +try { + let expandScreenIds = [1, 2, 3]; + screen.stopExpand(expandScreenIds, (err) => { + if (err.code) { + console.error('Failed to stop expand screens. Code:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in stopping expand screens.'); + }); +} catch (exception) { + console.error('Failed to stop expand screens. Code: ' + JSON.stringify(exception)); +}; +``` + +## screen.stopExpand10+ + +stopExpand(expandScreen:Array<number>): Promise<void> + +Stops the expanded mode. This API uses a promise to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| ------------ | ------------------- | --- | --------------- | +| expandScreen | Array<number> | Yes | IDs of the expanded screens.| + +**Return value** + +| Type| Description| +| --------------------- | ----------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | ----------------------- | +| 1400001 | Invalid display or screen. | + +**Example** + +```js +try { + let expandScreenIds = [1, 2, 3]; + screen.stopExpand(expandScreenIds).then(() => { + console.info('Succeeded in stopping expand screens.'); + }).catch((err) => { + console.error('Failed to stop expand screens. Code:' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to stop expand screens. Code:' + JSON.stringify(exception)); +}; +``` + ## screen.makeMirror makeMirror(mainScreen:number, mirrorScreen:Array<number>, callback: AsyncCallback<number>): void @@ -311,6 +394,89 @@ try { }; ``` +## screen.stopMirror10+ + +stopMirror(mirrorScreen:Array<number>, callback: AsyncCallback<void>): void + +Stops screen mirroring. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| ------------ | --------------------------- | --- | -------------------------------------------------------------- | +| mirrorScreen | Array<number> | Yes | IDs of secondary screens. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If screen mirroring is stopped, **err** is **undefined**; otherwise, **err** is an error object. | + +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | ----------------------- | +| 1400001 | Invalid display or screen. | + +**Example** + +```js +try { + let mirrorScreenIds = [1, 2, 3]; + screen.stopMirror(mirrorScreenIds, (err) => { + if (err.code) { + console.error('Failed to stop mirror screens. Code:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in stopping mirror screens.'); + }); +} catch (exception) { + console.error('Failed to stop mirror screens. Code: ' + JSON.stringify(exception)); +}; +``` + +## screen.stopMirror10+ + +stopMirror(mirrorScreen:Array<number>): Promise<void> + +Stops screen mirroring. This API uses a promise to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| ------------ | ------------------- | --- | --------------- | +| mirrorScreen | Array<number> | Yes | IDs of secondary screens.| + +**Return value** + +| Type| Description| +| --------------------- | ----------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | ----------------------- | +| 1400001 | Invalid display or screen. | + +**Example** + +```js +try { + let mirrorScreenIds = [1, 2, 3]; + screen.stopMirror(mirrorScreenIds).then(() => { + console.info('Succeeded in stopping mirror screens.'); + }).catch((err) => { + console.error('Failed to stop mirror screens. Code:' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to stop mirror screens. Code:' + JSON.stringify(exception)); +}; +``` + ## screen.createVirtualScreen createVirtualScreen(options:VirtualScreenOption, callback: AsyncCallback<Screen>): void @@ -744,7 +910,7 @@ Before calling any API in **Screen**, you must use **[getAllScreens()](#screenge | id | number | Yes | No | Screen ID. | | parent | number | Yes | No | ID of the group to which a screen belongs. | | supportedModeInfo | Array<[ScreenModeInfo](#screenmodeinfo)> | Yes | No | Mode set supported by the screen. | -| activeModeIndex | number | Yes | No | Index of the active screen mode.| +| activeModeIndex | number | Yes | No | Index of the active screen mode. The current value and value range of this parameter vary according to the screen resolution, refresh rate, and device hardware.| | orientation | [Orientation](#orientation) | Yes | No | Screen orientation. | | sourceMode10+ | [ScreenSourceMode](#screensourcemode10) | Yes | No | Source mode of the screen. | @@ -836,7 +1002,7 @@ Sets the active mode of the screen. This API uses an asynchronous callback to re | Name | Type | Mandatory| Description | | --------- | ------------------------- | ---- | ------------------------------------------------------------ | -| modeIndex | number | Yes | Index of the mode to set. | +| modeIndex | number | Yes | Index of the mode to set. The current value and value range of this parameter vary according to the screen resolution, refresh rate, and device hardware.| | callback | AsyncCallback<void> | Yes | Callback used to return the result. If the active mode is successfully set, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** @@ -874,7 +1040,7 @@ Sets the active mode of the screen. This API uses a promise to return the result | Name | Type | Mandatory| Description | | --------- | ------ | ---- | ---------- | -| modeIndex | number | Yes | Index of the mode to set.| +| modeIndex | number | Yes | Index of the mode to set. The current value and value range of this parameter vary according to the screen resolution, refresh rate, and device hardware.| **Return value** diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174582870.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174582870.gif new file mode 100644 index 0000000000000000000000000000000000000000..b5bba70f5ee63e00c398f7b3c253198bcb05a864 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174582870.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001256858433.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001256858433.gif deleted file mode 100644 index 07a8d81674d244e6ec76c0b43558890caf53062e..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001256858433.gif and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/ts-container-griditem.md b/en/application-dev/reference/arkui-ts/ts-container-griditem.md index ca8e19332e7c8eb573c9086b25ec455a573ed5f0..f47c0319907873b5b140e9c17b143a94965a4573 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-griditem.md +++ b/en/application-dev/reference/arkui-ts/ts-container-griditem.md @@ -26,14 +26,27 @@ GridItem() | columnStart | number | Start column number of the component.| | columnEnd | number | End column number of the component.| | forceRebuild(deprecated) | boolean | Whether to re-create the component when it is being built.
This API is deprecated since API version 9. Whether to re-create the component is automatically determined based on the component attributes and child component changes. No manual configuration is required.
Default value: **false**| -| selectable8+ | boolean | Whether the current grid item is selectable by the mouse.
> **NOTE**
> This attribute takes effect only when mouse frame selection is enabled for the parent **\** container.
Default value: **true**| +| selectable8+ | boolean | Whether the current grid item is selectable by the mouse.
**NOTE**
This attribute takes effect only when mouse frame selection is enabled for the parent **\** container.
Default value: **true** | + +> **NOTE** +> +> Rules for setting **rowStart**, **rowEnd**, **columnStart**, and **columnEnd**: +> +> - The valid value range of **rowStart** and **rowEnd** is 0 to the total number of rows minus 1. The valid value range of **columnStart** and **columnEnd** is 0 to the total number of columns minus 1. +> +> - Settings outside of the valid ranges do not take effect. +> +> - In the grid that has both **columnTemplate** and **rowTemplate** set, a grid item takes up the specified number of rows (rowEnd – rowStart + 1) or columns (columnEnd – columnStart + 1), depending on whether **rowStart**/**rowEnd** or **columnStart**/**columnEnd** is set. +>- In the grid that has only **columnTemplate** set, a grid item takes up the specified number of columns. +> - In the grid that has only **rowTemplate** set, a grid item takes up the specified number of rows. +>- In the grid that has neither **columnTemplate** nor **rowTemplate** set, the row and column number attributes do not work. ## Events | Name| Description| | -------- | -------- | -| onSelect(event: (isSelected: boolean) => void)8+ | Triggered when the selected state of the grid item changes.
**isSelected**: Returns **true** if the grid item is selected by the mouse; returns **false** otherwise.| +| onSelect(event: (isSelected: boolean) => void)8+ | Triggered when the selected state of the grid item changes.
**isSelected**: returns **true** if the grid item is being selected by the mouse; returns **false** otherwise. | ## Example @@ -57,7 +70,7 @@ struct GridItemExample { .width('100%') .height('100%') .textAlign(TextAlign.Center) - }.rowStart(1).rowEnd(4) + }.rowStart(1).rowEnd(2).columnStart(1).columnEnd(2) // Set valid row and column numbers. ForEach(this.numbers, (item) => { GridItem() { @@ -77,7 +90,7 @@ struct GridItemExample { .width('100%') .height('100%') .textAlign(TextAlign.Center) - }.columnStart(1).columnEnd(5) + }.columnStart(1).columnEnd(4) // Set only the column numbers. The layout does not start from the first column. } .columnsTemplate('1fr 1fr 1fr 1fr 1fr') .rowsTemplate('1fr 1fr 1fr 1fr 1fr') @@ -87,4 +100,4 @@ struct GridItemExample { } ``` -![en-us_image_0000001256858433](figures/en-us_image_0000001256858433.gif) +![en-us_image_0000001174582870](figures/en-us_image_0000001174582870.gif) diff --git a/en/application-dev/tools/Readme-EN.md b/en/application-dev/tools/Readme-EN.md index 7be1e5159712ec14a7b6f433883a0ccbcda64938..586a7db31018d12b33acc54ac340d5dc3356afce 100644 --- a/en/application-dev/tools/Readme-EN.md +++ b/en/application-dev/tools/Readme-EN.md @@ -8,3 +8,4 @@ - [Common Event Manager](cem-tool.md) - [Advanced Notification Manager](anm-tool.md) - [restool](restool.md) +- [LLDB Usage Guide](lldb-tool.md) diff --git a/en/application-dev/tools/lldb-tool.md b/en/application-dev/tools/lldb-tool.md new file mode 100644 index 0000000000000000000000000000000000000000..d8cb8a1c52a7f71d66642a62793526f14bb26827 --- /dev/null +++ b/en/application-dev/tools/lldb-tool.md @@ -0,0 +1,109 @@ +# LLDB Usage Guide +## Overview +Low Lever Debugger (LLDB) is a next-generation high-performance debugger. + +LLDB is developed based on the [llvm15.0.4](https://github.com/llvm/llvm-project/releases/tag/llvmorg-15.0.4) and supports debugging on the home screen and OpenHarmony devices or simulators. +## How to Obtain +Obtain the OpenHarmony SDK from http://ci.openharmony.cn/dailys/dailybuilds. + +LLDB is in the following path of the SDK: +``` +\ohos-sdk\[system]\native\llvm +``` +The value of **system** can be **windows**, **linux**, or **darwin**. + +For example, for Windows, **lldb.exe** is stored in the following path after the SDK is decompressed: +``` +\ohos-sdk\windows\native\llvm\bin +``` + +## Supported Platform and Architecture + +### Local Debugging +#### Example: Local Debugging on the Linux Platform +1. Obtain the name of the executable file with debugging information generated by the clang compiler of the same version as LLDB. + +2. Run the following command in the terminal window to specify the name of the file to debug: + + ``` + ./lldb filename + ``` + +3. Set a breakpoint at the **main** function in the code and run the following command on the LLDB interface: + + ``` + (lldb) b main + ``` + +4. Run the following command on the LLDB interface. The program will stop at the breakpoint: + + ``` + (lldb) run + ``` + +5. Perform subsequent debugging operations. + +### Remote Debugging + +> **Note: During remote debugging, the LLDB server and LLDB must be used together.** +- Debugging the OHOS device on the Windows platform (Arm architecture) +- Debugging the OHOS device on the Windows platform (AArch64 architecture) +- Debugging the simulator on the Windows platform +- Debugging the OHOS device on the macOS (M1) platform (Arm architecture) +- Debugging the OHOS device on the macOS (M1) platform (AArch64 architecture) +- Debugging the simulator on the macOS (M1) platform +- Debugging the OHOS device on the macOS (x86) platform (Arm architecture) +- Debugging the OHOS device on the macOS (x86) platform (AArch64 architecture) +- Debugging the simulator on the macOS (x86) platform +- Debugging the OHOS device on the Linux platform (Arm architecture) +- Debugging the OHOS device on the Linux platform (AArch64 architecture) + +#### Example: Remote Debugging the OHOS Device on the Linux Platform (Arm Architecture) + +1. Run the executable file with debugging information on the device. + + ``` + ./filename + ``` + +2. Push the LLDB server to the device and run the LLDB server. + + Command line window 1: + + ``` + hdc file send lldb-server /data/local/tmp + hdc shell ./data/local/tmp/lldb-server p --server --listen "*:8080" + ``` + + > **Note: /data/local/tmp is a directory on the device, and 8080 is a listening port. Both of them can be customized.** + +3. Start LLDB in another window, select the remote OHOS device, and connect to it. + + Command line window 2: + + ``` + ./lldb + (lldb) platform select remote-ohos + (lldb) platform connect connect://localhost:8080 + ``` + +4. Set breakpoints and perform debugging operations. + + Command line window 2: + + ``` + (lldb) breakpoint set --file --line + (lldb) process attach --name process-name + ``` + +## Functions Provided by LLDB +- Loading a program to LLDB +- Setting a breakpoint +- Setting an observation point +- Starting or attaching to a program +- Executing a control program +- Checking the thread status +- Checking the stack frame status + +## References +For details about other functions and commands, see [LLDB Usage Guide](https://gitee.com/openharmony/third_party_llvm-project/blob/master/lldb/README_zh.md) diff --git a/zh-cn/application-dev/reference/apis/js-apis-arkui-componentSnapshot.md b/zh-cn/application-dev/reference/apis/js-apis-arkui-componentSnapshot.md index dfb912a6ca97cc757f843b91b6973b566df13f25..40644a2dc4a59076730881ab9b3ad53390a0ee50 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-arkui-componentSnapshot.md +++ b/zh-cn/application-dev/reference/apis/js-apis-arkui-componentSnapshot.md @@ -1,6 +1,6 @@ # @ohos.arkui.componentSnapshot(组件截图) -本模块提供获取组件截图的能力,包括已加载的组件的截图和没有加载的组件的截图。 +本模块提供获取组件截图的能力,包括已加载的组件的截图和没有加载的组件的截图。组件截图只能够截取组件大小的区域,如果组件的绘制超出了它的区域,或子组件的绘制超出了父组件的区域,这些在组件区域外绘制的内容不会在截图中呈现。 > **说明:** > @@ -8,6 +8,7 @@ > > 示例效果请以真机运行为准,当前 IDE 预览器不支持。 + ## 导入模块 ```js @@ -20,6 +21,10 @@ get(id: string, callback: AsyncCallback): void 获取已加载的组件的截图,传入组件的[ID 标识](../arkui-ts/ts-universal-attributes-component-id.md#组件标识),找到对应组件进行截图。通过回调返回结果。 +> **说明:** +> +> 截图会获取最近一帧的绘制内容。如果在组件触发更新的同时调用截图,更新的渲染内容不会被截取到,截图会返回上一帧的绘制内容。 + **系统能力:** SystemCapability.ArkUI.ArkUI.Full **参数:** @@ -71,6 +76,10 @@ get(id: string): Promise 获取已加载的组件的截图,传入组件的[ID 标识](../arkui-ts/ts-universal-attributes-component-id.md#组件标识),找到对应组件进行截图。通过Promise返回结果。 +> **说明:** +> +> 截图会获取最近一帧的绘制内容。如果在组件触发更新的同时调用截图,更新的渲染内容不会被截取到,截图会返回上一帧的绘制内容。 + **系统能力:** SystemCapability.ArkUI.ArkUI.Full **参数:** @@ -134,6 +143,13 @@ createFromBuilder(builder: CustomBuilder, callback: AsyncCallback **说明:** +> +> 由于需要等待组件构建、渲染成功,离屏截图的回调有500ms以内的延迟。 +> +> 部分执行耗时任务的组件可能无法及时在截图前加载完成,因此会截取不到加载成功后的图像。例如:加载网络图片的Image组件、Web组件。 + + **系统能力:** SystemCapability.ArkUI.ArkUI.Full **参数:** @@ -194,6 +210,12 @@ createFromBuilder(builder: CustomBuilder): Promise 在应用后台渲染CustomBuilder自定义组件,并输出其截图。通过Promise返回结果。 +> **说明:** +> +> 由于需要等待组件构建、渲染成功,离屏截图的回调有500ms以内的延迟。 +> +> 部分执行耗时任务的组件可能无法及时在截图前加载完成,因此会截取不到加载成功后的图像。例如:加载网络图片的Image组件、Web组件。 + **系统能力:** SystemCapability.ArkUI.ArkUI.Full **参数:** diff --git a/zh-cn/device-dev/quick-start/pre-installed-app-config-and-Install.md b/zh-cn/device-dev/quick-start/pre-installed-app-config-and-Install.md deleted file mode 100644 index f73f6c9398ade014d335277d4744f20e7725f279..0000000000000000000000000000000000000000 --- a/zh-cn/device-dev/quick-start/pre-installed-app-config-and-Install.md +++ /dev/null @@ -1,60 +0,0 @@ -# 预置应用配置与安装指导 - -预置应用是指随OpenHarmony系统出厂预置的应用。 - -本文介绍开发者如何将一个非预置应用配置为预置应用,以及已有预置应用更新后如何重新安装。 - -## 将非预置应用配置为预置应用。 - -1. 确定预置应用支持的路径,可以通过下述命令查询。本文将以路径/system/etc/app/为例。 - -``` -hdc_std param get const.cust.config_dir_layer -``` - -2. 在install_list.json中配置hap在设备上的路径。 - -``` -hdc_std shell mount -o rw,renount / -hdc_std file recv /system/etc/app/install_list.json . -``` - -3. 按照json中的配置方式,配置对应的字段。 - -``` -{ - "app_dir":"system/app/xxxx/yyyy", // 设备上的hap路径,如果不存在,需要手动创建,并推送hap到此目录。 - "removable":true // 是否支持卸载,false表示不可卸载,true表示可以卸载。 -} -``` - -4. 修改完成后,将install_list.json文件推送到设备上,并重启设备生效。 - -``` - hdc_std shell mount -o rw,remount / - hdc_std file send install_list.json /system/etc/app/install_list.json - hdc_std shell reboot -``` - -## 重新安装更新后的已有预置应用 - -有两种方法。 - -- 方法一:直接清空data,重启设备,应用会自动安装。 - -``` - hdc_std shell mount -o rw,remount / - hdc_std shell rm /data/* -rf - hdc_std shell sync - hdc_std shell /system/bin/udevadm trigger - hdc_std shell reboot -``` -- 方法二:如果该应用之前没有安装过,则可以执行下面命令后重启设备。 - -``` - hdc_std shell mount -o rw,remount / - hdc_std shell param set persist.bms.test-upgrade true - hdc_std shell reboot -``` - -如果应用之前已经安装过,这时继续推送新的hap到/system/app/的路径下,则需要保证应用的版本号,分为[Stage模型的版本号(versionCode)](../../application-dev/quick-start/app-configuration-file.md),[FA模型的版本号(code)](../../application-dev/quick-start/app-structure.md#version对象内部结构)比之前的大。 这时执行方法二的命令,重启后应用同样可以正常安装。需要注意的是方法二命令,不需要反复执行, 重启之后依然生效。 \ No newline at end of file diff --git a/zh-cn/device-dev/subsystems/subsys-preinstall-app-config-guide.md b/zh-cn/device-dev/subsystems/subsys-preinstall-app-config-guide.md index f9b797fe4886a7793d70e52a1fbe9e3f31492b23..eb4a809978709dfdfa008d2cf5f4b05f1b042a12 100755 --- a/zh-cn/device-dev/subsystems/subsys-preinstall-app-config-guide.md +++ b/zh-cn/device-dev/subsystems/subsys-preinstall-app-config-guide.md @@ -2,21 +2,21 @@ 预置应用是指随设备出厂预置的应用。OpenHarmony支持在不同设备上对预置应用进行差异化配置,设备厂商可根据需要对与预置应用进行配置。 -## 将应用配置为预置应用。 +## 将应用配置为预置应用 1. 在进行预置应用配置前,使用如下命令查询系统支持的预置目录。 命令查询结果如system、chipset、sys_prod、chip_prod等,并且返回的顺序越靠后优先级越高,如chip_prod的优先级高于system的优先级。本文以路径/system/etc/app/为例。 ``` -hdc_std shell param get const.cust.config_dir_layer +hdc shell param get const.cust.config_dir_layer ``` 2. 在install_list.json中配置hap在设备上的路径。 ``` -hdc_std shell mount -o rw,remount / -hdc_std file recv /system/etc/app/install_list.json . +hdc shell mount -o rw,remount / +hdc file recv /system/etc/app/install_list.json . ``` 3. 按照json中的配置方式,配置对应的字段。 @@ -35,9 +35,9 @@ hdc_std file recv /system/etc/app/install_list.json . 4. 修改完成后,将install_list.json文件推送到设备上,并重启设备生效。 ``` - hdc_std shell mount -o rw,remount / - hdc_std file send install_list.json /system/etc/app/install_list.json - hdc_std shell reboot + hdc shell mount -o rw,remount / + hdc file send install_list.json /system/etc/app/install_list.json + hdc shell reboot ``` ## 更新预置应用 @@ -47,20 +47,20 @@ hdc_std file recv /system/etc/app/install_list.json . - 方法一:直接清空data,重启设备,应用会自动安装。 ``` - hdc_std shell mount -o rw,remount / - hdc_std shell rm /data/* -rf - hdc_std shell sync - hdc_std shell /system/bin/udevadm trigger - hdc_std shell reboot + hdc shell mount -o rw,remount / + hdc shell rm /data/* -rf + hdc shell sync + hdc shell /system/bin/udevadm trigger + hdc shell reboot ``` - 方法二:执行如下命令,重启设备,应用即可安装。 -如果应用之前已经安装过,这时推送新的hap到/system/app/路径下,需保证应用的版本号(Stage模型下对应app.json5配置文件中的[versionCode](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/quick-start/app-configuration-file.md)标签;FA模型下对应配置文件中的[code](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/quick-start/app-structure.md#version对象内部结构)标签)大于之前的版本号。 + 如果应用之前已经安装过,这时推送新的hap到/system/app/路径下,需保证应用的版本号(Stage模型下对应app.json5配置文件中的[versionCode](../../application-dev/quick-start/app-configuration-file.md)标签;FA模型下对应配置文件中的[code](../../application-dev/quick-start/app-structure.md#version对象内部结构)标签)大于之前的版本号。 ``` - hdc_std shell mount -o rw,remount / - hdc_std shell param set persist.bms.test-upgrade true - hdc_std shell reboot + hdc shell mount -o rw,remount / + hdc shell param set persist.bms.test-upgrade true + hdc shell reboot ``` # 预置不安装列表配置