提交 3cee84e4 编写于 作者: L luoying_ace 提交者: Gitee

Merge branch 'OpenHarmony-3.1-Release' of gitee.com:openharmony/docs into ly810

Signed-off-by: Nluoying_ace <luoying19@huawei.com>
......@@ -6,22 +6,20 @@ The Distributed Data Service (DDS) implements synchronization of application dat
## Available APIs
For details about the APIs related to distributed data, see [Distributed Data Management](../reference/apis/js-apis-distributed-data.md).
The table below describes the APIs provided by the OpenHarmony DDS module.
**Table 1** APIs provided by the DDS
| Category | API | Description |
| -------------------------- | ------------------------------------------------------------ | ----------------------------------------------- |
| Creating a distributed database | createKVManager(config:&nbsp;KVManagerConfig,&nbsp;callback:&nbsp;AsyncCallback&lt;KVManager&gt;):&nbsp;void<br>createKVManager(config:&nbsp;KVManagerConfig):&nbsp;Promise&lt;KVManager> | Creates a **KVManager** object for database management.|
| Obtaining a distributed KV store | getKVStore&lt;T&nbsp;extends&nbsp;KVStore&gt;(storeId:&nbsp;string,&nbsp;options:&nbsp;Options,&nbsp;callback:&nbsp;AsyncCallback&lt;T&gt;):&nbsp;void<br>getKVStore&lt;T&nbsp;extends&nbsp;KVStore&gt;(storeId:&nbsp;string,&nbsp;options:&nbsp;Options):&nbsp;Promise&lt;T&gt; | Obtains the KV store with the specified **Options** and **storeId**.|
| Managing data in a distributed KV store| put(key:&nbsp;string,&nbsp;value:&nbsp;Uint8Array&nbsp;\|&nbsp;string&nbsp;\|&nbsp;number&nbsp;\|&nbsp;boolean,&nbsp;callback:&nbsp;AsyncCallback&lt;void&gt;):&nbsp;void<br>put(key:&nbsp;string,&nbsp;value:&nbsp;Uint8Array&nbsp;\|&nbsp;string&nbsp;\|&nbsp;number&nbsp;\|&nbsp;boolean):&nbsp;Promise&lt;void> | Inserts and updates data. |
| Managing data in a distributed KV store| delete(key:&nbsp;string,&nbsp;callback:&nbsp;AsyncCallback&lt;void&gt;):&nbsp;void<br>delete(key:&nbsp;string):&nbsp;Promise&lt;void> | Deletes data. |
| Managing data in a distributed KV store| get(key:&nbsp;string,&nbsp;callback:&nbsp;AsyncCallback&lt;Uint8Array&nbsp;\|&nbsp;string&nbsp;\|&nbsp;boolean&nbsp;\|&nbsp;number&gt;):&nbsp;void<br>get(key:&nbsp;string):&nbsp;Promise&lt;Uint8Array&nbsp;\|&nbsp;string&nbsp;\|&nbsp;boolean&nbsp;\|&nbsp;number> | Queries data. |
| Subscribing to changes in the distributed data | on(event:&nbsp;'dataChange',&nbsp;type:&nbsp;SubscribeType,&nbsp;observer:&nbsp;Callback&lt;ChangeNotification&gt;):&nbsp;void<br>on(event:&nbsp;'syncComplete',&nbsp;syncCallback:&nbsp;Callback&lt;Array&lt;[string,&nbsp;number]&gt;&gt;):&nbsp;void | Subscribes to data changes in the KV store. |
| Synchronizing data across devices | sync(deviceIdList:&nbsp;string[],&nbsp;mode:&nbsp;SyncMode,&nbsp;allowedDelayMs?:&nbsp;number):&nbsp;void | Triggers database synchronization in manual mode. |
| API | Description |
| ------------------------------------------------------------ | ----------------------------------------------- |
| createKVManager(config:KVManagerConfig,callback:AsyncCallback&lt;KVManager&gt;):void<br>createKVManager(config:KVManagerConfig):Promise&lt;KVManager> | Creates a **KVManager** object for database management.|
| getKVStore&lt;TextendsKVStore&gt;(storeId:string,options:Options,callback:AsyncCallback&lt;T&gt;):void<br>getKVStore&lt;TextendsKVStore&gt;(storeId:string,options:Options):Promise&lt;T&gt; | Obtains a KV store with the specified **Options** and **storeId**.|
| put(key:string,value:Uint8Array\|string\|number\|boolean,callback:AsyncCallback&lt;void&gt;):void<br>put(key:string,value:Uint8Array\|string\|number\|boolean):Promise&lt;void> | Inserts and updates data. |
| delete(key:string,callback:AsyncCallback&lt;void&gt;):void<br>delete(key:string):Promise&lt;void> | Deletes data. |
| get(key:string,callback:AsyncCallback&lt;Uint8Array\|string\|boolean\|number&gt;):void<br>get(key:string):Promise&lt;Uint8Array\|string\|boolean\|number> | Queries data. |
| on(event:'dataChange',type:SubscribeType,observer:Callback&lt;ChangeNotification&gt;):void<br>on(event:'syncComplete',syncCallback:Callback&lt;Array&lt;[string,number]&gt;&gt;):void | Subscribes to data changes in the KV store. |
| sync(deviceIdList:string[],mode:SyncMode,allowedDelayMs?:number):void | Triggers database synchronization in manual mode. |
......@@ -36,11 +34,14 @@ The following uses a single KV store as an example to describe the development p
```
2. Create a **KvManager** instance based on the specified **KvManagerConfig** object.
1. Create a **KvManagerConfig** object based on the application context.
2. Create a **KvManager** instance.
(1) Create a **KvManagerConfig** object based on the application context.
(2) Create a **KvManager** instance.
The sample code is as follows:
```js
```
let kvManager;
try {
const kvManagerConfig = {
......@@ -63,9 +64,12 @@ The following uses a single KV store as an example to describe the development p
}
```
3. Create and obtain a single KV store.
1. Declare the ID of the single KV store to create.
2. Create a single KV store. You are advised to disable automatic synchronization (**autoSync:false**) and call **sync** when a synchronization is required.
(1) Declare the ID of the single KV store to create.
(2) Create a single KV store. You are advised to disable automatic synchronization (**autoSync:false**) and call **sync** when a synchronization is required.
The sample code is as follows:
```js
......@@ -92,8 +96,9 @@ The following uses a single KV store as an example to describe the development p
}
```
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/>
> For data synchronization between networked devices, you are advised to open the distributed KV store during application startup to obtain the database handle. With this database handle (**kvStore** in this example), you can perform operations, such as inserting data into the KV store, without creating the KV store repeatedly during the lifecycle of the handle.
> **NOTE**
>
> For data synchronization between networked devices, you are advised to open the distributed KV store during application startup to obtain the database handle. With this database handle (`kvStore` in this example), you can perform operations, such as inserting data into the KV store, without creating the KV store repeatedly during the lifecycle of the handle.
4. Subscribe to changes in the distributed data.<br/>
The following is the sample code for subscribing to the data changes of a single KV store:
......@@ -104,8 +109,10 @@ The following uses a single KV store as an example to describe the development p
```
5. Write data to the single KV store.
1. Construct the key and value to be written into the single KV store.
2. Write key-value pairs into the single KV store.
(1) Construct the key and value to be written into the single KV store.
(2) Write key-value pairs into the single KV store.
The following is the sample code for writing key-value pairs of the string type into the single KV store:
......@@ -126,8 +133,10 @@ The following uses a single KV store as an example to describe the development p
```
6. Query data in the single KV store.
1. Construct the key to be queried from the single KV store.
2. Query data from the single KV store.
(1) Construct the key to be queried from the single KV store.
(2) Query data from the single KV store.
The following is the sample code for querying data of the string type from the single KV store:
```js
......@@ -152,7 +161,11 @@ The following uses a single KV store as an example to describe the development p
7. Synchronize data to other devices.<br/>
Select the devices in the same network and the synchronization mode to synchronize data.
The following is the sample code for data synchronization in a single KV store. **deviceIds** can be obtained by deviceManager by calling **getTrustedDeviceListSync()**, and **1000** indicates that the maximum delay time is 1000 ms.
> **NOTE**
>
> The APIs of the `deviceManager` module are system interfaces.
The following is the sample code for synchronizing data in a single KV store:
```js
import deviceManager from '@ohos.distributedHardware.deviceManager';
......@@ -161,7 +174,7 @@ The following uses a single KV store as an example to describe the development p
deviceManager.createDeviceManager("bundleName", (err, value) => {
if (!err) {
devManager = value;
// Obtain deviceIds.
// deviceIds is obtained by deviceManager by calling getTrustedDeviceListSync().
let deviceIds = [];
if (devManager != null) {
var devices = devManager.getTrustedDeviceListSync();
......@@ -170,6 +183,7 @@ The following uses a single KV store as an example to describe the development p
}
}
try{
// 1000 indicates that the maximum delay is 1000 ms.
kvStore.sync(deviceIds, distributedData.SyncMode.PUSH_ONLY, 1000);
}catch (e) {
console.log("An unexpected error occurred. Error:" + e);
......@@ -177,7 +191,3 @@ The following uses a single KV store as an example to describe the development p
}
});
```
## Samples
The following samples are provided to help you better understand the distributed data development:
- [`KvStore`: Distributed Database (eTS) (API8)](https://gitee.com/openharmony/app_samples/tree/master/data/Kvstore)
- [Distributed Database](https://gitee.com/openharmony/codelabs/tree/master/Data/JsDistributedData)
......@@ -76,8 +76,8 @@ Use the following APIs to delete a **Storage** instance or data file.
1. Import **@ohos.data.storage** and related modules to the development environment.
```js
import dataStorage from '@ohos.data.storage'
import featureAbility from '@ohos.ability.featureAbility' // Used to obtain the file storage path.
import dataStorage from '@ohos.data.storage';
import featureAbility from '@ohos.ability.featureAbility'; // Used to obtain the file storage path.
```
2. Create a **Storage** instance.
......@@ -85,9 +85,14 @@ Use the following APIs to delete a **Storage** instance or data file.
Read the specified file and load its data to the **Storage** instance for data operations.
```js
var context = featureAbility.getContext()
var path = await context.getFilesDir()
let promise = dataStorage.getStorage(path + '/mystore')
var path;
var context = featureAbility.getContext();
context.getFilesDir().then((filePath) => {
path = filePath;
console.info("======================>getFilesDirPromsie====================>");
});
let promise = dataStorage.getStorage(path + '/mystore');
```
......@@ -97,14 +102,14 @@ Use the following APIs to delete a **Storage** instance or data file.
```js
promise.then((storage) => {
let getPromise = storage.put('startup', 'auto') // Save data to the Storage instance.
let getPromise = storage.put('startup', 'auto'); // Save data to the Storage instance.
getPromise.then(() => {
console.info("Put the value of startup successfully.")
console.info("Succeeded in putting the value of startup.");
}).catch((err) => {
console.info("Put the value of startup failed with err: " + err)
console.info("Failed to put the value of startup with err: " + err);
})
}).catch((err) => {
console.info("Get the storage failed")
console.info("Failed to get the storage.");
})
```
......@@ -115,14 +120,14 @@ Use the following APIs to delete a **Storage** instance or data file.
```js
promise.then((storage) => {
let getPromise = storage.get('startup', 'default')
let getPromise = storage.get('startup', 'default');
getPromise.then((value) => {
console.info("The value of startup is " + value)
console.info("The value of startup is " + value);
}).catch((err) => {
console.info("Get the value of startup failed with err: " + err)
console.info("Failed to get the value of startup with err: " + err);
})
}).catch((err) => {
console.info("Get the storage failed")
console.info("Failed to get the storage.");
})
```
......@@ -142,15 +147,15 @@ Use the following APIs to delete a **Storage** instance or data file.
```js
promise.then((storage) => {
var observer = function (key) {
console.info("The key of " + key + " changed.")
console.info("The key of " + key + " changed.");
}
storage.on('change', observer)
storage.putSync('startup', 'auto') // Modify data in the Storage instance.
storage.flushSync() // Trigger the StorageObserver callback.
storage.on('change', observer);
storage.putSync('startup', 'auto'); // Modify data in the Storage instance.
storage.flushSync(); // Trigger the StorageObserver callback.
storage.off(...change..., observer) // Unsubscribe from the data changes.
storage.off('change', observer); // Unsubscribe from the data changes.
}).catch((err) => {
console.info("Get the storage failed")
console.info("Failed to get the storage.");
})
```
......@@ -160,11 +165,11 @@ Use the following APIs to delete a **Storage** instance or data file.
Use the **deleteStorage** method to delete the **Storage** singleton of the specified file from the memory, and delete the specified file, its backup file, and damaged files. After the specified files are deleted, the application cannot use that instance to perform any data operation. Otherwise, data inconsistency will occur. The deleted data and files cannot be restored.
```js
let promise = dataStorage.deleteStorage(path + '/mystore')
let promise = dataStorage.deleteStorage(path + '/mystore');
promise.then(() => {
console.info("Deleted successfully.")
console.info("Succeeded in deleting the storage.");
}).catch((err) => {
console.info("Deleted failed with err: " + err)
console.info("Failed to deleted the storage with err: " + err);
})
```
......@@ -14,47 +14,49 @@ The following table describes APIs available for obtaining device location infor
**Table 1** APIs for obtaining device location information
| API| Description|
| -------- | -------- |
| on(type:&nbsp;'locationChange',&nbsp;request:&nbsp;LocationRequest,&nbsp;callback:&nbsp;Callback&lt;Location&gt;)&nbsp;:&nbsp;void | Registers a listener for location changes with a location request initiated.|
| off(type:&nbsp;'locationChange',&nbsp;callback?:&nbsp;Callback&lt;Location&gt;)&nbsp;:&nbsp;void | Unregisters the listener for location changes with the corresponding location request deleted.|
| on(type:&nbsp;'locationServiceState',&nbsp;callback:&nbsp;Callback&lt;boolean&gt;)&nbsp;:&nbsp;void | Registers a listener for location service status change events.|
| off(type:&nbsp;'locationServiceState',&nbsp;callback:&nbsp;Callback&lt;boolean&gt;)&nbsp;:&nbsp;void | Unregisters the listener for location service status change events.|
| on(type:&nbsp;'cachedGnssLocationsReporting',&nbsp;request:&nbsp;CachedGnssLoactionsRequest,&nbsp;callback:&nbsp;Callback&lt;Array&lt;Location&gt;&gt;)&nbsp;:&nbsp;void; | Registers a listener for cached GNSS location reports.|
| off(type:&nbsp;'cachedGnssLocationsReporting',&nbsp;callback?:&nbsp;Callback&lt;Array&lt;Location&gt;&gt;)&nbsp;:&nbsp;void; | Unregisters the listener for cached GNSS location reports.|
| on(type:&nbsp;'gnssStatusChange',&nbsp;callback:&nbsp;Callback&lt;SatelliteStatusInfo&gt;)&nbsp;:&nbsp;void; | Registers a listener for satellite status change events.|
| off(type:&nbsp;'gnssStatusChange',&nbsp;callback?:&nbsp;Callback&lt;SatelliteStatusInfo&gt;)&nbsp;:&nbsp;void; | Unregisters the listener for satellite status change events.|
| on(type:&nbsp;'nmeaMessageChange',&nbsp;callback:&nbsp;Callback&lt;string&gt;)&nbsp;:&nbsp;void; | Registers a listener for GNSS NMEA message change events.|
| off(type:&nbsp;'nmeaMessageChange',&nbsp;callback?:&nbsp;Callback&lt;string&gt;)&nbsp;:&nbsp;void; | Unregisters the listener for GNSS NMEA message change events.|
| on(type:&nbsp;'fenceStatusChange',&nbsp;request:&nbsp;GeofenceRequest,&nbsp;want:&nbsp;WantAgent)&nbsp;:&nbsp;void; | Registers a listener for status change events of the specified geofence.|
| off(type:&nbsp;'fenceStatusChange',&nbsp;request:&nbsp;GeofenceRequest,&nbsp;want:&nbsp;WantAgent)&nbsp;:&nbsp;void; | Unregisters the listener for status change events of the specified geofence.|
| getCurrentLocation(request:&nbsp;CurrentLocationRequest,&nbsp;callback:&nbsp;AsyncCallback&lt;Location&gt;)&nbsp;:&nbsp;void | Obtains the current location. This API uses an asynchronous callback to return the result. |
| getCurrentLocation(request?:&nbsp;CurrentLocationRequest)&nbsp;:&nbsp;Promise&lt;Location&gt; | Obtains the current location. This API uses a promise to return the result. |
| getLastLocation(callback:&nbsp;AsyncCallback&lt;Location&gt;)&nbsp;:&nbsp;void | Obtains the previous location. This API uses an asynchronous callback to return the result.|
| getLastLocation()&nbsp;:&nbsp;Promise&lt;Location&gt; | Obtains the previous location. This API uses a promise to return the result. |
| isLocationEnabled(callback:&nbsp;AsyncCallback&lt;boolean&gt;)&nbsp;:&nbsp;void | Checks whether the location service is enabled. This API uses an asynchronous callback to return the result.|
| isLocationEnabled()&nbsp;:&nbsp;Promise&lt;boolean&gt; | Checks whether the location service is enabled. This API uses a promise to return the result.|
| requestEnableLocation(callback:&nbsp;AsyncCallback&lt;boolean&gt;)&nbsp;:&nbsp;void | Requests to enable the location service. This API uses an asynchronous callback to return the result.|
| requestEnableLocation()&nbsp;:&nbsp;Promise&lt;boolean&gt; | Requests to enable the location service. This API uses a promise to return the result.|
| enableLocation(callback:&nbsp;AsyncCallback&lt;boolean&gt;)&nbsp;:&nbsp;void | Enables the location service. This API uses an asynchronous callback to return the result.|
| enableLocation()&nbsp;:&nbsp;Promise&lt;boolean&gt; | Enables the location service. This API uses a promise to return the result.|
| disableLocation(callback:&nbsp;AsyncCallback&lt;boolean&gt;)&nbsp;:&nbsp;void | Disables the location service. This function uses an asynchronous callback to return the result.|
| disableLocation()&nbsp;:&nbsp;Promise&lt;boolean&gt; | Disables the location service. This function uses a promise to return the result.|
| getCachedGnssLocationsSize(callback:&nbsp;AsyncCallback&lt;number&gt;)&nbsp;:&nbsp;void; | Obtains the number of cached GNSS locations. This function uses an asynchronous callback to return the result.|
| getCachedGnssLocationsSize()&nbsp;:&nbsp;Promise&lt;number&gt;; | Obtains the number of cached GNSS locations. This function uses a promise to return the result.|
| flushCachedGnssLocations(callback:&nbsp;AsyncCallback&lt;boolean&gt;)&nbsp;:&nbsp;void; | Obtains all cached GNSS locations and clears the GNSS cache queue. This function uses an asynchronous callback to return the result.|
| flushCachedGnssLocations()&nbsp;:&nbsp;Promise&lt;boolean&gt;; | Obtains all cached GNSS locations and clears the GNSS cache queue. This function uses a promise to return the result.|
| sendCommand(command:&nbsp;LocationCommand,&nbsp;callback:&nbsp;AsyncCallback&lt;boolean&gt;)&nbsp;:&nbsp;void; | Sends extended commands to the location subsystem. This function uses an asynchronous callback to return the result.|
| sendCommand(command:&nbsp;LocationCommand)&nbsp;:&nbsp;Promise&lt;boolean&gt;; | Sends extended commands to the location subsystem. This function uses a promise to return the result.|
| isLocationPrivacyConfirmed(type&nbsp;:&nbsp;LocationPrivacyType,&nbsp;callback:&nbsp;AsyncCallback&lt;boolean&gt;)&nbsp;:&nbsp;void; | Checks whether a user agrees with the privacy statement of the location service. This function uses an asynchronous callback to return the result.|
| isLocationPrivacyConfirmed(type&nbsp;:&nbsp;LocationPrivacyType,)&nbsp;:&nbsp;Promise&lt;boolean&gt;; | Checks whether a user agrees with the privacy statement of the location service. This function uses a promise to return the result.|
| setLocationPrivacyConfirmStatus(type&nbsp;:&nbsp;LocationPrivacyType,&nbsp;isConfirmed&nbsp;:&nbsp;boolean,&nbsp;callback:&nbsp;AsyncCallback&lt;boolean&gt;)&nbsp;:&nbsp;void; | Sets the user confirmation status for the privacy statement of the location service. This function uses an asynchronous callback to return the result.|
| setLocationPrivacyConfirmStatus(type&nbsp;:&nbsp;LocationPrivacyType,&nbsp;isConfirmed&nbsp;:&nbsp;boolean)&nbsp;:&nbsp;Promise&lt;boolean&gt;; | Sets the user confirmation status for the privacy statement of the location service. This function uses a promise to return the result.|
| API | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| on(type: 'locationChange', request: LocationRequest, callback: Callback&lt;Location&gt;) : void | Registers a listener for location changes with a location request initiated. |
| off(type: 'locationChange', callback?: Callback&lt;Location&gt;) : void | Unregisters the listener for location changes with the corresponding location request deleted. |
| on(type: 'locationServiceState', callback: Callback&lt;boolean&gt;) : void | Registers a listener for location service status change events. |
| off(type: 'locationServiceState', callback: Callback&lt;boolean&gt;) : void | Unregisters the listener for location service status change events. |
| on(type: 'cachedGnssLocationsReporting', request: CachedGnssLoactionsRequest, callback: Callback&lt;Array&lt;Location&gt;&gt;) : void; | Registers a listener for cached GNSS location reports. |
| off(type: 'cachedGnssLocationsReporting', callback?: Callback&lt;Array&lt;Location&gt;&gt;) : void; | Unregisters the listener for cached GNSS location reports. |
| on(type: 'gnssStatusChange', callback: Callback&lt;SatelliteStatusInfo&gt;) : void; | Registers a listener for satellite status change events. |
| off(type: 'gnssStatusChange', callback?: Callback&lt;SatelliteStatusInfo&gt;) : void; | Unregisters the listener for satellite status change events. |
| on(type: 'nmeaMessageChange', callback: Callback&lt;string&gt;) : void; | Registers a listener for GNSS NMEA message change events. |
| off(type: 'nmeaMessageChange', callback?: Callback&lt;string&gt;) : void; | Unregisters the listener for GNSS NMEA message change events. |
| on(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void; | Registers a listener for status change events of the specified geofence. |
| off(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void; | Unregisters the listener for status change events of the specified geofence. |
| getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback&lt;Location&gt;) : void | Obtains the current location. This API uses an asynchronous callback to return the result. |
| getCurrentLocation(request?: CurrentLocationRequest) : Promise&lt;Location&gt; | Obtains the current location. This API uses a promise to return the result. |
| getLastLocation(callback: AsyncCallback&lt;Location&gt;) : void | Obtains the previous location. This API uses an asynchronous callback to return the result. |
| getLastLocation() : Promise&lt;Location&gt; | Obtains the previous location. This API uses a promise to return the result. |
| isLocationEnabled(callback: AsyncCallback&lt;boolean&gt;) : void | Checks whether the location service is enabled. This API uses an asynchronous callback to return the result. |
| isLocationEnabled() : Promise&lt;boolean&gt; | Checks whether the location service is enabled. This API uses a promise to return the result. |
| requestEnableLocation(callback: AsyncCallback&lt;boolean&gt;) : void | Requests to enable the location service. This API uses an asynchronous callback to return the result. |
| requestEnableLocation() : Promise&lt;boolean&gt; | Requests to enable the location service. This API uses a promise to return the result. |
| enableLocation(callback: AsyncCallback&lt;boolean&gt;) : void | Enables the location service. This API uses an asynchronous callback to return the result. |
| enableLocation() : Promise&lt;boolean&gt; | Enables the location service. This API uses a promise to return the result. |
| disableLocation(callback: AsyncCallback&lt;boolean&gt;) : void | Disables the location service. This API uses an asynchronous callback to return the result. |
| disableLocation() : Promise&lt;boolean&gt; | Disables the location service. This API uses a promise to return the result. |
| getCachedGnssLocationsSize(callback: AsyncCallback&lt;number&gt;) : void; | Obtains the number of cached GNSS locations. This API uses an asynchronous callback to return the result. |
| getCachedGnssLocationsSize() : Promise&lt;number&gt;; | Obtains the number of cached GNSS locations. This API uses a promise to return the result. |
| flushCachedGnssLocations(callback: AsyncCallback&lt;boolean&gt;) : void; | Obtains all cached GNSS locations and clears the GNSS cache queue. This API uses an asynchronous callback to return the result.|
| flushCachedGnssLocations() : Promise&lt;boolean&gt;; | Obtains all cached GNSS locations and clears the GNSS cache queue. This API uses a promise to return the result.|
| sendCommand(command: LocationCommand, callback: AsyncCallback&lt;boolean&gt;) : void; | Sends extended commands to the location subsystem. This API uses an asynchronous callback to return the result.|
| sendCommand(command: LocationCommand) : Promise&lt;boolean&gt;; | Sends extended commands to the location subsystem. This API uses a promise to return the result. |
| isLocationPrivacyConfirmed(type : LocationPrivacyType, callback: AsyncCallback&lt;boolean&gt;) : void; | Checks whether a user agrees with the privacy statement of the location service. This API uses an asynchronous callback to return the result.|
| isLocationPrivacyConfirmed(type : LocationPrivacyType,) : Promise&lt;boolean&gt;; | Checks whether a user agrees with the privacy statement of the location service. This API uses a promise to return the result.|
| setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed : boolean, callback: AsyncCallback&lt;boolean&gt;) : void; | Sets the user confirmation status for the privacy statement of the location service. This API uses an asynchronous callback to return the result.|
| setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed : boolean) : Promise&lt;boolean&gt;; | Sets the user confirmation status for the privacy statement of the location service. This API uses a promise to return the result.|
## How to Develop
1. Before using basic location capabilities, check whether your application has been granted the permission to access the device location information. If not, your application needs to obtain the permission from the user. For details, see .
To learn more about the APIs for obtaining device location information, see [Geolocation](../reference/apis/js-apis-geolocation.md).
1. Before using basic location capabilities, check whether your application has been granted the permission to access the device location information. If not, your application needs to obtain the permission from the user as described below.
The system provides the following location permissions:
- ohos.permission.LOCATION
......@@ -62,7 +64,7 @@ The following table describes APIs available for obtaining device location infor
The **ohos.permission.LOCATION** permission is a must if your application needs to access the device location information.
If your application needs to access the device location information when running on the background, it must be allowed to run on the background in the configuration file and also granted the **ohos.permission.LOCATION_IN_BACKGROUND** permission. In this way, the system continues to report device location information even when your application moves to the background.
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.
To allow your application to access device location information, declare the required permissions in the **module.json** file of your application. The sample code is as follows:
......@@ -82,7 +84,7 @@ The following table describes APIs available for obtaining device location infor
}
```
For details about the configuration fields, see the description of the **module.json** file.
For details about these fields, see [Application Package Structure Configuration File](../quick-start/stage-structure.md).
2. Import the **geolocation** module by which you can implement all APIs related to the basic location capabilities.
......@@ -90,7 +92,8 @@ The following table describes APIs available for obtaining device location infor
import geolocation from '@ohos.geolocation';
```
3. Instantiate the **LocationRequest** object. This object provides APIs to notify the system of the location service type and the interval of reporting location information.<br>
3. Instantiate the **LocationRequest** object. This object provides APIs to notify the system of the location service type and the interval of reporting location information.
**Method 1:**
To better serve your needs for using APIs, the system has categorized APIs into different packages to match your common use cases of the location function. In this way, you can directly use the APIs specific to a certain use case, making application development much easier. The following table lists the use cases currently supported.
......@@ -110,18 +113,18 @@ The following table describes APIs available for obtaining device location infor
**Table 2** Common use cases of the location function
| Use Case| Constant| Description|
| -------- | -------- | -------- |
| Navigation| NAVIGATION | Applicable when your application needs to obtain the real-time location of a mobile device outdoors, such as navigation for driving or walking. In this scenario, the GNSS positioning technology is mainly used to ensure the location accuracy. However, due to its limitations, the technology may be unable to provide the location service when navigation is just started or when the user moves into a shielded environment such as indoors or a garage. To resolve this issue, the system uses the network positioning technology as an alternative to provide the location service for your application until the GNSS can provide stable location results. This helps achieve a smooth navigation experience for users.<br>By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.|
| Use Case | Constant | Description |
| ------------ | ------------------- | ------------------------------------------------------------ |
| Navigation | NAVIGATION | Applicable when your application needs to obtain the real-time location of a mobile device outdoors, such as navigation for driving or walking. In this scenario, the GNSS positioning technology is mainly used to ensure the location accuracy. However, due to its limitations, the technology may be unable to provide the location service when navigation is just started or when the user moves into a shielded environment such as indoors or a garage. To resolve this issue, the system uses the network positioning technology as an alternative to provide the location service for your application until the GNSS can provide stable location results. This helps achieve a smooth navigation experience for users.<br>By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.|
| Trajectory tracking| TRAJECTORY_TRACKING | Applicable when your application needs to record user trajectories, for example, the track recording function of sports applications. In this scenario, the GNSS positioning technology is mainly used to ensure the location accuracy.<br>By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.|
| Ride hailing| CAR_HAILING | Applicable when your application needs to obtain the current location of a user who is hailing a taxi.<br>By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.|
| Life service| DAILY_LIFE_SERVICE | Applicable when your application only needs the approximate user location for recommendations and push notifications in scenarios such as when the user is browsing news, shopping online, and ordering food.<br>By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.|
| Power efficiency| NO_POWER | Applicable when your application does not proactively start the location service for a higher battery efficiency. When responding to another application requesting the same location service, the system marks a copy of the location result to your application. In this way, your application will not consume extra power for obtaining the user location.<br>By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.|
| Power efficiency | NO_POWER | Applicable when your application does not proactively start the location service for a higher battery efficiency. When responding to another application requesting the same location service, the system marks a copy of the location result to your application. In this way, your application will not consume extra power for obtaining the user location.<br>By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.|
The following example instantiates the **RequestParam** object for navigation:
Sample code for initializing **requestInfo** for navigation:
```
var requestInfo = {'scenario': 0x301, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0};
var requestInfo = {'scenario': geolocation.LocationRequestScenario.NAVIGATION, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0};
```
**Method 2:**
......@@ -141,16 +144,16 @@ The following table describes APIs available for obtaining device location infor
**Table 3** Location priority policies
| Policy| Constant| Description|
| -------- | -------- | -------- |
| Location accuracy priority| ACCURACY | This policy mainly uses the GNSS positioning technology. In an open area, the technology can achieve the meter-level location accuracy, depending on the hardware performance of the device. However, in a shielded environment, the location accuracy may significantly decrease.<br>To use this policy, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.|
| Fast location priority| FAST_FIRST_FIX | This policy uses the GNSS positioning, base station positioning, WLAN positioning, and Bluetooth positioning technologies simultaneously to obtain the device location in both the indoor and outdoor scenarios. When all positioning technologies provide a location result, the system provides the most accurate location result for your application. This policy can lead to significant hardware resource consumption and power consumption.<br>To use this policy, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.|
| Policy | Constant | Description |
| ------------------ | -------------- | ------------------------------------------------------------ |
| Location accuracy priority | ACCURACY | This policy mainly uses the GNSS positioning technology. In an open area, the technology can achieve the meter-level location accuracy, depending on the hardware performance of the device. However, in a shielded environment, the location accuracy may significantly decrease.<br>To use this policy, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.|
| Fast location priority | FAST_FIRST_FIX | This policy uses the GNSS positioning, base station positioning, WLAN positioning, and Bluetooth positioning technologies simultaneously to obtain the device location in both the indoor and outdoor scenarios. When all positioning technologies provide a location result, the system provides the most accurate location result for your application. This policy can lead to significant hardware resource consumption and power consumption.<br>To use this policy, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.|
| Power efficiency priority| LOW_POWER | This policy mainly uses the base station positioning, WLAN positioning, and Bluetooth positioning technologies to obtain device location in both indoor and outdoor scenarios. The location accuracy depends on the distribution of surrounding base stations, visible WLANs, and Bluetooth devices and therefore may fluctuate greatly. This policy is recommended and can reduce power consumption when your application does not require high location accuracy or when base stations, visible WLANs, and Bluetooth devices are densely distributed.<br>To use this policy, you must declare at least the **ohos.permission.LOCATION** permission and obtain users' authorization.|
The following example instantiates the **RequestParam** object for the location accuracy priority policy:
Sample code for initializing **requestInfo** for the location accuracy priority policy:
```
var requestInfo = {'priority': 0x201, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0};
var requestInfo = {'priority': geolocation.LocationRequestPriority.ACCURACY, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0};
```
4. Instantiate the **Callback** object for the system to report location results.
......@@ -174,11 +177,15 @@ The following table describes APIs available for obtaining device location infor
geolocation.off('locationChange', locationChange);
```
If your application does not need the real-time device location, it can use the last known device location cached in the system instead.
If your application does not need the real-time device location, it can use the last known device location cached in the system instead.
```
geolocation.getLastLocation((data) => {
geolocation.getLastLocation((err, data) => {
if (err) {
console.log('getLastLocation: err: ' + JSON.stringify(err));
} else {
console.log('getLastLocation: data: ' + JSON.stringify(data));
}
});
```
......
# Performance Tracing
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> **NOTE**
> - The APIs of this module are no longer maintained since API version 8. It is recommended that you use the APIs of [hiTraceMeter](js-apis-hitracemeter.md) instead.
> - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
```
```js
import bytrace from '@ohos.bytrace';
```
......@@ -17,7 +17,11 @@ import bytrace from '@ohos.bytrace';
startTrace(name: string, taskId: number, expectedTime?: number): void
Starts a trace task. **expectedTime** is an optional parameter, which specifies the expected duration of the trace.
Marks the start of a timeslice trace task.
> **NOTE**
>
> If multiple trace tasks with the same name need to be performed at the same time or a trace task needs to be performed multiple times concurrently, different task IDs must be specified in **startTrace**. If the trace tasks with the same name are not performed at the same time, the same taskId can be used. For details, see the bytrace.finishTrace example.
**System capability**: SystemCapability.Developtools.Bytrace
......@@ -25,16 +29,14 @@ Starts a trace task. **expectedTime** is an optional parameter, which specifies
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| name | string | Yes| Name of the trace task to start.|
| taskId | number | Yes| Task ID.|
| name | string | Yes| Name of a timeslice trace task.|
| taskId | number | Yes| ID of a timeslice trace task.|
| expectedTime | number | No| Expected duration of the trace, in ms.|
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> If multiple trace tasks with the same name need to be performed at the same time or a trace task needs to be performed multiple times concurrently, different task IDs must be specified in **startTrace**. If the trace tasks with the same name are not performed at the same time, the same taskId can be used. For details, see the bytrace.finishTrace example.
**Example**
```
```js
bytrace.startTrace("myTestFunc", 1);
bytrace.startTrace("myTestFunc", 1, 5); // The expected duration of the trace is 5 ms.
```
......@@ -44,7 +46,11 @@ bytrace.startTrace("myTestFunc", 1, 5); // The expected duration of the trace is
finishTrace(name: string, taskId: number): void
Stops a trace task.
Marks the end of a timeslice trace task.
> **NOTE**
>
> To stop a trace task, the values of name and task ID in **finishTrace** must be the same as those in **startTrace**.
**System capability**: SystemCapability.Developtools.Bytrace
......@@ -52,15 +58,13 @@ Stops a trace task.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| name | string | Yes| Name of the trace task to start.|
| taskId | number | Yes| Task ID.|
| name | string | Yes| Name of a timeslice trace task.|
| taskId | number | Yes| ID of a timeslice trace task.|
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> To stop a trace task, the values of name and task ID in **finishTrace** must be the same as those in **startTrace**.
**Example**
```
```js
bytrace.finishTrace("myTestFunc", 1);
```
......@@ -91,9 +95,9 @@ bytrace.finishTrace("myTestFunc", 1);
traceByValue(name: string, count: number): void
Traces the value changes of a variable.
Defines the variable that indicates the number of timeslice trace tasks.
**System capability**: SystemCapability.Developtools.Bytrace
**System capability**: SystemCapability.HiviewDFX.HiTrace
**Parameters**
| Name| Type| Mandatory| Description|
......@@ -103,7 +107,7 @@ Traces the value changes of a variable.
**Example**
```
```js
let traceCount = 3;
bytrace.traceByValue("myTestCount", traceCount);
traceCount = 4;
......
......@@ -3,13 +3,12 @@
Lightweight storage provides applications with data processing capability and allows applications to perform lightweight data storage and query. Data is stored in key-value (KV) pairs. Keys are of the string type, and values can be of the number, string, or Boolean type.
> **NOTE**<br/>
> **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.
## Modules to Import
```js
......@@ -20,10 +19,10 @@ import data_storage from '@ohos.data.storage';
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| MAX_KEY_LENGTH | string | Yes| No| Maximum length of a key. It must be less than 80 bytes.|
| MAX_VALUE_LENGTH | string | Yes| No| Maximum length of a value. It must be less than 8192 bytes.|
| Name | Type | Readable | Writable | Description |
| ---------------- | ------ | -------- | -------- | ----------------------------------------------------------- |
| MAX_KEY_LENGTH | string | Yes | No | Maximum length of a key. It must be less than 80 bytes. |
| MAX_VALUE_LENGTH | string | Yes | No | Maximum length of a value. It must be less than 8192 bytes. |
## data_storage.getStorageSync
......@@ -35,25 +34,33 @@ Reads the specified file and loads its data to the **Storage** instance for data
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| path | string | Yes| Path of the target file.|
| Name | Type | Mandatory | Description |
| ---- | ------ | --------- | ------------------------ |
| path | string | Yes | Path of the target file. |
**Return value**
| Type| Description|
| -------- | -------- |
| [Storage](#storage) | **Storage** instance used for data storage operations.|
**Example**
```js
import data_storage from '@ohos.data.storage'
| Type | Description |
| ------------------- | ------------------------------------------------------ |
| [Storage](#storage) | **Storage** instance used for data storage operations. |
let path = '/data/storage/el2/database'
let storage = data_storage.getStorageSync(path + '/mystore')
storage.putSync('startup', 'auto')
storage.flushSync()
**Example**
```
```js
import featureAbility from '@ohos.ability.featureAbility';
var path;
var context = featureAbility.getContext();
context.getFilesDir().then((filePath) => {
path = filePath;
console.info("======================>getFilesDirPromsie====================>");
});
let storage = data_storage.getStorageSync(path + '/mystore');
storage.putSync('startup', 'auto');
storage.flushSync();
```
## data_storage.getStorage
......@@ -65,25 +72,33 @@ Reads the specified file and loads its data to the **Storage** instance for data
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| path | string | Yes| Path of the target file.|
| callback | AsyncCallback&lt;[Storage](#storage)&gt; | Yes| Callback used to return the execution result.|
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | --------- | --------------------------------------------- |
| path | string | Yes | Path of the target file. |
| callback | AsyncCallback&lt;[Storage](#storage)&gt; | Yes | Callback used to return the execution result. |
**Example**
```js
import data_storage from '@ohos.data.storage'
let path = '/data/storage/el2/database'
data_storage.getStorage(path + '/mystore', function (err, storage) {
```js
import featureAbility from '@ohos.ability.featureAbility';
var path;
var context = featureAbility.getContext();
context.getFilesDir().then((filePath) => {
path = filePath;
console.info("======================>getFilesDirPromsie====================>");
});
data_storage.getStorage(path + '/mystore', function (err, storage) {
if (err) {
console.info("Failed to get the storage. Path: " + path + '/mystore')
console.info("Failed to get the storage. path: " + path + '/mystore');
return;
}
storage.putSync('startup', 'auto')
storage.flushSync()
})
```
storage.putSync('startup', 'auto');
storage.flushSync();
})
```
## data_storage.getStorage
......@@ -95,29 +110,37 @@ Reads the specified file and loads its data to the **Storage** instance for data
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| path | string | Yes| Path of the target file.|
| Name | Type | Mandatory | Description |
| ---- | ------ | --------- | ------------------------ |
| path | string | Yes | Path of the target file. |
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;[Storage](#storage)&gt; | Promise used to return the result.|
**Example**
```js
import data_storage from '@ohos.data.storage'
| Type | Description |
| ---------------------------------- | ---------------------------------- |
| Promise&lt;[Storage](#storage)&gt; | Promise used to return the result. |
let path = '/data/storage/el2/database'
**Example**
let getPromise = data_storage.getStorage(path + '/mystore')
getPromise.then((storage) => {
storage.putSync('startup', 'auto')
storage.flushSync()
}).catch((err) => {
console.info("Failed to get the storage. Path: " + path + '/mystore')
})
```
```js
import featureAbility from '@ohos.ability.featureAbility';
var path;
var context = featureAbility.getContext();
context.getFilesDir().then((filePath) => {
path = filePath;
console.info("======================>getFilesDirPromsie====================>");
});
let getPromise = data_storage.getStorage(path + '/mystore');
getPromise.then((storage) => {
storage.putSync('startup', 'auto');
storage.flushSync();
}).catch((err) => {
console.info("Failed to get the storage. path: " + path + '/mystore');
})
```
## data_storage.deleteStorageSync
......@@ -129,15 +152,25 @@ Deletes the singleton **Storage** instance of a file from the memory, and delete
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| path | string | Yes| Path of the target file.|
| Name | Type | Mandatory | Description |
| ---- | ------ | --------- | ------------------------ |
| path | string | Yes | Path of the target file. |
**Example**
```js
let path = '/data/storage/el2/database'
data_storage.deleteStorageSync(path + '/mystore')
```
```js
import featureAbility from '@ohos.ability.featureAbility';
var path;
var context = featureAbility.getContext();
context.getFilesDir().then((filePath) => {
path = filePath;
console.info("======================>getFilesDirPromsie====================>");
});
data_storage.deleteStorageSync(path + '/mystore');
```
## data_storage.deleteStorage
......@@ -149,22 +182,32 @@ Deletes the singleton **Storage** instance of a file from the memory, and delete
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| path | string | Yes| Path of the target file.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback that returns no value.|
| Name | Type | Mandatory | Description |
| -------- | ------------------------- | --------- | ------------------------------- |
| path | string | Yes | Path of the target file. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback that returns no value. |
**Example**
```js
let path = '/data/storage/el2/database'
data_storage.deleteStorage(path + '/mystore', function (err) {
```js
import featureAbility from '@ohos.ability.featureAbility';
var path;
var context = featureAbility.getContext();
context.getFilesDir().then((filePath) => {
path = filePath;
console.info("======================>getFilesDirPromsie====================>");
});
data_storage.deleteStorage(path + '/mystore', function (err) {
if (err) {
console.info("Deleted failed with err: " + err)
return
console.info("Failed to delete the storage with err: " + err);
return;
}
console.info("Deleted successfully.")
})
```
console.info("Succeeded in deleting the storage.");
})
```
## data_storage.deleteStorage
......@@ -176,25 +219,35 @@ Deletes the singleton **Storage** instance of a file from the memory, and delete
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| path | string | Yes| Path of the target file.|
| Name | Type | Mandatory | Description |
| ---- | ------ | --------- | ------------------------ |
| path | string | Yes | Path of the target file. |
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise that returns no value.|
| Type | Description |
| ------------------- | ------------------------------ |
| Promise&lt;void&gt; | Promise that returns no value. |
**Example**
```js
let path = '/data/storage/el2/database'
let promisedelSt = data_storage.deleteStorage(path + '/mystore')
promisedelSt.then(() => {
console.info("Deleted successfully.")
}).catch((err) => {
console.info("Deleted failed with err: " + err)
})
```
```js
import featureAbility from '@ohos.ability.featureAbility';
var path;
var context = featureAbility.getContext();
context.getFilesDir().then((filePath) => {
path = filePath;
console.info("======================>getFilesDirPromsie====================>");
});
let promisedelSt = data_storage.deleteStorage(path + '/mystore');
promisedelSt.then(() => {
console.info("Succeeded in deleting the storage.");
}).catch((err) => {
console.info("Failed to delete the storage with err: " + err);
})
```
## data_storage.removeStorageFromCacheSync
......@@ -206,15 +259,25 @@ Removes the singleton **Storage** instance of a file from the cache. The removed
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| path | string | Yes| Path of the target file.|
| Name | Type | Mandatory | Description |
| ---- | ------ | --------- | ------------------------ |
| path | string | Yes | Path of the target file. |
**Example**
```js
let path = '/data/storage/el2/database'
data_storage.removeStorageFromCacheSync(path + '/mystore')
```
```js
import featureAbility from '@ohos.ability.featureAbility';
var path;
var context = featureAbility.getContext();
context.getFilesDir().then((filePath) => {
path = filePath;
console.info("======================>getFilesDirPromsie====================>");
});
data_storage.removeStorageFromCacheSync(path + '/mystore');
```
## data_storage.removeStorageFromCache
......@@ -226,22 +289,32 @@ Removes the singleton **Storage** instance of a file from the cache. The removed
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| path | string | Yes| Path of the target file.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback that returns no value.|
| Name | Type | Mandatory | Description |
| -------- | ------------------------- | --------- | ------------------------------- |
| path | string | Yes | Path of the target file. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback that returns no value. |
**Example**
```js
let path = '/data/storage/el2/database'
data_storage.removeStorageFromCache(path + '/mystore', function (err) {
```js
import featureAbility from '@ohos.ability.featureAbility';
var path;
var context = featureAbility.getContext();
context.getFilesDir().then((filePath) => {
path = filePath;
console.info("======================>getFilesDirPromsie====================>");
});
data_storage.removeStorageFromCache(path + '/mystore', function (err) {
if (err) {
console.info("Removed storage from cache failed with err: " + err)
return
console.info("Failed to remove storage from cache with err: " + err);
return;
}
console.info("Removed storage from cache successfully.")
})
```
console.info("Succeeded in removing storage from cache.");
})
```
## data_storage.removeStorageFromCache
......@@ -253,25 +326,36 @@ Removes the singleton **Storage** instance of a file from the cache. The removed
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| path | string | Yes| Path of the target file.|
| Name | Type | Mandatory | Description |
| ---- | ------ | --------- | ------------------------ |
| path | string | Yes | Path of the target file. |
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise that returns no value.|
| Type | Description |
| ------------------- | ------------------------------ |
| Promise&lt;void&gt; | Promise that returns no value. |
**Example**
```js
let path = '/data/storage/el2/database'
let promiserevSt = data_storage.removeStorageFromCache(path + '/mystore')
promiserevSt.then(() => {
console.info("Removed storage from cache successfully.")
}).catch((err) => {
console.info("Removed storage from cache failed with err: " + err)
})
```
```js
import featureAbility from '@ohos.ability.featureAbility';
var path;
var context = featureAbility.getContext();
context.getFilesDir().then((filePath) => {
path = filePath;
console.info("======================>getFilesDirPromsie====================>");
});
let promiserevSt = data_storage.removeStorageFromCache(path + '/mystore')
promiserevSt.then(() => {
console.info("Succeeded in removing storage from cache.");
}).catch((err) => {
console.info("Failed to remove storage from cache with err: " + err);
})
```
## Storage
......@@ -288,21 +372,24 @@ Obtains the value corresponding to a key. If the value is null or not in the def
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | string | Yes| Key of the data. It cannot be empty.|
| defValue | [ValueType](#valuetype) | Yes| Default value to be returned if the value of the specified key does not exist. It can be a number, string, or Boolean value.|
| Name | Type | Mandatory | Description |
| -------- | ----------------------- | --------- | ------------------------------------------------------------ |
| key | string | Yes | Key of the data. It cannot be empty. |
| defValue | [ValueType](#valuetype) | Yes | Default value to be returned if the value of the specified key does not exist. It can be a number, string, or Boolean value. |
**Return value**
| Type| Description|
| -------- | -------- |
| ValueType | Value corresponding to the specified key. If the value is null or not in the default value format, the default value is returned.|
| Type | Description |
| --------- | ------------------------------------------------------------ |
| ValueType | Value corresponding to the specified key. If the value is null or not in the default value format, the default value is returned. |
**Example**
```js
let value = storage.getSync('startup', 'default')
console.info("The value of startup is " + value)
```
```js
let value = storage.getSync('startup', 'default');
console.info("The value of startup is " + value);
```
### get
......@@ -314,22 +401,24 @@ Obtains the value corresponding to a key. If the value is null or not in the def
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | string | Yes| Key of the data. It cannot be empty.|
| defValue | [ValueType](#valuetype) | Yes| Default value to be returned. It can be a number, string, or Boolean value.|
| callback | AsyncCallback&lt;ValueType&gt; | Yes| Callback used to return the execution result.|
| Name | Type | Mandatory | Description |
| -------- | ------------------------------ | --------- | ------------------------------------------------------------ |
| key | string | Yes | Key of the data. It cannot be empty. |
| defValue | [ValueType](#valuetype) | Yes | Default value to be returned. It can be a number, string, or Boolean value. |
| callback | AsyncCallback&lt;ValueType&gt; | Yes | Callback used to return the execution result. |
**Example**
```js
storage.get('startup', 'default', function(err, value) {
```js
storage.get('startup', 'default', function(err, value) {
if (err) {
console.info("Get the value of startup failed with err: " + err)
return
console.info("Failed to get the value of startup with err: " + err);
return;
}
console.info("The value of startup is " + value)
})
```
console.info("The value of startup is " + value);
})
```
### get
......@@ -342,25 +431,26 @@ Obtains the value corresponding to a key. If the value is null or not in the def
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | string | Yes| Key of the data. It cannot be empty.|
| defValue | [ValueType](#valuetype) | Yes| Default value to be returned. It can be a number, string, or Boolean value.|
| Name | Type | Mandatory | Description |
| -------- | ----------------------- | --------- | ------------------------------------------------------------ |
| key | string | Yes | Key of the data. It cannot be empty. |
| defValue | [ValueType](#valuetype) | Yes | Default value to be returned. It can be a number, string, or Boolean value. |
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;ValueType&gt; | Promise used to return the result.|
| Type | Description |
| ------------------------ | ---------------------------------- |
| Promise&lt;ValueType&gt; | Promise used to return the result. |
**Example**
```js
let promiseget = storage.get('startup', 'default')
promiseget.then((value) => {
```js
let promiseget = storage.get('startup', 'default');
promiseget.then((value) => {
console.info("The value of startup is " + value)
}).catch((err) => {
console.info("Get the value of startup failed with err: " + err)
})
```
}).catch((err) => {
console.info("Failed to get the value of startup with err: " + err);
})
```
### putSync
......@@ -372,15 +462,17 @@ Obtains the **Storage** instance corresponding to the specified file, writes dat
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | string | Yes| Key of the data. It cannot be empty.|
| value | [ValueType](#valuetype) | Yes| New value to store. It can be a number, string, or Boolean value.|
| Name | Type | Mandatory | Description |
| ----- | ----------------------- | --------- | ------------------------------------------------------------ |
| key | string | Yes | Key of the data. It cannot be empty. |
| value | [ValueType](#valuetype) | Yes | New value to store. It can be a number, string, or Boolean value. |
**Example**
```js
storage.putSync('startup', 'auto')
```
```js
storage.putSync('startup', 'auto')
```
### put
......@@ -392,22 +484,24 @@ Obtains the **Storage** instance corresponding to the specified file, writes dat
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | string | Yes| Key of the data. It cannot be empty.|
| value | [ValueType](#valuetype) | Yes| New value to store. It can be a number, string, or Boolean value.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback that returns no value.|
| Name | Type | Mandatory | Description |
| -------- | ------------------------- | --------- | ------------------------------------------------------------ |
| key | string | Yes | Key of the data. It cannot be empty. |
| value | [ValueType](#valuetype) | Yes | New value to store. It can be a number, string, or Boolean value. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback that returns no value. |
**Example**
```js
storage.put('startup', 'auto', function (err) {
```js
storage.put('startup', 'auto', function (err) {
if (err) {
console.info("Put the value of startup failed with err: " + err)
return
console.info("Failed to put the value of startup with err: " + err);
return;
}
console.info("Put the value of startup successfully.")
})
```
console.info("Succeeded in putting the value of startup.");
})
```
### put
......@@ -419,25 +513,27 @@ Obtains the **Storage** instance corresponding to the specified file, writes dat
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | string | Yes| Key of the data. It cannot be empty.|
| value | [ValueType](#valuetype) | Yes| New value to store. It can be a number, string, or Boolean value.|
| Name | Type | Mandatory | Description |
| ----- | ----------------------- | --------- | ------------------------------------------------------------ |
| key | string | Yes | Key of the data. It cannot be empty. |
| value | [ValueType](#valuetype) | Yes | New value to store. It can be a number, string, or Boolean value. |
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise that returns no value.|
| Type | Description |
| ------------------- | ------------------------------ |
| Promise&lt;void&gt; | Promise that returns no value. |
**Example**
```js
let promiseput = storage.put('startup', 'auto')
promiseput.then(() => {
console.info("Put the value of startup successfully.")
}).catch((err) => {
console.info("Put the value of startup failed with err: " + err)
})
```
```js
let promiseput = storage.put('startup', 'auto');
promiseput.then(() => {
console.info("Succeeded in putting the value of startup.");
}).catch((err) => {
console.info("Failed to put the value of startup with err: " + err);
})
```
### hasSync
......@@ -449,22 +545,25 @@ Checks whether the storage object contains data with a given key.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | string | Yes| Key of the data. It cannot be empty.|
| Name | Type | Mandatory | Description |
| ---- | ------ | --------- | ------------------------------------ |
| key | string | Yes | Key of the data. It cannot be empty. |
**Return value**
| Type| Description|
| -------- | -------- |
| boolean | Returns **true** if the storage object contains data with the specified key; returns **false** otherwise.|
| Type | Description |
| ------- | ------------------------------------------------------------ |
| boolean | Returns **true** if the storage object contains data with the specified key; returns **false** otherwise. |
**Example**
```js
let isExist = storage.hasSync('startup')
if (isExist) {
console.info("The key of startup is contained.")
}
```
```js
let isExist = storage.hasSync('startup');
if (isExist) {
console.info("The key of startup is contained.");
}
```
### has
......@@ -476,28 +575,31 @@ Checks whether the storage object contains data with a given key. This API uses
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | string | Yes| Key of the data. It cannot be empty.|
| callback | AsyncCallback&lt;boolean&gt; | Yes| Callback used to return the execution result.|
| Name | Type | Mandatory | Description |
| -------- | ---------------------------- | --------- | --------------------------------------------- |
| key | string | Yes | Key of the data. It cannot be empty. |
| callback | AsyncCallback&lt;boolean&gt; | Yes | Callback used to return the execution result. |
**Return value**
| Type| Description|
| -------- | -------- |
| boolean | Returns **true** if the storage object contains data with the specified key; returns **false** otherwise.|
| Type | Description |
| ------- | ------------------------------------------------------------ |
| boolean | Returns **true** if the storage object contains data with the specified key; returns **false** otherwise. |
**Example**
```js
storage.has('startup', function (err, isExist) {
```js
storage.has('startup', function (err, isExist) {
if (err) {
console.info("Check the key of startup failed with err: " + err)
return
console.info("Failed to check the key of startup with err: " + err);
return;
}
if (isExist) {
console.info("The key of startup is contained.")
console.info("The key of startup is contained.");
}
})
```
})
```
### has
......@@ -509,26 +611,29 @@ Checks whether the storage object contains data with a given key. This API uses
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | string | Yes| Key of the data. It cannot be empty.|
| Name | Type | Mandatory | Description |
| ---- | ------ | --------- | ------------------------------------ |
| key | string | Yes | Key of the data. It cannot be empty. |
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return the result.|
| Type | Description |
| ---------------------- | ---------------------------------- |
| Promise&lt;boolean&gt; | Promise used to return the result. |
**Example**
```js
let promisehas = storage.has('startup')
promisehas.then((isExist) => {
```js
let promisehas = storage.has('startup')
promisehas.then((isExist) => {
if (isExist) {
console.info("The key of startup is contained.")
console.info("The key of startup is contained.");
}
}).catch((err) => {
console.info("Check the key of startup failed with err: " + err)
})
```
}).catch((err) => {
console.info("Failed to check the key of startup with err: " + err);
})
```
### deleteSync
......@@ -540,14 +645,16 @@ Deletes data with the specified key from this storage object.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | string | Yes| Key of the data. It cannot be empty.|
| Name | Type | Mandatory | Description |
| ---- | ------ | --------- | ------------------------------------ |
| key | string | Yes | Key of the data. It cannot be empty. |
**Example**
```js
storage.deleteSync('startup')
```
```js
storage.deleteSync('startup')
```
### delete
......@@ -559,21 +666,23 @@ Deletes data with the specified key from this storage object. This API uses an a
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | string | Yes| Key of the data. It cannot be empty.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback that returns no value.|
| Name | Type | Mandatory | Description |
| -------- | ------------------------- | --------- | ------------------------------------ |
| key | string | Yes | Key of the data. It cannot be empty. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback that returns no value. |
**Example**
```js
storage.delete('startup', function (err) {
```js
storage.delete('startup', function (err) {
if (err) {
console.info("Delete startup key failed with err: " + err)
return
console.info("Failed to delete startup key failed err: " + err);
return;
}
console.info("Deleted startup key successfully.")
})
```
console.info("Succeeded in deleting startup key.");
})
```
### delete
......@@ -585,24 +694,27 @@ Deletes data with the specified key from this storage object. This API uses a pr
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | string | Yes| Key of the data.|
| Name | Type | Mandatory | Description |
| ---- | ------ | --------- | ---------------- |
| key | string | Yes | Key of the data. |
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise that returns no value.|
| Type | Description |
| ------------------- | ------------------------------ |
| Promise&lt;void&gt; | Promise that returns no value. |
**Example**
```js
let promisedel = storage.delete('startup')
promisedel.then(() => {
console.info("Deleted startup key successfully.")
}).catch((err) => {
console.info("Delete startup key failed with err: " + err)
})
```
```js
let promisedel = storage.delete('startup')
promisedel.then(() => {
console.info("Succeeded in deleting startup key.");
}).catch((err) => {
console.info("Failed to delete startup key failed err: " + err);
})
```
### flushSync
......@@ -614,9 +726,10 @@ Saves the modification of this object to the **Storage** instance and synchroniz
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Example**
```js
storage.flushSync()
```
```js
storage.flushSync()
```
### flush
......@@ -628,20 +741,22 @@ Saves the modification of this object to the **Storage** instance and synchroniz
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;void&gt; | Yes| Callback that returns no value.|
| Name | Type | Mandatory | Description |
| -------- | ------------------------- | --------- | ------------------------------- |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback that returns no value. |
**Example**
```js
storage.flush(function (err) {
```js
storage.flush(function (err) {
if (err) {
console.info("Flush to file failed with err: " + err)
return
console.info("Failed to flush to file with err: " + err);
return;
}
console.info("Flushed to file successfully.")
})
```
console.info("Succeeded in flushing to file.");
})
```
### flush
......@@ -653,19 +768,21 @@ Saves the modification of this object to the **Storage** instance and synchroniz
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise that returns no value.|
| Type | Description |
| ------------------- | ------------------------------ |
| Promise&lt;void&gt; | Promise that returns no value. |
**Example**
```js
let promiseflush = storage.flush()
promiseflush.then(() => {
console.info("Flushed to file successfully.")
}).catch((err) => {
console.info("Flush to file failed with err: " + err)
})
```
```js
let promiseflush = storage.flush();
promiseflush.then(() => {
console.info("Succeeded in flushing to file.");
}).catch((err) => {
console.info("Failed to flush to file with err: " + err);
})
```
### clearSync
......@@ -677,9 +794,10 @@ Clears this **Storage** object.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Example**
```js
storage.clearSync()
```
```js
storage.clearSync()
```
### clear
......@@ -691,20 +809,22 @@ Clears this **Storage** object. This API uses an asynchronous callback to return
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;void&gt; | Yes| Callback that returns no value.|
| Name | Type | Mandatory | Description |
| -------- | ------------------------- | --------- | ------------------------------- |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback that returns no value. |
**Example**
```js
storage.clear(function (err) {
```js
storage.clear(function (err) {
if (err) {
console.info("Clear to file failed with err: " + err)
return
console.info("Failed to clear the storage with err: " + err);
return;
}
console.info("Cleared to file successfully.")
})
```
console.info("Succeeded in clearing the storage.");
})
```
### clear
......@@ -716,19 +836,21 @@ Clears this **Storage** object. This API uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise that returns no value.|
| Type | Description |
| ------------------- | ------------------------------ |
| Promise&lt;void&gt; | Promise that returns no value. |
**Example**
```js
let promiseclear = storage.clear()
promiseclear.then(() => {
console.info("Cleared to file successfully.")
}).catch((err) => {
console.info("Clear to file failed with err: " + err)
})
```
```js
let promiseclear = storage.clear();
promiseclear.then(() => {
console.info("Succeeded in clearing the storage.");
}).catch((err) => {
console.info("Failed to clear the storage with err: " + err);
})
```
### on('change')
......@@ -740,20 +862,22 @@ Subscribes to data changes. The **StorageObserver** needs to be implemented. Whe
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Description|
| -------- | -------- | -------- |
| type | string | Event type. The value **change** indicates data change events.|
| callback | Callback&lt;[StorageObserver](#storageobserver)&gt; | Callback used to return data changes.|
| Name | Type | Description |
| -------- | --------------------------------------------------- | ------------------------------------------------------------ |
| type | string | Event type. The value **change** indicates data change events. |
| callback | Callback&lt;[StorageObserver](#storageobserver)&gt; | Callback used to return data changes. |
**Example**
```js
var observer = function (key) {
console.info("The key of " + key + " changed.")
}
storage.on('change', observer)
storage.putSync('startup', 'auto')
storage.flushSync() // observer will be called.
```
```js
var observer = function (key) {
console.info("The key of " + key + " changed.");
}
storage.on('change', observer);
storage.putSync('startup', 'auto');
storage.flushSync(); // observer will be called.
```
### off('change')
......@@ -765,27 +889,29 @@ Unsubscribes from data changes.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Description|
| -------- | -------- | -------- |
| type | string | Event type. The value **change** indicates data change events.|
| callback | Callback&lt;[StorageObserver](#storageobserver)&gt; | Callback used to return data changes.|
| Name | Type | Description |
| -------- | --------------------------------------------------- | ------------------------------------------------------------ |
| type | string | Event type. The value **change** indicates data change events. |
| callback | Callback&lt;[StorageObserver](#storageobserver)&gt; | Callback used to return data changes. |
**Example**
```js
var observer = function (key) {
console.info("The key of " + key + " changed.")
}
storage.off('change', observer)
```
```js
var observer = function (key) {
console.info("The key of " + key + " changed.");
}
storage.off('change', observer);
```
## StorageObserver
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | string | No| Data changed.|
| Name | Type | Mandatory | Description |
| ---- | ------ | --------- | ------------- |
| key | string | No | Data changed. |
## ValueType
......@@ -794,7 +920,7 @@ Enumerates the value types.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
| Type | Description |
| ------- | -------------------- |
| ------- | ----------------------------- |
| number | The value is a number. |
| string | The value is a string. |
| boolean | The value is of Boolean type.|
| boolean | The value is of Boolean type. |
\ No newline at end of file
......@@ -2175,7 +2175,7 @@ Opens a file stream based on the file path. This API uses a promise to return th
| Type | Description |
| --------------------------------- | --------- |
| Promise&lt;[Stream](#stream7)&gt; | Promise used to return the result.|
| Promise&lt;[Stream](#stream)&gt; | Promise used to return the result.|
**Example**
......@@ -2202,7 +2202,7 @@ Opens a file stream based on the file path. This API uses an asynchronous callba
| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ |
| path | string | Yes | Application sandbox path of the file. |
| mode | string | Yes | -&nbsp;**r**: Open a file for reading. The file must exist.<br>-&nbsp;**r+**: Open a file for both reading and writing. The file must exist.<br>-&nbsp;**w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.<br>-&nbsp;**w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.<br>-&nbsp;**a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).<br>-&nbsp;**a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).|
| callback | AsyncCallback&lt;[Stream](#stream7)&gt; | Yes | Callback invoked when the stream is open asynchronously. |
| callback | AsyncCallback&lt;[Stream](#stream)&gt; | Yes | Callback invoked when the stream is open asynchronously. |
**Example**
......@@ -2232,7 +2232,7 @@ Synchronously opens a stream based on the file path.
| Type | Description |
| ------------------ | --------- |
| [Stream](#stream7) | Stream opened.|
| [Stream](#stream) | Stream opened.|
**Example**
......@@ -2260,7 +2260,7 @@ Opens a file stream based on the file descriptor. This API uses a promise to ret
| Type | Description |
| --------------------------------- | --------- |
| Promise&lt;[Stream](#stream7)&gt; | Promise used to return the result.|
| Promise&lt;[Stream](#stream)&gt; | Promise used to return the result.|
**Example**
......@@ -2288,7 +2288,7 @@ Opens a file stream based on the file descriptor. This API uses an asynchronous
| -------- | ---------------------------------------- | ---- | ---------------------------------------- |
| fd | number | Yes | File descriptor of the target file. |
| mode | string | Yes | -&nbsp;**r**: Open a file for reading. The file must exist.<br>-&nbsp;**r+**: Open a file for both reading and writing. The file must exist.<br>-&nbsp;**w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.<br>-&nbsp;**w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.<br>-&nbsp;**a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).<br>-&nbsp;**a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).|
| callback | AsyncCallback&nbsp;&lt;[Stream](#stream7)&gt; | Yes | Callback invoked when the stream is open asynchronously. |
| callback | AsyncCallback&nbsp;&lt;[Stream](#stream)&gt; | Yes | Callback invoked when the stream is open asynchronously. |
**Example**
......@@ -2319,7 +2319,7 @@ Synchronously opens a stream based on the file descriptor.
| Type | Description |
| ------------------ | --------- |
| [Stream](#stream7) | Stream opened.|
| [Stream](#stream) | Stream opened.|
**Example**
......
# User File Access and Management
The fileManager module provides APIs for accessing and managing user files. It interworks with the underlying file management services to implement media library and external card management, and provides capabilities for applications to query and create user files.
The **fileManager** module provides APIs for accessing and managing user files. It interworks with the underlying file management services to implement media library and external card management, and provides capabilities for applications to query and create user files.
>**NOTE**<br/>
>
......@@ -35,11 +35,9 @@ Obtains information about the root album or directory in asynchronous mode. This
**Example**
```js
filemanager.getRoot().then((fileInfo) => {
if(Array.isArray(fileInfo)) {
for (var i = 0; i < fileInfo.length; i++) {
console.log("file:"+JSON.stringify(fileInfo));
}
filemanager.getRoot().then((fileInfos) => {
for (var i = 0; i < fileInfos.length; i++) {
console.log("files:"+JSON.stringify(fileInfos));
}
}).catch((err) => {
console.log(err)
......@@ -69,14 +67,11 @@ Obtains information about the root album or directory in asynchronous mode. This
"name":"local"
}
};
filemanager.getRoot(options, (err, fileInfo)=>{
if(Array.isArray(fileInfo)) {
for (var i = 0; i < fileInfo.length; i++) {
console.log("file:"+JSON.stringify(fileInfo));
}
filemanager.getRoot(options, (err, fileInfos)=>{
for (var i = 0; i < fileInfos.length; i++) {
console.log("files:"+JSON.stringify(fileInfos));
}
});
```
## filemanager.listFile
......@@ -111,18 +106,17 @@ Obtains information about the second-level album or files in asynchronous mode.
**Example**
```js
// Obtain all files in the directory.
// Call listFile() and getRoot() to obtain the file URI.
let media_path = ""
filemanager.listFile(media_path, "file")
.then((fileInfo) => {
if(Array.isArray(fileInfo)) {
for (var i = 0; i < fileInfo.length; i++) {
console.log("file:"+JSON.stringify(fileInfo));
}
}
// Obtain all files in the directory. You can use getRoot to obtain the directory URI.
filemanager.getRoot().then((fileInfos) => {
let file = fileInfos.find(item => item.name == "file_folder");
let path = file.path;
filemanager.listFile(path, "file").then((files) => {
console.log("files:" + JSON.stringify(files));
}).catch((err) => {
console.log("Failed to get file"+err);
console.log("failed to get files" + err);
});
}).catch((err) => {
console.log("failed to get root" + err);
});
```
......@@ -153,33 +147,18 @@ Obtains information about the second-level album or files in asynchronous mode.
**Example**
```js
// Call listFile() and getRoot() to obtain the file path.
let fileInfos = filemanager.getRoot();
let media_path = "";
for (let i = 0; i < fileInfos.length; i++) {
if (fileInfos[i].name == "image_album") {
media_path = fileInfos[i].path;
} else if (fileInfos[i].name == "audio_album") {
media_path = fileInfos[i].path;
} else if (fileInfos[i].name == "video_album") {
media_path = fileInfos[i].path;
} else if (fileInfos[i].name == "file_folder") {
media_path = fileInfos[i].path;
}
}
filemanager.listFile(media_path, "file")
.then((fileInfo) => {
if(Array.isArray(fileInfo)) {
for (var i = 0; i < fileInfo.length; i++) {
console.log("file:"+JSON.stringify(fileInfo));
}
}
}).catch((err) => {
console.log("Failed to get file"+err);
});
```
```js
// Obtain all files in the directory. You can use getRoot to obtain the directory URI.
filemanager.getRoot().then((fileInfos) => {
let file = fileInfos.find(item => item.name == "image_album");
let path = file.path;
filemanager.listFile(path, "image",function(err, files){
console.log("files:" + JSON.stringify(files));
})
}).catch((err) => {
console.log("failed to get root" + err);
});
```
## filemanager.createFile
......
# OS Account Management
The osAccount module provides basic capabilities for managing operating system (OS) accounts, including adding, deleting, querying, setting, subscribing to, and enabling an OS account, and storing OS account data to disks.
The **osAccount** module provides basic capabilities for managing operating system (OS) accounts, including adding, deleting, querying, setting, subscribing to, and enabling an OS account, and storing OS account data to disks.
> **NOTE**<br>
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
......@@ -801,7 +801,7 @@ Obtains the OS account ID based on domain account information. This API uses an
| Name | Type | Mandatory| Description |
| ---------- | --------------------------------------- | ---- | -------------------------------------------- |
| domainInfo | [DomainAccountInfo](#domainaccountinfo) | Yes | Domain account information. |
| domainInfo | [DomainAccountInfo](#domainaccountinfo8) | Yes | Domain account information. |
| callback | AsyncCallback&lt;number&gt; | Yes | Callback used to return the ID of the OS account associated with the domain account.|
**Example**
......@@ -829,7 +829,7 @@ Obtains the OS account ID based on domain account information. This API uses a p
| Name | Type | Mandatory| Description |
| ---------- | --------------------------------------- | ---- | ------------ |
| domainInfo | [DomainAccountInfo](#domainaccountinfo) | Yes | Domain account information.|
| domainInfo | [DomainAccountInfo](#domainaccountinfo8) | Yes | Domain account information.|
**Return value**
......@@ -1156,7 +1156,7 @@ This is a system API and cannot be called by third-party applications.
| Name | Type | Mandatory| Description |
| :--------- | ---------------------------------------------------- | ---- | ------------------------------------------ |
| type | [OsAccountType](#osaccounttype) | Yes | Type of the OS account to create. |
| domainInfo | [DomainAccountInfo](#domainaccountinfo) | Yes | Domain account information. |
| domainInfo | [DomainAccountInfo](#domainaccountinfo8) | Yes | Domain account information. |
| callback | AsyncCallback&lt;[OsAccountInfo](#osaccountinfo)&gt; | Yes | Callback used to return the OS account created.|
**Example**
......@@ -1187,7 +1187,7 @@ This is a system API and cannot be called by third-party applications.
| Name | Type | Mandatory| Description |
| ---------- | --------------------------------------- | ---- | ---------------------- |
| type | [OsAccountType](#osaccounttype) | Yes | Type of the OS account to create.|
| domainInfo | [DomainAccountInfo](#domainaccountinfo) | Yes | Domain account information. |
| domainInfo | [DomainAccountInfo](#domainaccountinfo8) | Yes | Domain account information. |
**Return value**
......@@ -1765,7 +1765,7 @@ Defines information about an OS account.
| isActived<sup>8+</sup> | boolean | Yes | Whether the OS account is activated. |
| isCreateCompleted<sup>8+</sup> | boolean | Yes | Whether the OS account information is complete. |
| distributedInfo | [distributedAccount.DistributedInfo](js-apis-distributed-account.md) | No | Distributed account information. |
| domainInfo<sup>8+</sup> | [DomainAccountInfo](#domainaccountinfo) | No | Domain account information. |
| domainInfo<sup>8+</sup> | [DomainAccountInfo](#domainaccountinfo8) | No | Domain account information. |
## DomainAccountInfo<sup>8+</sup>
......
......@@ -263,12 +263,6 @@ Enables the display of a confirm dialog box before returning to the previous pag
enableAlertBeforeBackPage() {
router.enableAlertBeforeBackPage({
message: 'Message Info',
success: function() {
console.log('success');
},
fail: function() {
console.log('fail');
},
});
}
}
......@@ -434,4 +428,5 @@ Describes the page routing options.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
>
> The page routing stack supports a maximum of 32 pages.
......@@ -66,6 +66,7 @@ export default {
```
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
>
> The page routing stack supports a maximum of 32 pages.
......@@ -182,6 +183,7 @@ export default {
```
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
>
> In the example, the **uri** field indicates the page route, which is specified by the **pages** list in the **config.json** file.
## router.getParams
......@@ -375,8 +377,8 @@ Defines the **EnableAlertBeforeBackPage** parameters.
| Name | Type | Mandatory | Description |
| -------- | ------------------------ | ---- | ------------------------- |
| message | string | Yes | Content displayed in the confirm dialog box. |
| success | (errMsg: string) => void | No | Called when a dialog box is displayed. **errMsg** indicates the returned information. |
| fail | (errMsg: string) => void | No | Called when the API fails to be called. **errMsg** indicates the returned information.|
| success | (errMsg: string) => void | No | Called when the **OK** button in the confirm dialog box is clicked. **errMsg** indicates the returned information. |
| cancel | (errMsg: string) => void | No | Called when the **Cancel** button in the confirm dialog box is clicked. **errMsg** indicates the returned information. |
| complete | () => void | No | Called when the API call is complete. |
## DisableAlertBeforeBackPageOptions<sup>6+</sup>
......@@ -387,8 +389,8 @@ Define the **DisableAlertBeforeBackPage** parameters.
| Name | Type | Mandatory | Description |
| -------- | ------------------------ | ---- | ------------------------- |
| success | (errMsg: string) => void | No | Called when a dialog box is displayed. **errMsg** indicates the returned information. |
| fail | (errMsg: string) => void | No | Called when the API fails to be called. **errMsg** indicates the returned information.|
| success | (errMsg: string) => void | No | Called when the dialog box is closed. **errMsg** indicates the returned information. |
| cancel | (errMsg: string) => void | No | Called when the dialog box fails to be closed. **errMsg** indicates the returned information. |
| complete | () => void | No | Called when the API call is complete. |
## ParamsInterface
......
......@@ -12,9 +12,9 @@ App permissions are used to protect the following objects:
Without the required permissions, an app cannot access or perform operations on the target object. Permissions must be clearly defined for apps. With well-defined app permissions, the system can standardize the behavior of apps and protect user privacy. Before an app accesses the target object, the target object verifies the app's permissions and denies the access if the app does not have required permissions.
Currently, ATM performs app permission verification based on the token identity (Token ID). A token ID identifies an app. The ATM manages app permissions based on the app's token ID.
Currently, ATM verifies app permissions based on the token identity (Token ID). A token ID identifies an app. The ATM manages app permissions based on the app's token ID.
## How to Develop
## Permission Workflow
Determine the permissions required for an app to access data or perform an operation. Declare the required permissions in the app installation package.
......@@ -22,13 +22,13 @@ Determine whether the required permissions need to be authorized by users. If ye
After the user grants permissions to the app, the app can access the data or perform the operation.
The figure below shows the process.
The figure below shows the permission workflow.
![](figures/figure1.png)
## When to Use
### Scenarios
### Example Scenarios
The following describes two common scenarios.
......@@ -62,7 +62,7 @@ Observe the following principles for permission management:
To protect user privacy, ATM defines different permission levels based on the sensitivity of the data involved or the security threat of the ability.
### App APL
### App APLs
The ability privilege level (APL) defines the priority of the app permission requested. Apps of different APLs can apply for permissions of different levels.
......@@ -76,9 +76,9 @@ The table below describes the APLs.
By default, apps are of the normal APL.
For the app of the system_basic or system_core APL, declare the app APL level in the **apl** field in the app's profile, and use the profile signing tool to generate a certificate when developing the app installation package. For details about the signing process, see [Hapsigner Guide](hapsigntool-guidelines.md).
For the app of the system_basic or system_core APL, declare the app APL in the **apl** field in the app's profile, and use the profile signing tool to generate a certificate when developing the app installation package. For details about the signing process, see [Hapsigner Guide](hapsigntool-guidelines.md).
### Permission Levels
### Levels of Permissions
The permissions open to apps vary with the permission level. The permission levels include the following in ascending order of seniority.
......@@ -121,11 +121,11 @@ If the permission required by an app has higher level than the app's APL, you ca
In addition to the preceding [authorization processes](#authorization-processes), you must declare the ACL.
In other words, in addition to declaring the required permissions in the **config.json** file, you must declare the high-level permissions in the app's [profile](accesstoken-guidelines.md#declaring-the-acl). The subsequent steps of authorization are the same.
In other words, in addition to declaring the required permissions in the **config.json** file, you must [declare the ACL](accesstoken-guidelines.md#declaring-the-acl) in the app's profile. The subsequent steps of authorization are the same.
**NOTE**
**NOTICE**
Declare the target ACL in the **acl** field of the app's profile in the app installation package, and generate a certificate using the profile signing tool. For details about the signing process, see [Hapsigner Guide](hapsigntool-guidelines.md).
Declare the target ACL in the **acls** field of the app's profile in the app installation package, and generate a certificate using the profile signing tool. For details about the signing process, see [Hapsigner Guide](hapsigntool-guidelines.md).
## Permission Authorization Modes
......@@ -149,9 +149,7 @@ Permissions can be classified into the following types based on the authorizatio
### Authorization Processes
The process for an app obtaining the required permissions varies
depending on the permission authorization mode.
The process for an app obtaining the required permissions varies depending on the permission authorization mode.
- For a system_grant permission, you need to [declare the permission](accesstoken-guidelines.md) in the **config.json** file. The permission will be pre-granted when the app is installed.
......@@ -165,7 +163,7 @@ The procedure is as follows:
2. Associate the object that requires the permissions in the app with the target permissions. In this way, the user knows the operations to be granted with the specified permissions.
3. Check whether the user has granted the required permissions to the app when the app is running. If yes, the app can access the data or perform the operation. If the user has not granted the permissions to the app, display a dialog box requesting the user authorization when the app attempts to access the data or perform the operation.
3. Check whether the user has granted the required permissions to the app when the app is running. If yes, the app can access the data or perform the operation. If the user has not granted the permissions to the app, display a dialog box requesting the user authorization when the app attempts to access the data.
4. Check the user authorization result. Allow the next step only after the user has granted the permissions to the app.
......
......@@ -52,7 +52,7 @@ The camera module encapsulates camera operations in camera preview, photographin
| API | Description |
| ------------------------------------------------------------ | ---------------------------- |
| CamRetCode GetStreamOperator(<br> const OHOS::sptr<IStreamOperatorCallback> &callback,<br> OHOS::sptr<IStreamOperator> &streamOperator) | Obtains the stream controller. |
| CamRetCode UpdateSettings(const std::shared_ptr<CameraSetting> &settingss) | Updates device control parameters. |
| CamRetCode UpdateSettings(const std::shared_ptr<CameraSetting> &settings) | Updates device control parameters. |
| CamRetCode SetResultMode(const ResultCallbackMode &mode) | Sets the result callback mode and function.|
| CamRetCode GetEnabledResults(std::vector<MetaType> &results) | Obtains the enabled ResultMeta. |
| CamRetCode EnableResult(const std::vector<MetaType> &results) | Enables specific ResultMeta. |
......@@ -730,7 +730,7 @@ There is a camera demo in the **/drivers/peripheral/camera/hal/init** directory.
"-o | --offline stream offline test\n"
"-c | --capture capture one picture\n"
"-w | --set WB Set white balance Cloudy\n"
"-v | --video capture Viedeo of 10s\n"
"-v | --video capture Video of 10s\n"
"-a | --Set AE Set Auto exposure\n"
"-f | --Set Flashlight Set flashlight ON 5s OFF\n"
"-q | --quit stop preview and quit this app\n");
......
# I3C<a name="1"></a>
# I3C
## Introduction
## Overview<a name="section1"></a>
### Function
The Improved Inter-Integrated Circuit (I3C) is a simple and cost-efficient bidirectional 2-wire synchronous serial bus protocol developed by the Mobile Industry Processor Interface (MIPI) Alliance.
Improved Inter-Integrated Circuit (I3C) is a simple and cost-efficient two-wire bidirectional synchronous serial bus protocol developed by the Mobile Industry Processor Interface (MIPI) Alliance.
I3C is backward compatible with legacy Inter-Integrated Circuit (I2C). Moreover, it provides the in-band interrupt (IBI) function and supports hot-join of I3C devices. This eliminates the need for adding an extra interrupt line to implement interrupts in I2C.
The I2C device, I3C slave device, and I3C secondary master device can coexist on the I3C bus.
The I3C APIs provide a set of common functions for I3C transfer, including:
I3C is a two-wire bidirectional serial bus, optimized for multiple sensor target devices and controlled by only one I3C controller at a time. It is backward compatible with Inter-Integrated circuit (I2C) target devices, but features higher speed and lower power consumption. Moreover, I3C supports in-band interrupts (IBIs), hot-joins of target devices, and controller switchover. The IBIs over the serial bus eliminates the need for an extra interrupt line to complete interrupts in I2C. I2C devices, I3C target devices, and the I3C secondary controller can co-exist on the same I3C bus.
The I3C driver APIs provide a set of common functions for I3C transfer, including:
- Opening and closing an I3C controller
- Obtaining and setting I3C controller parameters
- Performing custom I3C message transfer by using a message array
- Requesting and releasing an IBI
[Figure 1](#fig1) shows the I3C physical connection.
**Figure 1** I3C physical connection<a name="fig1"></a>
### Basic Concepts
- IBI
When there is no start signal on the serial clock (SCL) line, the I3C target device can pull down the serial data (SDA) line to make the controller send an SCL start signal, which initiates an IBI request. If multiple target devices send interrupt requests at the same time, the I3C controller arbitrates the requests based on the target device addresses. The request with a lower address is responded first.
- Dynamic Address Assignment (DAA)
The I3C controller can dynamically allocate addresses to target devices to avoid address conflicts. Before addresses are allocated, each I3C device connected to a I3C bus must be uniquely identified in either of the following ways:
- The device has an I2C compliant static address that can be used by the host.
- The device has a 48-bit temporary ID.
The host must use a 48-bit temporary ID unless the device has a static IP address.
- Common Command Code (CCC)
All I3C devices support CCC. The CCC can be sent to a specific I3C target device or all I3C target devices.
- Bus Characteristic Register (BCR)
Each I3C device connected to an I3C bus has a read-only BCR, which describes the I3C compliant device's role and capabilities for use in DAA and CCC.
- Device Characteristic Register (DCR)
Each I3C device connected to an I3C bus has a read-only DCR, which describes the I3C compliant device type (such as accelerometers, gyroscope, and others) for use in DAA and DCC.
### Working Principles
In the Hardware Driver Foundation (HDF), the I3C module uses the unified service mode for API adaptation. In this mode, a service is used as the I3C manager to handle external access requests in a unified manner. The unified service mode applies when the system has multiple device objects of the same type, for example, when there are more than 10 I3C controllers. If the independent service mode is used in this case, more device nodes need to be configured and more memory resources will be consumed.
Multiple devices, such as I2C target device, I3C target device, and I3C secondary controller, can be connected to an I3C bus. However, the I3C bus must have only one controller.
**Figure 1** I3C physical connection
![](figures/I3C_physical_connection.png "I3C_physical_connection")
## Available APIs<a name="section2"></a>
### Constraints
Currently, the I3C module supports only the kernels (LiteOS) of mini and small systems.
## Usage Guidelines
### When to Use
I3C can connect to one or more I3C or I2C target devices. It is used to:
- Communicate with sensors, such as gyroscopes, barometers, and image sensors that support the I3C protocol.
- Communicate with devices with other ports (such as UART serial ports) through software or hardware protocols.
### Available APIs
**Table 1** I3C driver APIs
<a name="table1"></a>
<table><thead align="left"><tr><th class="cellrowborder" valign="top" width="18.63%"><p>Category</p>
</th>
<th class="cellrowborder" valign="top" width="28.03%"><p>API</p>
</th>
<th class="cellrowborder" valign="top" width="53.339999999999996%"><p>Description</p>
</th>
</tr>
</thead>
<tbody><tr><td class="cellrowborder" bgcolor="#ffffff" rowspan="2" valign="top" width="18.63%"><p>I3C controller management</p>
</td>
<td class="cellrowborder" valign="top" width="28.03%"><p>I3cOpen</p>
</td>
<td class="cellrowborder" valign="top" width="53.339999999999996%">Opens an I3C controller.</p>
</td>
</tr>
<tr><td class="cellrowborder" valign="top"><p>I3cClose</p>
</td>
<td class="cellrowborder" valign="top"><p>Closes an I3C controller.</p>
</td>
</tr>
<tr><td class="cellrowborder" bgcolor="#ffffff" valign="top" width="18.63%"><p>I3C transfer</p>
</td>
<td class="cellrowborder" valign="top" width="28.03%"><p>I3cTransfer</p>
</td>
<td class="cellrowborder" valign="top" width="53.339999999999996%"><p>Customizes an I3C transfer.</p>
</td>
</tr>
<tr><td class="cellrowborder" bgcolor=ffffff rowspan="2" valign="top" width="18.63%"><p>I3C controller configuration</p>
</td>
<td class="cellrowborder" valign="top" width="28.03%"><p>I3cSetConfig</p>
</td>
<td class="cellrowborder"valign="top" width="53.339999999999996%">Sets an I3C controller.</p>
</td>
</tr>
<tr><td class="cellrowborder" valign="top"><p>I3cGetConfig</p>
</td>
<td class="cellrowborder" valign="top"><p>Obtains the I3C controller configuration.</p>
</td>
</tr>
<tr><td class="cellrowborder" bgcolor=ffffff rowspan="2" valign="top" width="18.63%"><p>I3C IBI</p>
</td>
<td class="cellrowborder" valign="top" width="28.03%"><p>I3cRequestIbi</p>
</td>
<td class="cellrowborder" valign="top" width="53.339999999999996%">Requests an IBI.</p>
</td>
</tr>
<tr><td class="cellrowborder" valign="top"><p>I3cFreeIbi</p>
</td>
<td class="cellrowborder" valign="top"><p>Releases an IBI.</p>
</td>
</tr>
</table>
>![](../public_sys-resources/icon-note.gif) **NOTE**
>
>All functions described in this document can be called only in the kernel space.
## Usage Guidelines<a name="section3"></a>
### How to Use<a name="section4"></a>
[Figure 2](#fig2) shows how I3C works.
**Figure 2** How I3C works<a name="fig2"></a>
| API | Description |
| ------------- | ----------------- |
| I3cOpen | Opens an I3C controller. |
| I3cClose | Closes an I3C controller. |
| I3cTransfer | Performs custom transfer. |
| I3cSetConfig | Sets the I3C controller. |
| I3cGetConfig | Obtains the I3C controller configuration. |
| I3cRequestIbi | Requests an IBI. |
| I3cFreeIbi | Releases an IBI. |
>![](../public_sys-resources/icon-note.gif) **NOTE**<br>
>All APIs described in this document can be called only in kernel mode.
### How to Develop
The figure below illustrates the use of I3C driver APIs.
**Figure 2** Process of using I3C driver APIs
![](figures/I3C_usage_flowchart.png "I3C_usage_flowchart")
### Opening an I3C Controller<a name="section5"></a>
#### Opening an I3C Controller
Before I3C communication, call **I3cOpen** to open an I3C controller.
Before I3C communication, call **I3cOpen()** to open an I3C controller.
```c
DevHandle I3cOpen(int16_t number);
```
**Table 2** Description of I3cOpen
<a name="table2"></a>
<table><thead align="left"><tr><th class="cellrowborder" valign="top" width="20.66%"><p>Parameter</strong></p>
</th>
<th class="cellrowborder" valign="top" width="79.34%"><p><strong>Description</strong></p>
</th>
</tr>
</thead>
<tbody><tr><td class="cellrowborder" valign="top" width="20.66%"><p>number</p>
</td>
<td class="cellrowborder" valign="top" width="79.34%"><p>I3C controller ID.</p>
</td>
</tr>
<tr><td class="cellrowborder" valign="top" width="20.66%"><p><strong>Return Value</strong></p>
</td>
<td class="cellrowborder" valign="top" width="79.34%"><p><strong>Description</strong></p>
</td>
</tr>
<tr><td class="cellrowborder" valign="top" width="20.66%"><p>NULL</p>
</td>
<td class="cellrowborder" valign="top" width="79.34%"><p>Failed to open the I3C controller.</p>
</td>
</tr>
<tr><td class="cellrowborder" valign="top" width="20.66%"><p>Controller handle</p>
</td>
<td class="cellrowborder" valign="top" width="79.34%"><p>Handle of the I3C controller opened.</p>
</td>
</tr>
</tbody>
</table>
The following example opens I3C controller 1 of the eight I3C controllers (numbered from 0 to 7) in the system.
| Name | Description |
| ---------- | ------------------- |
| number | I3C controller number. |
| **Return Value**| **Description** |
| NULL | The operation failed. |
| Controller handle| The operation is successful. The handle of the I3C controller opened is returned. |
Example: Open I3C controller 1 of the eight I3C controllers numbered from 0 to 7 in the system.
```c
DevHandle i3cHandle = NULL; /* I3C controller handle. /
......@@ -147,7 +116,7 @@ if (i3cHandle == NULL) {
}
```
### Performing I3C Communication<a name="section6"></a>
#### Performing I3C Communication
Call **I3cTransfer()** to transfer messages.
```c
......@@ -156,53 +125,18 @@ int32_t I3cTransfer(DevHandle handle, struct I3cMsg *msgs, int16_t count, enum T
**Table 3** Description of I3cTransfer
<a name="table3"></a>
<table><thead align="left"><tr><th class="cellrowborder" valign="top" width="50%"><p><strong> Parameter</strong></p>
</th>
<th class="cellrowborder" valign="top" width="50%"><p><strong>Description</strong></p>
</th>
</tr>
</thead>
<tbody><tr><td class="cellrowborder" valign="top" width="50%"><p>handle</p>
</td>
<td class="cellrowborder" valign="top" width="50%"><p>I3C controller handle.</p>
</td>
</tr>
<tr><td class="cellrowborder" valign="top" width="50%"><p>msgs</p>
</td>
<td class="cellrowborder" valign="top" width="50%"><p>Pointer to the message structure array of the data to be transmitted.</p>
</td>
</tr>
<tr><td class="cellrowborder" valign="top" width="50%"><p>count</p>
</td>
<td class="cellrowborder" valign="top" width="50%"><p>Length of the message array.</p>
</td>
</tr>
<tr><td class="cellrowborder" valign="top" width="50%"><p>mode</p>
</td>
<td class="cellrowborder" valign="top" width="50%"><p>Transmission mode, where the value <b>0</b> indicates the I2C mode, <b>1</b> indicates the I3C mode, and <b>2</b> indicates transmission of the Common Command Code (CCC).
</td>
</tr>
<tr><td class="cellrowborder" valign="top" width="50%"><p><strong>Return Value</strong></p>
</td>
<td class="cellrowborder" valign="top" width="50%"><p><strong>Description</strong></p>
</td>
</tr>
<tr><td class="cellrowborder" valign="top" width="50%"><p>Positive integer</p>
</td>
<td class="cellrowborder" valign="top" width="50%"><p>Number of message structures successfully transferred.</p>
</td>
</tr>
<tr><td class="cellrowborder" valign="top" width="50%"><p>Negative number</p>
</td>
<td class="cellrowborder" valign="top" width="50%"><p>The operation failed.</p>
</td>
</tr>
</tbody>
</table>
The I3C messages are of the I3cMsg type. Each message structure indicates a read or write operation. A message array is used to perform multiple read or write operations.
| Name | Description |
| ---------- | -------------------------------------------- |
| handle | I3C controller handle. |
| msgs | Pointer to the message array of the data to transfer. |
| count | Length of the message array. |
| mode | Transmission mode. The value **0** indicates I2C mode, **1** indicates I3C mode, and **2** indicates CCC transmission. |
| **Return Value**| **Description** |
| Positive integer | The operation is successful. The number of message structures that are successfully transmitted is returned. |
| Negative value | The operation failed. |
The I3C messages are of the I3cMsg type. Each message structure indicates a read or write operation. A message array can be used to perform multiple read or write operations.
```c
int32_t ret;
......@@ -225,13 +159,14 @@ if (ret != 2) {
}
```
>![](../public_sys-resources/icon-caution.gif) **Caution**
>
>![](./public_sys-resources/icon-caution.gif) **Caution**<br>
>- The device address in the **I3cMsg** structure does not contain the read/write flag bit. The read/write information is passed by the read/write control bit in the member variable **flags**.
>- The **I3cTransfer()** function does not limit the number of message structures or the length of data in each message structure. The I3C controller determines these two limits.
>- Using **I3cTransfer()** may cause the system to sleep. Do not call it in the interrupt context.
### Obtaining the I3C Controller Configuration<a name="section7"></a>
#### Obtaining the I3C Controller Configuration
Call **I3cGetConfig()** to obtain the configuration of an I3C controller.
```c
int32_t I3cGetConfig(DevHandle handle, struct I3cConfig *config);
......@@ -239,43 +174,30 @@ int32_t I3cGetConfig(DevHandle handle, struct I3cConfig *config);
**Table 4** Description of I3cGetConfig
<a name="table4"></a>
<table><thead align="left"><tr><th class="cellrowborder" valign="top" width="50%"><p><strong>Parameter</strong></p>
</th>
<th class="cellrowborder" valign="top" width="50%"><p><strong>Description</strong></p>
</th>
</tr>
</thead>
<tbody><tr><td class="cellrowborder" valign="top" width="50%"><p>handle</p>
</td>
<td class="cellrowborder" valign="top" width="50%"><p>I3C controller handle.</p>
</td>
</tr>
<tr><td class="cellrowborder" valign="top" width="50%"><p>config</p>
</td>
<td class="cellrowborder" valign="top" width="50%"><p>Pointer to the I3C controller configuration.</p>
</td>
</tr>
<tr><td class="cellrowborder" valign="top" width="50%"><p><strong>Return Value</strong></p>
</td>
<td class="cellrowborder" valign="top" width="50%"><p><strong>Description</strong></p>
</td>
</tr>
<tr><td class="cellrowborder" valign="top" width="50%"><p>0</p>
</td>
<td class="cellrowborder" valign="top" width="50%"><p>The operation is successful.</p>
</td>
</tr>
<tr><td class="cellrowborder" valign="top" width="50%"><p>Negative number</p>
</td>
<td class="cellrowborder" valign="top" width="50%"><p>Failed to obtain the I3C controller configuration.</p>
</td>
</tr>
</tbody>
</table>
### Configuring an I3C Controller<a name="section8"></a>
| Name | Description |
| ---------- | -------------- |
| handle | I3C controller handle. |
| config | Pointer to the I3C controller configuration. |
| **Return Value**| **Description**|
| 0 | The operation is successful. |
| Negative value | The operation failed. |
The following is an example of obtaining the I3C controller configuration:
```c
struct I3cConfig config;
ret = I3cGetConfig(i3cHandle, &config);
if (ret != HDF_SUCCESS) {
HDF_LOGE("%s: Get config fail!", __func__);
return HDF_FAILURE;
}
```
#### Setting an I3C Controller
Call **I3cSetConfig()** to set an I3C controller.
```c
int32_t I3cSetConfig(DevHandle handle, struct I3cConfig *config);
......@@ -283,43 +205,32 @@ int32_t I3cSetConfig(DevHandle handle, struct I3cConfig *config);
**Table 5** Description of I3cSetConfig
<a name="table5"></a>
<table><thead align="left"><tr><th class="cellrowborder" valign="top" width="50%"><p><strong>Parameter</strong></p>
</th>
<th class="cellrowborder" valign="top" width="50%"><p><strong>Description</strong></p>
</th>
</tr>
</thead>
<tbody><tr><td class="cellrowborder" valign="top" width="50%"><p>handle</p>
</td>
<td class="cellrowborder" valign="top" width="50%"><p>I3C controller handle.</p>
</td>
</tr>
<tr><td class="cellrowborder" valign="top" width="50%"><p>config</p>
</td>
<td class="cellrowborder" valign="top" width="50%"><p>Pointer to the I3C controller configuration.</p>
</td>
</tr>
<tr><td class="cellrowborder" valign="top" width="50%"><p><strong>Return Value</strong></p>
</td>
<td class="cellrowborder" valign="top" width="50%"><p><strong>Description</strong></p>
</td>
</tr>
<tr><td class="cellrowborder" valign="top" width="50%"><p>0</p>
</td>
<td class="cellrowborder" valign="top" width="50%"><p>The operation is successful.</p>
</td>
</tr>
<tr><td class="cellrowborder" valign="top" width="50%"><p>Negative number</p>
</td>
<td class="cellrowborder" valign="top" width="50%"><p>Failed to configure the I3C controller.</p>
</td>
</tr>
</tbody>
</table>
### Requesting an IBI<a name="section9"></a>
| Name | Description |
| ---------- | -------------- |
| handle | I3C controller handle. |
| config | Pointer to the I3C controller configuration. |
| **Return Value**| **Description**|
| 0 | The operation is successful. |
| Negative value | The operation failed. |
The following is an example of setting an I3C controller:
```c
struct I3cConfig config;
config->busMode = I3C_BUS_HDR_MODE;
config->curMaster = NULL;
ret = I3cSetConfig(i3cHandle, &config);
if (ret != HDF_SUCCESS) {
HDF_LOGE("%s: Set config fail!", __func__);
return HDF_FAILURE;
}
```
#### Requesting an IBI
Call **I3cRequestIbi()** to request an IBI.
```c
int32_t I3cRequestIbi(DevHandle handle, uint16_t addr, I3cIbiFunc func, uint32_t payload);
......@@ -327,51 +238,18 @@ int32_t I3cRequestIbi(DevHandle handle, uint16_t addr, I3cIbiFunc func, uint32_t
**Table 6** Description of I3cRequestIbi
<a name="table6"></a>
<table><thead align="left"><tr><th class="cellrowborder" valign="top" width="50%"><p><strong>Parameter</strong></p>
</th>
<th class="cellrowborder" valign="top" width="50%"><p><strong>Description</strong></p>
</th>
</tr>
</thead>
<tbody><tr><td class="cellrowborder" valign="top" width="50%"><p>handle</p>
</td>
<td class="cellrowborder" valign="top" width="50%"><p>I3C controller handle.</p>
</td>
</tr>
<tr><td class="cellrowborder" valign="top" width="50%"><p>addr</p>
</td>
<td class="cellrowborder" valign="top" width="50%"><p>I3C device address.</p>
</td>
</tr>
<tr><td class="cellrowborder" valign="top" width="50%"><p>func</p>
</td>
<td class="cellrowborder" valign="top" width="50%"><p>Callback used to return the IBI.</p>
</td>
</tr>
<tr><td class="cellrowborder" valign="top" width="50%"><p>payload</p>
</td>
<td class="cellrowborder" valign="top" width="50%"><p>IBI payload.</p>
</td>
</tr>
<tr><td class="cellrowborder" valign="top" width="50%"><p><strong>Return Value</strong></p>
</td>
<td class="cellrowborder" valign="top" width="50%"><p><strong>Description</strong></p>
</td>
</tr>
<tr><td class="cellrowborder"valign="top" width="50%"><p>0</p>
</td>
<td class="cellrowborder" valign="top" width="50%"><p>The operation is successful.</p>
</td>
</tr>
<tr><td class="cellrowborder" valign="top" width="50%"><p>Negative number</p>
</td>
<td class="cellrowborder" valign="top" width="50%"><p> Failed to request the IBI.</p>
</td>
</tr>
</tbody>
</table>
| Name | Description |
| ---------- | -------------- |
| handle | I3C controller handle. |
| addr | I3C device address. |
| func | Callback used to return the IBI. |
| payload | IBI payload. |
| **Return Value**| **Description**|
| 0 | The operation is successful. |
| Negative value | The operation failed. |
The following is an example:
```c
static int32_t TestI3cIbiFunc(DevHandle handle, uint16_t addr, struct I3cIbiData data)
......@@ -388,7 +266,7 @@ int32_t I3cTestRequestIbi(void)
DevHandle i3cHandle = NULL;
int32_t ret;
/* Open an I3C controller. */
/* Open the I3C controller. */
i3cHandle = I3cOpen(1);
if (i3cHandle == NULL) {
HDF_LOGE("I3cOpen: failed\n");
......@@ -396,7 +274,7 @@ int32_t I3cTestRequestIbi(void)
}
ret = I3cRequestIbi(i3cHandle, 0x3F, TestI3cIbiFunc, 16);
if (ret != 0) {
HDF_LOGE("%s: Requset IBI failed!", __func__);
HDF_LOGE("%s: Request IBI failed!", __func__);
return -1;
}
......@@ -407,7 +285,9 @@ int32_t I3cTestRequestIbi(void)
}
```
### Releasing an IBI<a name="section10"></a>
#### Releasing an IBI
Call **I3cFreeIbi()** to release an IBI.
```c
int32_t I3cFreeIbi(DevHandle handle, uint16_t addr);
......@@ -415,47 +295,22 @@ int32_t I3cFreeIbi(DevHandle handle, uint16_t addr);
**Table 7** Description of I3cFreeIbi
<a name="table7"></a>
<table><thead align="left"><tr><th class="cellrowborder" valign="top" width="50%"><p><strong>Parameter</strong></p>
</th>
<th class="cellrowborder" valign="top" width="50%"><p><strong>Description</strong></p>
</th>
</tr>
</thead>
<tbody><tr><td class="cellrowborder" valign="top" width="50%"><p>handle</p>
</td>
<td class="cellrowborder" valign="top" width="50%"><p>I3C controller handle.</p>
</td>
</tr>
<tr><td class="cellrowborder" valign="top" width="50%"><p>addr</p>
</td>
<td class="cellrowborder" valign="top" width="50%"><p>I3C device address.</p>
</td>
</tr>
<tr><td class="cellrowborder" valign="top" width="50%"><p><strong>Return Value</strong></p>
</td>
<td class="cellrowborder" valign="top" width="50%"><p><strong>Description</strong></p>
</td>
</tr>
<tr><td class="cellrowborder" valign="top" width="50%"><p>0</p>
</td>
<td class="cellrowborder" valign="top" width="50%"><p>The operation is successful.</p>
</td>
</tr>
<tr><td class="cellrowborder" valign="top" width="50%"><p>Negative number</p>
</td>
<td class="cellrowborder" valign="top" width="50%"><p>Failed to release the IBI.</p>
</td>
</tr>
</tbody>
</table>
| Name | Description |
| ---------- | -------------- |
| handle | I3C controller handle. |
| addr | I3C device address. |
| **Return Value**| **Description**|
| 0 | The operation is successful. |
| Negative value | The operation failed. |
The following is an example:
```c
I3cFreeIbi(i3cHandle, 0x3F); /* Release an IBI. */
```
### Closing an I3C controller<a name="section11"></a>
#### Closing an I3C Controller
Call **I3cClose()** to close the I3C controller after the communication is complete.
```c
......@@ -464,28 +319,18 @@ void I3cClose(DevHandle handle);
**Table 8** Description of I3cClose
<a name="table4"></a>
<table><thead align="left"><tr><th class="cellrowborder" valign="top" width="50%"><p> Parameter</p>
</th>
<th class="cellrowborder" valign="top" width="50%"><p>Description</p>
</th>
</tr>
</thead>
<tbody><tr><td class="cellrowborder" valign="top" width="50%"><p>handle</p>
</td>
<td class="cellrowborder" valign="top" width="50%"><p>I3C controller handle.</p>
</td>
</tr>
</tbody>
</table>
| Name | Description |
| ---------- | -------------- |
| handle | I3C controller handle. |
The following is an example:
```c
I3cClose(i3cHandle); /* Close an I3C controller. */
I3cClose(i3cHandle); /* Close the I3C controller. */
```
## Example<a name="section12""></a>
## Development Example
This following example shows how to use I3C APIs to manage an I3C device on a Hi3516D V300 development board.
......@@ -503,10 +348,9 @@ The sample code is as follows:
```c
#include "i3c_if.h" /* Header file for I3C standard APIs */
#include "i3c_ccc.h" /* Header file for I3C CCC */
#include "hdf_log.h" /* Header file for log APIs */
##include "osal_io.h" /* Header file for I/O read and write APIs */
##include "osal_time.h" /* Header file for delay and sleep APIs */
#include "osal_time.h" /* Header file for delay and sleep APIs */
/* Define a device structure to hold information. */
struct TestI3cDevice {
......@@ -516,7 +360,7 @@ struct TestI3cDevice {
DevHandle i3cHandle; /* I3C controller handle */
};
/* Use I3cTransfer to encapsulate a register read/write helper function. Use flag to indicate a read or write operation. */
/* Use I3cTransfer() to encapsulate a register read/write helper function. Use flag to indicate a read or write operation. */
static int TestI3cReadWrite(struct TestI3cDevice *testDevice, unsigned int regAddr,
unsigned char *regData, unsigned int dataLen, uint8_t flag)
{
......@@ -539,7 +383,7 @@ static int TestI3cReadWrite(struct TestI3cDevice *testDevice, unsigned int regAd
msgs[0].buf = regBuf;
msgs[1].addr = testDevice->addr;
msgs[1].flags = (flag == 1) ? I3C_FLAG_READ: 0; /* Add a read flag bit to read data. */
msgs[1].flags = (flag == 1) ? I3C_FLAG_READ : 0; /* Add the read flag. */
msgs[1].len = dataLen;
msgs[1].buf = regData;
......
# UART<a name="EN-US_TOPIC_0000001153656474"></a>
# UART
## Overview<a name="section1761881586154520"></a>
In the Hardware Driver Foundation \(HDF\), the Universal Asynchronous Receiver/Transmitter \(UART\) uses the independent service mode for API adaptation. In this mode, each device independently publishes a device service to handle external access requests. After receiving an access request from an API, the device manager extracts the parameters in the request to call the internal method of the target device. In the independent service mode, the service management capabilities of the HDF Device Manager can be directly used. However, you need to configure a device node for each device, which increases the memory usage.
## Overview
**Figure 1** Independent service mode<a name="fig1474518243468"></a>
![](figures/independent-service-mode.png "independent-service-mode-14")
In the Hardware Driver Foundation (HDF), the Universal Asynchronous Receiver/Transmitter (UART) uses the independent service mode for API adaptation. In this mode, each device independently publishes a service to process external access requests. When receiving an access request, the HDF DeviceManager extracts parameters from the request to call the internal APIs of the target device. In the independent service mode, the HDF DeviceManager provides service management capabilities. However, you need to configure a node for each device, which increases memory usage.
## Available APIs<a name="section752964871810"></a>
**Figure 1** Independent service mode
![image](figures/independent-service-mode.png)
## Available APIs
**UartHostMethod**:
UartHostMethod
```
struct UartHostMethod {
......@@ -26,181 +30,57 @@ struct UartHostMethod {
};
```
**Table 1** Callbacks for the members in the UartHostMethod structure
<a name="table22862114719"></a>
<table><thead align="left"><tr id="row5297211471"><th class="cellrowborder" valign="top" width="20%" id="mcps1.2.6.1.1"><p id="p12291121134710"><a name="p12291121134710"></a><a name="p12291121134710"></a>Callback</p>
</th>
<th class="cellrowborder" valign="top" width="20%" id="mcps1.2.6.1.2"><p id="p3291921164712"><a name="p3291921164712"></a><a name="p3291921164712"></a>Input Parameter</p>
</th>
<th class="cellrowborder" valign="top" width="19.98%" id="mcps1.2.6.1.3"><p id="p15291321114718"><a name="p15291321114718"></a><a name="p15291321114718"></a>Output Parameter</p>
</th>
<th class="cellrowborder" valign="top" width="20.02%" id="mcps1.2.6.1.4"><p id="p03092115478"><a name="p03092115478"></a><a name="p03092115478"></a>Return Value</p>
</th>
<th class="cellrowborder" valign="top" width="20%" id="mcps1.2.6.1.5"><p id="p230172113475"><a name="p230172113475"></a><a name="p230172113475"></a>Description</p>
</th>
</tr>
</thead>
<tbody><tr id="row13305217472"><td class="cellrowborder" valign="top" width="20%" headers="mcps1.2.6.1.1 "><p id="p193012104714"><a name="p193012104714"></a><a name="p193012104714"></a>Init</p>
</td>
<td class="cellrowborder" valign="top" width="20%" headers="mcps1.2.6.1.2 "><p id="p53082134713"><a name="p53082134713"></a><a name="p53082134713"></a><strong id="b231216565514"><a name="b231216565514"></a><a name="b231216565514"></a>host</strong>: structure pointer to the UART controller at the core layer.</p>
</td>
<td class="cellrowborder" valign="top" width="19.98%" headers="mcps1.2.6.1.3 "><p id="p14301121174719"><a name="p14301121174719"></a><a name="p14301121174719"></a></p>
</td>
<td class="cellrowborder" valign="top" width="20.02%" headers="mcps1.2.6.1.4 "><p id="p83092116473"><a name="p83092116473"></a><a name="p83092116473"></a>HDF_STATUS</p>
</td>
<td class="cellrowborder" valign="top" width="20%" headers="mcps1.2.6.1.5 "><p id="p173032124713"><a name="p173032124713"></a><a name="p173032124713"></a>Initializes the UART device.</p>
</td>
</tr>
<tr id="row530121144713"><td class="cellrowborder" valign="top" width="20%" headers="mcps1.2.6.1.1 "><p id="p12301215474"><a name="p12301215474"></a><a name="p12301215474"></a>Deinit</p>
</td>
<td class="cellrowborder" valign="top" width="20%" headers="mcps1.2.6.1.2 "><p id="p14301921174718"><a name="p14301921174718"></a><a name="p14301921174718"></a><strong id="b7500154935512"><a name="b7500154935512"></a><a name="b7500154935512"></a>host</strong>: structure pointer to the UART controller at the core layer.</p>
</td>
<td class="cellrowborder" valign="top" width="19.98%" headers="mcps1.2.6.1.3 "><p id="p143142110477"><a name="p143142110477"></a><a name="p143142110477"></a></p>
</td>
<td class="cellrowborder" valign="top" width="20.02%" headers="mcps1.2.6.1.4 "><p id="p1531162174719"><a name="p1531162174719"></a><a name="p1531162174719"></a>HDF_STATUS</p>
</td>
<td class="cellrowborder" valign="top" width="20%" headers="mcps1.2.6.1.5 "><p id="p203162110478"><a name="p203162110478"></a><a name="p203162110478"></a>Deinitializes the UART device.</p>
</td>
</tr>
<tr id="row93172118476"><td class="cellrowborder" valign="top" width="20%" headers="mcps1.2.6.1.1 "><p id="p1231102194712"><a name="p1231102194712"></a><a name="p1231102194712"></a>Read</p>
</td>
<td class="cellrowborder" valign="top" width="20%" headers="mcps1.2.6.1.2 "><p id="p117841019115819"><a name="p117841019115819"></a><a name="p117841019115819"></a><strong id="b8784519205820"><a name="b8784519205820"></a><a name="b8784519205820"></a>host</strong>: structure pointer to the UART controller at the core layer.</p>
<p id="p13318214472"><a name="p13318214472"></a><a name="p13318214472"></a><strong id="b76471214185712"><a name="b76471214185712"></a><a name="b76471214185712"></a>size</strong>: data size, which is of the uint32_t type.</p>
</td>
<td class="cellrowborder" valign="top" width="19.98%" headers="mcps1.2.6.1.3 "><p id="p1313213473"><a name="p1313213473"></a><a name="p1313213473"></a><strong id="b1372195311577"><a name="b1372195311577"></a><a name="b1372195311577"></a>data</strong>: uint8_t pointer to the output data.</p>
</td>
<td class="cellrowborder" valign="top" width="20.02%" headers="mcps1.2.6.1.4 "><p id="p193110216473"><a name="p193110216473"></a><a name="p193110216473"></a>HDF_STATUS</p>
</td>
<td class="cellrowborder" valign="top" width="20%" headers="mcps1.2.6.1.5 "><p id="p1331102115475"><a name="p1331102115475"></a><a name="p1331102115475"></a>Receives data.</p>
</td>
</tr>
<tr id="row1731102120479"><td class="cellrowborder" valign="top" width="20%" headers="mcps1.2.6.1.1 "><p id="p731321204711"><a name="p731321204711"></a><a name="p731321204711"></a>Write</p>
</td>
<td class="cellrowborder" valign="top" width="20%" headers="mcps1.2.6.1.2 "><p id="p11377332105815"><a name="p11377332105815"></a><a name="p11377332105815"></a><strong id="b193771532135811"><a name="b193771532135811"></a><a name="b193771532135811"></a>host</strong>: structure pointer to the UART controller at the core layer.</p>
<p id="p174031635125817"><a name="p174031635125817"></a><a name="p174031635125817"></a><strong id="b540373505819"><a name="b540373505819"></a><a name="b540373505819"></a>data</strong>: pointer to the input data, which is of the uint8_t type.</p>
<p id="p15311321204719"><a name="p15311321204719"></a><a name="p15311321204719"></a><strong id="b15686191305911"><a name="b15686191305911"></a><a name="b15686191305911"></a>size</strong>: data size, which is of the uint32_t type.</p>
</td>
<td class="cellrowborder" valign="top" width="19.98%" headers="mcps1.2.6.1.3 "><p id="p143142114478"><a name="p143142114478"></a><a name="p143142114478"></a></p>
</td>
<td class="cellrowborder" valign="top" width="20.02%" headers="mcps1.2.6.1.4 "><p id="p143212110477"><a name="p143212110477"></a><a name="p143212110477"></a>HDF_STATUS</p>
</td>
<td class="cellrowborder" valign="top" width="20%" headers="mcps1.2.6.1.5 "><p id="p123216211477"><a name="p123216211477"></a><a name="p123216211477"></a>Sends data.</p>
</td>
</tr>
<tr id="row73215214478"><td class="cellrowborder" valign="top" width="20%" headers="mcps1.2.6.1.1 "><p id="p1032112119475"><a name="p1032112119475"></a><a name="p1032112119475"></a>SetBaud</p>
</td>
<td class="cellrowborder" valign="top" width="20%" headers="mcps1.2.6.1.2 "><p id="p863959125812"><a name="p863959125812"></a><a name="p863959125812"></a><strong id="b11631159145818"><a name="b11631159145818"></a><a name="b11631159145818"></a>host</strong>: structure pointer to the UART controller at the core layer. </p>
<p id="p3321521134717"><a name="p3321521134717"></a><a name="p3321521134717"></a><strong id="b16745461412"><a name="b16745461412"></a><a name="b16745461412"></a>baudRate</strong>: pointer to the input baud rate, which is of the uint32_t type.</p>
</td>
<td class="cellrowborder" valign="top" width="19.98%" headers="mcps1.2.6.1.3 "><p id="p18327218478"><a name="p18327218478"></a><a name="p18327218478"></a></p>
</td>
<td class="cellrowborder" valign="top" width="20.02%" headers="mcps1.2.6.1.4 "><p id="p23242111475"><a name="p23242111475"></a><a name="p23242111475"></a>HDF_STATUS</p>
</td>
<td class="cellrowborder" valign="top" width="20%" headers="mcps1.2.6.1.5 "><p id="p7321521114711"><a name="p7321521114711"></a><a name="p7321521114711"></a>Sets the baud rate.</p>
</td>
</tr>
<tr id="row113252104713"><td class="cellrowborder" valign="top" width="20%" headers="mcps1.2.6.1.1 "><p id="p9323219476"><a name="p9323219476"></a><a name="p9323219476"></a>GetBaud</p>
</td>
<td class="cellrowborder" valign="top" width="20%" headers="mcps1.2.6.1.2 "><p id="p132821184711"><a name="p132821184711"></a><a name="p132821184711"></a><strong id="b4510164912550"><a name="b4510164912550"></a><a name="b4510164912550"></a>host</strong>: structure pointer to the UART controller at the core layer.</p>
</td>
<td class="cellrowborder" valign="top" width="19.98%" headers="mcps1.2.6.1.3 "><p id="p63262112477"><a name="p63262112477"></a><a name="p63262112477"></a><strong id="b1097116311227"><a name="b1097116311227"></a><a name="b1097116311227"></a>baudRate</strong>: uint32_t pointer to the output baud rate.</p>
</td>
<td class="cellrowborder" valign="top" width="20.02%" headers="mcps1.2.6.1.4 "><p id="p13262174719"><a name="p13262174719"></a><a name="p13262174719"></a>HDF_STATUS</p>
</td>
<td class="cellrowborder" valign="top" width="20%" headers="mcps1.2.6.1.5 "><p id="p163232154717"><a name="p163232154717"></a><a name="p163232154717"></a>Obtains the current baud rate.</p>
</td>
</tr>
<tr id="row2032102118472"><td class="cellrowborder" valign="top" width="20%" headers="mcps1.2.6.1.1 "><p id="p9331321154714"><a name="p9331321154714"></a><a name="p9331321154714"></a>GetAttribute</p>
</td>
<td class="cellrowborder" valign="top" width="20%" headers="mcps1.2.6.1.2 "><p id="p15331721164715"><a name="p15331721164715"></a><a name="p15331721164715"></a><strong id="b1518144935510"><a name="b1518144935510"></a><a name="b1518144935510"></a>host</strong>: structure pointer to the UART controller at the core layer.</p>
</td>
<td class="cellrowborder" valign="top" width="19.98%" headers="mcps1.2.6.1.3 "><p id="p23313219472"><a name="p23313219472"></a><a name="p23313219472"></a><strong id="b16392039333"><a name="b16392039333"></a><a name="b16392039333"></a>attribute</strong>: structure pointer to the output attributes. For details, see <strong id="b524111513416"><a name="b524111513416"></a><a name="b524111513416"></a>UartAttribute</strong> in <strong id="b47291920444"><a name="b47291920444"></a><a name="b47291920444"></a>uart_if.h</strong>.</p>
</td>
<td class="cellrowborder" valign="top" width="20.02%" headers="mcps1.2.6.1.4 "><p id="p833142115476"><a name="p833142115476"></a><a name="p833142115476"></a>HDF_STATUS</p>
</td>
<td class="cellrowborder" valign="top" width="20%" headers="mcps1.2.6.1.5 "><p id="p63342119476"><a name="p63342119476"></a><a name="p63342119476"></a>Obtains UART attributes.</p>
</td>
</tr>
<tr id="row1133112144717"><td class="cellrowborder" valign="top" width="20%" headers="mcps1.2.6.1.1 "><p id="p14331421114715"><a name="p14331421114715"></a><a name="p14331421114715"></a>SetAttribute</p>
</td>
<td class="cellrowborder" valign="top" width="20%" headers="mcps1.2.6.1.2 "><p id="p147011110590"><a name="p147011110590"></a><a name="p147011110590"></a><strong id="b070151125915"><a name="b070151125915"></a><a name="b070151125915"></a>host</strong>: structure pointer to the UART controller at the core layer.</p>
<p id="p16331210473"><a name="p16331210473"></a><a name="p16331210473"></a><strong id="b1497919522420"><a name="b1497919522420"></a><a name="b1497919522420"></a>attribute</strong>: structure pointer to the input attributes.</p>
</td>
<td class="cellrowborder" valign="top" width="19.98%" headers="mcps1.2.6.1.3 "><p id="p3331721204710"><a name="p3331721204710"></a><a name="p3331721204710"></a></p>
</td>
<td class="cellrowborder" valign="top" width="20.02%" headers="mcps1.2.6.1.4 "><p id="p03302111471"><a name="p03302111471"></a><a name="p03302111471"></a>HDF_STATUS</p>
</td>
<td class="cellrowborder" valign="top" width="20%" headers="mcps1.2.6.1.5 "><p id="p1933152113478"><a name="p1933152113478"></a><a name="p1933152113478"></a>Sets UART attributes.</p>
</td>
</tr>
<tr id="row834221114716"><td class="cellrowborder" valign="top" width="20%" headers="mcps1.2.6.1.1 "><p id="p1934821104719"><a name="p1934821104719"></a><a name="p1934821104719"></a>SetTransMode</p>
</td>
<td class="cellrowborder" valign="top" width="20%" headers="mcps1.2.6.1.2 "><p id="p1821251985919"><a name="p1821251985919"></a><a name="p1821251985919"></a><strong id="b1121271918594"><a name="b1121271918594"></a><a name="b1121271918594"></a>host</strong>: structure pointer to the UART controller at the core layer.</p>
<p id="p1034621104717"><a name="p1034621104717"></a><a name="p1034621104717"></a><strong id="b104767219711"><a name="b104767219711"></a><a name="b104767219711"></a>mode</strong>: transmission mode, which is an enumerated value. For details, see <strong id="b2101455871"><a name="b2101455871"></a><a name="b2101455871"></a>UartTransMode</strong> in <strong id="b99657016815"><a name="b99657016815"></a><a name="b99657016815"></a>uart_if.h</strong>).</p>
</td>
<td class="cellrowborder" valign="top" width="19.98%" headers="mcps1.2.6.1.3 "><p id="p173442110475"><a name="p173442110475"></a><a name="p173442110475"></a></p>
</td>
<td class="cellrowborder" valign="top" width="20.02%" headers="mcps1.2.6.1.4 "><p id="p1734721194720"><a name="p1734721194720"></a><a name="p1734721194720"></a>HDF_STATUS</p>
</td>
<td class="cellrowborder" valign="top" width="20%" headers="mcps1.2.6.1.5 "><p id="p15341021194715"><a name="p15341021194715"></a><a name="p15341021194715"></a>Sets the UART transmission mode.</p>
</td>
</tr>
<tr id="row434192119479"><td class="cellrowborder" valign="top" width="20%" headers="mcps1.2.6.1.1 "><p id="p133442184717"><a name="p133442184717"></a><a name="p133442184717"></a>PollEvent</p>
</td>
<td class="cellrowborder" valign="top" width="20%" headers="mcps1.2.6.1.2 "><p id="p31278367592"><a name="p31278367592"></a><a name="p31278367592"></a><strong id="b1127163625919"><a name="b1127163625919"></a><a name="b1127163625919"></a>host</strong>: structure pointer to the UART controller at the core layer.</p>
<p id="p16654144015591"><a name="p16654144015591"></a><a name="p16654144015591"></a><strong id="b86541440135917"><a name="b86541440135917"></a><a name="b86541440135917"></a>filep</strong>: void pointer to a file.</p>
<p id="p634121104712"><a name="p634121104712"></a><a name="p634121104712"></a><strong id="b163481035141514"><a name="b163481035141514"></a><a name="b163481035141514"></a>table</strong>: void pointer to a poll_table.</p>
</td>
<td class="cellrowborder" valign="top" width="19.98%" headers="mcps1.2.6.1.3 "><p id="p1334142111479"><a name="p1334142111479"></a><a name="p1334142111479"></a></p>
</td>
<td class="cellrowborder" valign="top" width="20.02%" headers="mcps1.2.6.1.4 "><p id="p133472110473"><a name="p133472110473"></a><a name="p133472110473"></a>HDF_STATUS</p>
</td>
<td class="cellrowborder" valign="top" width="20%" headers="mcps1.2.6.1.5 "><p id="p63522174720"><a name="p63522174720"></a><a name="p63522174720"></a>Polls for pending events.</p>
</td>
</tr>
</tbody>
</table>
## How to Develop<a name="section944397404154520"></a>
**Table 1** Description of the callback functions in UartHostMethod
| Function| Input Parameter| Output Parameter| Return Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| Init | **host**: structure pointer to the UART controller at the core layer.| –| HDF_STATUS| Initializes a UART device.|
| Deinit | **host**: structure pointer to the UART controller at the core layer.| –| HDF_STATUS| Deinitializes a UART device.|
| Read | **host**: structure pointer to the UART controller at the core layer.<br>**size**: data size, which is of the uint32_t type.| **data**: pointer to the output data. The value is of the uint8_t type.| HDF_STATUS| Reads data.|
| Write | **host**: structure pointer to the UART controller at the core layer.<br>**data**: pointer to the input data. The value is of the uint8_t type.<br>**size**: data size, which is of the uint32_t type.| –| HDF_STATUS| Writes data.|
| SetBaud | **host**: structure pointer to the UART controller at the core layer.<br>**baudRate**: pointer to the input baud rate. The value is of the uint32_t type. | –| HDF_STATUS| Sets the baud rate.|
| GetBaud | **host**: structure pointer to the UART controller at the core layer.| **baudRate**: pointer to the output baud rate. The value is of the uint32_t type.| HDF_STATUS| Obtains the current baud rate.|
| GetAttribute | **host**: structure pointer to the UART controller at the core layer.| **attribute**: structure pointer to the UART attributes. For details, see **UartAttribute** in **uart_if.h**.| HDF_STATUS| Obtains UART attributes.|
| SetAttribute | **host**: structure pointer to the UART controller at the core layer.<br>**attribute**: structure pointer to the UART attributes to set.| –| HDF_STATUS| Sets UART attributes.|
| SetTransMode | **host**: structure pointer to the UART controller at the core layer.<br>**mode**: transfer mode to set. For details, see **UartTransMode** in **uart_if.h**.| –| HDF_STATUS| Sets the UART transfer mode.|
| PollEvent | **host**: structure pointer to the UART controller at the core layer.<br>**filep**: void pointer to a file.<br>**table**: void pointer to poll_table.| –| HDF_STATUS| Polls for pending events.|
## How to Develop
The UART module adaptation involves the following steps:
1. Instantiate the driver entry.
- Instantiate the **HdfDriverEntry** structure.
- Call **HDF\_INIT** to register the **HdfDriverEntry** instance with the HDF.
- Call **HDF_INIT** to register the **HdfDriverEntry** instance with the HDF.
2. Configure attribute files.
- Add the **deviceNode** information to the **device\_info.hcs** file.
- \(Optional\) Add the **uart\_config.hcs** file.
- Add the **deviceNode** information to the **device_info.hcs** file.
- (Optional) Add the **uart_config.hcs** file.
3. Instantiate the UART controller object.
- Initialize **UartHost**.
- Instantiate **UartHostMethod** in the **UartHost** object.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br>
> For details about the functions in **UartHostMethod**, see [Available APIs](#available-apis).
>![](../public_sys-resources/icon-note.gif) **NOTE**
4. Debug the driver.<br>
(Optional) For new drivers, verify the basic functions, such as the UART status control and response to interrupts.
>For details, see [Available APIs](#available-apis).
## Development Example
4. Debug the driver.
- \(Optional\) For new drivers, verify the basic functions, such as the UART control status and response to interrupts.
The following uses **uart_hi35xx.c** as an example to present the information required for implementing device functions.
1. Instantiate the driver entry.<br/>The driver entry must be a global variable of the **HdfDriverEntry** type (defined in **hdf_device_desc.h**), and the value of **moduleName** must be the same as that in **device_info.hcs**. In the HDF, the start address of each **HdfDriverEntry** object of all loaded drivers is collected to form a segment address space similar to an array for the upper layer to invoke.
Generally, the HDF calls the **Bind** function and then the **Init** function to load a driver. If **Init** fails to be called, the HDF calls **Release** to release driver resources and exit.
## Development Example<a name="section774610224154520"></a>
The following uses **uart\_hi35xx.c** as an example to present the contents that need to be provided by the vendor to implement device functions.
1. Instantiate the driver entry. The driver entry must be a global variable of the **HdfDriverEntry** type \(defined in **hdf\_device\_desc.h**\), and the value of **moduleName** must be the same as that in **device\_info.hcs**. In the HDF, the start address of each **HdfDriverEntry** object of all loaded drivers is collected to form a segment address space similar to an array for the upper layer to invoke.
Generally, HDF calls the **Bind** function and then the **Init** function to load a driver. If **Init** fails to be called, HDF calls **Release** to release driver resources and exit.
- UART driver entry reference
UART driver entry example:
```
struct HdfDriverEntry g_hdfUartDevice = {
.moduleVersion = 1,
.moduleName = "HDF_PLATFORM_UART", // (Mandatory) This parameter must be the same as that in the .hcs file.
.moduleName = "HDF_PLATFORM_UART", // (Mandatory) The value must be the same as that in the .hcs file.
.Bind = HdfUartDeviceBind, // See the Bind function.
.Init = HdfUartDeviceInit, // See the Init function.
.Release = HdfUartDeviceRelease, //See the Release function.
......@@ -209,11 +89,10 @@ The following uses **uart\_hi35xx.c** as an example to present the contents th
HDF_INIT(g_hdfUartDevice);
```
2. Add the **deviceNode** information to the **device\_info.hcs** file and configure the device attributes in the **uart\_config.hcs** file. The **deviceNode** information is related to registration of the driver entry. The device attribute values are closely related to the default values or value ranges of the **UartHost** members at the core layer.
2. Add the **deviceNode** information to the **device_info.hcs** file and configure the device attributes in the **uart_config.hcs** file.<br> The **deviceNode** information is related to registration of the driver entry. The device attribute values are closely related to the default values or value ranges of the **UartHost** members at the core layer.
In this example, there is only one UART controller. If there are multiple UART controllers, you need to add the **deviceNode** information to the **device_info** file and add the corresponding device attributes to the **uart_config** file for each controller.
- **device_info.hcs** configuration example
In this example, there is only one UART controller. If there are multiple UART controllers, you need to add the **deviceNode** information to the **device\_info** file and add the corresponding device attributes to the **uart\_config** file.
- **device\_info.hcs** configuration reference
```
root {
......@@ -224,15 +103,15 @@ The following uses **uart\_hi35xx.c** as an example to present the contents th
priority = 50;
device_uart :: device {
device0 :: deviceNode {
policy = 1; // The value 1 indicates that the driver publishes kernel-mode services. The value 2 indicates that the driver publishes user-mode services.
priority = 40; // Driver startup priority
permission = 0644; // Permission for the driver to create a device node
moduleName = "HDF_PLATFORM_UART"; // Driver name, which must be the same as that of moduleName in the driver entry structure.
policy = 1; // The driver publishes services only for kernel-mode processes.
priority = 40; // Driver startup priority.
permission = 0644; // Permission for the driver to create a device node.
moduleName = "HDF_PLATFORM_UART"; // Driver name, which must be the same as moduleName in the HdfDriverEntry structure.
serviceName = "HDF_PLATFORM_UART_0";// Unique name of the service published by the driver. The name is in the HDF_PLATFORM_UART_X format. X indicates the UART controller number.
deviceMatchAttr = "hisilicon_hi35xx_uart_0"; // Keyword matching the private data of the driver. The value must be the same as that of match_attr in the private data configuration table of the driver.
deviceMatchAttr = "hisilicon_hi35xx_uart_0"; // Keyword for matching the private data of the driver. The value must be the same as that of match_attr in the private data configuration table of the driver.
}
device1 :: deviceNode {
policy = 2;
policy = 2; // The driver publishes services for both kernel- and user-mode processes.
permission = 0644;
priority = 40;
moduleName = "HDF_PLATFORM_UART";
......@@ -246,20 +125,21 @@ The following uses **uart\_hi35xx.c** as an example to present the contents th
}
```
- **uart\_config.hcs** configuration reference
- **uart_config.hcs** configuration example
```
root {
platform {
template uart_controller {// Template configuration. In the template, you can configure the common parameters shared by service nodes.
template uart_controller { // Template configuration. In the template, you can configure the common parameters shared by device nodes.
match_attr = "";
num = 0; // (Mandatory) Device number
baudrate = 115200; // (Mandatory) Baud rate. Set the value based on service requirements.
fifoRxEn = 1; // (Mandatory) Enable the receive of FIFOs.
fifoTxEn = 1; // (Mandatory) Enable the transmit of FIFOs.
flags = 4; // (Mandatory) Flag signal
fifoRxEn = 1; // (Mandatory) Enable FIFOs to be received.
fifoTxEn = 1; // (Mandatory) Enable FIFOs to be transferred.
flags = 4; // (Mandatory) Flag signal.
regPbase = 0x120a0000; // (Mandatory) Used for address mapping.
interrupt = 38; // (Mandatory) Interrupt number
interrupt = 38; // (Mandatory) Interrupt number.
iomemCount = 0x48; // (Mandatory) Used for address mapping.
}
controller_0x120a0000 :: uart_controller {
......@@ -273,42 +153,43 @@ The following uses **uart\_hi35xx.c** as an example to present the contents th
match_attr = "hisilicon_hi35xx_uart_1";
}
...
//(Optional) Add nodes to the device_info.hcs file as required.
//(Optional) Add more controller data. The node information must have been added in the device_info.hcs file.
}
}
```
3. Initialize the **UartHost** object at the core layer, including initializing the vendor custom structure \(transferring parameters and data\), instantiating **UartHostMethod** \(used to call underlying functions of the driver\) in **UartHost**, and implementing the **HdfDriverEntry** member functions \(**Bind**, **Init**, and **Release**\).
- Custom structure reference
3. Initialize the **UartHost** object at the core layer, including defining a custom structure (to pass parameters and data) and implementing the **HdfDriverEntry** member functions (**Bind**, **Init**, and **Release**) to instantiate **UartHostMethod** in **UartHost** (so that the underlying driver functions can be called).
- Defining a custom structure
To the driver, the custom structure holds parameters and data. The **DeviceResourceIface** method provided by the HDF reads the values in the **uart_config.hcs** file to initialize the members in the custom structure and passes important parameters, such as the device number, to the **UartHost** object at the core layer.
To the driver, the custom structure carries parameters and data. The values in the **uart\_config.hcs** file are read by HDF, and the structure members are initialized through **DeviceResourceIface**. Some important values, such as the device number, are also passed to the objects at the core layer.
```
struct UartPl011Port {// Structure related to the API
struct UartPl011Port { // Interface structure
int32_t enable;
unsigned long physBase; // Physical address
uint32_t irqNum; // Interrupt number
uint32_t defaultBaudrate;// Default baud rate
uint32_t flags; // Flag signal, which is related to the following three macros.
uint32_t flags; // Flags related to the following three macros.
#define PL011_FLG_IRQ_REQUESTED (1 << 0)
#define PL011_FLG_DMA_RX_REQUESTED (1 << 1)
#define PL011_FLG_DMA_TX_REQUESTED (1 << 2)
struct UartDmaTransfer *rxUdt; // DMA transmission
struct UartDriverData *udd; // See the following description.
struct UartDmaTransfer *rxUdt; // DMA transfer
struct UartDriverData *udd; // The data structure is defined as follows:
};
struct UartDriverData {// Structure related to data transmission
struct UartDriverData { // Structure related to data transfer
uint32_t num;
uint32_t baudrate; // Baud rate (configurable)
struct UartAttribute attr; // Transmission attributes, such as the data bit and stop bit
struct UartTransfer *rxTransfer; // FIFO structure related to the buffer
struct UartAttribute attr; // Attributes, such as the data bit and stop bit, related to data transfer
struct UartTransfer *rxTransfer; // Buffer (FIFO structure)
wait_queue_head_t wait; // Queuing signal related to conditional variables
int32_t count; // Data count
int32_t state; // UART controller status
int32_t state; // UART controller state
#define UART_STATE_NOT_OPENED 0
#define UART_STATE_OPENING 1
#define UART_STATE_USEABLE 2
#define UART_STATE_SUSPENED 3
uint32_t flags; // Status flag
#define UART_STATE_SUSPENDED 3
uint32_t flags; // Status flags
#define UART_FLG_DMA_RX (1 << 0)
#define UART_FLG_DMA_TX (1 << 1)
#define UART_FLG_RD_BLOCK (1 << 2)
......@@ -317,21 +198,21 @@ The following uses **uart\_hi35xx.c** as an example to present the contents th
void *private; // It stores the pointer to the start address of UartPl011Port for easy invocation.
};
// UartHost is the controller structure at the core layer. Its members are assigned with values by using the Init function.
// UartHost is the controller structure at the core layer. The Init function assigns values to the members of UartHost.
struct UartHost {
struct IDeviceIoService service;
struct HdfDeviceObject *device;
uint32_t num;
OsalAtomic atom;
void *priv; // It stores the pointer to the start address of the vendor's custom structure for invoking the structure.
struct UartHostMethod *method; // Hook at the core layer. The vendor needs to implement and instantiate its member functions.
void *priv; // It stores the pointer to the start address of the vendor's custom structure for easy invocation.
struct UartHostMethod *method; // Hook at the core layer. You need to implement and instantiate its member functions.
};
```
- Instantiating **UartHostMethod** in **UartHost** (other members are initialized by **Bind**)
- Instantiate the callback function structure **UartHostMethod** in **UartHost**. Other members are initialized by using the **Bind** function.
```
// Example in pwm_hi35xx.c: instantiate the hook.
// Example in uart_hi35xx.c: instantiate the hook.
struct UartHostMethod g_uartHostMethod = {
.Init = Hi35xxInit,
.Deinit = Hi35xxDeinit,
......@@ -346,62 +227,32 @@ The following uses **uart\_hi35xx.c** as an example to present the contents th
};
```
- Bind function
Input parameters:
**HdfDeviceObject**, an interface parameter exposed by the driver, contains the .hcs configuration file information.
Return values:
HDF\_STATUS \(The following table lists some status. For details about other status, see **HDF\_STATUS** in the **//drivers/framework/include/utils/hdf\_base.h** file.\)
**Table 2** Input parameters and return values of the Bind function
<a name="table69781823185619"></a>
<table><thead align="left"><tr id="row997916234569"><th class="cellrowborder" valign="top" width="50%" id="mcps1.2.3.1.1"><p id="p99801123205616"><a name="p99801123205616"></a><a name="p99801123205616"></a>Status (Value)</p>
</th>
<th class="cellrowborder" valign="top" width="50%" id="mcps1.2.3.1.2"><p id="p698092355615"><a name="p698092355615"></a><a name="p698092355615"></a>Description</p>
</th>
</tr>
</thead>
<tbody><tr id="row39803236568"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p8980123175613"><a name="p8980123175613"></a><a name="p8980123175613"></a>HDF_ERR_INVALID_OBJECT</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p79801423165611"><a name="p79801423165611"></a><a name="p79801423165611"></a>Invalid controller object</p>
</td>
</tr>
<tr id="row3980023165617"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p698011239568"><a name="p698011239568"></a><a name="p698011239568"></a>HDF_ERR_MALLOC_FAIL</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p798082395610"><a name="p798082395610"></a><a name="p798082395610"></a>Failed to allocate memory</p>
</td>
</tr>
<tr id="row10980223165610"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p1980172365614"><a name="p1980172365614"></a><a name="p1980172365614"></a>HDF_ERR_INVALID_PARAM</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p14980223145614"><a name="p14980223145614"></a><a name="p14980223145614"></a>Invalid parameter</p>
</td>
</tr>
<tr id="row7980142315612"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p17980152385611"><a name="p17980152385611"></a><a name="p17980152385611"></a>HDF_ERR_IO</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p17980182385611"><a name="p17980182385611"></a><a name="p17980182385611"></a>I/O error</p>
</td>
</tr>
<tr id="row9980122312564"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p10981323155616"><a name="p10981323155616"></a><a name="p10981323155616"></a>HDF_SUCCESS</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p11981423175614"><a name="p11981423175614"></a><a name="p11981423175614"></a>Initialization successful</p>
</td>
</tr>
<tr id="row15981122365618"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p19981122311567"><a name="p19981122311567"></a><a name="p19981122311567"></a>HDF_FAILURE</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p199811723105615"><a name="p199811723105615"></a><a name="p199811723105615"></a>Initialization failed</p>
</td>
</tr>
</tbody>
</table>
- **Bind** function
Input parameter:
**HdfDeviceObject**, an interface parameter exposed by the driver, contains the .hcs information.
Return value:
HDF_STATUS<br/>The table below describes some status. For more information, see **HDF_STATUS** in the **/drivers/framework/include/utils/hdf_base.h** file.
**Table 2** HDF_STATUS
| Status| Description|
| -------- | -------- |
| HDF_ERR_INVALID_OBJECT | Invalid controller object.|
| HDF_ERR_MALLOC_FAIL | Failed to allocate memory.|
| HDF_ERR_INVALID_PARAM | Invalid parameter.|
| HDF_ERR_IO | I/O error.|
| HDF_SUCCESS | Initialization successful.|
| HDF_FAILURE | Initialization failed.|
Function description:
Initializes the custom structure object and **UartHost**.
```
//uart_hi35xx.c
static int32_t HdfUartDeviceBind(struct HdfDeviceObject *device)
......@@ -409,36 +260,37 @@ The following uses **uart\_hi35xx.c** as an example to present the contents th
...
return (UartHostCreate(device) == NULL)? HDF_FAILURE: HDF_SUCCESS;// (Mandatory) Call UartHostCreate.
}
// Description of the UartHostCreate function at the core layer in uart_core.c
// Description of UartHostCreate() in uart_core.c
struct UartHost *UartHostCreate(struct HdfDeviceObject *device)
{
struct UartHost *host = NULL; // Create a UartHost.
struct UartHost *host = NULL; // Create UartHost.
...
host = (struct UartHost *)OsalMemCalloc(sizeof(*host));// Apply for memory.
host = (struct UartHost *)OsalMemCalloc(sizeof(*host));// Allocate memory.
...
host->device = device; // (Mandatory) Enable conversion between HdfDeviceObject and UartHost.
device->service = &(host->service); // (Mandatory) Enable conversion between HdfDeviceObject and UartHost.
host->device->service->Dispatch = UartIoDispatch;// Assign a value to the Dispatch method of service.
OsalAtomicSet(&host->atom, 0); // Initialize or set atomic data.
host->device = device; // (Mandatory) Prerequisites for conversion between HdfDeviceObject and UartHost
device->service = &(host->service; // (Mandatory) Prerequisites for conversion between HdfDeviceObject and UartHost
host->device->service->Dispatch = UartIoDispatch;// Assign values to Dispatch of service.
OsalAtomicSet(&host->atom, 0); // Initialize or set the atomic services.
host->priv = NULL;
host->method = NULL;
return host;
}
```
- Init function
- **Init** function
Input parameters:
Input parameter:
**HdfDeviceObject**, an interface parameter exposed by the driver, contains the .hcs configuration file information.
**HdfDeviceObject**, an interface parameter exposed by the driver, contains the .hcs information.
Return values:
Return value:
HDF\_STATUS
HDF_STATUS
Function description:
Initializes the custom structure object and **UartHost**, calls the **artAddDev** function at the core layer, and connects to VFS.
Initializes the custom structure object and **UartHost**, calls the **artAddDev** function at the core layer, and connects to the VFS.
```
int32_t HdfUartDeviceInit(struct HdfDeviceObject *device)
......@@ -447,38 +299,38 @@ The following uses **uart\_hi35xx.c** as an example to present the contents th
struct UartHost *host = NULL;
HDF_LOGI("%s: entry", __func__);
...
host = UartHostFromDevice(device);// Forcibly convert to UartHost by using service. The value is assigned in the Bind function.
host = UartHostFromDevice(device);// Forcibly convert to UartHost by using service. The values are assigned by Bind().
...
ret = Hi35xxAttach(host, device); // Initialize the UartHost object.
...
host->method = &g_uartHostMethod; // Connect to the UARTHostMethod instance.
host->method = &g_uartHostMethod; // Hook the UartHostMethod instance.
return ret;
}
// Complete initialization of the UartHost object.
// Initialize UartHost.
static int32_t Hi35xxAttach(struct UartHost *host, struct HdfDeviceObject *device)
{
int32_t ret;
// udd and port are structure objects customized by the vendor. The vendor needs to implement related functions as required.
// udd and port are customized structure objects. Implement the related functions as required.
struct UartDriverData *udd = NULL;
struct UartPl011Port *port = NULL;
...
// Steps [1] to [7] assign values to udd and then to the UartHost object at the core layer.
udd = (struct UartDriverData *)OsalMemCalloc(sizeof(*udd));// [1]
// Steps 1 to 7 instantiate and assign values to the udd object, and then assign values to UartHost.
udd = (struct UartDriverData *)OsalMemCalloc(sizeof(*udd));// Step 1
...
port = (struct UartPl011Port *)OsalMemCalloc(sizeof(struct UartPl011Port));// [2]
port = (struct UartPl011Port *)OsalMemCalloc(sizeof(struct UartPl011Port));// Step 2
...
udd->ops = Pl011GetOps();// [3] Perform operations, such as starting or stopping a device, setting attributes, and sending data.
udd->recv = PL011UartRecvNotify;// [4] Connect to the data receiving notification function (conditional lock mechanism).
udd->count = 0; // [5]
port->udd = udd; // [6] Enable conversion between UartPl011Port and UartDriverData.
ret = UartGetConfigFromHcs(port, device->property);// (Mandatory) Transfer the attributes of HdfDeviceObject to the vendor custom structure.
udd->ops = Pl011GetOps(); // Step 3 Hook the functions for starting or stopping a device, setting attributes, and sending data.
udd->recv = PL011UartRecvNotify;// Step 4 Hook the data receiving notification function (conditional lock mechanism).
udd->count = 0; // Step 5
port->udd = udd; // Step 6 Enable conversion between UartPl011Port and UartDriverData.
ret = UartGetConfigFromHcs(port, device->property);// Pass the attributes of HdfDeviceObject to the custom structure.
// The sample code is as follows:
...
udd->private = port; // [7]
udd->private = port; // Step 7
host->priv = udd; // (Mandatory) Enable conversion between UartHost and UartDriverData.
host->num = udd->num;// (Mandatory) UART device number
UartAddDev(host); // (Mandatory) Function in uart_dev.c at the core layer used to register a character device node with the VFS so that the UART can be accessed in user mode through this virtual file node.
host->num = udd->num; // (Mandatory) UART device number
UartAddDev(host); // (Mandatory) Function (in uart_dev.c) used to register a character device node to the VFS so that the UART can be accessed through the virtual file node in user mode.
return HDF_SUCCESS;
}
......@@ -488,7 +340,7 @@ The following uses **uart\_hi35xx.c** as an example to present the contents th
struct UartDriverData *udd = port->udd;
struct DeviceResourceIface *iface = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE);
...
// Extract the value based on the request parameter and assign the value to the vendor custom structure.
// Extract the values based on the request and assign the values to the custom structure.
if (iface->GetUint32(node, "num", &udd->num, 0) != HDF_SUCCESS) {
HDF_LOGE("%s: read busNum fail", __func__);
return HDF_FAILURE;
......@@ -497,20 +349,20 @@ The following uses **uart\_hi35xx.c** as an example to present the contents th
return 0;
}
```
- **Release** function
- Release function
Input parameters:
Input parameter:
**HdfDeviceObject**, an interface parameter exposed by the driver, contains the .hcs configuration file information.
**HdfDeviceObject**, an interface parameter exposed by the driver, contains the .hcs information.
Return values:
Return value:
No value is returned.
Function description:
Releases the memory and deletes the controller. This function assigns a value to the **Release** API in the driver entry structure. When the HDF fails to call the **Init** function to initialize the driver, the **Release** function can be called to release driver resources. All forced conversion operations for obtaining the corresponding object can be successful only when the **Init** function has the corresponding value assignment operations.
Releases the memory and deletes the controller. This function assigns values to the **Release** API in the driver entry structure. When the HDF fails to call the **Init** function to initialize the driver, the **Release** function can be called to release driver resources. All forced conversion operations for obtaining the corresponding object can be successful only when **Init()** has the corresponding value assignment operations.
```
void HdfUartDeviceRelease(struct HdfDeviceObject *device)
......@@ -520,7 +372,7 @@ The following uses **uart\_hi35xx.c** as an example to present the contents th
host = UartHostFromDevice(device);// Forcibly convert HdfDeviceObject to UartHost by using service. For details about the value assignment, see the Bind function.
...
if (host->priv != NULL) {
Hi35xxDetach(host); // Memory release function customized by the vendor. For details, see the following description.
Hi35xxDetach(host); // Customized memory release function.
}
UartHostDestroy(host); // Call the function of the core layer to release the host.
}
......@@ -536,15 +388,12 @@ The following uses **uart\_hi35xx.c** as an example to present the contents th
port = udd->private;// Convert UartDriverData to UartPl011Port.
if (port != NULL) {
if (port->physBase != 0) {
OsalIoUnmap((void *)port->physBase);// Remove address mapping.
OsalIoUnmap((void *)port->physBase);// Unmap addresses.
}
(void)OsalMemFree(port);
OsalMemFree(port);
udd->private = NULL;
}
(void)OsalMemFree(udd);// Release UartDriverData.
OsalMemFree(udd);//Release UartDriverData.
host->priv = NULL;
}
```
......@@ -115,7 +115,7 @@ Data提供方可以自定义数据的增、删、改、查,以及文件打开
其中,基础依赖包包括:
- @ohos.ability.featureAbility
- @ohos.data.dataability
- @ohos.data.dataAbility
- @ohos.data.rdb
#### DataAbility接口开发指导
......
......@@ -58,7 +58,7 @@ Ability功能如下(Ability类,具体的API详见[接口文档](../reference
```
import AbilityStage from "@ohos.application.AbilityStage"
```
2. 实现AbilityStage接口。
2. 实现AbilityStage接口,接口生成的默认相对路径:entry\src\main\ets\Application\AbilityStage.ts
```ts
export default class MyAbilityStage extends AbilityStage {
onCreate() {
......@@ -70,7 +70,7 @@ Ability功能如下(Ability类,具体的API详见[接口文档](../reference
```js
import Ability from '@ohos.application.Ability'
```
4. 实现Ability生命周期接口。
4. 实现Ability生命周期接口,接口默认生成的相对路径:entry\src\main\ets\MainAbility\MainAbility.ts
`onWindowStageCreate(windowStage)`中通过loadContent接口设置应用要加载的页面,window接口的使用详见[窗口开发指导](../windowmanager/window-guidelines.md)
```ts
......@@ -87,7 +87,7 @@ Ability功能如下(Ability类,具体的API详见[接口文档](../reference
console.log("MainAbility onWindowStageCreate")
windowStage.loadContent("pages/index").then((data) => {
console.log("MainAbility load content succeed with data: " + JSON.stringify(data))
console.log("MainAbility load content succeed")
}).catch((error) => {
console.error("MainAbility load content failed with error: "+ JSON.stringify(error))
})
......@@ -107,7 +107,8 @@ Ability功能如下(Ability类,具体的API详见[接口文档](../reference
}
```
### 获取AbilityStage及Ability的配置信息
AbilityStage类及Ability类均拥有context属性,应用可以通过`this.context`获取Ability实例的上下文,进而获取详细的配置信息。如下示例展示了AbilityStage通过context属性获取包代码路径、hap包名、ability名以及系统语言的方法。具体示例代码如下:
AbilityStage类及Ability类均拥有context属性,应用可以通过`this.context`获取Ability实例的上下文,进而获取详细的配置信息。
如下示例展示了AbilityStage通过context属性获取包代码路径、hap包名、ability名以及系统语言的方法。具体示例代码如下:
```ts
import AbilityStage from "@ohos.application.AbilityStage"
export default class MyAbilityStage extends AbilityStage {
......@@ -140,7 +141,7 @@ export default class MainAbility extends Ability {
console.log("MainAbility ability name" + abilityInfo.name)
let config = this.context.config
console.log("MyAbilityStage config language" + config.language)
console.log("MainAbility config language" + config.language)
}
}
```
......@@ -269,7 +270,7 @@ function getRemoteDeviceId() {
```
向用户申请数据同步'ohos.permission.DISTRIBUTED_DATASYNC'的权限。申请授权示例代码见[应用向用户申请授权](###应用向用户申请授权)
### 指定页面启动Ability
当Ability的启动模式设置为单例时,若Ability已被拉起,再次启动Ability会触发onNewWant回调。应用开发者可以通过want传递启动参数,比如希望指定页面启动Ability,可以通过want中的uri参数或parameters参数传递pages信息。目前,Stage模型中Ability暂时无法直接使用router的能力,可以将启动参数传递给自定义组件,在自定义组件的生命周期中调用router接口显示指定页面。具体示例代码如下:
当Ability的启动模式设置为单例时,若Ability已被拉起,再次启动Ability,不会触发onCreate,只会触发onNewWant回调。应用开发者可以通过want传递启动参数,比如希望指定页面启动Ability,可以通过want中的uri参数或parameters参数传递pages信息。目前,Stage模型中Ability暂时无法直接使用router的能力,可以将启动参数传递给自定义组件,在自定义组件的生命周期中调用router接口显示指定页面。具体示例代码如下:
使用startAbility再次拉起Ability,通过want中的uri参数传递页面信息:
```ts
......@@ -311,7 +312,7 @@ struct Index {
console.info('Index onPageShow')
let newWant = globalThis.newWant
if (newWant.hasOwnProperty("uri")) {
router.push({ uri: newWant.uri });
router.push({ url: newWant.uri });
globalThis.newWant = undefined
}
}
......
......@@ -26,7 +26,7 @@ ExtensionAbility,是Stage模型中新增的扩展组件的基类,一般用
1.创建ServiceExtensionAbility
开发者在创建TS文件中自定义类继承ServiceExtensionAbility,重写基类回调函数,示例如下:
开发者在创建TS文件中自定义类继承ServiceExtensionAbility,重写基类回调函数,接口生成的默认相对路径:entry\src\main\ets\ServiceExtAbility\ServiceExtAbility.ts,示例如下:
```js
import rpc from '@ohos.rpc'
......
......@@ -164,7 +164,7 @@
import data_rdb from '@ohos.data.rdb'
const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)";
const STORE_CONFIG = {name: "rdbstore.db",}
const STORE_CONFIG = {name: "rdbstore.db"}
data_rdb.getRdbStore(STORE_CONFIG, 1, function (err, rdbStore) {
rdbStore.executeSql(CREATE_TABLE_TEST )
console.info('create table done.')
......@@ -179,7 +179,7 @@
```js
var u8 = new Uint8Array([1, 2, 3])
const valueBucket = {"name": "Tom", "age": 18, "salary": 100.5, "blobType": u8,}
const valueBucket = {"name": "Tom", "age": 18, "salary": 100.5, "blobType": u8}
let insertPromise = rdbStore.insert("test", valueBucket)
```
......
......@@ -75,20 +75,22 @@
1. 准备工作,导入@ohos.data.storage以及相关的模块到开发环境。
```js
import dataStorage from '@ohos.data.storage'
import featureAbility from '@ohos.ability.featureAbility' // 用于获取文件存储路径
import dataStorage from '@ohos.data.storage';
import featureAbility from '@ohos.ability.featureAbility'; // 用于获取文件存储路径
```
2. 获取Storage实例。
读取指定文件,将数据加载到Storage实例,用于数据操作。
```js
var context = featureAbility.getContext()
context.getFilesDir().then(() => {
var path;
var context = featureAbility.getContext();
context.getFilesDir().then((filePath) => {
path = filePath;
console.info("======================>getFilesDirPromsie====================>");
});
let promise = dataStorage.getStorage(path + '/mystore')
let promise = dataStorage.getStorage(path + '/mystore');
```
3. 存入数据。
......@@ -97,14 +99,14 @@
```js
promise.then((storage) => {
let getPromise = storage.put('startup', 'auto') // 保存数据到缓存的storage示例中。
let getPromise = storage.put('startup', 'auto'); // 保存数据到缓存的storage示例中。
getPromise.then(() => {
console.info("Put the value of startup successfully.")
console.info("Succeeded in putting the value of startup.");
}).catch((err) => {
console.info("Put the value of startup failed with err: " + err)
console.info("Failed to put the value of startup failed with err: " + err);
})
}).catch((err) => {
console.info("Get the storage failed")
console.info("Failed to get the storage.");
})
```
......@@ -116,12 +118,14 @@
promise.then((storage) => {
let getPromise = storage.get('startup', 'default')
getPromise.then((value) => {
console.info("The value of startup is " + value)
console.info("The value of startup is " + value);
}).catch((err) => {
console.info("Get the value of startup failed with err: " + err)
console.info("Failed to get the value of startup with err: " + err);
})
}).catch((err) => {
console.info("Get the storage failed")})
console.info("Failed to get the storage.")
})
```
5. 数据持久化。
......@@ -139,15 +143,15 @@
```js
promise.then((storage) => {
var observer = function (key) {
console.info("The key of " + key + " changed.")
console.info("The key of " + key + " changed.");
}
storage.on('change', observer)
storage.putSync('startup', 'auto') // 修改storage存储数据
storage.flushSync() // 触发订阅者回调方法
storage.putSync('startup', 'auto'); // 修改storage存储数据
storage.flushSync(); // 触发订阅者回调方法
storage.off('change', observer) // 注销数据变化订阅
storage.off('change', observer); // 注销数据变化订阅
}).catch((err) => {
console.info("Get the storage failed")
console.info("Failed to get the storage.");
})
```
......@@ -156,11 +160,13 @@
使用deleteStorage方法从内存中移除指定文件对应的Storage单实例,并删除指定文件及其备份文件、损坏文件。删除指定文件时,应用不允许再使用该实例进行数据操作,否则会出现数据一致性问题。删除后,数据及文件将不可恢复。
```js
let promise = dataStorage.deleteStorage(path + '/mystore')
let promise = dataStorage.deleteStorage(path + '/mystore');
promise.then(() => {
console.info("Deleted successfully.")
console.info("Succeeded in deleting the storage.");
}).catch((err) => {
console.info("Deleted failed with err: " + err)})
console.info("Failed to delete the storage with err: " + err);
})
```
## 相关实例
针对轻量级数据存储开发,有以下相关实例可供参考:
......
......@@ -34,10 +34,10 @@
1. 获取设备上传感器的数据,需要在“config.json”里面进行配置请求权限。具体如下:
```
”reqPermissions“:[
"reqPermissions":[
{
"name":"ohos.permission.ACCELEROMETER",
"reason"":"",
"reason":"",
"usedScene":{
"ability": ["sensor.index.MainAbility",".MainAbility"],
"when":"inuse"
......@@ -45,7 +45,7 @@
},
{
"name":"ohos.permission.GYROSCOPE",
"reason"":"",
"reason":"",
"usedScene":{
"ability": ["sensor.index.MainAbility",".MainAbility"],
"when":"inuse"
......@@ -53,7 +53,7 @@
},
{
"name":"ohos.permission.ACTIVITY_MOTION",
"reason"":"ACTIVITY_MOTION_TEST",
"reason":"ACTIVITY_MOTION_TEST",
"usedScene":{
"ability": ["sensor.index.MainAbility",".MainAbility"],
"when":"inuse"
......@@ -61,7 +61,7 @@
},
{
"name":"ohos.permission.READ_HEALTH_DATA",
"reason"":"HEALTH_DATA_TEST",
"reason":"HEALTH_DATA_TEST",
"usedScene":{
"ability": ["sensor.index.MainAbility",".MainAbility"],
"when":"inuse"
......
......@@ -595,7 +595,7 @@ connectAbility(want: Want, options: ConnectOptions): number
| 类型 | 说明 |
| -------- | -------- |
| number | 连接Ability的代码 |
| number | 返回Ability连接的结果code。 |
**示例**
```js
......@@ -606,7 +606,7 @@ var want = {
}
var options = {
onConnect: (elementName, remote) => {
console.log('connectAbility onConnect, elementName: ' + elementName + ', remote: ' remote)
console.log('connectAbility onConnect, elementName: ' + elementName + ', remote: ' + remote)
},
onDisconnect: (elementName) => {
console.log('connectAbility onDisconnect, elementName: ' + elementName)
......@@ -615,8 +615,8 @@ var options = {
console.log('connectAbility onFailed, code: ' + code)
}
}
this.context.connectAbility(want, options) {
console.log('code: ' + code)
let result = this.context.connectAbility(want, options) {
console.log('code: ' + result)
}
```
......@@ -652,7 +652,7 @@ var want = {
var accountId = 111;
var options = {
onConnect: (elementName, remote) => {
console.log('connectAbility onConnect, elementName: ' + elementName + ', remote: ' remote)
console.log('connectAbility onConnect, elementName: ' + elementName + ', remote: ' + remote)
},
onDisconnect: (elementName) => {
console.log('connectAbility onDisconnect, elementName: ' + elementName)
......
# 性能打点
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
本模块提供了追踪进程轨迹。
> **说明:**
> - 从API Version 8开始,该接口不再维护,推荐使用新接口[`@ohos.hiTraceMeter`](js-apis-hitracemeter.md)。
> - 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 导入模块
```
```js
import bytrace from '@ohos.bytrace';
```
## bytrace.startTrace
startTrace(name: string, taskId: number, expectedTime?: number): void
标记一个预追踪耗时任务的开始,expectedTime是可选参数,标识该任务的期望耗时。
标记一个时间片跟踪任务的开始。
> **说明:**
> 如果有多个相同name的任务需要追踪或者对同一个任务要追踪多次,并且这些跟踪任务会同时被执行,则每次调用startTrace的taskId必须不一致。如果具有相同name的跟踪任务是串行执行的,则taskId可以相同。在下面bytrace.finishTrace的示例中会举例说明。
**系统能力:** SystemCapability.Developtools.Bytrace
**系统能力:** SystemCapability.HiviewDFX.HiTrace
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| name | string | 是 | 要追踪的任务名称 |
| taskId | number | 是 | 任务id |
| expectedTime | number | 否 | 期望的耗时时间,单位:ms |
| name | string | 是 | 时间片跟踪任务名称 |
| taskId | number | 是 | 时间片跟踪任务id |
| expectedTime | number | 否 | 期望的耗时时间(单位:ms) |
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> 如果有多个相同name的任务需要追踪或者对同一个任务要追踪多次,并且这些会同时被执行,则每次调用startTrace的taskId必须不一致。如果具有相同name的任务是串行执行的,则taskId可以相同。在下面bytrace.finishTrace的示例中会举例说明。
**示例:**
```
```js
bytrace.startTrace("myTestFunc", 1);
bytrace.startTrace("myTestFunc", 1, 5); //从startTrace到finishTrace流程的耗时期望为5ms
bytrace.startTrace("myTestFunc", 1, 5); // 从startTrace到finishTrace流程的期望耗时为5ms
```
## bytrace.finishTrace
finishTrace(name: string, taskId: number): void
标记一个预追踪耗时任务的结束。
标记一个时间片跟踪事件的结束。
> **说明:**<br>
> finishTrace的name和taskId必须与流程开始的startTrace对应参数值一致。
**系统能力:** SystemCapability.Developtools.Bytrace
**系统能力:** SystemCapability.HiviewDFX.HiTrace
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| name | string | 是 | 要追踪的任务名称 |
| taskId | number | 是 | 任务id |
| name | string | 是 | 时间片跟踪任务名称 |
| taskId | number | 是 | 时间片跟踪任务id |
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> finishTrace的name和taskId必须与流程开始的startTrace对应参数值一致。
**示例:**
```
```js
bytrace.finishTrace("myTestFunc", 1);
```
```
//踪并行执行的同名任务
//踪并行执行的同名任务
bytrace.startTrace("myTestFunc", 1);
//业务流程......
bytrace.startTrace("myTestFunc", 2); //第二个追踪的任务开始,同时第一个追踪的同名任务还没结束,出现了并行执行,对应接口的taskId需要不同。
//业务流程......
// 业务流程......
bytrace.startTrace("myTestFunc", 2); // 第二个跟踪任务开始,同时第一个同名跟踪任务还没结束,出现了并行执行,对应接口的taskId需要不同
// 业务流程......
bytrace.finishTrace("myTestFunc", 1);
//业务流程......
// 业务流程......
bytrace.finishTrace("myTestFunc", 2);
```
```
//踪串行执行的同名任务
//踪串行执行的同名任务
bytrace.startTrace("myTestFunc", 1);
//业务流程......
bytrace.finishTrace("myTestFunc", 1); //第一个追踪的任务结束
//业务流程......
bytrace.startTrace("myTestFunc", 1); //第二个追踪的同名任务开始,同名的待追踪任务串行执行。
//业务流程......
// 业务流程......
bytrace.finishTrace("myTestFunc", 1); // 第一个跟踪任务结束
// 业务流程......
bytrace.startTrace("myTestFunc", 1); // 第二个跟踪任务开始,同名跟踪任务串行执行
// 业务流程......
bytrace.finishTrace("myTestFunc", 1);
```
## bytrace.traceByValue
traceByValue(name: string, count: number): void
用来标记一个预追踪的数值变量,该变量的数值会不断变化。
标记预追踪耗时任务的数值变量,该变量的数值会不断变化。
**系统能力:** SystemCapability.Developtools.Bytrace
**系统能力:** SystemCapability.HiviewDFX.HiTrace
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| name | string | 是 | 要追踪的数值变量名称 |
| count | number | 是 | 变量的值 |
| name | string | 是 | 数值变量的名称 |
| count | number | 是 | 数值变量的值 |
**示例:**
```
```js
let traceCount = 3;
bytrace.traceByValue("myTestCount", traceCount);
traceCount = 4;
bytrace.traceByValue("myTestCount", traceCount);
//业务流程......
// 业务流程......
```
......@@ -19,7 +19,7 @@ import data_storage from '@ohos.data.storage';
**系统能力:** 以下各项对应的系统能力均为SystemCapability.DistributedDataManager.Preferences.Core
| 名称 | 参数类型 | 可读 | 可写 | 说明 |
| -------- | -------- | -------- | -------- | -------- |
| ---------------- | -------- | ---- | ---- | ------------------------------------- |
| MAX_KEY_LENGTH | string | 是 | 否 | key的最大长度限制,需小于80字节。 |
| MAX_VALUE_LENGTH | string | 是 | 否 | value的最大长度限制,需小于8192字节。 |
......@@ -33,25 +33,33 @@ getStorageSync(path: string): Storage
**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| path | string | 是 | 应用程序内部数据存储路径。 |
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | -------------------------- |
| path | string | 是 | 应用程序内部数据存储路径。 |
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| [Storage](#storage) | 获取到要操作的Storage实例,用于进行数据存储操作。 |
**示例:**
```js
import data_storage from '@ohos.data.storage'
| 类型 | 说明 |
| ------------------- | ------------------------------------------------- |
| [Storage](#storage) | 获取到要操作的Storage实例,用于进行数据存储操作。 |
let path = '/data/storage/el2/database'
let storage = data_storage.getStorageSync(path + '/mystore')
storage.putSync('startup', 'auto')
storage.flushSync()
**示例:**
```
```js
import featureAbility from '@ohos.ability.featureAbility';
var path;
var context = featureAbility.getContext();
context.getFilesDir().then((filePath) => {
path = filePath;
console.info("======================>getFilesDirPromsie====================>");
});
let storage = data_storage.getStorageSync(path + '/mystore');
storage.putSync('startup', 'auto');
storage.flushSync();
```
## data_storage.getStorage
......@@ -63,25 +71,33 @@ getStorage(path: string, callback: AsyncCallback&lt;Storage&gt;): void
**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| path | string | 是 | 应用程序内部数据存储路径。 |
| callback | AsyncCallback&lt;[Storage](#storage)&gt; | 是 | 回调函数。 |
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------- | ---- | -------------------------- |
| path | string | 是 | 应用程序内部数据存储路径。 |
| callback | AsyncCallback&lt;[Storage](#storage)&gt; | 是 | 回调函数。 |
**示例:**
```js
import data_storage from '@ohos.data.storage'
let path = '/data/storage/el2/database'
data_storage.getStorage(path + '/mystore', function (err, storage) {
```js
import featureAbility from '@ohos.ability.featureAbility';
var path;
var context = featureAbility.getContext();
context.getFilesDir().then((filePath) => {
path = filePath;
console.info("======================>getFilesDirPromsie====================>");
});
data_storage.getStorage(path + '/mystore', function (err, storage) {
if (err) {
console.info("Get the storage failed, path: " + path + '/mystore')
console.info("Failed to get the storage. path: " + path + '/mystore');
return;
}
storage.putSync('startup', 'auto')
storage.flushSync()
})
```
storage.putSync('startup', 'auto');
storage.flushSync();
})
```
## data_storage.getStorage
......@@ -93,29 +109,37 @@ getStorage(path: string): Promise&lt;Storage&gt;
**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| path | string | 是 | 应用程序内部数据存储路径。 |
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | -------------------------- |
| path | string | 是 | 应用程序内部数据存储路径。 |
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| Promise&lt;[Storage](#storage)&gt; | Promise实例,用于异步获取结果。 |
**示例:**
```js
import data_storage from '@ohos.data.storage'
| 类型 | 说明 |
| ---------------------------------- | ------------------------------- |
| Promise&lt;[Storage](#storage)&gt; | Promise实例,用于异步获取结果。 |
let path = '/data/storage/el2/database'
**示例:**
let getPromise = data_storage.getStorage(path + '/mystore')
getPromise.then((storage) => {
storage.putSync('startup', 'auto')
storage.flushSync()
}).catch((err) => {
console.info("Get the storage failed, path: " + path + '/mystore')
})
```
```js
import featureAbility from '@ohos.ability.featureAbility';
var path;
var context = featureAbility.getContext();
context.getFilesDir().then((filePath) => {
path = filePath;
console.info("======================>getFilesDirPromsie====================>");
});
let getPromise = data_storage.getStorage(path + '/mystore');
getPromise.then((storage) => {
storage.putSync('startup', 'auto');
storage.flushSync();
}).catch((err) => {
console.info("Failed to get the storage. path: " + path + '/mystore');
})
```
## data_storage.deleteStorageSync
......@@ -127,15 +151,25 @@ deleteStorageSync(path: string): void
**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| path | string | 是 | 应用程序内部数据存储路径。 |
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | -------------------------- |
| path | string | 是 | 应用程序内部数据存储路径。 |
**示例:**
```js
let path = '/data/storage/el2/database'
data_storage.deleteStorageSync(path + '/mystore')
```
```js
import featureAbility from '@ohos.ability.featureAbility';
var path;
var context = featureAbility.getContext();
context.getFilesDir().then((filePath) => {
path = filePath;
console.info("======================>getFilesDirPromsie====================>");
});
data_storage.deleteStorageSync(path + '/mystore');
```
## data_storage.deleteStorage
......@@ -147,22 +181,32 @@ deleteStorage(path: string, callback: AsyncCallback&lt;void&gt;): void
**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| path | string | 是 | 应用程序内部数据存储路径。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。 |
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------- | ---- | -------------------------- |
| path | string | 是 | 应用程序内部数据存储路径。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。 |
**示例:**
```js
let path = '/data/storage/el2/database'
data_storage.deleteStorage(path + '/mystore', function (err) {
```js
import featureAbility from '@ohos.ability.featureAbility';
var path;
var context = featureAbility.getContext();
context.getFilesDir().then((filePath) => {
path = filePath;
console.info("======================>getFilesDirPromsie====================>");
});
data_storage.deleteStorage(path + '/mystore', function (err) {
if (err) {
console.info("Deleted failed with err: " + err)
return
console.info("Failed to delete the storage with err: " + err);
return;
}
console.info("Deleted successfully.")
})
```
console.info("Succeeded in deleting the storage.");
})
```
## data_storage.deleteStorage
......@@ -174,25 +218,36 @@ deleteStorage(path: string): Promise&lt;void&gt;
**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| path | string | 是 | 应用程序内部数据存储路径。 |
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | -------------------------- |
| path | string | 是 | 应用程序内部数据存储路径。 |
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| Promise&lt;void&gt; | Promise实例,用于异步获取结果。 |
| 类型 | 说明 |
| ------------------- | ------------------------------- |
| Promise&lt;void&gt; | Promise实例,用于异步获取结果。 |
**示例:**
```js
let path = '/data/storage/el2/database'
let promisedelSt = data_storage.deleteStorage(path + '/mystore')
promisedelSt.then(() => {
console.info("Deleted successfully.")
}).catch((err) => {
console.info("Deleted failed with err: " + err)
})
```
```js
import featureAbility from '@ohos.ability.featureAbility';
var path;
var context = featureAbility.getContext();
context.getFilesDir().then((filePath) => {
path = filePath;
console.info("======================>getFilesDirPromsie====================>");
});
let promisedelSt = data_storage.deleteStorage(path + '/mystore');
promisedelSt.then(() => {
console.info("Succeeded in deleting the storage.");
}).catch((err) => {
console.info("Failed to delete the storage with err: " + err);
})
```
## data_storage.removeStorageFromCacheSync
......@@ -204,15 +259,24 @@ removeStorageFromCacheSync(path: string): void
**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| path | string | 是 | 应用程序内部数据存储路径。 |
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | -------------------------- |
| path | string | 是 | 应用程序内部数据存储路径。 |
**示例:**
```js
let path = '/data/storage/el2/database'
data_storage.removeStorageFromCacheSync(path + '/mystore')
```
```js
import featureAbility from '@ohos.ability.featureAbility';
var path;
var context = featureAbility.getContext();
context.getFilesDir().then((filePath) => {
path = filePath;
console.info("======================>getFilesDirPromsie====================>");
});
data_storage.removeStorageFromCacheSync(path + '/mystore');
```
## data_storage.removeStorageFromCache
......@@ -224,22 +288,32 @@ removeStorageFromCache(path: string, callback: AsyncCallback&lt;void&gt;): void
**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| path | string | 是 | 应用程序内部数据存储路径。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。 |
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------- | ---- | -------------------------- |
| path | string | 是 | 应用程序内部数据存储路径。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。 |
**示例:**
```js
let path = '/data/storage/el2/database'
data_storage.removeStorageFromCache(path + '/mystore', function (err) {
```js
import featureAbility from '@ohos.ability.featureAbility';
var path;
var context = featureAbility.getContext();
context.getFilesDir().then((filePath) => {
path = filePath;
console.info("======================>getFilesDirPromsie====================>");
});
data_storage.removeStorageFromCache(path + '/mystore', function (err) {
if (err) {
console.info("Removed storage from cache failed with err: " + err)
return
console.info("Failed to remove storage from cache with err: " + err);
return;
}
console.info("Removed storage from cache successfully.")
})
```
console.info("Succeeded in removing storage from cache.");
})
```
## data_storage.removeStorageFromCache
......@@ -251,25 +325,36 @@ removeStorageFromCache(path: string): Promise&lt;void&gt;
**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| path | string | 是 | 应用程序内部数据存储路径。 |
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | -------------------------- |
| path | string | 是 | 应用程序内部数据存储路径。 |
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| Promise&lt;void&gt; | Promise实例,用于异步获取结果。 |
| 类型 | 说明 |
| ------------------- | ------------------------------- |
| Promise&lt;void&gt; | Promise实例,用于异步获取结果。 |
**示例:**
```js
let path = '/data/storage/el2/database'
let promiserevSt = data_storage.removeStorageFromCache(path + '/mystore')
promiserevSt.then(() => {
console.info("Removed storage from cache successfully.")
}).catch((err) => {
console.info("Removed storage from cache failed with err: " + err)
})
```
```js
import featureAbility from '@ohos.ability.featureAbility';
var path;
var context = featureAbility.getContext();
context.getFilesDir().then((filePath) => {
path = filePath;
console.info("======================>getFilesDirPromsie====================>");
});
let promiserevSt = data_storage.removeStorageFromCache(path + '/mystore')
promiserevSt.then(() => {
console.info("Succeeded in removing storage from cache.");
}).catch((err) => {
console.info("Failed to remove storage from cache with err: " + err);
})
```
## Storage
......@@ -286,21 +371,24 @@ getSync(key: string, defValue: ValueType): ValueType
**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| key | string | 是 | 要获取的存储key名称,不能为空。 |
| defValue | [ValueType](#valuetype) | 是 | 给定key的存储不存在,则要返回的默认值。支持number、string、boolean。 |
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------- | ---- | ------------------------------------------------------------ |
| key | string | 是 | 要获取的存储key名称,不能为空。 |
| defValue | [ValueType](#valuetype) | 是 | 给定key的存储不存在,则要返回的默认值。支持number、string、boolean。 |
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| ValueType | 键对应的值,如果值为null或者非默认值类型,返回默认数据。 |
| 类型 | 说明 |
| --------- | -------------------------------------------------------- |
| ValueType | 键对应的值,如果值为null或者非默认值类型,返回默认数据。 |
**示例:**
```js
let value = storage.getSync('startup', 'default')
console.info("The value of startup is " + value)
```
```js
let value = storage.getSync('startup', 'default');
console.info("The value of startup is " + value);
```
### get
......@@ -312,22 +400,24 @@ get(key: string, defValue: ValueType, callback: AsyncCallback&lt;ValueType&gt;):
**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| key | string | 是 | 要获取的存储key名称,不能为空。 |
| defValue | [ValueType](#valuetype) | 是 | 默认返回值。支持number、string、boolean。 |
| callback | AsyncCallback&lt;ValueType&gt; | 是 | 回调函数。 |
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------ | ---- | ----------------------------------------- |
| key | string | 是 | 要获取的存储key名称,不能为空。 |
| defValue | [ValueType](#valuetype) | 是 | 默认返回值。支持number、string、boolean。 |
| callback | AsyncCallback&lt;ValueType&gt; | 是 | 回调函数。 |
**示例:**
```js
storage.get('startup', 'default', function(err, value) {
```js
storage.get('startup', 'default', function(err, value) {
if (err) {
console.info("Get the value of startup failed with err: " + err)
return
console.info("Failed to get the value of startup with err: " + err);
return;
}
console.info("The value of startup is " + value)
})
```
console.info("The value of startup is " + value);
})
```
### get
......@@ -341,24 +431,26 @@ get(key: string, defValue: ValueType): Promise&lt;ValueType&gt;
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| -------- | ----------------------- | ---- | ----------------------------------------- |
| key | string | 是 | 要获取的存储key名称,不能为空。 |
| defValue | [ValueType](#valuetype) | 是 | 默认返回值。支持number、string、boolean。 |
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| Promise&lt;ValueType&gt; | Promise实例,用于异步获取结果。 |
| 类型 | 说明 |
| ------------------------ | ------------------------------- |
| Promise&lt;ValueType&gt; | Promise实例,用于异步获取结果。 |
**示例:**
```js
let promiseget = storage.get('startup', 'default')
promiseget.then((value) => {
```js
let promiseget = storage.get('startup', 'default');
promiseget.then((value) => {
console.info("The value of startup is " + value)
}).catch((err) => {
console.info("Get the value of startup failed with err: " + err)
})
```
}).catch((err) => {
console.info("Failed to get the value of startup with err: " + err);
})
```
### putSync
......@@ -370,15 +462,17 @@ putSync(key: string, value: ValueType): void
**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| key | string | 是 | 要修改的存储的key,不能为空。 |
| value | [ValueType](#valuetype) | 是 | 存储的新值。支持number、string、boolean。 |
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ----------------------- | ---- | ----------------------------------------- |
| key | string | 是 | 要修改的存储的key,不能为空。 |
| value | [ValueType](#valuetype) | 是 | 存储的新值。支持number、string、boolean。 |
**示例:**
```js
storage.putSync('startup', 'auto')
```
```js
storage.putSync('startup', 'auto');
```
### put
......@@ -390,22 +484,24 @@ put(key: string, value: ValueType, callback: AsyncCallback&lt;void&gt;): void
**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| key | string | 是 | 要修改的存储的key,不能为空。 |
| value | [ValueType](#valuetype) | 是 | 存储的新值。支持number、string、boolean。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。 |
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------- | ---- | ----------------------------------------- |
| key | string | 是 | 要修改的存储的key,不能为空。 |
| value | [ValueType](#valuetype) | 是 | 存储的新值。支持number、string、boolean。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。 |
**示例:**
```js
storage.put('startup', 'auto', function (err) {
```js
storage.put('startup', 'auto', function (err) {
if (err) {
console.info("Put the value of startup failed with err: " + err)
return
console.info("Failed to put the value of startup with err: " + err);
return;
}
console.info("Put the value of startup successfully.")
})
```
console.info("Succeeded in putting the value of startup.");
})
```
### put
......@@ -417,25 +513,28 @@ put(key: string, value: ValueType): Promise&lt;void&gt;
**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| key | string | 是 | 要修改的存储的key,不能为空。 |
| value | [ValueType](#valuetype) | 是 | 存储的新值。支持number、string、boolean。 |
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ----------------------- | ---- | ----------------------------------------- |
| key | string | 是 | 要修改的存储的key,不能为空。 |
| value | [ValueType](#valuetype) | 是 | 存储的新值。支持number、string、boolean。 |
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| Promise&lt;void&gt; | Promise实例,用于异步处理。 |
| 类型 | 说明 |
| ------------------- | --------------------------- |
| Promise&lt;void&gt; | Promise实例,用于异步处理。 |
**示例:**
```js
let promiseput = storage.put('startup', 'auto')
promiseput.then(() => {
console.info("Put the value of startup successfully.")
}).catch((err) => {
console.info("Put the value of startup failed with err: " + err)
})
```
```js
let promiseput = storage.put('startup', 'auto');
promiseput.then(() => {
console.info("Succeeded in putting the value of startup.");
}).catch((err) => {
console.info("Failed to put the value of startup with err: " + err);
})
```
### hasSync
......@@ -447,22 +546,25 @@ hasSync(key: string): boolean
**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| key | string | 是 | 要获取的存储key名称,不能为空。 |
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | ------------------------------- |
| key | string | 是 | 要获取的存储key名称,不能为空。 |
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| boolean | true&nbsp;表示存在,false表示不存在。 |
| 类型 | 说明 |
| ------- | ------------------------------------- |
| boolean | true&nbsp;表示存在,false表示不存在。 |
**示例:**
```js
let isExist = storage.hasSync('startup')
if (isExist) {
console.info("The key of startup is contained.")
}
```
```js
let isExist = storage.hasSync('startup');
if (isExist) {
console.info("The key of startup is contained.");
}
```
### has
......@@ -474,28 +576,31 @@ has(key: string, callback: AsyncCallback&lt;boolean&gt;): boolean
**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| key | string | 是 | 要获取的存储key名称,不能为空。 |
| callback | AsyncCallback&lt;boolean&gt; | 是 | 回调函数。 |
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------- | ---- | ------------------------------- |
| key | string | 是 | 要获取的存储key名称,不能为空。 |
| callback | AsyncCallback&lt;boolean&gt; | 是 | 回调函数。 |
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| boolean | true表示存在,false表示不存在。 |
| 类型 | 说明 |
| ------- | ------------------------------- |
| boolean | true表示存在,false表示不存在。 |
**示例:**
```js
storage.has('startup', function (err, isExist) {
```js
storage.has('startup', function (err, isExist) {
if (err) {
console.info("Check the key of startup failed with err: " + err)
return
console.info("Failed to check the key of startup with err: " + err);
return;
}
if (isExist) {
console.info("The key of startup is contained.")
console.info("The key of startup is contained.");
}
})
```
})
```
### has
......@@ -507,26 +612,29 @@ has(key: string): Promise&lt;boolean&gt;
**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| key | string | 是 | 要获取的存储key名称,不能为空。 |
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | ------------------------------- |
| key | string | 是 | 要获取的存储key名称,不能为空。 |
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| Promise&lt;boolean&gt; | Promise实例,用于异步处理。 |
| 类型 | 说明 |
| ---------------------- | --------------------------- |
| Promise&lt;boolean&gt; | Promise实例,用于异步处理。 |
**示例:**
```js
let promisehas = storage.has('startup')
promisehas.then((isExist) => {
```js
let promisehas = storage.has('startup')
promisehas.then((isExist) => {
if (isExist) {
console.info("The key of startup is contained.")
console.info("The key of startup is contained.");
}
}).catch((err) => {
console.info("Check the key of startup failed with err: " + err)
})
```
}).catch((err) => {
console.info("Failed to check the key of startup with err: " + err);
})
```
### deleteSync
......@@ -538,14 +646,16 @@ deleteSync(key: string): void
**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| key | string | 是 | 要获取的存储key名称。它不能为空。 |
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | --------------------------------- |
| key | string | 是 | 要获取的存储key名称。它不能为空。 |
**示例:**
```js
storage.deleteSync('startup')
```
```js
storage.deleteSync('startup');
```
### delete
......@@ -557,21 +667,23 @@ delete(key: string, callback: AsyncCallback&lt;void&gt;): void
**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| key | string | 是 | 要获取的存储key名称,不能为空。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。 |
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------- | ---- | ------------------------------- |
| key | string | 是 | 要获取的存储key名称,不能为空。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。 |
**示例:**
```js
storage.delete('startup', function (err) {
```js
storage.delete('startup', function (err) {
if (err) {
console.info("Delete startup key failed with err: " + err)
return
console.info("Failed to delete startup key failed err: " + err);
return;
}
console.info("Deleted startup key successfully.")
})
```
console.info("Succeeded in deleting startup key.");
})
```
### delete
......@@ -583,24 +695,27 @@ delete(key: string): Promise&lt;void&gt;
**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| key | string | 是 | 要获取的存储key名称。 |
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | --------------------- |
| key | string | 是 | 要获取的存储key名称。 |
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| Promise&lt;void&gt; | Promise实例,用于异步处理。 |
| 类型 | 说明 |
| ------------------- | --------------------------- |
| Promise&lt;void&gt; | Promise实例,用于异步处理。 |
**示例:**
```js
let promisedel = storage.delete('startup')
promisedel.then(() => {
console.info("Deleted startup key successfully.")
}).catch((err) => {
console.info("Delete startup key failed with err: " + err)
})
```
```js
let promisedel = storage.delete('startup')
promisedel.then(() => {
console.info("Succeeded in deleting startup key.");
}).catch((err) => {
console.info("Failed to delete startup key failed err: " + err);
})
```
### flushSync
......@@ -612,9 +727,10 @@ flushSync(): void
**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core
**示例:**
```js
storage.flushSync()
```
```js
storage.flushSync();
```
### flush
......@@ -626,20 +742,22 @@ flush(callback: AsyncCallback&lt;void&gt;): void
**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。 |
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------- | ---- | ---------- |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。 |
**示例:**
```js
storage.flush(function (err) {
```js
storage.flush(function (err) {
if (err) {
console.info("Flush to file failed with err: " + err)
return
console.info("Failed to flush to file with err: " + err);
return;
}
console.info("Flushed to file successfully.")
})
```
console.info("Succeeded in flushing to file.");
})
```
### flush
......@@ -651,19 +769,21 @@ flush(): Promise&lt;void&gt;
**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| Promise&lt;void&gt; | Promise实例,用于异步处理。 |
| 类型 | 说明 |
| ------------------- | --------------------------- |
| Promise&lt;void&gt; | Promise实例,用于异步处理。 |
**示例:**
```js
let promiseflush = storage.flush()
promiseflush.then(() => {
console.info("Flushed to file successfully.")
}).catch((err) => {
console.info("Flush to file failed with err: " + err)
})
```
```js
let promiseflush = storage.flush();
promiseflush.then(() => {
console.info("Succeeded in flushing to file.");
}).catch((err) => {
console.info("Failed to flush to file with err: " + err);
})
```
### clearSync
......@@ -675,9 +795,10 @@ clearSync(): void
**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core
**示例:**
```js
storage.clearSync()
```
```js
storage.clearSync();
```
### clear
......@@ -689,20 +810,22 @@ clear(callback: AsyncCallback&lt;void&gt;): void
**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。 |
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------- | ---- | ---------- |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。 |
**示例:**
```js
storage.clear(function (err) {
```js
storage.clear(function (err) {
if (err) {
console.info("Clear to file failed with err: " + err)
return
console.info("Failed to clear the storage with err: " + err);
return;
}
console.info("Cleared to file successfully.")
})
```
console.info("Succeeded in clearing the storage.");
})
```
### clear
......@@ -714,19 +837,20 @@ clear(): Promise&lt;void&gt;
**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| Promise&lt;void&gt; | Promise实例,用于异步处理。 |
| 类型 | 说明 |
| ------------------- | --------------------------- |
| Promise&lt;void&gt; | Promise实例,用于异步处理。 |
**示例:**
```js
let promiseclear = storage.clear()
promiseclear.then(() => {
console.info("Cleared to file successfully.")
}).catch((err) => {
console.info("Clear to file failed with err: " + err)
})
```
```js
let promiseclear = storage.clear();
promiseclear.then(() => {
console.info("Succeeded in clearing the storage.");
}).catch((err) => {
console.info("Failed to clear the storage with err: " + err);
})
```
### on('change')
......@@ -738,20 +862,22 @@ on(type: 'change', callback: Callback&lt;StorageObserver&gt;): void
**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core
**参数:**
| 参数名 | 类型 | 说明 |
| -------- | -------- | -------- |
| type | string | 事件类型,固定值'change',表示数据变更。 |
| callback | Callback&lt;[StorageObserver](#storageobserver)&gt; | 回调对象实例。 |
| 参数名 | 类型 | 说明 |
| -------- | --------------------------------------------------- | ---------------------------------------- |
| type | string | 事件类型,固定值'change',表示数据变更。 |
| callback | Callback&lt;[StorageObserver](#storageobserver)&gt; | 回调对象实例。 |
**示例:**
```js
var observer = function (key) {
console.info("The key of " + key + " changed.")
}
storage.on('change', observer)
storage.putSync('startup', 'auto')
storage.flushSync() // observer will be called.
```
```js
var observer = function (key) {
console.info("The key of " + key + " changed.");
}
storage.on('change', observer);
storage.putSync('startup', 'auto');
storage.flushSync(); // observer will be called.
```
### off('change')
......@@ -763,26 +889,28 @@ off(type: 'change', callback: Callback&lt;StorageObserver&gt;): void
**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core
**参数:**
| 参数名 | 类型 | 说明 |
| -------- | -------- | -------- |
| type | string | 事件类型,固定值'change',表示数据变更。 |
| callback | Callback&lt;[StorageObserver](#storageobserver)&gt; | 需要取消的回调对象实例。 |
| 参数名 | 类型 | 说明 |
| -------- | --------------------------------------------------- | ---------------------------------------- |
| type | string | 事件类型,固定值'change',表示数据变更。 |
| callback | Callback&lt;[StorageObserver](#storageobserver)&gt; | 需要取消的回调对象实例。 |
**示例:**
```js
var observer = function (key) {
console.info("The key of " + key + " changed.")
}
storage.off('change', observer)
```
```js
var observer = function (key) {
console.info("The key of " + key + " changed.");
}
storage.off('change', observer);
```
## StorageObserver
**系统能力:** 以下各项对应的系统能力均为SystemCapability.DistributedDataManager.Preferences.Core
**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core
| 名称 | 参数类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| ---- | -------- | ---- | ---------------- |
| key | string | 否 | 变更的数据内容。 |
## ValueType
......
......@@ -23,7 +23,7 @@ isLoggable(domain: number, tag: string, level: LogLevel) : boolean
| 参数名 | 类型 | 必填 | 说明 |
| ------ | --------------------- | ---- | ------------------------------------------------------------ |
| domain | number | 是 | 日志对应的领域标识,范围是0x0~0xFFFF,开发者可根据需要自定义。 |
| domain | number | 是 | 日志对应的领域标识,范围是0x0~0xFFFF<br/>建议开发者在应用内根据需要自定义划分。 |
| tag | string | 是 | 指定日志标识,可以为任意字符串,建议用于标识调用所在的类或者业务行为。 |
| level | [LogLevel](#loglevel) | 是 | 日志级别。 |
......@@ -67,7 +67,7 @@ DEBUG级别的日志在正式发布版本中默认不被打印,只有在调试
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | ------------------------------------------------------------ |
| domain | number | 是 | 日志对应的领域标识,范围是0x0~0xFFFF,开发者可根据需要自定义。 |
| domain | number | 是 | 日志对应的领域标识,范围是0x0~0xFFFF<br/>建议开发者在应用内根据需要自定义划分。 |
| tag | string | 是 | 指定日志标识,可以为任意字符串,建议用于标识调用所在的类或者业务行为。 |
| format | string | 是 | 格式字符串,用于日志的格式化输出。格式字符串中可以设置多个参数,参数需要包含参数类型、隐私标识。<br>隐私标识分为{public}和{private},缺省为{private}。标识{public}的内容明文输出,标识{private}的内容以\<private>过滤回显。 |
| args | any[] | 是 | 与格式字符串format对应的可变长度参数列表。参数数目、参数类型必须与格式字符串中的标识一一对应。 |
......@@ -82,7 +82,7 @@ hilog.debug(0x0001, "testTag", "%{public}s World %{private}d", "hello", 3);
字符串`"hello"`填入`%{public}s`,整型数`3`填入`%{private}d`,输出日志:
```
```txt
08-05 12:21:47.579 2695-2703/com.example.myapplication D 00001/testTag: hello World <private>
```
......@@ -98,7 +98,7 @@ info(domain: number, tag: string, format: string, ...args: any[]) : void
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | ------------------------------------------------------------ |
| domain | number | 是 | 日志对应的领域标识,范围是0x0~0xFFFF,开发者可根据需要自定义。 |
| domain | number | 是 | 日志对应的领域标识,范围是0x0~0xFFFF<br/>建议开发者在应用内根据需要自定义划分。 |
| tag | string | 是 | 指定日志标识,可以为任意字符串,建议用于标识调用所在的类或者业务行为。 |
| format | string | 是 | 格式字符串,用于日志的格式化输出。格式字符串中可以设置多个参数,参数需要包含参数类型、隐私标识。<br/>隐私标识分为{public}和{private},缺省为{private}。标识{public}的内容明文输出,标识{private}的内容以\<private>过滤回显。 |
| args | any[] | 是 | 与格式字符串format对应的可变长度参数列表。参数数目、参数类型必须与格式字符串中的标识一一对应。 |
......@@ -113,7 +113,7 @@ hilog.info(0x0001, "testTag", "%{public}s World %{private}d", "hello", 3);
字符串`"hello"`填入`%{public}s`,整型数`3`填入`%{private}d`,输出日志:
```
```txt
08-05 12:21:47.579 2695-2703/com.example.myapplication I 00001/testTag: hello World <private>
```
......@@ -129,7 +129,7 @@ warn(domain: number, tag: string, format: string, ...args: any[]) : void
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | ------------------------------------------------------------ |
| domain | number | 是 | 日志对应的领域标识,范围是0x0~0xFFFF,开发者可根据需要自定义。 |
| domain | number | 是 | 日志对应的领域标识,范围是0x0~0xFFFF<br/>建议开发者在应用内根据需要自定义划分。 |
| tag | string | 是 | 指定日志标识,可以为任意字符串,建议用于标识调用所在的类或者业务行为。 |
| format | string | 是 | 格式字符串,用于日志的格式化输出。格式字符串中可以设置多个参数,参数需要包含参数类型、隐私标识。<br/>隐私标识分为{public}和{private},缺省为{private}。标识{public}的内容明文输出,标识{private}的内容以\<private>过滤回显。 |
| args | any[] | 是 | 与格式字符串format对应的可变长度参数列表。参数数目、参数类型必须与格式字符串中的标识一一对应。 |
......@@ -144,7 +144,7 @@ hilog.warn(0x0001, "testTag", "%{public}s World %{private}d", "hello", 3);
字符串`"hello"`填入`%{public}s`,整型数`3`填入`%{private}d`,输出日志:
```
```txt
08-05 12:21:47.579 2695-2703/com.example.myapplication W 00001/testTag: hello World <private>
```
......@@ -160,7 +160,7 @@ error(domain: number, tag: string, format: string, ...args: any[]) : void
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | ------------------------------------------------------------ |
| domain | number | 是 | 日志对应的领域标识,范围是0x0~0xFFFF,开发者可根据需要自定义。 |
| domain | number | 是 | 日志对应的领域标识,范围是0x0~0xFFFF<br/>建议开发者在应用内根据需要自定义划分。 |
| tag | string | 是 | 指定日志标识,可以为任意字符串,建议用于标识调用所在的类或者业务行为。 |
| format | string | 是 | 格式字符串,用于日志的格式化输出。格式字符串中可以设置多个参数,参数需要包含参数类型、隐私标识。<br/>隐私标识分为{public}和{private},缺省为{private}。标识{public}的内容明文输出,标识{private}的内容以\<private>过滤回显。 |
| args | any[] | 是 | 与格式字符串format对应的可变长度参数列表。参数数目、参数类型必须与格式字符串中的标识一一对应。 |
......@@ -175,7 +175,7 @@ hilog.error(0x0001, "testTag", "%{public}s World %{private}d", "hello", 3);
字符串`"hello"`填入`%{public}s`,整型数`3`填入`%{private}d`,输出日志:
```
```txt
08-05 12:21:47.579 2695-2703/com.example.myapplication E 00001/testTag: hello World <private>
```
......@@ -191,7 +191,7 @@ fatal(domain: number, tag: string, format: string, ...args: any[]) : void
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | ------------------------------------------------------------ |
| domain | number | 是 | 日志对应的领域标识,范围是0x0~0xFFFF,开发者可根据需要自定义。 |
| domain | number | 是 | 日志对应的领域标识,范围是0x0~0xFFFF<br/>建议开发者在应用内根据需要自定义划分。 |
| tag | string | 是 | 指定日志标识,可以为任意字符串,建议用于标识调用所在的类或者业务行为。 |
| format | string | 是 | 格式字符串,用于日志的格式化输出。格式字符串中可以设置多个参数,参数需要包含参数类型、隐私标识。<br/>隐私标识分为{public}和{private},缺省为{private}。标识{public}的内容明文输出,标识{private}的内容以\<private>过滤回显。 |
| args | any[] | 是 | 与格式字符串format对应的可变长度参数列表。参数数目、参数类型必须与格式字符串中的标识一一对应。 |
......@@ -206,6 +206,6 @@ hilog.fatal(0x0001, "testTag", "%{public}s World %{private}d", "hello", 3);
字符串`"hello"`填入`%{public}s`,整型数`3`填入`%{private}d`,输出日志:
```
```txt
08-05 12:21:47.579 2695-2703/com.example.myapplication F 00001/testTag: hello World <private>
```
\ No newline at end of file
......@@ -115,7 +115,7 @@ back(options?: RouterOptions ): void
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| options | [RouterOptions](#routeroptions) | 是 | 返回页面描述信息,其中参数url指路由跳转时会返回到指定url的界面,如果页面栈上没有url页面,则不响应该情况。如果url未设置,则返回上一页。 |
| options | [RouterOptions](#routeroptions) | 是 | 返回页面描述信息,其中参数url指路由跳转时会返回到指定url的界面,如果页面栈上没有url页面,则不响应该情况。如果url未设置,则返回上一页,页面栈里面的page不会回收,出栈后会回收。 |
**示例:**
```js
......
......@@ -1124,13 +1124,14 @@ setSystemBarEnable(names: Array<'status' | 'navigation'>, callback: AsyncCallbac
**示例:**
```js
var names = ["status", "navigation"];
// 此处以不显示导航栏、状态栏为例
var names = [];
windowClass.setSystemBarEnable(names, (err, data) => {
if (err.code) {
console.error('Failed to set the system bar to be visible. Cause:' + JSON.stringify(err));
console.error('Failed to set the system bar to be invisible. Cause:' + JSON.stringify(err));
return;
}
console.info('Succeeded in setting the system bar to be visible. Data: ' + JSON.stringify(data));
console.info('Succeeded in setting the system bar to be invisible. Data: ' + JSON.stringify(data));
});
```
......@@ -1157,12 +1158,13 @@ setSystemBarEnable(names: Array<'status' | 'navigation'>): Promise&lt;void&gt;
**示例:**
```js
var names = ["status", "navigation"];
// 此处以不显示导航栏、状态栏为例
var names = [];
let promise = windowClass.setSystemBarEnable(names);
promise.then((data)=> {
console.info('Succeeded in setting the system bar to be visible. Data: ' + JSON.stringify(data));
console.info('Succeeded in setting the system bar to be invisible. Data: ' + JSON.stringify(data));
}).catch((err)=>{
console.error('Failed to set the system bar to be visible. Cause:' + JSON.stringify(err));
console.error('Failed to set the system bar to be invisible. Cause:' + JSON.stringify(err));
});
```
......
......@@ -14,8 +14,8 @@
| onLayoutReady | Function | 自定义组件布局完成 | 自定义组件插入Page组件树后,将会对自定义组件进行布局计算,调整其内容元素尺寸与位置,当布局计算结束后触发该回调。 |
| onDetached | Function | 自定义组件摘除 | 自定义组件摘除时,触发该回调,常用于停止动画或异步逻辑停止执行的场景。 |
| onDestroy | Function | 自定义组件销毁 | 自定义组件销毁时,触发该回调,常用于资源释放。 |
| onPageShow | Function | 自定义组件Page显示 | 自定义组件所在Page显示后,触发该回调。 |
| onPageHide | Function | 自定义组件Page隐藏 | 自定义组件所在Page隐藏后,触发该回调。 |
| onShow | Function | 自定义组件Page显示 | 自定义组件所在Page显示后,触发该回调。 |
| onHide | Function | 自定义组件Page隐藏 | 自定义组件所在Page隐藏后,触发该回调。 |
## 示例
......@@ -42,10 +42,10 @@ export default {
onDetached() {
this.value = ""
},
onPageShow() {
onShow() {
console.log("Page显示")
},
onPageHide() {
onHide() {
console.log("Page隐藏")
}
}
......
......@@ -10,28 +10,10 @@
| 名称 | 参数类型 | 默认值 | 描述 |
| ---------- | ---------------------------------------- | --------------- | ----------------------- |
| duration | number | 1000 | 单位为毫秒,默认动画时长为1000毫秒。 |
| curve | Curve | Curve.Linear | 默认曲线为线性。 |
| curve | [Curve](ts-appendix-enums.md#curve) | Curve.Linear | 默认曲线为线性。 |
| delay | number | 0 | 单位为毫秒,默认不延时播放。 |
| iterations | number | 1 | 默认播放一次,设置为-1时表示无限次播放。 |
| playMode | [PlayMode](ts-appendix-enums.md#playmode枚举值说明) | PlayMode.Normal | 设置动画播放模式,默认播放完成后重头开始播放。 |
## Curve枚举说明
| 名称 | 描述 |
| ------------------- | ---------------------------------------- |
| Linear | 表示动画从头到尾的速度都是相同的。 |
| Ease | 表示动画以低速开始,然后加快,在结束前变慢,CubicBezier(0.25,&nbsp;0.1,&nbsp;0.25,&nbsp;1.0)。 |
| EaseIn | 表示动画以低速开始,CubicBezier(0.42,&nbsp;0.0,&nbsp;1.0,&nbsp;1.0)。 |
| EaseOut | 表示动画以低速结束,CubicBezier(0.0,&nbsp;0.0,&nbsp;0.58,&nbsp;1.0)。 |
| EaseInOut | 表示动画以低速开始和结束,CubicBezier(0.42,&nbsp;0.0,&nbsp;0.58,&nbsp;1.0)。 |
| FastOutSlowIn | 标准曲线,cubic-bezier(0.4,&nbsp;0.0,&nbsp;0.2,&nbsp;1.0)。 |
| LinearOutSlowIn | 减速曲线,cubic-bezier(0.0,&nbsp;0.0,&nbsp;0.2,&nbsp;1.0)。 |
| FastOutLinearIn | 加速曲线,cubic-bezier(0.4,&nbsp;0.0,&nbsp;1.0,&nbsp;1.0)。 |
| ExtremeDeceleration | 急缓曲线,cubic-bezier(0.0,&nbsp;0.0,&nbsp;0.0,&nbsp;1.0)。 |
| Sharp | 锐利曲线,cubic-bezier(0.33,&nbsp;0.0,&nbsp;0.67,&nbsp;1.0)。 |
| Rhythm | 节奏曲线,cubic-bezier(0.7,&nbsp;0.0,&nbsp;0.2,&nbsp;1.0)。 |
| Smooth | 平滑曲线,cubic-bezier(0.4,&nbsp;0.0,&nbsp;0.4,&nbsp;1.0)。 |
| Friction | 阻尼曲线,CubicBezier(0.2,&nbsp;0.0,&nbsp;0.2,&nbsp;1.0)。 |
| playMode | [PlayMode](ts-appendix-enums.md#playmode) | PlayMode.Normal | 设置动画播放模式,默认播放完成后重头开始播放。 |
## 示例
......
# 文档中涉及到的内置枚举值
## Alignment枚举说明
## Color
| 颜色名称 | 颜色值 | 颜色示意 |
| ------------------------ | -------- | ------------------------------------------------------------ |
| Black | 0x000000 | ![zh-cn_image_0000001219864153](figures/zh-cn_image_0000001219864153.png) |
| Blue | 0x0000ff | ![zh-cn_image_0000001174104404](figures/zh-cn_image_0000001174104404.png) |
| Brown | 0xa52a2a | ![zh-cn_image_0000001219744201](figures/zh-cn_image_0000001219744201.png) |
| Gray | 0x808080 | ![zh-cn_image_0000001174264376](figures/zh-cn_image_0000001174264376.png) |
| Green | 0x008000 | ![zh-cn_image_0000001174422914](figures/zh-cn_image_0000001174422914.png) |
| Orange | 0xffa500 | ![zh-cn_image_0000001219662661](figures/zh-cn_image_0000001219662661.png) |
| Pink | 0xffc0cb | ![zh-cn_image_0000001219662663](figures/zh-cn_image_0000001219662663.png) |
| Red | 0xff0000 | ![zh-cn_image_0000001219662665](figures/zh-cn_image_0000001219662665.png) |
| White | 0xffffff | ![zh-cn_image_0000001174582866](figures/zh-cn_image_0000001174582866.png) |
| Yellow | 0xffff00 | ![zh-cn_image_0000001174582864](figures/zh-cn_image_0000001174582864.png) |
## ImageFit
| 名称 | 描述 |
| --------- | ------------------------------------------------------------ |
| Contain | 保持宽高比进行缩小或者放大,使得图片完全显示在显示边界内。 |
| Cover | 保持宽高比进行缩小或者放大,使得图片两边都大于或等于显示边界。 |
| Auto | 自适应显示 |
| Fill | 不保持宽高比进行放大缩小,使得图片充满显示边界。 |
| ScaleDown | 保持宽高比显示,图片缩小或者保持不变。 |
| None | 保持原有尺寸显示。 |
## BorderStyle
| 名称 | 描述 |
| ------ | ----------------------------------------------- |
| Dotted | 显示为一系列圆点,圆点半径为borderWidth的一半。 |
| Dashed | 显示为一系列短的方形虚线。 |
| Solid | 显示为一条实线。 |
## LineJoinStyle
| 名称 | 描述 |
| ----- | -------------------- |
| Bevel | 使用斜角连接路径段。 |
| Miter | 使用尖角连接路径段。 |
| Round | 使用圆角连接路径段。 |
## TouchType
| 名称 | 描述 |
| ------ | ------------------------------ |
| Down | 手指按下时触发。 |
| Up | 手指抬起时触发。 |
| Move | 手指按压态在屏幕上移动时触发。 |
| Cancel | 触摸事件取消时触发。 |
## MouseButton
| 名称 | 描述 |
| ------- | ---------------- |
| Left | 鼠标左键。 |
| Right | 鼠标右键。 |
| Middle | 鼠标中键。 |
| Back | 鼠标左侧后退键。 |
| Forward | 鼠标左侧前进键。 |
| None | 无按键。 |
## MouseAction
| 名称 | 描述 |
| ------- | -------------- |
| Press | 鼠标按键按下。 |
| Release | 鼠标按键松开。 |
| Move | 鼠标移动。 |
## Curve
| 名称 | 描述 |
| ------------------- | ------------------------------------------------------------ |
| Linear | 表示动画从头到尾的速度都是相同的。 |
| Ease | 表示动画以低速开始,然后加快,在结束前变慢,CubicBezier(0.25, 0.1, 0.25, 1.0)。 |
| EaseIn | 表示动画以低速开始,CubicBezier(0.42, 0.0, 1.0, 1.0)。 |
| EaseOut | 表示动画以低速结束,CubicBezier(0.0, 0.0, 0.58, 1.0)。 |
| EaseInOut | 表示动画以低速开始和结束,CubicBezier(0.42, 0.0, 0.58, 1.0)。 |
| FastOutSlowIn | 标准曲线,cubic-bezier(0.4, 0.0, 0.2, 1.0)。 |
| LinearOutSlowIn | 减速曲线,cubic-bezier(0.0, 0.0, 0.2, 1.0)。 |
| FastOutLinearIn | 加速曲线,cubic-bezier(0.4, 0.0, 1.0, 1.0)。 |
| ExtremeDeceleration | 急缓曲线,cubic-bezier(0.0, 0.0, 0.0, 1.0)。 |
| Sharp | 锐利曲线,cubic-bezier(0.33, 0.0, 0.67, 1.0)。 |
| Rhythm | 节奏曲线,cubic-bezier(0.7, 0.0, 0.2, 1.0)。 |
| Smooth | 平滑曲线,cubic-bezier(0.4, 0.0, 0.4, 1.0)。 |
| Friction | 阻尼曲线,CubicBezier(0.2, 0.0, 0.2, 1.0)。 |
## AnimationStatus
| 名称 | 描述 |
| ------- | ------------------ |
| Initial | 动画初始状态。 |
| Running | 动画处于播放状态。 |
| Paused | 动画处于暂停状态。 |
| Stopped | 动画处于停止状态。 |
## FillMode
| 名称 | 描述 |
| -------- | -------------------------------- |
| None | 播放完成后恢复初始状态。 |
| Forwards | 播放完成后保持动画结束时的状态。 |
## PlayMode
| 名称 | 描述 |
| ---------------- | ------------------------------------------------------------ |
| Normal | 动画按正常播放。 |
| Reverse | 动画反向播放。 |
| Alternate | 动画在奇数次(1、3、5...)正向播放,在偶数次(2、4、6...)反向播放。 |
| AlternateReverse | 动画在奇数次(1、3、5...)反向播放,在偶数次(2、4、6...)正向播放。 |
## KeyType
| 名称 | 描述 |
| ---- | ---------- |
| Down | 按键按下。 |
| Up | 按键松开。 |
## KeySource
| 名称 | 描述 |
| -------- | -------------------- |
| Unknown | 输入设备类型未知。 |
| Keyboard | 输入设备类型为键盘。 |
## Edge
| 名称 | 描述 |
| -------- | ---------------------- |
| Top | 竖直方向上边缘 |
| Center | 竖直方向居中位置 |
| Bottom | 竖直方向下边缘 |
| Baseline | 交叉轴方向文本基线位置 |
| Start | 水平方向起始位置 |
| Middle | 水平方向居中位置 |
| End | 水平方向末尾位置 |
## Week
| 名称 | 描述 |
| -------- | ---------------------- |
| Mon | 星期一 |
| Tue | 星期二 |
| Wed | 星期三 |
| Thur | 星期四 |
| Fri | 星期五 |
| Sat | 星期六 |
| Sun | 星期日 |
## Direction
| 名称 | 描述 |
| ---- | ---------------------- |
| Ltr | 元素从左到右布局。 |
| Rtl | 元素从右到左布局。 |
| Auto | 使用系统默认布局方向。 |
## BarState
| 名称 | 描述 |
| ---- | -------------------------------- |
| Off | 不显示。 |
| On | 常驻显示。 |
| Auto | 按需显示(触摸时显示,2s后消失)。 |
## EdgeEffect
| 名称 | 描述 |
| ------ | ------------------------------------------------------------ |
| Spring | 弹性物理动效,滑动到边缘后可以根据初始速度或通过触摸事件继续滑动一段距离,松手后回弹。 |
| Fade | 阴影效果,滑动到边缘后会有圆弧状的阴影。 |
| None | 滑动到边缘后无效果。 |
## Alignment
| 名称 | 描述 |
| -------- | -------- |
| ----------- | ---------------- |
| TopStart | 顶部起始端。 |
| Top | 顶部横向居中。 |
| TopEnd | 顶部尾端。 |
......@@ -14,19 +189,67 @@
| Bottom | 底部横向居中。 |
| BottomEnd | 底部尾端。 |
## TransitionType
| 名称 | 描述 |
| ------ | -------------------------------------------------- |
| All | 指定当前的Transition动效生效在组件的所有变化场景。 |
| Insert | 指定当前的Transition动效生效在组件的插入场景。 |
| Delete | 指定当前的Transition动效生效在组件的删除场景。 |
## RelateType
| 名称 | 描述 |
| ------ | ------------------------------- |
| FILL | 缩放当前子组件以填充满父组件 |
| FIT | 缩放当前子组件以自适应父组件 |
## Visibility
| 名称 | 描述 |
| ------- | -------------------------------- |
| Hidden | 隐藏,但参与布局进行占位。 |
| Visible | 显示。 |
| None | 隐藏,但不参与布局,不进行占位。 |
## LineCapStyle
| 名称 | 描述 |
| ------ | -------------------- |
| Butt | 分割线两端为平行线。 |
| Round | 分割线两端为半圆。 |
| Square | 分割线两端为平行线。 |
## Axis枚举说明
## Axis
| 名称 | 描述 |
| -------- | -------- |
| ---------- | ------------ |
| Vertical | 方向为纵向。 |
| Horizontal | 方向为横向。 |
## HorizontalAlign
## ItemAlign枚举说明
| 名称 | 描述 |
| ------ | ------------------------ |
| Start | 按照语言方向起始端对齐。 |
| Center | 居中对齐,默认对齐方式。 |
| End | 按照语言方向末端对齐。 |
## FlexAlign
| 名称 | 描述 |
| ------------ | ------------------------------------------------------------ |
| Start | 元素在主轴方向首端对齐,第一个元素与行首对齐,同时后续的元素与前一个对齐。 |
| Center | 元素在主轴方向中心对齐,第一个元素与行首的距离与最后一个元素与行尾距离相同。 |
| End | 元素在主轴方向尾部对齐,最后一个元素与行尾对齐,其他元素与后一个对齐。 |
| SpaceBetween | Flex主轴方向均匀分配弹性元素,相邻元素之间距离相同。第一个元素与行首对齐,最后一个元素与行尾对齐。 |
| SpaceAround | Flex主轴方向均匀分配弹性元素,相邻元素之间距离相同。第一个元素到行首的距离和最后一个元素到行尾的距离是相邻元素之间距离的一半。 |
| SpaceEvenly | 距、第一个元素与行首的间距、最后一个元素到行尾的间距都完全一样。 |
## ItemAlign
| 名称 | 描述 |
| -------- | -------- |
| -------- | ------------------------------------------------------------ |
| Auto | 使用Flex容器中默认配置。 |
| Start | 元素在Flex容器中,交叉轴方向首部对齐。 |
| Center | 元素在Flex容器中,交叉轴方向居中对齐。 |
......@@ -34,59 +257,145 @@
| Stretch | 元素在Flex容器中,交叉轴方向拉伸填充,在未设置尺寸时,拉伸到容器尺寸。 |
| Baseline | 元素在Flex容器中,交叉轴方向文本基线对齐。 |
## LineCapStyle枚举说明
## FlexDirection
| 名称 | 描述 |
| -------- | -------- |
| Butt | 分割线两端为平行线。 |
| Round | 分割线两端为半圆。 |
| Square | 分割线两端为平行线。 |
| ------------- | ------------------------------ |
| Row | 主轴与行方向一致作为布局模式。 |
| RowReverse | 与Row方向相反方向进行布局。 |
| Column | 主轴与列方向一致作为布局模式。 |
| ColumnReverse | 与Column相反方向进行布局。 |
## PlayMode枚举值说明
## FlexWrap
| 名称 | 描述 |
| -------- | -------- |
| Normal | 动画按正常播放。 |
| Reverse | 动画反向播放。 |
| Alternate | 动画在奇数次(1、3、5...)正向播放,在偶数次(2、4、6...)反向播放。 |
| AlternateReverse | 动画在奇数次(1、3、5...)反向播放,在偶数次(2、4、6...)正向播放。 |
| ----------- | ------------------------------------------------- |
| NoWrap | Flex容器的元素单行/列布局,子项不允许超出容器。 |
| Wrap | Flex容器的元素多行/列排布,子项允许超出容器。 |
| WrapReverse | Flex容器的元素反向多行/列排布,子项允许超出容器。 |
## VerticalAlign
## ImageRepeat枚举说明
| 名称 | 描述 |
| ------ | ------------------------ |
| Top | 顶部对齐。 |
| Center | 居中对齐,默认对齐方式。 |
| Bottom | 底部对齐。 |
## ImageRepeat
| 名称 | 描述 |
| -------- | -------- |
| -------- | -------------------------- |
| X | 只在水平轴上重复绘制图片。 |
| Y | 只在竖直轴上重复绘制图片。 |
| XY | 在两个轴上重复绘制图片。 |
| NoRepeat | 不重复绘制图片。 |
## ImageSize
| 类型 | 描述 |
| ------- | ------------------------------------------------------------ |
| Cover | 默认值,保持宽高比进行缩小或者放大,使得图片两边都大于或等于显示边界。 |
| Contain | 保持宽高比进行缩小或者放大,使得图片完全显示在显示边界内。 |
| Auto | 保持原图的比例不变。 |
## GradientDirection
| 名称 | 描述 |
| ----------- | ---------- |
| Left | 从右向左。 |
| Top | 从下向上。 |
| Right | 从左向右。 |
| Bottom | 从上向下。 |
| LeftTop | 左上。 |
| LeftBottom | 左下。 |
| RightTop | 右上。 |
| RightBottom | 右下。 |
| None | 无。 |
## SharedTransitionEffectType
| 名称 | 描述 |
| ----------- | ---------- |
| Static | 目标页面元素的位置保持不变,可以配置透明度动画。目前,只有为重定向到目标页面而配置的静态效果才会生效。 |
| Exchange | 将源页面元素移动到目标页面元素位置并适当缩放。 |
## TextDecorationType枚举说明
## FontStyle
| 名称 | 描述 |
| -------- | -------- |
| ------ | ---------------- |
| Normal | 标准的字体样式。 |
| Italic | 斜体的字体样式。 |
## FontWeight
| 名称 | 描述 |
| ------- | -------------- |
| Lighter | 字体较细。 |
| Normal | 字体粗细正常。 |
| Regular | 字体粗细正常。 |
| Medium | 字体粗细适中。 |
| Bold | 字体较粗。 |
| Bolder | 字体非常粗。 |
## TextAlign
| 名称 | 描述 |
| ------ | -------------- |
| Start | 水平对齐首部。 |
| Center | 水平居中对齐。 |
| End | 水平对齐尾部。 |
## TextOverflow
| 名称 | 描述 |
| -------- | -------------------------------------- |
| Clip | 文本超长时进行裁剪显示。 |
| Ellipsis | 文本超长时显示不下的文本用省略号代替。 |
| None | 文本超长时不进行裁剪。 |
## TextDecorationType
| 名称 | 描述 |
| ----------- | ------------------ |
| Underline | 文字下划线修饰。 |
| LineThrough | 穿过文本的修饰线。 |
| Overline | 文字上划线修饰。 |
| None | 不使用文本装饰线。 |
## TextCase枚举说明
## TextCase
| 名称 | 描述 |
| -------- | -------- |
| --------- | -------------------- |
| Normal | 保持文本原有大小写。 |
| LowerCase | 文本采用全小写。 |
| UpperCase | 文本采用全大写。 |
## ResponseType<sup>8+</sup>
| 名称 | 描述 |
| ---------- | -------------------------- |
| LongPress | 通过长按触发菜单弹出。 |
| RightClick | 通过鼠标右键触发菜单弹出。 |
## BarState枚举说明
## HoverEffect<sup>8+</sup>
| 名称 | 描述 |
| -------- | -------- |
| Off | 不显示。 |
| On | 常驻显示。 |
| Auto | 按需显示(触摸时显示,2s后消失)。 |
| --------- | ---------------------------- |
| Auto | 使用组件的系统默认悬浮效果。 |
| Scale | 放大缩小效果。 |
| Highlight | 背景淡入淡出的强调效果。 |
| None | 不设置效果。 |
## Placement<sup>8+</sup>
| 名称 | 描述 |
| ------------- | ------------------------------------------------------------ |
| Left | 气泡提示位于组件左侧,与组件左侧中心对齐。 |
| Right | 气泡提示位于组件右侧,与组件右侧中心对齐。 |
| Top | 气泡提示位于组件上侧,与组件上侧中心对齐。 |
| Bottom | 气泡提示位于组件下侧,与组件下侧中心对齐。 |
| TopLeft | 气泡提示位于组件上侧。 |
| TopRight | 气泡提示位于组件上侧。 |
| BottomLeft | 气泡提示位于组件下侧。 |
| BottomRight | 气泡提示位于组件下侧。 |
\ No newline at end of file
......@@ -42,7 +42,7 @@ Image(src: string | PixelMap | Resource)
| 名称 | 参数类型 | 默认值 | 描述 |
| --------------------- | ------------------------------------------------------- | -------- | ------------------------------------------------------------ |
| alt | string \| [Resource](../../ui/ts-types.md#resource类型) | - | 加载时显示的占位图。支持本地图片和网络路径。 |
| objectFit | ImageFit | Cover | 设置图片的缩放类型。 |
| objectFit | [ImageFit](ts-appendix-enums.md#imagefit) | Cover | 设置图片的缩放类型。 |
| objectRepeat | [ImageRepeat](ts-appendix-enums.md#imagerepeat枚举说明) | NoRepeat | 设置图片的重复样式。<br/>>&nbsp;&nbsp;**说明:**<br/>>&nbsp;-&nbsp;svg类型图源不支持该属性。 |
| interpolation | ImageInterpolation | None | 设置图片的插值效果,即减轻低清晰度图片在放大显示的时候出现的锯齿问题,仅针对图片放大插值。<br/>>&nbsp;&nbsp;**说明:**<br/>>&nbsp;-&nbsp;svg类型图源不支持该属性。<br/>>&nbsp;-&nbsp;PixelMap资源不支持该属性。 |
| renderMode | ImageRenderMode | Original | 设置图片渲染的模式。<br/>>&nbsp;&nbsp;**说明:**<br/>>&nbsp;-&nbsp;svg类型图源不支持该属性。 |
......@@ -53,16 +53,6 @@ Image(src: string | PixelMap | Resource)
| autoResize | boolean | true | 是否需要在图片解码过程中对图源做resize操作,该操作会根据显示区域的尺寸决定用于绘制的图源尺寸,有利于减少内存占用。 |
| syncLoad<sup>8+</sup> | boolean | false | 设置是否同步加载图片,默认是异步加载。同步加载时阻塞UI线程,不会显示占位图。 |
## ImageFit枚举说明
| 名称 | 描述 |
| --------- | -------------------------------- |
| Cover | 保持宽高比进行缩小或者放大,使得图片两边都大于或等于显示边界。 |
| Contain | 保持宽高比进行缩小或者放大,使得图片完全显示在显示边界内。 |
| Fill | 不保持宽高比进行放大缩小,使得图片填充满显示边界。 |
| None | 保持原有尺寸显示。通常配合objectRepeat属性一起使用。 |
| ScaleDown | 保持宽高比显示,图片缩小或者保持不变。 |
## ImageInterpolation枚举说明
| 名称 | 描述 |
......
......@@ -27,30 +27,14 @@ ImageAnimator()
| 参数名称 | 参数类型 | 默认值 | 必填 | 参数描述 |
| ---------- | ---------------------------------------- | -------- | ---- | ---------------------------------------- |
| images | Array&lt;{<br/>src:string,<br/>width?:Length,<br/>height?:Length,<br/>top?:Length,<br/>left?:Length,<br/>duration?:number<br/>}&gt; | [] | 是 | 设置图片帧信息集合。每一帧的帧信息包含图片路径、图片大小、图片位置和图片播放时长信息。详细说明如下:<br/>src:图片路径,图片格式为svg,png和jpg。<br/>width:图片宽度。<br/>height:图片高度。<br/>top:图片相对于组件左上角的纵向坐标。<br/>left:图片相对于组件左上角的横向坐标。<br/>duration:每一帧图片的播放时长,单位毫秒。 |
| state | AnimationStatus | Initial | 否 | 默认为初始状态,用于控制播放状态。 |
| state | [AnimationStatus](ts-appendix-enums.md#animationstatus) | Initial | 否 | 默认为初始状态,用于控制播放状态。 |
| duration | number | 1000 | 否 | 单位为毫秒,默认时长为1000ms;duration为0时,不播放图片;值的改变只会在下一次循环开始时生效;当images中设置了单独的duration后,该属性设置无效。 |
| reverse | boolean | false | 否 | 设置播放顺序。false表示从第1张图片播放到最后1张图片;&nbsp;true表示从最后1张图片播放到第1张图片。 |
| fixedSize | boolean | true | 否 | 设置图片大小是否固定为组件大小。&nbsp;true表示图片大小与组件大小一致,此时设置图片的width&nbsp;、height&nbsp;、top&nbsp;和left属性是无效的。false表示每一张图片的&nbsp;width&nbsp;、height&nbsp;、top和left属性都要单独设置。 |
| preDecode | number | 0 | 否 | 是否启用预解码,默认值为0,即不启用预解码,如该值设为2,则播放当前页时会提前加载后面两张图片至缓存以提升性能。 |
| fillMode | FillMode | Forwards | 否 | 设置动画开始前和结束后的状态,可选值参见FillMode说明。 |
| fillMode | [FillMode](ts-appendix-enums.md#fillmode) | Forwards | 否 | 设置动画开始前和结束后的状态,可选值参见FillMode说明。 |
| iterations | number | 1 | 否 | 默认播放一次,设置为-1时表示无限次播放。 |
## AnimationStatus枚举说明
| 名称 | 描述 |
| ------- | --------- |
| Initial | 动画初始状态。 |
| Running | 动画处于播放状态。 |
| Paused | 动画处于暂停状态。 |
| Stopped | 动画处于停止状态。 |
## FillMode枚举值说明
| 名称 | 描述 |
| -------- | ---------------- |
| None | 播放完成后恢复初始状态。 |
| Forwards | 播放完成后保持动画结束时的状态。 |
## 事件
| 名称 | 功能描述 |
......
......@@ -27,7 +27,7 @@ ScrollBar(value: { scroller: Scroller, direction?: ScrollBarDirection, state?: B
| --------- | ---------------------------------------- | ---- | --------------------------- | ----------------------- |
| scroller | [Scroller](ts-container-scroll.md#scroller) | 是 | - | 可滚动组件的控制器。用于与可滚动组件进行绑定。 |
| direction | ScrollBarDirection | 否 | ScrollBarDirection.Vertical | 滚动条的方向,控制可滚动组件对应方向的滚动。 |
| state | BarState | 否 | BarState.Auto | 滚动条状态。 |
| state | [BarState](ts-appendix-enums.md#barstate) | 否 | BarState.Auto | 滚动条状态。 |
> **说明:**
> ScrollBar组件负责定义可滚动区域的行为样式,ScrollBar的子节点负责定义滚动条的行为样式。
......@@ -41,13 +41,6 @@ ScrollBar(value: { scroller: Scroller, direction?: ScrollBarDirection, state?: B
| Vertical | 纵向滚动条。 |
| Horizontal | 横向滚动条。 |
## BarState枚举说明
| 名称 | 描述 |
| ---- | --------------------- |
| On | 常驻显示。 |
| Off | 不显示。 |
| Auto | 按需显示(触摸时显示,无操作2s后消失)。 |
## 示例
......
......@@ -31,49 +31,17 @@ Text(content?: ResourceStr)
| 名称 | 参数类型 | 默认值 | 描述 |
| -------------- | ---------------------------------------- | ---------------------------------------- | ---------------------------------------- |
| textAlign | TextAlign | TextAlign.Start | 设置多行文本的文本对齐方式。 |
| textOverflow | {overflow:&nbsp;TextOverflow} | {overflow:&nbsp;TextOverflow.Clip} | 设置文本超长时的显示方式。<br/>**说明:**<br/>文本截断是按字截断。例如,英文以单词为最小单位进行截断,若需要以字母为单位进行截断,可在字母间添加零宽空格:\u200B。 |
| textAlign | [TextAlign](ts-appendix-enums.md#textalign) | TextAlign.Start | 设置多行文本的文本对齐方式。 |
| textOverflow | {overflow:&nbsp;[TextOverflow](ts-appendix-enums.md#textoverflow)} | {overflow:&nbsp;TextOverflow.Clip} | 设置文本超长时的显示方式。<br/>**说明:**<br/>文本截断是按字截断。例如,英文以单词为最小单位进行截断,若需要以字母为单位进行截断,可在字母间添加零宽空格:\u200B。 |
| maxLines | number | Infinity | 设置文本的最大行数。 |
| lineHeight | string&nbsp;\|&nbsp;number&nbsp;\|&nbsp;[Resource](../../ui/ts-types.md) | - | 设置文本的文本行高,设置值不大于0时,不限制文本行高,自适应字体大小,Length为number类型时单位为fp。 |
| decoration | {<br/>type:&nbsp;TextDecorationType,<br/>color?:&nbsp;[ResourceColor](../../ui/ts-types.md)<br/>} | {<br/>type:&nbsp;TextDecorationType.None,<br/>color:Color.Black<br/>} | 设置文本装饰线样式及其颜色。 |
| decoration | {<br/>type:&nbsp;[TextDecorationType](ts-appendix-enums.md#textdecorationtype),<br/>color?:&nbsp;[ResourceColor](../../ui/ts-types.md)<br/>} | {<br/>type:&nbsp;TextDecorationType.None,<br/>color:Color.Black<br/>} | 设置文本装饰线样式及其颜色。 |
| baselineOffset | [Length](../../ui/ts-types.md) | - | 设置文本基线的偏移量。 |
| textCase | TextCase | TextCase.Normal | 设置文本大小写。 |
| letterSpacing | [Length](../../ui/ts-types.md) | - | 设置文本字符间距。 |
| minFontSize | number&nbsp;\|&nbsp;string&nbsp;\|&nbsp;[Resource](../../ui/ts-types.md) | - | 设置文本最小显示字号。 |
| maxFontSize | number&nbsp;\|&nbsp;string&nbsp;\|&nbsp;[Resource](../../ui/ts-types.md) | - | 设置文本最大显示字号。 |
| textCase | [TextCase](ts-appendix-enums.md#textcase) | TextCase.Normal | 设置文本大小写。 |
## TextAlign枚举说明
| 名称 | 描述 |
| ------ | -------------- |
| Center | 文本居中对齐。 |
| Start | 根据文字书写相同的方向对齐。 |
| End | 根据文字书写相反的方向对齐。 |
## TextOverflow枚举说明
| 名称 | 描述 |
| -------- | ------------------- |
| Clip | 文本超长时进行裁剪显示。 |
| Ellipsis | 文本超长时显示不下的文本用省略号代替。 |
| None | 文本超长时不进行裁剪。 |
## TextDecorationType枚举说明
| 名称 | 描述 |
| ----------- | --------- |
| Underline | 文字下划线修饰。 |
| LineThrough | 穿过文本的修饰线。 |
| Overline | 文字上划线修饰。 |
| None | 不使用文本装饰线。 |
## TextCase枚举说明
| 名称 | 描述 |
| --------- | ---------- |
| Normal | 保持文本原有大小写。 |
| LowerCase | 文本采用全小写。 |
| UpperCase | 文本采用全大写。 |
> **说明:**
>
......
......@@ -37,18 +37,10 @@ TextArea(value?:{placeholder?: ResourceStr, text?: ResourceStr, controller?: Tex
| ------------------------ | ---------------------------------------- | ----- | ---------------------------------------- |
| placeholderColor | [ResourceColor](../../ui/ts-types.md) | - | 设置placeholder文本颜色。 |
| placeholderFont | {<br/>size?:&nbsp;number,<br/>weight?:number&nbsp;\|&nbsp;[FontWeight](ts-universal-attributes-text-style.md),<br/>family?:&nbsp;string,<br/>style?:&nbsp;[FontStyle](ts-universal-attributes-text-style.md)<br/>} | - | 设置placeholder文本样式:<br/>-&nbsp;size:&nbsp;设置文本尺寸,Length为number类型时,使用fp单位。<br/>-&nbsp;weight:&nbsp;设置文本的字体粗细,number类型取值[100,&nbsp;900],取值间隔为100,默认为400,取值越大,字体越粗。<br/>-&nbsp;family:&nbsp;设置文本的字体列表。使用多个字体,使用','进行分割,优先级按顺序生效,例如:'Arial,&nbsp;sans-serif'。<br/>-&nbsp;style:&nbsp;设置文本的字体样式。 |
| textAlign | TextAlign | Start | 设置文本水平对齐方式。 |
| textAlign | [TextAlign](ts-appendix-enums.md#textalign) | Start | 设置文本水平对齐方式。 |
| caretColor | [ResourceColor](../../ui/ts-types.md) | - | 设置输入框光标颜色。 |
| inputFilter<sup>8+</sup> | {<br/>value:&nbsp;[ResourceStr](../../ui/ts-types.md)<sup>8+</sup>,<br/>error?:&nbsp;(value:&nbsp;string)&nbsp;=&gt;&nbsp;void<br/>} | - | 通过正则表达式设置输入过滤器。满足表达式的输入允许显示,不满足的输入被忽略。仅支持单个字符匹配,不支持字符串匹配。例如:^(?=.\*\d)(?=.\*[a-z])(?=.\*[A-Z]).{8,10}$,不支持过滤8到10位的强密码。<br/>-&nbsp;value:设置正则表达式。<br/>-&nbsp;error:正则匹配失败时,返回被忽略的内容。 |
## TextAlign枚举说明
| 名称 | 描述 |
| ------ | ------- |
| Start | 水平对齐首部。 |
| Center | 水平居中对齐。 |
| End | 水平对齐尾部。 |
## 事件
| 名称 | 功能描述 |
......
......@@ -81,12 +81,12 @@ domStorageAccess(domStorageAccess: boolean)
fileAccess(fileAccess: boolean)
设置是否开启通过[$rawfile(filepath/filename)](../../ui/ts-resource-access.md)访问应用中rawfile路径的文件, 默认启用
设置是否开启应用中文件系统的访问,默认启用。[$rawfile(filepath/filename)](../../ui/ts-resource-access.md)中rawfile路径的文件不受该属性影响而限制访问
**参数:**
| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 |
| ---------- | ------- | ---- | ---- | ---------------------------------------- |
| fileAccess | boolean | 是 | true | 设置是否开启通过[$rawfile(filepath/filename)](../../ui/ts-resource-access.md)访问应用中rawfile路径的文件,默认启用。 |
| fileAccess | boolean | 是 | true | 设置是否开启应用中文件系统的访问,默认启用。 |
**示例:**
```ts
......@@ -323,6 +323,7 @@ databaseAccess(databaseAccess: boolean)
| -------------- | ------- | ---- | ---- | ----------------- |
| databaseAccess | boolean | 是 | false | 设置是否开启数据库存储API权限。 |
**示例:**
```ts
// xxx.ets
@Entry
......@@ -349,6 +350,7 @@ geolocationAccess(geolocationAccess: boolean)
| -------------- | ------- | ---- | ---- | ----------------- |
| geolocationAccess | boolean | 是 | true | 设置是否开启获取地理位置权限。 |
**示例:**
```ts
// xxx.ets
@Entry
......@@ -1349,7 +1351,7 @@ forward(): void
deleteJavaScriptRegister(name: string)
删除通过registerJavaScriptProxy注册到window上的指定name的应用侧JavaScript对象。
删除通过registerJavaScriptProxy注册到window上的指定name的应用侧JavaScript对象。删除后立即生效,无须调用[refresh](#refresh)接口。
**参数:**
| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 |
......@@ -1596,7 +1598,7 @@ refresh()
registerJavaScriptProxy(options: { object: object, name: string, methodList: Array\<string\> })
注入JavaScript对象到window对象中,并在window对象中调用该对象的方法。注册后,须调用refresh接口生效。
注入JavaScript对象到window对象中,并在window对象中调用该对象的方法。注册后,须调用[refresh](#refresh)接口生效。
**参数:**
| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 |
......
......@@ -17,10 +17,10 @@ PanGesture(options?: { fingers?: number, direction?: PanDirection, distance?: nu
**参数:**
| 参数名称 | 参数类型 | 必填 | 默认值 | 参数描述 |
| --------- | ------------ | ---- | ---- | ---------------------------------- |
| --------- | ------------ | ---- | ------ | ------------------------------------------------------------ |
| fingers | number | 否 | 1 | 触发滑动的最少手指数,最小为1指,&nbsp;最大取值为10指。 |
| direction | PanDirection | 否 | All | 设置滑动方向,此枚举值支持逻辑与(&amp;)和逻辑或(\|)运算。 |
| distance | number | 否 | 5.0 | 最小滑动识别距离,单位为vp。 |
| distance | number | 否 | 5.0 | 最小滑动识别距离,单位为vp。<br/>**说明:**<br/>> tab滑动与该拖动手势事件同时存在时,可将distance值设为1,使拖动更灵敏,避免造成事件错乱。 |
## PanDirection枚举说明
......
......@@ -17,7 +17,7 @@ import lottie from '@ohos/lottieETS'
```
> **说明:**
> 在Terminal窗口使用 `npm install @ohos/lottieETS` 命令下载Lottie。
> 在Terminal窗口使用 `npm install @ohos/lottieETS` 命令下载Lottie,下载之前需要配置权限
## lottie.loadAnimation
......@@ -63,7 +63,7 @@ destroy(name: string): void
private animatePath: string = "common/lottie/data.json"
private animateItem: any = null
private onPageHide(): void {
onPageHide(): void {
console.log('onPageHide')
lottie.destroy()
}
......
......@@ -31,17 +31,9 @@ Column(value?:{space?: Length})
| 名称 | 参数类型 | 默认值 | 描述 |
| ---------------- | --------------------------------- | ---------------------- | ----------------- |
| alignItems | HorizontalAlign | HorizontalAlign.Center | 设置子组件在水平方向上的对齐格式。 |
| alignItems | [HorizontalAlign](ts-appendix-enums.md#horizontalalign) | HorizontalAlign.Center | 设置子组件在水平方向上的对齐格式。 |
| justifyContent<sup>8+</sup> | [FlexAlign](ts-container-flex.md) | FlexAlign.Start | 设置子组件在垂直方向上的对齐格式。 |
## HorizontalAlign枚举说明
| 名称 | 描述 |
| ------ | ------------ |
| Start | 按照语言方向起始端对齐。 |
| Center | 居中对齐,默认对齐方式。 |
| End | 按照语言方向末端对齐。 |
## 示例
......
......@@ -27,39 +27,12 @@ Flex(value?: { direction?: FlexDirection, wrap?: FlexWrap, justifyContent?: Fle
| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 |
| -------------- | ---------------------------------------- | ---- | ----------------- | ---------------------------------------- |
| direction | FlexDirection | 否 | FlexDirection.Row | 子组件在Flex容器上排列的方向,即主轴的方向。 |
| wrap | FlexWrap | 否 | FlexWrap.NoWrap | Flex容器是单行/列还是多行/列排列。 |
| justifyContent | FlexAlign | 否 | FlexAlign.Start | 子组件在Flex容器主轴上的对齐格式。 |
| alignItems | [ItemAlign](ts-appendix-enums.md#itemalign枚举说明) | 否 | ItemAlign.Stretch | 子组件在Flex容器交叉轴上的对齐格式。 |
| alignContent | FlexAlign | 否 | FlexAlign.Start | 交叉轴中有额外的空间时,多行内容的对齐方式。仅在wrap为Wrap或WrapReverse下生效。 |
## FlexDirection枚举说明
| 名称 | 描述 |
| ------------- | ---------------- |
| Row | 主轴与行方向一致作为布局模式。 |
| RowReverse | 与Row方向相反方向进行布局。 |
| Column | 主轴与列方向一致作为布局模式。 |
| ColumnReverse | 与Column相反方向进行布局。 |
## FlexWrap枚举说明
| 名称 | 描述 |
| ----------- | --------------------------- |
| NoWrap | Flex容器的元素单行/列布局,子项不允许超出容器。 |
| Wrap | Flex容器的元素多行/列排布,子项允许超出容器。 |
| WrapReverse | Flex容器的元素反向多行/列排布,子项允许超出容器。 |
## FlexAlign枚举说明
| 名称 | 描述 |
| ------------ | ---------------------------------------- |
| Start | 元素在主轴方向首端对齐,&nbsp;第一个元素与行首对齐,同时后续的元素与前一个对齐。 |
| Center | 元素在主轴方向中心对齐,第一个元素与行首的距离与最后一个元素与行尾距离相同。 |
| End | 元素在主轴方向尾部对齐,&nbsp;&nbsp;最后一个元素与行尾对齐,其他元素与后一个对齐。 |
| SpaceBetween | Flex主轴方向均匀分配弹性元素,相邻元素之间距离相同。&nbsp;第一个元素与行首对齐,最后一个元素与行尾对齐。 |
| SpaceAround | Flex主轴方向均匀分配弹性元素,相邻元素之间距离相同。&nbsp;第一个元素到行首的距离和最后一个元素到行尾的距离是相邻元素之间距离的一半。 |
| SpaceEvenly | Flex主轴方向元素等间距布局,&nbsp;相邻元素之间的间距、第一个元素与行首的间距、最后一个元素到行尾的间距都完全一样。 |
| direction | [FlexDirection](ts-appendix-enums.md#flexdirection) | 否 | FlexDirection.Row | 子组件在Flex容器上排列的方向,即主轴的方向。 |
| wrap | [FlexWrap](ts-appendix-enums.md#flexwrap) | 否 | FlexWrap.NoWrap | Flex容器是单行/列还是多行/列排列。 |
| justifyContent | [FlexAlign](ts-appendix-enums.md#flexalign) | 否 | FlexAlign.Start | 子组件在Flex容器主轴上的对齐格式。 |
| alignItems | [ItemAlign](ts-appendix-enums.md#itemalign) | 否 | ItemAlign.Stretch | 子组件在Flex容器交叉轴上的对齐格式。 |
| alignContent | [FlexAlign](ts-appendix-enums.md#flexalign) | 否 | FlexAlign.Start | 交叉轴中有额外的空间时,多行内容的对齐方式。仅在wrap为Wrap或WrapReverse下生效。 |
## 示例
......
......@@ -4,7 +4,9 @@
> **说明:**
>
> 该组件从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
> - 该组件从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
>
> - 该组件回弹的前提是要有滚动。内容小于一屏时,没有回弹效果。
## 权限列表
......@@ -33,23 +35,16 @@ List(value:{space?: number | string, initialIndex?: number, scroller?: Scroller}
| 名称 | 参数类型 | 默认值 | 描述 |
| ---------------------------- | ---------------------------------------- | ----------------- | ---------------------------------------- |
| listDirection | [Axis](ts-appendix-enums.md#axis枚举说明) | Vertical | 设置List组件排列方向参照Axis枚举说明。 |
| listDirection | [Axis](ts-appendix-enums.md#axis) | Vertical | 设置List组件排列方向参照Axis枚举说明。 |
| divider | {<br/>strokeWidth:&nbsp;Length,<br/>color?:[ResourceColor](../../ui/ts-types.md),<br/>startMargin?:&nbsp;Length,<br/>endMargin?:&nbsp;Length<br/>} | - | 用于设置ListItem分割线样式,默认无分割线。<br/>strokeWidth:&nbsp;分割线的线宽。<br/>color:&nbsp;分割线的颜色。<br/>startMargin:&nbsp;分割线距离列表侧边起始端的距离。<br/>endMargin:&nbsp;分割线距离列表侧边结束端的距离。 |
| scrollBar | [BarState](ts-appendix-enums.md#barstate枚举说明) | BarState.Off | 设置滚动条状态。 |
| scrollBar | [BarState](ts-appendix-enums.md#barstate) | BarState.Off | 设置滚动条状态。 |
| cachedCount | number | 1 | 设置预加载的ListItem的数量。 |
| editMode | boolean | false | 声明当前List组件是否处于可编辑模式。 |
| edgeEffect | EdgeEffect | EdgeEffect.Spring | 滑动效果,目前支持的滑动效果参见EdgeEffect的枚举说明。 |
| edgeEffect | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | EdgeEffect.Spring | 滑动效果,目前支持的滑动效果参见EdgeEffect的枚举说明。 |
| chainAnimation | boolean | false | 用于设置当前list是否启用链式联动动效,开启后列表滑动以及顶部和底部拖拽时会有链式联动的效果。链式联动效果:list内的list-item间隔一定距离,在基本的滑动交互行为下,主动对象驱动从动对象进行联动,驱动效果遵循弹簧物理动效。<br/>-&nbsp;false:不启用链式联动。<br/>-&nbsp;true:启用链式联动。 |
| multiSelectable<sup>8+</sup> | boolean | false | 是否开启鼠标框选。<br/>-&nbsp;false:关闭框选。<br/>-&nbsp;true:开启框选。 |
| restoreId<sup>8+</sup> | number | - | 组件迁移标识符,标识后的组件在应用迁移时,组件状态会被迁移到被拉起方的同标识组件。<br/>列表组件状态,包括起始位置显示的item序号。 |
## EdgeEffect枚举说明
| 名称 | 描述 |
| ------ | ---------------------------------------- |
| Spring | 弹性物理动效,滑动到边缘后可以根据初始速度或通过触摸事件继续滑动一段距离,松手后回弹。 |
| Fade | 阴影效果,滑动到边缘后会有圆弧状的阴影。 |
| None | 滑动到边缘后无效果。 |
## 事件
......
......@@ -31,16 +31,8 @@ Row(value?:{space?: Length})
| 名称 | 参数类型 | 默认值 | 描述 |
| ---------------- | --------------------------------- | -------------------- | ----------------- |
| alignItems | VerticalAlign | VerticalAlign.Center | 在垂直方向上子组件的对齐格式。 |
| justifyContent<sup>8+</sup> | [FlexAlign](ts-container-flex.md) | FlexAlign.Start | 设置子组件在水平方向上的对齐格式。 |
## VerticalAlign枚举说明
| 名称 | 描述 |
| ------ | ------------ |
| Top | 顶部对齐。 |
| Center | 居中对齐,默认对齐方式。 |
| Bottom | 底部对齐。 |
| alignItems | [VerticalAlign](ts-appendix-enums.md#verticalalign) | VerticalAlign.Center | 在垂直方向上子组件的对齐格式。 |
| justifyContent<sup>8+</sup> | [FlexAlign](ts-appendix-enums.md#flexalign) | FlexAlign.Start | 设置子组件在水平方向上的对齐格式。 |
## 示例
......
......@@ -4,7 +4,8 @@
> **说明:**
>
> 该组件从API version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
> - 该组件从API version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
> - 该组件回弹的前提是要有滚动。内容小于一屏时,没有回弹效果。
## 权限列表
......@@ -27,7 +28,7 @@ Scroll(scroller?: Scroller)
| 名称 | 参数类型 | 默认值 | 描述 |
| -------------- | ---------------------------------------- | ------------------------ | --------- |
| scrollable | ScrollDirection | ScrollDirection.Vertical | 设置滚动方法。 |
| scrollBar | [BarState](ts-appendix-enums.md#barstate枚举说明) | BarState.Off | 设置滚动条状态。 |
| scrollBar | [BarState](ts-appendix-enums.md#barstate) | BarState.Off | 设置滚动条状态。 |
| scrollBarColor | string&nbsp;\|&nbsp;number&nbsp;\|&nbsp;Color | - | 设置滚动条的颜色。 |
| scrollBarWidth | Length | - | 设置滚动条的宽度。 |
| edgeEffect | EdgeEffect | EdgeEffect.Spring | 设置滑动效果,目前支持的滑动效果参见EdgeEffect的枚举说明。 |
......
......@@ -28,6 +28,8 @@ Swiper(value:{controller?: SwiperController})
## 属性
不支持[Menu控制](ts-universal-attributes-menu.md)
| 名称 | 参数类型 | 默认值 | 描述 |
| --------------------------- | ---------------------------------------- | ---------- | ---------------------------------------- |
| index | number | 0 | 设置当前在容器中显示的子组件的索引值。 |
......
......@@ -40,20 +40,13 @@ Shape(value:{target?: PixelMap})
| stroke | Color | - | 否 | 边框颜色。 |
| strokeDashArray | Array&lt;Length&gt; | [] | 否 | 设置边框的间隙。 |
| strokeDashOffset | Length | 0 | 否 | 边框绘制起点的偏移量。 |
| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#LineCapStyle枚举说明) | LineCapStyle.Butt | 否 | 路径端点绘制样式。 |
| strokeLineJoin | LineJoinStyle | LineJoinStyle.Miter | 否 | 边框拐角绘制样式。 |
| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | 否 | 路径端点绘制样式。 |
| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | 否 | 边框拐角绘制样式。 |
| strokeMiterLimit | number | 4 | 否 | 锐角绘制成斜角的极限值。 |
| strokeOpacity | number | 1 | 否 | 设置边框的不透明度。 |
| strokeWidth | Length | 1 | 否 | 设置边框的宽度。 |
| antiAlias | boolean | true | 否 | 是否开启抗锯齿。 |
## LineJoinStyle枚举说明
| 名称 | 描述 |
| ----- | ---------- |
| Bevel | 使用斜角连接路径段。 |
| Miter | 使用尖角连接路径段。 |
| Round | 使用圆角连接路径段。 |
## 示例
......
......@@ -21,7 +21,7 @@
| curve | Curve&nbsp;\|&nbsp;Curves | Linear | 动画曲线。 |
| delay | number | 0 | 单位为ms(毫秒),默认不延时播放。 |
| iterations | number | 1 | 默认播放一次,设置为-1时表示无限次播放。 |
| playMode | PlayMode | Normal | 设置动画播放模式,默认播放完成后重头开始播放。 |
| playMode | [PlayMode](ts-appendix-enums.md#playmode) | Normal | 设置动画播放模式,默认播放完成后重头开始播放。 |
### 接口
......
......@@ -4,7 +4,7 @@
> 从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
通过CustomDialogController类显示自定义弹窗。
通过CustomDialogController类显示自定义弹窗。使用弹窗组件时,可优先考虑自定义弹窗,便于自定义弹窗的样式与内容。
## 接口
......@@ -63,17 +63,23 @@ close(): void
## 示例
```
// xxx.ets
@CustomDialog
struct CustomDialogExample {
@Link textValue: string
@Link inputValue: string
controller: CustomDialogController
cancel: () => void
confirm: () => void
build() {
Column() {
Text('Software uninstall').width('70%').fontSize(20).margin({ top: 10, bottom: 10 })
Image($r('app.media.icon')).width(80).height(80)
Text('Whether to uninstall a software?').fontSize(16).margin({ bottom: 10 })
Text('Change text').fontSize(20).margin({ top: 10, bottom: 10 })
TextInput({ placeholder: '', text: this.textValue }).height(60).width('90%')
.onChange((value: string) => {
this.textValue = value
})
Text('Whether to change a text?').fontSize(16).margin({ bottom: 10 })
Flex({ justifyContent: FlexAlign.SpaceAround }) {
Button('cancel')
.onClick(() => {
......@@ -82,6 +88,7 @@ struct CustomDialogExample {
}).backgroundColor(0xffffff).fontColor(Color.Black)
Button('confirm')
.onClick(() => {
this.inputValue = this.textValue
this.controller.close()
this.confirm()
}).backgroundColor(0xffffff).fontColor(Color.Red)
......@@ -93,8 +100,10 @@ struct CustomDialogExample {
@Entry
@Component
struct CustomDialogUser {
@State textValue: string = ''
@State inputValue: string = 'click me'
dialogController: CustomDialogController = new CustomDialogController({
builder: CustomDialogExample({ cancel: this.onCancel, confirm: this.onAccept }),
builder: CustomDialogExample({ cancel: this.onCancel, confirm: this.onAccept, textValue: $textValue, inputValue: $inputValue }),
cancel: this.existApp,
autoCancel: true
})
......@@ -111,7 +120,7 @@ struct CustomDialogUser {
build() {
Column() {
Button('click me')
Button(this.inputValue)
.onClick(() => {
this.dialogController.open()
}).backgroundColor(0x317aff)
......
......@@ -10,9 +10,10 @@ close(): void
可以通过该方法在页面范围内关闭通过[bindContextMenu](./ts-universal-attributes-menu.md#属性)给组件绑定的菜单。
**示例:**
## 示例
```
```ts
// xxx.ets
@Entry
@Component
struct Index {
......@@ -26,8 +27,8 @@ struct Index {
})
}.height(400)
.backgroundColor(Color.Pink)
}
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.Start }) {
Column(){
......
......@@ -16,18 +16,11 @@
- transition入参说明
| 参数名称 | 参数类型 | 默认值 | 必填 | 参数描述 |
| -------- | -------- | -------- | -------- | -------- |
| type | TransitionType | TransitionType.All | 否 | 默认包括组件新增和删除。<br/>>&nbsp;&nbsp;**说明:**<br/>>&nbsp;不指定Type时说明插入删除使用同一种效果。 |
| type | [TransitionType](ts-appendix-enums.md#transitiontype) | TransitionType.All | 否 | 默认包括组件新增和删除。<br/>>&nbsp;&nbsp;**说明:**<br/>>&nbsp;不指定Type时说明插入删除使用同一种效果。 |
| opacity | number | 1 | 否 | 设置组件转场时的透明度效果,为插入时起点和删除时终点的值。 |
| translate | {<br/>x?&nbsp;:&nbsp;number,<br/>y?&nbsp;:&nbsp;number,<br/>z?&nbsp;:&nbsp;number<br/>} | - | 否 | 设置组件转场时的平移效果,为插入时起点和删除时终点的值。 |
| scale | {<br/>x?&nbsp;:&nbsp;number,<br/>y?&nbsp;:&nbsp;number,<br/>z?&nbsp;:&nbsp;number,<br/>centerX?&nbsp;:&nbsp;number,<br/>centerY?&nbsp;:&nbsp;number<br/>} | - | 否 | 设置组件转场时的缩放效果,为插入时起点和删除时终点的值。 |
| rotate | {<br/>x?:&nbsp;number,<br/>y?:&nbsp;number,<br/>z?:&nbsp;number,<br/>angle?:&nbsp;Angle,<br/>centerX?:&nbsp;Length,<br/>centerY?:&nbsp;Length<br/>} | - | 否 | 设置组件转场时的旋转效果,为插入时起点和删除时终点的值。 |
- TransitionType枚举说明
| 名称 | 描述 |
| -------- | -------- |
| All | 指定当前的Transition动效生效在组件的所有变化场景。 |
| Insert | 指定当前的Transition动效生效在组件的插入场景。 |
| Delete | 指定当前的Transition动效生效在组件的删除场景。 |
| translate | {<br/>x?&nbsp;:&nbsp;number,<br/>y?&nbsp;:&nbsp;number,<br/>z?&nbsp;:&nbsp;number<br/>} | - | 否 | 设置组件转场时的平移效果,为插入时起点和删除时终点的值。<br/>**说明:**<br/>>&nbsp;x、y、z分别是横向、纵向、竖向的平移距离 |
| scale | {<br/>x?&nbsp;:&nbsp;number,<br/>y?&nbsp;:&nbsp;number,<br/>z?&nbsp;:&nbsp;number,<br/>centerX?&nbsp;:&nbsp;number,<br/>centerY?&nbsp;:&nbsp;number<br/>} | - | 否 | 设置组件转场时的缩放效果,为插入时起点和删除时终点的值。设置组件转场时的平移效果,为插入时起点和删除时终点的值。<br/>**说明:**<br/>\>&nbsp;x、y、z分别是横向、纵向、竖向放大倍数(或缩小到原来的多少)<br/>>&nbsp;centerX、centerY缩放中心点<br/>>&nbsp;中心点为0时,默认的是组件的左上角<br/> |
| rotate | {<br/>x?:&nbsp;number,<br/>y?:&nbsp;number,<br/>z?:&nbsp;number,<br/>angle?:&nbsp;Angle,<br/>centerX?:&nbsp;Length,<br/>centerY?:&nbsp;Length<br/>} | - | 否 | 设置组件转场时的旋转效果,为插入时起点和删除时终点的值。<br/>**说明:**<br/>>&nbsp;x、y、z分别是横向、纵向、竖向的旋转向量<br/>>&nbsp;centerX,centerY指旋转中心点<br/>>&nbsp;中心点为0时,默认的是组件的左上角 |
## 示例
......
......@@ -18,17 +18,9 @@
| 名称 | 参数类型 | 默认值 | 描述 |
| -------- | -------- | -------- | -------- |
| backgroundColor | Color | - | 设置组件的背景色。 |
| backgroundImage | src:&nbsp;string,<br/>repeat?:&nbsp;[ImageRepeat](ts-appendix-enums.md#imagerepeat枚举说明) | - | src参数:图片地址,支持网络图片资源和本地图片资源地址(不支持svg类型的图片)。<br/>repeat参数:设置背景图片的重复样式,默认不重复。 |
| backgroundImageSize | {<br/>width?:&nbsp;Length,<br/>height?:&nbsp;Length<br/>}&nbsp;\|&nbsp;ImageSize | Auto | 设置背景图像的高度和宽度。当输入为{width:&nbsp;Length,&nbsp;height:&nbsp;Length}对象时,如果只设置一个属性,则第二个属性保持图片原始宽高比进行调整。默认保持原图的比例不变。 |
| backgroundImagePosition | {<br/>x?:&nbsp;Length,<br/>y?:&nbsp;Length<br/>}&nbsp;\|&nbsp;[Alignment](ts-appendix-enums.md#alignment枚举说明) | {<br/>x:&nbsp;0,<br/>y:&nbsp;0<br/>} | 设置背景图在组件中显示位置。 |
- ImageSize枚举说明
| 类型 | 描述 |
| -------- | -------- |
| Cover | 默认值,保持宽高比进行缩小或者放大,使得图片两边都大于或等于显示边界。 |
| Contain | 保持宽高比进行缩小或者放大,使得图片完全显示在显示边界内。 |
| Auto | 保持原图的比例不变。 |
| backgroundImage | src:&nbsp;string,<br/>repeat?:&nbsp;[ImageRepeat](ts-appendix-enums.md#imagerepeat) | - | src参数:图片地址,支持网络图片资源和本地图片资源地址(不支持svg类型的图片)。<br/>repeat参数:设置背景图片的重复样式,默认不重复。 |
| backgroundImageSize | {<br/>width?:&nbsp;Length,<br/>height?:&nbsp;Length<br/>}&nbsp;\|&nbsp;[ImageSize](ts-appendix-enums.md#imagesize) | Auto | 设置背景图像的高度和宽度。当输入为{width:&nbsp;Length,&nbsp;height:&nbsp;Length}对象时,如果只设置一个属性,则第二个属性保持图片原始宽高比进行调整。默认保持原图的比例不变。 |
| backgroundImagePosition | {<br/>x?:&nbsp;Length,<br/>y?:&nbsp;Length<br/>}&nbsp;\|&nbsp;[Alignment](ts-appendix-enums.md#alignment) | {<br/>x:&nbsp;0,<br/>y:&nbsp;0<br/>} | 设置背景图在组件中显示位置。 |
## 示例
......
......@@ -17,20 +17,13 @@
| 名称 | 参数类型 | 默认值 | 描述 |
| -------- | -------- | -------- | -------- |
| border | {<br/>width?:&nbsp;Length,<br/>color?:&nbsp;Color,<br/>radius?:&nbsp;Length,<br/>style?:&nbsp;BorderStyle<br/>} | - | 统一边框样式设置接口。 |
| borderStyle | BorderStyle | &nbsp;BorderStyle.Solid | 设置元素的边框样式。 |
| border | {<br/>width?:&nbsp;Length,<br/>color?:&nbsp;Color,<br/>radius?:&nbsp;Length,<br/>style?:&nbsp;[BorderStyle](ts-appendix-enums.md#borderstyle)<br/>} | - | 统一边框样式设置接口。 |
| borderStyle | [BorderStyle](ts-appendix-enums.md#borderstyle) | &nbsp;BorderStyle.Solid | 设置元素的边框样式。 |
| borderWidth | Length | 0 | 设置元素的边框宽度。 |
| borderColor | Color | - | 设置元素的边框颜色。 |
| borderRadius | Length | 0 | 设置元素的边框圆角半径。 |
- BorderStyle枚举说明
| 名称 | 描述 |
| -------- | -------- |
| Dotted | 显示为一系列圆点,圆点半径为borderWidth的一半。 |
| Dashed | 显示为一系列短的方形虚线。 |
| Solid | 显示为一条实线。 |
## 示例
......
......@@ -14,27 +14,11 @@
| 名称 | 参数类型 | 默认值 | 描述 |
| -------- | -------- | -------- | -------- |
| linearGradient | {<br/>angle?:&nbsp;[Angle](../../ui/ts-types.md),<br/>direction?:&nbsp;GradientDirection,<br/>colors:&nbsp;Array&lt;[ColorStop](../../ui/ts-types.md)&gt;<br/>repeating?:&nbsp;boolean<br/>} | - | 线性渐变。<br/>angle:&nbsp;线性渐变的角度。<br/>direction:&nbsp;线性渐变的方向,设置angle后不生效。<br/>colors:&nbsp;为渐变的颜色描述。<br/>repeating:&nbsp;为渐变的颜色重复着色。 |
| linearGradient | {<br/>angle?:&nbsp;[Angle](../../ui/ts-types.md),<br/>direction?:&nbsp;[GradientDirection](ts-appendix-enums.md#gradientdirection),<br/>colors:&nbsp;Array&lt;[ColorStop](../../ui/ts-types.md)&gt;<br/>repeating?:&nbsp;boolean<br/>} | - | 线性渐变。<br/>angle:&nbsp;线性渐变的角度。<br/>direction:&nbsp;线性渐变的方向,设置angle后不生效。<br/>colors:&nbsp;为渐变的颜色描述。<br/>repeating:&nbsp;为渐变的颜色重复着色。 |
| sweepGradient | {<br/>center:&nbsp;Point,<br/>start?:&nbsp;angle,<br/>end?:&nbsp;angle,<br/>colors:&nbsp;Array&lt;[ColorStop](../../ui/ts-types.md)&gt;<br/>repeating?:&nbsp;boolean<br/>} | - | 角度渐变。<br/>center:为角度渐变的中心点。<br/>start:角度渐变的起点。<br/>end:角度渐变的终点。<br/>colors:&nbsp;为渐变的颜色描述。<br/>repeating:&nbsp;为渐变的颜色重复着色。 |
| radialGradient | {<br/>center:&nbsp;Point,<br/>radius:&nbsp;Length,<br/>colors:&nbsp;Array&lt;[ColorStop](../../ui/ts-types.md)&gt;<br/>repeating:&nbsp;boolean<br/>} | - | 径向渐变。<br/>center:径向渐变的中心点。<br/>radius:径向渐变的半径。<br/>colors:&nbsp;为渐变的颜色描述。<br/>repeating:&nbsp;为渐变的颜色重复着色。 |
- GradientDirection枚举说明<br>
GradientDirection用于描述渐变方向。
| 名称 | 描述 |
| -------- | -------- |
| Left | 从右向左。 |
| Top | 从下向上。 |
| Right | 从左向右。 |
| Bottom | 从上向下。 |
| LeftTop | 左上。 |
| LeftBottom | 左下。 |
| RightTop | 右上。 |
| RightBottom | 右下。 |
| None | 无。 |
## 示例
```ts
......
......@@ -13,15 +13,7 @@
| 名称 | 参数类型 | 默认值 | 描述 |
| -------- | -------- | -------- | -------- |
| hoverEffect | HoverEffect | HoverEffect.Auto | 设置当前组件悬停态下的悬浮效果。 |
- HoverEffect 枚举说明
| 名称 | 描述 |
| -------- | -------- |
| Auto | 使用组件的系统默认悬浮效果。 |
| Scale | 放大缩小效果。 |
| Highlight | 背景淡入淡出的强调效果。 |
| None | 不设置效果。 |
| hoverEffect | [HoverEffect](ts-appendix-enums.md#hovereffect8) | HoverEffect.Auto | 设置当前组件悬停态下的悬浮效果。 |
## 示例
......
......@@ -13,7 +13,7 @@
| 名称 | 参数类型 | 默认值 | 描述 |
| -------- | -------- | -------- | -------- |
| ----------------------------- | ---------------------------------------- | ------ | ---------------------------------------- |
| blur | number | - | 为当前组件添加内容模糊效果,入参为模糊半径,模糊半径越大越模糊,为0时不模糊。 |
| backdropBlur | number | - | 为当前组件添加背景模糊效果,入参为模糊半径,模糊半径越大越模糊,为0时不模糊。 |
| shadow | {<br/>radius:&nbsp;number,<br/>color?:&nbsp;Color,<br/>offsetX?:&nbsp;number,<br/>offsetY?:&nbsp;number<br/>} | - | 为当前组件添加阴影效果,入参为模糊半径(必填)、阴影的颜色(可选,默认为灰色)、X轴的偏移量(可选,默认为0),Y轴的偏移量(可选,默认为0),偏移量单位为px。 |
......@@ -26,9 +26,10 @@
| sepia | number | 0 | 将图像转换为深褐色。入参为图像反转的比例。值为1则完全是深褐色的,值为0图像无变化。&nbsp;(百分比) |
| hueRotate | number \| string | '0deg' | 为当前组件添加色相旋转效果,入参为旋转的角度值,0deg时图像无变化。入参没有最大值,超过360deg时相当于又绕一圈,即,370deg和10deg的色相旋转效果相同。 |
## 示例
示例效果请以真机运行为准,当前IDE预览器不支持
```ts
// xxx.ets
@Entry
......
......@@ -15,19 +15,12 @@
| 名称 | 参数类型 | 默认值 | 描述 |
| ---------- | ---------------------------------------- | ------------------------------------ | ---------------------------------------- |
| align | [Alignment](ts-appendix-enums.md#alignment枚举说明) | Center | 设置元素内容的对齐方式,只有当设置的width和height大小超过元素本身内容大小时生效。 |
| direction | Direction | Auto | 设置元素水平方向的布局,可选值参照Direction枚举说明。 |
| align | [Alignment](ts-appendix-enums.md#alignment) | Center | 设置元素内容的对齐方式,只有当设置的width和height大小超过元素本身内容大小时生效。 |
| direction | [Direction](ts-appendix-enums.md#direction) | Auto | 设置元素水平方向的布局,可选值参照Direction枚举说明。 |
| position | {<br/>x:&nbsp;Length,<br/>y:&nbsp;Length<br/>} | - | 使用绝对定位,设置元素锚点相对于父容器顶部起点偏移位置。在布局容器中,设置该属性不影响父容器布局,仅在绘制时进行位置调整。 |
| markAnchor | {<br/>x:&nbsp;Length,<br/>y:&nbsp;Length<br/>} | {<br/>x:&nbsp;0,<br/>y:&nbsp;0<br/>} | 设置元素在位置定位时的锚点,以元素顶部起点作为基准点进行偏移。 |
| offset | {<br/>x:&nbsp;Length,<br/>y:&nbsp;Length<br/>} | {<br/>x:&nbsp;0,<br/>y:&nbsp;0<br/>} | 相对布局完成位置坐标偏移量,设置该属性,不影响父容器布局,仅在绘制时进行位置调整。 |
## Direction枚举说明
| 名称 | 描述 |
| ---- | ----------- |
| Ltr | 元素从左到右布局。 |
| Rtl | 元素从右到左布局。 |
| Auto | 使用系统默认布局方向。 |
## 示例
......
......@@ -16,7 +16,7 @@
| 名称 | 参数类型 | 默认值 | 描述 |
| ---------------------------- | ---------------------------------------- | ---- | ---------------------------------- |
| bindMenu | Array<MenuItem&gt;&nbsp;\|&nbsp;[CustomBuilder](../../ui/ts-types.md)<sup>8+</sup> | - | 给组件绑定菜单,点击后弹出菜单。弹出菜单项支持文本和自定义两种功能。 |
| bindContextMenu<sup>8+</sup> | content:&nbsp;[CustomBuilder](../../ui/ts-types.md)<br>responseType:&nbsp;ResponseType | - | 给组件绑定菜单,触发方式为长按或者右键点击,弹出菜单项需要自定义。 |
| bindContextMenu<sup>8+</sup> | content:&nbsp;[CustomBuilder](../../ui/ts-types.md)<br>responseType:&nbsp;[ResponseType](ts-appendix-enums.md#responsetype8) | - | 给组件绑定菜单,触发方式为长按或者右键点击,弹出菜单项需要自定义。 |
## MenuItem
......@@ -25,12 +25,6 @@
| value | string | 菜单项文本。 |
| action | ()&nbsp;=&gt;&nbsp;void | 点击菜单项的事件回调。 |
## ResponseType<sup>8+</sup>
| 参数值 | 描述 |
| ---------- | ------------- |
| LongPress | 通过长按触发菜单弹出。 |
| RightClick | 通过鼠标右键触发菜单弹出。 |
## 示例
......@@ -41,6 +35,7 @@
@Entry
@Component
struct MenuExample {
build() {
Column() {
Text('click for Menu')
......@@ -69,8 +64,9 @@ struct MenuExample {
#### 自定义内容菜单
```
import router from '@system.router';
```ts
// xxx.ets
import router from '@system.router'
@Entry
@Component
......
......@@ -32,25 +32,13 @@
| 名称 | 类型 | 必填 | 默认值 | 描述 |
| ------------- | ---------------------------------------- | ---- | ---------------- | ------------------------------ |
| builder | ()&nbsp;=&gt;&nbsp;any | 是 | - | 提示气泡内容的构造器。 |
| placement | Placement | 否 | Placement.Bottom | 气泡组件优先显示的位置,当前位置显示不下时,会自动调整位置。 |
| placement | [Placement](ts-appendix-enums.md#placement8) | 否 | Placement.Bottom | 气泡组件优先显示的位置,当前位置显示不下时,会自动调整位置。 |
| maskColor | [Color](../../ui/ts-types.md#颜色类型) | 否 | - | 提示气泡遮障层的颜色。 |
| popupColor | [Color](../../ui/ts-types.md#颜色类型) | 否 | - | 提示气泡的颜色。 |
| enableArrow | boolean | 否 | true | 是否显示箭头,只有上、下方向的气泡会显示箭头。 |
| autoCancel | boolean | 否 | true | 页面有操作时,是否自动关闭气泡 |
| onStateChange | (isVisible:&nbsp;boolean)&nbsp;=&gt;&nbsp;void | 否 | - | 弹窗状态变化事件回调,参数为弹窗当前的显示状态。 |
## Placement<sup>8+</sup>枚举说明
| 名称 | 描述 |
| ----------- | ------------ |
| Left | 气泡提示位于组件左侧。 |
| Right | 气泡提示位于组件右侧。 |
| Top | 气泡提示位于组件上侧。 |
| Bottom | 气泡提示位于组件下侧。 |
| TopLeft | 气泡提示位于组件左上角。 |
| TopRight | 气泡提示位于组件右上角。 |
| BottomLeft | 气泡提示位于组件左下角。 |
| BottomRight | 气泡提示位于组件右下角。 |
## 示例
......
......@@ -21,11 +21,12 @@
## 示例
```
```ts
// xxx.ets
@Entry
@Component
struct ClipAndMaskExample {
build() {
Column({ space: 5 }) {
Text('clip').fontSize(9).width('90%').fontColor(0xCCCCCC)
......
......@@ -14,14 +14,14 @@
| 名称 | 参数说明 | 默认值 | 描述 |
| -------------- | ---------------------------------------- | ---------------------------------------- | ---------------------------------------- |
| -------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ |
| width | Length | - | 设置组件自身的宽度,缺省时使用元素自身内容需要的宽度。 |
| height | Length | - | 设置组件自身的高度,缺省时使用元素自身内容需要的高度。 |
| size | {<br/>width?:&nbsp;Length,<br/>height?:&nbsp;Length<br/>} | - | 设置高宽尺寸。 |
| padding | {<br/>top?:&nbsp;Length,<br/>right?:&nbsp;Length,<br/>bottom?:&nbsp;Length,<br/>left?:&nbsp;Length<br/>}&nbsp;\|&nbsp;Length | 0 | 设置内边距属性。<br/>参数为Length类型时,四个方向内边距同时生效。 |
| margin | {<br/>top?:&nbsp;Length,<br/>right?:&nbsp;Length,<br/>bottom?:&nbsp;Length,<br/>left?:&nbsp;Length<br/>}<br/>\|&nbsp;Length | 0 | 设置外边距属性。<br/>参数为Length类型时,四个方向外边距同时生效。 |
| constraintSize | {<br/>minWidth?:&nbsp;Length,<br/>maxWidth?:&nbsp;Length,<br/>minHeight?:&nbsp;Length,<br/>maxHeight?:&nbsp;Length<br/>} | {<br/>minWidth:&nbsp;0,<br/>maxWidth:&nbsp;Infinity,<br/>minHeight:&nbsp;0,<br/>maxHeight:&nbsp;Infinity<br/>} | 设置约束尺寸,组件布局时,进行尺寸范围限制。 |
| layoutWeight | number | 0 | 容器尺寸确定时,元素与兄弟节点主轴布局尺寸按照权重进行分配,忽略本身尺寸设置<br/>>&nbsp;&nbsp;**说明:**<br/>>&nbsp;仅在Row/Column/Flex布局中生效。 |
| layoutWeight | number | 0 | 容器尺寸确定时,元素与兄弟节点主轴布局尺寸按照权重进行分配,忽略本身尺寸设置,表示自适应占满剩余空间<br/>>&nbsp;&nbsp;**说明:**<br/>>&nbsp;仅在Row/Column/Flex布局中生效。 |
## 示例
......
......@@ -20,27 +20,10 @@
| ---------- | ------------------------ | --------------------------- | ---------------------------------------- |
| fontColor | Color | - | 设置文本颜色。 |
| fontSize | Length | - | 设置文本尺寸,Length为number类型时,使用fp单位。 |
| fontStyle | FontStyle | FontStyle.Normal | 设置文本的字体样式。 |
| fontWeight | number&nbsp;\|FontWeight | FontWeight.FontWeightNormal | 设置文本的字体粗细,number类型取值[100,&nbsp;900],取值间隔为100,默认为400,取值越大,字体越粗。<br/>提供常用枚举值,参考:FontWeight枚举说明。 |
| fontStyle | [FontStyle](ts-appendix-enums.md#fontstyle) | FontStyle.Normal | 设置文本的字体样式。 |
| fontWeight | number&nbsp;\|[FontWeight](ts-appendix-enums.md#fontweight) | FontWeight.FontWeightNormal | 设置文本的字体粗细,number类型取值[100,&nbsp;900],取值间隔为100,默认为400,取值越大,字体越粗。<br/>提供常用枚举值,参考:FontWeight枚举说明。 |
| fontFamily | string | - | 设置文本的字体列表。使用多个字体,使用','进行分割,优先级按顺序生效。例如:'Arial,&nbsp;sans-serif'。 |
## FontStyle枚举说明
| 名称 | 描述 |
| ------ | -------- |
| Normal | 标准的字体样式。 |
| Italic | 斜体的字体样式。 |
## FontWeight枚举说明
| 名称 | 描述 |
| ------- | ------- |
| Lighter | 字体较细。 |
| Normal | 字体粗细正常。 |
| Regular | 字体粗细正常。 |
| Medium | 字体粗细适中。 |
| Bold | 字体较粗。 |
| Bolder | 字体非常粗。 |
## 示例
......
......@@ -23,12 +23,14 @@
## 示例
```
```ts
// xxx.ets
import Matrix4 from '@ohos.matrix4'
@Entry
@Component
struct TransformExample {
build() {
Column() {
Text('rotate').width('90%').fontColor(0xCCCCCC).padding(15).fontSize(30)
......
......@@ -15,15 +15,8 @@
| 名称 | 参数类型 | 默认值 | 描述 |
| ---------- | ---------- | ------------------ | ------------ |
| visibility | Visibility | Visibility.Visible | 控制当前组件显示或隐藏。 |
| visibility | [Visibility](ts-appendix-enums.md#visibility) | Visibility.Visible | 控制当前组件显示或隐藏。 |
## Visibility枚举说明
| 名称 | 描述 |
| ------- | ---------------- |
| Hidden | 隐藏,但参与布局进行占位。 |
| Visible | 显示。 |
| None | 隐藏,但不参与布局,不进行占位。 |
## 示例
......
......@@ -25,10 +25,10 @@
| 属性名称 | 类型 | 描述 |
| ------------------------------------- | --------------------------- | -------------------------- |
| type | [KeyType](#keytype枚举说明) | 按键的类型。 |
| type | [KeyType](ts-appendix-enums.md#keytype) | 按键的类型。 |
| [keyCode](../apis/js-apis-keycode.md) | number | 按键的键码。 |
| keyText | string | 按键的键值。 |
| keySource | [KeySource](#keysource枚举说明) | 触发当前按键的输入设备类型。 |
| keySource | [KeySource](ts-appendix-enums.md#keysource) | 触发当前按键的输入设备类型。 |
| deviceId | number | 触发当前按键的输入设备ID。 |
| metaKey | number | 按键发生时元键的状态,1表示按压态,0表示未按压态。 |
| timestamp | number | 按键发生时的时间戳。 |
......@@ -39,21 +39,6 @@
| ---------------------------- | --------- |
| stopPropagation():&nbsp;void | 阻塞事件冒泡传递。 |
## KeyType枚举说明
| 名称 | 描述 |
| ---- | ----- |
| Down | 按键按下。 |
| Up | 按键松开。 |
## KeySource枚举说明
| 名称 | 描述 |
| -------- | ---------- |
| Unknown | 输入设备类型未知。 |
| Keyboard | 输入设备类型为键盘。 |
## 示例
......
......@@ -20,7 +20,8 @@
## 示例
```
```ts
// xxx.ets
import prompt from '@system.prompt'
@Entry
......
......@@ -22,11 +22,11 @@
### 属性
| 属性名称 | 类型 | 描述 |
| ------------------- | ---------------------------------------- | ------------ |
| type | TouchType | 触摸事件的类型。 |
| ------------------- | ------------------------------------------------------------ | ---------------------------------- |
| type | [TouchType](ts-appendix-enums.md#touchtype) | 触摸事件的类型。 |
| touches | Array&lt;[TouchObject](#touchobject对象说明)&gt; | 全部手指信息。 |
| changedTouches | Array&lt;[TouchObject](#touchobject对象说明)&gt; | 当前发生变化的手指信息。 |
| timestamp | number | 事件时间戳。 |
| timestamp | number | 距离开机时间的时间戳,单位为毫秒。 |
| target<sup>8+</sup> | [EventTarget](ts-universal-events-click.md#eventtarget8对象说明) | 被触摸元素对象。 |
### 接口
......@@ -38,23 +38,13 @@
## TouchObject对象说明
| 属性名称 | 类型 | 描述 |
| ------- | --------------------------- | ------------------- |
| type | [TouchType](#touchtype枚举说明) | 触摸事件的类型。 |
| type | [TouchType](ts-appendix-enums.md#touchtype) | 触摸事件的类型。 |
| id | number | 手指唯一标识符。 |
| screenX | number | 触摸点相对于设备屏幕左边沿的X坐标。 |
| screenY | number | 触摸点相对于设备屏幕上边沿的Y坐标。 |
| x | number | 触摸点相对于被触摸元素左边沿的X坐标。 |
| y | number | 触摸点相对于被触摸元素上边沿的Y坐标。 |
## TouchType枚举说明
| 名称 | 描述 |
| ------ | --------------- |
| Down | 手指按下时触发。 |
| Up | 手指抬起时触发。 |
| Move | 手指按压态在屏幕上移动时触发。 |
| Cancel | 触摸事件取消时触发。 |
## 示例
```ts
......
......@@ -26,27 +26,8 @@
| screenY | number | 点击触点相对于屏幕左上角的y轴坐标。 |
| x | number | 点击触点相对于当前组件左上角的x轴坐标。 |
| y | number | 点击触点相对于当前组件左上角的y轴坐标。 |
| button | [MouseButton](#mousebutton类型说明) | 鼠标按键。 |
| action | [MouseAction](#mouseaction类型说明) | 事件动作。 |
## MouseButton类型说明
| 属性名称 | 属性类型 | 描述 |
| ------- | ------ | -------- |
| Left | number | 鼠标左键。 |
| Right | number | 鼠标右键。 |
| Middle | number | 鼠标中键。 |
| Back | number | 鼠标左侧后退键。 |
| Forward | number | 鼠标左侧前进键。 |
| None | number | 无按键。 |
## MouseAction类型说明
| 属性名称 | 属性类型 | 描述 |
| ------- | ------ | ------- |
| Press | number | 鼠标按键按下。 |
| Release | number | 鼠标按键松开。 |
| Move | number | 鼠标移动。 |
| button | [MouseButton](ts-appendix-enums.md#mousebutton) | 鼠标按键。 |
| action | [MouseAction](ts-appendix-enums.md#mouseaction) | 事件动作。 |
## 示例
......
......@@ -7,7 +7,7 @@
## 长度类型
| 名称 | 类型定义 | 描述 |
| -------- | -------- | -------- |
| ---------- | -------------------------- | ---------------------------------------- |
| length | string&nbsp;\|&nbsp;number | 用于描述尺寸单位,输入为number类型时,使用px单位。输入为string类型时,需要显式指定像素单位,当前支持的像素单位有:<br/>-&nbsp;px:逻辑尺寸单位。<br/>-&nbsp;fp:字体尺寸单位,随系统字体大小设置发生变化,仅支持文本类组件设置相应的字体大小。 |
| percentage | string | 百分比尺寸单位,如“50%”。 |
......@@ -15,13 +15,13 @@
## 颜色类型
| 名称 | 类型定义 | 描述 |
| -------- | -------- | -------- |
| ----- | ------------------ | ---------------------------------------- |
| color | string&nbsp;\|颜色枚举 | 用于描述颜色信息。<br/>&nbsp;&nbsp;字符串格式如下:<br/>-&nbsp;'rgb(255,&nbsp;255,&nbsp;255)'。<br/>-&nbsp;'rgba(255,&nbsp;255,&nbsp;255,&nbsp;1.0)'。<br/>-&nbsp;HEX格式:'\#rrggbb','\#aarrggbb'。<br/>-&nbsp;枚举格式:'black','white'。<br/>JS脚本中不支持颜色枚举格式。 |
**表1** 当前支持的颜色枚举
| 枚举名称 | 对应颜色 | 颜色 |
| -------- | -------- | -------- |
| -------------------- | -------- | ---------------------------------------- |
| aliceblue | \#f0f8ff | ![aliceblue](figures/aliceblue.png) |
| antiquewhite | \#faebd7 | ![antiquewhite](figures/antiquewhite.png) |
| aqua | \#00ffff | ![aqua](figures/aqua.png) |
......@@ -29,7 +29,7 @@
| azure | \#f0ffff | ![azure](figures/azure.png) |
| beige | \#f5f5dc | ![beige](figures/beige.png) |
| bisque | \#ffe4c4 | ![bisque](figures/bisque.png) |
| black | \#000000 | ![#000000](figures/#000000.png) |
| black | \#000000 | ![000000](figures/000000.png) |
| blanchedalmond | \#ffebcd | ![blanchedalmond](figures/blanchedalmond.png) |
| blue | \#0000ff | ![blue](figures/blue.png) |
| blueviolet | \#8a2be2 | ![blueviolet](figures/blueviolet.png) |
......
......@@ -17,7 +17,7 @@
支持[通用属性](js-service-widget-common-attributes.md)外,还支持如下属性:
| 名称 | 类型 | 默认值 | 必填 | 描述 |
| -------- | -------- | -------- | -------- | -------- |
| -------------- | ------ | ----- | ---- | ---------------------------------------- |
| date | string | 当前日期 | 否 | 当前页面选中的日期,默认是当前日期,格式为年-月-日,如"2019-11-22"。 |
| cardcalendar | bool | false | 否 | 标识当前日历是否为卡片日历。 |
| startdayofweek | int | 6 | 否 | 标识卡片显示的起始天,默认是星期天(取值范围:0-6)。 |
......@@ -28,7 +28,7 @@
**表1** calendardata的日属性
| 名称 | 类型 | 描述 |
| -------- | -------- | -------- |
| -------------- | ------ | --------------------------------------- |
| index | int | 数据的索引,表示第几个日期。 |
| day | int | 表示具体哪一天。 |
| month | int | 表示月份。 |
......@@ -43,7 +43,7 @@
calendardata示例:
```json
```
{
"year":2021,
"month":1,
......@@ -94,21 +94,21 @@ calendardata示例:
## 样式
| 名称 | 类型 | 默认值 | 必填 | 描述 |
| -------- | -------- | -------- | -------- | -------- |
| ---------------- | ------------- | ---- | ---- | ------- |
| background-color | &lt;color&gt; | - | 否 | 设置背景颜色。 |
## 事件
| 名称 | 参数 | 描述 |
| -------- | -------- | -------- |
| -------------- | ------------ | --------------- |
| selectedchange | changeEvent | 在点击日期和上下月跳转时触发。 |
| requestdata | requestEvent | 请求日期时触发。 |
**表2** changeEvent
| 名称 | 类型 | 描述 |
| -------- | -------- | -------- |
| ------------ | ------ | ------ |
| $event.day | string | 选择的日期。 |
| $event.month | string | 选择的月份。 |
| $event.year | string | 选择的年份。 |
......@@ -116,7 +116,7 @@ calendardata示例:
**表3** requestEvent
| 名称 | 类型 | 描述 |
| -------- | -------- | -------- |
| ------------------- | ------ | -------- |
| $event.month | string | 请求的月份。 |
| $event.year | string | 请求的年份。 |
| $event.currentYear | string | 当前显示的年份。 |
......@@ -160,7 +160,6 @@ calendardata示例:
```json
// xxx.json
{
"data": {
"currentDate": "",
......
......@@ -17,7 +17,7 @@
除支持[通用属性](js-service-widget-common-attributes.md)外,还支持如下属性:
| 名称 | 类型 | 默认值 | 必填 | 描述 |
| -------- | -------- | -------- | -------- | -------- |
| ----------------- | ---------------------------------- | ---- | ---- | ---------------------------------------- |
| type | string | line | 否 | 设置图表类型(不支持动态修改),可选项有:<br/>-&nbsp;bar:柱状图。<br/>-&nbsp;line:线形图。<br/>-&nbsp;gauge:量规图。<br/>-&nbsp;progress:进度类圆形图表。<br/>-&nbsp;loading:加载类圆形图表。<br/>-&nbsp;rainbow:占比类圆形图表。 |
| options | ChartOptions | - | 否 | 图表参数设置,柱状图和线形图必须设置参数设置,量规图不生效。可以设置x轴、y轴的最小值、最大值、刻度数、是否显示,线条宽度、是否平滑等。(不支持动态修改) |
| datasets | Array\<ChartDataset> | - | 否 | 数据集合,柱状图和线形图必须设置数据集合,量规图不生效。可以设置多条数据集及其背景色。 |
......@@ -28,7 +28,7 @@
**表1** ChartOptions
| 名称 | 类型 | 默认值 | 必填 | 描述 |
| -------- | -------- | -------- | -------- | -------- |
| ------ | --------- | ---- | ---- | ---------------------------------------- |
| xAxis | ChartAxis | - | 是 | x轴参数设置。可以设置x轴最小值、最大值、刻度数以及是否显示。 |
| yAxis | ChartAxis | - | 是 | y轴参数设置。可以设置y轴最小值、最大值、刻度数以及是否显示。 |
| series | ChartAxis | - | 否 | 数据序列参数设置,仅线形图支持。可以设置:<br>- 线的样式,如线宽、是否平滑。<br>- 线最前端位置白点的样式和大小。 |
......@@ -36,7 +36,7 @@
**表2** ChartDataset
| 名称 | 类型 | 默认值 | 必填 | 描述 |
| -------- | -------- | -------- | -------- | -------- |
| ----------- | ---------------------------------------- | -------- | ---- | -------------------- |
| strokeColor | &lt;color&gt; | \#ff6384 | 否 | 线条颜色,仅线形图支持。 |
| fillColor | &lt;color&gt; | \#ff6384 | 否 | 填充颜色,线形图表示填充的渐变颜色。 |
| data | Array&lt;number&gt;&nbsp;\|&nbsp;Array\<Point&gt; | - | 是 | 设置绘制线或柱中的点集。 |
......@@ -45,7 +45,7 @@
**表3** ChartAxis
| 名称 | 类型 | 默认值 | 必填 | 描述 |
| -------- | -------- | -------- | -------- | -------- |
| -------- | ------------- | -------- | ---- | ---------------------------------------- |
| min | number | 0 | 否 | 轴的最小值,不支持负数,仅线形图支持。 |
| max | number | 100 | 否 | 轴的最大值,不支持负数,仅线形图支持。 |
| axisTick | number | 10 | 否 | 轴显示的刻度数量。<br/>仅支持1~20,且具体显示的效果与如下计算值有关(图的宽度所占的像素/(max-min))。在柱状图中,每组数据显示的柱子数量与刻度数量一致,且柱子显示在刻度处。 |
......@@ -55,7 +55,7 @@
**表4** ChartSeries
| 名称 | 类型 | 默认值 | 必填 | 描述 |
| -------- | -------- | -------- | -------- | -------- |
| ----------- | -------------- | ---- | ---- | -------------------- |
| lineStyle | ChartLineStyle | - | 否 | 线样式设置,如线宽、是否平滑。 |
| headPoint | PointStyle | - | 否 | 线最前端位置白点的样式和大小。 |
| topPoint | PointStyle | - | 否 | 最高点的样式和大小。 |
......@@ -65,14 +65,14 @@
**表5** ChartLineStyle
| 名称 | 类型 | 默认值 | 必填 | 描述 |
| -------- | -------- | -------- | -------- | -------- |
| ------ | -------------- | ----- | ---- | ----- |
| width | &lt;length&gt; | 1px | 否 | 线宽设置。 |
| smooth | boolean | false | 否 | 是否平滑。 |
**表6** PointStyle
| 名称 | 类型 | 默认值 | 必填 | 描述 |
| -------- | -------- | -------- | -------- | -------- |
| ----------- | -------------- | -------- | ---- | ---------------------------------------- |
| shape | string | circle | 否 | 高亮点的形状。可选值为:<br/>-&nbsp;circle:圆形。<br/>-&nbsp;square:方形。<br/>-&nbsp;triangle:三角形。 |
| size | &lt;length&gt; | 5px | 否 | 高亮点的大小。 |
| strokeWidth | &lt;length&gt; | 1px | 否 | 边框宽度。 |
......@@ -82,14 +82,14 @@
**表7** ChartLoop
| 名称 | 类型 | 默认值 | 必填 | 描述 |
| -------- | -------- | -------- | -------- | -------- |
| -------- | -------------- | ----- | ---- | ---------------------------------------- |
| margin | &lt;length&gt; | 1 | 否 | 擦除点的个数(最新绘制的点与最老的点之间的横向距离)。<br>margin和topPoint/bottomPoint/headPoint同时使用时,有概率出现point正好位于擦除区域的情况,导致point不可见,因此不建议同时使用。 |
| gradient | boolean | false | 否 | 是否需要渐变擦除。 |
**表8** Point
| 名称 | 类型 | 默认值 | 必填 | 描述 |
| -------- | -------- | -------- | -------- | -------- |
| ------------ | ------------- | -------- | ---- | ---------------------------------------- |
| value | number | 0 | 是 | 表示绘制点的Y轴坐标。 |
| pointStyle | PointStyle | - | 否 | 表示当前数据点的绘制样式。 |
| description | string | - | 否 | 表示当前点的注释内容。 |
......@@ -101,14 +101,14 @@
**表9** DataSegment
| 名称 | 类型 | 默认值 | 必填 | 描述 |
| -------- | -------- | -------- | -------- | -------- |
| ---------- | ------ | ---- | ---- | ---------------------------------------- |
| startColor | Color | - | 否 | 起始位置的颜色,设置startColor必须设置endColor。不设置startColor时,会使用系统默认预置的颜色数组,具体颜色值见下表。 |
| endColor | Color | - | 否 | 终止位置的颜色,设置endColor必须设置startColor。<br/>不设置startColor时,会使用系统默认预置的颜色数组。 |
| value | number | 0 | 是 | 占比数据的所占份额,最大100。 |
| name | string | - | 否 | 此类数据的名称。 |
| 数据组 | 主题 | 深色主题 |
| -------- | -------- | -------- |
| ---- | --------------------------- | --------------------------- |
| 0 | 起始颜色:\#f7ce00,结束颜色:\#f99b11 | 起始颜色:\#d1a738,结束颜色:\#eb933d |
| 1 | 起始颜色:\#f76223,结束颜色:\#f2400a | 起始颜色:\#e67d50,结束颜色:\#d9542b |
| 2 | 起始颜色:\#f772ac,结束颜色:\#e65392 | 起始颜色:\#d5749e,结束颜色:\#d6568d |
......@@ -122,7 +122,7 @@
当类型为量规图时,还支持如下属性:
| 名称 | 类型 | 默认值 | 必填 | 描述 |
| -------- | -------- | -------- | -------- | -------- |
| ------- | ------ | ---- | ---- | ---------------------- |
| percent | number | 0 | 否 | 当前值占整体的百分比,取值范围为0-100。 |
......@@ -131,7 +131,7 @@
除支持[通用样式](js-service-widget-common-styles.md)外,还支持如下样式:
| 名称 | 类型 | 默认值 | 必填 | 描述 |
| -------- | -------- | -------- | -------- | -------- |
| ------------ | -------------- | -------------------------- | ---- | ---------------------------------------- |
| stroke-width | &lt;length&gt; | 32px(量规)<br/>24px(占比类圆形图表) | 否 | 量规、占比类圆形图表组件刻度条的宽度。 |
| start-angle | &lt;deg&gt; | 240(量规)<br/>0(占比类圆形图表) | 否 | 量规、占比类圆形图表组件刻度条起始角度,以时钟0点为基线。范围为0到360。 |
| total-angle | &lt;deg&gt; | 240(量规)<br/>360(占比类圆形图表) | 否 | 量规、占比类圆形图表组件刻度条总长度,范围为-360到360,负数标识起点到终点为逆时针。 |
......@@ -186,7 +186,6 @@
```json
// xxx.json
{
"data": {
"lineData": [
......@@ -251,7 +250,7 @@
}
}
```
**4*4卡片**
**4*4卡片**
![zh-cn_image_0000001185652902](figures/zh-cn_image_0000001185652902.png)
......@@ -290,7 +289,6 @@
```json
// xxx.json
{
"data": {
"barData": [
......@@ -323,7 +321,7 @@
}
}
```
**4*4卡片**
**4*4卡片**
![barchart](figures/barchart.PNG)
......@@ -356,6 +354,6 @@
weights: 4, 2, 1;
}
```
**4*4卡片**
**4*4卡片**
![gauge](figures/gauge.PNG)
......@@ -17,7 +17,7 @@
除支持[通用属性](js-service-widget-common-attributes.md)外,还支持如下属性:
| 名称 | 类型 | 默认值 | 必填 | 描述 |
| -------- | -------- | -------- | -------- | -------- |
| ----------- | ----------- | ---- | ---- | ---------------------------------------- |
| clockconfig | ClockConfig | - | 是 | Clock的图片资源和样式设置,包括日间时段(6:00-18:00)和夜间时段(18:00-次日6:00)两套资源和样式设置。<br/>其中每套资源和样式包括表盘资源、时针指针资源、分针指针资源、秒针指针资源四张图和相应时间段的表盘数字颜色。<br/>日间资源为必填项。夜间资源可不填,不填时默认会复用日间资源用作夜间时段的显示。<br/>仅支持动态更新整个Object,不支持动态更新Object里的内容。<br/>建议使用PNG资源作为Clock组件的图片资源。<br/>不支持使用SVG资源作为Clock组件的图片资源。 |
| showdigit | boolean | true | 否 | 是否由Clock组件绘制表盘数字。<br/>该属性为true时,请留意clockconfig中digitRadiusRatio和digitSizeRatio参数与表盘的匹配情况。<br/>由Clock组件绘制的表盘数字支持国际化。 |
| hourswest | number | - | 否 | 时钟的时区偏移值,时区为标准时区减去hourswest。<br/>有效范围为[-12,&nbsp;12],其中负值范围表示东时区,比如东八区对应的是-8。不设置默认采用系统时间所在的时区。 |
......@@ -25,7 +25,7 @@
**表1** ClockConfig
| 名称 | 类型 | 默认值 | 必填 | 描述 |
| -------- | -------- | -------- | -------- | -------- |
| ---------------- | -------------- | --------------- | ---- | ---------------------------------------- |
| face | &lt;string&gt; | - | 是 | 日间时段的表盘资源路径。<br/>表盘资源须为包含时钟刻度的正方形图片,表盘区域(圆形)为该图片的内切圆或内切圆的同心圆。如果表盘区域为表盘资源内切圆的同心圆的话,请相应调整digitRadiusRatio和digitSizeRatio参数。 |
| hourHand | &lt;string&gt; | - | 是 | 日间时段的时针资源路径。<br/>- 时针图片的高度须与表盘资源高度相同。<br/>- 时针图片的宽高比建议在0.062。<br/>- 时针图片上指针的旋转中心须处于时针图片的中心(对角线交点)。<br/>- 夜间时段的时针资源请调整hourHandNight参数。 |
| minuteHand | &lt;string&gt; | - | 是 | 日间时段的分针资源路径。<br/>- 分针图片的高度须与表盘资源高度相同。<br/>- 分针图片的宽高比建议在0.062。<br/>- 分针图片上指针的旋转中心须处于分针图片的中心(对角线交点)。<br/>-&nbsp;夜间时段的分针资源请调整minuteHandNight参数。 |
......@@ -47,7 +47,7 @@
除支持[通用样式](js-service-widget-common-styles.md)之外,还支持如下样式:
| 名称 | 类型 | 默认值 | 必填 | 描述 |
| -------- | -------- | -------- | -------- | -------- |
| ----------- | -------------- | ---------- | ---- | ---------------------------------------- |
| font-family | &lt;string&gt; | sans-serif | 否 | 表盘数字的字体列表,用逗号分隔,每个字体用字体名或者字体族名设置。列表中第一个系统中存在的或者通过2.1.6&nbsp;自定义字体样式指定的字体,会被选中作为文本的字体。 |
> **说明:**
......@@ -58,7 +58,7 @@
## 事件
| 名称 | 参数 | 描述 |
| -------- | -------- | -------- |
| ---- | ------------------- | --------- |
| hour | {hour:&nbsp;number} | 每个整点触发该事件 |
......@@ -101,7 +101,6 @@
```json
// xxx.json
{
"data": {
"clockconfig": {
......
......@@ -12,7 +12,7 @@
除支持[通用属性](js-service-widget-common-attributes.md)外,还支持如下属性:
| 名称 | 类型 | 默认值 | 必填 | 描述 |
| -------- | -------- | -------- | -------- | -------- |
| ------- | ------- | ----- | ---- | ---------------------------------------- |
| type | string | radio | 是 | input组件类型,当前仅支持radio类型:<br/>-&nbsp;"radio":定义单选按钮,允许在多个拥有相同name值的选项中选中其中一个; |
| checked | boolean | false | 否 | 当前组件是否选中。 |
| name | string | - | 否 | input组件的名称。 |
......@@ -27,7 +27,7 @@
## 事件
| 名称 | 参数 | 描述 |
| -------- | -------- | -------- |
| ------ | ------------------ | ---------------------------------------- |
| change | $event.checkedItem | radio单选框的checked状态发生变化时触发该事件,返回选中的组件value值。 |
| click | - | 点击动作触发该事件。 |
......@@ -57,7 +57,6 @@
```json
// xxx.json
{
"actions": {
"onRadioChange":{
......
......@@ -4,7 +4,7 @@
> **说明:**
>
>从API Version 8 开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
> 从API Version 8 开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
开发框架支持线性渐变 (linear-gradient)和重复线性渐变 (repeating-linear-gradient)两种渐变效果。
......@@ -36,7 +36,7 @@ background: repeating-linear-gradient(direction/angle, color, color, ...);
- 参数
| 名称 | 类型 | 默认值 | 必填 | 描述 |
| -------- | -------- | -------- | -------- | -------- |
| --------- | ---------------------------------------- | ---------------------------- | ---- | ---------------------------------------- |
| direction | to&nbsp;&lt;side-or-corner&gt;&nbsp;&nbsp;&lt;side-or-corner&gt;&nbsp;=&nbsp;[left&nbsp;\|&nbsp;right]&nbsp;\|\|&nbsp;[top&nbsp;\|&nbsp;bottom] | to&nbsp;bottom&nbsp;(由上到下渐变) | 否 | 指定过渡方向,如:to&nbsp;left&nbsp;(从右向左渐变)&nbsp;&nbsp;,或者to&nbsp;bottom&nbsp;right&nbsp;(从左上角到右下角)。 |
| angle | &lt;deg&gt; | 180deg | 否 | 指定过渡方向,以元素几何中心为坐标原点,水平方向为X轴,angle指定了渐变线与Y轴的夹角(顺时针方向)。 |
| color | &lt;color&gt;&nbsp;[&lt;length&gt;\|&lt;percentage&gt;] | - | 是 | 定义使用渐变样式区域内颜色的渐变效果。 |
......
......@@ -5,7 +5,7 @@ js标签中包含了实例名称、窗口样式和卡片页面信息。
| 标签 | 类型 | 默认值 | 必填 | 描述 |
| -------- | -------- | -------- | -------- | -------- |
| ------ | ------ | ------- | ---- | --------------------------- |
| name | String | default | 是 | 标识JS实例的名字。 |
| pages | Array | - | 是 | 路由信息,详见“[pages](#pages)”。 |
| window | Object | - | 否 | 窗口信息,详见“[window](#window)”。 |
......@@ -47,12 +47,11 @@ window用于定义与显示窗口相关的配置。对于卡片尺寸适配问
> - autoDesignWidth、designWidth的设置不影响默认值计算方式和绘制结果。
| 属性 | 类型 | 必填 | 默认值 | 描述 |
| -------- | -------- | -------- | -------- | -------- |
| --------------- | ------- | ---- | ----- | ---------------------------------------- |
| designWidth | number | 否 | 150px | 页面显示设计时的参考值,实际显示效果基于设备宽度与参考值之间的比例进行缩放。 |
| autoDesignWidth | boolean | 否 | false | 页面设计基准宽度是否自动计算,当设为true时,designWidth将会被忽略,设计基准宽度由设备宽度与屏幕密度计算得出。 |
示例如下:
```
{
...
"window": {
......@@ -60,7 +59,6 @@ window用于定义与显示窗口相关的配置。对于卡片尺寸适配问
}
...
}
```
## 示例
......
......@@ -43,7 +43,6 @@
```json
// comp.json
{
"data": {
},
......@@ -84,7 +83,6 @@
```json
// xxx.json
{
"data": {
},
......
......@@ -35,7 +35,6 @@
```json
// comp.json
{
"data": {
"progress": {
......
......@@ -35,7 +35,6 @@ HML(OpenHarmony Markup Language)是一套类HTML的标记语言,通过组
```json
// xxx.json
{
"data": {
"content": "Hello World!",
......@@ -74,7 +73,7 @@ HML(OpenHarmony Markup Language)是一套类HTML的标记语言,通过组
通过定义ability名称和携带的参数字段params直接跳转,可用"params"作为key提取到跳转事件定义的params字段值。
| 选择器 | 样例 | 默认值 | 样例描述 |
| -------- | -------- | -------- | -------- |
| ----------- | ------ | -------- | ---------------------------------------- |
| action | string | "router" | 事件类型。<br/>- "router":用于应用跳转。<br/>- "message":自定义点击事件。 |
| abilityName | string | - | 跳转ability名。 |
| params | Object | - | 跳转应用携带的额外参数。 |
......@@ -99,14 +98,14 @@ HML(OpenHarmony Markup Language)是一套类HTML的标记语言,通过组
也可以使用want格式绑定参数跳转到目标应用,want定义了ability名称、包名、携带的参数字段等。
| 选择器 | 类型 | 默认值 | 样例描述 |
| ------ | ------ | -------- | ------------------------------------------------------------ |
| ------ | ------ | -------- | ---------------------------------------- |
| action | string | "router" | 事件类型。<br>- "router":用于应用跳转。<br>- "message":自定义点击事件。 |
| want | Object | - | 跳转目标应用的信息,参考want格式表。 |
**表1** want格式
| 选择器 | 类型 | 默认值 | 样例描述 |
| ----------- | -------------------- | ------------ | ------------------------------------------------------------ |
| ----------- | -------------------- | ------------ | ---------------------------------------- |
| bundleName | string | - | 表示包描述。如果在Want中同时指定了BundleName和AbilityName,则Want可以直接匹配到指定的Ability。 |
| abilityName | string | - | 表示待启动的Ability名称。 |
| action | string | - | 表示action选项描述。 |
......@@ -147,7 +146,7 @@ HML(OpenHarmony Markup Language)是一套类HTML的标记语言,通过组
- 消息事件格式
| 选择器 | 样例 | 默认值 | 样例描述 |
| -------- | -------- | -------- | -------- |
| ------ | ------ | ------- | ------------ |
| action | string | message | 表示事件类型。 |
| params | Object | - | 跳转应用携带的额外参数。 |
......
......@@ -58,7 +58,7 @@ CSS是描述HML页面结构的样式语言。所有组件均存在系统默认
css选择器用于选择需要添加样式的元素,支持的选择器如下表所示:
| 选择器 | 样例 | 样例描述 |
| -------- | -------- | -------- |
| ------------------------- | ------------------------------------- | ---------------------------------------- |
| .class | .container | 用于选择class="container"的组件。 |
| \#id | \#titleId | 用于选择id="titleId"的组件。 |
| tag | text | 用于选择text组件。 |
......@@ -79,7 +79,7 @@ css选择器用于选择需要添加样式的元素,支持的选择器如下
```
/* 页面样式xxx.css */
/\* 对所有div组件设置样式 \*/
/* 对所有div组件设置样式 */
div {
flex-direction: column;
}
......@@ -95,13 +95,13 @@ div {
.title, .content {
padding: 5px;
}
/\* 对class="container"的组件下的所有text设置样式 \*/
/* 对class="container"的组件下的所有text设置样式 */
.container text {
color: \#007dff;
color: #007dff;
}
/\* 对class="container"的组件下的直接后代text设置样式 \*/
/* 对class="container"的组件下的直接后代text设置样式 */
.container &gt; text {
color: \#fa2a2d;
color: #fa2a2d;
}
```
......@@ -125,7 +125,7 @@ css伪类是选择器中的关键字,用于指定要选择元素的特殊状
除了单个伪类之外,还支持伪类的组合,例如,:focus:checked状态可以用来设置元素的focus属性和checked属性同时为true时的样式。支持的单个伪类如下表所示,按照优先级降序排列:
| 名称 | 支持组件 | 描述 |
| -------- | -------- | -------- |
| --------- | ---------------------------------------- | ---------------------------------------- |
| :disabled | 支持disabled属性的组件 | 表示disabled属性变为true时的元素(不支持动画样式的设置)。 |
| :active | 支持click事件的组件<br/> | 表示被用户激活的元素,如:被用户按下的按钮、被激活的tab-bar页签(不支持动画样式的设置)。 |
| :waiting | button | 表示waiting属性为true的元素(不支持动画样式的设置)。 |
......
# @State
@State装饰的变量是组件内部的状态数据,当这些状态数据被修改时,将会调用所在组件的build方法进行UI刷新。
@State装饰的变量是组件内部的状态数据,当这些状态数据被修改时,将会调用所在组件的build方法进行UI刷新,只能监听第一层数据的改变,内层数据的改变@State监听不到,无法触发build生命周期
@State状态数据具有以下特征:
......
......@@ -8,7 +8,10 @@
引用rawfile下资源时使用```"$rawfile('filename')"```的形式,当前$rawfile仅支持Image控件引用图片资源,filename需要表示为rawfile目录下的文件相对路径,文件名需要包含后缀,路径开头不可以以"/"开头。
> **说明:**
>
> 资源描述符不能拼接使用,仅支持普通字符串如`'app.type.name'`。
>
> `$r`返回值为Resource对象,可通过[getString](../../reference/apis/js-apis-resource-manager.md#getstring) 方法获取对应的字符串。
在xxx.ets文件中,可以使用在resources目录中定义的资源。
......
......@@ -27,25 +27,7 @@
| 名称 | 类型定义 | 描述 |
| -------- | -------- | -------- |
| Color | string&nbsp;\|&nbsp;number&nbsp;\|&nbsp;Color | 用于描述颜色信息,输入为string类型时,使用rgb或者rgba进行描述;输入为number类型是,使用HEX格式颜色;输入类型为Color枚举时,使用颜色枚举值。<br/>-&nbsp;'rgb(255,&nbsp;255,&nbsp;255)'。<br/>-&nbsp;'rgba(255,&nbsp;255,&nbsp;255,&nbsp;1.0)'。<br/>-&nbsp;HEX格式:0xrrggbb,0xaarrggbb,'\#FFFFFF'。<br/>-&nbsp;枚举格式:Color.Black,Color.White等。 |
当前支持的Color颜色枚举:
| 颜色名称 | 颜色值 | 颜色示意 |
| -------- | -------- | -------- |
| Black | 0x000000 | ![zh-cn_image_0000001219864153](figures/zh-cn_image_0000001219864153.png) |
| Blue | 0x0000ff | ![zh-cn_image_0000001174104404](figures/zh-cn_image_0000001174104404.png) |
| Brown | 0xa52a2a | ![zh-cn_image_0000001219744201](figures/zh-cn_image_0000001219744201.png) |
| Gray | 0x808080 | ![zh-cn_image_0000001174264376](figures/zh-cn_image_0000001174264376.png) |
| Green | 0x008000 | ![zh-cn_image_0000001174422914](figures/zh-cn_image_0000001174422914.png) |
| Orange | 0xffa500 | ![zh-cn_image_0000001219662661](figures/zh-cn_image_0000001219662661.png) |
| Pink | 0xffc0cb | ![zh-cn_image_0000001219662663](figures/zh-cn_image_0000001219662663.png) |
| Red | 0xff0000 | ![zh-cn_image_0000001219662665](figures/zh-cn_image_0000001219662665.png) |
| White | 0xffffff | ![zh-cn_image_0000001174582866](figures/zh-cn_image_0000001174582866.png) |
| Yellow | 0xffff00 | ![zh-cn_image_0000001174582864](figures/zh-cn_image_0000001174582864.png) |
| Color | string&nbsp;\|&nbsp;number&nbsp;\|&nbsp;[Color](../reference/arkui-ts/ts-appendix-enums.md#color) | 用于描述颜色信息,输入为string类型时,使用rgb或者rgba进行描述;输入为number类型是,使用HEX格式颜色;输入类型为Color枚举时,使用颜色枚举值。<br/>-&nbsp;'rgb(255,&nbsp;255,&nbsp;255)'。<br/>-&nbsp;'rgba(255,&nbsp;255,&nbsp;255,&nbsp;1.0)'。<br/>-&nbsp;HEX格式:0xrrggbb,0xaarrggbb,'\#FFFFFF'。<br/>-&nbsp;枚举格式:Color.Black,Color.White等。 |
## ColorStop类型
......
......@@ -52,9 +52,7 @@ Switch为开关选择器,切换开启或关闭状态。具体用法请参考[S
background-color: #F1F3F5;
}
switch{
// 选中时的字体颜色
texton-color: #002aff;
// 未选中时的字体颜色
textoff-color: silver;
text-padding: 20px;
font-size: 50px;
......
......@@ -75,7 +75,7 @@ base目录与限定词目录下面可以创建资源组目录(包括element、
| ------- | ---------------------------------------- | ---------------------------------------- |
| element | 表示元素资源,以下每一类数据都采用相应的JSON文件来表征。<br/>-&nbsp;boolean,布尔型<br/>-&nbsp;color,颜色<br/>-&nbsp;float,浮点型<br/>-&nbsp;intarray,整型数组<br/>-&nbsp;integer,整型<br/>-&nbsp;pattern,样式<br/>-&nbsp;plural,复数形式<br/>-&nbsp;strarray,字符串数组<br/>-&nbsp;string,字符串 | element目录中的文件名称建议与下面的文件名保持一致。每个文件中只能包含同一类型的数据。<br/>-&nbsp;boolean.json<br/>-&nbsp;color.json<br/>-&nbsp;float.json<br/>-&nbsp;intarray.json<br/>-&nbsp;integer.json<br/>-&nbsp;pattern.json<br/>-&nbsp;plural.json<br/>-&nbsp;strarray.json<br/>-&nbsp;string.json |
| media | 表示媒体资源,包括图片、音频、视频等非文本格式的文件。 | 文件名可自定义,例如:icon.png。 |
| profile | 表示其他类型文件,以原始文件形式保存。 | 文件名可自定义。 |
| rawfile | 表示其他类型文件,在应用构建为hap包后,以原始文件形式保存,不会被集成到resources.index文件中。 | 文件名可自定义。 |
### 媒体资源类型说明
......
......@@ -43,9 +43,9 @@ listener.on('change', onPortrait)
`(max-height: 800)` :当高度小于800时条件成立
`(height &lt;= 800) ` :当高度小于800时条件成立
`(height <= 800) ` :当高度小于等于800时条件成立
`screen and (device-type: tv) or (resolution &lt; 2)` :包含多个媒体特征的多条件复杂语句查询
`screen and (device-type: tv) or (resolution < 2)` :包含多个媒体特征的多条件复杂语句查询
### 媒体类型(media-type)
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册