提交 0980b055 编写于 作者: L longwei 提交者: Gitee

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

Signed-off-by: Nlongwei <longwei27@huawei.com>
# Legal Notices
**Copyright (c) 2020-2022 OpenAtom OpenHarmony. All rights reserved.**
## Copyright
All copyrights of the OpenHarmony documents are reserved by OpenAtom OpenHarmony.
The OpenHarmony documents are licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). For easier understanding, you can visit [Creative Commons](https://creativecommons.org/licenses/by/4.0/) to get a human-readable summary of the license. For the complete content, see [Creative Commons Attribution 4.0 International Public License](https://creativecommons.org/licenses/by/4.0/legalcode).
## Trademarks and Permissions
No content provided in the OpenHarmony documentation shall be deemed as a grant of the approval or right to use any trademark, name, or logo of the OpenAtom Foundation and OpenAtom OpenHarmony. No third parties shall use any of the aforementioned trademarks, names, or logos in any way without explicit prior written permission of the OpenAtom Foundation.
## Disclaimer
The information in the OpenHarmony documents is subject to change without notice.
The OpenHarmony documents are provided without any express or implied warranty. In any case, the OpenAtom Foundation or the copyright owner is not liable for any direct or indirect loss arising from the use of the OpenHarmony documents, regardless of the cause or legal theory, even if the OpenHarmony documents have stated that there is a possibility of such loss.
<!--no_check-->
\ No newline at end of file
......@@ -7,7 +7,7 @@ To ensure successful communications between the client and server, interfaces re
![IDL-interface-description](./figures/IDL-interface-description.png)
IDL provides the following functions:
**IDL provides the following functions:**
- Declares interfaces provided by system services for external systems, and based on the interface declaration, generates C, C++, JS, or TS code for inter-process communication (IPC) or remote procedure call (RPC) proxies and stubs during compilation.
......@@ -17,7 +17,7 @@ IDL provides the following functions:
![IPC-RPC-communication-model](./figures/IPC-RPC-communication-model.png)
IDL has the following advantages:
**IDL has the following advantages:**
- Services are defined in the form of interfaces in IDL. Therefore, you do not need to focus on implementation details.
......@@ -433,7 +433,7 @@ export default {
console.log('ServiceAbility want:' + JSON.stringify(want));
console.log('ServiceAbility want name:' + want.bundleName)
} catch(err) {
console.log("ServiceAbility error:" + err)
console.log('ServiceAbility error:' + err)
}
console.info('ServiceAbility onConnect end');
return new IdlTestImp('connect');
......@@ -455,13 +455,13 @@ import featureAbility from '@ohos.ability.featureAbility';
function callbackTestIntTransaction(result: number, ret: number): void {
if (result == 0 && ret == 124) {
console.log("case 1 success ");
console.log('case 1 success');
}
}
function callbackTestStringTransaction(result: number): void {
if (result == 0) {
console.log("case 2 success ");
console.log('case 2 success');
}
}
......@@ -472,17 +472,17 @@ var onAbilityConnectDone = {
testProxy.testStringTransaction('hello', callbackTestStringTransaction);
},
onDisconnect:function (elementName) {
console.log("onDisconnectService onDisconnect");
console.log('onDisconnectService onDisconnect');
},
onFailed:function (code) {
console.log("onDisconnectService onFailed");
console.log('onDisconnectService onFailed');
}
};
function connectAbility: void {
let want = {
"bundleName":"com.example.myapplicationidl",
"abilityName": "com.example.myapplicationidl.ServiceAbility"
bundleName: 'com.example.myapplicationidl',
abilityName: 'com.example.myapplicationidl.ServiceAbility'
};
let connectionId = -1;
connectionId = featureAbility.connectAbility(want, onAbilityConnectDone);
......@@ -495,7 +495,7 @@ function connectAbility: void {
You can send a class from one process to another through IPC interfaces. However, you must ensure that the peer can use the code of this class and this class supports the **marshalling** and **unmarshalling** methods. OpenHarmony uses **marshalling** and **unmarshalling** to serialize and deserialize objects into objects that can be identified by each process.
To create a class that supports the sequenceable type, perform the following operations:
**To create a class that supports the sequenceable type, perform the following operations:**
1. Implement the **marshalling** method, which obtains the current state of the object and serializes the object into a **Parcel** object.
2. Implement the **unmarshalling** method, which deserializes the object from a **Parcel** object.
......@@ -595,7 +595,7 @@ export default class IdlTestServiceProxy implements IIdlTestService {
let _reply = new rpc.MessageParcel();
_data.writeInt(data);
this.proxy.sendRequest(IdlTestServiceProxy.COMMAND_TEST_INT_TRANSACTION, _data, _reply, _option).then(function(result) {
if (result.errCode === 0) {
if (result.errCode == 0) {
let _errCode = result.reply.readInt();
if (_errCode != 0) {
let _returnValue = undefined;
......@@ -605,7 +605,7 @@ export default class IdlTestServiceProxy implements IIdlTestService {
let _returnValue = result.reply.readInt();
callback(_errCode, _returnValue);
} else {
console.log("sendRequest failed, errCode: " + result.errCode);
console.log('sendRequest failed, errCode: ' + result.errCode);
}
})
}
......@@ -617,11 +617,11 @@ export default class IdlTestServiceProxy implements IIdlTestService {
let _reply = new rpc.MessageParcel();
_data.writeString(data);
this.proxy.sendRequest(IdlTestServiceProxy.COMMAND_TEST_STRING_TRANSACTION, _data, _reply, _option).then(function(result) {
if (result.errCode === 0) {
if (result.errCode == 0) {
let _errCode = result.reply.readInt();
callback(_errCode);
} else {
console.log("sendRequest failed, errCode: " + result.errCode);
console.log('sendRequest failed, errCode: ' + result.errCode);
}
})
}
......@@ -644,12 +644,12 @@ import nativeMgr from 'nativeManager';
function testIntTransactionCallback(errCode: number, returnValue: number)
{
console.log("errCode: " + errCode + " returnValue: " + returnValue);
console.log('errCode: ' + errCode + ' returnValue: ' + returnValue);
}
function testStringTransactionCallback(errCode: number)
{
console.log("errCode: " + errCode);
console.log('errCode: ' + errCode);
}
function jsProxyTriggerCppStub()
......@@ -660,6 +660,6 @@ function jsProxyTriggerCppStub()
tsProxy.testIntTransaction(10, testIntTransactionCallback);
// Call testStringTransaction.
tsProxy.testStringTransaction("test", testIntTransactionCallback);
tsProxy.testStringTransaction('test', testIntTransactionCallback);
}
```
......@@ -14,20 +14,20 @@ As the entry of the ability continuation capability, **continuationManager** is
## Available APIs
| API | Description|
| ---------------------------------------------------------------------------------------------- | ----------- |
| register(callback: AsyncCallback\<number>): void | Registers the continuation management service and obtains a token. This API does not involve any filter parameters and uses an asynchronous callback to return the result.|
| register(options: ContinuationExtraParams, callback: AsyncCallback\<number>): void | Registers the continuation management service and obtains a token. This API uses an asynchronous callback to return the result.|
| register(options?: ContinuationExtraParams): Promise\<number> | Registers the continuation management service and obtains a token. This API uses a promise to return the result.|
| on(type: "deviceConnect", token: number, callback: Callback\<Array\<ContinuationResult>>): void | Subscribes to device connection events. This API uses an asynchronous callback to return the result.|
| on(type: "deviceDisconnect", token: number, callback: Callback\<Array\<string>>): void | Subscribes to device disconnection events. This API uses an asynchronous callback to return the result.|
| off(type: "deviceConnect", token: number): void | Unsubscribes from device connection events.|
| off(type: "deviceDisconnect", token: number): void | Unsubscribes from device disconnection events.|
| startDeviceManager(token: number, callback: AsyncCallback\<void>): void | Starts the device selection module to show the list of available devices. This API does not involve any filter parameters and uses an asynchronous callback to return the result.|
| startDeviceManager(token: number, options: ContinuationExtraParams, callback: AsyncCallback\<void>): void | Starts the device selection module to show the list of available devices. This API uses an asynchronous callback to return the result.|
| startDeviceManager(token: number, options?: ContinuationExtraParams): Promise\<void> | Starts the device selection module to show the list of available devices. This API uses a promise to return the result.|
| updateConnectStatus(token: number, deviceId: string, status: DeviceConnectState, callback: AsyncCallback\<void>): void | Instructs the device selection module to update the device connection state. This API uses an asynchronous callback to return the result.|
| updateConnectStatus(token: number, deviceId: string, status: DeviceConnectState): Promise\<void> | Instructs the device selection module to update the device connection state. This API uses a promise to return the result.|
| unregister(token: number, callback: AsyncCallback\<void>): void | Deregisters the continuation management service. This API uses an asynchronous callback to return the result.|
| unregister(token: number): Promise\<void> | Deregisters the continuation management service. This API uses a promise to return the result.|
| registerContinuation(callback: AsyncCallback\<number>): void | Registers the continuation management service and obtains a token. This API does not involve any filter parameters and uses an asynchronous callback to return the result.|
| registerContinuation(options: ContinuationExtraParams, callback: AsyncCallback\<number>): void | Registers the continuation management service and obtains a token. This API uses an asynchronous callback to return the result.|
| registerContinuation(options?: ContinuationExtraParams): Promise\<number> | Registers the continuation management service and obtains a token. This API uses a promise to return the result.|
| on(type: "deviceSelected", token: number, callback: Callback\<Array\<ContinuationResult>>): void | Subscribes to device connection events. This API uses an asynchronous callback to return the result.|
| on(type: "deviceUnselected", token: number, callback: Callback\<Array\<ContinuationResult>>): void | Subscribes to device disconnection events. This API uses an asynchronous callback to return the result.|
| off(type: "deviceSelected", token: number): void | Unsubscribes from device connection events.|
| off(type: "deviceUnselected", token: number): void | Unsubscribes from device disconnection events.|
| startContinuationDeviceManager(token: number, callback: AsyncCallback\<void>): void | Starts the device selection module to show the list of available devices. This API does not involve any filter parameters and uses an asynchronous callback to return the result.|
| startContinuationDeviceManager(token: number, options: ContinuationExtraParams, callback: AsyncCallback\<void>): void | Starts the device selection module to show the list of available devices. This API uses an asynchronous callback to return the result.|
| startContinuationDeviceManager(token: number, options?: ContinuationExtraParams): Promise\<void> | Starts the device selection module to show the list of available devices. This API uses a promise to return the result.|
| updateContinuationState(token: number, deviceId: string, status: DeviceConnectState, callback: AsyncCallback\<void>): void | Instructs the device selection module to update the device connection state. This API uses an asynchronous callback to return the result.|
| updateContinuationState(token: number, deviceId: string, status: DeviceConnectState): Promise\<void> | Instructs the device selection module to update the device connection state. This API uses a promise to return the result.|
| unregisterContinuation(token: number, callback: AsyncCallback\<void>): void | Deregisters the continuation management service. This API uses an asynchronous callback to return the result.|
| unregisterContinuation(token: number): Promise\<void> | Deregisters the continuation management service. This API uses a promise to return the result.|
## How to Develop
1. Import the **continuationManager** module.
......@@ -36,7 +36,7 @@ As the entry of the ability continuation capability, **continuationManager** is
import continuationManager from '@ohos.continuation.continuationManager';
```
2. Apply for permissions required for cross-device continuation or collaboration operations.
2. Apply for the **DISTRIBUTED_DATASYNC** permission.
The permission application operation varies according to the ability model in use. In the FA mode, add the required permission in the `config.json` file, as follows:
......@@ -57,6 +57,7 @@ As the entry of the ability continuation capability, **continuationManager** is
```ts
import abilityAccessCtrl from "@ohos.abilityAccessCtrl";
import bundle from '@ohos.bundle';
import featureAbility from '@ohos.ability.featureAbility';
async function requestPermission() {
let permissions: Array<string> = [
......@@ -124,7 +125,8 @@ As the entry of the ability continuation capability, **continuationManager** is
// If the permission is not granted, call requestPermissionsFromUser to apply for the permission.
if (needGrantPermission) {
try {
await globalThis.abilityContext.requestPermissionsFromUser(permissions);
// globalThis.context is Ability.context, which must be assigned a value in the MainAbility.ts file in advance.
await globalThis.context.requestPermissionsFromUser(permissions);
} catch (err) {
console.error('app permission request permissions error' + JSON.stringify(err));
}
......@@ -140,13 +142,16 @@ As the entry of the ability continuation capability, **continuationManager** is
```ts
let token: number = -1; // Used to save the token returned after the registration. The token will be used when listening for device connection/disconnection events, starting the device selection module, and updating the device connection state.
continuationManager.register().then((data) => {
console.info('register finished, ' + JSON.stringify(data));
try {
continuationManager.registerContinuation().then((data) => {
console.info('registerContinuation finished, ' + JSON.stringify(data));
token = data; // Obtain a token and assign a value to the token variable.
}).catch((err) => {
console.error('register failed, cause: ' + JSON.stringify(err));
console.error('registerContinuation failed, cause: ' + JSON.stringify(err));
});
} catch (err) {
console.error('registerContinuation failed, cause: ' + JSON.stringify(err));
}
```
4. Listen for the device connection/disconnection state.
......@@ -156,9 +161,10 @@ As the entry of the ability continuation capability, **continuationManager** is
```ts
let remoteDeviceId: string = ""; // Used to save the information about the remote device selected by the user, which will be used for cross-device continuation or collaboration.
try {
// The token parameter is the token obtained during the registration.
continuationManager.on("deviceConnect", token, (continuationResults) => {
console.info('registerDeviceConnectCallback len: ' + continuationResults.length);
continuationManager.on("deviceSelected", token, (continuationResults) => {
console.info('registerDeviceSelectedCallback len: ' + continuationResults.length);
if (continuationResults.length <= 0) {
console.info('no selected device');
return;
......@@ -171,13 +177,15 @@ As the entry of the ability continuation capability, **continuationManager** is
bundleName: 'ohos.samples.continuationmanager',
abilityName: 'MainAbility'
};
// To initiate multi-device collaboration, you must obtain the ohos.permission.DISTRIBUTED_DATASYNC permission.
globalThis.abilityContext.startAbility(want).then((data) => {
console.info('StartRemoteAbility finished, ' + JSON.stringify(data));
}).catch((err) => {
console.error('StartRemoteAbility failed, cause: ' + JSON.stringify(err));
});
});
} catch (err) {
console.error('on failed, cause: ' + JSON.stringify(err));
}
```
The preceding multi-device collaboration operation is performed across devices in the stage model. For details about this operation in the FA model, see [Page Ability Development](https://gitee.com/openharmony/docs/blob/master/en/application-dev/ability/fa-pageability.md).
......@@ -189,35 +197,43 @@ As the entry of the ability continuation capability, **continuationManager** is
let deviceConnectStatus: continuationManager.DeviceConnectState = continuationManager.DeviceConnectState.CONNECTED;
// The token parameter is the token obtained during the registration, and the remoteDeviceId parameter is the remoteDeviceId obtained.
continuationManager.updateConnectStatus(token, remoteDeviceId, deviceConnectStatus).then((data) => {
console.info('updateConnectStatus finished, ' + JSON.stringify(data));
try {
continuationManager.updateContinuationState(token, remoteDeviceId, deviceConnectStatus).then((data) => {
console.info('updateContinuationState finished, ' + JSON.stringify(data));
}).catch((err) => {
console.error('updateConnectStatus failed, cause: ' + JSON.stringify(err));
console.error('updateContinuationState failed, cause: ' + JSON.stringify(err));
});
} catch (err) {
console.error('updateContinuationState failed, cause: ' + JSON.stringify(err));
}
```
Listen for the device disconnection state so that the user can stop cross-device continuation or collaboration in time. The sample code is as follows:
```ts
try {
// The token parameter is the token obtained during the registration.
continuationManager.on("deviceDisconnect", token, (deviceIds) => {
console.info('onDeviceDisconnect len: ' + deviceIds.length);
if (deviceIds.length <= 0) {
continuationManager.on("deviceUnselected", token, (continuationResults) => {
console.info('onDeviceUnselected len: ' + continuationResults.length);
if (continuationResults.length <= 0) {
console.info('no unselected device');
return;
}
// Update the device connection state.
let unselectedDeviceId: string = deviceIds[0]; // Assign the deviceId of the first deselected remote device to the unselectedDeviceId variable.
let unselectedDeviceId: string = continuationResults[0].id; // Assign the deviceId of the first deselected remote device to the unselectedDeviceId variable.
let deviceConnectStatus: continuationManager.DeviceConnectState = continuationManager.DeviceConnectState.DISCONNECTING; // Device disconnected.
// The token parameter is the token obtained during the registration, and the unselectedDeviceId parameter is the unselectedDeviceId obtained.
continuationManager.updateConnectStatus(token, unselectedDeviceId, deviceConnectStatus).then((data) => {
console.info('updateConnectStatus finished, ' + JSON.stringify(data));
continuationManager.updateContinuationState(token, unselectedDeviceId, deviceConnectStatus).then((data) => {
console.info('updateContinuationState finished, ' + JSON.stringify(data));
}).catch((err) => {
console.error('updateConnectStatus failed, cause: ' + JSON.stringify(err));
console.error('updateContinuationState failed, cause: ' + JSON.stringify(err));
});
});
} catch (err) {
console.error('updateContinuationState failed, cause: ' + JSON.stringify(err));
}
```
5. Start the device selection module to show the list of available devices on the network.
......@@ -231,12 +247,16 @@ As the entry of the ability continuation capability, **continuationManager** is
continuationMode: continuationManager.ContinuationMode.COLLABORATION_SINGLE // Single-choice mode of the device selection module.
};
try {
// The token parameter is the token obtained during the registration.
continuationManager.startDeviceManager(token, continuationExtraParams).then((data) => {
console.info('startDeviceManager finished, ' + JSON.stringify(data));
continuationManager.startContinuationDeviceManager(token, continuationExtraParams).then((data) => {
console.info('startContinuationDeviceManager finished, ' + JSON.stringify(data));
}).catch((err) => {
console.error('startDeviceManager failed, cause: ' + JSON.stringify(err));
console.error('startContinuationDeviceManager failed, cause: ' + JSON.stringify(err));
});
} catch (err) {
console.error('startContinuationDeviceManager failed, cause: ' + JSON.stringify(err));
}
```
6. If you do not need to perform cross-device migration or collaboration operations, you can deregister the continuation management service, by passing the token obtained during the registration.
......@@ -244,10 +264,14 @@ As the entry of the ability continuation capability, **continuationManager** is
The sample code is as follows:
```ts
try {
// The token parameter is the token obtained during the registration.
continuationManager.unregister(token).then((data) => {
console.info('unregister finished, ' + JSON.stringify(data));
continuationManager.unregisterContinuation(token).then((data) => {
console.info('unregisterContinuation finished, ' + JSON.stringify(data));
}).catch((err) => {
console.error('unregister failed, cause: ' + JSON.stringify(err));
console.error('unregisterContinuation failed, cause: ' + JSON.stringify(err));
});
} catch (err) {
console.error('unregisterContinuation failed, cause: ' + JSON.stringify(err));
}
```
......@@ -66,7 +66,7 @@ To learn more about the APIs for obtaining device location information, see [Geo
If your application needs to access the device location information when running on the background, it must be configured to be able to run on the background and be granted the **ohos.permission.LOCATION_IN_BACKGROUND** permission. In this way, the system continues to report device location information after your application moves to the background.
You can declare the required permission in your application's configuration file. For details, see [Application Package Structure Configuration File](../quick-start/stage-structure.md).
You can declare the required permission in your application's configuration file. For details, see [Access Control (Permission) Development](../security/accesstoken-guidelines.md).
2. Import the **geolocation** module by which you can implement all APIs related to the basic location capabilities.
......
# Audio Playback Development
## When to Use
## Introduction
You can use audio playback APIs to convert audio data into audible analog signals, play the signals using output devices, and manage playback tasks.
You can use audio playback APIs to convert audio data into audible analog signals and play the signals using output devices. You can also manage playback tasks. For example, you can start, suspend, stop playback, release resources, set the volume, seek to a playback position, and obtain track information.
**Figure 1** Playback status
## Working Principles
The following figures show the audio playback status changes and the interaction with external modules for audio playback.
**Figure 1** Audio playback state transition
![en-us_image_audio_state_machine](figures/en-us_image_audio_state_machine.png)
**Note**: If the status is **Idle**, setting the **src** attribute does not change the status. In addition, after the **src** attribute is set successfully, you must call **reset()** before setting it to another value.
**NOTE**: If the status is **Idle**, setting the **src** attribute does not change the status. In addition, after the **src** attribute is set successfully, you must call **reset()** before setting it to another value.
**Figure 2** Layer 0 diagram of audio playback
**Figure 2** Interaction with external modules for audio playback
![en-us_image_audio_player](figures/en-us_image_audio_player.png)
**NOTE**: When a third-party application calls the JS interface provided by the JS interface layer to implement a feature, the framework layer invokes the audio component through the media service of the native framework and outputs the audio data decoded by the software to the audio HDI of the hardware interface layer to implement audio playback.
## How to Develop
For details about the APIs, see [AudioPlayer in the Media API](../reference/apis/js-apis-media.md#audioplayer).
> **NOTE**
>
> The method for obtaining the path in the FA model is different from that in the stage model. **pathDir** used in the sample code below is an example. You need to obtain the path based on project requirements. For details about how to obtain the path, see [Application Sandbox Path Guidelines](../reference/apis/js-apis-fileio.md#guidelines).
### Full-Process Scenario
The full audio playback process includes creating an instance, setting the URI, playing audio, seeking to the playback position, setting the volume, pausing playback, obtaining track information, stopping playback, resetting the player, and releasing resources.
......@@ -99,8 +109,9 @@ async function audioPlayerDemo() {
setCallBack(audioPlayer); // Set the event callbacks.
// 2. Set the URI of the audio file.
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/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile" command.
let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile/01.mp3';
let pathDir = "/data/storage/el2/base/haps/entry/files" // The method for obtaining pathDir in the FA model is different from that in the stage model. For details, see NOTE just below How to Develop. You need to obtain pathDir based on project requirements.
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command.
let path = pathDir + '/01.mp3'
await fileIO.open(path).then((fdNumber) => {
fdPath = fdPath + '' + fdNumber;
console.info('open fd success fd is' + fdPath);
......@@ -118,6 +129,7 @@ async function audioPlayerDemo() {
```js
import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio'
export class AudioDemo {
// Set the player callbacks.
setCallBack(audioPlayer) {
......@@ -139,8 +151,9 @@ export class AudioDemo {
let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance.
this.setCallBack(audioPlayer); // Set the event callbacks.
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/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile" command.
let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile/01.mp3';
let pathDir = "/data/storage/el2/base/haps/entry/files" // The method for obtaining pathDir in the FA model is different from that in the stage model. For details, see NOTE just below How to Develop. You need to obtain pathDir based on project requirements.
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command.
let path = pathDir + '/01.mp3'
await fileIO.open(path).then((fdNumber) => {
fdPath = fdPath + '' + fdNumber;
console.info('open fd success fd is' + fdPath);
......@@ -159,6 +172,7 @@ export class AudioDemo {
```js
import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio'
export class AudioDemo {
// Set the player callbacks.
private isNextMusic = false;
......@@ -185,8 +199,9 @@ export class AudioDemo {
async nextMusic(audioPlayer) {
this.isNextMusic = true;
let nextFdPath = 'fd://'
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\02.mp3 /data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile" command.
let nextpath = '/data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile/02.mp3';
let pathDir = "/data/storage/el2/base/haps/entry/files" // The method for obtaining pathDir in the FA model is different from that in the stage model. For details, see NOTE just below How to Develop. You need to obtain pathDir based on project requirements.
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\02.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command.
let nextpath = pathDir + '/02.mp3'
await fileIO.open(nextpath).then((fdNumber) => {
nextFdPath = nextFdPath + '' + fdNumber;
console.info('open fd success fd is' + nextFdPath);
......@@ -202,8 +217,9 @@ export class AudioDemo {
let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance.
this.setCallBack(audioPlayer); // Set the event callbacks.
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/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile" command.
let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile/01.mp3';
let pathDir = "/data/storage/el2/base/haps/entry/files" // The method for obtaining pathDir in the FA model is different from that in the stage model. For details, see NOTE just below How to Develop. You need to obtain pathDir based on project requirements.
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command.
let path = pathDir + '/01.mp3'
await fileIO.open(path).then((fdNumber) => {
fdPath = fdPath + '' + fdNumber;
console.info('open fd success fd is' + fdPath);
......@@ -222,6 +238,7 @@ export class AudioDemo {
```js
import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio'
export class AudioDemo {
// Set the player callbacks.
setCallBack(audioPlayer) {
......@@ -239,8 +256,9 @@ export class AudioDemo {
let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance.
this.setCallBack(audioPlayer); // Set the event callbacks.
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/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile" command.
let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile/01.mp3';
let pathDir = "/data/storage/el2/base/haps/entry/files" // The method for obtaining pathDir in the FA model is different from that in the stage model. For details, see NOTE just below How to Develop. You need to obtain pathDir based on project requirements.
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command.
let path = pathDir + '/01.mp3'
await fileIO.open(path).then((fdNumber) => {
fdPath = fdPath + '' + fdNumber;
console.info('open fd success fd is' + fdPath);
......
# Audio Recording Development
## When to Use
## Introduction
During audio recording, audio signals are captured, encoded, and saved to files. You can specify parameters such as the sampling rate, number of audio channels, encoding format, encapsulation format, and file path for audio recording.
During audio recording, audio signals are captured, encoded, and saved to files. You can specify parameters such as the sampling rate, number of audio channels, encoding format, encapsulation format, and output file path for audio recording.
## Working Principles
The following figures show the audio recording state transition and the interaction with external modules for audio recording.
**Figure 1** Audio recording state transition
......@@ -10,10 +14,16 @@ During audio recording, audio signals are captured, encoded, and saved to files.
**Figure 2** Layer 0 diagram of audio recording
**Figure 2** Interaction with external modules for audio recording
![en-us_image_audio_recorder_zero](figures/en-us_image_audio_recorder_zero.png)
**NOTE**: When a third-party recording application or recorder calls the JS interface provided by the JS interface layer to implement a feature, the framework layer invokes the audio component through the media service of the native framework to obtain the audio data captured through the audio HDI. The framework layer then encodes the audio data through software and saves the encoded and encapsulated audio data to a file to implement audio recording.
## Constraints
Before developing audio recording, configure the **ohos.permission.MICROPHONE** permission for your application. For details about the configuration, see [Permission Application Guide](../security/accesstoken-guidelines.md).
## How to Develop
For details about the APIs, see [AudioRecorder in the Media API](../reference/apis/js-apis-media.md#audiorecorder).
......
此差异已折叠。
# Video Playback Development
## When to Use
## Introduction
You can use video playback APIs to convert video data into visible signals, play the signals using output devices, and manage playback tasks. This document describes development for the following video playback scenarios: full-process, normal playback, video switching, and loop playback.
You can use video playback APIs to convert audio data into audible analog signals and play the signals using output devices. You can also manage playback tasks. For example, you can start, suspend, stop playback, release resources, set the volume, seek to a playback position, set the playback speed, and obtain track information. This document describes development for the following video playback scenarios: full-process, normal playback, video switching, and loop playback.
## Working Principles
The following figures show the video playback state transition and the interaction with external modules for video playback.
**Figure 1** Video playback state transition
![en-us_image_video_state_machine](figures/en-us_image_video_state_machine.png)
**Figure 2** Layer 0 diagram of video playback
**Figure 2** Interaction with external modules for video playback
![en-us_image_video_player](figures/en-us_image_video_player.png)
**NOTE**: When a third-party application calls a JS interface provided by the JS interface layer, the framework layer invokes the audio component through the media service of the native framework to output the audio data decoded by the software to the audio HDI. The graphics subsystem outputs the image data decoded by the codec HDI at the hardware interface layer to the display HDI. In this way, video playback is implemented.
*Note: Video playback requires hardware capabilities such as display, audio, and codec.*
1. A third-party application obtains a surface ID from the XComponent.
......
# Video Recording Development
## When to Use
## Introduction
During video recording, audio and video signals are captured, encoded, and saved to files. You can specify parameters such as the encoding format, encapsulation format, and file path for video recording.
You can use video recording APIs to capture audio and video signals, encode them, and save them to files. You can start, suspend, resume, and stop recording, and release resources. You can also specify parameters such as the encoding format, encapsulation format, and file path for video recording.
## Working Principles
The following figures show the video recording state transition and the interaction with external modules for video recording.
**Figure 1** Video recording state transition
![en-us_image_video_recorder_state_machine](figures/en-us_image_video_recorder_state_machine.png)
**Figure 2** Layer 0 diagram of video recording
**Figure 2** Interaction with external modules for video recording
![en-us_image_video_recorder_zero](figures/en-us_image_video_recorder_zero.png)
**NOTE**: When a third-party camera application or system camera calls a JS interface provided by the JS interface layer, the framework layer uses the media service of the native framework to invoke the audio component. Through the audio HDI, the audio component captures audio data, encodes the audio data through software, and saves the encoded audio data to a file. The graphics subsystem captures image data through the video HDI, encodes the image data through the video codec HDI, and saves the encoded image data to a file. In this way, video recording is implemented.
## Constraints
Before developing video recording, configure the permissions **ohos.permission.MICROPHONE** and **ohos.permission.CAMERA** for your application. For details about the configuration, see [Permission Application Guide](../security/accesstoken-guidelines.md).
## How to Develop
For details about the APIs, see [VideoRecorder in the Media API](../reference/apis/js-apis-media.md#videorecorder9).
......@@ -147,3 +157,4 @@ export class VideoRecorderDemo {
}
}
```
# Rendering Control
ArkTS provides conditional rendering and loop rendering. Conditional rendering can render state-specific UI content based on the application status. Loop rendering iteratively obtains data from the data source and creates the corresponding component during each iteration.
## Conditional Rendering
Use **if/else** for conditional rendering.
> **NOTE**
>
> - State variables can be used in the **if/else** statement.
>
> - The **if/else** statement can be used to implement rendering of child components.
>
> - The **if/else** statement must be used in container components.
>
> - Some container components limit the type or number of subcomponents. When **if/else** is placed in these components, the limitation applies to components created in **if/else** statements. For example, when **if/else** is used in the **\<Grid>** container component, whose child components can only be **\<GridItem>**, only the **\<GridItem>** component can be used in the **if/else** statement.
```ts
Column() {
if (this.count < 0) {
Text('count is negative').fontSize(14)
} else if (this.count % 2 === 0) {
Text('count is even').fontSize(14)
} else {
Text('count is odd').fontSize(14)
}
}
```
## Loop Rendering
You can use **ForEach** to obtain data from arrays and create components for each data item.
```
ForEach(
arr: any[],
itemGenerator: (item: any, index?: number) => void,
keyGenerator?: (item: any, index?: number) => string
)
```
**Parameters**
| Name | Type | Mandatory| Description |
| ------------- | ------------------------------------- | ---- | ------------------------------------------------------------ |
| arr | any[] | Yes | An array, which can be empty, in which case no child component is created. The functions that return array-type values are also allowed, for example, **arr.slice (1, 3)**. The set functions cannot change any state variables including the array itself, such as **Array.splice**, **Array.sort**, and **Array.reverse**.|
| itemGenerator | (item: any, index?: number) => void | Yes | A lambda function used to generate one or more child components for each data item in an array. A single child component or a list of child components must be included in parentheses.|
| keyGenerator | (item: any, index?: number) => string | No | An anonymous function used to generate a unique and fixed key value for each data item in an array. This key value must remain unchanged for the data item even when the item is relocated in the array. When the item is replaced by a new item, the key value of the new item must be different from that of the existing item. This key-value generator is optional. However, for performance reasons, it is strongly recommended that the key-value generator be provided, so that the development framework can better identify array changes. For example, if no key-value generator is provided, a reverse of an array will result in rebuilding of all nodes in **ForEach**.|
> **NOTE**
>
> - **ForEach** must be used in container components.
>
> - The generated child components should be allowed in the parent container component of **ForEach**.
>
> - The **itemGenerator** function can contain an **if/else** statement, and an **if/else** statement can contain **ForEach**.
>
> - The call sequence of **itemGenerator** functions may be different from that of the data items in the array. During the development, do not assume whether or when the **itemGenerator** and **keyGenerator** functions are executed. The following is an example of incorrect usage:
>
> ```ts
> ForEach(anArray.map((item1, index1) => { return { i: index1 + 1, data: item1 }; }),
> item => Text(`${item.i}. item.data.label`),
> item => item.data.id.toString())
> ```
## Example
```ts
// xxx.ets
@Entry
@Component
struct MyComponent {
@State arr: number[] = [10, 20, 30]
build() {
Column({ space: 5 }) {
Button('Reverse Array')
.onClick(() => {
this.arr.reverse()
})
ForEach(this.arr, (item: number) => {
Text(`item value: ${item}`).fontSize(18)
Divider().strokeWidth(2)
}, (item: number) => item.toString())
}
}
}
```
![forEach1](figures/forEach1.gif)
## Lazy Loading
You can use **LazyForEach** to iterate over provided data sources and create corresponding components during each iteration.
```ts
LazyForEach(
dataSource: IDataSource,
itemGenerator: (item: any) => void,
keyGenerator?: (item: any) => string
): void
interface IDataSource {
totalCount(): number;
getData(index: number): any;
registerDataChangeListener(listener: DataChangeListener): void;
unregisterDataChangeListener(listener: DataChangeListener): void;
}
interface DataChangeListener {
onDataReloaded(): void;
onDataAdd(index: number): void;
onDataMove(from: number, to: number): void;
onDataDelete(index: number): void;
onDataChange(index: number): void;
}
```
**Parameters**
| Name | Type | Mandatory| Description |
| ------------- | --------------------- | ---- | ------------------------------------------------------------ |
| dataSource | IDataSource | Yes | Object used to implement the **IDataSource** API. You need to implement related APIs. |
| itemGenerator | (item: any) => void | Yes | A lambda function used to generate one or more child components for each data item in an array. A single child component or a list of child components must be included in parentheses.|
| keyGenerator | (item: any) => string | No | An anonymous function used to generate a unique and fixed key value for each data item in an array. This key value must remain unchanged for the data item even when the item is relocated in the array. When the item is replaced by a new item, the key value of the new item must be different from that of the existing item. This key-value generator is optional. However, for performance reasons, it is strongly recommended that the key-value generator be provided, so that the development framework can better identify array changes. For example, if no key-value generator is provided, a reverse of an array will result in rebuilding of all nodes in **LazyForEach**.|
### Description of IDataSource
| Name | Description |
| ------------------------------------------------------------ | ---------------------- |
| totalCount(): number | Obtains the total number of data records. |
| getData(index: number): any | Obtains the data corresponding to the specified index. |
| registerDataChangeListener(listener:DataChangeListener): void | Registers a listener for data changes.|
| unregisterDataChangeListener(listener:DataChangeListener): void | Deregisters a listener for data changes.|
### Description of DataChangeListener
| Name | Description |
| -------------------------------------------------------- | -------------------------------------- |
| onDataReloaded(): void | Invoked when all data is reloaded. |
| onDataAdded(index: number): void (deprecated) | Invoked when data is added to the position indicated by the specified index. |
| onDataMoved(from: number, to: number): void (deprecated) | Invoked when data is moved from the **from** position to the **to** position.|
| onDataDeleted(index: number): void (deprecated) | Invoked when data is deleted from the position indicated by the specified index. |
| onDataChanged(index: number): void (deprecated) | Invoked when data in the position indicated by the specified index is changed. |
| onDataAdd(index: number): void 8+ | Invoked when data is added to the position indicated by the specified index. |
| onDataMove(from: number, to: number): void 8+ | Invoked when data is moved from the **from** position to the **to** position.|
| onDataDelete(index: number): void 8+ | Invoked when data is deleted from the position indicated by the specified index. |
| onDataChange(index: number): void 8+ | Invoked when data in the position indicated by the specified index is changed. |
## Example
```ts
// xxx.ets
class BasicDataSource implements IDataSource {
private listeners: DataChangeListener[] = []
public totalCount(): number {
return 0
}
public getData(index: number): any {
return undefined
}
registerDataChangeListener(listener: DataChangeListener): void {
if (this.listeners.indexOf(listener) < 0) {
console.info('add listener')
this.listeners.push(listener)
}
}
unregisterDataChangeListener(listener: DataChangeListener): void {
const pos = this.listeners.indexOf(listener);
if (pos >= 0) {
console.info('remove listener')
this.listeners.splice(pos, 1)
}
}
notifyDataReload(): void {
this.listeners.forEach(listener => {
listener.onDataReloaded()
})
}
notifyDataAdd(index: number): void {
this.listeners.forEach(listener => {
listener.onDataAdd(index)
})
}
notifyDataChange(index: number): void {
this.listeners.forEach(listener => {
listener.onDataChange(index)
})
}
notifyDataDelete(index: number): void {
this.listeners.forEach(listener => {
listener.onDataDelete(index)
})
}
notifyDataMove(from: number, to: number): void {
this.listeners.forEach(listener => {
listener.onDataMove(from, to)
})
}
}
class MyDataSource extends BasicDataSource {
// Initialize the data list.
private dataArray: string[] = ['/path/image0.png', '/path/image1.png', '/path/image2.png', '/path/image3.png']
public totalCount(): number {
return this.dataArray.length
}
public getData(index: number): any {
return this.dataArray[index]
}
public addData(index: number, data: string): void {
this.dataArray.splice(index, 0, data)
this.notifyDataAdd(index)
}
public pushData(data: string): void {
this.dataArray.push(data)
this.notifyDataAdd(this.dataArray.length - 1)
}
}
@Entry
@Component
struct MyComponent {
private data: MyDataSource = new MyDataSource()
build() {
List({ space: 3 }) {
LazyForEach(this.data, (item: string) => {
ListItem() {
Row() {
Image(item).width(50).height(50)
Text(item).fontSize(20).margin({ left: 10 })
}.margin({ left: 10, right: 10 })
}
.onClick(() => {
// The count increases by one each time the list is clicked.
this.data.pushData('/path/image' + this.data.totalCount() + '.png')
})
}, item => item)
}
}
}
```
> **NOTE**
>
> - **LazyForEach** must be used in the container component. Currently, only the **\<List>**, **\<Grid>**, and **\<Swiper>** components support lazy loading (that is, only the visible part and a small amount of data before and after the visible part are loaded for caching). For other components, all data is loaded at a time.
>
> - **LazyForEach** must create and only one child component in each iteration.
>
> - The generated child components must be allowed in the parent container component of **LazyForEach**.
>
> - **LazyForEach** can be included in an **if/else** statement, but cannot contain such a statement.
>
> - For the purpose of high-performance rendering, when the **onDataChange** method of the **DataChangeListener** object is used to update the UI, the component update is triggered only when the state variable is used in the child component created by **itemGenerator**.
>
> - The call sequence of **itemGenerator** functions may be different from that of the data items in the data source. During the development, do not assume whether or when the **itemGenerator** and **keyGenerator** functions are executed. The following is an example of incorrect usage:
>
> ```ts
> LazyForEach(dataSource,
> item => Text(`${item.i}. item.data.label`)),
> item => item.data.id.toString())
> ```
![lazyForEach](figures/lazyForEach.gif)
......@@ -45,6 +45,7 @@
- [@ohos.application.formInfo](js-apis-formInfo.md)
- [@ohos.application.formProvider](js-apis-formprovider.md)
- [@ohos.application.missionManager](js-apis-missionManager.md)
- [@ohos.application.quickFixManager](js-apis-application-quickFixManager.md)
- [@ohos.application.Want](js-apis-application-Want.md)
- [@ohos.continuation.continuationManager](js-apis-continuation-continuationExtraParams.md)
- [@ohos.continuation.continuationManager](js-apis-continuation-continuationManager.md)
......@@ -90,8 +91,8 @@
- UI Page
- [@ohos.animator](js-apis-animator.md)
- [@ohos.mediaquery](js-apis-mediaquery.md)
- [@ohos.promptAction](js-apis-promptAction.md)
- [@ohos.router](js-apis-router.md)
- [@ohos.uiAppearance](js-apis-uiappearance.md)
- Graphics
- [@ohos.animation.windowAnimationManager](js-apis-windowAnimationManager.md)
- [@ohos.display ](js-apis-display.md)
......@@ -146,6 +147,7 @@
- [@ohos.document](js-apis-document.md)
- [@ohos.environment](js-apis-environment.md)
- [@ohos.fileio](js-apis-fileio.md)
- [@ohos.filemanagement.userfile_manager](js-apis-userfilemanager.md)
- [@ohos.multimedia.medialibrary](js-apis-medialibrary.md)
- [@ohos.securityLabel](js-apis-securityLabel.md)
- [@ohos.statfs](js-apis-statfs.md)
......@@ -213,6 +215,7 @@
- [@ohos.geolocation](js-apis-geolocation.md)
- [@ohos.multimodalInput.inputConsumer](js-apis-inputconsumer.md)
- [@ohos.multimodalInput.inputDevice](js-apis-inputdevice.md)
- [@ohos.multimodalInput.inputDeviceCooperate](js-apis-cooperate.md)
- [@ohos.multimodalInput.inputEvent](js-apis-inputevent.md)
- [@ohos.multimodalInput.inputEventClient](js-apis-inputeventclient.md)
- [@ohos.multimodalInput.inputMonitor](js-apis-inputmonitor.md)
......@@ -261,6 +264,7 @@
- [@ohos.application.testRunner](js-apis-testRunner.md)
- [@ohos.uitest](js-apis-uitest.md)
- APIs No Longer Maintained
- [@ohos.bundleState](js-apis-deviceUsageStatistics.md)
- [@ohos.bytrace](js-apis-bytrace.md)
- [@ohos.data.storage](js-apis-data-storage.md)
- [@ohos.data.distributedData](js-apis-distributed-data.md)
......
# quickFixManager
The **quickFixManager** module provides APIs for quick fix. With quick fix, you can fix bugs in your application by applying patches, which is more efficient than by updating the entire 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
```
import quickFixManager from '@ohos.application.quickFixManager';
```
## HapModuleQuickFixInfo
Defines the quick fix information at the HAP file level.
**System capability**: SystemCapability.Ability.AbilityRuntime.QuickFix
**System API**: This is a system API and cannot be called by third-party applications.
| Name | Readable/Writable| Type | Mandatory| Description |
| ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ |
| moduleName | Read only | string | Yes | Name of the HAP file. |
| originHapHash | Read only | string | Yes | Hash value of the HAP file. |
| quickFixFilePath | Read only | string | Yes | Installation path of the quick fix file. |
## ApplicationQuickFixInfo
Defines the quick fix information at the application level.
**System capability**: SystemCapability.Ability.AbilityRuntime.QuickFix
**System API**: This is a system API and cannot be called by third-party applications.
| Name | Readable/Writable| Type | Mandatory| Description |
| ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ |
| bundleName | Read only | string | Yes | Bundle name of the application. |
| bundleVersionCode | Read only | number | Yes | Internal version number of the application. |
| bundleVersionName | Read only | string | Yes | Version number of the application that is shown to users. |
| quickFixVersionCode | Read only | number | Yes | Version code of the quick fix patch package. |
| quickFixVersionName | Read only | string | Yes | Text description of the version number of the quick fix patch package. |
| hapModuleQuickFixInfo | Read only | Array\<[HapModuleQuickFixInfo](#hapmodulequickfixinfo)> | Yes | Quick fix information at the HAP file level. |
## quickFixManager.applyQuickFix
applyQuickFix(hapModuleQuickFixFiles: Array\<string>, callback: AsyncCallback\<void>): void;
Applies a quick fix patch. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.INSTALL_BUNDLE
**System capability**: SystemCapability.Ability.AbilityRuntime.QuickFix
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Parameter| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| hapModuleQuickFixFiles | Array\<string> | No| Quick fix files, each of which must contain a valid file path.|
| callback | AsyncCallback\<void> | No| Callback used to return the result.|
**Example**
```js
import quickFixManager from '@ohos.application.quickFixManager'
let hapModuleQuickFixFiles = ["/data/storage/el2/base/entry.hqf"]
quickFixManager.applyQuickFix(hapModuleQuickFixFiles, (error) => {
if (error) {
console.info( `applyQuickFix failed with error + ${error}`)
} else {
console.info( 'applyQuickFix success')
}
})
```
## quickFixManager.applyQuickFix
applyQuickFix(hapModuleQuickFixFiles: Array\<string>): Promise\<void>;
Applies a quick fix patch. This API uses a promise to return the result.
**Required permissions**: ohos.permission.INSTALL_BUNDLE
**System capability**: SystemCapability.Ability.AbilityRuntime.QuickFix
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Parameter| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| hapModuleQuickFixFiles | Array\<string> | No| Quick fix files, each of which must contain a valid file path.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise\<void> | Promise used to return the result.|
**Example**
```js
import quickFixManager from '@ohos.application.quickFixManager'
let hapModuleQuickFixFiles = ["/data/storage/el2/base/entry.hqf"]
quickFixManager.applyQuickFix(hapModuleQuickFixFiles).then(() => {
console.info('applyQuickFix success')
}).catch((error) => {
console.info(`applyQuickFix err: + ${error}`)
})
```
## quickFixManager.getApplicationQuickFixInfo
getApplicationQuickFixInfo(bundleName: string, callback: AsyncCallback\<ApplicationQuickFixInfo>): void;
Obtains the quick fix information of the application. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
**System capability**: SystemCapability.Ability.AbilityRuntime.QuickFix
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Parameter| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| bundleName | string | No|Bundle name of the application. |
| callback | AsyncCallback\<[ApplicationQuickFixInfo](#applicationquickfixinfo)> | No| Callback used to return the quick fix information.|
**Example**
```js
import quickFixManager from '@ohos.application.quickFixManager'
let bundleName = "bundleName"
quickFixManager.getApplicationQuickFixInfo(bundleName, (error, data) => {
if (error) {
console.info(`getApplicationQuickFixInfo error: + ${error}`)
} else {
console.info(`getApplicationQuickFixInfo success: + ${data}`)
}
})
```
## quickFixManager.getApplicationQuickFixInfo
getApplicationQuickFixInfo(bundleName: string): Promise\<ApplicationQuickFixInfo>;
Obtains the quick fix information of the application. This API uses a promise to return the result.
**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
**System capability**: SystemCapability.Ability.AbilityRuntime.QuickFix
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Parameter| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| bundleName | string | No| Bundle name of the application. |
**Return value**
| Type| Description|
| -------- | -------- |
| Promise\<[ApplicationQuickFixInfo](#applicationquickfixinfo)> | Promise used to return the quick fix information.|
**Example**
```js
import quickFixManager from '@ohos.application.quickFixManager'
let bundleName = "bundleName"
quickFixManager.getApplicationQuickFixInfo(bundleName).then((data) => {
console.info(`getApplicationQuickFixInfo success: + ${data}`)
}).catch((error) => {
console.info(`getApplicationQuickFixInfo err: + ${error}`)
})
```
......@@ -796,7 +796,7 @@ call.reject(rejectMessageOptions, (err, data) => {
## call.reject<sup>7+</sup>
reject(callId: number, callback: AsyncCallback<void\>): <void\>
reject(callId: number, callback: AsyncCallback\<void>): void
Rejects a call based on the specified call ID. This API uses an asynchronous callback to return the result.
......@@ -811,16 +811,11 @@ This is a system API.
| callId | number | Yes | Call ID. You can obtain the value by subscribing to **callDetailsChange** events.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result. |
**Return value**
| Type | Description |
| ------------------- | --------------------------- |
| Promise&lt;void&gt; | Promise used to return the result.|
**Example**
```js
call.reject(1, (error, data) => {
call.reject(1, (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
});
```
......@@ -1621,8 +1616,8 @@ This is a system API.
**Example**
```js
call.on('callDetailsChange', (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
call.on('callDetailsChange', data => {
console.log(`callback: data->${JSON.stringify(data)}`);
});
```
......@@ -1646,8 +1641,8 @@ This is a system API.
**Example**
```js
call.on('callEventChange', (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
call.on('callEventChange', data => {
console.log(`callback: data->${JSON.stringify(data)}`);
});
```
......@@ -1671,8 +1666,8 @@ This is a system API.
**Example**
```js
call.on('callDisconnectedCause', (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
call.on('callDisconnectedCause', data => {
console.log(`callback: data->${JSON.stringify(data)}`);
});
```
......@@ -1696,8 +1691,8 @@ This is a system API.
**Example**
```js
call.on('mmiCodeResult', (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
call.on('mmiCodeResult', data => {
console.log(`callback: data->${JSON.stringify(data)}`);
});
```
......@@ -1721,8 +1716,8 @@ This is a system API.
**Example**
```js
call.off('callDetailsChange', (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
call.off('callDetailsChange', data => {
console.log(`callback: data->${JSON.stringify(data)}`);
});
```
......@@ -1746,8 +1741,8 @@ This is a system API.
**Example**
```js
call.off('callEventChange', (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
call.off('callEventChange', data => {
console.log(`callback: data->${JSON.stringify(data)}`);
});
```
......@@ -1771,8 +1766,8 @@ This is a system API.
**Example**
```js
call.off('callDisconnectedCause', (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
call.off('callDisconnectedCause', data => {
console.log(`callback: data->${JSON.stringify(data)}`);
});
```
......@@ -1796,8 +1791,8 @@ This is a system API.
**Example**
```js
call.off('mmiCodeResult', (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
call.off('mmiCodeResult', data => {
console.log(`callback: data->${JSON.stringify(data)}`);
});
```
......@@ -2386,7 +2381,7 @@ This is a system API.
let audioDeviceOptions={
bluetoothAddress: "IEEE 802-2014"
}
call.setAudioDevice(1, audioDeviceOptions, (err, value) => {
call.setAudioDevice(1, audioDeviceOptions, (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
});
```
......
# Configuration Policy
The configuration policy provides the capability of obtaining the custom configuration directory and file path based on the predefined custom configuration level.
The **configPolicy** module provides APIs for obtaining the custom configuration directory and file path based on the predefined custom configuration level.
> **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.
>
> The APIs of this module are system APIs and cannot be called by third-party applications.
> The APIs provided by this module are system APIs.
## Modules to Import
......@@ -32,7 +32,7 @@ For example, if the **config.xml** file is stored in **/system/etc/config.xml**
**Example**
```js
configPolicy.getOneCfgFile('etc/config.xml', (error, value) => {
if (error == undefined) {
if (error == null) {
console.log("value is " + value);
} else {
console.log("error occurs "+ error);
......@@ -73,7 +73,8 @@ Obtains the path of a configuration file with the specified name and highest pri
getCfgFiles(relPath: string, callback: AsyncCallback&lt;Array&lt;string&gt;&gt;)
Obtains all configuration files with the specified name and lists them in ascending order of priority. This API uses an asynchronous callback to return the result. For example, if the **config.xml** file is stored in **/system/etc/config.xml** and **/sys_pod/etc/config.xml**, then **/system/etc/config.xml, /sys_pod/etc/config.xml** is returned.
Obtains a list of configuration files with the specified name, sorted in ascending order of priority. This API uses an asynchronous callback to return the result.
For example, if the **config.xml** file is stored in **/system/etc/config.xml** and **/sys_pod/etc/config.xml** (in ascending order of priority), then **/system/etc/config.xml, /sys_pod/etc/config.xml** is returned.
**System capability**: SystemCapability.Customization.ConfigPolicy
......@@ -86,7 +87,7 @@ Obtains all configuration files with the specified name and lists them in ascend
**Example**
```js
configPolicy.getCfgFiles('etc/config.xml', (error, value) => {
if (error == undefined) {
if (error == null) {
console.log("value is " + value);
} else {
console.log("error occurs "+ error);
......@@ -99,7 +100,7 @@ Obtains all configuration files with the specified name and lists them in ascend
getCfgFiles(relPath: string): Promise&lt;Array&lt;string&gt;&gt;
Obtains all configuration files with the specified name and lists them in ascending order of priority. This API uses a promise to return the result.
Obtains a list of configuration files with the specified name, sorted in ascending order of priority. This API uses a promise to return the result.
**System capability**: SystemCapability.Customization.ConfigPolicy
......@@ -127,7 +128,7 @@ Obtains all configuration files with the specified name and lists them in ascend
getCfgDirList(callback: AsyncCallback&lt;Array&lt;string&gt;&gt;)
Obtains the configuration level directory list. This API uses an asynchronous callback to return the result.
Obtains the list of configuration level directories. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Customization.ConfigPolicy
......@@ -139,7 +140,7 @@ Obtains the configuration level directory list. This API uses an asynchronous ca
**Example**
```js
configPolicy.getCfgDirList((error, value) => {
if (error == undefined) {
if (error == null) {
console.log("value is " + value);
} else {
console.log("error occurs "+ error);
......@@ -152,7 +153,7 @@ Obtains the configuration level directory list. This API uses an asynchronous ca
getCfgDirList(): Promise&lt;Array&lt;string&gt;&gt;
Obtains the configuration level directory list. This API uses a promise to return the result.
Obtains the list of configuration level directories. This API uses a promise to return the result.
**System capability**: SystemCapability.Customization.ConfigPolicy
......
# Screen Hopping
The Screen Hopping module enables two or more networked devices to share the keyboard and mouse for collaborative operations.
> **Description**
>
> 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
```js
import inputDeviceCooperate from '@ohos.multimodalInput.inputDeviceCooperate'
```
## inputDeviceCooperate.enable
enable(enable: boolean, callback: AsyncCallback&lt;void&gt;): void
Specifies whether to enable screen hopping. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.MultimodalInput.Input.InputDeviceCooperate
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ------------------------- | ---- | --------------------------- |
| enable | boolean | Yes | Whether to enable screen hopping.|
| callback | AsyncCallback&lt;void&gt; | Yes |Callback used to return the result. |
**Example**
```js
try {
inputDeviceCooperate.enable(true, (error) => {
if (error) {
console.log(`Keyboard mouse crossing enable failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
return;
}
console.log(`Keyboard mouse crossing enable success.`);
});
} catch (error) {
console.log(`Keyboard mouse crossing enable failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
}
```
## inputDeviceCooperate.enable
enable(enable: boolean): Promise&lt;void&gt;
Specifies whether to enable screen hopping. This API uses a promise to return the result.
**System capability**: SystemCapability.MultimodalInput.Input.InputDeviceCooperate
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ------- | ---- | ------------------------------------------------------------------- |
| enable | boolean | Yes | Whether to enable screen hopping. |
**Return value**
| Name | Description |
| ------------------- | ------------------------------- |
| Promise&lt;void&gt; | Promise used to return the result. |
**Example**
```js
try {
inputDeviceCooperate.enable(true).then(() => {
console.log(`Keyboard mouse crossing enable success.`);
}, (error) => {
console.log(`Keyboard mouse crossing enable failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
});
} catch (error) {
console.log(`Keyboard mouse crossing enable failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
}
```
## inputDeviceCooperate.start
start(sinkDeviceDescriptor: string, srcInputDeviceId: number, callback: AsyncCallback\<void>): void
Starts screen hopping. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.MultimodalInput.Input.InputDeviceCooperate
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------------- | ---- | ---------------------------- |
| sinkDeviceDescriptor | string | Yes | Descriptor of the target device for screen hopping. |
| srcInputDeviceId | number | Yes | ID of the target device for screen hopping. |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.|
**Error codes**
For details about the error codes, see [Screen Hopping Error Codes](../errorcodes/errorcodes-multimodalinput.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 4400001 | This error code is reported if an invalid device descriptor is passed to the screen hopping API. |
| 4400002 | This error code is reported if the screen hopping status is abnormal when the screen hopping API is called. |
**Example**
```js
try {
inputDeviceCooperate.start(sinkDeviceDescriptor, srcInputDeviceId, (error) => {
if (error) {
console.log(`Start Keyboard mouse crossing failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
return;
}
console.log(`Start Keyboard mouse crossing success.`);
});
} catch (error) {
console.log(`Start Keyboard mouse crossing failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
}
```
## inputDeviceCooperate.start
start(sinkDeviceDescriptor: string, srcInputDeviceId: number): Promise\<void>
Starts screen hopping. This API uses a promise to return the result.
**System capability**: SystemCapability.MultimodalInput.Input.InputDeviceCooperate
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------------- | ---- | ---------------------------- |
| sinkDeviceDescriptor | string | Yes | Descriptor of the target device for screen hopping. |
| srcInputDeviceId | number | Yes | ID of the target device for screen hopping. |
**Return value**
| Name | Description |
| ---------------------- | ------------------------------- |
| Promise\<void> | Promise used to return the result. |
**Error codes**
For details about the error codes, see [Screen Hopping Error Codes](../errorcodes/errorcodes-multimodalinput.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 4400001 | This error code is reported if an invalid device descriptor is passed to the screen hopping API. |
| 4400002 | This error code is reported if the screen hopping status is abnormal when the screen hopping API is called. |
**Example**
```js
try {
inputDeviceCooperate.start(sinkDeviceDescriptor, srcInputDeviceId).then(() => {
console.log(`Start Keyboard mouse crossing success.`);
}, (error) => {
console.log(`Start Keyboard mouse crossing failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
});
} catch (error) {
console.log(`Start Keyboard mouse crossing failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
}
```
## inputDeviceCooperate.stop
stop(callback: AsyncCallback\<void>): void
Stops screen hopping. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.MultimodalInput.Input.InputDeviceCooperate
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------------- | ---- | ---------------------------- |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
**Example**
```js
try {
inputDeviceCooperate.stop((error) => {
if (error) {
console.log(`Stop Keyboard mouse crossing failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
return;
}
console.log(`Stop Keyboard mouse crossing success.`);
});
} catch (error) {
console.log(`Stop Keyboard mouse crossing failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
}
```
## inputDeviceCooperate.stop
stop(): Promise\<void>
Stops screen hopping. This API uses a promise to return the result.
**System capability**: SystemCapability.MultimodalInput.Input.InputDeviceCooperate
**Parameters**
| Name | Description |
| -------- | ---------------------------- |
| Promise\<void> | Promise used to return the result. |
**Example**
```js
try {
inputDeviceCooperate.stop().then(() => {
console.log(`Stop Keyboard mouse crossing success.`);
}, (error) => {
console.log(`Stop Keyboard mouse crossing failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
});
} catch (error) {
console.log(`Stop Keyboard mouse crossing failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
}
```
## inputDeviceCooperate.getState
getState(deviceDescriptor: string, callback: AsyncCallback<{ state: boolean }>): void
Checks whether screen hopping is enabled. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.MultimodalInput.Input.InputDeviceCooperate
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | --------- | ---- | ---------------------------- |
| deviceDescriptor | string | Yes | Descriptor of the target device for screen hopping. |
| callback | AsyncCallback<{ state: boolean }> | Yes | Callback used to return the result. |
**Example**
```js
try {
inputDeviceCooperate.getState(deviceDescriptor, (error, data) => {
if (error) {
console.log(`Get the status failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
return;
}
console.log(`Get the status success, data: ${JSON.stringify(data)}`);
});
} catch (error) {
console.log(`Get the status failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
}
```
## inputDeviceCooperate.getState
getState(deviceDescriptor: string): Promise<{ state: boolean }>
Checks whether screen hopping is enabled. This API uses a promise to return the result.
**System capability**: SystemCapability.MultimodalInput.Input.InputDeviceCooperate
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | --------- | ---- | ---------------------------- |
| deviceDescriptor | string | Yes | Descriptor of the target device for screen hopping. |
**Return value**
| Name | Description |
| ------------------- | ------------------------------- |
| Promise<{ state: boolean }>| Promise used to return the result. |
**Example**
```js
try {
inputDeviceCooperate.getState(deviceDescriptor).then((data) => {
console.log(`Get the status success, data: ${JSON.stringify(data)}`);
}, (error) => {
console.log(`Get the status failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
});
} catch (error) {
console.log(`Get the status failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
}
```
## on('cooperation')
on(type: 'cooperation', callback: AsyncCallback<{ deviceDescriptor: string, eventMsg: EventMsg }>): void
Enables listening for screen hopping events.
**System capability**: SystemCapability.MultimodalInput.Input.InputDeviceCooperate
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------------- | ---- | ---------------------------- |
| type | string | Yes | Event type. The value is **cooperation**. |
| callback | AsyncCallback<{ deviceDescriptor: string, eventMsg: [EventMsg](#eventmsg) }> | Yes | Callback used to return the result. |
**Example**
```js
try {
inputDeviceCooperate.on('cooperation', (data) => {
console.log(`Keyboard mouse crossing event: ${JSON.stringify(data)}`);
});
} catch (err) {
console.log(`Register failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
}
```
## off('cooperation')
off(type: 'cooperation', callback?: AsyncCallback\<void>): void
Disables listening for screen hopping events.
**System capability**: SystemCapability.MultimodalInput.Input.InputDeviceCooperate
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------------- | ---- | ---------------------------- |
| type | string | Yes | Event type. The value is **cooperation**. |
| callback | AsyncCallback<void> | No | Callback to be unregistered. If this parameter is not specified, all callbacks registered by the current application will be unregistered.|
**Example**
```js
// Unregister a single callback.
callback: function(event) {
console.log(`Keyboard mouse crossing event: ${JSON.stringify(event)}`);
return false;
},
try {
inputDeviceCooperate.on('cooperation', this.callback);
inputDeviceCooperate.off("cooperation", this.callback);
} catch (error) {
console.log(`Execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
}
```
```js
// Unregister all callbacks.
callback: function(event) {
console.log(`Keyboard mouse crossing event: ${JSON.stringify(event)}`);
return false;
},
try {
inputDeviceCooperate.on('cooperation', this.callback);
inputDeviceCooperate.off("cooperation");
} catch (error) {
console.log(`Execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
}
```
## EventMsg
Enumerates screen hopping event.
**System capability**: SystemCapability.MultimodalInput.Input.InputDeviceCooperate
| Name | Value | Description |
| -------- | --------- | ----------------- |
| MSG_COOPERATE_INFO_START | 200 | Screen hopping starts. |
| MSG_COOPERATE_INFO_SUCCESS | 201 | Screen hopping succeeds. |
| MSG_COOPERATE_INFO_FAIL | 202 | Screen hopping fails. |
| MSG_COOPERATE_STATE_ON | 500 | Screen hopping is enabled. |
| MSG_COOPERATE_STATE_OFF | 501 | Screen hopping is disabled. |
# Distributed Mission Management
The **distributedMissionManager** module implements system mission management across devices. You can use the APIs provided by this module to register or deregister a mission status listener, and start or stop synchronizing the remote mission list.
The **distributedMissionManager** module implements system mission management across devices. You can use the APIs provided by this module to register or deregister a mission status listener, start or stop synchronizing a remote mission list, and continue a mission on a remote device.
> **NOTE**
>
......@@ -48,16 +48,23 @@ Registers a mission status listener. This API uses an asynchronous callback to r
console.log('NotifyNetDisconnect state ' + JSON.stringify(state));
}
var parameter = {
deviceId: remoteDeviceId
deviceId: ""
};
var options = {
notifyMissionsChanged: NotifyMissionsChanged,
notifySnapshot: NotifySnapshot,
notifyNetDisconnect: NotifyNetDisconnect
}
try {
distributedMissionManager.registerMissionListener(parameter, options, (error) => {
console.log("error.code = " + error.code)
if (error.code != 0) {
console.error('registerMissionListener failed, cause: ' + JSON.stringify(error))
}
console.info('registerMissionListener finished')
})
} catch (error) {
console.error('registerMissionListener failed, cause: ' + JSON.stringify(error))
}
```
## distributedMissionManager.registerMissionListener
......@@ -97,19 +104,23 @@ Registers a mission status listener. This API uses a promise to return the resul
console.log('NotifyNetDisconnect state ' + JSON.stringify(state));
}
var parameter = {
deviceId: remoteDeviceId
deviceId: ""
};
var options = {
notifyMissionsChanged: NotifyMissionsChanged,
notifySnapshot: NotifySnapshot,
notifyNetDisconnect: NotifyNetDisconnect
}
try {
distributedMissionManager.registerMissionListener(parameter, options)
.then(data => {
console.info('success data is ' + data);
console.info('registerMissionListener finished, ' + JSON.stringify(data));
}).catch(error => {
console.info('error error is ' + error);
console.error('registerMissionListener failed, cause: ' + JSON.stringify(error));
})
} catch (error) {
console.error('registerMissionListener failed, cause: ' + JSON.stringify(error))
}
```
......@@ -134,11 +145,18 @@ Deregisters a mission status listener. This API uses an asynchronous callback to
```ts
var parameter = {
deviceId: remoteDeviceId
deviceId: ""
};
try {
distributedMissionManager.unRegisterMissionListener(parameter, (error) => {
console.log("error.code = " + error.code)
if (error.code != 0) {
console.error('unRegisterMissionListener failed, cause: ' + JSON.stringify(error))
}
console.info('unRegisterMissionListener finished')
})
} catch (error) {
console.error('unRegisterMissionListener failed, cause: ' + JSON.stringify(error))
}
```
......@@ -168,14 +186,18 @@ Deregisters a mission status listener. This API uses a promise to return the res
```ts
var parameter = {
deviceId: remoteDeviceId
deviceId: ""
};
try {
distributedMissionManager.unRegisterMissionListener(parameter)
.then(data => {
console.info('success data is ' + data);
console.info('unRegisterMissionListener finished, ' + JSON.stringify(data));
}).catch(error => {
console.info('error error is ' + error);
console.error('unRegisterMissionListener failed, cause: ' + JSON.stringify(error));
})
} catch (error) {
console.error('unRegisterMissionListener failed, cause: ' + JSON.stringify(error))
}
```
## distributedMissionManager.startSyncRemoteMissions
......@@ -199,13 +221,20 @@ Starts to synchronize the remote mission list. This API uses an asynchronous cal
```ts
var parameter = {
deviceId: remoteDeviceId,
deviceId: "",
fixConflict: false,
tag: 0
};
try {
distributedMissionManager.startSyncRemoteMissions(parameter, (error) => {
console.log("error.code = " + error.code)
if (error.code != 0) {
console.error('startSyncRemoteMissions failed, cause: ' + JSON.stringify(error))
}
console.info('startSyncRemoteMissions finished')
})
} catch (error) {
console.error('startSyncRemoteMissions failed, cause: ' + JSON.stringify(error))
}
```
## distributedMissionManager.startSyncRemoteMissions
......@@ -234,16 +263,20 @@ Starts to synchronize the remote mission list. This API uses a promise to return
```ts
var parameter = {
deviceId: remoteDeviceId,
deviceId: "",
fixConflict: false,
tag: 0
};
try {
distributedMissionManager.startSyncRemoteMissions(parameter)
.then(data => {
console.info('success data is ' + data);
console.info('startSyncRemoteMissions finished, ' + JSON.stringify(data));
}).catch(error => {
console.info('error error is ' + error);
console.error('startSyncRemoteMissions failed, cause: ' + JSON.stringify(error));
})
} catch (error) {
console.error('startSyncRemoteMissions failed, cause: ' + JSON.stringify(error))
}
```
## distributedMissionManager.stopSyncRemoteMissions
......@@ -267,11 +300,18 @@ Stops synchronizing the remote mission list. This API uses an asynchronous callb
```ts
var parameter = {
deviceId: remoteDeviceId
deviceId: ""
};
try {
distributedMissionManager.stopSyncRemoteMissions(parameter, (error) => {
console.log("error.code = " + error.code)
if (error.code != 0) {
console.error('stopSyncRemoteMissions failed, cause: ' + JSON.stringify(error))
}
console.info('stopSyncRemoteMissions finished')
})
} catch (error) {
console.error('stopSyncRemoteMissions failed, cause: ' + JSON.stringify(error))
}
```
## distributedMissionManager.stopSyncRemoteMissions
......@@ -300,14 +340,113 @@ Stops synchronizing the remote mission list. This API uses a promise to return t
```ts
var parameter = {
deviceId: remoteDeviceId
deviceId: ""
};
try {
distributedMissionManager.stopSyncRemoteMissions(parameter)
.then(data => {
console.info('success data is ' + data);
console.info('stopSyncRemoteMissions finished, ' + JSON.stringify(data));
}).catch(error => {
console.error('stopSyncRemoteMissions failed, cause: ' + JSON.stringify(error));
})
} catch (error) {
console.error('stopSyncRemoteMissions failed, cause: ' + JSON.stringify(error))
}
```
## distributedMissionManager.continueMission
continueMission(parameter: ContinueDeviceInfo, options: ContinueCallback, callback: AsyncCallback&lt;void&gt;): void;
Continues a mission on a remote device. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.MANAGE_MISSIONS and ohos.permission.DISTRIBUTED_DATASYNC
**System capability**: SystemCapability.Ability.AbilityRuntime.Mission
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | --------------------------------------- | ---- | ----- |
| parameter | [ContinueDeviceInfo](#continuedeviceinfo) | Yes | Parameters required for mission continuation.|
| options | [ContinueCallback](#continuecallback) | Yes | Callback invoked when the mission continuation is complete.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result.|
**Example**
```ts
var parameter = {
srcDeviceId: "",
dstDeviceId: "",
missionId: 1,
wantParam: {"key": "value"}
};
function OnContinueDone(resultCode) {
console.log('OnContinueDone resultCode: ' + JSON.stringify(resultCode));
};
var options = {
OnContinueDone: OnContinueDone
};
try {
distributedMissionManager.continueMission(parameter, options, (error) => {
if (error.code != 0) {
console.error('continueMission failed, cause: ' + JSON.stringify(error))
}
console.info('continueMission finished')
})
} catch (error) {
console.error('continueMission failed, cause: ' + JSON.stringify(error))
}
```
## distributedMissionManager.continueMission
continueMission(parameter: ContinueDeviceInfo, options: ContinueCallback): Promise&lt;void&gt;
Continues a mission on a remote device. This API uses a promise to return the result.
**Required permissions**: ohos.permission.MANAGE_MISSIONS and ohos.permission.DISTRIBUTED_DATASYNC
**System capability**: SystemCapability.Ability.AbilityRuntime.Mission
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | --------------------------------------- | ---- | ----- |
| parameter | [ContinueDeviceInfo](#continuedeviceinfo) | Yes | Parameters required for mission continuation.|
| options | [ContinueCallback](#continuecallback) | Yes | Callback invoked when the mission continuation is complete.|
**Return value**
| Type | Description |
| ------------------- | ---------------- |
| Promise&lt;void&gt; | Promise used to return the result.|
**Example**
```ts
var parameter = {
srcDeviceId: "",
dstDeviceId: "",
missionId: 1,
wantParam: {"key": "value"}
};
function OnContinueDone(resultCode) {
console.log('OnContinueDone resultCode: ' + JSON.stringify(resultCode));
};
var options = {
OnContinueDone: OnContinueDone
};
try {
distributedMissionManager.continueMission(parameter, options)
.then(data => {
console.info('continueMission finished, ' + JSON.stringify(data));
}).catch(error => {
console.info('error error is ' + error);
console.error('continueMission failed, cause: ' + JSON.stringify(error));
})
} catch (error) {
console.error('continueMission failed, cause: ' + JSON.stringify(error))
}
```
## MissionCallback
......@@ -349,3 +488,30 @@ Defines the parameters required for registering a listener.
| Name | Type | Readable | Writable | Description |
| -------- | ------ | ---- | ---- | ------- |
| deviceId | string | Yes | Yes | Device ID.|
## ContinueDeviceInfo
Defines the parameters required for mission continuation.
**Required permissions**: ohos.permission.MANAGE_MISSIONS
**System capability**: SystemCapability.Ability.AbilityRuntime.Mission
| Name | Type | Readable | Writable | Description |
| -------- | ------ | ---- | ---- | ------- |
| srcDeviceId | string | Yes | Yes | ID of the source device.|
| dstDeviceId | string | Yes | Yes | ID of the target device.|
| missionId | number | Yes | Yes | Mission ID.|
| wantParam | {[key: string]: any} | Yes | Yes | Extended parameters.|
## ContinueCallback
Defines the callback invoked when the mission continuation is complete.
**Required permissions**: ohos.permission.MANAGE_MISSIONS
**System capability**: SystemCapability.Ability.AbilityRuntime.Mission
| Name | Type | Readable | Writable | Description |
| --------------------- | -------- | ---- | ---- | ------------------ |
| onContinueDone | function | Yes | No | Callback used to notify the user that the mission continuation is complete and return the continuation result. |
......@@ -38,12 +38,16 @@ This is a system API.
**Example**
```
let keyOptions = {preKeys: [], finalKey: 3, isFinalKeyDown: true, finalKeyDownDuration: 0}
let callback = function(keyOptions) {
let keyOptions = { preKeys: [], finalKey: 18, isFinalKeyDown: true, finalKeyDownDuration: 0 }
let callback = function (keyOptions) {
console.info("preKeys: " + keyOptions.preKeys, "finalKey: " + keyOptions.finalKey,
"isFinalKeyDown: " + keyOptions.isFinalKeyDown, "finalKeyDownDuration: " + keyOptions.finalKeyDownDuration)
}
inputConsumer.on('key', keyOptions, callback);
try {
inputConsumer.on(inputConsumer.SubscribeType.KEY, keyOptions, callback);
} catch (error) {
console.info(`inputConsumer.on, error.code=${JSON.stringify(error.code)}, error.msg=${JSON.stringify(error.message)}`);
}
```
......@@ -68,12 +72,16 @@ This is a system API.
**Example**
```
let keyOptions = {preKeys: [], finalKey: 18, isFinalKeyDown: true, finalKeyDownDuration: 0}
let callback = function(keyOptions) {
let keyOptions = { preKeys: [], finalKey: 18, isFinalKeyDown: true, finalKeyDownDuration: 0 }
let callback = function (keyOptions) {
console.info("preKeys: " + keyOptions.preKeys, "finalKey: " + keyOptions.finalKey,
"isFinalKeyDown: " + keyOptions.isFinalKeyDown, "finalKeyDownDuration: " + keyOptions.finalKeyDownDuration)
}
inputConsumer.off('key', keyOptions, callback);
try {
inputConsumer.off(inputConsumer.SubscribeType.KEY, keyOptions, callback);
} catch (error) {
console.info(`inputConsumer.off, error.code=${JSON.stringify(error.code)}, error.msg=${JSON.stringify(error.message)}`);
}
```
......
......@@ -15,6 +15,130 @@ The Input Device module implements listening for connection, disconnection, and
```js
import inputDevice from '@ohos.multimodalInput.inputDevice';
```
## inputDevice.getDeviceList<sup>9+</sup>
getDeviceList(callback: AsyncCallback&lt;Array&lt;number&gt;&gt;): void
Obtains the IDs of all input devices. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.MultimodalInput.Input.InputDevice
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------------------------- | ---- | ---------- |
| callback | AsyncCallback&lt;Array&lt;number&gt;&gt; | Yes | Callback used to return the result.|
**Example**
```js
try {
inputDevice.getDeviceList((error, ids) => {
if (error) {
console.log(`Failed to get device list.
error code=${JSON.stringify(err.code)} msg=${JSON.stringify(err.message)}`);
return;
}
this.data = ids;
console.log("The device ID list is: " + ids);
});
} catch (error) {
console.info("getDeviceList " + error.code + " " + error.message);
}
```
## inputDevice.getDeviceList<sup>9+</sup>
getDeviceList(): Promise&lt;Array&lt;number&gt;&gt;
Obtains the IDs of all input devices. This API uses a promise to return the result.
**System capability**: SystemCapability.MultimodalInput.Input.InputDevice
**Return value**
| Name | Description |
| ---------------------------------- | ------------------------------- |
| Promise&lt;Array&lt;number&gt;&gt; | Promise used to return the result.|
**Example**
```js
try {
inputDevice.getDeviceList().then((ids) => {
console.log("The device ID list is: " + ids);
});
} catch (error) {
console.info("getDeviceList " + error.code + " " + error.message);
}
```
## inputDevice.getDeviceInfo<sup>9+</sup>
getDeviceInfo(deviceId: number, callback: AsyncCallback&lt;InputDeviceData&gt;): void
Obtains information about an input device. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.MultimodalInput.Input.InputDevice
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------------------------------------------- | ---- | --------------------------------------- |
| deviceId | number | Yes | ID of the input device. |
| callback | AsyncCallback&lt;[InputDeviceData](#inputdevicedata)&gt; | Yes | Callback used to return the result, which is an **InputDeviceData** object.|
**Example**
```js
// Obtain the name of the device whose ID is 1.
try {
inputDevice.getDeviceInfo(1, (error, inputDevice) => {
if (error) {
console.log(`Failed to get device information.
error code=${JSON.stringify(err.code)} msg=${JSON.stringify(err.message)}`);
return;
}
console.log("The device name is: " + inputDevice.name);
});
} catch (error) {
console.info("getDeviceInfo " + error.code + " " + error.message);
}
```
## inputDevice.getDeviceInfo<sup>9+</sup>
getDeviceInfo(deviceId: number): Promise&lt;InputDeviceData&gt;
Obtains information about an input device. This API uses a promise to return the result.
**System capability**: SystemCapability.MultimodalInput.Input.InputDevice
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------ | ---- | ---------------------- |
| deviceId | number | Yes | ID of the input device.|
**Return value**
| Name | Description |
| -------------------------------------------------- | ------------------------------- |
| Promise&lt;[InputDeviceData](#inputdevicedata)&gt; | Promise used to return the result.|
**Example**
```js
// Obtain the name of the device whose ID is 1.
try {
inputDevice.getDeviceInfo(id).then((inputDevice) => {
console.log("The device name is: " + inputDevice.name);
});
} catch (error) {
console.info("getDeviceInfo " + error.code + " " + error.message);
}
```
## inputDevice.on<sup>9+</sup>
......@@ -35,7 +159,8 @@ Enables listening for hot swap events of an input device.
```js
let isPhysicalKeyboardExist = true;
inputDevice.on("change", (data) => {
try {
inputDevice.on("change", (data) => {
console.log("type: " + data.type + ", deviceId: " + data.deviceId);
inputDevice.getKeyboardType(data.deviceId, (err, ret) => {
console.log("The keyboard type of the device is: " + ret);
......@@ -47,8 +172,11 @@ inputDevice.on("change", (data) => {
isPhysicalKeyboardExist = false;
}
});
});
// Check whether the soft keyboard is open based on the value of isPhysicalKeyboardExist.
});
// Check whether the soft keyboard is open based on the value of isPhysicalKeyboardExist.
} catch (error) {
console.info("oninputdevcie " + error.code + " " + error.message);
}
```
## inputDevice.off<sup>9+</sup>
......@@ -69,24 +197,43 @@ Disables listening for hot swap events of an input device.
**Example**
```js
function listener(data) {
callback: function(data) {
console.log("type: " + data.type + ", deviceId: " + data.deviceId);
}
try {
inputDevice.on("change", this.callback);
} catch (error) {
console.info("oninputdevcie " + error.code + " " + error.message)
}
// Enable listening for hot swap events of an input device.
inputDevice.on("change", listener);
// Disable this listener.
inputDevice.off("change", listener);
try {
inputDevice.off("change", this.callback);
} catch (error) {
console.info("offinputdevcie " + error.code + " " + error.message)
}
// Disable all listeners.
inputDevice.off("change");
try {
inputDevice.off("change");
} catch (error) {
console.info("offinputdevcie " + error.code + " " + error.message);
}
// By default, the soft keyboard is closed when listening is disabled.
```
## inputDevice.getDeviceIds
## inputDevice.getDeviceIds<sup>(deprecated)</sup>
getDeviceIds(callback: AsyncCallback&lt;Array&lt;number&gt;&gt;): void
Obtains the IDs of all input devices. This API uses an asynchronous callback to return the result.
This API is deprecated since API version 9. You are advised to use [inputDevice.getDeviceList](#inputdevicegetdevicelist9) instead.
**System capability**: SystemCapability.MultimodalInput.Input.InputDevice
**Parameters**
......@@ -103,12 +250,14 @@ inputDevice.getDeviceIds((ids)=>{
});
```
## inputDevice.getDeviceIds
## inputDevice.getDeviceIds<sup>(deprecated)</sup>
getDeviceIds(): Promise&lt;Array&lt;number&gt;&gt;
Obtains the IDs of all input devices. This API uses a promise to return the result.
This API is deprecated since API version 9. You are advised to use [inputDevice.getDeviceList](#inputdevicegetdevicelist9) instead.
**System capability**: SystemCapability.MultimodalInput.Input.InputDevice
**Return value**
......@@ -125,12 +274,14 @@ inputDevice.getDeviceIds().then((ids)=>{
});
```
## inputDevice.getDevice
## inputDevice.getDevice<sup>(deprecated)</sup>
getDevice(deviceId: number, callback: AsyncCallback&lt;InputDeviceData&gt;): void
Obtains information about an input device. This API uses an asynchronous callback to return the result.
This API is deprecated since API version 9. You are advised to use [inputDevice.getDeviceInfo](#inputdevicegetdeviceinfo9) instead.
**System capability**: SystemCapability.MultimodalInput.Input.InputDevice
**Parameters**
......@@ -149,12 +300,14 @@ inputDevice.getDevice(1, (inputDevice)=>{
});
```
## inputDevice.getDevice
## inputDevice.getDevice<sup>(deprecated)</sup>
getDevice(deviceId: number): Promise&lt;InputDeviceData&gt;
Obtains information about an input device. This API uses a promise to return the result.
This API is deprecated since API version 9. You are advised to use [inputDevice.getDeviceInfo](#inputdevicegetdeviceinfo9) instead.
**System capability**: SystemCapability.MultimodalInput.Input.InputDevice
**Parameters**
......@@ -198,9 +351,13 @@ Obtains the key codes supported by the input device. This API uses an asynchrono
```js
// Check whether the input device whose ID is 1 supports key codes 17, 22, and 2055.
inputDevice.supportKeys(1, [17, 22, 2055], (ret)=>{
try {
inputDevice.supportKeys(1, [17, 22, 2055], (error, ret) => {
console.log("The query result is as follows: " + ret);
});
});
} catch (error) {
console.info("supportKeys " + error.code + " " + error.message);
}
```
## inputDevice.supportKeys<sup>9+</sup>
......@@ -228,9 +385,13 @@ Obtains the key codes supported by the input device. This API uses a promise to
```js
// Check whether the input device whose ID is 1 supports key codes 17, 22, and 2055.
inputDevice.supportKeys(1, [17, 22, 2055]).then((ret)=>{
try {
inputDevice.supportKeys(1, [17, 22, 2055]).then((ret) => {
console.log("The query result is as follows: " + ret);
})
});
} catch (error) {
console.info("supportKeys " + error.code + " " + error.message);
}
```
## inputDevice.getKeyboardType<sup>9+</sup>
......@@ -252,9 +413,18 @@ Obtains the keyboard type of an input device. This API uses an asynchronous call
```js
// Query the keyboard type of the input device whose ID is 1.
inputDevice.getKeyboardType(1, (ret)=>{
console.log("The keyboard type of the device is: " + ret);
});
try {
inputDevice.getKeyboardType(1, (error, number) => {
if (error) {
console.log(`Failed to get keyboardtype.
error code=${JSON.stringify(err.code)} msg=${JSON.stringify(err.message)}`);
return;
}
console.log("The keyboard type of the device is: " + number);
});
} catch (error) {
console.info("getKeyboardType " + error.code + " " + error.message);
}
```
## inputDevice.getKeyboardType<sup>9+</sup>
......@@ -275,14 +445,18 @@ Obtains the keyboard type of an input device. This API uses a promise to return
```js
// Query the keyboard type of the input device whose ID is 1.
inputDevice.getKeyboardType(1).then((ret)=>{
console.log("The keyboard type of the device is: " + ret);
})
try {
inputDevice.getKeyboardType(1).then((number) => {
console.log("The keyboard type of the device is: " + number);
});
} catch (error) {
console.info("getKeyboardType " + error.code + " " + error.message);
}
```
## DeviceListener<sup>9+</sup>
Defines the information about an input device.
Defines the listener for hot swap events of an input device.
**System capability**: SystemCapability.MultimodalInput.Input.InputDevice
......
......@@ -36,13 +36,24 @@ This is a system API.
**Example**
```js
let keyEvent = {
try {
var keyEvent = {
isPressed: true,
keyCode: 2,
keyDownDuration: 0,
isIntercepted: false
}
inputEventClient.injectKeyEvent({ KeyEvent: keyEvent });
var keyEvent1 = {
isPressed: false,
keyCode: 2,
keyDownDuration: 0,
isIntercepted: false
};
inputEventClient.injectKeyEvent({ KeyEvent: keyEvent1 });
} catch (error) {
console.info("injectKeyEvent " + error.code + " " + error.message);
}
let res = inputEventClient.injectEvent({KeyEvent: keyEvent});
```
......
......@@ -43,10 +43,14 @@ This is a system API.
**Example**
```js
inputMonitor.off("touch", (event) => {
// A touch event is consumed.
try {
inputMonitor.on("touch", (data)=> {
console.info(`monitorOnTouchEvent success ${JSON.stringify(data)}`);
return false;
});
});
} catch (error) {
console.info("onMonitor " + error.code + " " + error.message)
}
```
on(type: "mouse", receiver: Callback&lt;MouseEvent&gt;): void
......@@ -69,13 +73,16 @@ This is a system API.
**Example**
```js
inputMonitor.off("mouse", (event) => {
// A mouse event is consumed.
});
try {
inputMonitor.on("mouse", (data)=> {
console.info(`monitorOnMouseEvent success ${JSON.stringify(data)}`);
return false;
});
} catch (error) {
console.info("onMonitor " + error.code + " " + error.message)
}
```
## inputMonitor.off
off(type: "touch", receiver?: TouchEventReceiver): void
......@@ -98,7 +105,26 @@ This is a system API.
**Example**
```js
inputMonitor.off("touch");
// Disable listening globally.
try {
inputMonitor.off("touch");
} catch (error) {
console.info("offMonitor " + error.code + " " + error.message)
}
// Disable listening for this receiver.
callback:function(data) {
console.info(`call success ${JSON.stringify(data)}`);
},
try {
inputMonitor.on("touch", this.callback);
} catch (error) {
console.info("onTouchMonitor " + error.code + " " + error.message)
},
try {
inputMonitor.off("touch",this.callback);
} catch (error) {
console.info("offTouchMonitor " + error.code + " " + error.message)
}
```
off(type: "mouse", receiver?:Callback\<MouseEvent>):void
......@@ -121,7 +147,26 @@ This is a system API.
**Example**
```js
inputMonitor.off("mouse");
// Disable listening globally.
try {
inputMonitor.off("mouse");
} catch (error) {
console.info("offMonitor " + error.code + " " + error.message)
}
// Disable listening for this receiver.
callback:function(data) {
console.info(`call success ${JSON.stringify(data)}`);
},
try {
inputMonitor.on("mouse", this.callback);
} catch (error) {
console.info("onMouseMonitor " + error.code + " " + error.message)
},
try {
inputMonitor.off("mouse", this.callback);
} catch (error) {
console.info("offMouseMonitor " + error.code + " " + error.message)
}
```
......@@ -149,9 +194,13 @@ This is a system API.
**Example**
```js
inputMonitor.on("touch", (event) => {
// A touch event is consumed.
try {
inputMonitor.on("touch", (event) => {
// If true is returned, all subsequent events of this operation will be consumed by the listener, instead of being distributed to the window.
return false;
});
inputMonitor.off("touch");
});
inputMonitor.off("touch");
} catch (error) {
console.info("offMonitor " + error.code + " " + error.message)
}
```
# Media
> **NOTE**
>
> 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 multimedia subsystem provides a set of simple and easy-to-use APIs for you to access the system and use media resources.
......@@ -53,7 +52,7 @@ Creates a **VideoPlayer** instance. This API uses an asynchronous callback to re
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------- | ---- | ------------------------------ |
| callback | AsyncCallback<[VideoPlayer](#videoplayer8)> | Yes | Callback used to return the **VideoPlayer** instance, which can be used to manage and play video media.|
| callback | AsyncCallback<[VideoPlayer](#videoplayer8)> | Yes | Callback used to return the result. If the operation is successful, the **VideoPlayer** instance is returned; otherwise, **null** is returned. The instance can be used to manage and play video media.|
**Example**
......@@ -81,8 +80,8 @@ Creates a **VideoPlayer** instance. This API uses a promise to return the result
**Return value**
| Type | Description |
| ------------------------------------- | ----------------------------------- |
| Promise<[VideoPlayer](#videoplayer8)> | Promise used to return the **VideoPlayer** instance, which can be used to manage and play video media.|
| ------------------------------------- | ------------------------------------------------------------ |
| Promise<[VideoPlayer](#videoplayer8)> | Promise used to return the result. If the operation is successful, the **VideoPlayer** instance is returned; otherwise, **null** is returned. The instance can be used to manage and play video media.|
**Example**
......@@ -113,8 +112,8 @@ Only one **AudioRecorder** instance can be created per device.
**Return value**
| Type | Description |
| ------------------------------- | ----------------------------------------- |
| [AudioRecorder](#audiorecorder) | Returns the **AudioRecorder** instance if the operation is successful; returns **null** otherwise.|
| ------------------------------- | ------------------------------------------------------------ |
| [AudioRecorder](#audiorecorder) | Returns the **AudioRecorder** instance if the operation is successful; returns **null** otherwise. The instance can be used to record audio media.|
**Example**
......@@ -135,7 +134,7 @@ Only one **AudioRecorder** instance can be created per device.
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------------------- | ---- | ------------------------------ |
| callback | AsyncCallback<[VideoRecorder](#videorecorder9)> | Yes | Callback used to return the **VideoRecorder** instance, which can be used to record video media.|
| callback | AsyncCallback<[VideoRecorder](#videorecorder9)> | Yes | Callback used to return the result. If the operation is successful, the **VideoRecorder** instance is returned; otherwise, **null** is returned. The instance can be used to record video media.|
**Example**
......@@ -164,8 +163,8 @@ Only one **AudioRecorder** instance can be created per device.
**Return value**
| Type | Description |
| ----------------------------------------- | ----------------------------------- |
| Promise<[VideoRecorder](#videorecorder9)> | Promise used to return the **VideoRecorder** instance, which can be used to record video media.|
| ----------------------------------------- | ------------------------------------------------------------ |
| Promise<[VideoRecorder](#videorecorder9)> | Promise used to return the result. If the operation is successful, the **VideoRecorder** instance is returned; otherwise, **null** is returned. The instance can be used to record video media.|
**Example**
......@@ -263,7 +262,7 @@ Enumerates the buffering event types.
| BUFFERING_START | 1 | Buffering starts. |
| BUFFERING_END | 2 | Buffering ends. |
| BUFFERING_PERCENT | 3 | Buffering progress, in percent. |
| CACHED_DURATION | 4 | Cache duration, in milliseconds.|
| CACHED_DURATION | 4 | Cache duration, in ms.|
## AudioPlayer
......@@ -363,8 +362,8 @@ Seeks to the specified playback position.
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------------------------ |
| timeMs | number | Yes | Position to seek to, in milliseconds.|
| ------ | ------ | ---- | ----------------------------------------------------------- |
| timeMs | number | Yes | Position to seek to, in ms. The value range is [0, duration].|
**Example**
......@@ -428,8 +427,8 @@ Obtains the audio track information. This API uses an asynchronous callback to r
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | -------------------------- |
| callback | AsyncCallback<Array<[MediaDescription](#mediadescription8)>> | Yes | Callback used to return the audio track information obtained.|
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------ |
| callback | AsyncCallback<Array<[MediaDescription](#mediadescription8)>> | Yes | Callback used to return a **MediaDescription** array, which records the audio track information.|
**Example**
......@@ -464,8 +463,8 @@ Obtains the audio track information. This API uses a promise to return the resul
**Return value**
| Type | Description |
| ------------------------------------------------------ | ------------------------------- |
| Promise<Array<[MediaDescription](#mediadescription8)>> | Promise used to return the audio track information obtained.|
| ------------------------------------------------------ | ----------------------------------------------- |
| Promise<Array<[MediaDescription](#mediadescription8)>> | Promise used to return a **MediaDescription** array, which records the audio track information.|
**Example**
......@@ -497,7 +496,7 @@ for (let i = 0; i < arrayDescription.length; i++) {
on(type: 'bufferingUpdate', callback: (infoType: [BufferingInfoType](#bufferinginfotype8), value: number) => void): void
Subscribes to the audio buffering update event.
Subscribes to the audio buffering update event. Only network playback supports this subscription.
**System capability**: SystemCapability.Multimedia.Media.AudioPlayer
......@@ -594,7 +593,7 @@ audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' e
on(type: 'timeUpdate', callback: Callback\<number>): void
Subscribes to the **'timeUpdate'** event.
Subscribes to the **'timeUpdate'** event. This event is reported every second when the audio playback is in progress.
**System capability**: SystemCapability.Multimedia.Media.AudioPlayer
......@@ -1015,8 +1014,8 @@ Seeks to the specified playback position. The next key frame at the specified po
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------- | ---- | ------------------------------------ |
| timeMs | number | Yes | Position to seek to, in milliseconds.|
| -------- | -------- | ---- | ------------------------------------------------------------ |
| timeMs | number | Yes | Position to seek to, in ms. The value range is [0, duration].|
| callback | function | Yes | Callback used to return the result. |
**Example**
......@@ -1043,8 +1042,8 @@ Seeks to the specified playback position. This API uses an asynchronous callback
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------- | ---- | ------------------------------------ |
| timeMs | number | Yes | Position to seek to, in milliseconds.|
| -------- | ---------------------- | ---- | ------------------------------------------------------------ |
| timeMs | number | Yes | Position to seek to, in ms. The value range is [0, duration].|
| mode | [SeekMode](#seekmode8) | Yes | Seek mode. |
| callback | function | Yes | Callback used to return the result. |
......@@ -1073,15 +1072,15 @@ Seeks to the specified playback position. If **mode** is not specified, the next
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ---------------------- | ---- | ------------------------------------ |
| timeMs | number | Yes | Position to seek to, in milliseconds.|
| ------ | ---------------------- | ---- | ------------------------------------------------------------ |
| timeMs | number | Yes | Position to seek to, in ms. The value range is [0, duration].|
| mode | [SeekMode](#seekmode8) | No | Seek mode. |
**Return value**
| Type | Description |
| -------------- | ----------------------------------- |
| Promise\<void> | Promise used to return the result.|
| -------------- | ------------------------------------------- |
| Promise\<number> | Promise used to return the playback position, in ms.|
**Example**
......@@ -1221,8 +1220,8 @@ Obtains the video track information. This API uses an asynchronous callback to r
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | -------------------------- |
| callback | AsyncCallback<Array<[MediaDescription](#mediadescription8)>> | Yes | Callback used to return the video track information obtained.|
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------ |
| callback | AsyncCallback<Array<[MediaDescription](#mediadescription8)>> | Yes | Callback used to return a **MediaDescription** array, which records the video track information.|
**Example**
......@@ -1257,8 +1256,8 @@ Obtains the video track information. This API uses a promise to return the resul
**Return value**
| Type | Description |
| ------------------------------------------------------ | ------------------------------- |
| Promise<Array<[MediaDescription](#mediadescription8)>> | Promise used to return the video track information obtained.|
| ------------------------------------------------------ | ----------------------------------------------- |
| Promise<Array<[MediaDescription](#mediadescription8)>> | Promise used to return a **MediaDescription** array, which records the video track information.|
**Example**
......@@ -1333,8 +1332,8 @@ Sets the video playback speed. This API uses a promise to return the result.
**Return value**
| Type | Description |
| ---------------- | ------------------------- |
| Promise\<number> | Promise used to return the result.|
| ---------------- | ------------------------------------------------------------ |
| Promise\<number> | Promise used to return playback speed. For details, see [PlaybackSpeed](#playbackspeed8).|
**Example**
......@@ -1389,13 +1388,13 @@ Selects a bit rate from available ones, which can be obtained by calling [availa
| Name | Type | Mandatory| Description |
| ------- | ------ | ---- | -------------------------------------------- |
| bitrate | number | Yes | Bit rate to select, which is used in the HLS multi-bit rate scenario. The unit is bit/s.|
| bitrate | number | Yes | Bit rate, which is used in the HLS multi-bit rate scenario. The unit is bit/s.|
**Return value**
| Type | Description |
| ---------------- | ------------------------- |
| Promise\<number> | Promise used to return the result.|
| ---------------- | --------------------------- |
| Promise\<number> | Promise used to return the bit rate.|
**Example**
......@@ -1435,7 +1434,7 @@ videoPlayer.on('playbackCompleted', () => {
on(type: 'bufferingUpdate', callback: (infoType: BufferingInfoType, value: number) => void): void
Subscribes to the video buffering update event.
Subscribes to the video buffering update event. Only network playback supports this subscription.
**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
......
......@@ -309,6 +309,8 @@ reportNetConnected(netHandle: NetHandle, callback: AsyncCallback&lt;void&gt;): v
Reports connection of the data network. This API uses an asynchronous callback to return the result.
If this API is called, the application considers that the network connection state (**ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED**) is inconsistent with that in the network management module.
**Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetManager.Core
......@@ -337,6 +339,8 @@ reportNetConnected(netHandle: NetHandle): Promise&lt;void&gt;
Reports connection of the data network. This API uses a promise to return the result.
If this API is called, the application considers that the network connection state (**ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED**) is inconsistent with that in the network management module.
**Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetManager.Core
......@@ -351,7 +355,7 @@ Reports connection of the data network. This API uses a promise to return the re
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
| Promise&lt;void&gt; | Promise that returns no value.|
**Example**
......@@ -370,6 +374,8 @@ reportNetDisconnected(netHandle: NetHandle, callback: AsyncCallback&lt;void&gt;)
Reports disconnection of the data network. This API uses an asynchronous callback to return the result.
If this API is called, the application considers that the network connection state (**ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED**) is inconsistent with that in the network management module.
**Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetManager.Core
......@@ -398,6 +404,8 @@ reportNetDisconnected(netHandle: NetHandle): Promise&lt;void&gt;
Reports disconnection of the data network. This API uses a promise to return the result.
If this API is called, the application considers that the network connection state (**ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED**) is inconsistent with that in the network management module.
**Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetManager.Core
......@@ -412,7 +420,7 @@ Reports disconnection of the data network. This API uses a promise to return the
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
| Promise&lt;void&gt; | Promise that returns no value.|
**Example**
......@@ -521,7 +529,7 @@ This is a system API.
| Type | Description |
| ------------------------------------------- | ----------------------------- |
| Promise\<void> | Promise used to return the result.|
| Promise\<void> | Promise that returns no value.|
**Example**
......@@ -570,7 +578,7 @@ This is a system API.
| Type | Description |
| ------------------------------------------- | ----------------------------- |
| Promise\<void> | Promise used to return the result.|
| Promise\<void> | Promise that returns no value.|
**Example**
......@@ -888,7 +896,7 @@ Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses
| Type | Description |
| -------------- | ---------------------- |
| Promise\<void> | Promise used to return the result.|
| Promise\<void> | Promise that returns no value.|
**Example**
......
......@@ -4,6 +4,8 @@ The **Prompt** module provides APIs for creating and showing toasts, dialog boxe
> **NOTE**
>
> The APIs of this module are deprecated since API Version 9. You are advised to use [@ohos.promptAction](js-apis-promptAction.md) instead.
>
> 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
......@@ -35,6 +37,8 @@ prompt.showToast({
});
```
![en-us_image_0001](figures/en-us_image_0001.gif)
## ShowToastOptions
Describes the options for showing the toast.
......@@ -43,9 +47,9 @@ Describes the options for showing the toast.
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ---------------------------------------- |
| message | string\| [Resource](../../ui/ts-types.md#resource-type)<sup>9+</sup>| Yes | Text to display. |
| message | string\| [Resource](../arkui-ts/ts-types.md#resource)<sup>9+</sup> | Yes | Text to display. |
| duration | number | No | Duration that the toast will remain on the screen. The default value is 1500 ms. The value range is 1500 ms to 10000 ms. If a value less than 1500 ms is set, the default value is used. If the value greater than 10000 ms is set, the upper limit 10000 ms is used.|
| bottom | string\| number | No | Distance between the toast border and the bottom of the screen. |
| bottom | string\| number | No | Distance between the toast border and the bottom of the screen. It does not have an upper limit. The default unit is vp. |
## prompt.showDialog
......@@ -92,6 +96,8 @@ prompt.showDialog({
})
```
![en-us_image_0002](figures/en-us_image_0002.gif)
## prompt.showDialog
showDialog(options: ShowDialogOptions, callback: AsyncCallback&lt;ShowDialogSuccessResponse&gt;):void
......@@ -132,6 +138,8 @@ prompt.showDialog({
});
```
![en-us_image_0004](figures/en-us_image_0004.gif)
## ShowDialogOptions
Describes the options for showing the dialog box.
......@@ -140,8 +148,8 @@ Describes the options for showing the dialog box.
| Name | Type | Mandatory | Description |
| ------- | ---------------------------------------- | ---- | ---------------------------------------- |
| title | string\| [Resource](../../ui/ts-types.md#resource-type)<sup>9+</sup>| No | Title of the dialog box. |
| message | string\| [Resource](../../ui/ts-types.md#resource-type)<sup>9+</sup>| No | Text body. |
| title | string\| [Resource](../arkui-ts/ts-types.md#resource)<sup>9+</sup> | No | Title of the dialog box. |
| message | string\| [Resource](../arkui-ts/ts-types.md#resource)<sup>9+</sup> | No | Text body. |
| buttons | Array | No | Array of buttons in the dialog box. The array structure is **{text:'button', color: '\#666666'}**. Up to three buttons are supported. The first button is of the **positiveButton** type, the second is of the **negativeButton** type, and the third is of the **neutralButton** type.|
## ShowDialogSuccessResponse
......@@ -170,7 +178,6 @@ Shows an action menu. This API uses a callback to return the result asynchronous
| options | [ActionMenuOptions](#actionmenuoptions) | Yes | Action menu options. |
| callback | AsyncCallback&lt;[ActionMenuSuccessResponse](#actionmenusuccessresponse)> | Yes | Callback used to return the action menu response result.|
**Example**
```js
......@@ -195,6 +202,8 @@ prompt.showActionMenu({
})
```
![en-us_image_0005](figures/en-us_image_0005.gif)
## prompt.showActionMenu
showActionMenu(options: ActionMenuOptions): Promise&lt;ActionMenuSuccessResponse&gt;
......@@ -238,6 +247,8 @@ prompt.showActionMenu({
console.info('showActionMenu error: ' + err);
})
```
![en-us_image_0006](figures/en-us_image_0006.gif)
## ActionMenuOptions
Describes the options for showing the action menu.
......@@ -246,7 +257,7 @@ Describes the options for showing the action menu.
| Name | Type | Mandatory | Description |
| ------- | ---------------------------------------- | ---- | ---------------------------------------- |
| title | string\| [Resource](../../ui/ts-types.md#resource-type)<sup>9+</sup>| No | Title of the text to display. |
| title | string\| [Resource](../arkui-ts/ts-types.md#resource)<sup>9+</sup> | No | Title of the text to display. |
| buttons | Array&lt;[Button](#button)&gt; | Yes | Array of menu item buttons. The array structure is **{text:'button', color: '\#666666'}**. Up to six buttons are supported. If there are more than six buttons, extra buttons will not be displayed.|
## ActionMenuSuccessResponse
......@@ -267,5 +278,5 @@ Describes the menu item button in the action menu.
| Name | Type | Mandatory | Description |
| ----- | ---------------------------------------- | ---- | ------- |
| text | string\| [Resource](../../ui/ts-types.md#resource-type)<sup>9+</sup>| Yes | Button text.|
| color | string\| [Resource](../../ui/ts-types.md#resource-type)<sup>9+</sup>| Yes | Text color of the button.|
| text | string\| [Resource](../arkui-ts/ts-types.md#resource)<sup>9+</sup> | Yes | Button text.|
| color | string\| [Resource](../arkui-ts/ts-types.md#resource)<sup>9+</sup> | Yes | Text color of the button.|
......@@ -710,7 +710,7 @@ Sets a display name for the SIM card in the specified slot. This API uses an asy
**Example**
```js
let name = "China Mobile";
let name = "ShowName";
sim.setShowName(0, name, (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
});
......@@ -744,7 +744,7 @@ Sets a display name for the SIM card in the specified slot. This API uses a prom
**Example**
```js
let name = "China Mobile";
let name = "ShowName";
let promise = sim.setShowName(0, name);
promise.then(data => {
console.log(`setShowName success, promise: data->${JSON.stringify(data)}`);
......
......@@ -10,10 +10,10 @@ You can set the background of a component.
| Name| Type| Description|
| -------- | -------- | -------- |
| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the component. |
| backgroundImage | src: [ResourceStr](ts-types.md#resourcestr),<br>repeat?: [ImageRepeat](ts-appendix-enums.md#imagerepeat) | Background image of the component.<br>**src**: image address, which can be the address of an Internet or a local image. (SVG images are not supported.)<br>**repeat**: whether the background image is repeatedly used. By default, the background image is not repeatedly used. |
| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the component.|
| backgroundImage | src: [ResourceStr](ts-types.md#resourcestr),<br>repeat?: [ImageRepeat](ts-appendix-enums.md#imagerepeat) | **src**: image address, which can be the address of an Internet or a local image. (SVG images are not supported.)<br>**repeat**: whether the background image is repeatedly used. By default, the background image is not repeatedly used.|
| backgroundImageSize | {<br>width?: [Length](ts-types.md#length),<br>height?: [Length](ts-types.md#length)<br>} \| [ImageSize](ts-appendix-enums.md#imagesize) | Width and height of the background image. If the input is a **{width: Length, height: Length}** object and only one attribute is set, the other attribute is the set value multiplied by the original aspect ratio of the image. By default, the original image aspect ratio remains unchanged.<br>Default value: **ImageSize.Auto**|
| backgroundImagePosition | [Position](ts-types.md#position8) \| [Alignment](ts-appendix-enums.md#alignment) | Position of the background image in the component.<br>Default value:<br>**{<br>x: 0,<br>y: 0<br>}** |
| backgroundImagePosition | [Position](ts-types.md#position8) \| [Alignment](ts-appendix-enums.md#alignment) | Position of the background image in the component, that is, the coordinates relative to the upper left corner of the component.<br>Default value:<br>{<br>x: 0,<br>y: 0<br>} <br> When **x** and **y** are set in percentage, the offset is calculated based on the width and height of the component.|
## Example
......
......@@ -11,8 +11,8 @@ Layout constraints refer to constraints on the aspect ratio and display priority
| Name | Type | Description |
| --------------- | ------ | ---------------------------------------- |
| aspectRatio | number | Aspect ratio of the component. |
| displayPriority | number | Display priority for the component in the layout container. When the space of the parent container is insufficient, the component with a lower priority is hidden.<br>**NOTE**<br>This attribute is valid only for the **\<Row>**, **\<Column>**, and **\<Flex>** (single-row) container components.|
| aspectRatio | number | Aspect ratio of the component, which can be obtained using the following formula: Width/Height. |
| displayPriority | number | Display priority for the component in the layout container. When the space of the parent container is insufficient, the component with a lower priority is hidden.<br>The digits after the decimal point are not counted in determining the display priority. That is, numbers in the [x, x + 1) range are considered to represent the same priority. For example, **1.0** and **1.9** represent the same priority.<br>**NOTE**<br>This attribute is valid only for the **\<Row>**, **\<Column>**, and **\<Flex>** (single-row) container components. |
## Example
......@@ -22,29 +22,32 @@ Layout constraints refer to constraints on the aspect ratio and display priority
@Entry
@Component
struct AspectRatioExample {
private children : string[] = ['1', '2', '3', '4', '5', '6']
private children: string[] = ['1', '2', '3', '4', '5', '6']
build() {
Column({space: 20}) {
Column({ space: 20 }) {
Text('using container: row').fontSize(14).fontColor(0xCCCCCC).width('100%')
Row({space: 10}) {
Row({ space: 10 }) {
ForEach(this.children, (item) => {
// Component width = Component height x 1.5 = 90
Text(item)
.backgroundColor(0xbbb2cb)
.fontSize(20)
.aspectRatio(1.5)
.height(60)
// Component height = Component width/1.5 = 60/1.5 = 40
Text(item)
.backgroundColor(0xbbb2cb)
.fontSize(20)
.aspectRatio(1.5)
.width(60)
}, item=>item)
}, item => item)
}
.size({width: "100%", height: 100})
.size({ width: "100%", height: 100 })
.backgroundColor(0xd2cab3)
.clip(true)
// Grid child component width/height = 3/2
Text('using container: grid').fontSize(14).fontColor(0xCCCCCC).width('100%')
Grid() {
ForEach(this.children, (item) => {
......@@ -54,12 +57,12 @@ struct AspectRatioExample {
.fontSize(40)
.aspectRatio(1.5)
}
}, item=>item)
}, item => item)
}
.columnsTemplate('1fr 1fr 1fr')
.columnsGap(10)
.rowsGap(10)
.size({width: "100%", height: 165})
.size({ width: "100%", height: 165 })
.backgroundColor(0xd2cab3)
}.padding(10)
}
......@@ -67,47 +70,53 @@ struct AspectRatioExample {
```
**Figure 1** Portrait display
![en-us_image_0000001256978379](figures/en-us_image_0000001256978379.gif)
**Figure 2** Landscape display
![en-us_image_0000001212218476](figures/en-us_image_0000001212218476.gif)
```ts
class ContainerInfo {
label : string = ''
size : string = ''
label: string = '';
size: string = '';
}
class ChildInfo {
text : string = ''
priority : number = 0
text: string = '';
priority: number = 0;
}
@Entry
@Component
struct DisplayPriorityExample {
private container : ContainerInfo[] = [
{label: 'Big container', size: '90%'},
{label: 'Middle container', size: '50%'},
{label: 'Small container', size: '30%'}
// Display the container size.
private container: ContainerInfo[] = [
{ label: 'Big container', size: '90%' },
{ label: 'Middle container', size: '50%' },
{ label: 'Small container', size: '30%' }
]
private children : ChildInfo[] = [
{text: '1\n(priority:2)', priority: 2},
{text: '2\n(priority:1)', priority: 1},
{text: '3\n(priority:3)', priority: 3},
{text: '4\n(priority:1)', priority: 1},
{text: '5\n(priority:2)', priority: 2}
private children: ChildInfo[] = [
{ text: '1\n(priority:2)', priority: 2 },
{ text: '2\n(priority:1)', priority: 1 },
{ text: '3\n(priority:3)', priority: 3 },
{ text: '4\n(priority:1)', priority: 1 },
{ text: '5\n(priority:2)', priority: 2 }
]
@State currentIndex : number = 0
@State currentIndex: number = 0;
build() {
Column({space: 10}) {
Column({ space: 10 }) {
// Switch the size of the parent container.
Button(this.container[this.currentIndex].label).backgroundColor(0x317aff)
.onClick((event: ClickEvent) => {
this.currentIndex = (this.currentIndex + 1) % this.container.length
.onClick(() => {
this.currentIndex = (this.currentIndex + 1) % this.container.length;
})
Flex({justifyContent: FlexAlign.SpaceBetween}) {
ForEach(this.children, (item)=>{
// Set the width for the parent flex container through variables.
Flex({ justifyContent: FlexAlign.SpaceBetween }) {
ForEach(this.children, (item) => {
// Bind the display priority to the child component through displayPriority.
Text(item.text)
.width(120)
.height(60)
......@@ -115,11 +124,11 @@ struct DisplayPriorityExample {
.textAlign(TextAlign.Center)
.backgroundColor(0xbbb2cb)
.displayPriority(item.priority)
}, item=>item.text)
}, item => item.text)
}
.width(this.container[this.currentIndex].size)
.backgroundColor(0xd2cab3)
}.width("100%").margin({top:50})
}.width("100%").margin({ top: 50 })
}
}
......
......@@ -8,10 +8,9 @@ You can set overlay text for a component.
## Attributes
| Name | Type | Description |
| ------- | ----------------------------- | ------------------------- |
| overlay | value: string,<br>options?: {<br>align?: [Alignment](ts-appendix-enums.md#alignment), <br>offset?: {<br> x?: number,<br> y?: number<br> }<br>} | Overlay added to the component. The overlay has the same layout as the component.<br>Default value:<br>{<br>align: Alignment.Center,<br>offset: {0, 0}<br>} |
| Name| Type| Default Value| Description|
| -------- | -------- | -------- | -------- |
| overlay | value: string,<br>options?: {<br>align?: [Alignment](ts-appendix-enums.md#alignment), <br>offset?: {x?: number, y?: number}<br>} | {<br>align: Alignment.Center,<br>offset: {0, 0}<br>} | Overlay added to the component.<br> **value**: mask text.<br>**options**: text positioning. **align** indicates the location of the text relative to the component. **[offset](ts-universal-attributes-location.md)** indicates the offset of the text relative to the upper left corner of itself. By default, the text is in the upper left corner of the component.<br>If both **align** and **offset** are set, the text is first positioned relative to the component, and then offset relative to the upper left corner of itself.|
## Example
......@@ -28,7 +27,10 @@ struct OverlayExample {
Column() {
Image($r('app.media.img'))
.width(240).height(240)
.overlay("Winter is a beautiful season, especially when it snows.", { align: Alignment.Bottom, offset: { x: 0, y: -15 } })
.overlay("Winter is a beautiful season, especially when it snows.", {
align: Alignment.Bottom,
offset: { x: 0, y: -15 }
})
}.border({ color: Color.Black, width: 2 })
}.width('100%')
}.padding({ top: 20 })
......
......@@ -10,7 +10,7 @@ The visibility attribute controls whether a component is visible.
| Name | Type | Description |
| ---------- | ---------------------------- | ------------------------------------------ |
| visibility | [Visibility](ts-appendix-enums.md#visibility) | Whether the component is visible. Note that even if a component is hidden, it needs to be re-created when the page is refreshed. Therefore, you are advised to use [conditional rendering](../../ui/ts-rending-control-syntax-if-else.md) instead under scenarios where consistently high performance is required.<br>Default value: **Visibility.Visible**|
| visibility | [Visibility](ts-appendix-enums.md#visibility) | Whether the component is visible. Note that even if a component is invisible, it still needs to be re-created when the page is refreshed. Therefore, you are advised to use [conditional rendering](../../quick-start/arkts-rendering-control.md#conditional-rendering) instead under scenarios where consistently high performance is required.<br>Default value: **Visibility.Visible**|
## Example
......@@ -23,20 +23,21 @@ struct VisibilityExample {
build() {
Column() {
Column() {
Text('Visible').fontSize(9).width('90%').fontColor(0xCCCCCC)
Row().visibility(Visibility.Visible).width('90%').height(80).backgroundColor(0xAFEEEE)
Text('None').fontSize(9).width('90%').fontColor(0xCCCCCC)
// The component is hidden, and no placeholder is used.
Text('None').fontSize(9).width('90%').fontColor(0xCCCCCC)
Row().visibility(Visibility.None).width('90%').height(80).backgroundColor(0xAFEEEE)
Text('Hidden').fontSize(9).width('90%').fontColor(0xCCCCCC)
// The component is hidden, and a placeholder is used for it in the layout.
Text('Hidden').fontSize(9).width('90%').fontColor(0xCCCCCC)
Row().visibility(Visibility.Hidden).width('90%').height(80).backgroundColor(0xAFEEEE)
// The component is visiable, which is the default display mode.
Text('Visible').fontSize(9).width('90%').fontColor(0xCCCCCC)
Row().visibility(Visibility.Visible).width('90%').height(80).backgroundColor(0xAFEEEE)
}.width('90%').border({ width: 1 })
}.width('100%').margin({ top: 5 })
}
}
```
![en-us_image_0000001257058421](figures/en-us_image_0000001257058421.gif)
![visibility.png](figures/visibility.png)
# Sensor Error Codes
## 14500101 Service exception.
## 14500101 Service Exception
**Error Message**
......@@ -14,7 +14,7 @@ This error code is reported if the HDI service is abnormal when the **on**, **on
The HDI service is abnormal.
**Procedure**
**Solution**
1. Retry the operation at a specified interval (for example, 1s) or at an exponential increase interval.
2. If the operation fails for three consecutive times, stop the retry. You can also attempt to obtain the sensor list to check for device availability.
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册