diff --git a/en/application-dev/reference/apis/js-apis-geolocation.md b/en/application-dev/reference/apis/js-apis-geolocation.md index f15805a326e19b0a579d1da1ae0e44e9937fef6f..92118167ad603189eac98eae73e156a794542f99 100644 --- a/en/application-dev/reference/apis/js-apis-geolocation.md +++ b/en/application-dev/reference/apis/js-apis-geolocation.md @@ -14,7 +14,7 @@ import geolocation from '@ohos.geolocation'; ## geolocation.on('locationChange') -on(type: 'locationChange', request: LocationRequest, callback: Callback<Location>) : void +on(type: 'locationChange', request: LocationRequest, callback: Callback<Location>): void Registers a listener for location changes with a location request initiated. @@ -34,6 +34,7 @@ Registers a listener for location changes with a location request initiated. **Example** ```js + import geolocation from '@ohos.geolocation'; var requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; var locationChange = (location) => { console.log('locationChanger: data: ' + JSON.stringify(location)); @@ -44,7 +45,7 @@ Registers a listener for location changes with a location request initiated. ## geolocation.off('locationChange') -off(type: 'locationChange', callback?: Callback<Location>) : void +off(type: 'locationChange', callback?: Callback<Location>): void Unregisters the listener for location changes with the corresponding location request deleted. @@ -63,6 +64,7 @@ Unregisters the listener for location changes with the corresponding location re **Example** ```js + import geolocation from '@ohos.geolocation'; var requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; var locationChange = (location) => { console.log('locationChanger: data: ' + JSON.stringify(location)); @@ -74,7 +76,7 @@ Unregisters the listener for location changes with the corresponding location re ## geolocation.on('locationServiceState') -on(type: 'locationServiceState', callback: Callback<boolean>) : void +on(type: 'locationServiceState', callback: Callback<boolean>): void Registers a listener for location service status change events. @@ -93,6 +95,7 @@ Registers a listener for location service status change events. **Example** ```js + import geolocation from '@ohos.geolocation'; var locationServiceState = (state) => { console.log('locationServiceState: ' + JSON.stringify(state)); } @@ -102,7 +105,7 @@ Registers a listener for location service status change events. ## geolocation.off('locationServiceState') -off(type: 'locationServiceState', callback?: Callback<boolean>) : void; +off(type: 'locationServiceState', callback?: Callback<boolean>): void; Unregisters the listener for location service status change events. @@ -121,6 +124,7 @@ Unregisters the listener for location service status change events. **Example** ```js + import geolocation from '@ohos.geolocation'; var locationServiceState = (state) => { console.log('locationServiceState: state: ' + JSON.stringify(state)); } @@ -131,7 +135,7 @@ Unregisters the listener for location service status change events. ## geolocation.on('cachedGnssLocationsReporting')8+ -on(type: 'cachedGnssLocationsReporting', request: CachedGnssLocationsRequest, callback: Callback<Array<Location>>) : void; +on(type: 'cachedGnssLocationsReporting', request: CachedGnssLocationsRequest, callback: Callback<Array<Location>>): void; Registers a listener for cached GNSS location reports. @@ -151,6 +155,7 @@ Registers a listener for cached GNSS location reports. **Example** ```js + import geolocation from '@ohos.geolocation'; var cachedLocationsCb = (locations) => { console.log('cachedGnssLocationsReporting: locations: ' + JSON.stringify(locations)); } @@ -161,7 +166,7 @@ Registers a listener for cached GNSS location reports. ## geolocation.off('cachedGnssLocationsReporting')8+ -off(type: 'cachedGnssLocationsReporting', callback?: Callback<Array<Location>>) : void; +off(type: 'cachedGnssLocationsReporting', callback?: Callback<Array<Location>>): void; Unregisters the listener for cached GNSS location reports. @@ -180,6 +185,7 @@ Unregisters the listener for cached GNSS location reports. **Example** ```js + import geolocation from '@ohos.geolocation'; var cachedLocationsCb = (locations) => { console.log('cachedGnssLocationsReporting: locations: ' + JSON.stringify(locations)); } @@ -191,7 +197,7 @@ Unregisters the listener for cached GNSS location reports. ## geolocation.on('gnssStatusChange')8+ -on(type: 'gnssStatusChange', callback: Callback<SatelliteStatusInfo>) : void; +on(type: 'gnssStatusChange', callback: Callback<SatelliteStatusInfo>): void; Registers a listener for GNSS satellite status change events. @@ -210,6 +216,7 @@ Registers a listener for GNSS satellite status change events. **Example** ```js + import geolocation from '@ohos.geolocation'; var gnssStatusCb = (satelliteStatusInfo) => { console.log('gnssStatusChange: ' + JSON.stringify(satelliteStatusInfo)); } @@ -219,7 +226,7 @@ Registers a listener for GNSS satellite status change events. ## geolocation.off('gnssStatusChange')8+ -off(type: 'gnssStatusChange', callback?: Callback<SatelliteStatusInfo>) : void; +off(type: 'gnssStatusChange', callback?: Callback<SatelliteStatusInfo>): void; Unregisters the listener for GNSS satellite status change events. @@ -237,6 +244,7 @@ Unregisters the listener for GNSS satellite status change events. **Example** ```js + import geolocation from '@ohos.geolocation'; var gnssStatusCb = (satelliteStatusInfo) => { console.log('gnssStatusChange: ' + JSON.stringify(satelliteStatusInfo)); } @@ -247,7 +255,7 @@ Unregisters the listener for GNSS satellite status change events. ## geolocation.on('nmeaMessageChange')8+ -on(type: 'nmeaMessageChange', callback: Callback<string>) : void; +on(type: 'nmeaMessageChange', callback: Callback<string>): void; Registers a listener for GNSS NMEA message change events. @@ -266,6 +274,7 @@ Registers a listener for GNSS NMEA message change events. **Example** ```js + import geolocation from '@ohos.geolocation'; var nmeaCb = (str) => { console.log('nmeaMessageChange: ' + JSON.stringify(str)); } @@ -275,7 +284,7 @@ Registers a listener for GNSS NMEA message change events. ## geolocation.off('nmeaMessageChange')8+ -off(type: 'nmeaMessageChange', callback?: Callback<string>) : void; +off(type: 'nmeaMessageChange', callback?: Callback<string>): void; Unregisters the listener for GNSS NMEA message change events. @@ -294,6 +303,7 @@ Unregisters the listener for GNSS NMEA message change events. **Example** ```js + import geolocation from '@ohos.geolocation'; var nmeaCb = (str) => { console.log('nmeaMessageChange: ' + JSON.stringify(str)); } @@ -304,7 +314,7 @@ Unregisters the listener for GNSS NMEA message change events. ## geolocation.on('fenceStatusChange')8+ -on(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void; +on(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent): void; Registers a listener for status change events of the specified geofence. @@ -331,13 +341,13 @@ Registers a listener for status change events of the specified geofence. wants: [ { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility" + abilityName: "com.example.myapplication.MainAbility", action: "action1", } ], operationType: wantAgent.OperationType.START_ABILITY, requestCode: 0, - wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG], }; wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { @@ -349,7 +359,7 @@ Registers a listener for status change events of the specified geofence. ## geolocation.off('fenceStatusChange')8+ -off(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void; +off(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent): void; Unregisters the listener for status change events of the specified geofence. @@ -375,7 +385,7 @@ Unregisters the listener for status change events of the specified geofence. wants: [ { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility" + abilityName: "com.example.myapplication.MainAbility", action: "action1", } ], @@ -392,62 +402,9 @@ Unregisters the listener for status change events of the specified geofence. ``` -## geolocation.on('countryCodeChange')9+ - -on(type: 'countryCodeChange', callback: Callback<CountryCode>) : void; - -Subscribe to country code information reporting events. - -**System capability**: SystemCapability.Location.Location.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is "countrycodechange", which means subscribing to the submission of country code information. | - | callback | Callback<CountryCode> | Yes | Callback is used to receive the country code information report. | - - -**Example** - - ```js - var callback = (code) => { - console.log('countryCodeChange: ' + JSON.stringify(code)); - } - geolocation.on('countryCodeChange', callback); - ``` - - -## geolocation.off('countryCodeChange')9+ - -off(type: 'countryCodeChange', callback?: Callback<CountryCode>) : void; - -Unsubscribe from the country code to report events. - -**System capability**: SystemCapability.Location.Location.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is "countrycodechange", which means unsubscribing to the submission of country code information. | - | callback | Callback<CountryCode> | Yes | Callback is used to receive the country code information report. | - - -**Example** - - ```js - var callback = (code) => { - console.log('countryCodeChange: ' + JSON.stringify(code)); - } - geolocation.on('countryCodeChange', callback); - geolocation.off('countryCodeChange', callback); - ``` - - ## geolocation.getCurrentLocation -getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback<Location>) : void +getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback<Location>): void Obtains the current location. This API uses an asynchronous callback to return the result. @@ -466,6 +423,7 @@ Obtains the current location. This API uses an asynchronous callback to return t **Example** ```js + import geolocation from '@ohos.geolocation'; var requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0}; var locationChange = (err, location) => { if (err) { @@ -482,7 +440,7 @@ Obtains the current location. This API uses an asynchronous callback to return t ## geolocation.getCurrentLocation -getCurrentLocation(request?: CurrentLocationRequest) : Promise<Location> +getCurrentLocation(request?: CurrentLocationRequest): Promise<Location> Obtains the current location. This API uses a promise to return the result. @@ -507,6 +465,7 @@ Obtains the current location. This API uses a promise to return the result. **Example** ```js + import geolocation from '@ohos.geolocation'; var requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0}; geolocation.getCurrentLocation(requestInfo).then((result) => { console.log('current location: ' + JSON.stringify(result)); @@ -516,7 +475,7 @@ Obtains the current location. This API uses a promise to return the result. ## geolocation.getLastLocation -getLastLocation(callback: AsyncCallback<Location>) : void +getLastLocation(callback: AsyncCallback<Location>): void Obtains the previous location. This API uses an asynchronous callback to return the result. @@ -534,6 +493,7 @@ Obtains the previous location. This API uses an asynchronous callback to return **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.getLastLocation((err, data) => { if (err) { console.log('getLastLocation: err=' + JSON.stringify(err)); @@ -547,7 +507,7 @@ Obtains the previous location. This API uses an asynchronous callback to return ## geolocation.getLastLocation -getLastLocation() : Promise<Location> +getLastLocation(): Promise<Location> Obtains the previous location. This API uses a promise to return the result. @@ -565,6 +525,7 @@ Obtains the previous location. This API uses a promise to return the result. **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.getLastLocation().then((result) => { console.log('getLastLocation: result: ' + JSON.stringify(result)); }); @@ -573,7 +534,7 @@ Obtains the previous location. This API uses a promise to return the result. ## geolocation.isLocationEnabled -isLocationEnabled(callback: AsyncCallback<boolean>) : void +isLocationEnabled(callback: AsyncCallback<boolean>): void Checks whether the location service is enabled. This API uses an asynchronous callback to return the result. @@ -591,6 +552,7 @@ Checks whether the location service is enabled. This API uses an asynchronous ca **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.isLocationEnabled((err, data) => { if (err) { console.log('isLocationEnabled: err=' + JSON.stringify(err)); @@ -604,7 +566,7 @@ Checks whether the location service is enabled. This API uses an asynchronous ca ## geolocation.isLocationEnabled -isLocationEnabled() : Promise<boolean> +isLocationEnabled(): Promise<boolean> Checks whether the location service is enabled. This API uses a promise to return the result. @@ -621,15 +583,16 @@ Checks whether the location service is enabled. This API uses a promise to retur **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.isLocationEnabled().then((result) => { - console.log('promise, isLocationEnabled: ' + result); + console.log('promise, isLocationEnabled: ' + JSON.stringify(result)); }); ``` ## geolocation.requestEnableLocation -requestEnableLocation(callback: AsyncCallback<boolean>) : void +requestEnableLocation(callback: AsyncCallback<boolean>): void Requests to enable the location service. This API uses an asynchronous callback to return the result. @@ -647,6 +610,7 @@ Requests to enable the location service. This API uses an asynchronous callback **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.requestEnableLocation((err, data) => { if (err) { console.log('requestEnableLocation: err=' + JSON.stringify(err)); @@ -660,7 +624,7 @@ Requests to enable the location service. This API uses an asynchronous callback ## geolocation.requestEnableLocation -requestEnableLocation() : Promise<boolean> +requestEnableLocation(): Promise<boolean> Requests to enable the location service. This API uses a promise to return the result. @@ -677,6 +641,7 @@ Requests to enable the location service. This API uses a promise to return the r **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.requestEnableLocation().then((result) => { console.log('promise, requestEnableLocation: ' + JSON.stringify(result)); }); @@ -685,7 +650,7 @@ Requests to enable the location service. This API uses a promise to return the r ## geolocation.enableLocation -enableLocation(callback: AsyncCallback<boolean>) : void; +enableLocation(callback: AsyncCallback<boolean>): void; Enables the location service. This API uses an asynchronous callback to return the result. @@ -704,6 +669,7 @@ Enables the location service. This API uses an asynchronous callback to return t **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.enableLocation((err, data) => { if (err) { console.log('enableLocation: err=' + JSON.stringify(err)); @@ -717,7 +683,7 @@ Enables the location service. This API uses an asynchronous callback to return t ## geolocation.enableLocation -enableLocation() : Promise<boolean> +enableLocation(): Promise<boolean> Enables the location service. This API uses a promise to return the result. @@ -736,6 +702,7 @@ Enables the location service. This API uses a promise to return the result. **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.enableLocation().then((result) => { console.log('promise, enableLocation: ' + JSON.stringify(result)); }); @@ -743,7 +710,7 @@ Enables the location service. This API uses a promise to return the result. ## geolocation.disableLocation -disableLocation(callback: AsyncCallback<boolean>) : void; +disableLocation(callback: AsyncCallback<boolean>): void; Disables the location service. This API uses an asynchronous callback to return the result. @@ -762,6 +729,7 @@ Disables the location service. This API uses an asynchronous callback to return **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.disableLocation((err, data) => { if (err) { console.log('disableLocation: err=' + JSON.stringify(err)); @@ -775,7 +743,7 @@ Disables the location service. This API uses an asynchronous callback to return ## geolocation.disableLocation -disableLocation() : Promise<boolean> +disableLocation(): Promise<boolean> Disables the location service. This API uses a promise to return the result. @@ -794,6 +762,7 @@ Disables the location service. This API uses a promise to return the result. **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.disableLocation().then((result) => { console.log('promise, disableLocation: ' + JSON.stringify(result)); }); @@ -801,7 +770,7 @@ Disables the location service. This API uses a promise to return the result. ## geolocation.isGeoServiceAvailable -isGeoServiceAvailable(callback: AsyncCallback<boolean>) : void +isGeoServiceAvailable(callback: AsyncCallback<boolean>): void Checks whether the (reverse) geocoding service is available. This API uses an asynchronous callback to return the result. @@ -818,6 +787,7 @@ Checks whether the (reverse) geocoding service is available. This API uses an as **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.isGeoServiceAvailable((err, data) => { if (err) { console.log('isGeoServiceAvailable: err=' + JSON.stringify(err)); @@ -831,7 +801,7 @@ Checks whether the (reverse) geocoding service is available. This API uses an as ## geolocation.isGeoServiceAvailable -isGeoServiceAvailable() : Promise<boolean> +isGeoServiceAvailable(): Promise<boolean> Checks whether the (reverse) geocoding service is available. This API uses a promise to return the result. @@ -848,6 +818,7 @@ Checks whether the (reverse) geocoding service is available. This API uses a pro **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.isGeoServiceAvailable().then((result) => { console.log('promise, isGeoServiceAvailable: ' + JSON.stringify(result)); }); @@ -856,7 +827,7 @@ Checks whether the (reverse) geocoding service is available. This API uses a pro ## geolocation.getAddressesFromLocation -getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>) : void +getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>): void Converts coordinates into geographic description through reverse geocoding. This API uses an asynchronous callback to return the result. @@ -874,6 +845,7 @@ Converts coordinates into geographic description through reverse geocoding. This **Example** ```js + import geolocation from '@ohos.geolocation'; var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; geolocation.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => { if (err) { @@ -888,7 +860,7 @@ Converts coordinates into geographic description through reverse geocoding. This ## geolocation.getAddressesFromLocation -getAddressesFromLocation(request: ReverseGeoCodeRequest) : Promise<Array<GeoAddress>>; +getAddressesFromLocation(request: ReverseGeoCodeRequest): Promise<Array<GeoAddress>>; Converts coordinates into geographic description through reverse geocoding. This API uses a promise to return the result. @@ -911,6 +883,7 @@ Converts coordinates into geographic description through reverse geocoding. This **Example** ```js + import geolocation from '@ohos.geolocation'; var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; geolocation.getAddressesFromLocation(reverseGeocodeRequest).then((data) => { console.log('getAddressesFromLocation: ' + JSON.stringify(data)); @@ -920,7 +893,7 @@ Converts coordinates into geographic description through reverse geocoding. This ## geolocation.getAddressesFromLocationName -getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>) : void +getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>): void Converts geographic description into coordinates through geocoding. This API uses an asynchronous callback to return the result. @@ -938,6 +911,7 @@ Converts geographic description into coordinates through geocoding. This API use **Example** ```js + import geolocation from '@ohos.geolocation'; var geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1}; geolocation.getAddressesFromLocationName(geocodeRequest, (err, data) => { if (err) { @@ -952,7 +926,7 @@ Converts geographic description into coordinates through geocoding. This API use ## geolocation.getAddressesFromLocationName -getAddressesFromLocationName(request: GeoCodeRequest) : Promise<Array<GeoAddress>> +getAddressesFromLocationName(request: GeoCodeRequest): Promise<Array<GeoAddress>> Converts geographic description into coordinates through geocoding. This API uses a promise to return the result. @@ -975,6 +949,7 @@ Converts geographic description into coordinates through geocoding. This API use **Example** ```js + import geolocation from '@ohos.geolocation'; var geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1}; geolocation.getAddressesFromLocationName(geocodeRequest).then((result) => { console.log('getAddressesFromLocationName: ' + JSON.stringify(result)); @@ -984,7 +959,7 @@ Converts geographic description into coordinates through geocoding. This API use ## geolocation.getCachedGnssLocationsSize8+ -getCachedGnssLocationsSize(callback: AsyncCallback<number>) : void; +getCachedGnssLocationsSize(callback: AsyncCallback<number>): void; Obtains the number of cached GNSS locations. @@ -1001,6 +976,7 @@ Obtains the number of cached GNSS locations. **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.getCachedGnssLocationsSize((err, size) => { if (err) { console.log('getCachedGnssLocationsSize: err=' + JSON.stringify(err)); @@ -1014,7 +990,7 @@ Obtains the number of cached GNSS locations. ## geolocation.getCachedGnssLocationsSize8+ -getCachedGnssLocationsSize() : Promise<number>; +getCachedGnssLocationsSize(): Promise<number>; Obtains the number of cached GNSS locations. @@ -1031,6 +1007,7 @@ Obtains the number of cached GNSS locations. **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.getCachedGnssLocationsSize().then((result) => { console.log('promise, getCachedGnssLocationsSize: ' + JSON.stringify(result)); }); @@ -1039,7 +1016,7 @@ Obtains the number of cached GNSS locations. ## geolocation.flushCachedGnssLocations8+ -flushCachedGnssLocations(callback: AsyncCallback<boolean>) : void; +flushCachedGnssLocations(callback: AsyncCallback<boolean>): void; Obtains all cached GNSS locations and clears the GNSS cache queue. @@ -1056,6 +1033,7 @@ Obtains all cached GNSS locations and clears the GNSS cache queue. **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.flushCachedGnssLocations((err, result) => { if (err) { console.log('flushCachedGnssLocations: err=' + JSON.stringify(err)); @@ -1069,7 +1047,7 @@ Obtains all cached GNSS locations and clears the GNSS cache queue. ## geolocation.flushCachedGnssLocations8+ -flushCachedGnssLocations() : Promise<boolean>; +flushCachedGnssLocations(): Promise<boolean>; Obtains all cached GNSS locations and clears the GNSS cache queue. @@ -1086,6 +1064,7 @@ Obtains all cached GNSS locations and clears the GNSS cache queue. **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.flushCachedGnssLocations().then((result) => { console.log('promise, flushCachedGnssLocations: ' + JSON.stringify(result)); }); @@ -1094,7 +1073,7 @@ Obtains all cached GNSS locations and clears the GNSS cache queue. ## geolocation.sendCommand8+ -sendCommand(command: LocationCommand, callback: AsyncCallback<boolean>) : void; +sendCommand(command: LocationCommand, callback: AsyncCallback<boolean>): void; Sends an extended command to the location subsystem. This API can only be called by system applications. @@ -1112,6 +1091,7 @@ Sends an extended command to the location subsystem. This API can only be called **Example** ```js + import geolocation from '@ohos.geolocation'; var requestInfo = {'scenario': 0x301, 'command': "command_1"}; geolocation.sendCommand(requestInfo, (err, result) => { if (err) { @@ -1126,7 +1106,7 @@ Sends an extended command to the location subsystem. This API can only be called ## geolocation.sendCommand8+ -sendCommand(command: LocationCommand) : Promise<boolean>; +sendCommand(command: LocationCommand): Promise<boolean>; Sends an extended command to the location subsystem. This API can only be called by system applications. @@ -1149,6 +1129,7 @@ Sends an extended command to the location subsystem. This API can only be called **Example** ```js + import geolocation from '@ohos.geolocation'; var requestInfo = {'scenario': 0x301, 'command': "command_1"}; geolocation.sendCommand(requestInfo).then((result) => { console.log('promise, sendCommand: ' + JSON.stringify(result)); @@ -1156,826 +1137,182 @@ Sends an extended command to the location subsystem. This API can only be called ``` -## geolocation.isLocationPrivacyConfirmed8+ - -isLocationPrivacyConfirmed(type : LocationPrivacyType, callback: AsyncCallback<boolean>) : void; - -Checks whether a user agrees with the privacy statement of the location service. This API can only be called by system applications. +## LocationRequestPriority -**System API**: This is a system API and cannot be called by third-party applications. +Sets the priority of the location request. **Permission required**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core -**Parameters** +| Name| Default Value| Description| +| -------- | -------- | -------- | +| UNSET | 0x200 | Priority unspecified.| +| ACCURACY | 0x201 | Location accuracy.| +| LOW_POWER | 0x202 | Power efficiency.| +| FIRST_FIX | 0x203 | Fast location. Use this option if you want to obtain a location as fast as possible.| - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | LocationPrivacyType | Yes| Privacy statement type, for example, privacy statement displayed in the startup wizard or privacy statement displayed when enabling the location service.| - | callback | AsyncCallback<boolean> | Yes| Callback used to return the result, which indicates whether the user agrees with the privacy statement.| -**Example** - - ```js - geolocation.isLocationPrivacyConfirmed(1, (err, result) => { - if (err) { - console.log('isLocationPrivacyConfirmed: err=' + JSON.stringify(err)); - } - if (result) { - console.log('isLocationPrivacyConfirmed: result=' + JSON.stringify(result)); - } - }); - ``` +## LocationRequestScenario + + Sets the scenario of the location request. + +**Permission required**: ohos.permission.LOCATION +**System capability**: SystemCapability.Location.Location.Core -## geolocation.isLocationPrivacyConfirmed8+ +| Name| Default Value| Description| +| -------- | -------- | -------- | +| UNSET | 0x300 | Scenario unspecified.| +| NAVIGATION | 0x301 | Navigation.| +| TRAJECTORY_TRACKING | 0x302 | Trajectory tracking.| +| CAR_HAILING | 0x303 | Ride hailing.| +| DAILY_LIFE_SERVICE | 0x304 | Daily life services.| +| NO_POWER | 0x305 | Power efficiency. Your application does not proactively start the location service. 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.| -isLocationPrivacyConfirmed(type : LocationPrivacyType,) : Promise<boolean>; -Checks whether a user agrees with the privacy statement of the location service. This API can only be called by system applications. +## GeoLocationErrorCode -**System API**: This is a system API and cannot be called by third-party applications. +Enumerates error codes of the location service. **Permission required**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core -**Parameters** +| Name| Default Value| Description| +| -------- | -------- | -------- | +| INPUT_PARAMS_ERROR7+ | 101 | Incorrect input parameters.| +| REVERSE_GEOCODE_ERROR7+ | 102 | Failed to call the reverse geocoding API.| +| GEOCODE_ERROR7+ | 103 | Failed to call the geocoding API.| +| LOCATOR_ERROR7+ | 104 | Failed to obtain the location.| +| LOCATION_SWITCH_ERROR7+ | 105 | Failed to change the location service switch.| +| LAST_KNOWN_LOCATION_ERROR7+ | 106 | Failed to obtain the previous location.| +| LOCATION_REQUEST_TIMEOUT_ERROR7+ | 107 | Failed to obtain the location within the specified time.| - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | LocationPrivacyType | Yes| Privacy statement type, for example, privacy statement displayed in the startup wizard or privacy statement displayed when enabling the location service.| -**Return value** +## ReverseGeoCodeRequest - | Name| Description| - | -------- | -------- | - | Promise<boolean> | Callback used to return the result, which indicates whether the user agrees with the privacy statement.| +Defines a reverse geocoding request. -**Example** - - ```js - geolocation.isLocationPrivacyConfirmed(1).then((result) => { - console.log('promise, isLocationPrivacyConfirmed: ' + JSON.stringify(result)); - }); - ``` +**Permission required**: ohos.permission.LOCATION +**System capability**: SystemCapability.Location.Location.Geocoder -## geolocation.setLocationPrivacyConfirmStatus8+ +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| locale | string | No| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| +| latitude | number | Yes| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| +| longitude | number | Yes| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| +| maxItems | number | No| Maximum number of location records to be returned.| -setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed: boolean, callback: AsyncCallback<boolean>) : void; -Sets the user confirmation status for the privacy statement of the location service. This API can only be called by system applications. +## GeoCodeRequest -**System API**: This is a system API and cannot be called by third-party applications. +Defines a geocoding request. **Permission required**: ohos.permission.LOCATION -**System capability**: SystemCapability.Location.Location.Core +**System capability**: SystemCapability.Location.Location.Geocoder -**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| locale | string | No| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| +| description | number | Yes| Location description, for example, No. xx, xx Road, Pudong New District, Shanghai.| +| maxItems | number | No| Maximum number of location records to be returned.| +| minLatitude | number | No| Minimum latitude. This parameter is used with minLongitude, maxLatitude, and maxLongitude to specify the latitude and longitude ranges.| +| minLongitude | number | No| Minimum longitude.| +| maxLatitude | number | No| Maximum latitude.| +| maxLongitude | number | No| Maximum longitude.| - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | LocationPrivacyType | Yes| Privacy statement type, for example, privacy statement displayed in the startup wizard or privacy statement displayed when enabling the location service.| - | isConfirmed | boolean | Yes| Callback used to return the result, which indicates whether the user agrees with the privacy statement.| - | callback | AsyncCallback<boolean> | Yes| Callback used to return the operation result.| -**Example** - - ```js - geolocation.setLocationPrivacyConfirmStatus(1, true, (err, result) => { - if (err) { - console.log('setLocationPrivacyConfirmStatus: err=' + JSON.stringify(err)); - } - if (result) { - console.log('setLocationPrivacyConfirmStatus: result=' + JSON.stringify(result)); - } - }); - ``` +## GeoAddress + +Defines a geographic location. + +**Permission required**: ohos.permission.LOCATION +**System capability**: SystemCapability.Location.Location.Geocoder -## geolocation.setLocationPrivacyConfirmStatus8+ +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| latitude7+ | number | No| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| +| longitude7+ | number | No| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| +| locale7+ | string | No| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| +| placeName7+ | string | No| Landmark of the location.| +| countryCode7+ | string | No| Country code.| +| countryName7+ | string | No| Country name.| +| administrativeArea7+ | string | No| Administrative region name.| +| subAdministrativeArea7+ | string | No| Sub-administrative region name.| +| locality7+ | string | No| Locality information. | +| subLocality7+ | string | No| Sub-locality information. | +| roadName7+ | string | No| Road name.| +| subRoadName7+ | string | No| Auxiliary road information.| +| premises7+ | string | No| House information.| +| postalCode7+ | string | No| Postal code.| +| phoneNumber7+ | string | No| Phone number.| +| addressUrl7+ | string | No| Website URL.| +| descriptions7+ | Array<string> | No| Additional description.| +| descriptionsSize7+ | number | No| Total number of additional descriptions.| -setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed : boolean) : Promise<boolean>; -Sets the user confirmation status for the privacy statement of the location service. This API can only be called by system applications. +## LocationRequest -**System API**: This is a system API and cannot be called by third-party applications. +Defines a location request. **Permission required**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core -**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| priority | [LocationRequestPriority](#locationrequestpriority) | No| Priority of the location request.| +| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes| Scenario of the location request.| +| timeInterval | number | No| Time interval at which location information is reported.| +| distanceInterval | number | No| Distance interval at which location information is reported.| +| maxAccuracy | number | No| Location accuracy.| - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | LocationPrivacyType | Yes| Privacy statement type, for example, privacy statement displayed in the startup wizard or privacy statement displayed when enabling the location service.| - | isConfirmed | boolean | Yes| Callback used to return the result, which indicates whether the user agrees with the privacy statement.| -**Return value** +## CurrentLocationRequest - | Name| Description| - | -------- | -------- | - | Promise<boolean> | Callback used to return the operation result.| +Defines the current location request. -**Example** - - ```js - geolocation.setLocationPrivacyConfirmStatus(1, true).then((result) => { - console.log('promise, setLocationPrivacyConfirmStatus: ' + JSON.stringify(result)); - }); - ``` +**Permission required**: ohos.permission.LOCATION +**System capability**: SystemCapability.Location.Location.Core -## geolocation.getCountryCode9+ +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| priority | [LocationRequestPriority](#locationrequestpriority) | No| Priority of the location request.| +| scenario | [LocationRequestScenario](#locationrequestscenario) | No| Scenario of the location request.| +| maxAccuracy | number | No| Location accuracy, in meters.| +| timeoutMs | number | No| Timeout duration, in milliseconds. The minimum value is 1000.| -getCountryCode(callback: AsyncCallback<CountryCode>) : void; -Query the current country code. +## SatelliteStatusInfo8+ -**System capability**: SystemCapability.Location.Location.Core +Defines the satellite status information. -**Parameters** +**Permission required**: ohos.permission.LOCATION - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<CountryCode> | Yes | Callback is used to receive the country code. | +**System capability**: SystemCapability.Location.Location.Gnss -**Example**: - - ```js - geolocation.getCountryCode((err, result) => { - if (err) { - console.log('getCountryCode: err=' + JSON.stringify(err)); - } - if (result) { - console.log('getCountryCode: result=' + JSON.stringify(result)); - } - }); - ``` +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| satellitesNumber | number | Yes| Number of satellites.| +| satelliteIds | Array<number> | Yes| Array of satellite IDs.| +| carrierToNoiseDensitys | Array<number> | Yes| Carrier-to-noise density ratio, that is, **cn0**.| +| altitudes | Array<number> | Yes| Altitude information.| +| azimuths | Array<number> | Yes| Azimuth information.| +| carrierFrequencies | Array<number> | Yes| Carrier frequency.| -## geolocation.getCountryCode9+ +## CachedGnssLocationsRequest8+ -getCountryCode() : Promise<CountryCode>; +Represents a request for reporting cached GNSS locations. -Query the current country code. +**Permission required**: ohos.permission.LOCATION -**System capability**: SystemCapability.Location.Location.Core - -**Parameters** - -None - -**Return value** - - | Name| Description| - | -------- | -------- | - | Promise<CountryCode> | return country code. | - -**Example**: - - ```js - geolocation.getCountryCode() - .then((result) => { - console.log('promise, getCountryCode: result=' + JSON.stringify(result)); - }) - .catch((error) => { - console.log('promise, getCountryCode: error=' + JSON.stringify(error)); - }); - ``` - - -## geolocation.enableLocationMock9+ - -enableLocationMock(scenario?: LocationRequestScenario, callback: AsyncCallback<void>) : void; - -Enable the position simulation function of a scene, and only one scene can be enabled at the same time. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | scenario | LocationRequestScenario | No | Indicates under what scenario the position simulation function is enabled. | - | callback | AsyncCallback<void> | Yes | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | - -**Example**: - - ```js - var request = {"scenario": 0x0301}; - geolocation.enableLocationMock(request, (err, result) => { - if (err) { - console.log('enableLocationMock: err=' + JSON.stringify(err)); - } - if (result) { - console.log('enableLocationMock: result=' + JSON.stringify(result)); - } - }); - ``` - -## geolocation.enableLocationMock9+ - -enableLocationMock(scenario?: LocationRequestScenario) : Promise<void>; - -Enable the position simulation function of a scene, and only one scene can be enabled at the same time. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | scenario | LocationRequestScenario | No | Indicates which scene's position simulation function is enabled. If this parameter is not carried, it means that the position simulation function of all scenes is enabled. | - - -**Return value** - - | Name| Description| - | -------- | -------- | - | Promise<void> | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | - -**Example**: - - ```js - var request = {"scenario": 0x0301}; - geolocation.enableLocationMock(request) - .then((result) => { - if (result) { - console.log('promise, enableLocationMock: result=' + JSON.stringify(result)); - } - }) - .catch((error) => { - if (error) { - console.log('promise, enableLocationMock: error=' + JSON.stringify(error)); - } - }); - ``` - - -## geolocation.disableLocationMock9+ - -disableLocationMock(scenario?: LocationRequestScenario, callback: AsyncCallback<void>) : void; - -To disable the position simulation function. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | scenario | LocationRequestScenario | No | Indicates to disable the position simulation function of a scene. If this parameter is not carried, it means to disable the position simulation function of all scenes. | - | callback | AsyncCallback<void> | Yes | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | - -**Example**: - - ```js - var request = {"scenario": 0x0301}; - geolocation.disableLocationMock(request, (err, result) => { - if (err) { - console.log('disableLocationMock: err=' + JSON.stringify(err)); - } - if (result) { - console.log('disableLocationMock: result=' + JSON.stringify(result)); - } - }); - ``` - - -## geolocation.disableLocationMock9+ - -disableLocationMock(scenario?: LocationRequestScenario) : Promise<void>; - -To disable the position simulation function. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | scenario | LocationRequestScenario | No | Indicates to disable the position simulation function of a scene. If this parameter is not carried, it means to disable the position simulation function of all scenes. | - -**Return value** - - | Name| Description| - | -------- | -------- | - | Promise<void> | It is used to receive the execution result. If the execution is successful, it will return nullptr, otherwise it will return an error message | - -**Example**: - - ```js - var request = {"scenario": 0x0301}; - geolocation.disableLocationMock(request) - .then((result) => { - if (result) { - console.log('promise, disableLocationMock: result=' + JSON.stringify(result)); - } - }) - .catch((error) => { - if (error) { - console.log('promise, disableLocationMock: error=' + JSON.stringify(error)); - } - }); - ``` - - -## geolocation.setMockedLocations9+ - -setMockedLocations(config: LocationMockConfig, callback: AsyncCallback<void>) : void; - -Set the simulated location information, and then report the simulated location at the time interval carried in the interface. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | config | LocationMockConfig | Yes | Indicates the configuration parameters of location simulation, including the time interval of simulation location reporting and the array of simulation locations. | - | callback | AsyncCallback<void> | Yes | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | - -**Example**: - - ```js - var locations = [ - {"latitude": 30.12, "longitude": 120.11, "altitude": 123, "accuracy": 1, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 1000000000, "additionSize": 0, "isFromMock": true}, - {"latitude": 31.13, "longitude": 121.11, "altitude": 123, "accuracy": 2, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 2000000000, "additionSize": 0, "isFromMock": true}, - {"latitude": 32.14, "longitude": 122.11, "altitude": 123, "accuracy": 3, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 3000000000, "additionSize": 0, "isFromMock": true}, - {"latitude": 33.15, "longitude": 123.11, "altitude": 123, "accuracy": 4, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 4000000000, "additionSize": 0, "isFromMock": true}, - {"latitude": 34.16, "longitude": 124.11, "altitude": 123, "accuracy": 5, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 5000000000, "additionSize": 0, "isFromMock": true} - ]; - var config = {"timeInterval": 5, "locations": locations}; - geolocation.setMockedLocations(config, (err, data) => { - if (err) { - console.log('setMockedLocations: err=' + JSON.stringify(err)); - } - if (data) { - console.log('setMockedLocations: data=' + JSON.stringify(data)); - } - }); - ``` - -## geolocation.setMockedLocations9+ - -setMockedLocations(config: LocationMockConfig) : Promise<void>; - -Set the simulated location information, and then report the simulated location at the time interval carried in the interface. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | config | LocationMockConfig | Yes | Indicates the configuration parameters of location simulation, including the time interval of simulation location reporting and the array of simulation locations. | - -**Return value** - - | Name| Description| - | -------- | -------- | - | Promise<void> | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | - -**Example**: - - ```js - var locations = [ - {"latitude": 30.12, "longitude": 120.11, "altitude": 123, "accuracy": 1, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 1000000000, "additionSize": 0, "isFromMock": true}, - {"latitude": 31.13, "longitude": 121.11, "altitude": 123, "accuracy": 2, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 2000000000, "additionSize": 0, "isFromMock": true}, - {"latitude": 32.14, "longitude": 122.11, "altitude": 123, "accuracy": 3, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 3000000000, "additionSize": 0, "isFromMock": true}, - {"latitude": 33.15, "longitude": 123.11, "altitude": 123, "accuracy": 4, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 4000000000, "additionSize": 0, "isFromMock": true}, - {"latitude": 34.16, "longitude": 124.11, "altitude": 123, "accuracy": 5, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 5000000000, "additionSize": 0, "isFromMock": true} - ]; - var config = {"timeInterval": 5, "locations":locations}; - geolocation.setMockedLocations(config) - .then((result) => { - if (result) { - console.log('promise, setMockedLocations: result=' + JSON.stringify(result)); - } - }) - .catch((error) => { - if (error) { - console.log('promise, setMockedLocations: error=' + JSON.stringify(error)); - } - }); - ``` - - - -## geolocation.enableReverseGeocodingMock9+ - -enableReverseGeocodingMock(callback: AsyncCallback<void>) : void; - -Enable reverse geocoding simulation function. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | Yes | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | - -**Example**: - - ```js - geolocation.enableReverseGeocodingMock((err, data) => { - if (err) { - console.log('enableReverseGeocodingMock: err=' + JSON.stringify(err)); - } - if (data) { - console.log('enableReverseGeocodingMock: data=' + JSON.stringify(data)); - } - }); - ``` - - -## geolocation.enableReverseGeocodingMock9+ - -enableReverseGeocodingMock() : Promise<void>; - -Enable reverse geocoding simulation function. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters**: - -None - -**Return value** - - | Name| Description| - | -------- | -------- | - | Promise<void> | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | - -**Example**: - - ```js - geolocation.enableReverseGeocodingMock() - .then((result) => { - if (result) { - console.log('promise, enableReverseGeocodingMock: result=' + JSON.stringify(result)); - } - }) - .catch((error) => { - if (error) { - console.log('promise, enableReverseGeocodingMock: error=' + JSON.stringify(error)); - } - }); - ``` - - -## geolocation.disableReverseGeocodingMock9+ - -disableReverseGeocodingMock(callback: AsyncCallback<void>) : void; - -Disable reverse geocoding simulation function. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters**: - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | Yes | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message | - -**Example**: - - ```js - geolocation.disableReverseGeocodingMock((err, result) => { - if (err) { - console.log('disableReverseGeocodingMock: err=' + JSON.stringify(err)); - } - if (result) { - console.log('disableReverseGeocodingMock: result=' + JSON.stringify(result)); - } - }); - ``` - - -## geolocation.disableReverseGeocodingMock9+ - -disableReverseGeocodingMock() : Promise<void>; - -Disable reverse geocoding simulation function. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters**: - -None - -**Return value** - - | Name| Description| - | -------- | -------- | - | Promise<void> | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | - -**Example**: - - ```js - geolocation.disableReverseGeocodingMock() - .then((result) => { - if (result) { - console.log('promise, disableReverseGeocodingMock: result=' + JSON.stringify(result)); - } - }) - .catch((error) => { - if (error) { - console.log('promise, disableReverseGeocodingMock: error=' + JSON.stringify(error)); - } - }); - ``` - - -## geolocation.setReverseGeocodingMockInfo9+ - -setReverseGeocodingMockInfo(mockInfos: Array<ReverseGeocodingMockInfo>, callback: AsyncCallback<void>) : void; - -Set the configuration information of the reverse geocoding simulation function, including the corresponding relationship between location and place name. If the location information is in the configuration information during the subsequent reverse geocoding query, the corresponding place name will be returned. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | mockInfos | Array<ReverseGeocodingMockInfo> | Yes | An array of configuration parameters indicating the inverse geocoding simulation function. The configuration parameters of the inverse geocoding simulation function include a location and a place name. | - | callback | AsyncCallback<void> | Yes | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | - -**Example**: - - ```js - var mockInfos = [ - {"location": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 33.12, "longitude": 123.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 33.12, "longitude": 123.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "maxItems": 1, "isFromMock": true}}, - ]; - geolocation.setReverseGeocodingMockInfo(mockInfos, (err, data) => { - if (err) { - console.log('promise, setReverseGeocodingMockInfo, err:' + JSON.stringify(err)); - } - if (data) { - console.log('promise, setReverseGeocodingMockInfo, data:' + JSON.stringify(data)); - } - }); - ``` - - -## geolocation.setReverseGeocodingMockInfo9+ - -setReverseGeocodingMockInfo(mockInfos: Array<ReverseGeocodingMockInfo>) : Promise<void>; - -Set the configuration information of the reverse geocoding simulation function, including the corresponding relationship between location and place name. If the location information is in the configuration information during the subsequent reverse geocoding query, the corresponding place name will be returned. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | mockInfos | Array<ReverseGeocodingMockInfo> | Yes | An array of configuration parameters indicating the inverse geocoding simulation function. The configuration parameters of the inverse geocoding simulation function include a location and a place name. | - -**Return value** - - | Name| Description| - | -------- | -------- | - | Promise<void> | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | - -**Example**: - - ```js - var mockInfos = [ - {"location": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 33.12, "longitude": 123.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 33.12, "longitude": 123.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "maxItems": 1, "isFromMock": true}}, - ]; - geolocation.setReverseGeocodingMockInfo(mockInfos) - .then((result) => { - if (result) { - console.log('promise, setReverseGeocodingMockInfo: result=' + JSON.stringify(result)); - } - }) - .catch((error) => { - if (error) { - console.log('promise, setReverseGeocodingMockInfo: error=' + JSON.stringify(error)); - } - }); - ``` - - -## LocationRequestPriority - -Sets the priority of the location request. - -**Permission required**: ohos.permission.LOCATION - -**System capability**: SystemCapability.Location.Location.Core - -| Name| Default Value| Description| -| -------- | -------- | -------- | -| UNSET | 0x200 | Priority unspecified.| -| ACCURACY | 0x201 | Location accuracy.| -| LOW_POWER | 0x202 | Power efficiency.| -| FIRST_FIX | 0x203 | Fast location. Use this option if you want to obtain a location as fast as possible.| - - -## LocationRequestScenario - - Sets the scenario of the location request. - -**Permission required**: ohos.permission.LOCATION - -**System capability**: SystemCapability.Location.Location.Core - -| Name| Default Value| Description| -| -------- | -------- | -------- | -| UNSET | 0x300 | Scenario unspecified.| -| NAVIGATION | 0x301 | Navigation.| -| TRAJECTORY_TRACKING | 0x302 | Trajectory tracking.| -| CAR_HAILING | 0x303 | Ride hailing.| -| DAILY_LIFE_SERVICE | 0x304 | Daily life services.| -| NO_POWER | 0x305 | Power efficiency. Your application does not proactively start the location service. 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.| - - -## GeoLocationErrorCode - -Enumerates error codes of the location service. - -**Permission required**: ohos.permission.LOCATION - -**System capability**: SystemCapability.Location.Location.Core - -| Name| Default Value| Description| -| -------- | -------- | -------- | -| NOT_SUPPORTED9+ | 100 | Indicates that the interface function is not supported. | -| INPUT_PARAMS_ERROR7+ | 101 | Incorrect input parameters.| -| REVERSE_GEOCODE_ERROR7+ | 102 | Failed to call the reverse geocoding API.| -| GEOCODE_ERROR7+ | 103 | Failed to call the geocoding API.| -| LOCATOR_ERROR7+ | 104 | Failed to obtain the location.| -| LOCATION_SWITCH_ERROR7+ | 105 | Failed to change the location service switch.| -| LAST_KNOWN_LOCATION_ERROR7+ | 106 | Failed to obtain the previous location.| -| LOCATION_REQUEST_TIMEOUT_ERROR7+ | 107 | Failed to obtain the location within the specified time.| -| QUERY_COUNTRY_CODE_ERROR9+ | 108 | Indicates that the country code query failed. | - - -## ReverseGeoCodeRequest - -Defines a reverse geocoding request. - -**Permission required**: ohos.permission.LOCATION - -**System capability**: SystemCapability.Location.Location.Geocoder - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| locale | string | No| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| -| latitude | number | Yes| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| -| longitude | number | Yes| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| -| maxItems | number | No| Maximum number of location records to be returned.| - - -## GeoCodeRequest - -Defines a geocoding request. - -**Permission required**: ohos.permission.LOCATION - -**System capability**: SystemCapability.Location.Location.Geocoder - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| locale | string | No| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| -| description | number | Yes| Location description, for example, No. xx, xx Road, Pudong New District, Shanghai.| -| maxItems | number | No| Maximum number of location records to be returned.| -| minLatitude | number | No| Minimum latitude. This parameter is used with minLongitude, maxLatitude, and maxLongitude to specify the latitude and longitude ranges.| -| minLongitude | number | No| Minimum longitude.| -| maxLatitude | number | No| Maximum latitude.| -| maxLongitude | number | No| Maximum longitude.| - - -## GeoAddress - -Defines a geographic location. - -**Permission required**: ohos.permission.LOCATION - -**System capability**: SystemCapability.Location.Location.Geocoder - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| latitude7+ | number | No| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| -| longitude7+ | number | No| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| -| locale7+ | string | No| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| -| placeName7+ | string | No| Landmark of the location.| -| countryCode7+ | string | No| Country code.| -| countryName7+ | string | No| Country name.| -| administrativeArea7+ | string | No| Administrative region name.| -| subAdministrativeArea7+ | string | No| Sub-administrative region name.| -| locality7+ | string | No| Locality information. | -| subLocality7+ | string | No| Sub-locality information. | -| roadName7+ | string | No| Road name.| -| subRoadName7+ | string | No| Auxiliary road information.| -| premises7+ | string | No| House information.| -| postalCode7+ | string | No| Postal code.| -| phoneNumber7+ | string | No| Phone number.| -| addressUrl7+ | string | No| Website URL.| -| descriptions7+ | Array<string> | No| Additional description.| -| descriptionsSize7+ | number | No| Total number of additional descriptions.| -| isFromMock9+ | Boolean | No | Indicates whether the geographical name information comes from the reverse geocoding simulation function. | - - -## LocationRequest - -Defines a location request. - -**Permission required**: ohos.permission.LOCATION - -**System capability**: SystemCapability.Location.Location.Core - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| priority | [LocationRequestPriority](#locationrequestpriority) | No| Priority of the location request.| -| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes| Scenario of the location request.| -| timeInterval | number | No| Time interval at which location information is reported.| -| distanceInterval | number | No| Distance interval at which location information is reported.| -| maxAccuracy | number | No| Location accuracy.| - - -## CurrentLocationRequest - -Defines the current location request. - -**Permission required**: ohos.permission.LOCATION - -**System capability**: SystemCapability.Location.Location.Core - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| priority | [LocationRequestPriority](#locationrequestpriority) | No| Priority of the location request.| -| scenario | [LocationRequestScenario](#locationrequestscenario) | No| Scenario of the location request.| -| maxAccuracy | number | No| Location accuracy, in meters.| -| timeoutMs | number | No| Timeout duration, in milliseconds. The minimum value is 1000.| - - -## SatelliteStatusInfo8+ - -Defines the satellite status information. - -**Permission required**: ohos.permission.LOCATION - -**System capability**: SystemCapability.Location.Location.Gnss - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| satellitesNumber | number | Yes| Number of satellites.| -| satelliteIds | Array<number> | Yes| Array of satellite IDs.| -| carrierToNoiseDensitys | Array<number> | Yes| Carrier-to-noise density ratio, that is, **cn0**.| -| altitudes | Array<number> | Yes| Altitude information.| -| azimuths | Array<number> | Yes| Azimuth information.| -| carrierFrequencies | Array<number> | Yes| Carrier frequency.| - - -## CachedGnssLocationsRequest8+ - -Represents a request for reporting cached GNSS locations. - -**Permission required**: ohos.permission.LOCATION - -**System capability**: SystemCapability.Location.Location.Gnss +**System capability**: SystemCapability.Location.Location.Gnss | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | @@ -2063,58 +1400,3 @@ Defines a location. | timeSinceBoot7+ | number | Yes| Location timestamp since boot.| | additions7+ | Array<string> | No| Additional information.| | additionSize7+ | number | No| Number of additional descriptions.| -| isFromMock9+ | Boolean | No | Indicates whether the location information comes from the location simulation function. | - - -## ReverseGeocodingMockInfo9+ - -The configuration information of the reverse geocoding simulation function includes a location information and a place name information. - -**System capability**:SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| location | ReverseGeoCodeRequest | Yes | Indicates longitude and latitude information. | -| geoAddress | GeoAddress | Yes | Represents a geographic location. | - - -## LocationMockConfig9+ - -The configuration parameters of the location simulation function include the time interval of the simulation position report and the array of simulation locations. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| timeInterval | number | Yes | Indicates the time interval of analog location reporting, in seconds. | -| locations | Array<Location> | Yes | Represents an array of mocked locations. | - - -## CountryCode9+ - -The country code information structure contains the country code string and the source information of the country code. - -**System capability**: SystemCapability.Location.Location.Core - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| country | string | Yes | Represents the country code string. | -| type | CountryCodeType | Yes | Indicates the source of country code information. | - - -## CountryCodeType9+ - -Country code source type. - -**System capability**: SystemCapability.Location.Location.Core - -| Name| Default Value| Description| -| -------- | -------- | -------- | -| COUNTRY_CODE_FROM_LOCALE | 1 | The country code obtained from the language configuration information of the globalization module. | -| COUNTRY_CODE_FROM_SIM | 2 | The country code obtained from the SIM card. | -| COUNTRY_CODE_FROM_LOCATION | 3 | Based on the user's location information, the country code is queried through reverse geocoding. | -| COUNTRY_CODE_FROM_NETWORK | 4 | The country code obtained from the cellular network registration information. | \ No newline at end of file diff --git a/zh-cn/application-dev/IDL/figures/SDKpath2.png b/zh-cn/application-dev/IDL/figures/SDKpath2.png index b11b6017d722c7842454df0a380ee2dfa0bb0665..51ac48d2f04d876a204493415b79a5f12e183685 100644 Binary files a/zh-cn/application-dev/IDL/figures/SDKpath2.png and b/zh-cn/application-dev/IDL/figures/SDKpath2.png differ diff --git a/zh-cn/application-dev/IDL/idl-guidelines.md b/zh-cn/application-dev/IDL/idl-guidelines.md index a2457e671e590909643faa59c79e44938e1a6973..1dba7cebf0602da3e2121aa1965ef7ee01601d5b 100644 --- a/zh-cn/application-dev/IDL/idl-guidelines.md +++ b/zh-cn/application-dev/IDL/idl-guidelines.md @@ -150,24 +150,23 @@ OpenHarmony IDL容器数据类型与Ts数据类型、C++数据类型的对应关 ## 开发步骤 ### IDL工具的获取 -首先,打开DevEco Studio—>Tools—>SDK Manager,查看OpenHarmony SDK的本地安装路径,如下图所示。 +首先,打开DevEco Studio—>Tools—>SDK Manager,查看OpenHarmony SDK的本地安装路径,此处以DevEco Studio 3.0.0.993版本为例,查看方式如下图所示。 ![SDKpath](./figures/SDKpath.png) ![SDKpath](./figures/SDKpath2.png) 进入对应路径后,查看toolchains->3.x.x.x(对应版本号命名文件夹)下是否存在idl工具的可执行文件,若不存在,可对应版本前往[docs仓版本目录](https://gitee.com/openharmony/docs/tree/master/zh-cn/release-notes)下载SDK包,以[3.2Beta3版本](https://gitee.com/openharmony/docs/blob/master/zh-cn/release-notes/OpenHarmony-v3.2-beta3.md#%E4%BB%8E%E9%95%9C%E5%83%8F%E7%AB%99%E7%82%B9%E8%8E%B7%E5%8F%96)为例,可通过镜像站点获取。 -关于如何替换DevEco Studio的SDK包具体操作,参考[full-SDK替换指南](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/quick-start/full-sdk-switch-guide.md#full-sdk%E6%9B%BF%E6%8D%A2%E6%8C%87%E5%8D%97)。 +关于如何替换DevEco Studio的SDK包具体操作,参考[full-SDK替换指南](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/quick-start/full-sdk-switch-guide.md#full-sdk%E6%9B%BF%E6%8D%A2%E6%8C%87%E5%8D%97)中的替换方法。 得到idl工具的可执行文件后,根据具体场景进行后续开发步骤。 -### C++开发步骤 +### TS开发步骤 #### 创建.idl文件 - 开发者可以使用C++编程语言构建.idl文件。 - - - 例如,此处构建一个名为iTest.idl的文件,文件内具体内容如下: + 开发者可以使用TS编程语言构建.idl文件。 + + 例如,此处构建一个名为IIdlTestService.idl的文件,文件内具体内容如下: ```cpp interface OHOS.IIdlTestService { @@ -176,199 +175,23 @@ OpenHarmony IDL容器数据类型与Ts数据类型、C++数据类型的对应关 } ``` -通过idl的可执行文件所在文件夹下执行命令 `idl -gen-cpp -d dir -c dir/IIdlTestService.idl`(-d后的dir为目标输出目录)在执行环境的dir目录中生成接口文件、Stub文件、Proxy文件。 - - > **注意**:生成的接口类文件名称和.idl文件名称保持一致 - -以命名为`IIdlTestService.idl`的.idl文件,在输出文件夹为生成文件IIdlTestServiceCpp中生成的代码目录结构例类似于: - -``` -├── IIdlTestServiceCpp # idl代码输出文件夹 -│ ├── i_idl_test_service.h # 生成文件 -│ ├── idl_test_service_proxy.h # 生成文件 -│ ├── idl_test_service_stub.h # 生成文件 -│ ├── idl_test_service_proxy.cpp # 生成文件 -│ └── idl_test_service_stub.cpp # 生成文件 -└── IIdlTestService.idl # 构造的.idl文件 -``` - -#### 服务端公开接口 +在idl的可执行文件所在文件夹下执行命令 `idl -gen-ts -d dir -c dir/IIdlTestService.idl`。 -OpenHarmony IDL工具生成的Stub类是接口类的抽象实现,并且会声明.idl文件中的所有方法。 +-d后的dir为目标输出目录,以输出文件夹名为IIdlTestServiceTs为例,在idl可执行文件所在目录下执行`idl -gen-ts -d IIdlTestServiceTs -c IIdlTestServiceTs/IIdlTestService.idl`,将会在执行环境的dir目录(即IIdlTestServiceTs目录)中生成接口文件、Stub文件、Proxy文件。 -```cpp -#ifndef OHOS_IDLTESTSERVICESTUB_H -#define OHOS_IDLTESTSERVICESTUB_H -#include -#include "iidl_test_service.h" - -namespace OHOS { -class IdlTestServiceStub : public IRemoteStub { -public: - int OnRemoteRequest( - /* [in] */ uint32_t code, - /* [in] */ MessageParcel& data, - /* [out] */ MessageParcel& reply, - /* [in] */ MessageOption& option) override; - -private: - static constexpr int COMMAND_TEST_INT_TRANSACTION = MIN_TRANSACTION_ID + 0; - static constexpr int COMMAND_TEST_STRING_TRANSACTION = MIN_TRANSACTION_ID + 1; -}; -} // namespace OHOS -#endif // OHOS_IDLTESTSERVICESTUB_H -``` +> **注意**:生成的接口类文件名称和.idl文件名称保持一致,否则会生成代码时会出现错误。 -开发者需要继承.idl文件中定义的接口类并实现其中的方法,同时在服务侧初始化时需要将定义的服务注册至SAMGR中,在本示例中,TestService类继承了IdlTestServiceStub接口类并实现了其中的TestIntTransaction和TestStringTransaction方法。具体的示例代码如下: +以名为`IIdlTestService.idl`的.idl文件、目标输出文件夹为IIdlTestServiceTs为例,其目录结构应类似于: -```cpp -#ifndef OHOS_IPC_TEST_SERVICE_H -#define OHOS_IPC_TEST_SERVICE_H - -#include "hilog/log.h" -#include "log_tags.h" -#include "idl_test_service_stub.h" - -namespace OHOS { -class TestService : public IdlTestServiceStub { -public: - TestService(); - ~TestService(); - static int Instantiate(); - ErrCode TestIntTransaction(int data, int &rep) override; - ErrCode TestStringTransaction(const std::string& data) override; -private: - static constexpr HiviewDFX::HiLogLabel LABEL = { LOG_CORE, LOG_ID_IPC, "TestService" }; -}; -} // namespace OHOS -#endif // OHOS_IPC_TEST_SERVICE_H ``` - -注册服务的示例代码如下: - -```cpp -#include "test_service.h" - -#include - -#include "if_system_ability_manager.h" -#include "ipc_debug.h" -#include "ipc_skeleton.h" -#include "iservice_registry.h" -#include "system_ability_definition.h" - -namespace OHOS { -using namespace OHOS::HiviewDFX; - -int TestService::Instantiate() -{ - ZLOGI(LABEL, "%{public}s call in", __func__); - auto saMgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - if (saMgr == nullptr) { - ZLOGE(LABEL, "%{public}s:fail to get Registry", __func__); - return -ENODEV; - } - - sptr newInstance = new TestService(); - int result = saMgr->AddSystemAbility(IPC_TEST_SERVICE, newInstance); - ZLOGI(LABEL, "%{public}s: IPC_TEST_SERVICE result = %{public}d", __func__, result); - return result; -} - -TestService::TestService() -{ -} - -TestService::~TestService() -{ -} - -ErrCode TestService::TestIntTransaction(int data, int &rep) -{ - ZLOGE(LABEL, " TestService:read from client data = %{public}d", data); - rep = data + data; - return ERR_NONE; -} - -ErrCode TestService::TestStringTransaction(const std::string &data) -{ - ZLOGE(LABEL, "TestService:read string from client data = %{public}s", data.c_str()); - return data.size(); -} -} // namespace OHOS +├── IIdlTestServiceTs # idl代码输出文件夹 +│ ├── i_idl_test_service.ts # 生成文件 +│ ├── idl_test_service_proxy.ts # 生成文件 +│ ├── idl_test_service_stub.ts # 生成文件 +│ └── IIdlTestService.idl # 构造的.idl文件 +└── idl.exe # idl的可执行文件 ``` -#### 客户端调用IPC方法 - -C++客户端通常通过SAMGR获取系统中定义的服务代理,随后即可正常调用proxy提供的接口。示例代码如下: - -```cpp -#include "test_client.h" - -#include "if_system_ability_manager.h" -#include "ipc_debug.h" -#include "ipc_skeleton.h" -#include "iservice_registry.h" -#include "system_ability_definition.h" - -namespace OHOS { -int TestClient::ConnectService() -{ - auto saMgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - if (saMgr == nullptr) { - ZLOGE(LABEL, "get registry fail"); - return -1; - } - - sptr object = saMgr->GetSystemAbility(IPC_TEST_SERVICE); - if (object != nullptr) { - ZLOGE(LABEL, "Got test Service object"); - testService_ = (new (std::nothrow) IdlTestServiceProxy(object)); - } - - if (testService_ == nullptr) { - ZLOGE(LABEL, "Could not find Test Service!"); - return -1; - } - - return 0; -} - -void TestClient::StartIntTransaction() -{ - if (testService_ != nullptr) { - ZLOGE(LABEL, "StartIntTransaction"); - [[maybe_unused]] int result = 0; - testService_->TestIntTransaction(1234, result); // 1234 : test number - ZLOGE(LABEL, "Rec result from server %{public}d.", result); - } -} - -void TestClient::StartStringTransaction() -{ - if (testService_ != nullptr) { - ZLOGI(LABEL, "StartIntTransaction"); - testService_->TestStringTransaction("IDL Test"); - } -} -} // namespace OHOS -``` - -### TS开发步骤 - -#### 创建.idl文件 - - 开发者可以使用TS编程语言构建.idl文件。.idl示例如下: - -```ts - interface OHOS.IIdlTestService { - int TestIntTransaction([in] int data); - void TestStringTransaction([in] String data); - } -``` - -使用者通过执行命令 “./idl -c IIdlTestService.idl -gen-ts -d /data/ts/” (-d为输出目录)在执行环境的/data/ts/目录中生成接口文件、Stub文件、Proxy文件。生成的接口类文件名称和.idl文件名称保持一致,区别在于其使用.ts扩展名。例如,IIdlTestService.idl 生成的文件名是 i_idl_test_service.ts、idl_test_service_proxy.ts、idl_test_service_stub.ts。 - #### 服务端公开接口 OpenHarmony IDL工具生成的Stub类是接口类的抽象实现,并且会声明.idl文件中的所有方法。 @@ -557,137 +380,3 @@ export default class MySequenceable { private str; } ``` - -## C++与TS互通开发步骤 - -### TS Proxy与C++ Stub开发步骤 - -#### C++端提供服务对象 - -1. 如上所述C++开发步骤,开发者使用C++编程语言构建.idl文件,通过命令生成接口、Stub文件、Proxy文件。 - -2. 开发者创建服务对象,并继承C++ Stub文件中定义的接口类并实现其中的方法,例如: - - ```cpp - class IdlTestServiceImpl : public IdlTestServiceStub { - public: - IdlTestServiceImpl() = default; - virtual ~IdlTestServiceImpl() = default; - - ErrCode TestIntTransaction(int _data, int& result) override - { - result = 256; - return ERR_OK; - } - - ErrCode TestStringTransaction(const std::string& _data) override - { - return ERR_OK; - } - }; - ``` - -#### C++端提供napi接口 - -C++需要通过napi的方式,把C++服务对象提供给TS端,例如:C++端提供一个GetNativeObject方法,方法里创建IdlTestServiceImpl实例,通过NAPI_ohos_rpc_CreateJsRemoteObject方法,创建出一个JS远程对象供TS应用使用,如下: - -```cpp -NativeValue* GetNativeObject(NativeEngine& engine, NativeCallbackInfo& info) -{ - sptr impl = new IdlTestServiceImpl(); - napi_value napiRemoteObject = NAPI_ohos_rpc_CreateJsRemoteObject(reinterpret_cast(&engine), impl); - NativeValue* nativeRemoteObject = reinterpret_cast(napiRemoteObject); - return nativeRemoteObject; -} -``` - -#### TS端提供Proxy对象 - -如上所述TS开发步骤,开发者使用TS编程语言构建.idl文件,通过命令生成接口、Stub文件、Proxy文件。Proxy文件例如: - -```ts -import {testIntTransactionCallback} from "./i_idl_test_service"; -import {testStringTransactionCallback} from "./i_idl_test_service"; -import IIdlTestService from "./i_idl_test_service"; -import rpc from "@ohos.rpc"; - -export default class IdlTestServiceProxy implements IIdlTestService { - constructor(proxy) { - this.proxy = proxy; - } - - testIntTransaction(data: number, callback: testIntTransactionCallback): void - { - let _option = new rpc.MessageOption(); - let _data = new rpc.MessageParcel(); - let _reply = new rpc.MessageParcel(); - _data.writeInt(data); - this.proxy.sendRequest(IdlTestServiceProxy.COMMAND_TEST_INT_TRANSACTION, _data, _reply, _option).then(function(result) { - if (result.errCode == 0) { - let _errCode = result.reply.readInt(); - if (_errCode != 0) { - let _returnValue = undefined; - callback(_errCode, _returnValue); - return; - } - let _returnValue = result.reply.readInt(); - callback(_errCode, _returnValue); - } else { - console.log('sendRequest failed, errCode: ' + result.errCode); - } - }) - } - - testStringTransaction(data: string, callback: testStringTransactionCallback): void - { - let _option = new rpc.MessageOption(); - let _data = new rpc.MessageParcel(); - let _reply = new rpc.MessageParcel(); - _data.writeString(data); - this.proxy.sendRequest(IdlTestServiceProxy.COMMAND_TEST_STRING_TRANSACTION, _data, _reply, _option).then(function(result) { - if (result.errCode == 0) { - let _errCode = result.reply.readInt(); - callback(_errCode); - } else { - console.log('sendRequest failed, errCode: ' + result.errCode); - } - }) - } - - static readonly COMMAND_TEST_INT_TRANSACTION = 1; - static readonly COMMAND_TEST_STRING_TRANSACTION = 2; - private proxy -} -``` - -#### TS与C++实现互通 - -1. TS应用调用napi接口获取C++服务的远程对象 -2. 构建TS Proxy对象,并把C++服务的远程对象传递给它 -3. 此时开发者通过TS Proxy对象调用.idl声明的方法,实现TS Proxy与C++ Stub的互通,示例如下: - -```ts -import IdlTestServiceProxy from './idl_test_service_proxy' -import nativeMgr from 'nativeManager'; - -function testIntTransactionCallback(errCode: number, returnValue: number) -{ - console.log('errCode: ' + errCode + ' returnValue: ' + returnValue); -} - -function testStringTransactionCallback(errCode: number) -{ - console.log('errCode: ' + errCode); -} - -function jsProxyTriggerCppStub() -{ - let nativeObj = nativeMgr.GetNativeObject(); - let tsProxy = new IdlTestServiceProxy(nativeObj); - // invoke testIntTransaction - tsProxy.testIntTransaction(10, testIntTransactionCallback); - - // invoke testStringTransaction - tsProxy.testStringTransaction('test', testIntTransactionCallback); -} -``` diff --git a/zh-cn/application-dev/quick-start/package-structure.md b/zh-cn/application-dev/quick-start/package-structure.md index 462dc9120fb3f296677c5cac7d2390078f41fe67..c51e7a2855d52515c947406c6c1cbe0d178f938b 100755 --- a/zh-cn/application-dev/quick-start/package-structure.md +++ b/zh-cn/application-dev/quick-start/package-structure.md @@ -92,9 +92,6 @@ app对象包含应用全局配置信息,内部结构说明参见表2。 | vendor | 标识对应用开发厂商的描述。字符串长度不超过255字节。 | 字符串 | 可缺省,缺省值为空 | | version | 标识应用的版本信息。参考表3。 | 对象 | 否 | | apiVersion | 标识应用程序所依赖的OpenHarmony API版本。参考表4。 | 对象 | 可缺省,缺省值为空 | -| singleton | 标识应用是否开启单例模式,仅支持系统应用,三方应用配置不生效。如果配置为true,在多用户场景下,该应用仍然单实例运行,不会随用户切换而变动,该字段从API8开始支持。 | 布尔值 | 可缺省,缺省值为false | -| removable | 标识应用是否可卸载,仅支持系统应用,三方应用配置不生效,该字段从API8开始支持。 | 布尔值 | 可缺省,缺省值为true | -| userDataClearable | 标识是否允许应用清除用户数据,仅支持系统应用,三方应用配置不生效,该字段从API8开始支持。 | 布尔值 | 可缺省,缺省值为true | 表3 version内部结构说明 diff --git a/zh-cn/application-dev/quick-start/stage-structure.md b/zh-cn/application-dev/quick-start/stage-structure.md index dbdb68f9ae500bd586ec8fc85f20159cf1bcf8b6..fe72991043a1e313e677f968c8240d6b96bec2fa 100755 --- a/zh-cn/application-dev/quick-start/stage-structure.md +++ b/zh-cn/application-dev/quick-start/stage-structure.md @@ -2,7 +2,7 @@ # 应用包结构配置文件的说明 -在开发FA模型下的应用程序时,需要在config.json文件中对应用的包结构进行申明;同样的,在开发stage模型下的应用程序时,需要在module.json5和app.json配置文件中对应用的包结构进行声明。 +在开发stage模型的应用程序时,需要在app.json5和module.json5配置文件中对应用的包结构进行声明。 ## 配置文件内部结构 @@ -12,18 +12,41 @@ | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | ------------------------------------------------------------ | -------- | ---------- | -| app | 标识应用的全局配置信息。参考[app对象内部结构](#app对象内部结构)。 | 对象 | 否 | -| module | 标识HAP包的配置信息。该标签下的配置只对当前HAP包生效。参考[module对象内部结构](#module对象内部结构)。 | 对象 | 否 | +| app | 标识应用的全局配置信息。参考[app对象内部结构](#app对象内部结构)。 | 对象 | 不可缺省。 | +| module | 标识HAP包的配置信息。该标签下的配置只对当前HAP包生效。参考[module对象内部结构](#module对象内部结构)。 | 对象 | 不可缺省。 | ### app对象内部结构 -app.json示例: +该标签为整个应用的属性,影响应用中所有HAP及组件。该标签的内部结构参见表2。 + +表2 app对象的内部结构说明 + +| 属性名称 | 含义 | 数据类型 | 是否可缺省 | +| ------------------------------ | ------------------------------------------------------------ | -------- | ------------------------------------------- | +| bundleName | 该标签标识应用的包名,用于标识应用的唯一性。标签的值命名规则 :
1)字符串以字母、数字、下划线和符号”.”组成;
2)以字母开头;
3)最小长度7字节,最大长度127个字节。
推荐采用反域名形式命名(如 :com.example.xxx,建议第一级为域名后缀com,第二级为厂商/个人名,第三级为应用名,也可以多级)。 | 字符串 | 不可缺省。 | +| debug | 该标签标识应用是否可调试。该标签由IDE编译构建时产生。 | 布尔值 | 可缺省,缺省值为false。 | +| icon | 该标签标识应用的图标,标签值为图标资源文件的索引。 | 字符串 | 不可缺省。 | +| label | 该标签标识应用的名称,标签值为字符串资源的索引。 | 字符串 | 不可缺省。 | +| description | 该标签标识App的描述信息,标签值是是字符串类型或对描述内容的字符串资源索引。 | 字符串 | 可缺省,缺省值为空。 | +| vendor | 该标签是对应用开发厂商的描述。最大长度255字节。 | 字符串 | 可缺省,缺省值为空。 | +| versionCode | 该标签标识应用的版本号,该标签值为32位非负整数。此数字仅用于确定某个版本是否比另一个版本更新,数值越大表示版本越高。开发者可以将该值设置为任何正整数,但是必须确保应用的新版本都使用比旧版本更大的值。versionCode 值应小于2的31次方。 | 数值 | 不可缺省。 | +| versionName | 该标签标识版本号的文字描述,用于向用户展示。
该标签仅由数字和点构成,推荐采用“A.B.C.D”四段式的形式。四段式推荐的含义如下所示。
第一段 :主版本号/Major,范围0-99,重大修改的版本,如实现新的大功能或重大变化。
第二段 :次版本号/Minor,范围0-99,表示实现较突出的特点,如新功能添加和大问题修复。
第三段 :特性版本号/Feature,范围0-99,标识规划的新版本特性。
第四段 :修订版本号/Patch,范围0-999,表示维护版本,修复bug。 | 字符串 | 不可缺省。 | +| minCompatibleVersionCode | 该标签标识该app能够兼容的最低历史版本号,用于跨设备兼容性判断。 | 数值 | 可缺省。缺省值等于versionCode标签值。| +| minAPIVersion | 该标签标识应用运行需要的SDK的API最小版本。 | 数值 | 可缺省,缺省值为bundle-profile.json5中的compatibleSdkVersion。| +| targetAPIVersion | 该标签标识应用运行需要的API目标版本。 | 数值 | 可缺省,缺省值为bundle-profile.json5中的compileSdkVersion。| +| apiReleaseType | 该标签标识应用运行需要的API目标版本的类型,采用字符串类型表示。取值为“CanaryN”、“BetaN”或者“Release”,其中,N代表大于零的整数。
Canary :受限发布的版本。
Beta :公开发布的Beta版本。
Release :公开发布的正式版本。
该字段由IDE读取当前使用的SDK的stage来生成。 | 字符串 | 可缺省,由IDE生成并覆盖。 | +| distributedNotificationEnabled | 该标签标记该应用是否开启分布式通知。 | 布尔值 | 可缺省,缺省值为true。 | +| entityType | 该标签标记该应用的类别,具体有 :游戏类(game),影音类(media)、社交通信类(communication)、新闻类(news)、出行类(travel)、工具类(utility)、购物类(shopping)、教育类(education)、少儿类(kids)、商务类(business)、拍摄类(photography)。 | 字符串 | 可缺省,缺省值为"unspecified"。 | +| multiProjects | 标识当前工程是否支持多工程。 | 布尔值 | 可缺省,缺省值为false。 | +| 设备类型 | 该标签可以配置多个,表示具体设备上的特殊配置信息,具体的设备类型有:"tablet"、"tv"、"wearable"、"car"、"default",可包含的字段有:minAPIVersion、distributedNotificationEnabled。 | 对象 | 可缺省,缺省值使用app下面相关的字段。 | + +app.json示例 : ```json { "app": { - "bundleName": "com.application.music", - "vendor": "application", + "bundleName": "bundleName", + "vendor": "vendorName", "versionCode": 1, "versionName": "1.0", "minCompatibleVersionCode": 1, @@ -32,76 +55,73 @@ app.json示例: "apiReleaseType": "Release", "debug": false, "icon": "$media:app_icon", - "label": "$string:app_name", - "description": "$string:description_application", + "label": "$string:app_label", + "description": "$string:app_description", "distributedNotificationEnabled": true, "entityType": "game", "car": { - "apiCompatibleVersion": 8 + "minAPIVersion": 8 } } } ``` -该标签为整个应用的属性,影响应用中所有hap及组件。该标签的内部结构参见表2。 +### module对象内部结构 -表2 app对象的内部结构说明 +HAP包的配置信息,该标签下的配置只对当前HAP包生效。 -| 属性名称 | 含义 | 数据类型 | 是否可缺省 | -| ------------------------------ | ------------------------------------------------------------ | -------- | ------------------------------------------- | -| bundleName | 该标签标识应用的包名,用于标识应用的唯一性。该标签不可缺省。标签的值命名规则 :
1)字符串以字母、数字、下划线和符号”.”组成;
2)以字母开头;
3)最小长度7个字节,最大长度127个字节。
推荐采用反域名形式命名(如 :com.example.xxx,建议第一级为域名后缀com,第二级为厂商/个人名,第三级为应用名,也可以多级)。
其中,随系统源码编译的应用需命名为”com.ohos.xxx”形式, ohos标识OpenHarmony系统应用。 | 字符串 | 否 | -| debug | 该标签标识应用是否可调试。 | 布尔值 | 该标签可以缺省,缺省为false。 | -| icon | 该标签标识应用的图标,标签值为资源文件的索引。 | 字符串 | 该标签不可缺省。 | -| label | 该标签标识应用的的名称,标签值为资源文件的索引,以支持多语言。 | 字符串 | 该标签不可缺省。 | -| description | 该标签标识App的描述信息,标签值是是字符串类型或对描述内容的资源索引,以支持多语言。 | 字符串 | 该标签可缺省,缺省值为空。 | -| vendor | 该标签是对应用开发厂商的描述。该标签的值是字符串类型(最大255个字节)。 | 字符串 | 该标签可以缺省,缺省为空。 | -| versionCode | 该标签标识应用的版本号,该标签值为32位非负整数。此数字仅用于确定某个版本是否比另一个版本更新,数值越大表示版本越高。开发者可以将该值设置为任何正整数,但是必须确保应用的新版本都使用比旧版本更大的值。该标签不可缺省,versionCode 值应小于2的31方。 | 数值 | 该标签不可缺省 | -| versionName | 该标签标识版本号的文字描述,用于向用户展示。
该标签仅由数字和点构成,推荐采用“A.B.C.D”四段式的形式。四段式推荐的含义如下所示。
第一段 :主版本号/Major,范围0-99,重大修改的版本,如实现新的大功能或重大变化。
第二段 :次版本号/Minor,范围0-99,表示实现较突出的特点,如新功能添加和大问题修复。
第三段 :特性版本号/Feature,范围0-99,标识规划的新版本特性。
第四段 :修订版本号/Patch,范围0-999,表示维护版本,修复bug。 | 字符串 | 该标签不可缺省 | -| minCompatibleVersionCode | 该标签标识该app能够兼容的最低历史版本号,用于跨设备兼容性判断。 | 数值 | 该标签可缺省。缺省值等于versionCode标签值。| -| minAPIVersion | 该标签标识应用运行需要的API最小版本。 | 整形 | 该标签可缺省,缺省值为bundle-profile.json5中的compatibleSdkVersion。| -| targetAPIVersion | 该标签标识应用运行需要的API目标版本。 | 整形 | 该标签可缺省,缺省值为bundle-profile.json5中的compileSdkVersion。| -| apiReleaseType | 该标签标识应用运行需要的API目标版本的类型,采用字符串类型表示。取值为“CanaryN”、“BetaN”或者“Release”,其中,N代表大于零的整数。
Canary :受限发布的版本。
Beta :公开发布的Beta版本。
Release :公开发布的正式版本。 | 字符串 | 该标签可缺省,缺省为“Release”。 | -| distributedNotificationEnabled | 该标签标记该应用是否开启分布式通知。 | 布尔值 | 该标签可缺省,缺省值为true。 | -| entityType | 该标签标记该应用的类别,具体有 :游戏类(game),影音类(media)、社交通信类(communication)、新闻类(news)、出行类(travel)、工具类(utility)、购物类(shopping)、教育类(education)、少儿类(kids)、商务类(business)、拍摄类(photography)。 | 字符串 | 该标签可以缺省,缺省为unspecified。 | -| singleton | 标识该应用开启单例模式,仅支持系统应用配置,三方应用配置不生效。配置为true时,在多用户场景下,该应用仍然单实例运行,不会随用户切换而变动。采用布尔类型,该字段从API8开始支持。 | 布尔值 | 可缺省,缺省值为false。 | -| removable | 标识应用是否可卸载,仅支持系统应用配置,三方应用配置不生效,该字段从API8开始支持。 | 布尔值 | 可缺省,缺省值为true。 | -| keepAlive | 标识应用是否始终保持运行状态,仅支持系统应用配置,三方应用配置不生效。标签值为布尔类型,如果为true,应用将始终保持为运行状态,并且在系统启动的时候会被系统启动起来,应用进程退出后,系统也会重新启动该应用进程。 | 布尔值 | 可缺省,缺省值为false。 | -| userDataClearable | 标识是否允许应用清除用户数据,仅支持系统应用配置,三方应用配置不生效,该字段从API8开始支持。 | 布尔值 | 可缺省,缺省值为true。 | -| accessible | 标识应用的安装目录是否是可访问的,仅支持系统应用配置,三方应用配置不生效。配置为true表示安装目录可以被三方应用访问,false表示不能被三方应用访问。 | 布尔值 | 可缺省,缺省值为false。 | -| multiProjects | 标识当前工程是否支持多工程。 | 布尔值 | 可缺省,缺省值为false。 | -| 设备类型 | 该标签可以配置多个,表示具体设备上的特殊配置信息,具体的设备类型有:"tablet"、"tv"、"wearable"、"car",可能包含的字段有:minAPIVersion、distributedNotificationEnabled、keepAlive、removable。 | 对象 | 该标签可缺省,缺省值使用app下面相关的字段。 | +表3 module对象内部结构说明 + +| 属性名称 | 含义 | 数据类型 | 是否可缺省 | +| -------------------- | ------------------------------------------------------------ | ---------- | ------------------------------------------------------------ | +| name | 该标签标识当前module的名字。module打包成HAP后,表示HAP的名称,标签值采用字符串表示(最大长度31字节),该名称在整个应用要唯一。 | 字符串 | 不可缺省。 | +| type | 该标签标识当前module的类型。类型有两种,分别是entry、feature。 | 字符串 | 不可缺省。 | +| srcEntrance | 该标签标识HAP所对应的入口js代码路径,标签值为字符串(最大长度127字节)。 | 字符串 | 可缺省,缺省值为空。 | +| description | 该标签标识HAP包的描述信息,标签值是是字符串类型或对描述内容的字符串资源索引。 | 字符串 | 可缺省,缺省值为空。 | +| process | 该标签标识HAP的进程名,标签值为字符串类型(最大长度31字节)。如果在HAP标签下配置了process,该应用的所有ability都运行在该进程中。该标签只支持系统应用配置。 | 字符串 | 可缺省,缺省值为app标签下的bundleName。 | +| mainElement | 该标签标识HAP的入口Ability名称或者Extension名称。只有配置为mainElement的Ability或者Extension才允许在服务中心露出。 | 字符串 | 创建OpenHarmony原子化服务时,不可缺省。OpenHarmony应用下,可缺省,缺省值为空。 | +| deviceTypes | 该标签标识HAP可以运行在哪类设备上,标签值采用字符串数组的表示,系统预定义的设备类型见表4。 | 字符串数组 | 不可缺省。 | +| deliveryWithInstall | 该标签标识当前HAP是否在用户主动安装的时候安装,true表示主动安装时安装,false表示主动安装时不安装。 | 布尔值 | 不可缺省。 | +| installationFree | 标识当前HAP是否支持免安装特性。所有Hap包都需要配置不可缺省。
true :表示支持免安装特性,且符合免安装约束。
false :表示不支持免安装特性。

当entry.hap该字段配置为true时,与该entry.hap相关的所有feature.hap该字段也需要配置为true。
当entry.hap该字段配置为false时,与该entry.hap相关的各feature.hap该字段可按业务需求配置true或false。 | 布尔值 | 不可缺省。 | +| virtualMachine | 该标签用于标识当前HAP运行的目标虚拟机类型,供云端分发使用,如应用市场和分发中心。
该标签值为字符串。如果目标虚拟机类型为方舟虚拟机,则其值为"ark + 版本号"。 该标签由IDE构建HAP的时候自动插入。 | 字符串 | 该标签由IDE构建HAP的时候自动插入。 | +| uiSyntax(deprecated) | syntax定义该JS Component的语法类型。
hml标识该JS Component使用hml/css/js进行开发;
ets标识该JS Component使用ets声明式语法进行开发。 | 字符串 | 可缺省,缺省值为hml,该字段从API9开始废弃。 | +| pages | 该标签是一个profile资源,用于列举JS Component中每个页面信息。可以配置window标签定义与显示窗口相关的配置。window参考[window对象内部结构](#window对象内部结构)。 | 字符串 | 在有ability的场景下,不可缺省。 | +| metadata | 该标签标识Hap的自定义元信息。参考[metadata对象内部结构](#metadata对象内部结构)。 | 对象数组 | 可缺省,缺省值为空。 | +| abilities | 描述元能力的配置信息,该标签下的配置只对当前ability生效。参考[abilities对象内部结构](#abilities对象内部结构)。 | 对象数组 | 可缺省,缺省值为空。 | +| extensionAbilities | 描述extensionAbilities的配置信息,该标签下的配置只对当前extensionAbility生效。参考[extensionAbilities对象内部结构](#extensionabilities对象内部结构)。 | 对象数组 | 可缺省,缺省值为空。 | +| definePermissions | 标识HAP定义的权限,仅支持系统应用配置,三方应用配置不生效。参考[definePermissions对象内部结构](#definepermissions对象内部结构)。 | 对象数组 | 可缺省,缺省值为空。 | +| requestPermissions | 该标签标识应用运行时需向系统申请的权限集合。参考[requestPermissions对象内部结构](#requestpermissions对象内部结构)。 | 对象数组 | 可缺省,缺省值为空。 | +| testRunner | 该标签用于支持对测试框架的配置,参考[testRunner对象内部结构说明](#testrunner对象内部结构)。 | 对象 | 可缺省,缺省值为空。 | -### module对象内部结构 module.json5示例: ```json { "module": { - "name": "myHapName", - "type": "entry|feature|har", - "srcEntrance" : "./MyAbilityStage.js", + "name": "moduleName", + "type": "entry", + "srcEntrance" : "./abilityStage.js", "description" : "$string:description_application", "mainElement": "MainAbility", + "pages": "$profile:pages_config", "deviceTypes": [ "tablet", "tv", "wearable", - "car", - "router" + "car" ], "deliveryWithInstall": true, "installationFree": false, - "virtualMachine": "ark | default", "metadata": [ { - "name": "string", - "value": "string", + "name": "name1", + "value": "value1", "resource": "$profile:config_file1" }, { - "name": "string", - "value": "string", + "name": "name2", + "value": "value2", "resource": "$profile:config_file2" } ], @@ -111,7 +131,7 @@ module.json5示例: "srcEntrance" : "./login/MyMainAbility.ts", "description": "$string:description_main_ability", "icon": "$media:icon", - "label": "HiMusic", + "label": "$string:label", "visible": true, "skills": [ { @@ -121,7 +141,7 @@ module.json5示例: "entities": [ "entity.system.home" ], - "uris": [ ] + "uris": [] } ], "backgroundModes": [ @@ -143,7 +163,7 @@ module.json5示例: "srcEntrance" : "./login/sampleAbility.ts", "description": "$string:description_sample_ability", "icon": "$media:icon", - "label": "HiMusic", + "label": "$string:label", "visible": true, "startWindowIcon": "$media:icon", "startWindowBackground": "$color:red" @@ -151,7 +171,7 @@ module.json5示例: ], "requestPermissions": [ { - "name": "ohos.abilitydemo.permission.PROVIDER", + "name": "permissionName", "reason": "$string:reason", "usedScene": { "abilities": [ @@ -165,80 +185,76 @@ module.json5示例: } ``` -hap包的配置信息,该标签下的配置只对当前hap包生效。 +pages示例 : -表3 module对象内部结构 +1.在开发视图的resources/base/profile下面定义配置文件pages_config.json(文件名称可由开发者定义): -| 属性名称 | 含义 | 数据类型 | 是否可缺省 | -| -------------------- | ------------------------------------------------------------ | ---------- | ------------------------------------------------------------ | -| name | 该标签标识当前module的名字,module打包成hap后,表示hap的名称,标签值采用字符串表示(最大长度31个字节),该名称在整个应用要唯一。 | 字符串 | 该标签不可缺省。 | -| type | 该标签标识当前hap的类型。类型有三种,分别是entry、feature和har。 | 字符串 | 该标签不可缺省。 | -| srcEntrance | 该标签标识hap所对应的入口js代码路径,标签值为字符串(最长为127字节)。 | 字符串 | 该标签可缺省。 | -| description | 该标签标识hap包的描述信息,标签值是是字符串类型或对描述内容的资源索引,以支持多语言。 | 字符串 | 该标签可缺省,缺省值为空。 | -| process | 该标签标识hap的进程名,标签值为字符串类型(最长为31个字节)。如果在hap标签下配置了process,该应用的所有ability都运行在该进程中。该标签只支持系统应用配置。 | 字符串 | 可缺省,缺省为app标签下的bundleName。 | -| mainElement | 该标签标识hap的入口ability名称或者extension名称。只有配置为mainElement的ability或者extension才允许在服务中心露出。创建OpenHarmony原子化服务时,该标签不可缺省。 | 字符串 | OpenHarmony应用下,该标签可缺省。 | -| deviceTypes | 该标签标识hap可以运行在哪类设备上,标签值采用字符串数组的表示,系统预定义的设备类型见表4。
与syscap不同的是,deviceTypes是以设备类型为粒度,而syscap是以设备能力(例如蓝牙、wifi)为粒度。 | 字符串数组 | 该标签不可缺省,可以为空值。 | -| deliveryWithInstall | 该标签标识当前hap是否在用户主动安装的时候安装,true表示主动安装时安装,false表示主动安装时不安装。 | 布尔值 | 该标签不可缺省。 | -| installationFree | 标识当前HAP是否支持免安装特性。所有Hap包都需要配置不可缺省。
true :表示支持免安装特性,且符合免安装约束。
false :表示不支持免安装特性。

当entry.hap该字段配置为true时,与该entry.hap相关的所有feature.hap该字段也需要配置为true。
当entry.hap该字段配置为false时,与该entry.hap相关的各feature.hap该字段可按业务需求配置true或false。 | 布尔值 | 该标签不可缺省。 | -| virtualMachine | 该标签用于标识当前hap运行的目标虚拟机类型,供云端分发使用,如应用市场和分发中心。
该标签值为字符串。如果目标虚拟机类型为方舟虚拟机,则其值为”ark”; 如果目标虚拟机类型不是方舟虚拟机,则其值为”default”。该标签由IDE构建hap的时候自动插入。解包工具解析时,如果hap包没有该标签,设置该标签值为”default”。 | 字符串 | 该标签可缺省,缺省值为“default”。 | -| uiSyntax(deprecated) | syntax定义该JS Component的语法类型。
hml标识该JS Component使用hml/css/js进行开发;
ets标识该JS Component使用ets声明式语法进行开发。 | 字符串 | 该标签可缺省,默认值为hml,该字段从API9开始废弃。 | -| pages | 该标签是一个profile资源,用于列举JS Component中每个页面信息。pages使用参考pages示例。 | 对象 | 在有ability的场景下,该标签不可缺省。 | -| metadata | 该标签标识Hap的自定义元信息,标签值为数组类型,该标签下的配置只对当前module、或者ability、或者extensionAbility生效。metadata参考[metadata对象内部结构](#metadata对象内部结构)。 | 数组 | 该标签可缺省,缺省值为空。 | -| abilities | 描述元能力的配置信息,标签值为数组类型,该标签下的配置只对当前ability生效。abilities参考[abilities对象内部结构](#abilities对象内部结构)。 | 对象 | 该标签可缺省,缺省值为空。 | -| extensionAbilities | 描述extensionAbilities的配置信息,标签值为数组类型,该标签下的配置只对当前extensionAbility生效。extensionAbilities参考[extensionAbility对象的内部结构说明](#extensionability对象的内部结构说明)。 | 对象 | 该标签可缺省,缺省值为空。 | -| definePermissions | 标识hap定义的权限,仅支持系统应用配置,三方应用配置不生效。该应用的调用者必须申请这些权限才能正常调用该应用。definePermissions参考[definePermissions对象内部结构](#definepermissions对象内部结构) | 对象 | 该标签可缺省,缺省值为空,表示调用者无需任何权限即可调用该应用。 | -| requestPermissions | 该标签标识应用运行时需向系统申请的权限集合,标签值为数组类型。requestPermissions参考[requestPermissions对象内部结构](#requestpermissions对象内部结构)。 | 对象 | 该标签可缺省,缺省值为空。 | -| testRunner | 此标签用于支持对测试框架的配置,参考[testRunner对象内部结构说明](#testrunner对象内部结构)说明。 | 对象 | 可缺省,缺省值为空 | - -表4 deviceTypes对象的系统预定义设备 - -| 中文 | 英文 | 枚举值 | 设备类型 | -| -------- | ----------- | -------- | -------------------------------------------------------- | -| 平板 | tablet | tablet | 平板,带屏音箱 | -| 智慧屏 | smart TV | tv | 智慧屏 | -| 智能手表 | smart watch | wearable | 智能手表,儿童手表,特指资源较丰富的的手表,具备电话功能 | -| 车机 | head unit | car | 车机 | -| 路由器 | router | router | 路由器 | +```json +{ + "src": [ + "pages/index/index", + "pages/second/second", + "pages/third/third", + "pages/four/four" + ], + "window": { + "designWidth": 720, + "autoDesignWidth": false + } +} +``` -deviceTypes示例 : +2.在module.json5的module标签下定义pages信息 : ```json { "module": { - "name": "myHapName", - "type": "har", - "deviceTypes" : [ - "wearable" - ] + "pages": "$profile:pages_config" } } ``` -pages示例 : +表4 deviceTypes对象的系统预定义设备 + +| 设备类型 | 枚举值 | 说明 | +| -------- | ----------- | -------- | +| 平板 | tablet | - | +| 智慧屏 | tv | - | +| 智能手表 | wearable | 系统能力较丰富的手表,具备电话功能。 | +| 车机 | car | - | +| 默认设备 | default | 能够使用全部系统能力的OpenHarmony设备。 | + +deviceTypes示例 : ```json { "module": { - "name": "myHapName", - "type": "har", "deviceTypes" : [ "wearable" - ], - "pages": "$profile:pages_config" + ] } } ``` -pages_config配置文件 +#### window对象内部结构 + +定义与显示窗口相关的配置。 + +表5 window对象内部结构说明 + +| 属性名称 | 含义 | 数据类型 | 是否可缺省 | +| -------- | ------------------------------------------------------------ | -------- | -------------------------- | +| designWidth | 定义页面设计基准宽度,根据实际设备宽度来缩放元素大小。 | 数值 | 可缺省,缺省值为750。 | +| autoDesignWidth | 定义页面设计基准宽度是否自动计算,当设置为true时,designWidth将被忽略,设计基准宽度由设备宽度与屏幕密度计算得出。 | 布尔值 | 可缺省,缺省值为false。 | + +window示例 : ```json { - "src": [ - "pages/index/index", - "pages/second/second", - "pages/third/third", - "pages/four/four" - ] + "window": { + "designWidth": 720, + "autoDesignWidth": false + } } ``` @@ -248,112 +264,32 @@ pages_config配置文件 描述的module、ability、extensionAbility配置信息,标签值为数组类型,该标签下的配置只对当前module、或者ability、或者extensionAbility生效。 -表5 metadata对象内部结构说明 +表6 metadata对象内部结构说明 | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | ------------------------------------------------------------ | -------- | -------------------------- | -| name | 该标签标识数据项的键名称,字符串类型(最大长度255字节)。 | 字符串 | 该标签可缺省,缺省值为空。 | -| value | 该标签标识数据项的值,标签值为字符串(最大长度255字节)。 | 字符串 | 可缺省,缺省为空。 | -| resource | 该标签标识定义用户自定义数据格式,标签值为标识该数据的资源的索引值。 | 字符串 | 可缺省,缺省为空。 | +| name | 该标签标识数据项的键名称,最大长度255字节。 | 字符串 | 可缺省,缺省值为空。 | +| value | 该标签标识数据项的值,最大长度255字节。 | 字符串 | 可缺省,缺省值为空。 | +| resource | 该标签标识定义用户自定义数据格式,标签值为标识该数据的资源的索引值。 | 字符串 | 可缺省,缺省值为空。 | -metadata示例 : +metadata示例 : ```json -{ +{ "module": { "metadata": [ { - "name": "string", - "value": "string", - "resource": "$profile:config_file" + "name": "name1", + "value": "value1", + "resource": "$profile:config_file1" }, { - "name": "string", - "value": "string", - "resource": "$profile:config_file" + "name": "name2", + "value": "value2", + "resource": "$profile:config_file2" } - ] - } -} -``` - -#### abilities对象内部结构 - -abilities描述ability的配置信息,标签值为数组类型。 - -表6 abilities对象内部结构说明 - -| 属性 | 含义 | 数据类型 | 是否可缺省 | -| --------------- | ------------------------------------------------------------ | ---------- | ------------------------------------------------------------ | -| name | 该标签标识当前ability的逻辑名,该名称在整个应用要唯一,标签值采用字符串表示(最大长度127个字节)。 | 字符串 | 该标签不可缺省。 | -| srcEntrance | 该标签标识ability所对应的js代码路径,标签值为字符串(最长为127字节)。。 | 字符串 | 该标签不可缺省。 | -| launchType | 该标签标示ability的启动模式,标签值可选“standard”、“singleton”、“specified”。该标签缺省为"singleton"。standard表示普通多实例,specified表示指定实例,运行时由ability内部业务决定是否创建多实例,singleton表示单实例。 | 字符串 | 可缺省,该标签缺省为"singleton" | -| description | 该标签标识ability的描述,标签值是是字符串类型或对描述内容的资源索引,要求采用用资源索引方式,以支持多语言。 | 字符串 | 该标签可缺省,缺省值为空。 | -| icon | 该标签标识ability图标,标签值为资源文件的索引。该标签可缺省,缺省值为空。
如果ability被配置为MainElement,该标签必须配置。 | 字符串 | 该标签可缺省,缺省值为空。
如果ability被配置为MainElement,该标签必须配置。 | -| permissions | 该标签标识被其它应用的ability调用时需要申请的权限的集合,一个数组元素为一个权限名称。通常采用反向域名格式(最大255字节),取值为系统预定义的权限。 | 字符串数组 | 该标签可缺省,缺省值为空。 | -| metadata | 该标签标识ability的元信息。metadata参考[metadata对象内部结构](#metadata对象内部结构)。 | 数组 | 该标签可缺省,缺省值为空。 | -| visible | 该标签标识ability是否可以被其它应用调用,为布尔类型,true表示可以被其它应用调用, false表示不可以被其它应用调用。 | 布尔值 | 该标签可缺省,缺省值为false。 | -| continuable | 该标签标识ability是否可以迁移,为布尔类型,true表示可以被迁移, false表示不可以被迁移。 | 布尔值 | 该标签可缺省,缺省值为false。 | -| skills | 该标签标识ability能够接收的意图的特征集,为数组格式。
配置规则 : entry包可以配置多个具有入口能力的skills标签(配置了action.system.home和entity.system.home)的ability,其中第一个配置了skills标签的ability中的label和icon作为OpenHarmony服务或应用的label和icon。
OpenHarmony服务的Feature包不能配置具有入口能力的skills标签。
OpenHarmony应用的Feature包可以配置具有入口能力的skills标签。
skills内部结构参考[skills对象内部结构](#skills对象内部结构)。 | 数组 | 该标签可缺省,缺省值为空。 | -| backgroundModes | 该标签标识ability长时任务集合。指定用于满足特定类型的长时任务。
长时任务类型有如下 :
dataTransfer :通过网络/对端设备进行数据下载、备份、分享、传输等业务。
audioPlayback :音频输出业务。
audioRecording :音频输入业务。
location :定位、导航业务。
bluetoothInteraction :蓝牙扫描、连接、传输业务(穿戴)。
multiDeviceConnection :多设备互联业务。
wifiInteraction :Wifi扫描、连接、传输业务(克隆 多屏)。
voip :音视频电话,VOIP业务。
taskKeeping :计算业务。
| 字符串 | 可缺省,缺省为空。 | -| startWindowIcon | 标识该Ability启动页面图标资源文件的索引。取值示例:$media:icon。 | 字符串 | 不可缺省。| -| startWindowBackground | 标识该Ability启动页面背景颜色资源文件的索引。取值示例:$color:red。 | 字符串 | 不可缺省。| -| removeMissionAfterTerminate | 该标签标识ability销毁后是否从任务列表中移除任务。为布尔类型,true表示销毁后移除任务, false表示销毁后不移除任务。 | 布尔值 | 该标签可缺省,缺省值为false。| -| orientation | 标识该ability启动时的方向。该方向的取值范围包括:
unspecified: 未指定方向,由系统自动判断显示方向,
landscape:横屏,
portrait:竖屏,
landscape_inverted: 反向横屏,
portrait_inverted: 反向竖屏,
auto_rotation: 随传感器旋转,
auto_rotation_landscape: 传感器横屏旋转,包括了横屏和反向横屏,
auto_rotation_portrait: 传感器竖屏旋转,包括了竖屏和反向竖屏,
auto_rotation_restricted: 传感器开关打开,方向可随传感器旋转,
auto_rotation_landscape_restricted: 传感器开关打开,方向可随传感器旋转为横屏, 包括了横屏和反向横屏,
auto_rotation_portrait_restricted: 传感器开关打开,方向随可传感器旋转为竖屏, 包括了横屏和反向横屏,
locked: 传感器开关关闭,方向锁定。 | 字符串 | 该标签可缺省,缺省值为unspecified。| -|supportWindowMode|标识该ability所支持的窗口模式,包含:
fullscreen: 全屏模式,
split: 分屏模式,
floating: 悬浮窗模式。 |数组 | 该标签可缺省,缺省值为
["fullscreen", "split", "floating"]。| -|priority|标识ability的优先级,仅支持系统应用配置,三方应用配置不生效。隐式查询时,优先级越高,ability在返回列表越靠前。该标签取值为integer类型,取值范围0-10。数值越大,优先级越高。 |数值 | 该标签可缺省,缺省值为0。 | -|maxWindowRatio|标识该ability支持的最大的宽高比。| 数值 |该标签可缺省,缺省值为平台支持的最大的宽高比。| -|minWindowRatio|标识该ability支持的最小的宽高比。| 数值 |该标签可缺省,缺省值为平台支持的最小的宽高比。| -|maxWindowWidth|标识该ability支持的最大的窗口宽度,宽度单位为vp。| 数值 |该标签可缺省,缺省值为平台支持的最大的窗口宽度。| -|minWindowWidth|标识该ability支持的最小的窗口宽度, 宽度单位为vp。| 数值 |该标签可缺省,缺省值为平台支持的最小的窗口宽度。| -|maxWindowHeight|标识该ability支持的最大的窗口高度, 高度单位为vp。| 数值 |该标签可缺省,缺省值为平台支持的最大的窗口高度。| -|minWindowHeight|标识该ability支持的最小的窗口高度, 高度单位为vp。| 数值 |该标签可缺省,缺省值为平台支持的最小的窗口高度。| -| excludeFromMissions | 该标签标识ability是否在最近任务列表中显示,仅支持系统应用配置,三方应用配置不生效。为布尔类型,true表示不在任务列表中显示,false表示在任务列表中显示。 | 布尔值 | 该标签可缺省,缺省值为false。| - -abilities示例 - -```json -{ - "abilities": [{ - "name": "MainAbility", - "srcEntrance": "./ets/login/MyLoginAbility.ts", - "launchType":"standard", - "description": "$string:description_main_ability", - "icon": "$media:icon", - "label": "Login", - "permissions": [], - "metadata": [], - "visible": true, - "continuable": true, - "skills": [{ - "actions": ["action.system.home"], - "entities": ["entity.system.home"], - "uris": [] - }], - "backgroundModes": [ - "dataTransfer", - "audioPlayback", - "audioRecording", - "location", - "bluetoothInteraction", - "multiDeviceConnection", - "wifiInteraction", - "voip", - "taskKeeping" ], - "startWindowIcon": "$media:icon", - "startWindowBackground": "$color:red", - "removeMissionAfterTerminate": true, - "orientation": " ", - "supportWindowMode": ["fullscreen", "split", "floating"], - "maxWindowRatio": 3.5, - "minWindowRatio": 0.5, - "maxWindowWidth": 2560, - "minWindowWidth": 1400, - "maxWindowHeight": 300, - "minWindowHeight": 200, - "excludeFromMissions": false - }] + } } ``` @@ -361,231 +297,374 @@ abilities示例 该标签标识ability或者extension能够接收的意图的特征。 -表7 skills内部结构示例 +表7 skill对象内部结构说明 | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | ------------------------------------------------------------ | ---------- | -------------------- | | actions | 该标签标识能够接收的意图的action值的集合,取值通常为系统预定义的action值,也允许自定义。 | 字符串数组 | 可缺省,缺省值为空。 | | entities | 该标签标识能够接收Want的元能力的类别集合,取值通常为系统预定义的类别,也允许自定义。 | 字符串数组 | 可缺省,缺省值为空。 | -| uris | 该标签标识向 want过滤器添加数据规范集合。该规范可以是只有数据类型(mimeType 属性),可以是只有 URI,也可以是既有数据类型又有 URI。uris内部结构参考表8。 | 对象数组 | 可缺省,缺省值为空。 | +| uris | 该标签标识与意图中URI(Uniform Resource Identifier)相匹配的集合。uris内部结构参考表8。 | 对象数组 | 可缺省,缺省值为空。 | -表8 uris对象的内部结构说明 +表8 uris对象内部结构说明 | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | ------------------- | -------- | -------------------- | -| scheme | 标识uri的scheme值。 | 字符串 | 不可缺省。 | -| host | 标识uri的host值。 | 字符串 | 可缺省,缺省值为空。 | -| port | 标识uri的port值。 | 字符串 | 可缺省,缺省值为空。 | -| path | 标识uri的path值。 | 字符串 | 可缺省,缺省值为空。 | -| type | 标识uri的type值。 | 字符串 | 可缺省,缺省值为空。 | +| scheme | 标识URI的协议名部分,常见的有http、https、file、ftp等。 | 字符串 | 当配置type时可缺省,缺省值为空。没有配置type时不可缺省。 | +| host | 标识URI的主机地址部分,常见的有域名的方式,如example.com,ip地址的方式,如192.0.0.1。该字段要在scheme存在时才有意义。 | 字符串 | 可缺省,缺省值为空。 | +| port | 标识URI的端口部分。如http默认端口为80,https默认端口是443,ftp默认端口是21。该字段要在scheme和host都存在时才有意义。| 字符串 | 可缺省,缺省值为空。 | +| path \| pathStartWith \| pathRegex | 标识URI的路径部分,path、pathStartWith和pathRegex配置时三选一。path标识URI与want中的路径部分全匹配,pathStartWith标识URI与want中的路径部分允许前缀匹配,pathRegex标识URI与want中的路径部分允许正则匹配。该字段要在scheme和host都存在时才有意义。| 字符串 | 可缺省,缺省值为空。 | +| type | 标识数据类型,使用MIME(Multipurpose Internet Mail Extensions)类型规范。可与scheme同时配置,也可以单独配置。| 字符串 | 可缺省,缺省值为空。 | -skills示例 +skills示例 : ```json { - "abilities": [ - { - "skills": [ - { - "actions": [ - "action.system.home" - ], - "entities": [ - "entity.system.home" - ], - "uris": [ - { - "scheme":"uri2", - "host":"host2", - "port":"port2", - "pathStartWith":"path2", - "pathRegex":"/query/.*", - "path":"path", - "type": "text/*" - } - ] - } - ] - } - ], - "extensionAbilities": [ - { - "skills": [ - { - "actions": [ - ], - "entities": [ - ], - "uris": [ - { - "scheme":"uri2", - "host":"host2", - "port":"port2", - "pathStartWith":"path2", - "pathRegex":"/query/.*", - "path":"path", - "type": "text/*" - } - ] - } - ] - } - ] + "module": { + "abilities": [ + { + "skills": [ + { + "actions": [ + "action.system.home" + ], + "entities": [ + "entity.system.home" + ], + "uris": [ + { + "scheme":"https", + "host":"www.example.com", + "port":"8080", + "path":"query/student/name", + "pathStartWith":"query/student", + "pathRegex":"query/.*/name", + "type": "text/*" + } + ] + } + ] + } + ], + "extensionAbilities": [ + { + "skills": [ + { + "actions": [ + "actionName" + ], + "entities": [ + "entityName" + ], + "uris": [ + { + "scheme":"https", + "host":"www.example.com", + "port":"8080", + "path":"query/student/name", + "pathStartWith":"query/student", + "pathRegex":"query/.*/name", + "type": "text/*" + } + ] + } + ] + } + ] + } +} +``` + +#### abilities对象内部结构 + +abilities描述Ability组件的配置信息,标签值为数组类型。 + +表9 ability对象内部结构说明 + +| 属性 | 含义 | 数据类型 | 是否可缺省 | +| --------------- | ------------------------------------------------------------ | ---------- | ------------------------------------------------------------ | +| name | 该标签标识当前Ability组件的逻辑名,该名称在整个应用要唯一,标签值采用字符串表示(最大长度127字节)。 | 字符串 | 不可缺省。 | +| srcEntrance | 该标签标识Ability组件所对应的js代码路径,标签值为字符串(最大长度127字节)。 | 字符串 | 不可缺省。 | +| launchType | 该标签标识Ability组件的启动模式,可选标签值:
"standard":多实例,每次启动创建一个新的实例。
"singleton":单实例,仅第一次启动创建新实例。
"specified":运行时由开发者决定是否创建新实例。 | 字符串 | 可缺省,缺省值为"singleton" | +| description | 该标签标识Ability组件的描述信息,标签值是是字符串类型或对描述内容的资源索引,要求采用资源索引方式,以支持多语言。 | 字符串 | 可缺省,缺省值为空。 | +| icon | 该标签标识Ability组件的图标,标签值为图标资源文件的索引。 | 字符串 | 可缺省,缺省值为空。
如果Ability组件被配置为MainElement,该标签必须配置。 | +| permissions | 该标签标识被其它应用的Ability组件调用时需要申请的权限的集合,一个数组元素为一个权限名称。通常采用反向域名格式(最大长度255字节),取值为系统预定义的权限。 | 字符串数组 | 可缺省,缺省值为空。 | +| metadata | 该标签标识Ability组件的元信息。参考[metadata对象内部结构](#metadata对象内部结构)。 | 对象数组 | 可缺省,缺省值为空。 | +| visible | 该标签标识Ability组件是否可以被其它应用调用,true表示可以被其它应用调用, false表示不可以被其它应用调用。 | 布尔值 | 可缺省,缺省值为false。 | +| continuable | 该标签标识Ability组件是否可以迁移,true表示可以被迁移, false表示不可以被迁移。 | 布尔值 | 可缺省,缺省值为false。 | +| skills | 该标签标识Ability组件能够接收的意图的特征集。
配置规则 : entry包可以配置多个具有入口能力的skills标签(配置了action.system.home和entity.system.home)的Ability组件,其中第一个配置了skills标签的Ability组件中的label和icon作为OpenHarmony服务或应用的label和icon。
OpenHarmony服务的Feature包不能配置具有入口能力的skills标签。
OpenHarmony应用的Feature包可以配置具有入口能力的skills标签。
参考[skills对象内部结构](#skills对象内部结构)。 | 对象数组 | 可缺省,缺省值为空。 | +| backgroundModes | 该标签标识Ability组件的长时任务集合。指定用于满足特定类型的长时任务。
长时任务类型有如下 :
dataTransfer :通过网络/对端设备进行数据下载、备份、分享、传输等业务。
audioPlayback :音频输出业务。
audioRecording :音频输入业务。
location :定位、导航业务。
bluetoothInteraction :蓝牙扫描、连接、传输业务(穿戴)。
multiDeviceConnection :多设备互联业务。
wifiInteraction :Wifi扫描、连接、传输业务(克隆 多屏)。
voip :音视频电话,VOIP业务。
taskKeeping :计算业务。
| 字符串 | 可缺省,缺省值为空。 | +| startWindowIcon | 标识该Ability组件启动页面图标资源文件的索引。取值示例:$media:icon。 | 字符串 | 不可缺省。| +| startWindowBackground | 标识该Ability组件启动页面背景颜色资源文件的索引。取值示例:$color:red。 | 字符串 | 不可缺省。| +| removeMissionAfterTerminate | 该标签标识Ability组件销毁后是否从任务列表中移除任务。true表示销毁后移除任务, false表示销毁后不移除任务。 | 布尔值 | 可缺省,缺省值为false。| +| orientation | 标识该Ability组件启动时的方向。取值范围包括:
unspecified: 未指定方向,由系统自动判断显示方向,
landscape:横屏,
portrait:竖屏,
landscape_inverted: 反向横屏,
portrait_inverted: 反向竖屏,
auto_rotation: 随传感器旋转,
auto_rotation_landscape: 传感器横屏旋转,包括了横屏和反向横屏,
auto_rotation_portrait: 传感器竖屏旋转,包括了竖屏和反向竖屏,
auto_rotation_restricted: 传感器开关打开,方向可随传感器旋转,
auto_rotation_landscape_restricted: 传感器开关打开,方向可随传感器旋转为横屏, 包括了横屏和反向横屏,
auto_rotation_portrait_restricted: 传感器开关打开,方向随可传感器旋转为竖屏, 包括了横屏和反向横屏,
locked: 传感器开关关闭,方向锁定。 | 字符串 | 可缺省,缺省值为"unspecified"。| +|supportWindowMode|标识该Ability组件所支持的窗口模式,取值范围包括:
fullscreen: 全屏模式,
split: 分屏模式,
floating: 悬浮窗模式。 |字符串数组 | 可缺省,缺省值为
["fullscreen", "split", "floating"]。| +|maxWindowRatio|标识该Ability组件支持的最大的宽高比。| 数值 |可缺省,缺省值为平台支持的最大的宽高比。| +|minWindowRatio|标识该Ability组件支持的最小的宽高比。| 数值 |可缺省,缺省值为平台支持的最小的宽高比。| +|maxWindowWidth|标识该Ability组件支持的最大的窗口宽度,宽度单位为vp。| 数值 |可缺省,缺省值为平台支持的最大的窗口宽度。| +|minWindowWidth|标识该Ability组件支持的最小的窗口宽度, 宽度单位为vp。| 数值 |可缺省,缺省值为平台支持的最小的窗口宽度。| +|maxWindowHeight|标识该Ability组件支持的最大的窗口高度, 高度单位为vp。| 数值 |可缺省,缺省值为平台支持的最大的窗口高度。| +|minWindowHeight|标识该Ability组件支持的最小的窗口高度, 高度单位为vp。| 数值 |可缺省,缺省值为平台支持的最小的窗口高度。| + +abilities示例 : + +```json +{ + "module": { + "abilities": [ + { + "name": "MainAbility", + "srcEntrance": "./ets/login/LoginAbility.ts", + "launchType":"standard", + "description": "$string:description", + "icon": "$media:icon", + "label": "$string:label", + "permissions": [], + "metadata": [], + "visible": true, + "continuable": true, + "skills": [ + { + "actions": ["action.system.home"], + "entities": ["entity.system.home"], + "uris": [] + } + ], + "backgroundModes": [ + "dataTransfer", + "audioPlayback", + "audioRecording", + "location", + "bluetoothInteraction", + "multiDeviceConnection", + "wifiInteraction", + "voip", + "taskKeeping" + ], + "startWindowIcon": "$media:icon", + "startWindowBackground": "$color:red", + "removeMissionAfterTerminate": true, + "orientation": "landscape", + "supportWindowMode": ["fullscreen", "split", "floating"], + "maxWindowRatio": 3.5, + "minWindowRatio": 0.5, + "maxWindowWidth": 2560, + "minWindowWidth": 1400, + "maxWindowHeight": 300, + "minWindowHeight": 200 + } + ] + } } ``` -#### extensionAbility对象的内部结构说明 -描述extensionAbility的配置信息,标签值为数组类型,该标签下的配置只对当前extensionAbility生效。 +#### extensionAbilities对象内部结构 + +extensionAbilities描述extensionAbility的配置信息,标签值为数组类型。 -表9 extensionAbility对象内部结构说明 +表10 extensionAbility对象内部结构说明 | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | ----------- | ------------------------------------------------------------ | ---------- | ----------------------------- | -| name | 该标签标识当前extensionAbility的逻辑名,标签值采用字符串表示(最大长度127个字节),该名称在整个应用要唯一。 | 字符串 | 该标签不可缺省。 | -| srcEntrance | 该标签标识extensionAbility所对应的js代码路径,标签值为字符串(最长为127字节)。 | 字符串 | 该标签不可缺省。 | -| description | 该标签标识extensionAbility的描述,标签值是是字符串类型或对描述内容的资源索引,以支持多语言。 | 字符串 | 该标签可缺省,缺省值为空。 | -| icon | 该标签标识extensionAbility图标,标签值为资源文件的索引。如果extensionAbility被配置为MainElement,该标签必须配置。 | 字符串 | 该标签可缺省,缺省值为空。 | -| label | 该标签标识extensionAbility对用户显示的名称,标签值配置为该名称的资源索引以支持多语言。
如果extensionAbility被配置为MainElement,该标签必须配置,且应用内唯一。 | 字符串 | 该标签不可缺省。 | -| type | 该标签标识extensionAbility的类型,取值为form、workScheduler、inputMethod、service、accessibility、dataShare、fileShare、staticSubscriber、wallpaper、backup、window、enterpriseAdmin、thumbnail、preview其中之一。 | 字符串 | 该标签不可缺省。 | -| permissions | 该标签标识被其它应用的ability调用时需要申请的权限的集合,字符串数组类型,每个数组元素为一个权限名称,通常采用反向域名方式表示(最大255字节),可以是系统预定义的权限,也可以是该应用自定义的权限。如果是后者,需与defPermissions标签中定义的某个权限的name标签值一致。 | 字符串数组 | 该标签可缺省,缺省值为空。 | -| uri | 该标签标识ability提供的数据uri,为字符数组类型(最大长度255),用反向域名的格式表示。该标签在type为dataShare类型的extensionAbility时,不可缺省。 | 字符串 | 该标签可缺省,缺省值为空。 | -| skills | 该标签标识ability能够接收的意图的特征集,为数组格式。
配置规则 : entry包可以配置多个具有入口能力的skills标签(配置了action.system.home和entity.system.home)的ability,其中第一个配置了skills标签的ability中的label和icon作为OpenHarmony服务或应用的label和icon。
OpenHarmony服务的Feature包不能配置具有入口能力的skills标签。
OpenHarmony应用的Feature包可以配置具有入口能力的skills标签。
skills内部结构参考[skills对象内部结构](#skills对象内部结构)。 | 数组 | 该标签可缺省,缺省值为空。 | -| metadata | 该标签标识extensionAbility的元信息。metadata内部结构参考[metadata对象内部结构](#metadata对象内部结构)。 | 对象 | 该标签可缺省,缺省值为空。 | -| visible | 该标签标识extensionAbility是否可以被其它应用调用,为布尔类型。true表示可以被其它应用调用, false表示不可以被其它应用调用。 | 布尔值 | 该标签可缺省,缺省值为false。 | - -extensionAbility示例 : +| name | 该标签标识当前ExtensionAbility组件的逻辑名,标签值采用字符串表示(最大长度127字节),该名称在整个应用要唯一。 | 字符串 | 不可缺省。 | +| srcEntrance | 该标签标识ExtensionAbility组件所对应的js代码路径,标签值为字符串(最大长度127字节)。 | 字符串 | 不可缺省。 | +| description | 该标签标识ExtensionAbility组件的描述,标签值是是字符串类型或对描述内容的资源索引,以支持多语言。 | 字符串 | 可缺省,缺省值为空。 | +| icon | 该标签标识ExtensionAbility组件图标,标签值为资源文件的索引。 | 字符串 | 可缺省,缺省值为空。如果ExtensionAbility组件被配置为MainElement,不可缺省。 | +| label | 该标签标识ExtensionAbility组件对用户显示的名称,标签值配置为该名称的资源索引以支持多语言。 | 字符串 | 可缺省,缺省值为空。如果ExtensionAbility组件被配置为MainElement,该标签必须配置,且应用内唯一。 | +| type | 该标签标识ExtensionAbility组件的类型,取值为form、workScheduler、inputMethod、service、accessibility、dataShare、fileShare、staticSubscriber、wallpaper、backup、window、enterpriseAdmin、thumbnail、preview其中之一。 | 字符串 | 不可缺省。 | +| permissions | 该标签标识被其它应用的ability调用时需要申请的权限的集合,字符串数组类型,每个数组元素为一个权限名称,通常采用反向域名方式表示(最大长度255字节),取值为系统预定义权限或者应用自定义权限,如果是后者,需与defPermissions标签中定义的某个权限的name标签值一致。 | 字符串数组 | 可缺省,缺省值为空。 | +| uri | 该标签标识ability提供的数据URI,为字符数组类型(最大长度255字节),用反向域名的格式表示。 | 字符串 | 可缺省,缺省值为空。该标签在type为dataShare类型的ExtensionAbility组件时,不可缺省。 | +| skills | 该标签标识ability能够接收的意图的特征集,为数组格式。
配置规则 : entry包可以配置多个具有入口能力的skills标签(配置了action.system.home和entity.system.home)的ability,其中第一个配置了skills标签的ability中的label和icon作为OpenHarmony服务或应用的label和icon。
OpenHarmony服务的Feature包不能配置具有入口能力的skills标签。
OpenHarmony应用的Feature包可以配置具有入口能力的skills标签。
参考[skills对象内部结构](#skills对象内部结构)。 | 对象数组 | 可缺省,缺省值为空。 | +| metadata | 该标签标识ExtensionAbility组件的元信息。参考[metadata对象内部结构](#metadata对象内部结构)。 | 对象数组 | 可缺省,缺省值为空。 | +| visible | 该标签标识ExtensionAbility组件是否可以被其它应用调用。true表示可以被其它应用调用, false表示不可以被其它应用调用。 | 布尔值 | 可缺省,缺省值为false。 | +| readPermission | 该标签标识读取ExtensionAbility组件的数据所需的权限。最大长度255字节。type为dataShare类型的ExtensionAbility组件支持该配置。该标签只对系统应用生效。 | 字符串 | 可缺省,缺省值为空。 | +| writePermission | 该标签标识向ExtensionAbility组件写数据所需的权限。最大长度255字节。type为dataShare类型的ExtensionAbility组件支持该配置。该标签只对系统应用生效。 | 字符串 | 可缺省,缺省值为空。 | + +extensionAbilities示例 : ```json { - "extensionAbilities": [ - { - "name": "FormName", - "srcEntrance": "./form/MyForm.ts", - "icon": "$media:icon", - "label" : "$string:extension_name", - "description": "$string:form_description", - "type": "form", - "permissions": ["ohos.abilitydemo.permission.PROVIDER"], - "readPermission": "", - "writePermission": "", - "visible": true, - "uri":"scheme://authority/path/query" - "skills": [{ - "actions": [], - "entities": [], - "uris": [] - }], - "metadata": [ - { - "name": "ohos.extability.form", - "resource": "$profile:form_config", - } - ] - } - ] + "module": { + "extensionAbilities": [ + { + "name": "extensionName", + "srcEntrance": "./extension/FormExtension.ts", + "icon": "$media:icon", + "label" : "$string:label", + "description": "$string:description", + "type": "form", + "permissions": ["permissionName"], + "readPermission": "", + "writePermission": "", + "visible": true, + "uri":"scheme://authority/path/query" + "skills": [ + { + "actions": [], + "entities": [], + "uris": [] + } + ], + "metadata": [ + { + "name": "ohos.extability.form", + "resource": "$profile:form_config", + } + ] + } + ] + } } ``` #### definePermissions对象内部结构 -该标签标识hap定义的权限。 +该标签标识HAP定义的权限。该标签只支持系统应用配置。 -表10 definePermissions定义权限字段说明 +表11 definePermission对象内部结构说明 | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | ---------------------- | ------------------------------------------------------------ | -------- | ------------------------------ | -| name | 标识权限的名称。 | 字符串 | 不可缺省 | -| grantMode | 标识权限的授予方式,授予模式如下:
system_grant:安装后系统自动授予该权限。
user_grant:使用动态申请,用户授权后才可使用 | 字符串 | 可缺省,缺省值为system_grant。 | -| availableLevel | 标识权限限制门限,可选值为"system_core"、"system_basic"、"normal"。该标签有缺省值,缺省值为normal。权限范围如下:
system_core:系统核心权限。
system_basic:系统基础权限。
normal:普通权限。所有应用允许申请的权限。 | 字符串 | 可缺省,缺省值为"normal" | -| provisionEnable | 标识权限是否支持证书方式申请权限,包括高级别的权限,true标识需要开发者可以通过provision证书acls方式申请权限。 | 布尔值 | 可缺省,缺省值为true | -| distributedSceneEnable | 标识权限是否支持分布式场景下使用该权限。 | 布尔值 | 可缺省,缺省值为false | -| label | 标识权限的简短描述,配置为对描述内容的资源索引。 | 字符串 | 可缺省,缺省值为空 | -| description | 标识权限的详细描述,可以是表示描述内容的字符串,也可以是对描述内容的资源索引。 | 字符串 | 可缺省,缺省值为空 | +| name | 标识权限的名称。 | 字符串 | 不可缺省。 | +| grantMode | 标识权限的授予方式,授予模式如下:
system_grant:安装后系统自动授予该权限。
user_grant:应用动态申请,用户授权后才可使用 | 字符串 | 可缺省,缺省值为"system_grant"。 | +| availableLevel | 标识权限限制门限,可选值为system_core、system_basic、normal。
system_core:系统核心权限。
system_basic:系统基础权限。
normal:普通权限。所有应用允许申请的权限。 | 字符串 | 可缺省,缺省值为"normal"。 | +| provisionEnable | 标识权限是否支持证书方式申请权限,包括高级别的权限,true标识需要开发者可以通过provision证书acls方式申请权限。 | 布尔值 | 可缺省,缺省值为true。 | +| distributedSceneEnable | 标识权限是否支持分布式场景下使用该权限。 | 布尔值 | 可缺省,缺省值为false。 | +| label | 标识权限的简短描述,配置为对描述内容的资源索引。 | 字符串 | 可缺省,缺省值为空。 | +| description | 标识权限的详细描述,可以是表示描述内容的字符串,也可以是对描述内容的资源索引。 | 字符串 | 可缺省,缺省值为空。 | + +definePermissions示例 : + +```json +{ + "module": { + "definePermissions": [ + { + "name": "permissionName", + "grantMode": "user_grant", + "availableLevel": "system_basic", + "provisionEnable": false, + "distributedSceneEnable": true, + "label" : "$string:label", + "description": "$string:description" + } + ] + } +} + +``` #### requestPermissions对象内部结构 该标签标识应用运行时需向系统申请的权限集合。 -表11 requestPermissions权限申请字段说明 +表12 requestPermission对象内部结构说明 -| 属性名称 | 含义 | **类型** | **取值范围** | **默认值** | **规则约束** | -| --------- | ------------------------------------------------------------ | ---------------------------------------- | ------------------------------------------------------------ | -------------------- | ------------------------------------------------------------ | -| name | 必须,填写需要使用的权限名称。 | 字符串 | 自定义 | 无 | 未填写时,解析失败。 | -| reason | 可选,当申请的权限为user_grant权限时此字段必填。描述申请权限的原因。 | 字符串 | 使用string类资源引用。格式为`$string: ***`。 | 空 | user_grant权限必填,否则不允许在应用市场上架。需做多语种适配。 | -| usedScene | 可选,当申请的权限为user_grant权限时此字段必填。描述权限使用的场景和时机。场景类型有 :ability、when(调用时机)。可配置多个ability。 | abilities:ability字符串数组,when:字符串 | abilities:ability的名称,when:inuse(使用时)、always(始终) | abilities:空 when:空 | user_grant权限必填abilities,可选填when。 | +| 属性名称 | 含义 | 数据类型 | 是否可缺省 | +| ------| ------| -------- | ------------------------------ | +| name | 需要申请的权限名称。| 字符串 | 不可缺省。 | +| reason | 申请权限的原因。配置为描述内容的资源索引,以支持多语言。 | 字符串 | 可缺省,缺省值为空。当申请权限的grantMode为user_grant时不可缺省。 | +| usedScene | 权限使用的场景和时机。参考[usedScene对象内部结构](#usedscene对象内部结构)。| 对象 | 可缺省,缺省值为空。当申请权限的grantMode为user_grant时不可缺省。 | -requestPermissions示例 : +requestPermissions示例 : ```json { - "name": "ohos.abilitydemo.permission.PROVIDER", - "reason": "$string:reason", - "usedScene": { - "abilities": [ - "AudioAbility", - "VideoAbility", - ], - "when": "inuse" - } + "module": { + "requestPermissions": [ + { + "name": "permissionName", + "reason": "$string:reason", + "usedScene": { + "abilities": [ + "AudioAbility", + "VideoAbility" + ], + "when": "inuse" + } + } + ] + } } ``` + 权限访问的更多说明,可参考[访问控制开发指导](../security/accesstoken-guidelines.md) -#### form对象内部结构 +#### usedScene对象内部结构 + +该标签标识权限使用的场景和时机。 + +表13 usedScene对象内部结构说明 + +| 属性名称 | 含义 | 数据类型 | 是否可缺省 | +| ------- | --------------------| -------- | ------ | +| abilities | 标识需要使用到该权限的ability。| 字符串数组 | 不可缺省。 | +| when | 标识使用该权限的时机,可选值为inuse和always。inuse表示仅前台使用,always表示前后台都可使用 | 字符串 | 可缺省,缺省值为空。 | -forms标签标识卡片的配置,form卡片是可以嵌入桌面上并接收定期更新的应用简要视图。在以下场景中可以包含form标签。 -1. extensions中指定type为form。 +usedScene示例 : + +```json +{ + "module": { + "requestPermissions": [ + { + "usedScene": { + "abilities": [ + "AudioAbility", + "VideoAbility" + ], + "when": "inuse" + } + } + ] + } +} +``` + +#### forms对象内部结构 -2. metadata中指定form信息,其中 : - name :指定form的名称。使用ohos.extability.form作为form信息的标识。 - resource :指定form信息的资源位置。 +forms标签标识卡片的配置,form卡片是可以嵌入桌面上并接收定期更新的应用简要视图。
+配置方式如下:
+extensionAbility标签配置type为form,并配置metadata信息:name :"ohos.extability.form"。resource :指定form信息的资源位置。 -表12 forms对象的内部结构说明 +表14 form对象内部结构说明 | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | ------------------- | ------------------------------------------------------------ | ---------- | ----------------------------- | -| name | 标识卡片的类名。字符串最大长度为127字节。 | 字符串 | 否 | -| description | 标识卡片的描述。取值可以是描述性内容,也可以是对描述性内容的资源索引,以支持多语言。字符串最大长度为255字节。 | 字符串 | 可缺省,缺省为空。 | -| src | 该标签标识JS卡片对应的UI代码。建议开发者通过自适应布局显示不同规格卡片,如果不同规格卡片布局相差较大,建议通过不同卡片来区分。 | 字符串 | 可缺省,缺省为空。 | -| window | 该标签标识JS卡片的自适应能力。window结构参考表12。 | 对象 | 可缺省,缺省为空。 | -| isDefault | 标识该卡片是否为默认卡片,每个Ability有且只有一个默认卡片。 true :默认卡片。 false :非默认卡片。 | 布尔值 | 否 | -| colorMode | 标识卡片的主题样式,取值范围如下 : auto :自适应。 dark :深色主题。 light :浅色主题。 | 字符串 | 可缺省,缺省值为“auto”。 | -| supportDimensions | 标识卡片支持的外观规格,取值范围 : 1 * 2 :表示1行2列的二宫格。 2 * 1 :表示2行1列的二宫格。 2 * 2 :表示2行2列的四宫格。 2 * 4 :表示2行4列的八宫格。 4 * 4 :表示4行4列的十六宫格。 | 字符串数组 | 否 | -| defaultDimension | 标识卡片的默认外观规格,取值必须在该卡片supportDimensions配置的列表中。 | 字符串 | 否 | -| updateEnabled | 该标签标识该卡片是否支持实时刷新,true标识卡片支持实时刷新,false标识不支持。 | 布尔值 | 否 | -| scheduledUpdateTime | 该标签标识卡片定点刷新的时间,采用24小时计数,精确到分钟。 | 字符串 | 是 | -| updateDuration | 该标签标识卡片定时刷新的更新频率,单位为30分钟,取值为30的倍数值。卡片的最高频率为每30分钟刷新一次,和定点刷新二选一,二者都配置的情况下,定时优先。 | 数值 | 可缺省,缺省为空。 | -| metadata | 该标签标识卡片的自定义信息。metadata内部结构参考表5。 | 对象 | 可缺省,缺省为空。 | -| formConfigAbility | 该标签标识卡片调整的Ability名称。标签值为字符串类型(最长127字符)。该标签值必须满足下面的格式 :
ability://单个ability名字
单个ability名字必须为本应用的ability。 | 字符串 | 可缺省,缺省为空。 | -| formVisibleNotify | 该标签标识卡片是否被允许使用卡片可见性通知。标签值为true或false | 布尔值 | 该标签可缺省,默认值为false。 | - -表13 window内部结构说明 - -| 属性名称 | 含义 | 数据类型 | 是否可缺省 | -| --------------- | ------------------------------------------------------------ | -------- | -------------------- | -| designWidth | 指示页面设计的基线宽度,以像素为单位。 元素的大小由实际设备宽度缩放。 这个标签是一个整数。 | 数值 | 可缺省,缺省值为空。 | -| autoDesignWidth | 指定是否自动计算页面设计的基线宽度。 如果设置为true,则designWidth属性无效。基线宽度根据设备宽度和屏幕密度计算。 | 布尔值 | 可缺省,缺省值为空。 | +| name | 标识卡片的名称。最大长度为127字节。 | 字符串 | 不可缺省。 | +| description | 标识卡片的描述。取值可以是描述性内容,也可以是对描述性内容的资源索引,以支持多语言。最大长度为255字节。 | 字符串 | 可缺省,缺省值为空。 | +| src | 该标签标识JS卡片对应的UI代码。建议开发者通过自适应布局显示不同规格卡片,如果不同规格卡片布局相差较大,建议通过不同卡片来区分。 | 字符串 | 可缺省,缺省值为空。 | +| window | 该标签标识JS卡片的自适应能力。参考[window对象内部结构](#window对象内部结构)。 | 对象 | 可缺省,缺省值为空。 | +| isDefault | 标识该卡片是否为默认卡片,每个Ability有且只有一个默认卡片。 true :默认卡片。 false :非默认卡片。 | 布尔值 | 不可缺省。 | +| colorMode | 标识卡片的主题样式,取值范围如下 :
auto :自适应。
dark :深色主题。
light :浅色主题。
| 字符串 | 可缺省,缺省值为“auto”。 | +| supportDimensions | 标识卡片支持的外观规格,取值范围 :
1 * 2 :表示1行2列的二宫格。
2 * 1 :表示2行1列的二宫格。
2 * 2 :表示2行2列的四宫格。
2 * 4 :表示2行4列的八宫格。
4 * 4 :表示4行4列的十六宫格。 | 字符串数组 | 不可缺省。 | +| defaultDimension | 标识卡片的默认外观规格,取值必须在该卡片supportDimensions配置的列表中。 | 字符串 | 不可缺省。 | +| updateEnabled | 该标签标识该卡片是否支持实时刷新,true标识卡片支持实时刷新,false表示不支持。 | 布尔值 | 不可缺省。 | +| scheduledUpdateTime | 该标签标识卡片定点刷新的时间,采用24小时计数,精确到分钟。 | 字符串 | 可缺省,缺省值为空。 | +| updateDuration | 该标签标识卡片定时刷新的更新频率,单位为30分钟,取值为30的倍数。卡片的最高频率为每30分钟刷新一次,和定点刷新二选一,二者都配置的情况下,定时优先。 | 数值 | 可缺省,缺省值为空。 | +| metadata | 该标签标识卡片的元信息。参考[metadata对象内部结构](#metadata对象内部结构)。 | 对象数组 | 可缺省,缺省值为空。 | +| formConfigAbility | 该标签标识卡片调整的Ability名称。最大长度127字节。该标签值必须满足下面的格式 :
ability://单个ability名字
单个ability名字必须为本应用的ability。 | 字符串 | 可缺省,缺省值为空。 | +| formVisibleNotify | 该标签标识卡片是否被允许使用卡片可见性通知。 | 布尔值 | 可缺省,缺省值为false。 | form示例 : -在开发视图的resources/base/profile下面定义配置文件form_config.json(文件名称可由开发者定义) +1.在开发视图的resources/base/profile下面定义配置文件form_config.json(文件名称可由开发者定义): ```json { "forms": [ { "name": "Form_Js", - "description": "$string:form_description", + "description": "$string:description", "src": "./js/pages/card/index", "window": { "designWidth": 720, "autoDesignWidth": true }, "colorMode": "auto", - "formConfigAbility": "ability://xxxxx", + "formConfigAbility": "ability://xxx", "formVisibleNotify": false, "isDefault": true, "updateEnabled": true, @@ -593,200 +672,221 @@ form示例 : "updateDuration": 1, "defaultDimension": "2*2", "updateEnabled": true, - "scheduledUpdateTime": "21:33", "supportDimensions": [ "2*2" ], "metadata": [ - { - "name": "string", - "value": "string", - "resource": "$profile:config_file" - } + { + "name": "name", + "value": "value", + "resource": "$profile:resource" + } ] } ] } ``` -在module.json5的extension组件下面定义metadata信息 +2.在module.json5的extensionAbilities标签下定义metadata信息 : ```json { - "extensionAbilities": [{ - "name": "MyForm", - "type": "form", - "metadata": [{ - "name": "ohos.extability.form", - "resource": "$profile:form_config" - }] - }] + "module": { + "extensionAbilities": [ + { + "type": "form", + "metadata": [ + { + "name": "ohos.extability.form", + "resource": "$profile:form_config" + } + ] + } + ] + } } ``` #### shortcuts对象内部结构 -标识应用的快捷方式信息。标签值为数组,最多可以配置四个快捷方式。其包含四个子标签shortcutId、label、icon、wants。 - -metadata中指定shortcut信息,其中 : -1)name :指定shortcuts的名称。使用ohos.ability.shortcuts作为shortcuts信息的标识。 -2)resource :指定shortcuts信息的资源位置。 +标识应用的快捷方式信息。最多可以配置四个快捷方式。
+配置方式如下:
+ability标签配置metadata信息。name :"ohos.ability.shortcuts"。resource :指定shortcuts信息的资源位置。 -表14 shortcuts对象的内部结构说明 +表15 shortcut对象内部结构说明 | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | ---------- | ------------------------------------------------------------ | -------- | -------------------------- | -| shortcutId | 标识快捷方式的ID。字符串的最大长度为63字节。 | 字符串 | 否 | -| label | 标识快捷方式的标签信息,即快捷方式对外显示的文字描述信息。取值可以是描述性内容,也可以是标识label的资源索引。字符串最大长度为63字节。 | 字符串 | 可缺省,缺省为空。 | -| icon | 该标签标识shortcut的图标,标签值为资源文件的索引。 | 字符串 | 该标签可缺省,缺省值为空。 | -| wants | 该标签标识快捷方式内定义的目标wants信息集合,每个want可配置两个子标签,bundleName,abilityName。
bundleName :快捷方式目标包名,字符串类型。
abilityName :快捷方式的目标组件名,字符串类型。 | 对象 | 该标签可缺省,缺省为空。 | +| shortcutId | 标识快捷方式的ID。最大长度为63字节。 | 字符串 | 不可缺省。 | +| label | 标识快捷方式的标签信息,即快捷方式对外显示的文字描述信息。取值可以是描述性内容,也可以是标识label的资源索引。字符串最大长度为63字节。 | 字符串 | 可缺省,缺省值为空。 | +| icon | 该标签标识shortcut的图标,标签值为资源文件的索引。 | 字符串 | 可缺省,缺省值为空。 | +| wants | 该标签标识快捷方式内定义的目标wants信息集合,每个want可配置两个子标签,bundleName,abilityName。
bundleName :快捷方式目标包名,字符串类型。
abilityName :快捷方式的目标组件名,字符串类型。 | 对象数组 | 可缺省,缺省值为空。 | -在开发视图的resources/base/profile下面定义配置文件shortcut_config.json(文件名称可由开发者定义)。 +shortcuts示例 : + +1.在开发视图的resources/base/profile下面定义配置文件shortcuts_config.json(文件名称可由开发者定义): ```json { - "shortcuts": [{ - "shortcutId": "id_test1", - "label": "$string:shortcut", - "icon": "$media:aa_icon", - "wants": [{ - "bundleName": "com.ohos.hello", - "abilityName": "MainAbility" - }] - }] + "shortcuts": [ + { + "shortcutId": "shortcut_id", + "label": "$string:label", + "icon": "$media:icon", + "wants": [ + { + "bundleName": "bundleName", + "abilityName": "abilityName" + } + ] + } + ] } ``` -在module.json5的module下面定义metadata信息,如下 : +2.在module.json5的abilities标签下定义metadata信息 : ```json { "module": { - "name": "MyAbilityStage", - "abilities": [{ - "name": "MyAbility", - "srcEntrance": "./abilities/MyAbility.ts", - "skills": [{ - "actions": ["action.system.home"], - "entities": ["entity.system.home"], - "uris": [] - }], - "metadata": [{ - "name": "ohos.ability.shortcuts", - "resource": "$profile:shortcuts_config" - }] - }] + "abilities": [ + { + "name": "MainAbility", + "srcEntrance": "./abilities/MainAbility.ts", + "skills": [ + { + "actions": ["action.system.home"], + "entities": ["entity.system.home"] + } + ], + "metadata": [ + { + "name": "ohos.ability.shortcuts", + "resource": "$profile:shortcuts_config" + } + ] + } + ] } } ``` #### commonEvents对象内部结构 -commonEvents标签标识注册静态公共事件信息。标签值为数组。 -metadata中指定commonEvent信息,其中 : - -1. name :指定commonEvent的名称。使用ohos.extability.staticSubscriber作为commonEvent信息的标识。 +commonEvents标签标识注册静态公共事件信息。
+配置方式如下:
+extensionAbility标签配置type为staticSubscriber,并配置metadata信息:name :"ohos.extability.staticSubscriber"。resource :指定commonEvents信息的资源位置。 -2. resource :指定commonEvent信息的资源位置。 - -表15 commonEvents对象内部结构 +表16 commonEvent对象内部结构 | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | ---------- | ------------------------------------------------------------ | ---------- | -------------------------- | -| name | 该标签指明当前静态公共事件对应的ability名,该类需要在ability中标明。 | 字符串 | 该标签不可缺省。 | +| name | 该标签指明当前静态公共事件对应的ability名,该类需要在ability中标明。 | 字符串 | 不可缺省。 | | permission | 该标签标识实现该静态公共事件需要申请的权限,以字符串类型表示一个权限名称,通常采用反向域名方式表示(最大255字节)。 | 字符串 | 可缺省,缺省值为空。 | -| types | 该标签配置当前静态公共事件的类别数组,字符串数组类型,每个数组元素为一个类别名称。 | 字符串数组 | 该标签可缺省,缺省值为空。 | -| events | 该标签标识能够接收的意图的event值的集合,取值通常为系统预定义的event值,也允许自定义。 | 字符串数组 | 该标签不可缺省。 | +| types | 该标签配置当前静态公共事件的类别数组,字符串数组类型,每个数组元素为一个类别名称。 | 字符串数组 | 可缺省,缺省值为空。 | +| events | 该标签标识能够接收的意图的event值的集合,取值通常为系统预定义的event值,也允许自定义。 | 字符串数组 | 不可缺省。 | + +commonEvents示例 : -在开发视图的resources/base/profile下面定义配置文件common_event_config.json(文件名称可由开发者定义)。 +1.在开发视图的resources/base/profile下面定义配置文件common_event_config.json(文件名称可由开发者定义): ```json { - "commonEvents": [{ - "name": "abilityName", - "permission": "string", - "types": [ - "string", - "string" - ], - "events": [ - "string", - "string" - ] - }] + "commonEvents": [ + { + "name": "abilityName", + "permission": "permissionName", + "types": [ + "type1", + "type2" + ], + "events": [ + "event1", + "event2" + ] + } + ] } ``` -在module.json5的extension组件下面定义metadata信息,如下 : +2.在module.json5的extensionAbilities标签下定义metadata信息 : ```json -"extensionAbilities": [ - { - "name": "mySubscriber", - "srcEntrance": "./extension/my_subscriber.js", - "type": "staticSubscriber", - "metadata": [{ - "name": "ohos.extability.staticSubscriber", - "resource": "$profile:common_event_config", - }], +{ + "module": { + "extensionAbilities": [ + { + "name": "subscriber", + "srcEntrance": "./extension/subscriber.js", + "type": "staticSubscriber", + "metadata": [ + { + "name": "ohos.extability.staticSubscriber", + "resource": "$profile:common_event_config" + } + ] + } + ] } -] +} ``` #### distroFilter对象内部结构 标识应用的分发规则。 -该标签用于定义HAP包对应的细分设备规格的分发策略,以便在应用市场进行云端分发应用包时做精准匹配。该标签可配置的分发策略维度包括API Version、屏幕形状、屏幕分辨率。在进行分发时,通过deviceType与这三个属性的匹配关系,唯一确定一个用于分发到设备的HAP。 +该标签用于定义HAP包对应的细分设备规格的分发策略,以便在应用市场进行云端分发应用包时做精准匹配。该标签可配置的分发策略维度包括API Version、屏幕形状、窗口分辨率、屏幕分辨率、国家码。在进行分发时,通过deviceType与这五个属性的匹配关系,唯一确定一个用于分发到设备的HAP。
+配置方式如下:
+module标签配置metadata信息。name :"ohos.module.distro"。resource :指定distroFilter信息的资源位置。 -表16 distroFilter对象内部结构 +表17 distroFilter对象内部结构 | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | ------------- | ------------------------------------------------------------ | -------- | -------------------------- | -| apiVersion | 标识支持的apiVersion范围。参考表16。 | 对象数组 | 该标签可缺省,缺省值为空。 | -| screenShape | 标识屏幕形状的支持策略。 | 对象数组 | 该标签可缺省,缺省值为空。 | -| screenWindow | 标识应用运行时窗口的分辨率支持策略。该字段仅支持对轻量级智能穿戴设备进行配置。 | 对象数组 | 该标签可缺省,缺省值为空。 | -| screenDensity | 该标签标识屏幕的像素密度(dpi :Dot Per Inch)。该字段可选,如果配置了该字段,取值必须合法。该标签为字符串数组,字符串范围如下。
sdpi :表示小规模的屏幕密度(Small-scale Dots per Inch),适用于dpi取值为(0,120]的设备。
mdpi :表示中规模的屏幕密度(Medium-scale Dots Per Inch),适用于dpi取值为(120,160]的设备。
ldpi :表示大规模的屏幕密度(Large-scale Dots Per Inch),适用于dpi取值为(160,240]的设备。
xldpi :表示大规模的屏幕密度(Extra Large-scale Dots Per Inch),适用于dpi取值为(240,320]的设备。
xxldpi :表示大规模的屏幕密度(Extra Extra Large-scale Dots Per Inch),适用于dpi取值为(320,480]的设备。
xxxldpi :表示大规模的屏幕密度(Extra Extra Extra Large-scale Dots Per Inch),适用于dpi取值为(480, 640]的设备。 | 对象数组 | 该标签可缺省,缺省值为空。 | -| countryCode | 该标签标识应用需要分发的国家地区码,具体值以ISO-3166-1标准为准。支持多个国家和地区枚举定义。该字段可选,如果配置了该字段,取值必须合法。标签值字符串数组,子串表示所支持的国家或地区,由两个大写字母组成。 | 对象数组 | 该标签可缺省,缺省值为空。 | +| apiVersion | 标识支持的apiVersion。 | 对象 | 可缺省,缺省值为空。 | +| screenShape | 标识屏幕形状的支持策略。仅支持liteWearable设备配置。 | 对象 | 可缺省,缺省值为空。 | +| screenWindow | 标识应用运行时窗口的分辨率支持策略。仅支持liteWearable设备配置。 | 对象 | 可缺省,缺省值为空。 | +| screenDensity | 标识屏幕的像素密度(dpi : Dot Per Inch)。 | 对象 | 可缺省,缺省值为空。 | +| countryCode | 标识应用需要分发的国家地区码。具体值以ISO-3166-1标准为准。 | 对象 | 可缺省,缺省值为空。 | -表17 apiVersion对象的内部结构说明 +表18 apiVersion对象内部结构 | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | ------------------------------------------------------------ | -------- | -------------------- | -| policy | 标识该子属性取值的黑白名单规则。配置为“exclude”或“include”。“include”表示该字段取值为白名单,满足value枚举值匹配规则的表示匹配该属性。 | 字符串 | 可缺省,缺省值为空。 | -| value | 支持的取值为API Version存在的整数值,例如4、5、6。场景示例 :某应用,针对相同设备型号,同时在网的为使用API 5和API 6开发的两个软件版本,则允许上架2个entry类型的安装包,分别支持到对应设备侧软件版本的分发。 | 数组 | 可缺省,缺省值为空。 | +| policy | 标识该子属性取值的黑白名单规则。配置为"exclude"或"include"。"include"表示该字段取值为白名单,满足value枚举值匹配规则的表示匹配该属性。 | 字符串 | 可缺省,缺省值为空。 | +| value | 支持的取值为API Version存在的整数值,例如4、5、6,最小取值为3。场景示例 :某应用,针对相同设备型号,同时在网的为使用API 5和API 6开发的两个软件版本,则允许上架2个entry类型的安装包,分别支持到对应设备侧软件版本的分发。 | 数值数组 | 可缺省,缺省值为空。 | -表18 screenShape对象的内部结构说明 +表19 screenShape对象内部结构 | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | ------------------------------------------------------------ | -------- | -------------------- | -| policy | 标识该子属性取值的黑白名单规则。配置为“exclude”或“include”。“include”表示该字段取值为白名单,满足value枚举值匹配规则的表示匹配该属性。 | 字符串 | 可缺省,缺省值为空。 | -| value | 支持的取值为circle(圆形)、rect(矩形)。场景示例 :针对智能穿戴设备,可为圆形表盘和矩形表盘分别提供不同的HAP。 | 数组 | 可缺省,缺省值为空。 | +| policy | 标识该子属性取值的黑白名单规则。配置为"exclude"或"include"。"include"表示该字段取值为白名单,满足value枚举值匹配规则的表示匹配该属性。 | 字符串 | 可缺省,缺省值为空。 | +| value | 支持的取值为circle(圆形屏幕)、rect(矩形屏幕)。场景示例:针对智能穿戴设备,可为圆形表盘和矩形表盘分别提供不同的HAP。 | 字符串数组 | 可缺省,缺省值为空。 | -表19 screenWindow对象的内部结构说明 +表20 screenWindow对象内部结构 | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | ------------------------------------------------------------ | -------- | -------------------- | -| policy | 标识该子属性取值的黑白名单规则。配置为“exclude”或“include”。“include”表示该字段取值为白名单,满足value枚举值匹配规则的表示匹配该属性。 | 字符串 | 可缺省,缺省值为空。 | -| value | 单个字符串的取值格式为 :“宽 * 高”,取值为整数像素值,例如“454 * 454”。 | 数组 | 可缺省,缺省值为空。 | +| policy | 标识该子属性取值的黑白名单规则。配置为"include"。"include"表示该字段取值为白名单,满足value枚举值匹配规则的表示匹配该属性。 | 字符串 | 可缺省,缺省值为空。 | +| value | 单个字符串的取值格式为 :“宽 * 高”,取值为整数像素值,例如“454 * 454”。 | 字符串数组 | 可缺省,缺省值为空。 | -表20 screenDensity对象的内部结构说明 +表21 screenDensity对象内部结构 | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | ------------------------------------------------------------ | -------- | -------------------- | -| policy | 标识该子属性取值的黑白名单规则。配置为“exclude”或“include”。“include”表示该字段取值为白名单,满足value枚举值匹配规则的表示匹配该属性。 | 字符串 | 可缺省,缺省值为空。 | -| value | 该标签标识屏幕的像素密度(dpi :Dot Per Inch)。 | 数组 | 可缺省,缺省值为空。 | +| policy | 标识该子属性取值的黑白名单规则。配置为"exclude"或"include"。"include"表示该字段取值为白名单,满足value枚举值匹配规则的表示匹配该属性。 | 字符串 | 可缺省,缺省值为空。 | +| value | 字符串范围如下:
sdpi :表示小规模的屏幕密度(Small-scale Dots per Inch),适用于dpi取值为(0,120]的设备。
mdpi :表示中规模的屏幕密度(Medium-scale Dots Per Inch),适用于dpi取值为(120,160]的设备。
ldpi :表示大规模的屏幕密度(Large-scale Dots Per Inch),适用于dpi取值为(160,240]的设备。
xldpi :表示大规模的屏幕密度(Extra Large-scale Dots Per Inch),适用于dpi取值为(240,320]的设备。
xxldpi :表示大规模的屏幕密度(Extra Extra Large-scale Dots Per Inch),适用于dpi取值为(320,480]的设备。
xxxldpi :表示大规模的屏幕密度(Extra Extra Extra Large-scale Dots Per Inch),适用于dpi取值为(480, 640]的设备。 | 字符串数组 | 可缺省,缺省值为空。 | -表21 countryCode对象的内部结构说明 +表22 countryCode对象内部结构 | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | ------------------------------------------------------------ | -------- | -------------------- | -| policy | 标识该子属性取值的黑白名单规则。配置为“exclude”或“include”。“include”表示该字段取值为白名单,满足value枚举值匹配规则的表示匹配该属性。 | 字符串 | 可缺省,缺省值为空。 | -| value | 该标签标识应用需要分发的国家地区码。 | 数组 | 可缺省,缺省值为空。 | +| policy | 标识该子属性取值的黑白名单规则。配置为"exclude"或"include"。"include"表示该字段取值为白名单,满足value枚举值匹配规则的表示匹配该属性。 | 字符串 | 可缺省,缺省值为空。 | +| value | 支持多个国家和地区枚举定义。字符串表示所支持的国家或地区,由两个大写字母组成。 | 字符串数组 | 可缺省,缺省值为空。 | distroFilter示例 : -在开发视图的resources/base/profile下面定义配置文件distroFilter_config.json(文件名称可由开发者定义)。 +1.在开发视图的resources/base/profile下面定义配置文件distro_filter_config.json(文件名称可由开发者定义): ```json "distroFilter": [ @@ -802,39 +902,50 @@ distroFilter示例 : "screenWindow": { "policy": "include", "value": ["454*454", "466*466"] + }, + "screenDensity": { + "policy": "exclude", + "value": ["ldpi", "xldpi"] + }, + "countryCode": { + "policy": "include", + "value": ["CN", "HK"] } } ] ``` -在module.json5的extensionAbilities组件下面定义metadata信息,如下 : +2.在module.json5的module标签下定义metadata信息 : ```json -"extensionAbilities": [ - { - "name": "mySubscriber", - "srcEntrance": "./extension/my_subscriber.js", - "type": "staticSubscriber", - "metadata": [{ - "name": "ohos.extability.staticSubscriber", - "resource": "$profile:distroFilter_config", - }], +{ + "module":{ + "metadata": [ + { + "name": "ohos.module.distro", + "resource": "$profile:distro_filter_config" + } + ] } -] +} ``` #### testRunner对象内部结构 -表22 testRunner对象内部结构说明 +该标签用于支持对测试框架的配置 + +表23 testRunner对象内部结构 | 属性名称 | 含义 | 数据类型 | 是否可缺省 | | -------- | ---------------------- | -------- | ---------- | | name | 标识测试框架对象名称。 | 字符串 | 不可缺省。 | | srcPath | 标识测试框架代码路径。 | 字符串 | 不可缺省。 | +testRunner示例 : + ``` "testRunner": { - "name": "myTestRUnnerName", + "name": "testRunnerName", "srcPath": "etc/test/TestRunner.ts" } ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundle-appControl.md b/zh-cn/application-dev/reference/apis/js-apis-bundle-appControl.md new file mode 100644 index 0000000000000000000000000000000000000000..144887f76d9d62e5eda6ea2790bff6a2e38c4c24 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-bundle-appControl.md @@ -0,0 +1,394 @@ +# appControl模块 + +本模块提供应用拦截能力。对应用设置处置状态后,应用会被禁止运行;用户点击桌面图标时,会根据应用的处置状态,跳转到对应的页面。本模块支持对应用的处置状态进行设置、获取、删除。 + +> **说明:** +> +> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +本模块接口为系统接口。 + +## 导入模块 + +``` ts +import appControl from '@ohos.bundle.appControl' +``` + +## appControl.setDisposedStatus + +setDisposedStatus(appId: string, disposedWant: Want): Promise\ + +以异步方法设置应用的处置状态。使用Promise异步回调。成功返回null,失败返回对应错误信息。 + +**需要权限:** ohos.permission.MANAGE_DISPOSED_APP_STATUS + +**系统能力:** SystemCapability.BundleManager.BundleFramework.AppControl + +**系统API:** 此接口为系统接口,三方应用不支持调用。 + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ----------- | ------ | ---- | --------------------------------------- | +| appId | string | 是 | 需要设置处置状态的应用的appId。
appId是应用的唯一标识,由应用的包名和签名信息决定,可以通过getBundleInfo接口获取。 | +| disposedWant | Want | 是 | 对应用的处置意图。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------- | ------------------ | +| Promise\ | Promise对象。无返回结果的Promise对象。 | + +**错误码** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errcode-bundle.md)。 + +| 错误码 | 错误信息 | +| ------ | -------------------------------------- | +| 17700005 | The specified appId was not found. | + +**示例:** + +```ts +import appControl from '@ohos.bundle.appControl' +import bundleManager from '@ohos.bundle.bundleManager'; + +// 获取appId +var bundleName = 'com.example.myapplication'; +var appId; +try { + bundleManager.getBundleInfo(bundleName, BundleManager.BundleFlags.GET_BUNDLE_INFO_WITH_SIGNATURE_INFO) + .then((data) => { + appId = data.signatureInfo.appId; + }, error => { + console.error("getBundleInfo failed " + error.message); + }); +} catch (error) { + console.error("getBundleInfo failed " + error.message); +} + +var want = {bundleName: 'com.example.myapplication'}; + +try { + appControl.setDisposedStatus(appId, want) + .then(() => { + console.info('setDisposedStatus success'); + }).catch((error) => { + console.error('setDisposedStatus failed ' + error.message); + }); +} catch (error) { + console.error('setDisposedStatus failed ' + error.message); +} +``` + +## appControl.setDisposedStatus + +setDisposedStatus(appId: string, disposedWant: Want, callback: AsyncCallback\): void; + +以异步方法设置应用的处置状态。使用callback异步回调。成功返回null,失败返回对应错误信息。 + +**需要权限:** ohos.permission.MANAGE_DISPOSED_APP_STATUS + +**系统能力:** SystemCapability.BundleManager.BundleFramework.AppControl + +**系统API:** 此接口为系统接口,三方应用不支持调用 + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ----------- | ------------------------------- | ---- | --------------------------------------- | +| appId | string | 是 | 需要设置处置的应用的appId
appId是应用的唯一标识,由应用的包名和签名信息决定,可以通过getBundleInfo接口获取。 | +| disposedWant | Want | 是 | 对应用的处置意图。 | +| callback | AsyncCallback\ | 是 | 回调函数,当设置处置状态成功,err为undefined,否则为错误对象。 | + +**错误码** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errcode-bundle.md)。 + +| 错误码 | 错误信息 | +| ------ | -------------------------------------- | +| 17700005 | The specified appId was not found. | + +**示例:** + +```ts +import appControl from '@ohos.bundle.appControl' +import bundleManager from '@ohos.bundle.bundleManager'; + +// 获取appId +var bundleName = 'com.example.myapplication'; +var appId; +try { + bundleManager.getBundleInfo(bundleName, BundleManager.BundleFlags.GET_BUNDLE_INFO_WITH_SIGNATURE_INFO) + .then((data) => { + appId = data.signatureInfo.appId; + }, error => { + console.error("getBundleInfo failed " + error.message); + }); +} catch (error) { + console.error("getBundleInfo failed " + error.message); +} + +var want = {bundleName: 'com.example.myapplication'}; + +try { + appControl.setDisposedStatus(appId, want, (err, data) => { + if (err) { + console.error('setDisposedStatus failed ' + error.message); + return; + } + console.info('setDisposedStatus success'); + }); +} catch (error) { + console.error('setDisposedStatus failed ' + error.message); +} +``` + +## appControl.getDisposedStatus + +getDisposedStatus(appId: string): Promise\; + +以异步方法获取指定应用已设置的处置状态。使用Promise异步回调,成功返回应用的处置状态,失败返回对应错误信息。 + +**需要权限:** ohos.permission.MANAGE_DISPOSED_APP_STATUS + +**系统能力:** SystemCapability.BundleManager.BundleFramework.AppControl + +**系统API:** 此接口为系统接口,三方应用不支持调用 + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ----------- | ------ | ---- | --------------------------------------- | +| appId | string | 是 | 要查询的应用的appId
appId是应用的唯一标识,由应用的包名和签名信息决定,可以通过getBundleInfo接口获取。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------- | ------------------ | +| Promise\ | Promise对象,返回应用的处置状态。 | + +**错误码** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errcode-bundle.md)。 + +| 错误码 | 错误信息 | +| ------ | -------------------------------------- | +| 17700005 | The specified appId was not found. | + +**示例:** + +```ts +import appControl from '@ohos.bundle.appControl' +import bundleManager from '@ohos.bundle.bundleManager'; + +// 获取appId +var bundleName = 'com.example.myapplication'; +var appId; +try { + bundleManager.getBundleInfo(bundleName, BundleManager.BundleFlags.GET_BUNDLE_INFO_WITH_SIGNATURE_INFO) + .then((data) => { + appId = data.signatureInfo.appId; + }, error => { + console.error("getBundleInfo failed " + error.message); + }); +} catch (error) { + console.error("getBundleInfo failed " + error.message); +} + +try { + appControl.getDisposedStatus(appId) + .then((data) => { + console.info('getDisposedStatus success. DisposedStatus: ' + JSON.stringify(data)); + }).catch((error) => { + console.error('getDisposedStatus failed ' + error.message); + }); +} catch (error) { + console.error('getDisposedStatus failed ' + error.message); +} +``` + +## appControl.getDisposedStatus + +getDisposedStatus(appId: string, callback: AsyncCallback\): void; + +以异步方法获取指定应用的处置状态。使用callback异步回调,成功返回应用的处置状态,失败返回对应错误信息。 + +**需要权限:** ohos.permission.MANAGE_DISPOSED_APP_STATUS + +**系统能力:** SystemCapability.BundleManager.BundleFramework.AppControl + +**系统API:** 此接口为系统接口,三方应用不支持调用 + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ----------- | ------ | ---- | --------------------------------------- | +| appId | string | 是 | 要查询的应用的appId
appId是应用的唯一标识,由应用的包名和签名信息决定,可以通过getBundleInfo接口获取。 | +| callback | AsyncCallback\ | 是 | 回调函数。当获取应用的处置状态成功时,err为undefined,data为获取到的处置状态;否则为错误对象。 | + +**错误码** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errcode-bundle.md)。 + +| 错误码 | 错误信息 | +| ------ | -------------------------------------- | +| 17700005 | The specified appId was not found. | + +**示例:** + +```ts +import appControl from '@ohos.bundle.appControl' +import bundleManager from '@ohos.bundle.bundleManager'; + +// 获取appId +var bundleName = 'com.example.myapplication'; +var appId; +try { + bundleManager.getBundleInfo(bundleName, BundleManager.BundleFlags.GET_BUNDLE_INFO_WITH_SIGNATURE_INFO) + .then((data) => { + appId = data.signatureInfo.appId; + }, error => { + console.error("getBundleInfo failed " + error.message); + }); +} catch (error) { + console.error("getBundleInfo failed " + error.message); +} + +try { + appControl.getDisposedStatus(appId, (err, data) => { + if (err) { + console.error('getDisposedStatus failed ' + error.message); + return; + } + console.info('getDisposedStatus success. DisposedStatus: ' + JSON.stringify(data)); + }); +} catch (error) { + console.error('getDisposedStatus failed ' + error.message); +} +``` + +## appControl.deleteDisposedStatus + +deleteDisposedStatus(appId: string): Promise\ + +以异步方法删除应用的处置状态。使用promise异步回调,成功返回null,失败返回对应错误信息。 + +**需要权限:** ohos.permission.MANAGE_DISPOSED_APP_STATUS + +**系统能力:** SystemCapability.BundleManager.BundleFramework.AppControl + +**系统API:** 此接口为系统接口,三方应用不支持调用 + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ----------- | ------ | ---- | --------------------------------------- | +| appId | string | 是 | 要删除处置状态的应用的appId
appId是应用的唯一标识,由应用的包名和签名信息决定,可以通过getBundleInfo接口获取。 | | + +**返回值:** + +| 类型 | 说明 | +| ------------------------- | ------------------ | +| Promise\ | Promise对象,无返回结果的Promise对象 | + +**错误码** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errcode-bundle.md)。 + +| 错误码 | 错误信息 | +| ------ | -------------------------------------- | +| 17700005 | The specified appId was not found. | + +**示例:** + +```ts +import appControl from '@ohos.bundle.appControl' +import bundleManager from '@ohos.bundle.bundleManager'; + +// 获取appId +var bundleName = 'com.example.myapplication'; +var appId; +try { + bundleManager.getBundleInfo(bundleName, BundleManager.BundleFlags.GET_BUNDLE_INFO_WITH_SIGNATURE_INFO) + .then((data) => { + appId = data.signatureInfo.appId; + }, error => { + console.error("getBundleInfo failed " + error.message); + }); +} catch (error) { + console.error("getBundleInfo failed " + error.message); +} + +try { + appControl.deleteDisposedStatus(appId) + .then(() => { + console.info('deleteDisposedStatus success'); + }).catch((error) => { + console.error('deleteDisposedStatus failed ' + error.message); + }); +} catch (error) { + console.error('deleteDisposedStatus failed ' + error.message); +} +``` + +## appControl.deleteDisposedStatus + +deleteDisposedStatus(appId: string, callback: AsyncCallback\) : void + +以异步方法删除应用的处置状态。使用callback异步回调,成功返回null,失败返回对应错误信息。 + +**需要权限:** ohos.permission.MANAGE_DISPOSED_APP_STATUS + +**系统能力:** SystemCapability.BundleManager.BundleFramework.AppControl + +**系统API:** 此接口为系统接口,三方应用不支持调用 + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ----------- | ------ | ---- | --------------------------------------- | +| appId | string | 是 | 要查询的应用的appId。
appId是应用的唯一标识,由应用的包名和签名信息决定,可以通过getBundleInfo接口获取。 | +| callback | AsyncCallback\ | 是 | 回调函数,当设置处置状态成功时,err返回undefined。否则回调函数返回具体错误对象。 | + +**错误码** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errcode-bundle.md)。 + +| 错误码 | 错误信息 | +| ------ | -------------------------------------- | +| 17700005 | The specified appId was not found. | + +**示例:** + +```ts +import appControl from '@ohos.bundle.appControl' +import bundleManager from '@ohos.bundle.bundleManager'; + +// 获取appId +var bundleName = 'com.example.myapplication'; +var appId; +try { + bundleManager.getBundleInfo(bundleName, BundleManager.BundleFlags.GET_BUNDLE_INFO_WITH_SIGNATURE_INFO) + .then((data) => { + appId = data.signatureInfo.appId; + }, error => { + console.error("getBundleInfo failed " + error.message); + }); +} catch (error) { + console.error("getBundleInfo failed " + error.message); +} + +try { + appControl.deleteDisposedStatus(appId, (err, data) => { + if (err) { + console.error('deleteDisposedStatus failed ' + error.message); + return; + } + console.info('deleteDisposedStatus success'); + }); +} catch (error) { + console.error('deleteDisposedStatus failed ' + error.message); +} +``` + diff --git a/zh-cn/application-dev/reference/apis/js-apis-geoLocationManager.md b/zh-cn/application-dev/reference/apis/js-apis-geoLocationManager.md new file mode 100644 index 0000000000000000000000000000000000000000..b0e51a6b414bbdb2b3d6f23ffd3559eae266f144 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-geoLocationManager.md @@ -0,0 +1,1279 @@ +# 位置服务 + +位置服务提供GNSS定位、网络定位、地理编码、逆地理编码、国家码和地理围栏等基本功能。 + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + + +## 导入模块 + +```ts +import geoLocationManager from '@ohos.geoLocationManager'; +``` + + +## geoLocationManager.on('countryCodeChange') + +on(type: 'countryCodeChange', callback: Callback<CountryCode>): void; + +订阅国家码信息变化事件。 + +**系统能力**:SystemCapability.Location.Location.Core + +**参数**: + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | type | string | 是 | 设置事件类型。type为“countryCodeChange”,表示订阅国家码信息变化事件。 | + | callback | Callback<[CountryCode](#countrycode)> | 是 | 接收国家码信息上报。 | + +**错误码**: + +以下错误码的详细介绍请参见[位置服务子系统错误码](../errorcodes/errorcode-geoLocationManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | +|3301500 | Failed to query the area information. | + + +**示例** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var callback = (code) => { + console.log('countryCodeChange: ' + JSON.stringify(code)); + } + geoLocationManager.on('countryCodeChange', callback); + ``` + + +## geoLocationManager.off('countryCodeChange') + +off(type: 'countryCodeChange', callback?: Callback<CountryCode>): void; + +取消订阅国家码变化事件。 + +**系统能力**:SystemCapability.Location.Location.Core + +**参数**: + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | type | string | 是 | 设置事件类型。type为“countryCodeChange”,表示取消订阅国家码信息变化事件。 | + | callback | Callback<[CountryCode](#countrycode)> | 是 | 接收国家码信息上报。 | + +**错误码**: + +以下错误码的详细介绍请参见[位置服务子系统错误码](../errorcodes/errorcode-geoLocationManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | +|3301500 | Failed to query the area information. | + +**示例** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var callback = (code) => { + console.log('countryCodeChange: ' + JSON.stringify(code)); + } + geoLocationManager.on('countryCodeChange', callback); + geoLocationManager.off('countryCodeChange', callback); + ``` + + +## geoLocationManager.enableLocation + +enableLocation(callback: AsyncCallback<void>): void; + +打开位置服务,使用callback回调异步返回结果。 + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +**需要权限**:ohos.permission.MANAGE_SECURE_SETTINGS + +**系统能力**:SystemCapability.Location.Location.Core + +**参数**: + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<void> | 是 | 用来接收错误码信息。 | + +**错误码**: + +以下错误码的详细介绍请参见[位置服务子系统错误码](../errorcodes/errorcode-geoLocationManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**示例** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + geoLocationManager.enableLocation((err, data) => { + if (err) { + console.log('enableLocation: err=' + JSON.stringify(err)); + } + }); + ``` + + +## geoLocationManager.enableLocation + +enableLocation(): Promise<void> + +打开位置服务,使用Promise方式异步返回结果。 + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +**需要权限**:ohos.permission.MANAGE_SECURE_SETTINGS + +**系统能力**:SystemCapability.Location.Location.Core + +**返回值**: + + | 参数名 | 说明 | + | -------- | -------- | + | Promise<void> | 返回错误码信息。 | + +**错误码**: + +以下错误码的详细介绍请参见[位置服务子系统错误码](../errorcodes/errorcode-geoLocationManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**示例** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + geoLocationManager.enableLocation().then((result) => { + console.log('promise, enableLocation succeed'); + }) + .catch((error) => { + console.log('promise, enableLocation: error=' + JSON.stringify(error)); + }); + ``` + +## geoLocationManager.disableLocation + +disableLocation(callback: AsyncCallback<void>): void; + +关闭位置服务,使用callback回调异步返回结果。 + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +**需要权限**:ohos.permission.MANAGE_SECURE_SETTINGS + +**系统能力**:SystemCapability.Location.Location.Core + +**参数**: + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<void> | 是 | 用来接收错误码的回调。 | + +**错误码**: + +以下错误码的详细介绍请参见[位置服务子系统错误码](../errorcodes/errorcode-geoLocationManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**示例** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + geoLocationManager.disableLocation((err, data) => { + if (err) { + console.log('disableLocation: err=' + JSON.stringify(err)); + } + }); + ``` + + +## geoLocationManager.disableLocation + +disableLocation(): Promise<void> + +关闭位置服务,使用Promise方式异步返回结果。 + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +**需要权限**:ohos.permission.MANAGE_SECURE_SETTINGS + +**系统能力**:SystemCapability.Location.Location.Core + +**返回值**: + + | 参数名 | 说明 | + | -------- | -------- | + | Promise<void> | 返回错误码。 | + +**错误码**: + +以下错误码的详细介绍请参见[位置服务子系统错误码](../errorcodes/errorcode-geoLocationManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**示例** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + geoLocationManager.disableLocation().then((result) => { + console.log('promise, disableLocation succeed'); + }) + .catch((error) => { + console.log('promise, disableLocation: error=' + JSON.stringify(error)); + }); + ``` + + +## geoLocationManager.isLocationPrivacyConfirmed + +isLocationPrivacyConfirmed(type : LocationPrivacyType, callback: AsyncCallback<boolean>): void; + +查询用户是否同意定位服务隐私申明,是否同意启用定位服务。只有系统应用才能调用。 + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +**系统能力**:SystemCapability.Location.Location.Core + +**参数**: + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | type | [LocationPrivacyType](#locationprivacytype)| 是 | 指定隐私申明场景,例如开机向导中的隐私申明、开启网络定位功能时弹出的隐私申明等。 | + | callback | AsyncCallback<boolean> | 是 | 表示用户是否同意定位服务隐私申明。 | + +**错误码**: + +以下错误码的详细介绍请参见[位置服务子系统错误码](../errorcodes/errorcode-geoLocationManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**示例** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + geoLocationManager.isLocationPrivacyConfirmed(1, (err, result) => { + if (err) { + console.log('isLocationPrivacyConfirmed: err=' + JSON.stringify(err)); + } + if (result) { + console.log('isLocationPrivacyConfirmed: result=' + JSON.stringify(result)); + } + }); + ``` + + +## geoLocationManager.isLocationPrivacyConfirmed + +isLocationPrivacyConfirmed(type : LocationPrivacyType,): Promise<boolean>; + +查询用户是否同意定位服务隐私申明,是否同意启用定位服务。只有系统应用才能调用。 + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +**系统能力**:SystemCapability.Location.Location.Core + +**参数**: + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | type | [LocationPrivacyType](#locationprivacytype) | 是 | 指定隐私申明场景,例如开机向导中的隐私申明、开启网络定位功能时弹出的隐私申明等。 | + +**返回值**: + + | 参数名 | 说明 | + | -------- | -------- | + | Promise<boolean> | 表示用户是否同意定位服务隐私申明。 | + +**错误码**: + +以下错误码的详细介绍请参见[位置服务子系统错误码](../errorcodes/errorcode-geoLocationManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**示例** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + geoLocationManager.isLocationPrivacyConfirmed(1).then((result) => { + console.log('promise, isLocationPrivacyConfirmed: ' + JSON.stringify(result)); + }); + ``` + + +## geoLocationManager.setLocationPrivacyConfirmStatus + +setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed: boolean, callback: AsyncCallback<void>): void; + +设置用户勾选定位服务隐私申明的状态,记录用户是否同意启用定位服务。只有系统应用才能调用。 + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +**需要权限**:ohos.permission.MANAGE_SECURE_SETTINGS + +**系统能力**:SystemCapability.Location.Location.Core + +**参数**: + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | type | [LocationPrivacyType](#locationprivacytype) | 是 | 指定隐私申明场景,例如开机向导中的隐私申明、开启网络定位功能时弹出的隐私申明等。 | + | isConfirmed | boolean | 是 | 表示用户是否同意定位服务隐私申明。 | + | callback | AsyncCallback<void> | 是 | 接收错误码信息。 | + +**错误码**: + +以下错误码的详细介绍请参见[位置服务子系统错误码](../errorcodes/errorcode-geoLocationManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**示例** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + geoLocationManager.setLocationPrivacyConfirmStatus(1, true, (err, result) => { + if (err) { + console.log('setLocationPrivacyConfirmStatus: err=' + JSON.stringify(err)); + } + }); + ``` + + +## geoLocationManager.setLocationPrivacyConfirmStatus + +setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed : boolean): Promise<void>; + +设置用户勾选定位服务隐私申明的状态,记录用户是否同意启用定位服务。只有系统应用才能调用。 + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +**需要权限**:ohos.permission.MANAGE_SECURE_SETTINGS + +**系统能力**:SystemCapability.Location.Location.Core + +**参数**: + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | type | [LocationPrivacyType](#locationprivacytype) | 是 | 指定隐私申明场景,例如开机向导中的隐私申明、开启网络定位功能时弹出的隐私申明等。 | + | isConfirmed | boolean | 是 | 表示用户是否同意定位服务隐私申明。 | + +**返回值**: + + | 参数名 | 说明 | + | -------- | -------- | + | Promise<void> | 接收错误码。 | + +**错误码**: + +以下错误码的详细介绍请参见[位置服务子系统错误码](../errorcodes/errorcode-geoLocationManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**示例** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + geoLocationManager.setLocationPrivacyConfirmStatus(1, true).then((result) => { + console.log('promise, setLocationPrivacyConfirmStatus succeed'); + }) + .catch((error) => { + console.log('promise, disableLocation: error=' + JSON.stringify(error)); + }); + ``` + + +## geoLocationManager.getCountryCode + +getCountryCode(callback: AsyncCallback<CountryCode>): void; + +查询当前的国家码。 + +**系统能力**:SystemCapability.Location.Location.Core + +**参数**: + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[CountryCode](#countrycode)> | 是 | 用来接收国家码。 | + +**错误码**: + +以下错误码的详细介绍请参见[位置服务子系统错误码](../errorcodes/errorcode-geoLocationManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301500 | Failed to query the area information.| + +**示例** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + geoLocationManager.getCountryCode((err, result) => { + if (err) { + console.log('getCountryCode: err=' + JSON.stringify(err)); + } + if (result) { + console.log('getCountryCode: result=' + JSON.stringify(result)); + } + }); + ``` + + +## geoLocationManager.getCountryCode + +getCountryCode(): Promise<CountryCode>; + +查询当前的国家码。 + +**系统能力**:SystemCapability.Location.Location.Core + +**参数**: + +无 + +**返回值**: + + | 参数名 | 说明 | + | -------- | -------- | + | Promise<[CountryCode](#countrycode)> | 返回国家码。 | + +**错误码**: + +以下错误码的详细介绍请参见[位置服务子系统错误码](../errorcodes/errorcode-geoLocationManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301500 | Failed to query the area information.| + +**示例** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + geoLocationManager.getCountryCode() + .then((result) => { + console.log('promise, getCountryCode: result=' + JSON.stringify(result)); + }) + .catch((error) => { + console.log('promise, getCountryCode: error=' + JSON.stringify(error)); + }); + ``` + + +## geoLocationManager.enableLocationMock + +enableLocationMock(callback: AsyncCallback<void>): void; + +使能位置模拟功能。 + +**系统能力**:SystemCapability.Location.Location.Core + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +**参数**: + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<void> | 是 | 用来接收执行结果,如果执行成功就返回nullptr,否则就返回错误信息。 | + +**错误码**: + +以下错误码的详细介绍请参见[位置服务子系统错误码](../errorcodes/errorcode-geoLocationManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off.| + +**示例** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + geoLocationManager.enableLocationMock((err, result) => { + if (err) { + console.log('enableLocationMock: err=' + JSON.stringify(err)); + } + }); + ``` + +## geoLocationManager.enableLocationMock + +enableLocationMock(): Promise<void>; + +使能位置模拟功能。 + +**系统能力**:SystemCapability.Location.Location.Core + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +**参数**: + +无 + +**返回值**: + + | 参数名 | 说明 | + | -------- | -------- | + | Promise<void> | 用来接收执行结果,如果执行成功就返回nullptr,否则就返回错误信息。 | + +**错误码**: + +以下错误码的详细介绍请参见[位置服务子系统错误码](../errorcodes/errorcode-geoLocationManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off.| + +**示例** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + geoLocationManager.enableLocationMock() + .then((result) => { + console.log('promise, enableLocationMock: succeed'); + }) + .catch((error) => { + if (error) { + console.log('promise, enableLocationMock: error=' + JSON.stringify(error)); + } + }); + ``` + + +## geoLocationManager.disableLocationMock + +disableLocationMock(callback: AsyncCallback<void>): void; + +去使能位置模拟功能。 + +**系统能力**:SystemCapability.Location.Location.Core + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +**参数**: + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<void> | 是 | 用来接收执行结果,如果执行成功就返回nullptr,否则就返回错误信息。 | + +**错误码**: + +以下错误码的详细介绍请参见[位置服务子系统错误码](../errorcodes/errorcode-geoLocationManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off.| + +**示例** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + geoLocationManager.disableLocationMock((err, result) => { + if (err) { + console.log('disableLocationMock: err=' + JSON.stringify(err)); + } + }); + ``` + + +## geoLocationManager.disableLocationMock + +disableLocationMock(): Promise<void>; + +去使能位置模拟功能。 + +**系统能力**:SystemCapability.Location.Location.Core + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +**参数**: + +无 + +**返回值**: + + | 参数名 | 说明 | + | -------- | -------- | + | Promise<void> | 用来接收执行结果,如果执行成功就返回nullptr,否则就返回错误信息。 | + +**错误码**: + +以下错误码的详细介绍请参见[位置服务子系统错误码](../errorcodes/errorcode-geoLocationManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off.| + +**示例** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + geoLocationManager.disableLocationMock() + .then((result) => { + console.log('promise, disableLocationMock succeed'); + }) + .catch((error) => { + if (error) { + console.log('promise, disableLocationMock: error=' + JSON.stringify(error)); + } + }); + ``` + + +## geoLocationManager.setMockedLocations + +setMockedLocations(config: LocationMockConfig, callback: AsyncCallback<void>): void; + +设置模拟的位置信息,后面会以该接口中携带的时间间隔上报模拟位置。 + +**系统能力**:SystemCapability.Location.Location.Core + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +**参数**: + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | config | [LocationMockConfig](#locationmockconfig) | 是 | 指示位置模拟的配置参数,包含模拟位置上报的时间间隔和模拟位置数组。 | + | callback | AsyncCallback<void> | 是 | 用来接收执行结果,如果执行成功就返回nullptr,否则就返回错误信息。 | + +**错误码**: + +以下错误码的详细介绍请参见[位置服务子系统错误码](../errorcodes/errorcode-geoLocationManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off.| + +**示例** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var locations = [ + {"latitude": 30.12, "longitude": 120.11, "altitude": 123, "accuracy": 1, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 1000000000, "additionSize": 0, "isFromMock": true}, + {"latitude": 31.13, "longitude": 121.11, "altitude": 123, "accuracy": 2, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 2000000000, "additionSize": 0, "isFromMock": true}, + {"latitude": 32.14, "longitude": 122.11, "altitude": 123, "accuracy": 3, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 3000000000, "additionSize": 0, "isFromMock": true}, + {"latitude": 33.15, "longitude": 123.11, "altitude": 123, "accuracy": 4, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 4000000000, "additionSize": 0, "isFromMock": true}, + {"latitude": 34.16, "longitude": 124.11, "altitude": 123, "accuracy": 5, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 5000000000, "additionSize": 0, "isFromMock": true} + ]; + var config = {"timeInterval": 5, "locations": locations}; + geoLocationManager.setMockedLocations(config, (err, data) => { + if (err) { + console.log('setMockedLocations: err=' + JSON.stringify(err)); + } + }); + ``` + +## geoLocationManager.setMockedLocations + +setMockedLocations(config: LocationMockConfig): Promise<void>; + +设置模拟的位置信息,后面会以该接口中携带的时间间隔上报模拟位置。 + +**系统能力**:SystemCapability.Location.Location.Core + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +**参数**: + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | config | [LocationMockConfig](#locationmockconfig) | 是 | 指示位置模拟的配置参数,包含模拟位置上报的时间间隔和模拟位置数组。 | + +**返回值**: + + | 参数名 | 说明 | + | -------- | -------- | + | Promise<void> | 用来接收执行结果,如果执行成功就返回nullptr,否则就返回错误信息。 | + +**错误码**: + +以下错误码的详细介绍请参见[位置服务子系统错误码](../errorcodes/errorcode-geoLocationManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off.| + +**示例** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var locations = [ + {"latitude": 30.12, "longitude": 120.11, "altitude": 123, "accuracy": 1, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 1000000000, "additionSize": 0, "isFromMock": true}, + {"latitude": 31.13, "longitude": 121.11, "altitude": 123, "accuracy": 2, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 2000000000, "additionSize": 0, "isFromMock": true}, + {"latitude": 32.14, "longitude": 122.11, "altitude": 123, "accuracy": 3, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 3000000000, "additionSize": 0, "isFromMock": true}, + {"latitude": 33.15, "longitude": 123.11, "altitude": 123, "accuracy": 4, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 4000000000, "additionSize": 0, "isFromMock": true}, + {"latitude": 34.16, "longitude": 124.11, "altitude": 123, "accuracy": 5, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 5000000000, "additionSize": 0, "isFromMock": true} + ]; + var config = {"timeInterval": 5, "locations":locations}; + geoLocationManager.setMockedLocations(config) + .then((result) => { + console.log('promise, setMockedLocations succeed'); + }) + .catch((error) => { + if (error) { + console.log('promise, setMockedLocations: error=' + JSON.stringify(error)); + } + }); + ``` + + +## geoLocationManager.enableReverseGeocodingMock + +enableReverseGeocodingMock(callback: AsyncCallback<void>): void; + +使能逆地理编码模拟功能。 + +**系统能力**:SystemCapability.Location.Location.Core + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +**参数**: + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<void> | 是 | 用来接收执行结果,如果执行成功就返回nullptr,否则就返回错误信息。 | + +**错误码**: + +以下错误码的详细介绍请参见[位置服务子系统错误码](../errorcodes/errorcode-geoLocationManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**示例** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + geoLocationManager.enableReverseGeocodingMock((err, data) => { + if (err) { + console.log('enableReverseGeocodingMock: err=' + JSON.stringify(err)); + } + }); + ``` + + +## geoLocationManager.enableReverseGeocodingMock + +enableReverseGeocodingMock(): Promise<void>; + +使能逆地理编码模拟功能。 + +**系统能力**:SystemCapability.Location.Location.Core + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +**参数**: + +无 + +**返回值**: + + | 参数名 | 说明 | + | -------- | -------- | + | Promise<void> | 用来接收执行结果,如果执行成功就返回nullptr,否则就返回错误信息。 | + +**错误码**: + +以下错误码的详细介绍请参见[位置服务子系统错误码](../errorcodes/errorcode-geoLocationManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**示例** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + geoLocationManager.enableReverseGeocodingMock() + .then((result) => { + console.log('promise, enableReverseGeocodingMock succeed'); + }) + .catch((error) => { + if (error) { + console.log('promise, enableReverseGeocodingMock: error=' + JSON.stringify(error)); + } + }); + ``` + + +## geoLocationManager.disableReverseGeocodingMock + +disableReverseGeocodingMock(callback: AsyncCallback<void>): void; + +去使能逆地理编码模拟功能。 + +**系统能力**:SystemCapability.Location.Location.Core + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +**参数**: + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<void> | 是 | 用来接收执行结果,如果执行成功就返回nullptr,否则就返回错误信息。 | + +**错误码**: + +以下错误码的详细介绍请参见[位置服务子系统错误码](../errorcodes/errorcode-geoLocationManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**示例** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + geoLocationManager.disableReverseGeocodingMock((err, result) => { + if (err) { + console.log('disableReverseGeocodingMock: err=' + JSON.stringify(err)); + } + }); + ``` + + +## geoLocationManager.disableReverseGeocodingMock + +disableReverseGeocodingMock(): Promise<void>; + +去使能逆地理编码模拟功能。 + +**系统能力**:SystemCapability.Location.Location.Core + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +**参数**: + +无 + +**返回值**: + + | 参数名 | 说明 | + | -------- | -------- | + | Promise<void> | 用来接收执行结果,如果执行成功就返回nullptr,否则就返回错误信息。 | + +**错误码**: + +以下错误码的详细介绍请参见[位置服务子系统错误码](../errorcodes/errorcode-geoLocationManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**示例** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + geoLocationManager.disableReverseGeocodingMock() + .then((result) => { + console.log('promise, disableReverseGeocodingMock succeed'); + }) + .catch((error) => { + if (error) { + console.log('promise, disableReverseGeocodingMock: error=' + JSON.stringify(error)); + } + }); + ``` + + +## geoLocationManager.setReverseGeocodingMockInfo + +setReverseGeocodingMockInfo(mockInfos: Array<ReverseGeocodingMockInfo>, callback: AsyncCallback<void>): void; + +设置逆地理编码模拟功能的配置信息,包含了位置和地名的对应关系,后续进行逆地理编码查询时如果位置信息位于配置信息中,就返回对应的地名。 + +**系统能力**:SystemCapability.Location.Location.Core + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +**参数**: + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | mockInfos | Array<[ReverseGeocodingMockInfo](#reversegeocodingmockinfo)> | 是 | 指示逆地理编码模拟功能的配置参数数组。逆地理编码模拟功能的配置参数包含了一个位置和一个地名。 | + | callback | AsyncCallback<void> | 是 | 用来接收执行结果,如果执行成功就返回nullptr,否则就返回错误信息。 | + +**错误码**: + +以下错误码的详细介绍请参见[位置服务子系统错误码](../errorcodes/errorcode-geoLocationManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**示例** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var mockInfos = [ + {"location": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "maxItems": 1, "isFromMock": true}}, + {"location": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "maxItems": 1, "isFromMock": true}}, + {"location": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "maxItems": 1, "isFromMock": true}}, + {"location": {"locale": "zh", "latitude": 33.12, "longitude": 123.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 33.12, "longitude": 123.11, "maxItems": 1, "isFromMock": true}}, + {"location": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "maxItems": 1, "isFromMock": true}}, + ]; + geoLocationManager.setReverseGeocodingMockInfo(mockInfos, (err, data) => { + if (err) { + console.log('promise, setReverseGeocodingMockInfo, err:' + JSON.stringify(err)); + } + }); + ``` + + +## geoLocationManager.setReverseGeocodingMockInfo + +setReverseGeocodingMockInfo(mockInfos: Array<ReverseGeocodingMockInfo>): Promise<void>; + +设置逆地理编码模拟功能的配置信息,包含了位置和地名的对应关系,后续进行逆地理编码查询时如果位置信息位于配置信息中,就返回对应的地名。 + +**系统能力**:SystemCapability.Location.Location.Core + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +**参数**: + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | mockInfos | Array<[ReverseGeocodingMockInfo](#reversegeocodingmockinfo)> | 是 | 指示逆地理编码模拟功能的配置信息数组。逆地理编码模拟功能的配置信息包含了一个位置和一个地名。 | + +**返回值**: + + | 参数名 | 说明 | + | -------- | -------- | + | Promise<void> | 用来接收执行结果,如果执行成功就返回nullptr,否则就返回错误信息。 | + +**错误码**: + +以下错误码的详细介绍请参见[位置服务子系统错误码](../errorcodes/errorcode-geoLocationManager.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**示例** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var mockInfos = [ + {"location": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "maxItems": 1, "isFromMock": true}}, + {"location": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "maxItems": 1, "isFromMock": true}}, + {"location": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "maxItems": 1, "isFromMock": true}}, + {"location": {"locale": "zh", "latitude": 33.12, "longitude": 123.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 33.12, "longitude": 123.11, "maxItems": 1, "isFromMock": true}}, + {"location": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "maxItems": 1, "isFromMock": true}}, + ]; + geoLocationManager.setReverseGeocodingMockInfo(mockInfos) + .then((result) => { + console.log('promise, setReverseGeocodingMockInfo succeed'); + }) + .catch((error) => { + if (error) { + console.log('promise, setReverseGeocodingMockInfo: error=' + JSON.stringify(error)); + } + }); + ``` + + +## LocationRequestPriority + +位置请求中位置信息优先级设置。 + +**系统能力**:SystemCapability.Location.Location.Core + +| 名称 | 默认值 | 说明 | +| -------- | -------- | -------- | +| UNSET | 0x200 | 表示未设置优先级。 | +| ACCURACY | 0x201 | 表示精度优先。 | +| LOW_POWER | 0x202 | 表示低功耗优先。 | +| FIRST_FIX | 0x203 | 表示快速获取位置优先,如果应用希望快速拿到1个位置,可以将优先级设置为该字段。 | + + +## LocationRequestScenario + + 位置请求中定位场景设置。 + +**系统能力**:SystemCapability.Location.Location.Core + +| 名称 | 默认值 | 说明 | +| -------- | -------- | -------- | +| UNSET | 0x300 | 表示未设置场景信息。 | +| NAVIGATION | 0x301 | 表示导航场景。 | +| TRAJECTORY_TRACKING | 0x302 | 表示运动轨迹记录场景。 | +| CAR_HAILING | 0x303 | 表示打车场景。 | +| DAILY_LIFE_SERVICE | 0x304 | 表示日常服务使用场景。 | +| NO_POWER | 0x305 | 表示无功耗功场景,这种场景下不会主动触发定位,会在其他应用定位时,才给当前应用返回位置。 | + + +## ReverseGeoCodeRequest + +逆地理编码请求接口。 + +**系统能力**:SystemCapability.Location.Location.Geocoder + +| 名称 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| locale | string | 否 | 指定位置描述信息的语言,“zh”代表中文,“en”代表英文。 | +| latitude | number | 是 | 表示纬度信息,正值表示北纬,负值表示南纬。 | +| longitude | number | 是 | 表示经度信息,正值表示东经,负值表示西经。 | +| maxItems | number | 否 | 指定返回位置信息的最大个数。 | + + +## GeoCodeRequest + +地理编码请求接口。 + +**系统能力**:SystemCapability.Location.Location.Geocoder + +| 名称 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| locale | string | 否 | 表示位置描述信息的语言,“zh”代表中文,“en”代表英文。 | +| description | number | 是 | 表示位置信息描述,如“上海市浦东新区xx路xx号”。 | +| maxItems | number | 否 | 表示返回位置信息的最大个数。 | +| minLatitude | number | 否 | 表示最小纬度信息,与下面三个参数一起,表示一个经纬度范围。 | +| minLongitude | number | 否 | 表示最小经度信息。 | +| maxLatitude | number | 否 | 表示最大纬度信息。 | +| maxLongitude | number | 否 | 表示最大经度信息。 | + + +## GeoAddress + +地理编码类型。 + +**系统能力**:SystemCapability.Location.Location.Geocoder + +| 名称 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| latitude | number | 否 | 表示纬度信息,正值表示北纬,负值表示南纬。 | +| longitude | number | 否 | 表示经度信息,正值表示东经,负值表是西经。 | +| locale | string | 否 | 表示位置描述信息的语言,“zh”代表中文,“en”代表英文。 | +| placeName | string | 否 | 表示地区信息。 | +| countryCode | string | 否 | 表示国家码信息。 | +| countryName | string | 否 | 表示国家信息。 | +| administrativeArea | string | 否 | 表示省份区域信息。 | +| subAdministrativeArea | string | 否 | 表示表示子区域信息。 | +| locality | string | 否 | 表示城市信息。 | +| subLocality | string | 否 | 表示子城市信息。 | +| roadName | string | 否 | 表示路名信息。 | +| subRoadName | string | 否 | 表示子路名信息。 | +| premises | string | 否 | 表示门牌号信息。 | +| postalCode | string | 否 | 表示邮政编码信息。 | +| phoneNumber | string | 否 | 表示联系方式信息。 | +| addressUrl | string | 否 | 表示位置信息附件的网址信息。 | +| descriptions | Array<string> | 否 | 表示附加的描述信息。 | +| descriptionsSize | number | 否 | 表示附加的描述信息数量。 | +| isFromMock | Boolean | 否 | 表示地名信息是否来自于逆地理编码模拟功能。 | + + +## LocationRequest + +位置信息请求类型。 + +**系统能力**:SystemCapability.Location.Location.Core + +| 名称 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| priority | [LocationRequestPriority](#locationrequestpriority) | 否 | 表示优先级信息。 | +| scenario | [LocationRequestScenario](#locationrequestscenario) | 是 | 表示场景信息。 | +| timeInterval | number | 否 | 表示上报位置信息的时间间隔。 | +| distanceInterval | number | 否 | 表示上报位置信息的距离间隔。 | +| maxAccuracy | number | 否 | 表示精度信息。仅在精确位置功能场景下有效,模糊位置功能生效场景下该字段无意义。 | + + +## CurrentLocationRequest + +当前位置信息请求类型。 + +**系统能力**:SystemCapability.Location.Location.Core + +| 名称 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| priority | [LocationRequestPriority](#locationrequestpriority) | 否 | 表示优先级信息。 | +| scenario | [LocationRequestScenario](#locationrequestscenario) | 否 | 表示场景信息。 | +| maxAccuracy | number | 否 | 表示精度信息,单位是米。仅在精确位置功能场景下有效,模糊位置功能生效场景下该字段无意义。 | +| timeoutMs | number | 否 | 表示超时时间,单位是毫秒,最小为1000毫秒。 | + + +## SatelliteStatusInfo + +卫星状态信息。 + +**系统能力**:SystemCapability.Location.Location.Gnss + +| 名称 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| satellitesNumber | number | 是 | 表示卫星个数。 | +| satelliteIds | Array<number> | 是 | 表示每个卫星的ID,数组类型。 | +| carrierToNoiseDensitys | Array<number> | 是 | 表示载波噪声功率谱密度比,即cn0。 | +| altitudes | Array<number> | 是 | 表示高程信息。 | +| azimuths | Array<number> | 是 | 表示方位角。 | +| carrierFrequencies | Array<number> | 是 | 表示载波频率。 | + + +## CachedGnssLocationsRequest + +请求订阅GNSS缓存位置上报功能接口的配置参数。 + +**系统能力**:SystemCapability.Location.Location.Gnss + +| 名称 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| reportingPeriodSec | number | 是 | 表示GNSS缓存位置上报的周期,单位是毫秒。 | +| wakeUpCacheQueueFull | boolean | 是 | true表示GNSS芯片底层缓存队列满之后会主动唤醒AP芯片,并把缓存位置上报给应用。
false表示GNSS芯片底层缓存队列满之后不会主动唤醒AP芯片,会把缓存位置直接丢弃。 | + + +## Geofence + +GNSS围栏的配置参数。目前只支持圆形围栏。 + +**系统能力**:SystemCapability.Location.Location.Geofence + +| 名称 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| latitude | number | 是 | 表示纬度。 | +| longitude | number | 是 | 表示经度。 | +| radius | number | 是 | 表示圆形围栏的半径。 | +| expiration | number | 是 | 围栏存活的时间,单位是毫秒。 | + + +## GeofenceRequest + +请求添加GNSS围栏消息中携带的参数,包括定位优先级、定位场景和围栏信息。 + +**系统能力**:SystemCapability.Location.Location.Geofence + +| 名称 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| priority | [LocationRequestPriority](#locationrequestpriority) | 是 | 表示位置信息优先级。 | +| scenario | [LocationRequestScenario](#locationrequestscenario) | 是 | 表示定位场景。 | +| geofence | [Geofence](#geofence) | 是 | 表示围栏信息。 | + + +## LocationPrivacyType + +定位服务隐私协议类型。 + +**系统能力**:SystemCapability.Location.Location.Core + +| 名称 | 默认值 | 说明 | +| -------- | -------- | -------- | +| OTHERS | 0 | 其他场景。 | +| STARTUP | 1 | 开机向导场景下的隐私协议。 | +| CORE_LOCATION | 2 | 开启网络定位时弹出的隐私协议。 | + + +## LocationCommand + +扩展命令结构体。 + +**系统能力**:SystemCapability.Location.Location.Core + +| 名称 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| scenario | [LocationRequestScenario](#locationrequestscenario) | 是 | 表示定位场景。 | +| command | string | 是 | 扩展命令字符串。 | + + +## Location + +位置信息类型。 + +**系统能力**:SystemCapability.Location.Location.Core + +| 名称 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| latitude | number | 是 | 表示纬度信息,正值表示北纬,负值表示南纬。 | +| longitude | number | 是 | 表示经度信息,正值表示东经,负值表是西经。 | +| altitude | number | 是 | 表示高度信息,单位米。 | +| accuracy | number | 是 | 表示精度信息,单位米。 | +| speed | number | 是 | 表示速度信息,单位米每秒。 | +| timeStamp | number | 是 | 表示位置时间戳,UTC格式。 | +| direction | number | 是 | 表示航向信息。 | +| timeSinceBoot | number | 是 | 表示位置时间戳,开机时间格式。 | +| additions | Array<string> | 否 | 附加信息。 | +| additionSize | number | 否 | 附加信息数量。 | +| isFromMock | Boolean | 否 | 表示位置信息是否来自于位置模拟功能。 | + + +## ReverseGeocodingMockInfo + +逆地理编码模拟功能的配置信息,包含一个位置信息和一个地名信息。 + +**系统能力**:SystemCapability.Location.Location.Core + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +| 名称 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| location | [ReverseGeoCodeRequest](#reversegeocoderequest) | 是 | 表示经纬度信息。 | +| geoAddress | [GeoAddress](#geoaddress) | 是 | 表示地名信息。 | + + +## LocationMockConfig + +位置模拟功能的配置参数,包含了模拟位置上报的时间间隔和模拟位置数组。 + +**系统能力**:SystemCapability.Location.Location.Core + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +| 名称 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| timeInterval | number | 是 | 表示模拟位置上报的时间间隔,单位是秒。 | +| locations | Array<Location> | 是 | 表示模拟位置数组。 | + + +## CountryCode + +国家码信息结构体,包含国家码字符串和国家码的来源信息。 + +**系统能力**:SystemCapability.Location.Location.Core + +| 名称 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| country | string | 是 | 表示国家码字符串。 | +| type | [CountryCodeType](#countrycodetype)| 是 | 表示国家码信息来源。 | + + +## CountryCodeType + +国家码来源类型。 + +**系统能力**:SystemCapability.Location.Location.Core + +| 名称 | 默认值 | 说明 | +| -------- | -------- | -------- | +| COUNTRY_CODE_FROM_LOCALE | 1 | 从全球化模块的语言配置信息中获取到的国家码。 | +| COUNTRY_CODE_FROM_SIM | 2 | 从SIM卡中获取到的国家码。 | +| COUNTRY_CODE_FROM_LOCATION | 3 | 基于用户的位置信息,通过逆地理编码查询到的国家码。 | +| COUNTRY_CODE_FROM_NETWORK | 4 | 从蜂窝网络注册信息中获取到的国家码。 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-geolocation.md b/zh-cn/application-dev/reference/apis/js-apis-geolocation.md index 3cd5bb1b94919b8e48c4b2c8b215254963bd05aa..ab2399b1884ecb3a015e2c25794c485b284d7260 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-geolocation.md +++ b/zh-cn/application-dev/reference/apis/js-apis-geolocation.md @@ -8,15 +8,15 @@ ## 导入模块 -```js +```ts import geolocation from '@ohos.geolocation'; ``` ## geolocation.on('locationChange') -on(type: 'locationChange', request: LocationRequest, callback: Callback<Location>) : void +on(type: 'locationChange', request: LocationRequest, callback: Callback<Location>): void -开启位置变化订阅,并发起定位请求。 +开启位置变化订阅,并发起定位请求。定位结果按照[LocationRequest](#locationrequest)的属性进行上报, **需要权限**:ohos.permission.LOCATION @@ -27,14 +27,15 @@ on(type: 'locationChange', request: LocationRequest, callback: Callback<Locat | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | type | string | 是 | 设置事件类型。type为“locationChange”,表示位置变化。 | - | request | LocationRequest | 是 | 设置位置请求参数。 | + | request | [LocationRequest](#locationrequest) | 是 | 设置位置请求参数。 | | callback | Callback<[Location](#location)> | 是 | 接收位置变化状态变化监听。 | **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; var requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; var locationChange = (location) => { console.log('locationChanger: data: ' + JSON.stringify(location)); @@ -45,7 +46,7 @@ on(type: 'locationChange', request: LocationRequest, callback: Callback<Locat ## geolocation.off('locationChange') -off(type: 'locationChange', callback?: Callback<Location>) : void +off(type: 'locationChange', callback?: Callback<Location>): void 关闭位置变化订阅,并删除对应的定位请求。 @@ -63,7 +64,8 @@ off(type: 'locationChange', callback?: Callback<Location>) : void **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; var requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; var locationChange = (location) => { console.log('locationChanger: data: ' + JSON.stringify(location)); @@ -75,7 +77,7 @@ off(type: 'locationChange', callback?: Callback<Location>) : void ## geolocation.on('locationServiceState') -on(type: 'locationServiceState', callback: Callback<boolean>) : void +on(type: 'locationServiceState', callback: Callback<boolean>): void 订阅位置服务状态变化。 @@ -93,7 +95,8 @@ on(type: 'locationServiceState', callback: Callback<boolean>) : void **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; var locationServiceState = (state) => { console.log('locationServiceState: ' + JSON.stringify(state)); } @@ -103,7 +106,7 @@ on(type: 'locationServiceState', callback: Callback<boolean>) : void ## geolocation.off('locationServiceState') -off(type: 'locationServiceState', callback?: Callback<boolean>) : void; +off(type: 'locationServiceState', callback?: Callback<boolean>): void; 取消订阅位置服务状态变化。 @@ -121,7 +124,8 @@ off(type: 'locationServiceState', callback?: Callback<boolean>) : void; **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; var locationServiceState = (state) => { console.log('locationServiceState: state: ' + JSON.stringify(state)); } @@ -132,7 +136,7 @@ off(type: 'locationServiceState', callback?: Callback<boolean>) : void; ## geolocation.on('cachedGnssLocationsReporting')8+ -on(type: 'cachedGnssLocationsReporting', request: CachedGnssLocationsRequest, callback: Callback<Array<Location>>) : void; +on(type: 'cachedGnssLocationsReporting', request: CachedGnssLocationsRequest, callback: Callback<Array<Location>>): void; 订阅缓存GNSS定位结果上报事件。 @@ -145,13 +149,14 @@ on(type: 'cachedGnssLocationsReporting', request: CachedGnssLocationsRequest, ca | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | type | string | 是 | 设置事件类型。type为“cachedGnssLocationsReporting”,表示GNSS缓存定位结果上报。 | - | request | CachedGnssLocationsRequest | 是 | GNSS缓存功能配置参数 | + | request | [CachedGnssLocationsRequest](#cachedgnsslocationsrequest) | 是 | GNSS缓存功能配置参数 | | callback | Callback<boolean> | 是 | 接收GNSS缓存位置上报。 | **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; var cachedLocationsCb = (locations) => { console.log('cachedGnssLocationsReporting: locations: ' + JSON.stringify(locations)); } @@ -162,7 +167,7 @@ on(type: 'cachedGnssLocationsReporting', request: CachedGnssLocationsRequest, ca ## geolocation.off('cachedGnssLocationsReporting')8+ -off(type: 'cachedGnssLocationsReporting', callback?: Callback<Array<Location>>) : void; +off(type: 'cachedGnssLocationsReporting', callback?: Callback<Array<Location>>): void; 取消订阅缓存GNSS定位结果上报事件。 @@ -180,7 +185,8 @@ off(type: 'cachedGnssLocationsReporting', callback?: Callback<Array<Locati **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; var cachedLocationsCb = (locations) => { console.log('cachedGnssLocationsReporting: locations: ' + JSON.stringify(locations)); } @@ -192,7 +198,7 @@ off(type: 'cachedGnssLocationsReporting', callback?: Callback<Array<Locati ## geolocation.on('gnssStatusChange')8+ -on(type: 'gnssStatusChange', callback: Callback<SatelliteStatusInfo>) : void; +on(type: 'gnssStatusChange', callback: Callback<SatelliteStatusInfo>): void; 订阅GNSS卫星状态信息上报事件。 @@ -205,12 +211,13 @@ on(type: 'gnssStatusChange', callback: Callback<SatelliteStatusInfo>) : vo | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | type | string | 是 | 设置事件类型。type为“gnssStatusChange”,表示订阅GNSS卫星状态信息上报。 | - | callback | Callback<SatelliteStatusInfo> | 是 | 接收GNSS卫星状态信息上报。 | + | callback | Callback<[SatelliteStatusInfo](#satellitestatusinfo)> | 是 | 接收GNSS卫星状态信息上报。 | **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; var gnssStatusCb = (satelliteStatusInfo) => { console.log('gnssStatusChange: ' + JSON.stringify(satelliteStatusInfo)); } @@ -220,7 +227,7 @@ on(type: 'gnssStatusChange', callback: Callback<SatelliteStatusInfo>) : vo ## geolocation.off('gnssStatusChange')8+ -off(type: 'gnssStatusChange', callback?: Callback<SatelliteStatusInfo>) : void; +off(type: 'gnssStatusChange', callback?: Callback<SatelliteStatusInfo>): void; 取消订阅GNSS卫星状态信息上报事件。 @@ -233,11 +240,12 @@ off(type: 'gnssStatusChange', callback?: Callback<SatelliteStatusInfo>) : | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | type | string | 是 | 设置事件类型。type为“gnssStatusChange”,表示订阅GNSS卫星状态信息上报。 | - | callback | Callback<SatelliteStatusInfo> | 否 | 接收GNSS卫星状态信息上报。 | + | callback | Callback<[SatelliteStatusInfo](#satellitestatusinfo)> | 否 | 接收GNSS卫星状态信息上报。 | **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; var gnssStatusCb = (satelliteStatusInfo) => { console.log('gnssStatusChange: ' + JSON.stringify(satelliteStatusInfo)); } @@ -248,7 +256,7 @@ off(type: 'gnssStatusChange', callback?: Callback<SatelliteStatusInfo>) : ## geolocation.on('nmeaMessageChange')8+ -on(type: 'nmeaMessageChange', callback: Callback<string>) : void; +on(type: 'nmeaMessageChange', callback: Callback<string>): void; 订阅GNSS NMEA信息上报事件。 @@ -266,7 +274,8 @@ on(type: 'nmeaMessageChange', callback: Callback<string>) : void; **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; var nmeaCb = (str) => { console.log('nmeaMessageChange: ' + JSON.stringify(str)); } @@ -276,7 +285,7 @@ on(type: 'nmeaMessageChange', callback: Callback<string>) : void; ## geolocation.off('nmeaMessageChange')8+ -off(type: 'nmeaMessageChange', callback?: Callback<string>) : void; +off(type: 'nmeaMessageChange', callback?: Callback<string>): void; 取消订阅GNSS NMEA信息上报事件。 @@ -294,7 +303,8 @@ off(type: 'nmeaMessageChange', callback?: Callback<string>) : void; **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; var nmeaCb = (str) => { console.log('nmeaMessageChange: ' + JSON.stringify(str)); } @@ -305,7 +315,7 @@ off(type: 'nmeaMessageChange', callback?: Callback<string>) : void; ## geolocation.on('fenceStatusChange')8+ -on(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void; +on(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent): void; 添加一个围栏,并订阅地理围栏事件。 @@ -318,13 +328,13 @@ on(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void; | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | type | string | 是 | 设置事件类型。type为“fenceStatusChange”,表示订阅围栏事件上报。 | - | request | GeofenceRequest | 是 | 围栏的配置参数。 | + | request | [GeofenceRequest](#geofencerequest) | 是 | 围栏的配置参数。 | | want | WantAgent | 是 | 用于接收地理围栏事件上报(进出围栏)。 | **示例** - ```js + ```ts import geolocation from '@ohos.geolocation'; import wantAgent from '@ohos.wantAgent'; @@ -332,13 +342,13 @@ on(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void; wants: [ { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility" + abilityName: "com.example.myapplication.MainAbility", action: "action1", } ], operationType: wantAgent.OperationType.START_ABILITY, requestCode: 0, - wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG], }; wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { @@ -350,7 +360,7 @@ on(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void; ## geolocation.off('fenceStatusChange')8+ -off(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void; +off(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent): void; 删除一个围栏,并取消订阅该围栏事件。 @@ -363,12 +373,12 @@ off(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | type | string | 是 | 设置事件类型。type为“fenceStatusChange”,表示订阅围栏事件上报。 | - | request | GeofenceRequest | 是 | 围栏的配置参数。 | + | request | [GeofenceRequest](#geofencerequest) | 是 | 围栏的配置参数。 | | want | WantAgent | 是 | 用于接收地理围栏事件上报(进出围栏)。 | **示例** - ```js + ```ts import geolocation from '@ohos.geolocation'; import wantAgent from '@ohos.wantAgent'; @@ -376,7 +386,7 @@ off(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void wants: [ { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility" + abilityName: "com.example.myapplication.MainAbility", action: "action1", } ], @@ -393,62 +403,9 @@ off(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void ``` -## geolocation.on('countryCodeChange')9+ - -on(type: 'countryCodeChange', callback: Callback<CountryCode>) : void; - -订阅国家码信息上报事件。 - -**系统能力**:SystemCapability.Location.Location.Core - -**参数**: - - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | type | string | 是 | 设置事件类型。type为“countryCodeChange”,表示订阅国家码信息上报。 | - | callback | Callback<CountryCode> | 是 | 接收国家码信息上报。 | - - -**示例** - - ```js - var callback = (code) => { - console.log('countryCodeChange: ' + JSON.stringify(code)); - } - geolocation.on('countryCodeChange', callback); - ``` - - -## geolocation.off('countryCodeChange')9+ - -off(type: 'countryCodeChange', callback?: Callback<CountryCode>) : void; - -取消订阅国家码上报事件。 - -**系统能力**:SystemCapability.Location.Location.Core - -**参数**: - - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | type | string | 是 | 设置事件类型。type为“countryCodeChange”,表示取消订阅国家码信息上报。 | - | callback | Callback<CountryCode> | 是 | 接收国家码信息上报。 | - - -**示例** - - ```js - var callback = (code) => { - console.log('countryCodeChange: ' + JSON.stringify(code)); - } - geolocation.on('countryCodeChange', callback); - geolocation.off('countryCodeChange', callback); - ``` - - ## geolocation.getCurrentLocation -getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback<Location>) : void +getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback<Location>): void 获取当前位置,使用callback回调异步返回结果。 @@ -466,7 +423,8 @@ getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback<L **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; var requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0}; var locationChange = (err, location) => { if (err) { @@ -483,7 +441,7 @@ getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback<L ## geolocation.getCurrentLocation -getCurrentLocation(request?: CurrentLocationRequest) : Promise<Location> +getCurrentLocation(request?: CurrentLocationRequest): Promise<Location> 获取当前位置,使用Promise方式异步返回结果。 @@ -507,7 +465,8 @@ getCurrentLocation(request?: CurrentLocationRequest) : Promise<Location> **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; var requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0}; geolocation.getCurrentLocation(requestInfo).then((result) => { console.log('current location: ' + JSON.stringify(result)); @@ -517,7 +476,7 @@ getCurrentLocation(request?: CurrentLocationRequest) : Promise<Location> ## geolocation.getLastLocation -getLastLocation(callback: AsyncCallback<Location>) : void +getLastLocation(callback: AsyncCallback<Location>): void 获取上一次位置,使用callback回调异步返回结果。 @@ -534,7 +493,8 @@ getLastLocation(callback: AsyncCallback<Location>) : void **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; geolocation.getLastLocation((err, data) => { if (err) { console.log('getLastLocation: err=' + JSON.stringify(err)); @@ -548,7 +508,7 @@ getLastLocation(callback: AsyncCallback<Location>) : void ## geolocation.getLastLocation -getLastLocation() : Promise<Location> +getLastLocation(): Promise<Location> 获取上一次位置,使用Promise方式异步返回结果。 @@ -565,7 +525,8 @@ getLastLocation() : Promise<Location> **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; geolocation.getLastLocation().then((result) => { console.log('getLastLocation: result: ' + JSON.stringify(result)); }); @@ -574,7 +535,7 @@ getLastLocation() : Promise<Location> ## geolocation.isLocationEnabled -isLocationEnabled(callback: AsyncCallback<boolean>) : void +isLocationEnabled(callback: AsyncCallback<boolean>): void 判断位置服务是否已经打开,使用callback回调异步返回结果。 @@ -591,7 +552,8 @@ isLocationEnabled(callback: AsyncCallback<boolean>) : void **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; geolocation.isLocationEnabled((err, data) => { if (err) { console.log('isLocationEnabled: err=' + JSON.stringify(err)); @@ -605,7 +567,7 @@ isLocationEnabled(callback: AsyncCallback<boolean>) : void ## geolocation.isLocationEnabled -isLocationEnabled() : Promise<boolean> +isLocationEnabled(): Promise<boolean> 判断位置服务是否已经开启,使用Promise方式异步返回结果。 @@ -621,7 +583,8 @@ isLocationEnabled() : Promise<boolean> **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; geolocation.isLocationEnabled().then((result) => { console.log('promise, isLocationEnabled: ' + JSON.stringify(result)); }); @@ -630,7 +593,7 @@ isLocationEnabled() : Promise<boolean> ## geolocation.requestEnableLocation -requestEnableLocation(callback: AsyncCallback<boolean>) : void +requestEnableLocation(callback: AsyncCallback<boolean>): void 请求打开位置服务,使用callback回调异步返回结果。 @@ -647,7 +610,8 @@ requestEnableLocation(callback: AsyncCallback<boolean>) : void **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; geolocation.requestEnableLocation((err, data) => { if (err) { console.log('requestEnableLocation: err=' + JSON.stringify(err)); @@ -661,7 +625,7 @@ requestEnableLocation(callback: AsyncCallback<boolean>) : void ## geolocation.requestEnableLocation -requestEnableLocation() : Promise<boolean> +requestEnableLocation(): Promise<boolean> 请求打开位置服务,使用Promise方式异步返回结果。 @@ -677,7 +641,8 @@ requestEnableLocation() : Promise<boolean> **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; geolocation.requestEnableLocation().then((result) => { console.log('promise, requestEnableLocation: ' + JSON.stringify(result)); }); @@ -686,7 +651,7 @@ requestEnableLocation() : Promise<boolean> ## geolocation.enableLocation -enableLocation(callback: AsyncCallback<boolean>) : void; +enableLocation(callback: AsyncCallback<boolean>): void; 打开位置服务,使用callback回调异步返回结果。 @@ -704,7 +669,8 @@ enableLocation(callback: AsyncCallback<boolean>) : void; **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; geolocation.enableLocation((err, data) => { if (err) { console.log('enableLocation: err=' + JSON.stringify(err)); @@ -718,7 +684,7 @@ enableLocation(callback: AsyncCallback<boolean>) : void; ## geolocation.enableLocation -enableLocation() : Promise<boolean> +enableLocation(): Promise<boolean> 打开位置服务,使用Promise方式异步返回结果。 @@ -736,7 +702,8 @@ enableLocation() : Promise<boolean> **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; geolocation.enableLocation().then((result) => { console.log('promise, enableLocation: ' + JSON.stringify(result)); }); @@ -744,7 +711,7 @@ enableLocation() : Promise<boolean> ## geolocation.disableLocation -disableLocation(callback: AsyncCallback<boolean>) : void; +disableLocation(callback: AsyncCallback<boolean>): void; 关闭位置服务,使用callback回调异步返回结果。 @@ -762,7 +729,8 @@ disableLocation(callback: AsyncCallback<boolean>) : void; **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; geolocation.disableLocation((err, data) => { if (err) { console.log('disableLocation: err=' + JSON.stringify(err)); @@ -776,7 +744,7 @@ disableLocation(callback: AsyncCallback<boolean>) : void; ## geolocation.disableLocation -disableLocation() : Promise<boolean> +disableLocation(): Promise<boolean> 关闭位置服务,使用Promise方式异步返回结果。 @@ -794,7 +762,8 @@ disableLocation() : Promise<boolean> **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; geolocation.disableLocation().then((result) => { console.log('promise, disableLocation: ' + JSON.stringify(result)); }); @@ -802,7 +771,7 @@ disableLocation() : Promise<boolean> ## geolocation.isGeoServiceAvailable -isGeoServiceAvailable(callback: AsyncCallback<boolean>) : void +isGeoServiceAvailable(callback: AsyncCallback<boolean>): void 判断(逆)地理编码服务状态,使用callback回调异步返回结果。 @@ -818,7 +787,8 @@ isGeoServiceAvailable(callback: AsyncCallback<boolean>) : void **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; geolocation.isGeoServiceAvailable((err, data) => { if (err) { console.log('isGeoServiceAvailable: err=' + JSON.stringify(err)); @@ -832,7 +802,7 @@ isGeoServiceAvailable(callback: AsyncCallback<boolean>) : void ## geolocation.isGeoServiceAvailable -isGeoServiceAvailable() : Promise<boolean> +isGeoServiceAvailable(): Promise<boolean> 判断(逆)地理编码服务状态,使用Promise方式异步返回结果。 @@ -848,7 +818,8 @@ isGeoServiceAvailable() : Promise<boolean> **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; geolocation.isGeoServiceAvailable().then((result) => { console.log('promise, isGeoServiceAvailable: ' + JSON.stringify(result)); }); @@ -857,7 +828,7 @@ isGeoServiceAvailable() : Promise<boolean> ## geolocation.getAddressesFromLocation -getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>) : void +getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>): void 调用逆地理编码服务,将坐标转换为地理描述,使用callback回调异步返回结果。 @@ -874,7 +845,8 @@ getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; geolocation.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => { if (err) { @@ -889,7 +861,7 @@ getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback ## geolocation.getAddressesFromLocation -getAddressesFromLocation(request: ReverseGeoCodeRequest) : Promise<Array<GeoAddress>>; +getAddressesFromLocation(request: ReverseGeoCodeRequest): Promise<Array<GeoAddress>>; 调用逆地理编码服务,将坐标转换为地理描述,使用Promise方式异步返回结果。 @@ -911,7 +883,8 @@ getAddressesFromLocation(request: ReverseGeoCodeRequest) : Promise<Array<G **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; geolocation.getAddressesFromLocation(reverseGeocodeRequest).then((data) => { console.log('getAddressesFromLocation: ' + JSON.stringify(data)); @@ -921,7 +894,7 @@ getAddressesFromLocation(request: ReverseGeoCodeRequest) : Promise<Array<G ## geolocation.getAddressesFromLocationName -getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>) : void +getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>): void 调用地理编码服务,将地理描述转换为具体坐标,使用callback回调异步返回结果。 @@ -938,7 +911,8 @@ getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback< **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; var geocodeRequest = {"description": "上海市浦东新区xx路xx号", "maxItems": 1}; geolocation.getAddressesFromLocationName(geocodeRequest, (err, data) => { if (err) { @@ -953,7 +927,7 @@ getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback< ## geolocation.getAddressesFromLocationName -getAddressesFromLocationName(request: GeoCodeRequest) : Promise<Array<GeoAddress>> +getAddressesFromLocationName(request: GeoCodeRequest): Promise<Array<GeoAddress>> 调用地理编码服务,将地理描述转换为具体坐标,使用Promise方式异步返回结果。 @@ -975,7 +949,8 @@ getAddressesFromLocationName(request: GeoCodeRequest) : Promise<Array<GeoA **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; var geocodeRequest = {"description": "上海市浦东新区xx路xx号", "maxItems": 1}; geolocation.getAddressesFromLocationName(geocodeRequest).then((result) => { console.log('getAddressesFromLocationName: ' + JSON.stringify(result)); @@ -985,7 +960,7 @@ getAddressesFromLocationName(request: GeoCodeRequest) : Promise<Array<GeoA ## geolocation.getCachedGnssLocationsSize8+ -getCachedGnssLocationsSize(callback: AsyncCallback<number>) : void; +getCachedGnssLocationsSize(callback: AsyncCallback<number>): void; 获取GNSS芯片缓存位置的个数。 @@ -1001,7 +976,8 @@ getCachedGnssLocationsSize(callback: AsyncCallback<number>) : void; **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; geolocation.getCachedGnssLocationsSize((err, size) => { if (err) { console.log('getCachedGnssLocationsSize: err=' + JSON.stringify(err)); @@ -1015,7 +991,7 @@ getCachedGnssLocationsSize(callback: AsyncCallback<number>) : void; ## geolocation.getCachedGnssLocationsSize8+ -getCachedGnssLocationsSize() : Promise<number>; +getCachedGnssLocationsSize(): Promise<number>; 获取GNSS芯片缓存位置的个数。 @@ -1031,7 +1007,8 @@ getCachedGnssLocationsSize() : Promise<number>; **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; geolocation.getCachedGnssLocationsSize().then((result) => { console.log('promise, getCachedGnssLocationsSize: ' + JSON.stringify(result)); }); @@ -1040,7 +1017,7 @@ getCachedGnssLocationsSize() : Promise<number>; ## geolocation.flushCachedGnssLocations8+ -flushCachedGnssLocations(callback: AsyncCallback<boolean>) : void; +flushCachedGnssLocations(callback: AsyncCallback<boolean>): void; 读取并清空GNSS芯片所有缓存位置。 @@ -1056,7 +1033,8 @@ flushCachedGnssLocations(callback: AsyncCallback<boolean>) : void; **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; geolocation.flushCachedGnssLocations((err, result) => { if (err) { console.log('flushCachedGnssLocations: err=' + JSON.stringify(err)); @@ -1070,7 +1048,7 @@ flushCachedGnssLocations(callback: AsyncCallback<boolean>) : void; ## geolocation.flushCachedGnssLocations8+ -flushCachedGnssLocations() : Promise<boolean>; +flushCachedGnssLocations(): Promise<boolean>; 读取并清空GNSS芯片所有缓存位置。 @@ -1086,7 +1064,8 @@ flushCachedGnssLocations() : Promise<boolean>; **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; geolocation.flushCachedGnssLocations().then((result) => { console.log('promise, flushCachedGnssLocations: ' + JSON.stringify(result)); }); @@ -1095,7 +1074,7 @@ flushCachedGnssLocations() : Promise<boolean>; ## geolocation.sendCommand8+ -sendCommand(command: LocationCommand, callback: AsyncCallback<boolean>) : void; +sendCommand(command: LocationCommand, callback: AsyncCallback<boolean>): void; 给位置服务子系统的各个部件发送扩展命令。只有系统应用才能调用。 @@ -1107,12 +1086,13 @@ sendCommand(command: LocationCommand, callback: AsyncCallback<boolean>) : | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | command | LocationCommand | 是 | 指定目标场景,和将要发送的命令(字符串)。 | + | command | [LocationCommand](#locationcommand) | 是 | 指定目标场景,和将要发送的命令(字符串)。 | | callback | AsyncCallback<boolean> | 是 | 用来接收命令发送的结果。 | **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; var requestInfo = {'scenario': 0x301, 'command': "command_1"}; geolocation.sendCommand(requestInfo, (err, result) => { if (err) { @@ -1127,7 +1107,7 @@ sendCommand(command: LocationCommand, callback: AsyncCallback<boolean>) : ## geolocation.sendCommand8+ -sendCommand(command: LocationCommand) : Promise<boolean>; +sendCommand(command: LocationCommand): Promise<boolean>; 给位置服务子系统的各个部件发送扩展命令。只有系统应用才能调用。 @@ -1139,7 +1119,7 @@ sendCommand(command: LocationCommand) : Promise<boolean>; | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | command | LocationCommand | 是 | 指定目标场景,和将要发送的命令(字符串)。 | + | command | [LocationCommand](#locationcommand) | 是 | 指定目标场景,和将要发送的命令(字符串)。 | **返回值**: @@ -1149,7 +1129,8 @@ sendCommand(command: LocationCommand) : Promise<boolean>; **示例** - ```js + ```ts + import geolocation from '@ohos.geolocation'; var requestInfo = {'scenario': 0x301, 'command': "command_1"}; geolocation.sendCommand(requestInfo).then((result) => { console.log('promise, sendCommand: ' + JSON.stringify(result)); @@ -1157,836 +1138,193 @@ sendCommand(command: LocationCommand) : Promise<boolean>; ``` -## geolocation.isLocationPrivacyConfirmed8+ - -isLocationPrivacyConfirmed(type : LocationPrivacyType, callback: AsyncCallback<boolean>) : void; -查询用户是否同意定位服务隐私申明,是否同意启用定位服务。只有系统应用才能调用。 +## LocationRequestPriority -**系统API**:此接口为系统接口,三方应用不支持调用。 +位置请求中位置信息优先级设置。 **需要权限**:ohos.permission.LOCATION **系统能力**:SystemCapability.Location.Location.Core -**参数**: +| 名称 | 默认值 | 说明 | +| -------- | -------- | -------- | +| UNSET | 0x200 | 表示未设置优先级。 | +| ACCURACY | 0x201 | 表示精度优先。 | +| LOW_POWER | 0x202 | 表示低功耗优先。 | +| FIRST_FIX | 0x203 | 表示快速获取位置优先,如果应用希望快速拿到1个位置,可以将优先级设置为该字段。 | - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | type | LocationPrivacyType | 是 | 指定隐私申明场景,例如开机向导中的隐私申明、开启网络定位功能时弹出的隐私申明等。 | - | callback | AsyncCallback<boolean> | 是 | 表示用户是否同意定位服务隐私申明。 | -**示例** - - ```js - geolocation.isLocationPrivacyConfirmed(1, (err, result) => { - if (err) { - console.log('isLocationPrivacyConfirmed: err=' + JSON.stringify(err)); - } - if (result) { - console.log('isLocationPrivacyConfirmed: result=' + JSON.stringify(result)); - } - }); - ``` +## LocationRequestScenario + + 位置请求中定位场景设置。 + +**需要权限**:ohos.permission.LOCATION +**系统能力**:SystemCapability.Location.Location.Core -## geolocation.isLocationPrivacyConfirmed8+ +| 名称 | 默认值 | 说明 | +| -------- | -------- | -------- | +| UNSET | 0x300 | 表示未设置场景信息。 | +| NAVIGATION | 0x301 | 表示导航场景。 | +| TRAJECTORY_TRACKING | 0x302 | 表示运动轨迹记录场景。 | +| CAR_HAILING | 0x303 | 表示打车场景。 | +| DAILY_LIFE_SERVICE | 0x304 | 表示日常服务使用场景。 | +| NO_POWER | 0x305 | 表示无功耗功场景,这种场景下不会主动触发定位,会在其他应用定位时,才给当前应用返回位置。 | -isLocationPrivacyConfirmed(type : LocationPrivacyType,) : Promise<boolean>; -查询用户是否同意定位服务隐私申明,是否同意启用定位服务。只有系统应用才能调用。 +## GeoLocationErrorCode -**系统API**:此接口为系统接口,三方应用不支持调用。 +位置服务中的错误码信息。 **需要权限**:ohos.permission.LOCATION **系统能力**:SystemCapability.Location.Location.Core -**参数**: +| 名称 | 默认值 | 说明 | +| -------- | -------- | -------- | +| INPUT_PARAMS_ERROR7+ | 101 | 表示输入参数错误。 | +| REVERSE_GEOCODE_ERROR7+ | 102 | 表示逆地理编码接口调用失败。 | +| GEOCODE_ERROR7+ | 103 | 表示地理编码接口调用失败。 | +| LOCATOR_ERROR7+ | 104 | 表示定位失败。 | +| LOCATION_SWITCH_ERROR7+ | 105 | 表示定位开关。 | +| LAST_KNOWN_LOCATION_ERROR7+ | 106 | 表示获取上次位置失败。 | +| LOCATION_REQUEST_TIMEOUT_ERROR7+ | 107 | 表示单次定位,没有在指定时间内返回位置。 | - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | type | LocationPrivacyType | 是 | 指定隐私申明场景,例如开机向导中的隐私申明、开启网络定位功能时弹出的隐私申明等。 | -**返回值**: +## ReverseGeoCodeRequest - | 参数名 | 说明 | - | -------- | -------- | - | Promise<boolean> | 表示用户是否同意定位服务隐私申明。 | +逆地理编码请求接口。 -**示例** - - ```js - geolocation.isLocationPrivacyConfirmed(1).then((result) => { - console.log('promise, isLocationPrivacyConfirmed: ' + JSON.stringify(result)); - }); - ``` +**需要权限**:ohos.permission.LOCATION +**系统能力**:SystemCapability.Location.Location.Geocoder -## geolocation.setLocationPrivacyConfirmStatus8+ +| 名称 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| locale | string | 否 | 指定位置描述信息的语言,“zh”代表中文,“en”代表英文。 | +| latitude | number | 是 | 表示纬度信息,正值表示北纬,负值表示南纬。 | +| longitude | number | 是 | 表示经度信息,正值表示东经,负值表示西经。 | +| maxItems | number | 否 | 指定返回位置信息的最大个数。 | -setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed: boolean, callback: AsyncCallback<boolean>) : void; -设置用户勾选定位服务隐私申明的状态,记录用户是否同意启用定位服务。只有系统应用才能调用。 +## GeoCodeRequest -**系统API**:此接口为系统接口,三方应用不支持调用。 +地理编码请求接口。 **需要权限**:ohos.permission.LOCATION -**系统能力**:SystemCapability.Location.Location.Core +**系统能力**:SystemCapability.Location.Location.Geocoder -**参数**: +| 名称 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| locale | string | 否 | 表示位置描述信息的语言,“zh”代表中文,“en”代表英文。 | +| description | number | 是 | 表示位置信息描述,如“上海市浦东新区xx路xx号”。 | +| maxItems | number | 否 | 表示返回位置信息的最大个数。 | +| minLatitude | number | 否 | 表示最小纬度信息,与下面三个参数一起,表示一个经纬度范围。 | +| minLongitude | number | 否 | 表示最小经度信息。 | +| maxLatitude | number | 否 | 表示最大纬度信息。 | +| maxLongitude | number | 否 | 表示最大经度信息。 | - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | type | LocationPrivacyType | 是 | 指定隐私申明场景,例如开机向导中的隐私申明、开启网络定位功能时弹出的隐私申明等。 | - | isConfirmed | boolean | 是 | 表示用户是否同意定位服务隐私申明。 | - | callback | AsyncCallback<boolean> | 是 | 表示操作是否成功。 | -**示例** - - ```js - geolocation.setLocationPrivacyConfirmStatus(1, true, (err, result) => { - if (err) { - console.log('setLocationPrivacyConfirmStatus: err=' + JSON.stringify(err)); - } - if (result) { - console.log('setLocationPrivacyConfirmStatus: result=' + JSON.stringify(result)); - } - }); - ``` +## GeoAddress + +地理编码类型。 +**需要权限**:ohos.permission.LOCATION + +**系统能力**:SystemCapability.Location.Location.Geocoder -## geolocation.setLocationPrivacyConfirmStatus8+ +| 名称 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| latitude7+ | number | 否 | 表示纬度信息,正值表示北纬,负值表示南纬。 | +| longitude7+ | number | 否 | 表示经度信息,正值表示东经,负值表是西经。 | +| locale7+ | string | 否 | 表示位置描述信息的语言,“zh”代表中文,“en”代表英文。 | +| placeName7+ | string | 否 | 表示地区信息。 | +| countryCode7+ | string | 否 | 表示国家码信息。 | +| countryName7+ | string | 否 | 表示国家信息。 | +| administrativeArea7+ | string | 否 | 表示省份区域信息。 | +| subAdministrativeArea7+ | string | 否 | 表示表示子区域信息。 | +| locality7+ | string | 否 | 表示城市信息。 | +| subLocality7+ | string | 否 | 表示子城市信息。 | +| roadName7+ | string | 否 | 表示路名信息。 | +| subRoadName7+ | string | 否 | 表示子路名信息。 | +| premises7+ | string | 否 | 表示门牌号信息。 | +| postalCode7+ | string | 否 | 表示邮政编码信息。 | +| phoneNumber7+ | string | 否 | 表示联系方式信息。 | +| addressUrl7+ | string | 否 | 表示位置信息附件的网址信息。 | +| descriptions7+ | Array<string> | 否 | 表示附加的描述信息。 | +| descriptionsSize7+ | number | 否 | 表示附加的描述信息数量。 | -setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed : boolean) : Promise<boolean>; -设置用户勾选定位服务隐私申明的状态,记录用户是否同意启用定位服务。只有系统应用才能调用。 +## LocationRequest -**系统API**:此接口为系统接口,三方应用不支持调用。 +位置信息请求类型。 **需要权限**:ohos.permission.LOCATION **系统能力**:SystemCapability.Location.Location.Core -**参数**: +| 名称 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| priority | [LocationRequestPriority](#locationrequestpriority) | 否 | 表示优先级信息。 | +| scenario | [LocationRequestScenario](#locationrequestscenario) | 是 | 表示场景信息。 | +| timeInterval | number | 否 | 表示上报位置信息的时间间隔。 | +| distanceInterval | number | 否 | 表示上报位置信息的距离间隔。 | +| maxAccuracy | number | 否 | 表示精度信息。仅在精确位置功能场景下有效,模糊位置功能生效场景下该字段无意义。 | - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | type | LocationPrivacyType | 是 | 指定隐私申明场景,例如开机向导中的隐私申明、开启网络定位功能时弹出的隐私申明等。 | - | isConfirmed | boolean | 是 | 表示用户是否同意定位服务隐私申明。 | -**返回值**: +## CurrentLocationRequest - | 参数名 | 说明 | - | -------- | -------- | - | Promise<boolean> | 表示操作是否成功。 | +当前位置信息请求类型。 -**示例** - - ```js - geolocation.setLocationPrivacyConfirmStatus(1, true).then((result) => { - console.log('promise, setLocationPrivacyConfirmStatus: ' + JSON.stringify(result)); - }); - ``` +**需要权限**:ohos.permission.LOCATION +**系统能力**:SystemCapability.Location.Location.Core -## geolocation.getCountryCode9+ +| 名称 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| priority | [LocationRequestPriority](#locationrequestpriority) | 否 | 表示优先级信息。 | +| scenario | [LocationRequestScenario](#locationrequestscenario) | 否 | 表示场景信息。 | +| maxAccuracy | number | 否 | 表示精度信息,单位是米。仅在精确位置功能场景下有效,模糊位置功能生效场景下该字段无意义。 | +| timeoutMs | number | 否 | 表示超时时间,单位是毫秒,最小为1000毫秒。 | -getCountryCode(callback: AsyncCallback<CountryCode>) : void; -查询当前的国家码。 +## SatelliteStatusInfo8+ -**系统能力**:SystemCapability.Location.Location.Core +卫星状态信息。 -**参数**: +**需要权限**:ohos.permission.LOCATION - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<CountryCode> | 是 | 用来接收国家码。 | +**系统能力**:SystemCapability.Location.Location.Gnss -**示例** - - ```js - geolocation.getCountryCode((err, result) => { - if (err) { - console.log('getCountryCode: err=' + JSON.stringify(err)); - } - if (result) { - console.log('getCountryCode: result=' + JSON.stringify(result)); - } - }); - ``` +| 名称 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| satellitesNumber | number | 是 | 表示卫星个数。 | +| satelliteIds | Array<number> | 是 | 表示每个卫星的ID,数组类型。 | +| carrierToNoiseDensitys | Array<number> | 是 | 表示载波噪声功率谱密度比,即cn0。 | +| altitudes | Array<number> | 是 | 表示高程信息。 | +| azimuths | Array<number> | 是 | 表示方位角。 | +| carrierFrequencies | Array<number> | 是 | 表示载波频率。 | -## geolocation.getCountryCode9+ +## CachedGnssLocationsRequest8+ -getCountryCode() : Promise<CountryCode>; +请求订阅GNSS缓存位置上报功能接口的配置参数。 -查询当前的国家码。 +**需要权限**:ohos.permission.LOCATION -**系统能力**:SystemCapability.Location.Location.Core +**系统能力**:SystemCapability.Location.Location.Gnss -**参数**: +| 名称 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| reportingPeriodSec | number | 是 | 表示GNSS缓存位置上报的周期,单位是毫秒。 | +| wakeUpCacheQueueFull | boolean | 是 | true表示GNSS芯片底层缓存队列满之后会主动唤醒AP芯片,并把缓存位置上报给应用。
false表示GNSS芯片底层缓存队列满之后不会主动唤醒AP芯片,会把缓存位置直接丢弃。 | -无 -**返回值**: +## Geofence8+ - | 参数名 | 说明 | - | -------- | -------- | - | Promise<CountryCode> | 返回国家码。 | - -**示例** - - ```js - geolocation.getCountryCode() - .then((result) => { - console.log('promise, getCountryCode: result=' + JSON.stringify(result)); - }) - .catch((error) => { - console.log('promise, getCountryCode: error=' + JSON.stringify(error)); - }); - ``` - - -## geolocation.enableLocationMock9+ - -enableLocationMock(scenario?: LocationRequestScenario, callback: AsyncCallback<void>) : void; - -使能某个场景的位置模拟功能,同一时间只能使能一个场景的位置模拟功能。 - -**系统能力**:SystemCapability.Location.Location.Core - -**系统API**:此接口为系统接口,三方应用不支持调用。 - -**参数**: - - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | scenario | LocationRequestScenario | 否 | 指示在什么场景下使能位置模拟功能。 | - | callback | AsyncCallback<void> | 是 | 用来接收执行结果,如果执行成功就返回nullptr,否则就返回错误信息。 | - -**示例** - - ```js - var request = {"scenario": 0x0301}; - geolocation.enableLocationMock(request, (err, result) => { - if (err) { - console.log('enableLocationMock: err=' + JSON.stringify(err)); - } - if (result) { - console.log('enableLocationMock: result=' + JSON.stringify(result)); - } - }); - ``` - -## geolocation.enableLocationMock9+ - -enableLocationMock(scenario?: LocationRequestScenario) : Promise<void>; - -使能某个场景的位置模拟功能,同一时间只能使能一个场景的位置模拟功能。 - -**系统能力**:SystemCapability.Location.Location.Core - -**系统API**:此接口为系统接口,三方应用不支持调用。 - -**参数**: - - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | scenario | LocationRequestScenario | 否 | 指示使能什么场景的位置模拟功能。如果不携带该参数则表示使能所有场景的位置模拟功能。 | - - -**返回值**: - - | 参数名 | 说明 | - | -------- | -------- | - | Promise<void> | 用来接收执行结果,如果执行成功就返回nullptr,否则就返回错误信息。 | - -**示例** - - ```js - var request = {"scenario": 0x0301}; - geolocation.enableLocationMock(request) - .then((result) => { - if (result) { - console.log('promise, enableLocationMock: result=' + JSON.stringify(result)); - } - }) - .catch((error) => { - if (error) { - console.log('promise, enableLocationMock: error=' + JSON.stringify(error)); - } - }); - ``` - - -## geolocation.disableLocationMock9+ - -disableLocationMock(scenario?: LocationRequestScenario, callback: AsyncCallback<void>) : void; - -去使能位置模拟功能。 - -**系统能力**:SystemCapability.Location.Location.Core - -**系统API**:此接口为系统接口,三方应用不支持调用。 - -**参数**: - - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | scenario | LocationRequestScenario | 否 | 指示去使能某个场景的位置模拟功能。如果不携带该参数则表示去使能所有场景的位置模拟功能。 | - | callback | AsyncCallback<void> | 是 | 用来接收执行结果,如果执行成功就返回nullptr,否则就返回错误信息。 | - -**示例** - - ```js - var request = {"scenario": 0x0301}; - geolocation.disableLocationMock(request, (err, result) => { - if (err) { - console.log('disableLocationMock: err=' + JSON.stringify(err)); - } - if (result) { - console.log('disableLocationMock: result=' + JSON.stringify(result)); - } - }); - ``` - - -## geolocation.disableLocationMock9+ - -disableLocationMock(scenario?: LocationRequestScenario) : Promise<void>; - -去使能位置模拟功能。 - -**系统能力**:SystemCapability.Location.Location.Core - -**系统API**:此接口为系统接口,三方应用不支持调用。 - -**参数**: - - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | scenario | LocationRequestScenario | 否 | 指示去使能某个场景的位置模拟功能。如果不携带该参数则表示去使能所有场景的位置模拟功能。 | - -**返回值**: - - | 参数名 | 说明 | - | -------- | -------- | - | Promise<void> | 用来接收执行结果,如果执行成功就返回nullptr,否则就返回错误信息。 | - -**示例** - - ```js - var request = {"scenario": 0x0301}; - geolocation.disableLocationMock(request) - .then((result) => { - if (result) { - console.log('promise, disableLocationMock: result=' + JSON.stringify(result)); - } - }) - .catch((error) => { - if (error) { - console.log('promise, disableLocationMock: error=' + JSON.stringify(error)); - } - }); - ``` - - -## geolocation.setMockedLocations9+ - -setMockedLocations(config: LocationMockConfig, callback: AsyncCallback<void>) : void; - -设置模拟的位置信息,后面会以该接口中携带的时间间隔上报模拟位置。 - -**系统能力**:SystemCapability.Location.Location.Core - -**系统API**:此接口为系统接口,三方应用不支持调用。 - -**参数**: - - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | config | LocationMockConfig | 是 | 指示位置模拟的配置参数,包含模拟位置上报的时间间隔和模拟位置数组。 | - | callback | AsyncCallback<void> | 是 | 用来接收执行结果,如果执行成功就返回nullptr,否则就返回错误信息。 | - -**示例** - - ```js - var locations = [ - {"latitude": 30.12, "longitude": 120.11, "altitude": 123, "accuracy": 1, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 1000000000, "additionSize": 0, "isFromMock": true}, - {"latitude": 31.13, "longitude": 121.11, "altitude": 123, "accuracy": 2, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 2000000000, "additionSize": 0, "isFromMock": true}, - {"latitude": 32.14, "longitude": 122.11, "altitude": 123, "accuracy": 3, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 3000000000, "additionSize": 0, "isFromMock": true}, - {"latitude": 33.15, "longitude": 123.11, "altitude": 123, "accuracy": 4, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 4000000000, "additionSize": 0, "isFromMock": true}, - {"latitude": 34.16, "longitude": 124.11, "altitude": 123, "accuracy": 5, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 5000000000, "additionSize": 0, "isFromMock": true} - ]; - var config = {"timeInterval": 5, "locations": locations}; - geolocation.setMockedLocations(config, (err, data) => { - if (err) { - console.log('setMockedLocations: err=' + JSON.stringify(err)); - } - if (data) { - console.log('setMockedLocations: data=' + JSON.stringify(data)); - } - }); - ``` - -## geolocation.setMockedLocations9+ - -setMockedLocations(config: LocationMockConfig) : Promise<void>; - -设置模拟的位置信息,后面会以该接口中携带的时间间隔上报模拟位置。 - -**系统能力**:SystemCapability.Location.Location.Core - -**系统API**:此接口为系统接口,三方应用不支持调用。 - -**参数**: - - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | config | LocationMockConfig | 是 | 指示位置模拟的配置参数,包含模拟位置上报的时间间隔和模拟位置数组。 | - -**返回值**: - - | 参数名 | 说明 | - | -------- | -------- | - | Promise<void> | 用来接收执行结果,如果执行成功就返回nullptr,否则就返回错误信息。 | - -**示例** - - ```js - var locations = [ - {"latitude": 30.12, "longitude": 120.11, "altitude": 123, "accuracy": 1, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 1000000000, "additionSize": 0, "isFromMock": true}, - {"latitude": 31.13, "longitude": 121.11, "altitude": 123, "accuracy": 2, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 2000000000, "additionSize": 0, "isFromMock": true}, - {"latitude": 32.14, "longitude": 122.11, "altitude": 123, "accuracy": 3, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 3000000000, "additionSize": 0, "isFromMock": true}, - {"latitude": 33.15, "longitude": 123.11, "altitude": 123, "accuracy": 4, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 4000000000, "additionSize": 0, "isFromMock": true}, - {"latitude": 34.16, "longitude": 124.11, "altitude": 123, "accuracy": 5, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 5000000000, "additionSize": 0, "isFromMock": true} - ]; - var config = {"timeInterval": 5, "locations":locations}; - geolocation.setMockedLocations(config) - .then((result) => { - if (result) { - console.log('promise, setMockedLocations: result=' + JSON.stringify(result)); - } - }) - .catch((error) => { - if (error) { - console.log('promise, setMockedLocations: error=' + JSON.stringify(error)); - } - }); - ``` - - - -## geolocation.enableReverseGeocodingMock9+ - -enableReverseGeocodingMock(callback: AsyncCallback<void>) : void; - -使能逆地理编码模拟功能。 - -**系统能力**:SystemCapability.Location.Location.Core - -**系统API**:此接口为系统接口,三方应用不支持调用。 - -**参数**: - - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | 是 | 用来接收执行结果,如果执行成功就返回nullptr,否则就返回错误信息。 | - -**示例** - - ```js - geolocation.enableReverseGeocodingMock((err, data) => { - if (err) { - console.log('enableReverseGeocodingMock: err=' + JSON.stringify(err)); - } - if (data) { - console.log('enableReverseGeocodingMock: data=' + JSON.stringify(data)); - } - }); - ``` - - -## geolocation.enableReverseGeocodingMock9+ - -enableReverseGeocodingMock() : Promise<void>; - -使能逆地理编码模拟功能。 - -**系统能力**:SystemCapability.Location.Location.Core - -**系统API**:此接口为系统接口,三方应用不支持调用。 - -**参数**: - -无 - -**返回值**: - - | 参数名 | 说明 | - | -------- | -------- | - | Promise<void> | 用来接收执行结果,如果执行成功就返回nullptr,否则就返回错误信息。 | - -**示例** - - ```js - geolocation.enableReverseGeocodingMock() - .then((result) => { - if (result) { - console.log('promise, enableReverseGeocodingMock: result=' + JSON.stringify(result)); - } - }) - .catch((error) => { - if (error) { - console.log('promise, enableReverseGeocodingMock: error=' + JSON.stringify(error)); - } - }); - ``` - - -## geolocation.disableReverseGeocodingMock9+ - -disableReverseGeocodingMock(callback: AsyncCallback<void>) : void; - -去使能逆地理编码模拟功能。 - -**系统能力**:SystemCapability.Location.Location.Core - -**系统API**:此接口为系统接口,三方应用不支持调用。 - -**参数**: - - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | 是 | 用来接收执行结果,如果执行成功就返回nullptr,否则就返回错误信息。 | - -**示例** - - ```js - geolocation.disableReverseGeocodingMock((err, result) => { - if (err) { - console.log('disableReverseGeocodingMock: err=' + JSON.stringify(err)); - } - if (result) { - console.log('disableReverseGeocodingMock: result=' + JSON.stringify(result)); - } - }); - ``` - - -## geolocation.disableReverseGeocodingMock9+ - -disableReverseGeocodingMock() : Promise<void>; - -去使能逆地理编码模拟功能。 - -**系统能力**:SystemCapability.Location.Location.Core - -**系统API**:此接口为系统接口,三方应用不支持调用。 - -**参数**: - -无 - -**返回值**: - - | 参数名 | 说明 | - | -------- | -------- | - | Promise<void> | 用来接收执行结果,如果执行成功就返回nullptr,否则就返回错误信息。 | - -**示例** - - ```js - geolocation.disableReverseGeocodingMock() - .then((result) => { - if (result) { - console.log('promise, disableReverseGeocodingMock: result=' + JSON.stringify(result)); - } - }) - .catch((error) => { - if (error) { - console.log('promise, disableReverseGeocodingMock: error=' + JSON.stringify(error)); - } - }); - ``` - - -## geolocation.setReverseGeocodingMockInfo9+ - -setReverseGeocodingMockInfo(mockInfos: Array<ReverseGeocodingMockInfo>, callback: AsyncCallback<void>) : void; - -设置逆地理编码模拟功能的配置信息,包含了位置和地名的对应关系,后续进行逆地理编码查询时如果位置信息位于配置信息中,就返回对应的地名。 - -**系统能力**:SystemCapability.Location.Location.Core - -**系统API**:此接口为系统接口,三方应用不支持调用。 - -**参数**: - - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | mockInfos | Array<ReverseGeocodingMockInfo> | 是 | 指示逆地理编码模拟功能的配置参数数组。逆地理编码模拟功能的配置参数包含了一个位置和一个地名。 | - | callback | AsyncCallback<void> | 是 | 用来接收执行结果,如果执行成功就返回nullptr,否则就返回错误信息。 | - -**示例** - - ```js - var mockInfos = [ - {"location": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 33.12, "longitude": 123.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 33.12, "longitude": 123.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "maxItems": 1, "isFromMock": true}}, - ]; - geolocation.setReverseGeocodingMockInfo(mockInfos, (err, data) => { - if (err) { - console.log('promise, setReverseGeocodingMockInfo, err:' + JSON.stringify(err)); - } - if (data) { - console.log('promise, setReverseGeocodingMockInfo, data:' + JSON.stringify(data)); - } - }); - ``` - - -## geolocation.setReverseGeocodingMockInfo9+ - -setReverseGeocodingMockInfo(mockInfos: Array<ReverseGeocodingMockInfo>) : Promise<void>; - -设置逆地理编码模拟功能的配置信息,包含了位置和地名的对应关系,后续进行逆地理编码查询时如果位置信息位于配置信息中,就返回对应的地名。 - -**系统能力**:SystemCapability.Location.Location.Core - -**系统API**:此接口为系统接口,三方应用不支持调用。 - -**参数**: - - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | mockInfos | Array<ReverseGeocodingMockInfo> | 是 | 指示逆地理编码模拟功能的配置信息数组。逆地理编码模拟功能的配置信息包含了一个位置和一个地名。 | - -**返回值**: - - | 参数名 | 说明 | - | -------- | -------- | - | Promise<void> | 用来接收执行结果,如果执行成功就返回nullptr,否则就返回错误信息。 | - -**示例** - - ```js - var mockInfos = [ - {"location": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 33.12, "longitude": 123.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 33.12, "longitude": 123.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "maxItems": 1, "isFromMock": true}}, - ]; - geolocation.setReverseGeocodingMockInfo(mockInfos) - .then((result) => { - if (result) { - console.log('promise, setReverseGeocodingMockInfo: result=' + JSON.stringify(result)); - } - }) - .catch((error) => { - if (error) { - console.log('promise, setReverseGeocodingMockInfo: error=' + JSON.stringify(error)); - } - }); - ``` - - -## LocationRequestPriority - -位置请求中位置信息优先级设置。 - -**需要权限**:ohos.permission.LOCATION - -**系统能力**:SystemCapability.Location.Location.Core - -| 名称 | 默认值 | 说明 | -| -------- | -------- | -------- | -| UNSET | 0x200 | 表示未设置优先级。 | -| ACCURACY | 0x201 | 表示精度优先。 | -| LOW_POWER | 0x202 | 表示低功耗优先。 | -| FIRST_FIX | 0x203 | 表示快速获取位置优先,如果应用希望快速拿到1个位置,可以将优先级设置为该字段。 | - - -## LocationRequestScenario - - 位置请求中定位场景设置。 - -**需要权限**:ohos.permission.LOCATION - -**系统能力**:SystemCapability.Location.Location.Core - -| 名称 | 默认值 | 说明 | -| -------- | -------- | -------- | -| UNSET | 0x300 | 表示未设置场景信息。 | -| NAVIGATION | 0x301 | 表示导航场景。 | -| TRAJECTORY_TRACKING | 0x302 | 表示运动轨迹记录场景。 | -| CAR_HAILING | 0x303 | 表示打车场景。 | -| DAILY_LIFE_SERVICE | 0x304 | 表示日常服务使用场景。 | -| NO_POWER | 0x305 | 表示无功耗功场景,这种场景下不会主动触发定位,会在其他应用定位时,才给当前应用返回位置。 | - - -## GeoLocationErrorCode - -位置服务中的错误码信息。 - -**需要权限**:ohos.permission.LOCATION - -**系统能力**:SystemCapability.Location.Location.Core - -| 名称 | 默认值 | 说明 | -| -------- | -------- | -------- | -| NOT_SUPPORTED9+ | 100 | 表示该接口功能不支持。 | -| INPUT_PARAMS_ERROR7+ | 101 | 表示输入参数错误。 | -| REVERSE_GEOCODE_ERROR7+ | 102 | 表示逆地理编码接口调用失败。 | -| GEOCODE_ERROR7+ | 103 | 表示地理编码接口调用失败。 | -| LOCATOR_ERROR7+ | 104 | 表示定位失败。 | -| LOCATION_SWITCH_ERROR7+ | 105 | 表示定位开关。 | -| LAST_KNOWN_LOCATION_ERROR7+ | 106 | 表示获取上次位置失败。 | -| LOCATION_REQUEST_TIMEOUT_ERROR7+ | 107 | 表示单次定位,没有在指定时间内返回位置。 | -| QUERY_COUNTRY_CODE_ERROR9+ | 108 | 表示国家码查询失败。 | - - -## ReverseGeoCodeRequest - -逆地理编码请求接口。 - -**需要权限**:ohos.permission.LOCATION - -**系统能力**:SystemCapability.Location.Location.Geocoder - -| 名称 | 参数类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| locale | string | 否 | 指定位置描述信息的语言,“zh”代表中文,“en”代表英文。 | -| latitude | number | 是 | 表示纬度信息,正值表示北纬,负值表示南纬。 | -| longitude | number | 是 | 表示经度信息,正值表示东经,负值表示西经。 | -| maxItems | number | 否 | 指定返回位置信息的最大个数。 | - - -## GeoCodeRequest - -地理编码请求接口。 - -**需要权限**:ohos.permission.LOCATION - -**系统能力**:SystemCapability.Location.Location.Geocoder - -| 名称 | 参数类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| locale | string | 否 | 表示位置描述信息的语言,“zh”代表中文,“en”代表英文。 | -| description | number | 是 | 表示位置信息描述,如“上海市浦东新区xx路xx号”。 | -| maxItems | number | 否 | 表示返回位置信息的最大个数。 | -| minLatitude | number | 否 | 表示最小纬度信息,与下面三个参数一起,表示一个经纬度范围。 | -| minLongitude | number | 否 | 表示最小经度信息。 | -| maxLatitude | number | 否 | 表示最大纬度信息。 | -| maxLongitude | number | 否 | 表示最大经度信息。 | - - -## GeoAddress - -地理编码类型。 - -**需要权限**:ohos.permission.LOCATION - -**系统能力**:SystemCapability.Location.Location.Geocoder - -| 名称 | 参数类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| latitude7+ | number | 否 | 表示纬度信息,正值表示北纬,负值表示南纬。 | -| longitude7+ | number | 否 | 表示经度信息,正值表示东经,负值表是西经。 | -| locale7+ | string | 否 | 表示位置描述信息的语言,“zh”代表中文,“en”代表英文。 | -| placeName7+ | string | 否 | 表示地区信息。 | -| countryCode7+ | string | 否 | 表示国家码信息。 | -| countryName7+ | string | 否 | 表示国家信息。 | -| administrativeArea7+ | string | 否 | 表示省份区域信息。 | -| subAdministrativeArea7+ | string | 否 | 表示表示子区域信息。 | -| locality7+ | string | 否 | 表示城市信息。 | -| subLocality7+ | string | 否 | 表示子城市信息。 | -| roadName7+ | string | 否 | 表示路名信息。 | -| subRoadName7+ | string | 否 | 表示子路名信息。 | -| premises7+ | string | 否 | 表示门牌号信息。 | -| postalCode7+ | string | 否 | 表示邮政编码信息。 | -| phoneNumber7+ | string | 否 | 表示联系方式信息。 | -| addressUrl7+ | string | 否 | 表示位置信息附件的网址信息。 | -| descriptions7+ | Array<string> | 否 | 表示附加的描述信息。 | -| descriptionsSize7+ | number | 否 | 表示附加的描述信息数量。 | -| isFromMock9+ | Boolean | 否 | 表示地名信息是否来自于逆地理编码模拟功能。 | - - -## LocationRequest - -位置信息请求类型。 - -**需要权限**:ohos.permission.LOCATION - -**系统能力**:SystemCapability.Location.Location.Core - -| 名称 | 参数类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| priority | [LocationRequestPriority](#locationrequestpriority) | 否 | 表示优先级信息。 | -| scenario | [LocationRequestScenario](#locationrequestscenario) | 是 | 表示场景信息。 | -| timeInterval | number | 否 | 表示上报位置信息的时间间隔。 | -| distanceInterval | number | 否 | 表示上报位置信息的距离间隔。 | -| maxAccuracy | number | 否 | 表示精度信息。 | - - -## CurrentLocationRequest - -当前位置信息请求类型。 - -**需要权限**:ohos.permission.LOCATION - -**系统能力**:SystemCapability.Location.Location.Core - -| 名称 | 参数类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| priority | [LocationRequestPriority](#locationrequestpriority) | 否 | 表示优先级信息。 | -| scenario | [LocationRequestScenario](#locationrequestscenario) | 否 | 表示场景信息。 | -| maxAccuracy | number | 否 | 表示精度信息,单位是米。 | -| timeoutMs | number | 否 | 表示超时时间,单位是毫秒,最小为1000毫秒。 | - - -## SatelliteStatusInfo8+ - -卫星状态信息。 - -**需要权限**:ohos.permission.LOCATION - -**系统能力**:SystemCapability.Location.Location.Gnss - -| 名称 | 参数类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| satellitesNumber | number | 是 | 表示卫星个数。 | -| satelliteIds | Array<number> | 是 | 表示每个卫星的ID,数组类型。 | -| carrierToNoiseDensitys | Array<number> | 是 | 表示载波噪声功率谱密度比,即cn0。 | -| altitudes | Array<number> | 是 | 表示高程信息。 | -| azimuths | Array<number> | 是 | 表示方位角。 | -| carrierFrequencies | Array<number> | 是 | 表示载波频率。 | - - -## CachedGnssLocationsRequest8+ - -请求订阅GNSS缓存位置上报功能接口的配置参数。 - -**需要权限**:ohos.permission.LOCATION - -**系统能力**:SystemCapability.Location.Location.Gnss - -| 名称 | 参数类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| reportingPeriodSec | number | 是 | 表示GNSS缓存位置上报的周期,单位是毫秒。 | -| wakeUpCacheQueueFull | boolean | 是 | true表示GNSS芯片底层缓存队列满之后会主动唤醒AP芯片,并把缓存位置上报给应用。
false表示GNSS芯片底层缓存队列满之后不会主动唤醒AP芯片,会把缓存位置直接丢弃。 | - - -## Geofence8+ - -GNSS围栏的配置参数。目前只支持圆形围栏。 +GNSS围栏的配置参数。目前只支持圆形围栏。 **需要权限**:ohos.permission.LOCATION @@ -2010,9 +1348,9 @@ GNSS围栏的配置参数。目前只支持圆形围栏。 | 名称 | 参数类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| priority | LocationRequestPriority | 是 | 表示位置信息优先级。 | -| scenario | LocationRequestScenario | 是 | 表示定位场景。 | -| geofence | Geofence | 是 | 表示围栏信息。 | +| priority | [LocationRequestPriority](#locationrequestpriority) | 是 | 表示位置信息优先级。 | +| scenario | [LocationRequestScenario](#locationrequestscenario) | 是 | 表示定位场景。 | +| geofence | [Geofence](#geofence)| 是 | 表示围栏信息。 | ## LocationPrivacyType8+ @@ -2040,7 +1378,7 @@ GNSS围栏的配置参数。目前只支持圆形围栏。 | 名称 | 参数类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| scenario | LocationRequestScenario | 是 | 表示定位场景。 | +| scenario | [LocationRequestScenario](#locationrequestscenario) | 是 | 表示定位场景。 | | command | string | 是 | 扩展命令字符串。 | @@ -2063,59 +1401,4 @@ GNSS围栏的配置参数。目前只支持圆形围栏。 | direction7+ | number | 是 | 表示航向信息。 | | timeSinceBoot7+ | number | 是 | 表示位置时间戳,开机时间格式。 | | additions7+ | Array<string> | 否 | 附加信息。 | -| additionSize7+ | number | 否 | 附加信息数量。 | -| isFromMock9+ | Boolean | 否 | 表示位置信息是否来自于位置模拟功能。 | - - -## ReverseGeocodingMockInfo9+ - -逆地理编码模拟功能的配置信息,包含一个位置信息和一个地名信息。 - -**系统能力**:SystemCapability.Location.Location.Core - -**系统API**:此接口为系统接口,三方应用不支持调用。 - -| 名称 | 参数类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| location | ReverseGeoCodeRequest | 是 | 表示经纬度信息。 | -| geoAddress | GeoAddress | 是 | 表示地名信息。 | - - -## LocationMockConfig9+ - -位置模拟功能的配置参数,包含了模拟位置上报的时间间隔和模拟位置数组。 - -**系统能力**:SystemCapability.Location.Location.Core - -**系统API**:此接口为系统接口,三方应用不支持调用。 - -| 名称 | 参数类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| timeInterval | number | 是 | 表示模拟位置上报的时间间隔,单位是秒。 | -| locations | Array<Location> | 是 | 表示模拟位置数组。 | - - -## CountryCode9+ - -国家码信息结构体,包含国家码字符串和国家码的来源信息。 - -**系统能力**:SystemCapability.Location.Location.Core - -| 名称 | 参数类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| country | string | 是 | 表示国家码字符串。 | -| type | CountryCodeType | 是 | 表示国家码信息来源。 | - - -## CountryCodeType9+ - -国家码来源类型。 - -**系统能力**:SystemCapability.Location.Location.Core - -| 名称 | 默认值 | 说明 | -| -------- | -------- | -------- | -| COUNTRY_CODE_FROM_LOCALE | 1 | 从全球化模块的语言配置信息中获取到的国家码。 | -| COUNTRY_CODE_FROM_SIM | 2 | 从SIM卡中获取到的国家码。 | -| COUNTRY_CODE_FROM_LOCATION | 3 | 基于用户的位置信息,通过逆地理编码查询到的国家码。 | -| COUNTRY_CODE_FROM_NETWORK | 4 | 从蜂窝网络注册信息中获取到的国家码。 | \ No newline at end of file +| additionSize7+ | number | 否 | 附加信息数量。 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-inputmonitor.md b/zh-cn/application-dev/reference/apis/js-apis-inputmonitor.md index 235bbab8b80bc9dd1ad89a0896e39cd9725dabfe..06de18434c1f9fe4d721e5db79cd185dcebcd684 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-inputmonitor.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inputmonitor.md @@ -1,11 +1,11 @@ # 输入监听 -InputMonitor模块提供了监听全局触摸事件的功能。 - +输入监听模块,提供了监听输入设备事件(当前支持触摸屏和鼠标)的能力。 > **说明:** -> - 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > -> - 本模块接口均为系统接口。 +> - 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +> +> - 本模块接口均为系统接口。 ## 导入模块 @@ -29,19 +29,19 @@ on(type: "touch", receiver: TouchEventReceiver): void **参数:** | 参数 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | ------------------- | -| type | string | 是 | 监听输入事件类型,取值“touch”。 | -| receiver | [TouchEventReceiver](#toucheventreceiver) | 是 | 触摸输入事件回调函数。 | +| type | string | 是 | 输入设备事件类型,取值“touch”。 | +| receiver | [TouchEventReceiver](#toucheventreceiver) | 是 | 回调函数,异步上报触摸屏输入事件。 | **示例:** ```js try { - inputMonitor.on("touch", (data)=> { - console.log(`Monitor on TouchEvent success ${JSON.stringify(data)}`); - return false; - }); + inputMonitor.on("touch", (touchEvent) => { + console.log(`Monitor on success ${JSON.stringify(touchEvent)}`); + return false; + }); } catch (error) { - console.log(`Failed to monitor on TouchEvent, error: ${JSON.stringify(error, [`code`, `message`])}`); + console.log(`Monitor on failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` @@ -58,19 +58,19 @@ on(type: "mouse", receiver: Callback<MouseEvent>): void | 参数 | 类型 | 必填 | 说明 | | -------- | -------------------------- | ---- | ------------------- | -| type | string | 是 | 监听输入事件类型,取值“mouse”。 | -| receiver | Callback<MouseEvent> | 是 | 鼠标输入事件回调函数。 | +| type | string | 是 | 输入设备事件类型,取值“mouse”。 | +| receiver | Callback<MouseEvent> | 是 | 回调函数,异步上报鼠标输入事件。 | **示例:** ```js try { - inputMonitor.on("mouse", (data)=> { - console.log(`Monitor on MouseEvent success ${JSON.stringify(data)}`); - return false; - }); + inputMonitor.on("mouse", (mouseEvent) => { + console.log(`Monitor on success ${JSON.stringify(mouseEvent)}`); + return false; + }); } catch (error) { - console.log(`Failed to monitor on MouseEvent, error: ${JSON.stringify(error, [`code`, `message`])}`); + console.log(`Monitor on failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` @@ -89,31 +89,36 @@ off(type: "touch", receiver?: TouchEventReceiver): void **参数:** | 参数 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | ------------------- | -| type | string | 是 | 监听输入事件类型,取值“touch”。 | -| receiver | [TouchEventReceiver](#toucheventreceiver) | 否 | 触摸输入事件回调函数。 | +| type | string | 是 | 输入设备事件类型,取值“touch”。 | +| receiver | [TouchEventReceiver](#toucheventreceiver) | 否 | 需要取消监听的回调函数,若无此参数,则取消当前应用监听的所有回调函数。 | **示例:** ```js -// 取消监听全局触屏事件 -try { - inputMonitor.off("touch"); -} catch (error) { - console.log(`Failed to monitor off TouchEvent, error: ${JSON.stringify(error, [`code`, `message`])}`); -} -// 单独取消receiver的监听。 -callback:function(data) { - console.log(`call success ${JSON.stringify(data)}`); +// 取消监听单个回调函数 +callback: function(touchEvent) { + console.log(`Monitor on success ${JSON.stringify(touchEvent)}`); + return false; }, try { - inputMonitor.on("touch", this.callback); + inputMonitor.on("touch", this.callback); + inputMonitor.off("touch", this.callback); } catch (error) { - console.log(`Failed to monitor on TouchEvent, error: ${JSON.stringify(error, [`code`, `message`])}`); + console.log(`Monitor execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + +```js +// 取消监听所有回调函数 +callback: function(touchEvent) { + console.log(`Monitor on success ${JSON.stringify(touchEvent)}`); + return false; }, try { - inputMonitor.off("touch",this.callback); + inputMonitor.on("touch", this.callback); + inputMonitor.off("touch"); } catch (error) { - console.log(`Failed to monitor off TouchEvent, error: ${JSON.stringify(error, [`code`, `message`])}`); + console.log(`Monitor execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` @@ -129,39 +134,40 @@ off(type: "mouse", receiver?: Callback<MouseEvent>): void | 参数 | 类型 | 必填 | 说明 | | -------- | -------------------------- | ---- | ------------------- | -| type | string | 是 | 监听输入事件类型,取值“mouse”。 | -| receiver | Callback<MouseEvent> | 否 | 鼠标输入事件回调函数。 | +| type | string | 是 | 输入设备事件类型,取值“mouse”。 | +| receiver | Callback<MouseEvent> | 否 | 需要取消监听的回调函数,若无此参数,则取消当前应用监听的所有回调函数。 | **示例:** ```js -// 取消监听全局鼠标事件 -try { - inputMonitor.off("mouse"); -} catch (error) { - console.log(`Failed to monitor off MouseEvent, error: ${JSON.stringify(error, [`code`, `message`])}`); -} -// 单独取消receiver的监听。 -callback:function(data) { - console.log(`call success ${JSON.stringify(data)}`); +// 取消监听单个回调函数 +callback: function(mouseEvent) { + console.log(`Monitor on success ${JSON.stringify(mouseEvent)}`); }, try { - inputMonitor.on("mouse", this.callback); + inputMonitor.on("mouse", this.callback); + inputMonitor.off("mouse", this.callback); } catch (error) { - console.log(`Failed to monitor on MouseEvent, error: ${JSON.stringify(error, [`code`, `message`])}`); + console.log(`Monitor execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + +```js +// 取消监听所有回调函数 +callback: function(mouseEvent) { + console.log(`Monitor on success ${JSON.stringify(mouseEvent)}`); }, try { - inputMonitor.off("mouse", this.callback); + inputMonitor.on("mouse", this.callback); + inputMonitor.off("mouse"); } catch (error) { - console.log(`Failed to monitor off MouseEvent, error: ${JSON.stringify(error, [`code`, `message`])}`); + console.log(`Monitor execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` - - ## TouchEventReceiver -触摸输入事件的回调函数。如果返回true,则触摸输入被监听器消耗,系统将执行关闭动作。 +触摸输入事件的回调函数。 **需要权限:** ohos.permission.INPUT_MONITORING @@ -170,23 +176,25 @@ try { **参数:** | 参数 | 类型 | 必填 | 说明 | | ---------- | ---------------------------------------- | ---- | ---------------------------------------- | -| touchEvent | [TouchEvent](../arkui-js/js-components-common-events.md) | 是 | 触摸输入事件回调函数,返回true表示输触事件被监听器消费,false表示输触事件未被监听器消费。 | +| touchEvent | [TouchEvent](../arkui-js/js-components-common-events.md) | 是 | 触摸输入事件。 | **返回值:** | 类型 | 说明 | | ------- | ---------------------------------------- | -| Boolean | 返回true表示触摸输入事件被监听器消费,false表示触摸输入事件未被监听器消费。 | +| Boolean | 若返回true,本次触摸后续产生的事件不再分发到窗口;若返回false,本次触摸后续产生的事件还会分发到窗口。 | **示例:** ```js try { - inputMonitor.on("touch", (event) => { - // 若返回true,表示本次操作后续所有事件不再分发到窗口,事件都由监听者消费。 - return false; + inputMonitor.on("touch", touchEvent => { + if (touchEvent.touches.size() == 3) { // 当前有三个手指按下 + return true; + } else { + return false; + } }); - inputMonitor.off("touch"); } catch (error) { - console.log(`Failed to monitor off TouchEvent, error: ${JSON.stringify(error, [`code`, `message`])}`); + console.log(`Monitor on failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-matrix4.md b/zh-cn/application-dev/reference/apis/js-apis-matrix4.md index a53809173e6b63a26bfe5768a870991171ac22e7..5f07667259c42a4651a409ba78dab990d13fe388 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-matrix4.md +++ b/zh-cn/application-dev/reference/apis/js-apis-matrix4.md @@ -148,7 +148,7 @@ import matrix4 from '@ohos.matrix4' @Entry @Component struct Test { - private matrix1 = Matrix4.identity().translate({x:100}) + private matrix1 = matrix4.identity().translate({x:100}) private matrix2 = this.matrix1.copy().scale({x:2}) build() { diff --git a/zh-cn/application-dev/reference/apis/js-apis-nfcTag.md b/zh-cn/application-dev/reference/apis/js-apis-nfcTag.md index 3cccd741b976c1b9122a871a11601e411fa18c55..71a0bee5b2b0e60b8ee2984768de9fa1c4891da5 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-nfcTag.md +++ b/zh-cn/application-dev/reference/apis/js-apis-nfcTag.md @@ -64,29 +64,57 @@ import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag'; onCreate(want, launchParam) { - // add other code here + // add other code here... // want is initialized by nfc service, contains tag info for this found tag - var tagInfo = tag.getTagInfo(want); - if (tagInfo == undefined) { + var tagInfo; + try { + tag.getTagInfo(want); + } catch (error) { + console.log("tag.getTagInfo catched error: " + error); + } + if (tagInfo == null || tagInfo == undefined) { console.log("no TagInfo to be created, ignore it."); return; } + + // get the supported technologies for this found tag. var isNfcATag = false; + var isIsoDepTag = false; for (var i = 0; i < tagInfo.technology.length; i++) { if (tagInfo.technology[i] == tag.NFC_A) { isNfcATag = true; - break; } - // also check for technology: tag.NFC_B/NFC_F/NFC_V/ISO_DEP/NDEF/MIFARE_CLASSIC/MIFARE_ULTRALIGHT/NDEF_FORMATABLE + + if (tagInfo.technology[i] == tag.ISO_DEP) { + isIsoDepTag = true; + } + // also check for technology: tag.NFC_B/NFC_F/NFC_V/NDEF/MIFARE_CLASSIC/MIFARE_ULTRALIGHT/NDEF_FORMATABLE } + + // use NfcA APIs to access the found tag. if (isNfcATag) { - var nfcA = tag.getNfcATag(taginfo); + var nfcA; + try { + nfcA = tag.getNfcATag(taginfo); + } catch (error) { + console.log("tag.getNfcATag catched error: " + error); + } // other code to read or write this found tag. } - // use the same code to handle for "NfcA/NfcB/NfcF/NfcV/IsoDep/Ndef/MifareClassic/MifareUL/NdefFormatable", such as: - // var isoDep = tag.getIsoDepTag(taginfo); + // use getIsoDep APIs to access the found tag. + if (isIsoDepTag) { + var isoDep; + try { + isoDep = tag.getIsoDep(taginfo); + } catch (error) { + console.log("tag.getIsoDep catched error: " + error); + } + // other code to read or write this found tag. + } + + // use the same code to handle for "NfcA/NfcB/NfcF/NfcV/Ndef/MifareClassic/MifareUL/NdefFormatable". } ``` @@ -154,99 +182,135 @@ getNfcVTag(tagInfo: [TagInfo](#taginfo)): [NfcVTag](js-apis-nfctech.md#nfcvtag) | -------- | ---------------- | | [NfcVTag](js-apis-nfctech.md#nfcvtag) | NFC V类型Tag对象。 | -## tag.getIsoDepTag9+ +## tag.getIsoDep9+ -getIsoDepTag(tagInfo: [TagInfo](#taginfo)): [IsoDepTag](js-apis-nfctech.md#isoDepTag9 ) +getIsoDep(tagInfo: [TagInfo](#taginfo)): [IsoDepTag](js-apis-nfctech.md#isoDepTag9 ) -获取IsoDep类型Tag对象,通过该对象可访问Iso Dep技术类型的Tag。 - -**需要权限**:ohos.permission.NFC_TAG +获取IsoDep类型Tag对象,通过该对象可访问支持IsoDep技术类型的Tag。 **系统能力**:SystemCapability.Communication.NFC.Core -**返回值:** +**参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------- | ------------------------- | ---- | ---------------------------------------- | +| taginfo | [TagInfo](#taginfo) | 是 | 包含Tag技术类型和相关参数,从tag.getTagInfo(want: Want)获取。 | +**返回值:** | **类型** | **说明** | | ---------- | ------------------| -| [IsoDepTag](js-apis-nfctech.md#isodeptag9) | Iso Dep类型Tag对象。 | - -## tag.getNdefTag9+ +| [IsoDepTag](js-apis-nfctech.md#isodeptag9) | IsoDep类型Tag对象,通过该对象访问IsoDep类型的相关接口。 | -getNdefTag(tagInfo: [TagInfo](#taginfo)): [NdefTag](js-apis-nfctech.md#ndeftag9) +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state of service is abnormal. | -获取Ndef类型Tag对象,通过该对象可访问Ndef技术类型的Tag。 +## tag.getNdef9+ +getNdef(tagInfo: [TagInfo](#taginfo)): [NdefTag](js-apis-nfctech.md#ndeftag9) -**需要权限**:ohos.permission.NFC_TAG +获取NDEF类型Tag对象,通过该对象可访问支持NDEF技术类型的Tag。 **系统能力**:SystemCapability.Communication.NFC.Core -**返回值:** +**参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------- | ------------------------- | ---- | ---------------------------------------- | +| taginfo | [TagInfo](#taginfo) | 是 | 包含Tag技术类型和相关参数,从tag.getTagInfo(want: Want)获取。 | +**返回值:** | **类型** | **说明** | | ---------| -------------- | -| [NdefTag](js-apis-nfctech.md#ndeftag9) | Ndef类型Tag对象。| +| [NdefTag](js-apis-nfctech.md#ndeftag9) | NDEF类型Tag对象,通过该对象访问NDEF类型的相关接口。| -## tag.getMifareClassicTag9+ +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state of service is abnormal. | -getMifareClassicTag(tagInfo: [TagInfo](#taginfo)): [MifareClassicTag](js-apis-nfctech.md#mifareclassictag-9) +## tag.getMifareClassic9+ -获取Mifare Classic类型Tag对象,通过该对象访问Mifare Classic技术类型的Tag。 +getMifareClassic(tagInfo: [TagInfo](#taginfo)): [MifareClassicTag](js-apis-nfctech.md#mifareclassictag-9) -**需要权限**:ohos.permission.NFC_TAG +获取MIFARE Classic类型Tag对象,通过该对象访问支持MIFARE Classic技术类型的Tag。 **系统能力**:SystemCapability.Communication.NFC.Core -**返回值:** +**参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------- | ------------------------- | ---- | ---------------------------------------- | +| taginfo | [TagInfo](#taginfo) | 是 | 包含Tag技术类型和相关参数,从tag.getTagInfo(want: Want)获取。 | +**返回值:** | **类型** | **说明** | | ----------------- | ------------------------| -| [MifareClassicTag](js-apis-nfctech.md#mifareclassictag-9) | Mifare Classic类型Tag对象。 | +| [MifareClassicTag](js-apis-nfctech.md#mifareclassictag-9) | MIFARE Classic类型Tag对象,通过该对象访问MIFARE Classic类型的相关接口。 | -## tag.getMifareUltralightTag9+ +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state of service is abnormal. | -getMifareUltralightTag(tagInfo: [TagInfo](#taginfo)): [MifareUltralightTag](js-apis-nfctech.md#mifareultralighttag9) +## tag.getMifareUltralight9+ -获取Mifare Ultralight类型Tag对象,通过该对象可访问Mifare Ultralight技术类型的Tag。 +getMifareUltralight(tagInfo: [TagInfo](#taginfo)): [MifareUltralightTag](js-apis-nfctech.md#mifareultralighttag9) -**需要权限**:ohos.permission.NFC_TAG +获取MIFARE Ultralight类型Tag对象,通过该对象可访问支持MIFARE Ultralight技术类型的Tag。 **系统能力**:SystemCapability.Communication.NFC.Core -**返回值:** +**参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------- | ------------------------- | ---- | ---------------------------------------- | +| taginfo | [TagInfo](#taginfo) | 是 | 包含Tag技术类型和相关参数,从tag.getTagInfo(want: Want)获取。 | +**返回值:** | **类型** | **说明** | | -------------------- | ---------------------------| -| [MifareUltralightTag](js-apis-nfctech.md#mifareultralighttag9) | Mifare Ultralight类型Tag对象。 | +| [MifareUltralightTag](js-apis-nfctech.md#mifareultralighttag9) | MIFARE Ultralight类型Tag对象,通过该对象访问MIFARE Ultralight类型的相关接口。 | -## tag.getNdefFormatableTag9+ +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state of service is abnormal. | -getNdefFormatableTag(tagInfo: [TagInfo](#taginfo)): [NdefFormatableTag](js-apis-nfctech.md#ndefformatabletag9) +## tag.getNdefFormatable9+ -获取Ndef Formatable类型Tag对象,通过该对象可访问Ndef Formatable技术类型的Tag。 +getNdefFormatable(tagInfo: [TagInfo](#taginfo)): [NdefFormatableTag](js-apis-nfctech.md#ndefformatabletag9) -**需要权限**:ohos.permission.NFC_TAG +获取NDEF Formatable类型Tag对象,通过该对象可访问支持NDEF Formatable技术类型的Tag。 **系统能力**:SystemCapability.Communication.NFC.Core **返回值:** - | **类型** | **说明** | | ------------------ | --------------------------| -| [NdefFormatableTag](js-apis-nfctech.md#ndefformatabletag) | Ndef Formatable类型Tag对象。 | +| [NdefFormatableTag](js-apis-nfctech.md#ndefformatabletag) | NDEF Formatable类型Tag对象,通过该对象访问NDEF Formatable类型的相关接口。 | + +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state of service is abnormal. | ## tag.getTagInfo9+ -getTagInfo(want: Want): [TagInfo](#taginfo) +getTagInfo(want: [Want](js-apis-application-Want.md#Want)): [TagInfo](#taginfo) 从Want中获取TagInfo,Want是被NFC服务初始化,包含了TagInfo所需的属性值。 -**需要权限**:ohos.permission.NFC_TAG - **系统能力**:SystemCapability.Communication.NFC.Core -**返回值:** +**参数:** +| 参数名 | 类型 | 必填 | 说明 | +| --------- | ------------------------- | ---- | ---------------------------------------- | +| want | [Want](js-apis-application-Want.md#Want) | 是 | 分发Ability时,在系统onCreate入口函数的参数中获取。 | +**返回值:** | **类型** | **说明** | | ------------------ | --------------------------| | [TagInfo](#taginfo) | TagInfo对象,用于获取不同技术类型的Tag对象。 | @@ -255,8 +319,6 @@ getTagInfo(want: Want): [TagInfo](#taginfo) NFC服务在读取到标签时给出的对象,通过改对象属性,应用知道该标签支持哪些技术类型,并使用匹配的技术类型来调用相关接口。 -**需要权限**:ohos.permission.NFC_TAG - **系统能力**:SystemCapability.Communication.NFC.Core | **参数名** | **类型** | **说明** | @@ -268,8 +330,6 @@ NFC服务在读取到标签时给出的对象,通过改对象属性,应用 ## NdefRecord9+ NDEF标签Record属性的定义,参考NDEF标签技术规范《NFCForum-TS-NDEF_1.0》的定义细节。 -**需要权限**:ohos.permission.NFC_TAG - **系统能力**:SystemCapability.Communication.NFC.Core | **参数名** | **类型** | **说明** | | -------- | -------- | -------- | @@ -281,8 +341,6 @@ NDEF标签Record属性的定义,参考NDEF标签技术规范《NFCForum-TS-NDE ## 技术类型定义 NFC Tag有多种不同的技术类型,定义常量描述不同的技术类型。 -**需要权限**:ohos.permission.NFC_TAG - **系统能力**:SystemCapability.Communication.NFC.Core | **参数名** | **常量值** | **说明** | | -------- | -------- | -------- | @@ -292,15 +350,13 @@ NFC Tag有多种不同的技术类型,定义常量描述不同的技术类型 | NFC_F | 4 | NFC-F(JIS 6319-4)技术。| | NFC_V | 5 | NFC-V(ISO 15693)技术。| | NDEF | 6 | NDEF技术。| -| MIFARE_CLASSIC | 8 | Mifare Classic技术。| -| MIFARE_ULTRALIGHT | 9 | Mifare Utralight技术。| +| MIFARE_CLASSIC | 8 | MIFARE Classic技术。| +| MIFARE_ULTRALIGHT | 9 | MIFARE Utralight技术。| | NDEF_FORMATABLE9+ | 10 | 可以格式化的NDEF技术。| ## TnfType9+ NDEF Record的TNF(Type Name Field)类型值,参考NDEF标签技术规范《NFCForum-TS-NDEF_1.0》的定义细节。 -**需要权限**:ohos.permission.NFC_TAG - **系统能力**:SystemCapability.Communication.NFC.Core | **参数名** | **常量值** | **说明** | | -------- | -------- | -------- | @@ -315,8 +371,6 @@ NDEF Record的TNF(Type Name Field)类型值,参考NDEF标签技术规范《NFC ## NDEF Record RTD类型定义 NDEF Record的RTD(Record Type Definition)类型值,参考NDEF标签技术规范《NFCForum-TS-NDEF_1.0》的定义细节。 -**需要权限**:ohos.permission.NFC_TAG - **系统能力**:SystemCapability.Communication.NFC.Core | **参数名** | **常量值** | **说明** | | -------- | -------- | -------- | @@ -326,8 +380,6 @@ NDEF Record的RTD(Record Type Definition)类型值,参考NDEF标签技术规 ## NfcForumType9+ NFC Forum标准里面Tag类型的定义。 -**需要权限**:ohos.permission.NFC_TAG - **系统能力**:SystemCapability.Communication.NFC.Core | **参数名** | **常量值** | **说明** | | -------- | -------- | -------- | @@ -335,25 +387,21 @@ NFC Forum标准里面Tag类型的定义。 | NFC_FORUM_TYPE_2 | 2 | NFC论坛类型2。 | | NFC_FORUM_TYPE_3 | 3 | NFC论坛类型3。 | | NFC_FORUM_TYPE_4 | 4 | NFC论坛类型4。 | -| MIFARE_CLASSIC | 101 | Mifare Classic类型。 | +| MIFARE_CLASSIC | 101 | MIFARE Classic类型。 | ## MifareClassicType9+ -MifareClassic标签类型的定义。 - -**需要权限**:ohos.permission.NFC_TAG +MIFARE Classic标签类型的定义。 **系统能力**:SystemCapability.Communication.NFC.Core | **参数名** | **常量值** | **说明** | | -------- | -------- | -------- | -| TYPE_UNKNOWN | -1 | 未知Mifare类型。 | -| TYPE_CLASSIC | 0 | Mifare Classic类型。| -| TYPE_PLUS | 1 | Mifare Plus类型。| -| TYPE_PRO | 2 | Mifare Pro类型。 | +| TYPE_UNKNOWN | 0 | 未知MIFARE类型。 | +| TYPE_CLASSIC | 1 | MIFARE Classic类型。| +| TYPE_PLUS | 2 | MIFARE Plus类型。| +| TYPE_PRO | 3 | MIFARE Pro类型。 | ## MifareClassicSize9+ -MifareClassic标签存储大小的定义。 - -**需要权限**:ohos.permission.NFC_TAG +MIFARE Classic标签存储大小的定义。 **系统能力**:SystemCapability.Communication.NFC.Core | **参数名** | **常量值** | **说明** | @@ -363,15 +411,13 @@ MifareClassic标签存储大小的定义。 | MC_SIZE_2K | 2048 | 每个标签32个扇区,每个扇区4个块。 | | MC_SIZE_4K | 4096 | 每个标签40个扇区,每个扇区4个块。| -### MifareUltralightType9+ -MifareUltralight标签类型的定义。 - -**需要权限**:ohos.permission.NFC_TAG +## MifareUltralightType9+ +MIFARE Ultralight标签类型的定义。 **系统能力**:SystemCapability.Communication.NFC.Core | **参数名** | **常量值** | **说明** | | -------- | -------- | -------- | -| TYPE_UNKOWN | -1 | 未知的 Mifare 类型。 | -| TYPE_ULTRALIGHT | 1 | Mifare Ultralight类型。| -| TYPE_ULTRALIGHT_C | 2 | Mifare UltralightC 类型。 | +| TYPE_UNKOWN | 0 | 未知的 MIFARE 类型。 | +| TYPE_ULTRALIGHT | 1 | MIFARE Ultralight类型。| +| TYPE_ULTRALIGHT_C | 2 | MIFARE UltralightC 类型。 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-nfctech.md b/zh-cn/application-dev/reference/apis/js-apis-nfctech.md index 2ddd53f960a95e6d2b230017b8c34d17f1c8617f..f198cca93ffad384df83c41be315cc0a0c252b7c 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-nfctech.md +++ b/zh-cn/application-dev/reference/apis/js-apis-nfctech.md @@ -15,7 +15,7 @@ import tag from '@ohos.nfc.tag'; NfcATag 提供 NFC-A(ISO 14443-3A)技术的属性和I/O操作的访问,继承自TagSession。 -TagSession是所有Nfc tag 技术类型的基类, 提供建立连接和发送数据等共同接口。具体请参见[TagSession](js-apis-tagSession.md)。 +TagSession是所有NFC Tag技术类型的基类, 提供建立连接和发送数据等共同接口。具体请参见[TagSession](js-apis-tagSession.md)。 以下是NfcATag的独有接口。 @@ -40,8 +40,7 @@ getSak(): number ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'nfcA' correctly. - +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'nfcA' correctly. let sak = nfcA.getSak(); console.log("nfcA sak: " + sak); ``` @@ -67,7 +66,7 @@ getAtqa(): number[] ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'nfcA' correctly. +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'nfcA' correctly. let atqa = nfcA.getAtqa(); console.log("nfcA atqa: " + atqa); ``` @@ -76,7 +75,7 @@ console.log("nfcA atqa: " + atqa); NfcBTag 提供对NFC-B(ISO 14443-3B)技术的属性和I/O操作的访问,继承自TagSession。 -TagSession是所有Nfc tag 技术类型的基类,提供建立连接和发送数据等共同接口。具体请参见[TagSession](js-apis-tagSession.md)。 +TagSession是所有NFC Tag技术类型的基类,提供建立连接和发送数据等共同接口。具体请参见[TagSession](js-apis-tagSession.md)。 以下是NfcBTag的独有接口。 @@ -101,7 +100,7 @@ getRespAppData(): number[] ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'nfcB' correctly. +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'nfcB' correctly. let respAppData = nfcB.getRespAppData(); console.log("nfcB respAppData: " + respAppData); ``` @@ -127,7 +126,7 @@ getRespProtocol(): number[] ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'nfcB' correctly. +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'nfcB' correctly. let respProtocol = nfcB.getRespProtocol(); console.log("nfcB respProtocol: " + respProtocol); ``` @@ -136,7 +135,7 @@ console.log("nfcB respProtocol: " + respProtocol); NfcFTag 提供对NFC-F(JIS 6319-4)技术的属性和I/O操作的访问,继承自TagSession。 -TagSession是所有Nfc tag 技术类型的基类, 提供建立连接和发送数据等共同接口。具体请参见[TagSession](js-apis-tagSession.md)。 +TagSession是所有NFC Tag技术类型的基类, 提供建立连接和发送数据等共同接口。具体请参见[TagSession](js-apis-tagSession.md)。 以下是NfcFTag的独有接口。 @@ -161,7 +160,7 @@ getSystemCode(): number[] ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'nfcF' correctly. +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'nfcF' correctly. let systemCode = nfcF.getSystemCode(); console.log("nfcF systemCode: " + systemCode); ``` @@ -187,7 +186,7 @@ getPmm(): number[] ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'nfcF' correctly. +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'nfcF' correctly. let pmm = nfcF.getPmm(); console.log("nfcF pmm: " + pmm); ``` @@ -196,7 +195,7 @@ console.log("nfcF pmm: " + pmm); NfcVTag 提供对NFC-V(ISO 15693)技术的属性和I/O操作的访问,继承自TagSession。 -TagSession是所有Nfc tag 技术类型的基类, 提供建立连接和发送数据等共同接口。具体请参见[TagSession](js-apis-tagSession.md)。 +TagSession是所有NFC Tag技术类型的基类, 提供建立连接和发送数据等共同接口。具体请参见[TagSession](js-apis-tagSession.md)。 以下是NfcVTag的独有接口。 @@ -221,7 +220,7 @@ getResponseFlags(): number ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'nfcV' correctly. +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'nfcV' correctly. let responseFlags = nfcV.getResponseFlags(); console.log("nfcV responseFlags: " + responseFlags); ``` @@ -247,7 +246,7 @@ getDsfId(): number ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'nfcV' correctly. +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'nfcV' correctly. let dsfId = nfcV.getDsfId(); console.log("nfcV dsfId: " + dsfId); ``` @@ -256,7 +255,7 @@ console.log("nfcV dsfId: " + dsfId); IsoDepTag 提供对ISO-DEP(ISO 14443-4)技术的属性和I/O操作的访问,继承自TagSession。 -TagSession是所有Nfc tag 技术类型的基类, 提供建立连接和发送数据等共同接口。具体请参见[TagSession](js-apis-tagSession.md)。 +TagSession是所有NFC Tag技术类型的基类, 提供建立连接和发送数据等共同接口。具体请参见[TagSession](js-apis-tagSession.md)。 以下是IsoDepTag的独有接口。 @@ -264,24 +263,20 @@ TagSession是所有Nfc tag 技术类型的基类, 提供建立连接和发送 getHistoricalBytes(): number[] -获取标签的历史字节。 - -**需要权限**:ohos.permission.NFC_TAG +获取标签的历史字节,针对基于NfcA通信技术的IsoDep卡片。 **系统能力**:SystemCapability.Communication.NFC **返回值:** - | **类型** | **说明** | | ------------------ | --------------------------| -| number[] | IsoDepTag 标签的历史字节,每个number十六进制表示,范围是0x00~0xFF。| +| number[] | IsoDepTag 标签的历史字节,每个number十六进制表示,范围是0x00~0xFF。如果该IsoDep类型Tag是基于NfcB技术的,则该返回值为空。| **示例:** - ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'isoDep' correctly. +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'isoDep' correctly. let historicalBytes = isoDep.getHistoricalBytes(); console.log("isoDep historicalBytes: " + historicalBytes); ``` @@ -290,24 +285,20 @@ console.log("isoDep historicalBytes: " + historicalBytes); getHiLayerResponse(): number[] -获取标签的HiLayer响应字节。 - -**需要权限**:ohos.permission.NFC_TAG +获取标签的更高层响应字节,针对基于NfcB通信技术的IsoDep卡片。 **系统能力**:SystemCapability.Communication.NFC **返回值:** - | **类型** | **说明** | | ------------------ | --------------------------| -| number[] | IsoDepTag 标签的HiLayer响应字节,每个number十六进制表示,范围是0x00~0xFF。| +| number[] | IsoDepTag 标签的更高层响应字节,每个number十六进制表示,范围是0x00~0xFF。如果该IsoDep类型Tag是基于NfcA技术的,则该返回值为空。| **示例:** - ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'isoDep' correctly. +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'isoDep' correctly. let hiLayerResponse = isoDep.getHiLayerResponse(); console.log("isoDep hiLayerResponse: " + hiLayerResponse); ``` @@ -316,137 +307,368 @@ console.log("isoDep hiLayerResponse: " + hiLayerResponse); isExtendedApduSupported(): Promise<boolean> -检查是否支持扩展的APDU,使用promise方式作为异步方法。 +检查是否支持扩展的APDU,使用Promise方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **返回值:** - | **类型** | **说明** | | ------------------ | --------------------------| | Promise<boolean> | 检查结果,true: 支持, false: 不支持。| -**示例:** +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | +**示例:** ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'isoDep' correctly. -isoDep.isExtendedApduSupported() - .then((data) => { - console.log("isoDep isExtendedApduSupported data: " + data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'isoDep' correctly. + +// connect the tag at first if not connected. +if (!isoDep.isTagConnected()) { + if (!isoDep.connectTag()) { + console.log("isoDep connectTag failed."); + return; + } +} + +try { + isoDep.isExtendedApduSupported().then((response) => { + console.log("isoDep isExtendedApduSupported Promise response: " + response); }).catch((err)=> { - console.log("isoDep isExtendedApduSupported err: " + err); + console.log("isoDep isExtendedApduSupported Promise err: " + err); }); +} catch (busiError) { + console.log("isoDep isExtendedApduSupported Promise busiError: " + busiError); +} + ``` ### IsoDepTag.isExtendedApduSupported9+ isExtendedApduSupported(callback: AsyncCallback\): void -检查是否支持扩展的APDU,使用callback方式作为异步方法。 +检查是否支持扩展的APDU,使用AsyncCallback方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | | callback | AsyncCallback\ | 是 | 回调函数,true: 支持, false: 不支持。 | +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | + ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'isoDep' correctly. -isoDep.isExtendedApduSupported((err, data)=> { - if (err) { - console.log("isoDep isExtendedApduSupported err: " + err); - } else { - console.log("isoDep isExtendedApduSupported data: " + data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'isoDep' correctly. + +// connect the tag at first if not connected. +if (!isoDep.isTagConnected()) { + if (!isoDep.connectTag()) { + console.log("isoDep connectTag failed."); + return; } -}); +} + +try { + isoDep.isExtendedApduSupported((err, response)=> { + if (err) { + console.log("isoDep isExtendedApduSupported AsyncCallback err: " + err); + } else { + console.log("isoDep isExtendedApduSupported AsyncCallback response: " + response); + } + }); +} catch (busiError) { + console.log("isoDep isExtendedApduSupported AsyncCallback busiError: " + busiError); +} ``` -## NdefTag9+ +## NdefMessage9+ -提供对已格式化为NDEF的NFC标签的数据和操作的访问,继承自TagSession。 +### NdefMessage.getNdefRecords9+ -TagSession是所有NFC Tag技术类型的基类, 提供建立连接和发送数据等共同接口。具体请参见[TagSession](js-apis-tagSession.md)。 +getNdefRecords(): [NdefRecord](js-apis-nfcTag.md#ndefrecord9)[] -以下是NdefTag的独有接口。 +获取NDEF消息中的所有记录。 -### NdefTag.createNdefMessage9+ +**系统能力**:SystemCapability.Communication.NFC -createNdefMessage(data: number[]): [NdefMessage](#ndefmessage9) +**返回值:** +| **类型** | **说明** | +| ------------------ | --------------------------| +| [NdefRecord](js-apis-nfcTag.md#ndefrecord9)[] | NDEF标签的Record列表,详见NDEF技术规范《NFCForum-TS-NDEF_1.0》。 | -使用原始字节创建ndef消息。 +**示例:** +```js +import tag from '@ohos.nfc.tag'; -**需要权限**:ohos.permission.NFC_TAG +// see NdefTag, obtains ndefMessage from ndefTag.createNdefMessage or ndefTag.getNdefMessage. +// var ndefMessage = ndefTag.createNdefMessage(...); +// var ndefMessage = ndefTag.getNdefMessage(); -**系统能力**:SystemCapability.Communication.NFC +let ndefRecords = ndefMessage.getNdefRecords(); +console.log("ndef ndefRecords number: " + ndefRecords.length); +``` + +### NdefMessage.makeUriRecord9+ + +makeUriRecord(uri: string): [NdefRecord](js-apis-nfcTag.md#ndefrecord9); + +根据输入的URI,构建NDEF标签的Record数据对象。 +**系统能力**:SystemCapability.Communication.NFC **参数:** -| **参数名** | **类型** | **必填** | **说明** | -| -------- | -------- | -------- | -------- | -| data | number[] | 是 | 原始字节,每个number十六进制表示,范围是0x00~0xFF | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------- | ---- | -------------------------------------- | +| uri | string | 是 | 写入到NDEF Record里面的数据内容。 | **返回值:** - | **类型** | **说明** | | ------------------ | --------------------------| -| [NdefMessage](#ndefmessage9) | NDEF标签的Message,详见NDEF技术规范《NFCForum-TS-NDEF_1.0》。 | +| [NdefRecord](js-apis-nfcTag.md#ndefrecord9) | NDEF标签的Record,详见NDEF技术规范《NFCForum-TS-NDEF_1.0》。 | **示例:** +```js +import tag from '@ohos.nfc.tag'; + +// see NdefTag, obtains ndefMessage from ndefTag.createNdefMessage or ndefTag.getNdefMessage. Such as: +// var ndefMessage = ndefTag.createNdefMessage(...); +// var ndefMessage = ndefTag.getNdefMessage(); +try { + let uri = "https://gitee.com/openharmony"; // change it to be correct. + let ndefRecord = ndefMessage.makeUriRecord(uri); + if (ndefRecord != undefined) { + console.log("ndefMessage makeUriRecord rtdType: " + ndefRecord.rtdType); + console.log("ndefMessage makeUriRecord payload: " + ndefRecord.payload); + } else { + console.log("ndefMessage makeUriRecord ndefRecord: " + ndefRecord); + } +} catch (busiError) { + console.log("ndefMessage makeUriRecord catched busiError: " + busiError); +} +``` + +### NdefMessage.makeTextRecord9+ + +makeTextRecord(text: string, locale: string): [NdefRecord](js-apis-nfcTag.md#ndefrecord9); + +根据输入的文本数据和编码类型,构建NDEF标签的Record。 + +**系统能力**:SystemCapability.Communication.NFC +**参数:** +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------- | ---- | -------------------------------------- | +| text | string | 是 | 写入到NDEF Record里面的文本数据内容。 | +| locale | string | 是 | 文本数据内容的编码方式。 | + +**返回值:** +| **类型** | **说明** | +| ------------------ | --------------------------| +| [NdefRecord](js-apis-nfcTag.md#ndefrecord9) | NDEF标签的Record,详见NDEF技术规范《NFCForum-TS-NDEF_1.0》。 | + +**示例:** ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'ndef' correctly. -let rawData = [0x00, 0xa4, 0x04, ......]; // change the raw data bytes tobe correct. -let ndefMessage = ndef.createNdefMessage(rawData); -console.log("ndef ndefMessage: " + ndefMessage); +// see NdefTag, obtains ndefMessage from ndefTag.createNdefMessage or ndefTag.getNdefMessage. Such as: +// var ndefMessage = ndefTag.createNdefMessage(...); +// var ndefMessage = ndefTag.getNdefMessage(); + +try { + let text = "Hello World"; // change it to be correct. + let locale = "utf8"; // change it to be correct. + let ndefRecord = ndefMessage.makeTextRecord(text, locale); + if (ndefRecord != undefined) { + console.log("ndefMessage makeTextRecord rtdType: " + ndefRecord.rtdType); + console.log("ndefMessage makeTextRecord payload: " + ndefRecord.payload); + } else { + console.log("ndefMessage makeTextRecord ndefRecord: " + ndefRecord); + } +} catch (busiError) { + console.log("ndefMessage makeTextRecord catched busiError: " + busiError); +} ``` -## NdefMessage9+ -### NdefMessage.getNdefRecords9+ +### NdefMessage.makeMimeRecord9+ -getNdefRecords(): [NdefRecord](js-apis-nfcTag.md#ndefrecord9)[ ] +makeMimeRecord(mimeType: string, mimeData: number[]): [NdefRecord](js-apis-nfcTag.md#ndefrecord9); -获取ndef消息的所有记录。 +根据输入的MIME数据和类型,构建NDEF标签的Record。 -**需要权限**:ohos.permission.NFC_TAG +**系统能力**:SystemCapability.Communication.NFC +**参数:** +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------- | ---- | -------------------------------------- | +| mimeType | string | 是 | MIME数据的类型。 | +| mimeData | number[] | 是 | MIME数据内容。 | + +**返回值:** +| **类型** | **说明** | +| ------------------ | --------------------------| +| [NdefRecord](js-apis-nfcTag.md#ndefrecord9) | NDEF标签的Record,详见NDEF技术规范《NFCForum-TS-NDEF_1.0》。 | + +**示例:** +```js +import tag from '@ohos.nfc.tag'; + +// see NdefTag, obtains ndefMessage from ndefTag.createNdefMessage or ndefTag.getNdefMessage. Such as: +// var ndefMessage = ndefTag.createNdefMessage(...); +// var ndefMessage = ndefTag.getNdefMessage(); + +try { + let mimeType = "media"; // change it to be correct. + let mimeData = [0x01, 0x02, 0x03, 0x04]; // change it to be correct. + let ndefRecord = ndefMessage.makeMimeRecord(mimeType, mimeData); + if (ndefRecord != undefined) { + console.log("ndefMessage makeMimeRecord rtdType: " + ndefRecord.rtdType); + console.log("ndefMessage makeMimeRecord payload: " + ndefRecord.payload); + } else { + console.log("ndefMessage makeMimeRecord ndefRecord: " + ndefRecord); + } +} catch (busiError) { + console.log("ndefMessage makeMimeRecord catched busiError: " + busiError); +} +``` +### NdefMessage.makeExternalRecord9+ + +makeExternalRecord(domainName: string, serviceName: string, externalData: number[]): [NdefRecord](js-apis-nfcTag.md#ndefrecord9); + +根据应用程序特定的外部数据,构建NDEF标签的Record。 **系统能力**:SystemCapability.Communication.NFC +**参数:** +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------- | ---- | -------------------------------------- | +| domainName | string | 是 | 外部数据发布组织的域名,一般是应用程序的包名。 | +| serviceName | string | 是 | 外部数据的指定类型。 | +| externalData | number[] | 是 | 外部数据内容。 | **返回值:** +| **类型** | **说明** | +| ------------------ | --------------------------| +| [NdefRecord](js-apis-nfcTag.md#ndefrecord9) | NDEF标签的Record,详见NDEF技术规范《NFCForum-TS-NDEF_1.0》。 | + +**示例:** +```js +import tag from '@ohos.nfc.tag'; + +// see NdefTag, obtains ndefMessage from ndefTag.createNdefMessage or ndefTag.getNdefMessage. Such as: +// var ndefMessage = ndefTag.createNdefMessage(...); +// var ndefMessage = ndefTag.getNdefMessage(); + +try { + let domainName = "ohos.nfc.application"; // change it to be correct. + let type = "nfc"; // change it to be correct. + let externalData = [0x01, 0x02, 0x03, 0x04]; // change it to be correct. + let ndefRecord = ndefMessage.makeExternalRecord(domainName, type, externalData); + if (ndefRecord != undefined) { + console.log("ndefMessage makeExternalRecord rtdType: " + ndefRecord.rtdType); + console.log("ndefMessage makeExternalRecord payload: " + ndefRecord.payload); + } else { + console.log("ndefMessage makeExternalRecord ndefRecord: " + ndefRecord); + } +} catch (busiError) { + console.log("ndefMessage makeExternalRecord catched busiError: " + busiError); +} +``` + +### NdefMessage.messageToBytes9+ + +messageToBytes(ndefMessage: [NdefMessage](#ndefmessage9)): number[]; + +把输入的NDEF消息数据对象,转换为字节格式的数据。 +**系统能力**:SystemCapability.Communication.NFC +**参数:** +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------- | ---- | -------------------------------------- | +| ndefMessage | [NdefMessage](#ndefmessage9) | 是 | NDEF消息数据对象。 | + +**返回值:** | **类型** | **说明** | | ------------------ | --------------------------| -| [NdefRecord](js-apis-nfcTag.md#ndefrecord9)[ ] | NDEF标签的Record列表,详见NDEF技术规范《NFCForum-TS-NDEF_1.0》。 | +| number[] | NDEF消息数据对象,所转换成的字节格式的数据。每个number十六进制表示,范围是0x00~0xFF。 | **示例:** +```js +import tag from '@ohos.nfc.tag'; + +// see NdefTag, obtains ndefMessage from ndefTag.createNdefMessage or ndefTag.getNdefMessage. Such as: +// var ndefMessage = ndefTag.createNdefMessage(...); +// var ndefMessage = ndefTag.getNdefMessage(); + +try { + // the parameter 'ndefMessage' can be different from the instance object. + let rawData = ndefMessage.messageToBytes(ndefMessage); + console.log("ndefMessage messageToBytes rawData: " + rawData); +} catch (busiError) { + console.log("ndefMessage messageToBytes catched busiError: " + busiError); +} +``` + +## NdefTag9+ + +提供对已格式化为NDEF的NFC标签的数据和操作的访问,继承自TagSession。 + +TagSession是所有NFC Tag技术类型的基类, 提供建立连接和发送数据等共同接口。具体请参见[TagSession](js-apis-tagSession.md)。 + +以下是NdefTag的独有接口。 + +### NdefTag.createNdefMessage9+ + +createNdefMessage(data: number[]): [NdefMessage](#ndefmessage9) + +使用原始字节数据创建NDEF标签的Message。该数据必须符合NDEF Record数据格式,如果不符合格式,则返回的NdeMessage数据对象,所包含的NDE Record列表会为空。 + +**系统能力**:SystemCapability.Communication.NFC + +**参数:** +| **参数名** | **类型** | **必填** | **说明** | +| -------- | -------- | -------- | -------- | +| data | number[] | 是 | 原始字节,每个number十六进制表示,范围是0x00~0xFF。 | +**返回值:** +| **类型** | **说明** | +| ------------------ | --------------------------| +| [NdefMessage](#ndefmessage9) | NDEF标签的Message,详见NDEF技术规范《NFCForum-TS-NDEF_1.0》。 | + +**示例:** ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'ndef' correctly. -let ndefRecords = ndef.getNdefRecords(); -console.log("ndef ndefRecords number: " + ndefRecords.length); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'ndefTag' correctly. +let rawData = [0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]; // change the raw data bytes to be correct. +let ndefMessage; +try { + ndefMessage = ndefTag.createNdefMessage(rawData); + console.log("ndef createNdefMessage, ndefMessage: " + ndefMessage); +} catch (busiError) { + console.log("ndef createNdefMessage busiError: " + busiError); +} ``` ### NdefTag.createNdefMessage9+ createNdefMessage(ndefRecords: NdefRecord[]): [NdefMessage](#ndefmessage9) -使用记录列表创建NDEF消息。 - -**需要权限**:ohos.permission.NFC_TAG +使用NDEF Records列表,创建NDEF Message。 **系统能力**:SystemCapability.Communication.NFC @@ -456,17 +678,15 @@ createNdefMessage(ndefRecords: NdefRecord[]): [NdefMessage](#ndefmessage9) | ndefRecords | [NdefRecord](js-apis-nfcTag.md#ndefrecord9)[] | 是 | NDEF标签的Record列表,详见NDEF技术规范《NFCForum-TS-NDEF_1.0》。 | **返回值:** - | **类型** | **说明** | | ------------------ | --------------------------| | [NdefMessage](#ndefmessage9) | NDEF标签的Message,详见NDEF技术规范《NFCForum-TS-NDEF_1.0》。| **示例:** - ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'ndef' correctly. +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'ndefTag' correctly. let ndefRecords = [ // record format: tnf, rtdType, id, payload // 1st record: @@ -477,33 +697,34 @@ let ndefRecords = [ // other record if has one ... ]; -let ndefMessage = ndef.createNdefMessage(ndefRecords); -console.log("ndef ndefMessage: " + ndefMessage); +let ndefMessage; +try { + ndefMessage = ndefTag.createNdefMessage(ndefRecords); + console.log("ndef createNdefMessage ndefMessage: " + ndefMessage); +} catch (busiError) { + console.log("ndef createNdefMessage busiError: " + busiError); +} ``` ### NdefTag.getNdefTagType9+ getNdefTagType(): NfcForumType -获取Ndef标签的类型。 - -**需要权限**:ohos.permission.NFC_TAG +获取NDEF标签的类型。 **系统能力**:SystemCapability.Communication.NFC **返回值:** - | **类型** | **说明** | | ------------------ | --------------------------| | [NfcForumType](js-apis-nfcTag.md#nfcforumtype9) | NDEF标签类型,包括NFC FORUM TYPE 1/2/3/4等。| **示例:** - ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'ndef' correctly. -let ndefTagType = ndef.getNdefTagType(); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'ndefTag' correctly. +let ndefTagType = ndefTag.getNdefTagType(); console.log("ndef ndefTagType: " + ndefTagType); ``` @@ -513,217 +734,237 @@ getNdefMessage(): NdefMessage 获取发现NDEF标签时,从标签读取的Message。 -**需要权限**:ohos.permission.NFC_TAG - **系统能力**:SystemCapability.Communication.NFC **返回值:** - | **类型** | **说明** | | ------------------ | --------------------------| | [NdefMessage](#ndefmessage9) | NDEF标签的Message,详见NDEF技术规范《NFCForum-TS-NDEF_1.0》。| **示例:** - ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'ndef' correctly. -let ndefMessage = ndef.getNdefMessage(); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'ndefTag' correctly. +let ndefMessage = ndefTag.getNdefMessage(); console.log("ndef ndefMessage: " + ndefMessage); ``` ### NdefTag.isNdefWritable9+ -isNdefWritable(): Promise<boolean> - -检查NDEF标签是否可写,使用promise方式作为异步方法。 +isNdefWritable(): boolean; -**需要权限**:ohos.permission.NFC_TAG +检查NDEF标签是否可写。在调用写数据接口前,需要先判断是否支持写操作。 **系统能力**:SystemCapability.Communication.NFC **返回值:** - | **类型** | **说明** | | ------------------ | --------------------------| -| Promise<boolean> | 检查结果,true: 可写, false: 不可写。| +| boolean | 检查结果,true: 可写, false: 不可写。| **示例:** - ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'ndef' correctly. -ndef.isNdefWritable() - .then((data) => { - console.log("ndef isNdefWritable data: " + data); - }).catch((err)=> { - console.log("ndef isNdefWritable err: " + err); - }); -``` - -### NdefTag.isNdefWritable9+ - -isNdefWritable(callback: AsyncCallback<boolean>): void; - -检查ndef标签是否可写,使用callback方式作为异步方法。 - -**需要权限**:ohos.permission.NFC_TAG - -**系统能力**:SystemCapability.Communication.NFC - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ----------------------- | ---- | -------------------------------------- | -| callback | AsyncCallback\ | 是 | 回调函数,NDEF标签可写,返回true。 | - -**示例:** - -```js -import tag from '@ohos.nfc.tag'; - -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'ndef' correctly. -ndef.isNdefWritable((err, data)=> { - if (err) { - console.log("ndef isNdefWritable err: " + err); - } else { - console.log("ndef isNdefWritable data: " + data); - } -}); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'ndefTag' correctly. +var isWritable = ndefTag.isNdefWritable(); +console.log("ndef isNdefWritable: " + isWritable); ``` ### NdefTag.readNdef9+ readNdef(): Promise\ -读取标签上的ndef消息,使用promise方式作为异步方法。 +读取标签上的NDEF消息,使用Promise方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **返回值:** - | **类型** | **说明** | | ------------------ | --------------------------| -| Promise\<[NdefMessage](#ndefmessage9)> | 以Promise形式返回从NDEF标签中读取到的Message信息。| +| Promise\<[NdefMessage](#ndefmessage9)> | 以Promise形式返回从NDEF标签中读取到的Message数据对象。| -**示例:** +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | +**示例:** ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'ndef' correctly. -ndef.readNdef() - .then((data) => { - console.log("ndef readNdef data: " + data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'ndefTag' correctly. + +// connect the tag at first if not connected. +if (!ndefTag.isTagConnected()) { + if (!ndefTag.connectTag()) { + console.log("ndefTag connectTag failed."); + return; + } +} + +try { + ndefTag.readNdef().then((ndefmessage) => { + console.log("ndef readNdef Promise ndefmessage: " + ndefmessage); }).catch((err)=> { - console.log("ndef readNdef err: " + err); + console.log("ndef readNdef Promise err: " + err); }); +} catch (busiError) { + console.log("ndef readNdef Promise catched busiError: " + busiError); +} ``` ### NdefTag.readNdef9+ readNdef(callback: AsyncCallback\<[NdefMessage](#ndefmessage9)>): void -读取标签上的ndef消息,使用callback方式作为异步方法。 +读取标签上的NDEF消息,使用AsyncCallback方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | -| callback | AsyncCallback\<[NdefMessage](#ndefmessage9)> | 是 | 回调函数。| +| callback | AsyncCallback\<[NdefMessage](#ndefmessage9)> | 是 | 回调函数,返回从NDEF标签中读取到的Message信息。| -**示例:** +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | +**示例:** ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'ndef' correctly. -ndef.readNdef((err, data)=> { - if (err) { - console.log("ndef readNdef err: " + err); - } else { - console.log("ndef readNdef data: " + data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'ndefTag' correctly. + +// connect the tag at first if not connected. +if (!ndefTag.isTagConnected()) { + if (!ndefTag.connectTag()) { + console.log("ndefTag connectTag failed."); + return; } -}); +} + +try { + ndefTag.readNdef((err, ndefmessage)=> { + if (err) { + console.log("ndef readNdef AsyncCallback err: " + err); + } else { + console.log("ndef readNdef AsyncCallback ndefmessage: " + ndefmessage); + } + }); +} catch (busiError) { + console.log("ndef readNdef AsyncCallback catched busiError: " + busiError); +} ``` ### NdefTag.writeNdef9+ -writeNdef(msg: NdefMessage): Promise\; +writeNdef(msg: NdefMessage): Promise\; -将ndef消息写入标签,使用promise方式作为异步方法。 +将NDEF Messsage数据对象写入标签,使用Promise方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | -| msg | NdefMessage | 是 | Ndef消息。| - -**返回值:** +| msg | NdefMessage | 是 | NDEF Message数据对象。| -| **类型** | **说明** | -| ------------------ | --------------------------| -| Promise\ | 以Promise形式返回,写入执行后的错误代码。如果返回0,则表示成功。 | +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **示例:** - ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'ndef' correctly. -let ndefMessage = ndef.createNdefMessage([0x01, 0x02, ...]); // change the raw data to be correct. +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'ndefTag' correctly. +// ndefMessage created from raw data, such as: +let ndefMessage = ndefTag.createNdefMessage([0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]); // change the raw data to be correct. +// or ndefMessage created from ndefTag.createNdefMessage(ndefRecords: NdefRecord[]) -ndef.writeNdef(ndefMessage) - .then((data) => { - console.log("ndef writeNdef data: " + data); +// connect the tag at first if not connected. +if (!ndefTag.isTagConnected()) { + if (!ndefTag.connectTag()) { + console.log("ndefTag connectTag failed."); + return; + } +} + +try { + ndefTag.writeNdef(ndefMessage).then(() => { + console.log("ndef writeNdef Promise success."); }).catch((err)=> { console.log("ndef writeNdef err: " + err); }); +} catch (busiError) { + console.log("ndef writeNdef Promise catch busiError: " + busiError); +} ``` ### NdefTag.writeNdef9+ -writeNdef(msg: NdefMessage, callback: AsyncCallback\): void +writeNdef(msg: NdefMessage, callback: AsyncCallback\): void -将ndef消息写入此标签,使用callback方式作为异步方法。 +将NDEF Message数据对象写入此标签,使用AsyncCallback方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | -| msg | NdefMessage | 是 | Ndef消息 | -| callback | AsyncCallback\ | 是 | 回调函数。 | +| msg | NdefMessage | 是 | NDEF Message数据对象。 | +| callback | AsyncCallback\ | 是 | 回调函数。 | -**示例:** +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | +**示例:** ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'ndef' correctly. -let ndefMessage = ndef.createNdefMessage([0x01, 0x02, ...]); // change the raw data to be correct. -ndef.writeNdef(ndefMessage, (err, data)=> { - if (err) { - console.log("ndef writeNdef err: " + err); - } else { - console.log("ndef writeNdef data: " + data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'ndefTag' correctly. +// ndefMessage created from raw data, such as: +let ndefMessage = ndefTag.createNdefMessage([0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]); // change the raw data to be correct. +// or ndefMessage created from ndefTag.createNdefMessage(ndefRecords: NdefRecord[]) + +// connect the tag at first if not connected. +if (!ndefTag.isTagConnected()) { + if (!ndefTag.connectTag()) { + console.log("ndefTag connectTag failed."); + return; } -}); +} + +try { + ndefTag.writeNdef(ndefMessage, (err)=> { + if (err) { + console.log("ndef writeNdef AsyncCallback err: " + err); + } else { + console.log("ndef writeNdef AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("ndef writeNdef AsyncCallback catch busiError: " + busiError); +} ``` ### NdefTag.canSetReadOnly9+ @@ -737,659 +978,874 @@ canSetReadOnly(): boolean **系统能力**:SystemCapability.Communication.NFC **返回值:** - | **类型** | **说明** | | ------------------ | --------------------------| | boolean| true: NDEF标签可设置为只读, false: NDEF标签不可设置为只读。 | -**示例:** +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | +**示例:** ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'ndef' correctly. -var canSetReadOnly = ndef.canSetReadOnly(); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'ndefTag' correctly. +var canSetReadOnly = ndefTag.canSetReadOnly(); console.log("ndef canSetReadOnly: " + canSetReadOnly); ``` ### NdefTag.setReadOnly9+ -setReadOnly(): Promise\ +setReadOnly(): Promise\ -将Ndef标签设置为只读,使用promise方式作为异步方法。 +将NDEF标签设置为只读,使用Promise方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC -**返回值:** - -| **类型** | **说明** | -| ------------------ | --------------------------| -| Promise<number> | 0: 设置成功, 其它: 错误编码。 | +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **示例:** - ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'ndef' correctly. -ndef.setReadOnly() - .then((data) => { - console.log("ndef setReadOnly data: " + data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'ndefTag' correctly. + +// connect the tag at first if not connected. +if (!ndefTag.isTagConnected()) { + if (!ndefTag.connectTag()) { + console.log("ndefTag connectTag failed."); + return; + } +} + +try { + ndefTag.setReadOnly().then(() => { + console.log("ndef setReadOnly Promise success."); }).catch((err)=> { - console.log("ndef setReadOnly err: " + err); + console.log("ndef setReadOnly Promise err: " + err); }); +} catch (busiError) { + console.log("ndef setReadOnly Promise catch busiError: " + busiError); +} ``` ### NdefTag.setReadOnly9+ -setReadOnly(callback: AsyncCallback\): void +setReadOnly(callback: AsyncCallback\): void -将Ndef标签设置为只读,使用callback方式作为异步方法。 +将NDEF标签设置为只读,使用AsyncCallback方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | -| callback | AsyncCallback\ | 是 | 回调函数。 | +| callback | AsyncCallback\ | 是 | 回调函数。 | -**示例:** +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | +**示例:** ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'ndef' correctly. -ndef.setReadOnly((err, data)=> { - if (err) { - console.log("ndef setReadOnly err: " + err); - } else { - console.log("ndef setReadOnly data: " + data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'ndefTag' correctly. + +// connect the tag at first if not connected. +if (!ndefTag.isTagConnected()) { + if (!ndefTag.connectTag()) { + console.log("ndefTag connectTag failed."); + return; } -}); +} + +try { + ndefTag.setReadOnly((err)=> { + if (err) { + console.log("ndef setReadOnly AsyncCallback err: " + err); + } else { + console.log("ndef setReadOnly AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("ndef setReadOnly AsyncCallback catch busiError: " + busiError); +} ``` ### NdefTag.getNdefTagTypeString9+ getNdefTagTypeString(type: [NfcForumType](js-apis-nfcTag.md#nfcforumtype9)): string -将Nfc论坛类型转换为Nfc论坛中定义的字节数组。 - -**需要权限**:ohos.permission.NFC_TAG +将NFC论坛类型,转换为NFC论坛中定义的字符串描述。 **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | | type | [NfcForumType](js-apis-nfcTag.md#nfcforumtype9) | 是 | NDEF标签类型,包括NFC FORUM TYPE 1/2/3/4等。 | **返回值:** - | **类型** | **说明** | | ------------------ | --------------------------| | string | NFC论坛类型的字符串描述。| **示例:** - ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'ndef' correctly. -let ndefTypeString = ndef.getNdefTagTypeString(tag.NFC_FORUM_TYPE_1); -console.log("ndef ndefTypeString: " + ndefTypeString); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'ndefTag' correctly. + +try { + let ndefTypeString = ndefTag.getNdefTagTypeString(tag.NFC_FORUM_TYPE_1); + console.log("ndef ndefTypeString: " + ndefTypeString); +} catch (busiError) { + console.log("ndef getNdefTagTypeString catch busiError: " + busiError); +} ``` ## MifareClassicTag9+ -MifareClassicTag提供对MIFARE经典属性和I/O操作的访问,继承自TagSession。 +MifareClassicTag提供对MIFARE Classic属性和I/O操作的访问,继承自TagSession。 -TagSession是所有Nfc tag 技术类型的基类, 提供建立连接和发送数据等共同接口。具体请参见[TagSession](js-apis-tagSession.md)。 +TagSession是所有NFC Tag技术类型的基类, 提供建立连接和发送数据等共同接口。具体请参见[TagSession](js-apis-tagSession.md)。 以下是MifareClassicTag的独有接口。 ### MifareClassicTag.authenticateSector9+ -authenticateSector(sectorIndex: number, key: number[], isKeyA: boolean): Promise\ +authenticateSector(sectorIndex: number, key: number[], isKeyA: boolean): Promise\ -使用密钥对扇区进行身份验证,只有身份验证成功的扇区可以进行操作。使用promise方式作为异步方法。 +使用密钥对扇区进行身份验证,只有身份验证成功的扇区可以进行操作。使用Promise方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | -| sectorIndex | number | 是 | 待验证的扇区索引 | -| key | number[]| 是 | 用于身份验证的密钥(6字节) | +| sectorIndex | number | 是 | 待验证的扇区索引,从0开始。 | +| key | number[]| 是 | 用于扇区验证的密钥(6字节)。 | | isKeyA | boolean | 是 | isKeyA标志。true 表示KeyA,false 表示KeyB。| -**返回值:** - -| **类型** | **说明** | -| ------------------ | --------------------------| -| Promise\ | 身份验证结果,成功返回true,失败返回false。 | +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **示例:** - ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareClassic' correctly. -let sectorIndex = 1; // change it to be correct index. -let key = [0x04, 0x05, ....]; // change it to be correct key. -mifareClassic.authenticateSector(sectorIndex, key, true); - .then((data) => { - console.log("mifareClassic authenticateSector data: " + data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareClassic' correctly. + +// connect the tag at first if not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; + } +} + +try { + let sectorIndex = 1; // change it to be correct index. + let key = [0x01, 0x02, 0x03, 0x04, 0x05, 0x06] // MUST be 6 bytes, change it to be correct key. + mifareClassic.authenticateSector(sectorIndex, key, true).then(() => { + console.log("mifareClassic authenticateSector Promise success."); }).catch((err)=> { - console.log("mifareClassic authenticateSector err: " + err); + console.log("mifareClassic authenticateSector Promise err: " + err); }); +} catch (busiError) { + console.log("mifareClassic authenticateSector Promise catch busiError: " + busiError); +} ``` ### MifareClassicTag.authenticateSector9+ -authenticateSector(sectorIndex: number, key: number[], isKeyA: boolean, callback: AsyncCallback\): void +authenticateSector(sectorIndex: number, key: number[], isKeyA: boolean, callback: AsyncCallback\): void -使用密钥对扇区进行身份验证,只有身份验证成功的扇区可以进行操作。使用callback方式作为异步方法。 +使用密钥对扇区进行身份验证,只有身份验证成功的扇区可以进行操作。使用AsyncCallback方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | -| sectorIndex | number | 是 | 待验证的扇区索引。 | -| key | number[]| 是 | 用于身份验证的密钥(6字节)。 | +| sectorIndex | number | 是 | 待验证的扇区索引,从0开始。 | +| key | number[]| 是 | 用于扇区验证的密钥(6字节)。 | | isKeyA | boolean | 是 | isKeyA标志。true 表示KeyA,false 表示KeyB。| -| callback | AsyncCallback\ | 是 | 回调函数。| +| callback | AsyncCallback\ | 是 | 回调函数。| -**示例:** +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | +**示例:** ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareClassic' correctly. -let sectorIndex = 1; // change it to be correct index. -let key = [0x04, 0x05, ....]; // change it to be correct key. -mifareClassic.authenticateSector(sectorIndex, key, true, (err, data)=> { - if (err) { - console.log("mifareClassic authenticateSector err: " + err); - } else { - console.log("mifareClassic authenticateSector data: " + data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareClassic' correctly. + +// connect the tag at first if not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let sectorIndex = 1; // change it to be correct index. + let key = [0x01, 0x02, 0x03, 0x04, 0x05, 0x06] // MUST be 6 bytes, change it to be correct key. + mifareClassic.authenticateSector(sectorIndex, key, true, (err)=> { + if (err) { + console.log("mifareClassic authenticateSector AsyncCallback err: " + err); + } else { + console.log("mifareClassic authenticateSector AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("mifareClassic authenticateSector AsyncCallback catch busiError: " + busiError); +} ``` ### MifareClassicTag.readSingleBlock9+ readSingleBlock(blockIndex: number): Promise\ -读取标签中一个块存储的内容,一个块大小为16字节。使用promise方式作为异步方法。 +读取标签中一个块存储的内容,一个块大小为16字节。使用Promise方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | 是 | 要读取的块索引。 | +| blockIndex | number | 是 | 要读取的块索引,从0开始。 | **返回值:** - | **类型** | **说明** | | ------------------ | --------------------------| | Promise\ | 读取的块数据。 | -**示例:** +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | +**示例:** ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -mifareClassic.readSingleBlock(blockIndex, (err, data)=> { - if (err) { - console.log("mifareClassic readSingleBlock err: " + err); - } else { - console.log("mifareClassic readSingleBlock data: " + data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareClassic' correctly. + +// connect the tag at first if not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // change it to be correct index. + mifareClassic.readSingleBlock(blockIndex).then((data) => { + console.log("mifareClassic readSingleBlock Promise data: " + data); + }).catch((err)=> { + console.log("mifareClassic readSingleBlock Promise err: " + err); + }); +} catch (busiError) { + console.log("mifareClassic readSingleBlock Promise catch busiError: " + busiError); +} ``` ### MifareClassicTag.readSingleBlock9+ readSingleBlock(blockIndex: number, callback: AsyncCallback\): void -读取标签中一个块存储的内容,一个块大小为16字节。使用callback方式作为异步方法。 +读取标签中一个块存储的内容,一个块大小为16字节。使用AsyncCallback方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | 是 | 要读取的块索引 | -| callback | AsyncCallback\ | 是 | 回调函数。 | +| blockIndex | number | 是 | 要读取的块索引,从0开始。 | +| callback | AsyncCallback\ | 是 | 回调函数,返回读取到的数据。 | -**示例:** +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | +**示例:** ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -mifareClassic.readSingleBlock(blockIndex, (err, data)=> { - if (err) { - console.log("mifareClassic readSingleBlock err: " + err); - } else { - console.log("mifareClassic readSingleBlock data: " + data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareClassic' correctly. + +// connect the tag at first if not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // change it to be correct index. + mifareClassic.readSingleBlock(blockIndex, (err, data)=> { + if (err) { + console.log("mifareClassic readSingleBlock AsyncCallback err: " + err); + } else { + console.log("mifareClassic readSingleBlock AsyncCallback data: " + data); + } + }); +} catch (busiError) { + console.log("mifareClassic readSingleBlock AsyncCallback catch busiError: " + busiError); +} ``` ### MifareClassicTag.writeSingleBlock9+ -writeSingleBlock(blockIndex: number, data: number[]): Promise\ +writeSingleBlock(blockIndex: number, data: number[]): Promise\ -向标签中一个块存储写入内容,一个块大小为16字节。使用promise方式作为异步方法。 +向标签中一个块存储写入内容,一个块大小为16字节。使用Promise方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | 是 | 要写入的块索引。 | -| data | number[] | 是 | 要写入的数据。 | +| blockIndex | number | 是 | 要写入的块索引,从0开始。 | +| data | number[] | 是 | 要写入的数据,大小必须是16个字节。 | -**返回值:** - -| **类型** | **说明** | -| ------------------ | --------------------------| -| Promise\ | 执行写入操作返回的错误代码。如果返回0,则表示成功。 | +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **示例:** - ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -let rawData = [0x0a, 0x14, ...]; // change it to be correct data. -mifareClassic.writeSingleBlock(blockIndex, rawData, (err, data)=> { - if (err) { - console.log("mifareClassic writeSingleBlock err: " + err); - } else { - console.log("mifareClassic writeSingleBlock data: " + data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareClassic' correctly. + +// connect the tag at first if not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // change it to be correct index. + let rawData = [0x01, 0x02, ..., 0x0F, 0x10]; // MUST be 16 bytes, change it to be correct data. + mifareClassic.writeSingleBlock(blockIndex, rawData).then(() => { + console.log("mifareClassic writeSingleBlock Promise success."); + }).catch((err)=> { + console.log("mifareClassic writeSingleBlock Promise err: " + err); + }); +} catch (busiError) { + console.log("mifareClassic writeSingleBlock Promise catch busiError: " + busiError); +} ``` ### MifareClassicTag.writeSingleBlock9+ -writeSingleBlock(blockIndex: number, data: number[], callback: AsyncCallback\): void +writeSingleBlock(blockIndex: number, data: number[], callback: AsyncCallback\): void -向标签中一个块存储写入内容,一个块大小为16字节。使用callback方式作为异步方法。 +向标签中一个块存储写入内容,一个块大小为16字节。使用AsyncCallback方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | 是 | 要写入的块索引 | -| data | number[] | 是 | 要写入的数据 | -| callback | AsyncCallback\ | 是 | 回调函数。 | +| blockIndex | number | 是 | 要写入的块索引,从0开始。 | +| data | number[] | 是 | 要写入的数据,大小必须是16个字节。 | +| callback | AsyncCallback\ | 是 | 回调函数。 | -**示例:** +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | +**示例:** ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -let rawData = [0x0a, 0x14, ...]; // change it to be correct data. -mifareClassic.writeSingleBlock(blockIndex, rawData, (err, data)=> { - if (err) { - console.log("mifareClassic writeSingleBlock err: " + err); - } else { - console.log("mifareClassic writeSingleBlock data: " + data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareClassic' correctly. + +// connect the tag at first if not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // change it to be correct index. + let rawData = [0x01, 0x02, ..., 0x15, 0x16]; // MUST be 16 bytes, change it to be correct data. + mifareClassic.writeSingleBlock(blockIndex, rawData, (err)=> { + if (err) { + console.log("mifareClassic writeSingleBlock AsyncCallback err: " + err); + } else { + console.log("mifareClassic writeSingleBlock AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("mifareClassic writeSingleBlock AsyncCallback catch busiError: " + busiError); +} ``` ### MifareClassicTag.incrementBlock9+ -incrementBlock(blockIndex: number, value: number): Promise\ +incrementBlock(blockIndex: number, value: number): Promise\ -增加一块带值的区域块。使用promise方式作为异步方法。 +对指定块的内容,增加指定的数值。使用Promise方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | 是 | 要增加的块索引。 | -| value | number | 是 | 要增加的块数据,非负值。 | +| blockIndex | number | 是 | 要指定增加的块索引,从0开始。 | +| value | number | 是 | 要指定增加的数据,非负数。 | -**返回值:** - -| **类型** | **说明** | -| ------------------ | --------------------------| -| Promise\ | 执行新增操作返回的错误代码。如果返回0,则表示成功。 | +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **示例:** - ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -let value = 0x20; // change it to be correct data. -mifareClassic.incrementBlock(blockIndex, value, (err, data)=> { - if (err) { - console.log("mifareClassic incrementBlock err: " + err); - } else { - console.log("mifareClassic incrementBlock data: " + data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareClassic' correctly. + +// connect the tag at first if not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // change it to be correct index. + let value = 0x20; // change it to be correct data. + mifareClassic.incrementBlock(blockIndex, value).then(() => { + console.log("mifareClassic incrementBlock Promise success."); + }).catch((err)=> { + console.log("mifareClassic incrementBlock Promise err: " + err); + }); +} catch (busiError) { + console.log("mifareClassic incrementBlock Promise catch busiError: " + busiError); +} ``` ### MifareClassicTag.incrementBlock9+ -incrementBlock(blockIndex: number, value: number, callback: AsyncCallback\): void +incrementBlock(blockIndex: number, value: number, callback: AsyncCallback\): void -增加一块带值的区域块。使用callback方式作为异步方法。 +对指定块的内容,增加指定的数值。使用AsyncCallback方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | 是 | 要增加的块索引。 | -| value | number | 是 | 要增加的块数据,非负值。 | -| callback | AsyncCallback\ | 是 | 回调函数。 | +| blockIndex | number | 是 | 要被运算的块索引,从0开始。 | +| value | number | 是 | 要增加的数值,非负数。 | +| callback | AsyncCallback\ | 是 | 回调函数。 | -**示例:** +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | +**示例:** ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -let value = 0x20; // change it to be correct data. -mifareClassic.incrementBlock(blockIndex, value, (err, data)=> { - if (err) { - console.log("mifareClassic incrementBlock err: " + err); - } else { - console.log("mifareClassic incrementBlock data: " + data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareClassic' correctly. + +// connect the tag at first if not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // change it to be correct index. + let value = 0x20; // change it to be correct data. + mifareClassic.incrementBlock(blockIndex, value, (err)=> { + if (err) { + console.log("mifareClassic incrementBlock AsyncCallback err: " + err); + } else { + console.log("mifareClassic incrementBlock AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("mifareClassic incrementBlock AsyncCallback catch busiError: " + busiError); +} ``` ### MifareClassicTag.decrementBlock9+ -decrementBlock(blockIndex: number, value: number): Promise\ +decrementBlock(blockIndex: number, value: number): Promise\ -递减一块带值的区域块。使用promise方式作为异步方法。 +对指定块的内容,减少指定的数值。使用Promise方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | 是 | 要递减的块索引。 | -| value | number | 是 | 要递减的块数据,非负值。 | +| blockIndex | number | 是 | 要被运算的块索引,从0开始。 | +| value | number | 是 | 要减少的数值,非负数。 | -**返回值:** - -| **类型** | **说明** | -| ------------------ | --------------------------| -| Promise\ | 执行递减操作返回的错误代码。如果返回0,则表示成功。 | +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **示例:** - ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -let value = 0x20; // change it to be correct data. -mifareClassic.decrementBlock(blockIndex, value, (err, data)=> { - if (err) { - console.log("mifareClassic decrementBlock err: " + err); - } else { - console.log("mifareClassic decrementBlock data: " + data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareClassic' correctly. + +// connect the tag at first if not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // change it to be correct index. + let value = 0x20; // change it to be correct data. + mifareClassic.decrementBlock(blockIndex, value).then(() => { + console.log("mifareClassic decrementBlock Promise success."); + }).catch((err)=> { + console.log("mifareClassic decrementBlock Promise err: " + err); + }); +} catch (busiError) { + console.log("mifareClassic decrementBlock Promise catch busiError: " + busiError); +} ``` ### MifareClassicTag.decrementBlock9+ -decrementBlock(blockIndex: number, value: number, callback: AsyncCallback\): void +decrementBlock(blockIndex: number, value: number, callback: AsyncCallback\): void -递减一块带值的区域块。使用callback方式作为异步方法。 +对指定块的内容,减少指定的数值。使用AsyncCallback方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | 是 | 要递减的块索引。 | -| value | number | 是 | 要递减的块数据,非负值。 | -| callback | AsyncCallback\ | 是 | 回调函数。 | +| blockIndex | number | 是 | 要被运算的块索引,从0开始。 | +| value | number | 是 | 要减少的数值,非负数。 | +| callback | AsyncCallback\ | 是 | 回调函数。 | -**示例:** +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | +**示例:** ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -let value = 0x20; // change it to be correct data. -mifareClassic.decrementBlock(blockIndex, value, (err, data)=> { - if (err) { - console.log("mifareClassic decrementBlock err: " + err); - } else { - console.log("mifareClassic decrementBlock data: " + data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareClassic' correctly. + +// connect the tag at first if not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // change it to be correct index. + let value = 0x20; // change it to be correct data. + mifareClassic.decrementBlock(blockIndex, value, (err)=> { + if (err) { + console.log("mifareClassic decrementBlock AsyncCallback err: " + err); + } else { + console.log("mifareClassic decrementBlock AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("mifareClassic decrementBlock AsyncCallback catch busiError: " + busiError); +} ``` ### MifareClassicTag.transferToBlock9+ -transferToBlock(blockIndex: number): Promise\ +transferToBlock(blockIndex: number): Promise\ -将寄存器的值复制到块。使用promise方式作为异步方法。 +将临时寄存器的值转移到指定的块。使用Promise方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | 是 | 复制的目的块索引。 | +| blockIndex | number | 是 | 被操作的块的索引,从0开始。 | -**返回值:** - -| **类型** | **说明** | -| ------------------ | --------------------------| -| Promise\ | 执行复制操作返回的错误代码。如果返回0,表示成功;否则返回错误码。| +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **示例:** - ```js - import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -mifareClassic.transferToBlock(blockIndex, (err, data)=> { - if (err) { - console.log("mifareClassic transferToBlock err: " + err); - } else { - console.log("mifareClassic transferToBlock data: " + data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareClassic' correctly. + +// connect the tag at first if not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // change it to be correct index. + mifareClassic.transferToBlock(blockIndex).then(() => { + console.log("mifareClassic transferToBlock Promise success."); + }).catch((err)=> { + console.log("mifareClassic transferToBlock Promise err: " + err); + }); +} catch (busiError) { + console.log("mifareClassic transferToBlock Promise catch busiError: " + busiError); +} ``` ### MifareClassicTag.transferToBlock9+ -transferToBlock(blockIndex: number, callback: AsyncCallback\): void +transferToBlock(blockIndex: number, callback: AsyncCallback\): void -将寄存器的值复制到块。使用callback方式作为异步方法。 +将临时寄存器的值转移到指定的块。使用AsyncCallback方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | 是 | 复制的目的块索引 | -| callback | AsyncCallback\ | 是 | 回调函数。 | +| blockIndex | number | 是 | 被操作的块的索引,从0开始。 | +| callback | AsyncCallback\ | 是 | 回调函数。 | -**示例:** +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | +**示例:** ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -mifareClassic.transferToBlock(blockIndex, (err, data)=> { - if (err) { - console.log("mifareClassic transferToBlock err: " + err); - } else { - console.log("mifareClassic transferToBlock data: " + data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareClassic' correctly. + +// connect the tag at first if not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // change it to be correct index. + mifareClassic.transferToBlock(blockIndex, (err)=> { + if (err) { + console.log("mifareClassic transferToBlock AsyncCallback err: " + err); + } else { + console.log("mifareClassic transferToBlock AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("mifareClassic transferToBlock AsyncCallback catch busiError: " + busiError); +} ``` ### MifareClassicTag.restoreFromBlock9+ -restoreFromBlock(blockIndex: number): Promise\ +restoreFromBlock(blockIndex: number): Promise\ -将块的值复制到寄存器。使用promise方式作为异步方法。 +将指定块的值复制到临时寄存器。使用Promise方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | 是 | 复制的源块索引。| - -**返回值:** +| blockIndex | number | 是 | 被操作的块的索引,从0开始。| -| **类型** | **说明** | -| ------------------ | --------------------------| -| Promise\ | 执行复制操作返回的错误代码。如果返回0,表示成功;否则返回错误码。| +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **示例:** - ```js - import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -mifareClassic.restoreFromBlock(blockIndex) - .then((data) => { - console.log("mifareClassic restoreFromBlock data: " + data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareClassic' correctly. + +// connect the tag at first if not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; + } +} + +try { + let blockIndex = 1; // change it to be correct index. + mifareClassic.restoreFromBlock(blockIndex).then(() => { + console.log("mifareClassic restoreFromBlock Promise success."); }).catch((err)=> { - console.log("mifareClassic isExtendrestoreFromBlockedApduSupported err: " + err); + console.log("mifareClassic restoreFromBlock Promise err: " + err); }); +} catch (busiError) { + console.log("mifareClassic restoreFromBlock Promise catch busiError: " + busiError); +} ``` ### MifareClassicTag.restoreFromBlock9+ -restoreFromBlock(blockIndex: number, callback: AsyncCallback\): void +restoreFromBlock(blockIndex: number, callback: AsyncCallback\): void -将块的值复制到寄存器。使用callback方式作为异步方法。 +将指定块的值复制到临时寄存器。使用AsyncCallback方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | 是 | 复制的源块索引 | -| callback | AsyncCallback\ | 是 | 回调函数。| +| blockIndex | number | 是 | 被操作的块的索引,从0开始。 | +| callback | AsyncCallback\ | 是 | 回调函数。| -**示例:** +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | +**示例:** ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -mifareClassic.restoreFromBlock(blockIndex, (err, data)=> { - if (err) { - console.log("mifareClassic restoreFromBlock err: " + err); - } else { - console.log("mifareClassic restoreFromBlock data: " + data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareClassic' correctly. + +// connect the tag at first if not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // change it to be correct index. + mifareClassic.restoreFromBlock(blockIndex, (err)=> { + if (err) { + console.log("mifareClassic restoreFromBlock AsyncCallback err: " + err); + } else { + console.log("mifareClassic restoreFromBlock AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("mifareClassic restoreFromBlock AsyncCallback catch busiError: " + busiError); +} ``` ### MifareClassicTag.getSectorCount9+ getSectorCount(): number -获取mifare classic标签中的扇区数。 - -**需要权限**:ohos.permission.NFC_TAG +获取MIFARE Classic标签中的扇区数。 **系统能力**:SystemCapability.Communication.NFC **返回值:** - | **类型** | **说明** | | ------------------ | --------------------------| -| number | 扇区数量。| +| number | 标签中的扇区数量。| **示例:** - ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareClassic' correctly. +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareClassic' correctly. let sectorCount = mifareClassic.getSectorCount(); console.log("mifareClassic sectorCount: " + sectorCount); ``` @@ -1398,56 +1854,53 @@ console.log("mifareClassic sectorCount: " + sectorCount); getBlockCountInSector(sectorIndex: number): number -获取扇区中的块数。 - -**需要权限**:ohos.permission.NFC_TAG +获取指定扇区中的块数。 **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | -| sectorIndex | number | 是 | 扇区序号。| +| sectorIndex | number | 是 | 扇区序号,从0开始。| **返回值:** - | **类型** | **说明** | | ------------------ | --------------------------| | number | 该扇区内的块数量。| **示例:** - ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareClassic' correctly. -let blockCountInSector = mifareClassic.getBlockCountInSector(); -console.log("mifareClassic blockCountInSector: " + blockCountInSector); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareClassic' correctly. + +try { + let sectorIndex = 1; // change it to be correct index. + let blockCnt = mifareClassic.getBlockCountInSector(sectorIndex); + console.log("mifareClassic blockCnt: " + blockCnt); +} catch (busiError) { + console.log("mifareClassic getBlockCountInSector catch busiError: " + busiError); +} ``` ### MifareClassicTag.getType9+ getType(): [MifareClassicType](js-apis-nfcTag.md#mifareclassictype9) -获取MifareClassic标签的类型。 - -**需要权限**:ohos.permission.NFC_TAG +获取MIFARE Classic标签的类型。 **系统能力**:SystemCapability.Communication.NFC **返回值:** - | **类型** | **说明** | | ------------------ | --------------------------| | [MifareClassicType](js-apis-nfcTag.md#mifareclassictype9) | MifareClassic标签的类型。| **示例:** - ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareClassic' correctly. +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareClassic' correctly. let getType = mifareClassic.getType(); console.log("mifareClassic getType: " + getType); ``` @@ -1456,24 +1909,20 @@ console.log("mifareClassic getType: " + getType); getTagSize(): number -获取标签的大小(字节),具体请参见[MifareClassicSize](js-apis-nfcTag.md#mifareclassicsize9)。 - -**需要权限**:ohos.permission.NFC_TAG +获取标签的存储空间大小,具体请参见[MifareClassicSize](js-apis-nfcTag.md#mifareclassicsize9)。 **系统能力**:SystemCapability.Communication.NFC **返回值:** - | **类型** | **说明** | | ------------------ | --------------------------| | number | 标签的大小,单位为字节,请参见[MifareClassicSize](js-apis-nfcTag.md#mifareclassicsize9)。| **示例:** - ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareClassic' correctly. +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareClassic' correctly. let tagSize = mifareClassic.getTagSize(); console.log("mifareClassic tagSize: " + tagSize); ``` @@ -1482,24 +1931,20 @@ console.log("mifareClassic tagSize: " + tagSize); isEmulatedTag(): boolean -检查标签是否已模拟。 - -**需要权限**:ohos.permission.NFC_TAG +检查标签是不是被模拟的。 **系统能力**:SystemCapability.Communication.NFC **返回值:** - | **类型** | **说明** | | ------------------ | --------------------------| | boolean |检查结果,true: 是;false:否。 | **示例:** - ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareClassic' correctly. +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareClassic' correctly. let isEmulatedTag = mifareClassic.isEmulatedTag(); console.log("mifareClassic isEmulatedTag: " + isEmulatedTag); ``` @@ -1508,73 +1953,75 @@ console.log("mifareClassic isEmulatedTag: " + isEmulatedTag); getBlockIndex(sectorIndex: number): number -获取特定扇区的第一个块。 - -**需要权限**:ohos.permission.NFC_TAG +获取特定扇区的第一个块的序号。 **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | -| sectorIndex | number | 是 | 扇区序号。 | +| sectorIndex | number | 是 | 扇区序号,从0开始。 | **返回值:** - | **类型** | **说明** | | ------------------ | --------------------------| -| number | 该扇区内的第一个块的序列号。 | +| number | 该扇区内的第一个块的序号,从0开始。 | **示例:** - ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareClassic' correctly. -let sectorIndex = 1; // change it to be correct index. -let blockIndex = mifareClassic.getBlockIndex(sectorIndex); -console.log("mifareClassic blockIndex: " + blockIndex); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareClassic' correctly. + +try { + let sectorIndex = 1; // change it to be correct index. + let blockIndex = mifareClassic.getBlockIndex(sectorIndex); + console.log("mifareClassic blockIndex: " + blockIndex); +} catch (busiError) { + console.log("mifareClassic getBlockIndex catch busiError: " + busiError); +} ``` ### MifareClassicTag.getSectorIndex9+ getSectorIndex(blockIndex: number): number -获取扇区索引,该扇区包含特定块。 +获取包含指定块号的扇区序号。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | 是 | 块序号。 | +| blockIndex | number | 是 | 块序号,从0开始。 | **返回值:** - | **类型** | **说明** | | ------------------ | --------------------------| -| number | 扇区序号。 | +| number | 扇区序号,从0开始。 | **示例:** - ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -let sectorIndex = mifareClassic.getSectorIndex(blockIndex); -console.log("mifareClassic sectorIndex: " + sectorIndex); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareClassic' correctly. + +try { + let blockIndex = 1; // change it to be correct index. + let sectorIndex = mifareClassic.getSectorIndex(blockIndex); + console.log("mifareClassic sectorIndex: " + sectorIndex); +} catch (busiError) { + console.log("mifareClassic getSectorIndex catch busiError: " + busiError); +} ``` ## MifareUltralightTag9+ -MifareUltralightTag 提供对MIFARE超轻属性和I/O操作的访问,继承自TagSession。 +MifareUltralightTag 提供对MIFARE Ultralight属性和I/O操作的访问,继承自TagSession。 -TagSession是所有Nfc tag 技术类型的基类, 提供建立连接和发送数据等共同接口。具体请参见[TagSession](js-apis-tagSession.md)。 +TagSession是所有NFC Tag技术类型的基类, 提供建立连接和发送数据等共同接口。具体请参见[TagSession](js-apis-tagSession.md)。 以下是MifareUltralightTag的独有接口。 @@ -1582,7 +2029,7 @@ TagSession是所有Nfc tag 技术类型的基类, 提供建立连接和发送 readMultiplePages(pageIndex: number): Promise\ -阅读4页,共16字节。页面大小为4字节。使用promise方式作为异步方法。 +读取标签的4页数据,共16字节的数据。每个页面数据大小为4字节。使用Promise方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG @@ -1592,298 +2039,383 @@ readMultiplePages(pageIndex: number): Promise\ | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | ------------------------------ | -| pageIndex | number | 是 | 要读取页面的索引。 | +| pageIndex | number | 是 | 要读取页面的索引,从0开始。 | **返回值:** - | **类型** | **说明** | | ------------------ | --------------------------| -| Promise\ | 读取的4页的数据。 | +| Promise\ | 读取的4页的数据,共16字节。 | -**示例:** +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | +**示例:** ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareUltralight' correctly. -let pageIndex = 1; // change it to be correct index. -mifareUltralight.readMultiplePages(pageIndex) - .then((data) => { - console.log("mifareUltralight readMultiplePages data: " + data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareUltralight' correctly. + +// connect the tag at first if not connected. +if (!mifareUltralight.isTagConnected()) { + if (!mifareUltralight.connectTag()) { + console.log("mifareUltralight connectTag failed."); + return; + } +} + +try { + let pageIndex = 1; // change it to be correct index. + mifareUltralight.readMultiplePages(pageIndex).then((data) => { + console.log("mifareUltralight readMultiplePages Promise data = " + data); }).catch((err)=> { - console.log("mifareUltralight readMultiplePages err: " + err); + console.log("mifareUltralight readMultiplePages Promise err: " + err); }); +} catch (busiError) { + console.log("mifareUltralight readMultiplePages Promise catch busiError: " + busiError); +} ``` ### MifareUltralightTag.readMultiplePages9+ readMultiplePages(pageIndex: number, callback: AsyncCallback\): void -阅读4页,共16字节。页面大小为4字节。使用callback方式作为异步方法。 +读取标签的4页数据,共16字节的数据。每个页面数据大小为4字节。使用AsyncCallback方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | -| pageIndex | number | 是 | 要读取页面的索引 | -| callback | AsyncCallback\ | 是 | 回调函数。 | +| pageIndex | number | 是 | 要读取页面的索引,从0开始。 | +| callback | AsyncCallback\ | 是 | 回调函数,返回读取到的数据,共16字节。 | -**示例:** +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | +**示例:** ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareUltralight' correctly. -let pageIndex = 1; // change it to be correct index. -mifareUltralight.readMultiplePages(pageIndex, (err, data)=> { - if (err) { - console.log("mifareUltralight readMultiplePages err: " + err); - } else { - console.log("mifareUltralight readMultiplePages data: " + data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareUltralight' correctly. + +// connect the tag at first if not connected. +if (!mifareUltralight.isTagConnected()) { + if (!mifareUltralight.connectTag()) { + console.log("mifareUltralight connectTag failed."); + return; } -}); +} + +try { + let pageIndex = 1; // change it to be correct index. + mifareUltralight.readMultiplePages(pageIndex, (err, data)=> { + if (err) { + console.log("mifareUltralight readMultiplePages AsyncCallback err: " + err); + } else { + console.log("mifareUltralight readMultiplePages AsyncCallback data: " + data); + } + }); +} catch (busiError) { + console.log("mifareUltralight readMultiplePages AsyncCallback catch busiError: " + busiError); +} ``` -### MifareUltralightTag.writeSinglePages9+ +### MifareUltralightTag.writeSinglePage9+ -writeSinglePages(pageIndex: number, data: number[]): Promise\ +writeSinglePage(pageIndex: number, data: number[]): Promise\ -写入一页数据,页面大小为4字节。使用promise方式作为异步方法。 +写入一页数据,数据大小为4字节。使用Promise方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | -| pageIndex | number | 是 | 要写入页面的索引。 | -| data | number[] | 是 | 要写入页面的数据内容。 | - -**返回值:** +| pageIndex | number | 是 | 要写入页面的索引,从0开始。 | +| data | number[] | 是 | 要写入页面的数据内容,必须是4个字节大小。 | -| **类型** | **说明** | -| ------------------ | --------------------------| -| Promise\ | 执行写入操作返回的错误代码。如果返回0,则表示成功。 | +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **示例:** - ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareUltralight' correctly. -let pageIndex = 1; // change it to be correct index. -let data = [0x01, 0x02, ...]; // change it to be correct raw data. -mifareUltralight.writeSinglePages(pageIndex, data) - .then((data) => { - console.log("mifareUltralight writeSinglePages data: " + data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareUltralight' correctly. + +// connect the tag at first if not connected. +if (!mifareUltralight.isTagConnected()) { + if (!mifareUltralight.connectTag()) { + console.log("mifareUltralight connectTag failed."); + return; + } +} + +try { + let pageIndex = 1; // change it to be correct index. + let rawData = [0x01, 0x02, 0x03, 0x04]; // MUST be 4 bytes, change it to be correct raw data. + mifareUltralight.writeSinglePage(pageIndex, rawData).then(() => { + console.log("mifareUltralight writeSinglePage Promise success."); }).catch((err)=> { - console.log("mifareUltralight writeSinglePages err: " + err); + console.log("mifareUltralight writeSinglePage Promise err: " + err); }); +} catch (busiError) { + console.log("mifareUltralight writeSinglePage Promise catch busiError: " + busiError); +} ``` -### MifareUltralightTag.writeSinglePages9+ +### MifareUltralightTag.writeSinglePage9+ -writeSinglePages(pageIndex: number, data: number[], callback: AsyncCallback\): void +writeSinglePage(pageIndex: number, data: number[], callback: AsyncCallback\): void -写入一页数据,页面大小为4字节。使用callback方式作为异步方法。 +写入一页数据,数据大小为4字节。使用AsyncCallback方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | ------------------------ | -| pageIndex | number | 是 | 要写入页面的索引。 | -| data | number[] | 是 | 要写入页面的数据内容。 | -| callback|AsyncCallback\ |是| 回调函数。 | +| pageIndex | number | 是 | 要写入页面的索引,从0开始。 | +| data | number[] | 是 | 要写入页面的数据内容,必须是4个字节大小。 | +| callback|AsyncCallback\ |是| 回调函数。 | -**示例:** +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | +**示例:** ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareUltralight' correctly. -let pageIndex = 1; // change it to be correct index. -let data = [0x01, 0x02, ...]; // change it to be correct raw data. -mifareUltralight.writeSinglePages(pageIndex, data, (err, data)=> { - if (err) { - console.log("mifareUltralight writeSinglePages err: " + err); - } else { - console.log("mifareUltralight writeSinglePages data: " + data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareUltralight' correctly. + +// connect the tag at first if not connected. +if (!mifareUltralight.isTagConnected()) { + if (!mifareUltralight.connectTag()) { + console.log("mifareUltralight connectTag failed."); + return; } -}); +} + +try { + let pageIndex = 1; // change it to be correct index. + let rawData = [0x01, 0x02, 0x03, 0x04]; // MUST be 4 bytes, change it to be correct raw data. + mifareUltralight.writeSinglePage(pageIndex, rawData, (err)=> { + if (err) { + console.log("mifareUltralight writeSinglePage AsyncCallback err: " + err); + } else { + console.log("mifareUltralight writeSinglePage AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("mifareUltralight writeSinglePage AsyncCallback catch busiError: " + busiError); +} ``` ### MifareUltralightTag.getType9+ getType(): MifareUltralightType -获取MifareUltralight标签的类型,以字节形式返回,具体请参见 [MifareUltralightType](js-apis-nfcTag.md#mifareultralighttype9)。 - -**需要权限**:ohos.permission.NFC_TAG +获取MIFARE Ultralight标签的类型,具体请参见 [MifareUltralightType](js-apis-nfcTag.md#mifareultralighttype9)。 **系统能力**:SystemCapability.Communication.NFC **返回值:** - | **类型** | **说明** | | ------------------ | --------------------------| -| MifareUltralightType | MifareUltralight标签的类型, 具体请参见 [MifareUltralightType](js-apis-nfcTag.md#mifareultralighttype9)。| +| MifareUltralightType | MIFARE Ultralight标签的类型,具体请参见 [MifareUltralightType](js-apis-nfcTag.md#mifareultralighttype9)。| **示例:** - ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'mifareUltralight' correctly. +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'mifareUltralight' correctly. let getType = mifareClassic.getType(); console.log("mifareUltralight getType: " + getType); ``` ## NdefFormatableTag9+ -NdefFormatableTag为NDEF formattable的标签提供格式化操作,继承自TagSession。 +NdefFormatableTag为NDEF Formattable的标签提供格式化操作,继承自TagSession。 -TagSession是所有Nfc tag 技术类型的基类, 提供建立连接和发送数据等共同接口。具体请参见[TagSession](js-apis-tagSession.md)。 +TagSession是所有NFC Tag 技术类型的基类, 提供建立连接和发送数据等共同接口。具体请参见[TagSession](js-apis-tagSession.md)。 以下是NdefFormatableTag的独有接口。 ### NdefFormatableTag.format9+ -format(message: [NdefMessage](#ndefmessage9)): Promise\ +format(message: [NdefMessage](#ndefmessage9)): Promise\ -将标签格式化为NDEF标签,然后将NDEF消息写入NDEF标签。使用promise方式作为异步方法。 +将标签格式化为NDEF标签,将NDEF消息写入NDEF标签。使用Promise方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | -| message | [NdefMessage](#ndefmessage9) | 是 | 格式化成功时要写入的Ndef消息。可以为null,为null时仅格式化标签,不写入内容。 | +| message | [NdefMessage](#ndefmessage9) | 是 | 格式化成功时要写入的NDEF消息。可以为null,为null时仅格式化标签,不写入内容。 | -**返回值:** - -| **类型** | **说明** | -| ------------------ | --------------------------| -| Promise\ | 执行操作后返回的错误代码。如果返回0,则表示成功。 | +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **示例:** ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'ndef' correctly. -let data = [0x01, 0x02, ...]; // change it to be correct raw data. -let ndefmessage = ndef.createNdefMessage(data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'ndefFormatable' correctly. -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'ndefFormatable' correctly. -ndefFormatable.format(ndefmessage, (err, data)=> { - if (err) { - console.log("ndefFormatable format err: " + err); - } else { - console.log("ndefFormatable format data: " + data); +// connect the tag at first if not connected. +if (!ndefFormatable.isTagConnected()) { + if (!ndefFormatable.connectTag()) { + console.log("ndefFormatable connectTag failed."); + return; } -}); +} + +try { + // ndefMessage created from raw data, such as: + let ndefMessage = ndefTag.createNdefMessage([0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]); // change the raw data to be correct. + // or ndefMessage created from ndefTag.createNdefMessage(ndefRecords: NdefRecord[]) + + ndefFormatable.format(ndefMessage).then(() => { + console.log("ndefFormatable format Promise success."); + }).catch((err)=> { + console.log("ndefFormatable format Promise err: " + err); + }); +} catch (busiError) { + console.log("ndefFormatable format Promise catch busiError: " + busiError); +} ``` ### NdefFormatableTag.format9+ -format(message: [NdefMessage](#ndefmessage9), callback: AsyncCallback\): void +format(message: [NdefMessage](#ndefmessage9), callback: AsyncCallback\): void -将标签格式化为NDEF标签,然后将NDEF消息写入NDEF标签。使用callback方式作为异步方法。 +将标签格式化为NDEF标签,然后将NDEF消息写入NDEF标签。使用AsyncCallback方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | | message | [NdefMessage](#ndefmessage9) | 是 | 格式化成功时要写入的Ndef消息。可以为null,为null时仅格式化标签,不写入内容。 | **返回值:** - | **类型** | **说明** | | ------------------ | --------------------------| -| callback: AsyncCallback\ | 回调函数。 | +| callback: AsyncCallback\ | 回调函数。 | **示例:** - ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'ndef' correctly. -let data = [0x01, 0x02, ...]; // change it to be correct raw data. -let ndefmessage = ndef.createNdefMessage(data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'ndefFormatable' correctly. -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'ndefFormatable' correctly. -ndefFormatable.format(ndefmessage, (err, data)=> { - if (err) { - console.log("ndefFormatable format err: " + err); - } else { - console.log("ndefFormatable format data: " + data); +// connect the tag at first if not connected. +if (!ndefFormatable.isTagConnected()) { + if (!ndefFormatable.connectTag()) { + console.log("ndefFormatable connectTag failed."); + return; } -}); +} + +try { + // ndefMessage created from raw data, such as: + let ndefMessage = ndefTag.createNdefMessage([0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]); // change the raw data to be correct. + // or ndefMessage created from ndefTag.createNdefMessage(ndefRecords: NdefRecord[]) + + ndefFormatable.format(ndefMessage, (err)=> { + if (err) { + console.log("ndefFormatable format AsyncCallback err: " + err); + } else { + console.log("ndefFormatable format AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("ndefFormatable format AsyncCallback catch busiError: " + busiError); +} ``` ### NdefFormatableTag.formatReadOnly9+ -formatReadOnly(message: [NdefMessage](#ndefmessage9)): Promise\ +formatReadOnly(message: [NdefMessage](#ndefmessage9)): Promise\ -将标签格式化为NDEF标签,然后将NDEF消息写入NDEF标签,之后将标签设置为只读。使用promise方式作为异步方法。 +将标签格式化为NDEF标签,将NDEF消息写入NDEF标签,之后将标签设置为只读。使用Promise方式作为异步方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC **参数:** - | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | -------------------------------------- | -| message | [NdefMessage](#ndefmessage9) | 是 | 格式化成功时要写入的Ndef消息。可以为null,为null时仅格式化标签,不写入内容。 | - -**返回值:** +| message | [NdefMessage](#ndefmessage9) | 是 | 格式化成功时要写入的NDEF消息。可以为null,为null时仅格式化标签,不写入内容。 | -| **类型** | **说明** | -| ------------------ | --------------------------| -| Promise\ | 执行操作后返回的错误代码。如果返回0,则表示成功。 | +**错误码:** +以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 +| 错误码ID | 错误信息| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **示例:** - ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'ndef' correctly. -let data = [0x01, 0x02, ...]; // change it to be correct raw data. -let ndefmessage = ndef.createNdefMessage(data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'ndefFormatable' correctly. -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'ndefFormatable' correctly. -ndefFormatable.formatReadOnly(ndefmessage, (err, data)=> { - if (err) { - console.log("ndefFormatable formatReadOnly err: " + err); - } else { - console.log("ndefFormatable formatReadOnly data: " + data); +// connect the tag at first if not connected. +if (!ndefFormatable.isTagConnected()) { + if (!ndefFormatable.connectTag()) { + console.log("ndefFormatable connectTag failed."); + return; } -}); +} + +try { + // ndefMessage created from raw data, such as: + let ndefMessage = ndefTag.createNdefMessage([0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]); // change the raw data to be correct. + // or ndefMessage created from ndefTag.createNdefMessage(ndefRecords: NdefRecord[]) + + ndefFormatable.formatReadOnly(ndefMessage).then(() => { + console.log("ndefFormatable formatReadOnly Promise success."); + }).catch((err)=> { + console.log("ndefFormatable formatReadOnly Promise err: " + err); + }); +} catch (busiError) { + console.log("ndefFormatable formatReadOnly Promise catch busiError: " + busiError); +} ``` ### NdefFormatableTag.formatReadOnly9+ -formatReadOnly(message: [NdefMessage](#ndefmessage9), callback: AsyncCallback\): void +formatReadOnly(message: [NdefMessage](#ndefmessage9), callback: AsyncCallback\): void 将标签格式化为NDEF标签,然后将NDEF消息写入NDEF标签,之后将标签设置为只读。使用callback方式作为异步方法。 @@ -1892,33 +2424,43 @@ formatReadOnly(message: [NdefMessage](#ndefmessage9), callback: AsyncCallback\ | 回调函数。 | +| callback: AsyncCallback\ | 回调函数。 | **示例:** - ```js import tag from '@ohos.nfc.tag'; -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'ndef' correctly. -let data = [0x01, 0x02, ...]; // change it to be correct raw data. -let ndefmessage = ndef.createNdefMessage(data); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'ndefFormatable' correctly. -// see 'tag.TagInfo' at 'js-apis-nfcTag', has obtained the 'ndefFormatable' correctly. -ndefFormatable.formatReadOnly(ndefmessage, (err, data)=> { - if (err) { - console.log("ndefFormatable formatReadOnly err: " + err); - } else { - console.log("ndefFormatable formatReadOnly data: " + data); +// connect the tag at first if not connected. +if (!ndefFormatable.isTagConnected()) { + if (!ndefFormatable.connectTag()) { + console.log("ndefFormatable connectTag failed."); + return; } -}); +} + +try { + // ndefMessage created from raw data, such as: + let ndefMessage = ndefTag.createNdefMessage([0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]); // change the raw data to be correct. + // or ndefMessage created from ndefTag.createNdefMessage(ndefRecords: NdefRecord[]) + + ndefFormatable.formatReadOnly(ndefMessage, (err)=> { + if (err) { + console.log("ndefFormatable formatReadOnly AsyncCallback err: " + err); + } else { + console.log("ndefFormatable formatReadOnly AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("ndefFormatable formatReadOnly AsyncCallback catch busiError: " + busiError); +} ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-tagSession.md b/zh-cn/application-dev/reference/apis/js-apis-tagSession.md old mode 100755 new mode 100644 index 0e8c280b1ba2e0eda322df2e2fcb95bba4a6d105..7196bcf24b46dc61da69642ef1178a1cfb897c13 --- a/zh-cn/application-dev/reference/apis/js-apis-tagSession.md +++ b/zh-cn/application-dev/reference/apis/js-apis-tagSession.md @@ -13,64 +13,82 @@ import tag from '@ohos.nfc.tag'; ## tagSession -tagSession是所有[Nfc tag 技术类型](js-apis-nfctech.md)的基类, 提供建立连接和发送数据等共同接口。 +tagSession是所有[NFC Tag技术类型](js-apis-nfctech.md)的基类, 提供建立连接和发送数据等共同接口。 -需要通过其子类来访问以下接口。在下面的示例中 统一用 getXXTag表示获取子类实例的方法。 +需要通过其子类来访问以下接口。在下面的示例中 统一用 getXXX()表示获取子类实例的方法。 具体使用时,请根据实际采用的Nfc tag技术,选择对应的方法,具体请参见[nfcTag](js-apis-nfcTag.md)文档。 -### tagSession.connectTag - -connectTag(): boolean; +### tagSession.getTagInfo -和标签建立连接; +getTagInfo(): tag.TagInfo -在从标签读取数据或将数据写入标签之前,必须调用此方法。 +获取该Tag被分发时,NFC服务所提供的Tag数据对象。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC.Core **返回值:** - | **类型** | **说明** | | ------------------ | --------------------------| -| boolean | 连接建立成功返回 true,失败返回false。 | +| TagInfo | NFC服务所提供的Tag数据对象。 | **示例:** - ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an Object given by nfc service when tag is dispatched. -let isNfcConnected = tag.getXXXTag(taginfo).connectTag(); -console.log("isNfcConnected:" +isNfcConnected); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', tagInfo is an Object given by nfc service when tag is dispatched. +// the folowing getXXX, can be one of getIsoDep, getNdef, getMifareClassic, ... + +let tagInfo = tag.getXXX(tagInfo).getTagInfo(); +console.log("tag tagInfo: " + tagInfo); ``` -### tagSession.reset() +### tagSession.connectTag -reset(): void +connectTag(): boolean; -重置与标签的连接,并恢复将数据写入标签的默认超时时间。 +和标签建立连接。在从标签读取数据或将数据写入标签之前,必须调用此方法。 **需要权限**:ohos.permission.NFC_TAG **系统能力**:SystemCapability.Communication.NFC.Core **返回值:** - | **类型** | **说明** | | ------------------ | --------------------------| -| boolean | 方法执行成功返回 true,失败返回false。 | +| boolean | 连接建立成功返回true,失败返回false。 | **示例:** +```js +import tag from '@ohos.nfc.tag'; + +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', tagInfo is an Object given by nfc service when tag is dispatched. +// the folowing getXXX, can be one of getIsoDep, getNdef, getMifareClassic, ... + +let connectStatus = tag.getXXX(tagInfo).connectTag(); +console.log("connectStatus: " + connectStatus); +``` + +### tagSession.reset() + +reset(): void + +重置与标签的连接。 + +**需要权限**:ohos.permission.NFC_TAG + +**系统能力**:SystemCapability.Communication.NFC.Core +**示例:** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an Object given by nfc service when tag is dispatched. -let reset = tag.getXXXTag(taginfo).reset(); -console.log("reset:" +reset); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', tagInfo is an Object given by nfc service when tag is dispatched. +// the folowing getXXX, can be one of getIsoDep, getNdef, getMifareClassic, ... + +tag.getXXX(tagInfo).reset(); ``` ### tagSession.isTagConnected @@ -84,19 +102,19 @@ isTagConnected(): boolean **系统能力**:SystemCapability.Communication.NFC.Core **返回值:** - | **类型** | **说明** | | ------------------ | --------------------------| | boolean | 已建立连接返回 true,未建立连接返回false。 | **示例:** - ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an Object given by nfc service when tag is dispatched. -let isTagConnected = tag.getXXXTag(taginfo).isTagConnected(); -console.log("isTagConnected:" +isTagConnected); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', tagInfo is an Object given by nfc service when tag is dispatched. +// the folowing getXXX, can be one of getIsoDep, getNdef, getMifareClassic, ... + +let isTagConnected = tag.getXXX(tagInfo).isTagConnected(); +console.log("isTagConnected: " + isTagConnected); ``` ### tagSession.getMaxSendLength @@ -110,17 +128,160 @@ getMaxSendLength(): number **系统能力**:SystemCapability.Communication.NFC.Core **返回值:** +| **类型** | **说明** | +| ------------------ | --------------------------| +| number | 可以发送到标签的最大数据长度,非负数。 | + +**示例:** +```js +import tag from '@ohos.nfc.tag'; + +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', tagInfo is an Object given by nfc service when tag is dispatched. +// the folowing getXXX, can be one of getIsoDep, getNdef, getMifareClassic, ... +let maxSendLen = tag.getXXX(tagInfo).getMaxSendLength(); +console.log("tag maxSendLen: " + maxSendLen); +``` + +### tagSession.getSendDataTimeout + +getSendDataTimeout(): number + +查询发送数据到Tag的等待超时时间,单位是毫秒。 + +**需要权限**:ohos.permission.NFC_TAG + +**系统能力**:SystemCapability.Communication.NFC.Core + +**返回值:** | **类型** | **说明** | | ------------------ | --------------------------| -| number | 可以发送到标签的最大数据长度。 | +| number | 发送数据到Tag的等待超时时间,单位是毫秒,非负数。 | **示例:** +```js +import tag from '@ohos.nfc.tag'; +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', tagInfo is an Object given by nfc service when tag is dispatched. +// the folowing getXXX, can be one of getIsoDep, getNdef, getMifareClassic, ... + +let sendDataTimeout = tag.getXXX(tagInfo).getSendDataTimeout(); +console.log("tag sendDataTimeout: " + sendDataTimeout); +``` + +### tagSession.setSendDataTimeout + +setSendDataTimeout(timeout: number): boolean + +查询发送数据到Tag的等待超时时间,单位是毫秒。 + +**需要权限**:ohos.permission.NFC_TAG + +**系统能力**:SystemCapability.Communication.NFC.Core + +**参数:** +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------- | ---- | -------------------------------------- | +| timeout | number | 是 | 超时时间,单位毫秒,非负值。 | + +**返回值:** +| **类型** | **说明** | +| ------------------ | --------------------------| +| boolean | 设置超时时间成功返回true,设置失败返回false。 | + +**示例:** + +```js +import tag from '@ohos.nfc.tag'; + +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', tagInfo is an Object given by nfc service when tag is dispatched. +// the folowing getXXX, can be one of getIsoDep, getNdef, getMifareClassic, ... + +let timeoutMs = 700; // change it to be correct. +let setStatus = tag.getXXX(tagInfo).setSendDataTimeout(timeoutMs); +console.log("tag setSendDataTimeout setStatus: " + setStatus); +``` + +### tagSession.sendData + +sendData(data: number[]): Promise + +发送指令到Tag上,使用Promise方式作为异步方法。 + +**需要权限**:ohos.permission.NFC_TAG + +**系统能力**:SystemCapability.Communication.NFC + +**参数:** +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------- | ---- | -------------------------------------- | +| data | number[] | 是 | 要发送的指令。每个number十六进制表示,范围是0x00~0xFF。 | + +**返回值:** +| **类型** | **说明** | +| ------------------ | --------------------------| +| Promise | 对端Tag对指令的响应数据。每个number十六进制表示,范围是0x00~0xFF。| + +**示例:** +```js +import tag from '@ohos.nfc.tag'; + +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', tagInfo is an Object given by nfc service when tag is dispatched. +// the folowing getXXX, can be one of getIsoDep, getNdef, getMifareClassic, ... + +// connect the tag at first if not connected. +if (!tag.getXXX(tagInfo).isTagConnected()) { + if (!tag.getXXX(tagInfo).connectTag()) { + console.log("tagSession connectTag failed."); + return; + } +} + +let cmdData = [0x01, 0x02, ...]; // change the raw data to be correct. +tag.getXXX(tagInfo).sendData(cmdData).then((response) => { + console.log("tagSession sendData Promise response: " + response); +}).catch((err)=> { + console.log("tagSession sendData Promise err: " + err); +}); +``` + +### tagSession.sendData + +sendData(data: number[], callback: AsyncCallback): void + +发送指令到Tag上,使用AsyncCallback方式作为异步方法。 + +**需要权限**:ohos.permission.NFC_TAG + +**系统能力**:SystemCapability.Communication.NFC + +**参数:** +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------- | ---- | -------------------------------------- | +| data | number[] | 是 | 要发送的指令。每个number十六进制表示,范围是0x00~0xFF。 | +| callback | AsyncCallback | 是 | 回调函数,返回响应数据。每个number十六进制表示,范围是0x00~0xFF。 | + +**示例:** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an Object given by nfc service when tag is dispatched. -let mazSendLen = tag.getXXXTag(taginfo).getMaxSendLength(); -console.log("mazSendLen:" +mazSendLen); +// see 'tag.TagInfo' at 'js-apis-nfcTag.md', tagInfo is an Object given by nfc service when tag is dispatched. +// the folowing getXXX, can be one of getIsoDep, getNdef, getMifareClassic, ... + +// connect the tag at first if not connected. +if (!tag.getXXX(tagInfo).isTagConnected()) { + if (!tag.getXXX(tagInfo).connectTag()) { + console.log("tagSession connectTag failed."); + return; + } +} + +let cmdData = [0x01, 0x02, ...]; // change the raw data to be correct. +tag.getXXX(tagInfo).sendData(cmdData, (err, response)=> { + if (err) { + console.log("tagSession sendData AsyncCallback err: " + err); + } else { + console.log("tagSession sendData AsyncCallback response: " + response); + } +}); ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-testRunner.md b/zh-cn/application-dev/reference/apis/js-apis-testRunner.md index 273d1a19809895449766817a970e177dc4aeb3dd..92b46f63b5eab5c062cef6d588f7c972ef815afc 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-testRunner.md +++ b/zh-cn/application-dev/reference/apis/js-apis-testRunner.md @@ -29,7 +29,7 @@ export default class UserTestRunner implements TestRunner { onPrepare() { console.log("Trigger onPrepare") } - onRun(){} + onRun() {} }; ``` @@ -47,9 +47,9 @@ onRun(): void ```js export default class UserTestRunner implements TestRunner { - onPrepare() { - console.log("Trigger onRun") + onPrepare() {} + onRun() { + console.log("Trigger onRun") } - onRun(){} }; ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-userfilemanager.md b/zh-cn/application-dev/reference/apis/js-apis-userfilemanager.md index 7a5bd18ae9025bd98152dbef34527d4e1af6b409..ac164b3b6b8a98d7deb7ea3459009a68be9d43b8 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-userfilemanager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-userfilemanager.md @@ -1,12 +1,15 @@ # 用户数据管理 +该模块提供用户数据管理能力,包括访问、修改用户等用户公共媒体数据信息等常用功能。 + > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > 该模块从API Version 9开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 +> 本模块下的接口均为系统接口 ## 导入模块 -```js -import userFileManager from '@ohos.filemanagement.userfile_manager'; +```ts +import userFileManager from '@ohos.filemanagement.userFileManager'; ``` ## userFileManager.getUserFileMgr @@ -16,7 +19,7 @@ getUserFileMgr(context: Context): UserFileManager 获取用户数据管理模块的实例,用于访问和修改用户等用户公共媒体数据信息(如音频、视频、图片、文档等)。 **模型约束:** 此接口仅可在Stage模型下使用。 - + **系统能力**:SystemCapability.FileManagement.UserFileManager.Core **参数:** @@ -35,7 +38,7 @@ getUserFileMgr(context: Context): UserFileManager ```ts const context = getContext(this); -let userFileMgr = userfilemanager.getUserFileMgr(context); +let mgr = userfilemanager.getUserFileMgr(context); ``` ## userFileManager.getUserFileMgr @@ -58,739 +61,746 @@ getUserFileMgr(): UserFileManager **示例:** -```js -let userFileMgr = userfilemanager.getUserFileMgr(); +```ts +let mgr = userfilemanager.getUserFileMgr(); ``` ## UserFileManager -### getPublicDirectory +### getPhotoAssets + +getPhotoAssets(options: FetchOptions, callback: AsyncCallback<FetchResult<FileAsset>>): void; + + +获取图片和视频资源,使用callback方式返回结果。 -getPublicDirectory(type: DirectoryType, callback: AsyncCallback<string>): void; -获取系统预设的公共目录,使用callback方式返回异步结果。 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core +**需要权限**:ohos.permission.READ_IMAGEVIDEO + **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------ | ---- | ------------------------- | -| type | [DirectoryType](#directorytype) | 是 | 公共目录类型 | -| callback | AsyncCallback<string> | 是 | callback 返回公共目录路径 | +| options | [FetchOptions](#fetchoptions) | 是 | 图片和视频检索选项 | +| callback | AsyncCallback<[FetchResult](#fetchresult)<[FileAsset](#fileasset)>> | 是 | callback 返回图片和视频检索结果集 | **示例:** ```ts -async function getPublicDirectoryDemoCallback() { - console.info('getPublicDirectoryDemo'); - let DIR_CAMERA = directoryType.DIR_CAMERA; - console.info('DIR_CAMERA', DIR_CAMERA); - userFileMgr.getPublicDirectory(DIR_CAMERA, (err, dicResult) => { - if (dicResult == 'Camera/') { - console.info('mediaLibraryTest : getPublicDirectory passed'); - } else { - console.info('mediaLibraryTest : getPublicDirectory failed'); - } - }); +async function example() { + console.info('getPhotoAssets'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions = { + fetchColumns: [], + predicates: predicates + }; + + mgr.getPhotoAssets(fetchOptions, async (err, fetchResult) => { + if (fetchResult != undefined) { + console.info('fetchResult success'); + let fileAsset = await fetchResult.getFirstObject(); + if (fileAsset != undefined) { + console.info("fileAsset.displayName :" + fileAsset.displayName); + } + } else { + console.info('fetchResult fail' + err); + } + }) } ``` -### getPublicDirectory -getPublicDirectory(type: DirectoryType): Promise<string>; +### getPhotoAssets + +getPhotoAssets(options: FetchOptions): Promise<FetchResult<FileAsset>>; -获取系统预设的公共目录,使用Promise方式返回结果。 +获取图片和视频资源,使用Promise方式返回结果。 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core +**需要权限**:ohos.permission.READ_IMAGEVIDEO + **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------------- | ---- | ------------ | -| type | [DirectoryType](#directorytype) | 是 | 公共目录类型 | +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------------------- | ---- | ---------------- | +| options | [FetchOptions](#fetchoptions) | 是 | 图片和视频检索选项 | -**返回值:** +**返回值** -| 类型 | 说明 | -| ---------------- | ---------------- | -| Promise\ | 返回公共目录路径 | +| 类型 | 说明 | +| --------------------------- | -------------- | +| Promise<[FetchResult](#fetchresult)<[FileAsset](#fileasset)>> | 图片和视频数据结果集 | **示例:** ```ts -async function getPublicDirectoryDemoPromise() { - console.info('getPublicDirectoryDemo'); - let DIR_CAMERA = directoryType.DIR_CAMERA; - try { - let dicResult = await userFileMgr.getPublicDirectory(DIR_CAMERA); - console.info('mediaLibraryTest : getPublicDirectory passed, result = ', dicResult); - } catch (err) { - console.info('mediaLibraryTest : getPublicDirectory failed, message = ', err); +async function example() { + console.info('getPhotoAssets'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions = { + fetchColumns: [], + predicates: predicates + }; + try { + var fetchResult = await mgr.getPhotoAssets(fetchOptions) + if (fetchResult != undefined) { + console.info('fetchResult success'); + let fileAsset = await fetchResult.getFirstObject(); + if (fileAsset != undefined) { + console.info("fileAsset.displayName :" + fileAsset.displayName); + } } + } catch (err) { + console.info('getPhotoAssets failed, message = ', err); + } } ``` +### createPhotoAsset -### getFileAssets - -getFileAssets(type: Array<MediaType>, options: MediaFetchOptions, callback: AsyncCallback<FetchFileResult>): void; +createPhotoAsset(displayName: string, albumUri: string, callback: AsyncCallback<FileAsset>): void; -获取文件资源,使用callback方式返回结果。 +创建图片或视频资源,使用callback方式返回结果。 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core -**需要权限**:ohos.permission.READ_IMAGEVIDEO 或 ohos.permission.READ_AUDIO 或 ohos.permission.READ_DOCUMENT +**需要权限**:ohos.permission.WRITE_IMAGEVIDEO **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------ | ---- | ------------------------- | -| type | Array<[MediaType](#mediatype)> | 是 | 媒体类型检索范围 | -| options | [MediaFetchOptions](#mediafetchoptions) | 是 | 文件检索选项 | -| callback | AsyncCallback<string> | 是 | callback 返回文件检索结果 | +| displayName | string | 是 | 创建的图片或者视频文件名 | +| albumUri | string | 是 | 创建的图片或者视频所在相册的uri | +| callback | AsyncCallback<[FileAsset](#fileasset)> | 是 | callback 返回创建的图片和视频结果 | **示例:** ```ts -async function getFileAssetsDemoCallback() { - console.info('getFileAssets'); - let fileKeyObj = userfile_manager.FileKey - let imageType = userfile_manager.MediaType.IMAGE - let fetchOp = { - selections: '', - selectionArgs: [], - }; +async function example() { + console.info('createPhotoAssetDemo') + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions = { + predicates: predicates + }; + let albums = await mgr.getPhotoAlbums(fetchOptions) + let album = await albums.getFirstObject() + mgr.createPhotoAsset('testFile.txt', album.albumUri, (err, fileAsset) => { + if (fileAsset != undefined) { + console.info('createPhotoAsset file displayName' + fileAsset.displayName); + console.info('createPhotoAsset successfully'); + } else { + console.info('createPhotoAsset failed, message = ', err); + } + }) +} +``` - userFileMgr.getFileAssets([imageType, ], fetchOp, async (err, fetchFileResult) => { - if (fetchFileResult != undefined) { - console.info('fetchFileResult success'); - let fileAsset = await fetchFileResult.getFirstObject(); - if (fileAsset != undefined) { - console.info("fileAsset.displayName :" + fileAsset.displayName); - }; - } - }) +### createPhotoAsset + +createPhotoAsset(displayName: string, callback: AsyncCallback<FileAsset>): void; + +创建图片或视频资源,使用callback方式返回结果。 + +**系统能力**:SystemCapability.FileManagement.UserFileManager.Core + +**需要权限**:ohos.permission.WRITE_IMAGEVIDEO + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------ | ---- | ------------------------- | +| displayName | string | 是 | 创建的图片或者视频文件名 | +| callback | AsyncCallback<[FileAsset](#fileasset)> | 是 | callback 返回创建的图片和视频结果 | + +**示例:** + +```ts +async function example() { + console.info('createPhotoAssetDemo') + mgr.createPhotoAsset('testFile.txt', (err, fileAsset) => { + if (fileAsset != undefined) { + console.info('createPhotoAsset file displayName' + fileAsset.displayName); + console.info('createPhotoAsset successfully'); + } else { + console.info('createPhotoAsset failed, message = ', err); + } + }) } ``` -### getFileAssets +### createPhotoAsset -getFileAssets(type: Array<MediaType>, options: MediaFetchOptions): Promise<FetchFileResult>; +createPhotoAsset(displayName: string, albumUri?: string): Promise<FileAsset>; -获取文件资源,使用Promise方式返回结果。 +创建图片或视频资源,使用Promise方式返回结果。 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core -**需要权限**:ohos.permission.READ_IMAGEVIDEO 或 ohos.permission.READ_AUDIO 或 ohos.permission.READ_DOCUMENT +**需要权限**:ohos.permission.WRITE_IMAGEVIDEO **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------- | ------------------- | ---- | ---------------- | -| type | Array<[MediaType](#mediatype)> | 是 | 媒体类型检索范围 | -| options | [MediaFetchOptions](#mediafetchoptions) | 是 | 文件检索选项 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------ | ---- | ------------------------- | +| displayName | string | 是 | 创建的图片或者视频文件名 | +| albumUri | string | 否 | 创建的图片或者视频所在相册的uri | **返回值** | 类型 | 说明 | | --------------------------- | -------------- | -| Promise<[FetchFileResult](#fetchfileresult)> | 文件数据结果集 | +| Promise<[FileAsset](#fileasset)> | 返回创建的图片和视频结果 | **示例:** ```ts -async function getFileAssetsDemoPromise() { - console.info('getFileAssets'); - let fileKeyObj = userfile_manager.FileKey - let imageType = userfile_manager.MediaType.IMAGE - let fetchOp = { - selections: '', - selectionArgs: [], - }; - try { - var fetchFileResult = await userFileMgr.getFileAssets([imageType, ], fetchOp) - } catch (err) { - console.info('getFileAssets failed, message = ', err); - } - - if (fetchFileResult != undefined) { - console.info('fetchFileResult success'); - let fileAsset = await fetchFileResult.getFirstObject(); - if (fileAsset != undefined) { - console.info("fileAsset.displayName :" + fileAsset.displayName); - }; - } +async function example() { + console.info('createPhotoAssetDemo') + try { + let fileAsset = await mgr.createPhotoAsset('testFile.txt') + console.info('createPhotoAsset file displayName' + fileAsset.displayName); + console.info('createPhotoAsset successfully'); + } catch (err) { + console.info('createPhotoAsset failed, message = ', err); + } } ``` -### on +### getPhotoAlbums -on(type: 'deviceChange'|'albumChange'|'imageChange'|'audioChange'|'videoChange'|'fileChange'|'remoteFileChange', callback: Callback<void>): void +getPhotoAlbums(options: AlbumFetchOptions, callback: AsyncCallback<FetchResult<Album>>): void; -打开文件管理库变更通知,使用callback方式返回异步结果。 + +获取相册,使用callback方式返回结果。 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core +**需要权限**:ohos.permission.READ_IMAGEVIDEO + **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | ------------------------------------------------------------ | -| type | string | 是 | 媒体类型
'deviceChange': 注册设备变更
'albumChange': 相册变更
'imageChange': 图片文件变更
'audioChange':  音频文件变更
'videoChange':  视频文件变更
'fileChange':  文件变更
'remoteFileChange': 注册设备上文件变更 | -| callback | Callback<void> | 是 | 回调返回空 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------ | ---- | ------------------------- | +| options | [AlbumFetchOptions](#albumfetchoptions) | 是 | 相册检索选项 | +| callback | AsyncCallback<[FetchResult](#fetchresult)<[Album](#album)>> | 是 | callback 返回相册检索结果 | **示例:** ```ts -async function onDemo() { - console.info('onDemo') - userFileMgr.on('imageChange', () => { - // image file had changed, do something - }); +async function example() { + console.info('getPhotoAlbumsDemo') + let predicates = new dataSharePredicates.DataSharePredicates(); + let albumFetchOptions = { + predicates: predicates + }; + + mgr.getPhotoAlbums(albumFetchOptions, (err, fetchResult) => { + if (fetchResult != undefined) { + console.info('albums.count = ' + fetchResult.getCount()); + fetchResult.getFirstObject((err, album) => { + if (album != undefined) { + console.info('first album.albumName = ' + album.albumName); + } else { + console.info('album is undefined, err = ', err); + } + }) + } + console.info('getPhotoAlbums fail, message = ', err); + }) } ``` -### off +### getPhotoAlbums -off(type: 'deviceChange'|'albumChange'|'imageChange'|'audioChange'|'videoChange'|'fileChange'|'remoteFileChange', callback?: Callback<void>): void +getPhotoAlbums(options: AlbumFetchOptions): Promise<FetchResult<Album>>; -关闭文件管理库变更通知,使用callback方式返回异步结果。 +获取相册,使用callback方式返回结果。 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core +**需要权限**:ohos.permission.READ_IMAGEVIDEO + **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | ------------------------------------------------------------ | -| type | string | 是 | 媒体类型
'deviceChange': 注册设备变更
'albumChange': 相册变更
'imageChange': 图片文件变更
'audioChange':  音频文件变更
'videoChange':  视频文件变更
'fileChange':  文件变更
'remoteFileChange': 注册设备上文件变更 | -| callback | Callback<void> | 否 | 回调返回空 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------ | ---- | ------------------------- | +| options | [AlbumFetchOptions](#albumfetchoptions) | 是 | 相册检索选项 | + +**返回值** + +| 类型 | 说明 | +| --------------------------- | -------------- | +| Promise<[FetchResult](#fetchresult)<[Album](#album)>> | Promise 返回相册检索结果 | **示例:** ```ts -async function offDemo() { - console.info('offDemo') - userFileMgr.off('imageChange', () => { - // stop listening success - }); +async function example() { + console.info('getPhotoAlbumsDemo') + let predicates = new dataSharePredicates.DataSharePredicates(); + let albumFetchOptions = { + predicates: predicates + }; + try { + let fetchResult = await mgr.getPhotoAlbums(albumFetchOptions); + console.info('album.count = ' + fetchResult.getCount()); + const album = await fetchResult.getFirstObject(); + console.info('first album.albumName = ' + album.albumName); + } catch (err) { + console.info('getPhotoAlbums fail, message = ' + err); + } } ``` -### createAsset +### getPrivateAlbum -createAsset(mediaType: MediaType, displayName: string, relativePath: string, callback: AsyncCallback<FileAsset>): void +getPrivateAlbum(type: PrivateAlbumType, callback: AsyncCallback<FetchResult<PrivateAlbum>>): void; -创建文件资源,使用callback方式返回结果。 -此接口为系统接口。 +获取系统相册,使用 callback 方式返回系统相册的数组。 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core -**需要权限**:ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO 或 ohos.permission.WRITE_DOCUMENT +**需要权限**:ohos.permission.READ_IMAGEVIDEO **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------------ | --------------------------- | ---- | ------------------------------------------------------------ | -| mediaType | [MediaType](#mediatype) | 是 | 媒体类型 | -| displayName | string | 是 | 展示文件名 | -| relativePath | string | 是 | 文件保存路径,可以通过getPublicDirectory获取不同类型文件的保存路径 | -| callback | AsyncCallback<[FileAsset](#fileasset)> | 是 | 异步获取媒体数据FileAsset之后的回调 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------ | ---- | ------------------------- | +| type | [PrivateAlbumType](#privatealbumtype) | 是 | 系统相册类型 | +| callback | AsyncCallback<[FetchResult](#fetchresult)<[PrivateAlbum](#privatealbum)>> | 是 | callback 返回相册检索结果 | **示例:** ```ts -async function createAssetDemoCallback() { - console.info('createAssetDemo') - let mediaType = userfile_manager.MediaType.FILE; - let DIR_DOC = directoryType.DIR_DOCUMENTS; - const path = await userFileMgr.getPublicDirectory(DIR_DOC); - userFileMgr.createAsset(mediaType, 'tesfFile.txt', path + 'myDirectory/', (err, fileAsset) => { - if (err == undefined) { - console.info('createAsset successfully'); - } else { - console.info('createAsset failed, message = ', err); - } - }) +async function example() { + console.info('getPrivateAlbumDemo') + mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH, async (err, fetchResult) => { + if (fetchResult != undefined) { + let trashAlbum = await fetchResult.getFirstObject(); + console.info('first album.albumName = ' + trashAlbum.albumName); + } else { + console.info('getPrivateAlbum failed. message = ', err); + } + }); } ``` -### createAsset +### getPrivateAlbum -createAsset(mediaType: MediaType, displayName: string, relativePath: string): Promise<FileAsset>; +getPrivateAlbum(type: PrivateAlbumType): Promise<FetchResult<PrivateAlbum>>; -创建文件资源,使用Promise方式返回结果。 -此接口为系统接口。 +获取系统相册,使用Promise方式返回结果。 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core -**需要权限**:ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO 或 ohos.permission.WRITE_DOCUMENT +**需要权限**:ohos.permission.READ_IMAGEVIDEO **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------------ | --------- | ---- | ------------------------------------------------------------ | -| mediaType | [MediaType](#mediatype) | 是 | 媒体类型 | -| displayName | string | 是 | 展示文件名 | -| relativePath | string | 是 | 文件保存路径,可以通过getPublicDirectory获取不同类型文件的保存路径 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------ | ---- | ------------------------- | +| type | [PrivateAlbumType](#privatealbumtype) | 是 | 系统相册类型 | **返回值** -| 类型 | 说明 | -| --------------------- | ----------------- | -| Promise<[FileAsset](#fileasset)> | 媒体数据FileAsset | +| 类型 | 说明 | +| --------------------------- | -------------- | +| Promise<[FetchResult](#fetchresult)<[PrivateAlbum](#privatealbum)>> | Promise 返回相册检索结果 | **示例:** ```ts -async function createAssetDemoPromise() { - console.info('createAssetDemo') - let mediaType = userfile_manager.MediaType.FILE; - let DIR_DOC = directoryType.DIR_DOCUMENTS; - const path = await userFileMgr.getPublicDirectory(DIR_DOC); - try { - let fileAsset = await userFileMgr.createAsset(mediaType, 'tesfFile.txt', path + 'myDirectory/') - console.info('createAsset successfully'); - } catch (err) { - console.info('createAsset failed, message = ', err); - } +async function example() { + console.info('getPrivateAlbumDemo'); + try { + var fetchResult = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH); + let trashAlbum = await fetchResult.getFirstObject(); + console.info('first album.albumName = ' + trashAlbum.albumName); + } catch (err) { + console.info('getPrivateAlbum failed. message = ', err); + } } ``` -### deleteAsset +### getAudioAssets -deleteAsset(uri: string, callback: AsyncCallback<void>): void; +getAudioAssets(options: FetchOptions, callback: AsyncCallback<FetchResult<FileAsset>>): void; -删除文件资源,使用callback方式返回结果。 -此接口为系统接口。 +获取音频文件,使用callback方式返回结果。 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core -**需要权限**:ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO 或 ohos.permission.WRITE_DOCUMENT +**需要权限**:ohos.permission.READ_AUDIO **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | --------------------------- | ---- | ---------------------- | -| uri | string | 是 | 文件URI | -| callback | AsyncCallback<[FileAsset](#fileasset)> | 是 | 异步删除文件之后的回调 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------ | ---- | ------------------------- | +| options | [FetchOptions](#fetchoptions) | 是 | 检索选项 | +| callback | AsyncCallback<[FetchResult](#fetchresult)<[FileAsset](#fileasset)>> | 是 | callback 返回相册检索结果 | **示例:** ```ts -async function deleteAssetDemoCallback() { - console.info('deleteAssetDemo') - let fileKeyObj = userfile_manager.FileKey - let fileType = userfile_manager.MediaType.FILE - let option = { - selections: '', - selectionArgs: [], - }; - try { - const fetchFileResult = await userFileMgr.getFileAssets([fileType, ], option); - var asset = await fetchFileResult.getFirstObject(); - } catch(err) { - console.info('fetch failed, message =', err) - } - - if (asset == undefined) { - console.error('asset not exist') - return +async function example() { + console.info('getAudioAssets'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions = { + fetchColumns: [], + predicates: predicates + }; + + mgr.getPhotoAssets(fetchOptions, async (err, fetchResult) => { + if (fetchResult != undefined) { + console.info('fetchFileResult success'); + let fileAsset = await fetchResult.getFirstObject(); + if (fileAsset != undefined) { + console.info("fileAsset.displayName :" + fileAsset.displayName); + } + } else { + console.info('fetchFileResult fail' + err); } - userFileMgr.deleteAsset(asset.uri, (err) => { - if (err == undefined) { - console.info("deleteAsset successfully"); - } else { - console.info("deleteAsset failed with error:"+ err); - } - }); + }) } ``` -### deleteAsset +### getAudioAssets -deleteAsset(uri: string): Promise<void>; +getAudioAssets(options: FetchOptions): Promise<FetchResult<FileAsset>>; -创建文件资源,使用Promise方式返回结果。 -此接口为系统接口。 +获取音频文件,使用callback方式返回结果。 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core -**需要权限**:ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO 或 ohos.permission.WRITE_DOCUMENT +**需要权限**:ohos.permission.READ_AUDIO **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ------- | -| uri | string | 是 | 文件URI | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------ | ---- | ------------------------- | +| options | [FetchOptions](#fetchoptions) | 是 | 检索选项 | **返回值** -| 类型 | 说明 | -| ---------------- | --------------------------------- | -| Promise<void> | Promise实例,用于获取异步返回结果 | +| 类型 | 说明 | +| --------------------------- | -------------- | +| Promise<[FetchResult](#fetchresult)<[FileAsset](#fileasset)>> | Promise 返回相册检索结果 | **示例:** ```ts -async function deleteAssetDemoPromise() { - console.info('deleteAssetDemo') - let fileKeyObj = userfile_manager.FileKey - let fileType = userfile_manager.MediaType.FILE - let option = { - selections: '', - selectionArgs: [], - }; - try { - const fetchFileResult = await userFileMgr.getFileAssets([fileType, ], option); - var asset = await fetchFileResult.getFirstObject(); - } catch(err) { - console.info('fetch failed, message =', err) - } - if (asset == undefined) { - console.error('asset not exist') - return - } - try { - await userFileMgr.deleteAsset(asset.uri); - console.info("deleteAsset successfully"); - } catch (err) { - console.info("deleteAsset failed with error:"+ err); +async function example() { + console.info('getAudioAssets'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions = { + fetchColumns: [], + predicates: predicates + }; + try { + var fetchResult = await mgr.getPhotoAssets(fetchOptions) + } catch (err) { + console.info('getAudioAssets failed, message = ', err); + } + + if (fetchResult != undefined) { + console.info('fetchFileResult success'); + let fileAsset = await fetchResult.getFirstObject(); + if (fileAsset != undefined) { + console.info("fileAsset.displayName :" + fileAsset.displayName); } + } } ``` +### delete -### getAlbums - -getAlbums(type: Array<MediaType>, options: MediaFetchOptions, callback: AsyncCallback | 是 | 相册媒体类型检索范围 | -| options | [MediaFetchOptions](#mediafetchoptions) | 是 | 相册获取条件 | -| callback | AsyncCallback<Array<[Album](#album)>> | 是 | 异步获取Album列表之后的回调 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ---------- | +| uri | string | 是 | 媒体文件uri | +| callback | AsyncCallback<void> | 是 | 回调返回空 | -**示例:** +**示例**: ```ts -async function getAlbumsDemoCallback() { - console.info('getAlbumsDemo') - let AlbumNoArgsfetchOp = { - selections: '', - selectionArgs: [], - }; - userFileMgr.getAlbums([userfile_manager.MediaType.IMAGE], AlbumNoArgsfetchOp, (err, albumList) => { - if (albumList != undefined) { - const album = albumList[0]; - console.info('first album.albumName = ' + album.albumName); - console.info('album.count = ' + albumList.length); - } else { - console.info('getAlbum fail, message = ' + err); - } - }) +async function example() { + console.info('deleteAssetDemo') + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions = { + fetchColumns: [], + predicates: predicates + }; + try { + const fetchResult = await mgr.getPhotoAssets(fetchOptions); + var asset = await fetchResult.getFirstObject(); + } catch (err) { + console.info('fetch failed, message =', err) + } + + if (asset == undefined) { + console.error('asset not exist') + return; + } + mgr.delete(asset.uri, (err) => { + if (err == undefined) { + console.info("delete successfully"); + } else { + console.info("delete failed with error:" + err); + } + }); } ``` +### delete -### getAlbums +delete(uri: string): Promise<void>; -getAlbums(type: Array<MediaType>, options: MediaFetchOptions): Promise>; +删除媒体文件。 -获取相册列表,使用 promise 方式返回结果。 - -**需要权限**:ohos.permission.READ_IMAGEVIDEO 或 ohos.permission.READ_AUDIO 或 ohos.permission.READ_DOCUMENT +**需要权限**:ohos.permission.READ_IMAGEVIDEO 和 ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.READ_AUDIO 和 ohos.permission.WRITE_AUDIO **系统能力**:SystemCapability.FileManagement.UserFileManager.Core -**参数** +**参数**: -| 参数名 | 类型 | 必填 | 说明 | -| ------- | ------------------- | ---- | -------------------- | -| type | Array<[MediaType](#mediatype)> | 是 | 相册媒体类型检索范围 | -| options | [MediaFetchOptions](#mediafetchoptions) | 是 | 相册获取条件 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ---------- | +| uri | string | 是 | 媒体文件uri | -**返回值:** +**返回值**: -| 类型 | 说明 | -| ------------------------ | -------------------------- | -| Promise> | Promise实例,返回Album列表 | +| 类型 | 说明 | +| --------------------------------------- | ----------------- | +| Promise<void>| 回调返回空 | -**示例:** +**示例**: ```ts -async function getAlbumsDemoPromise() { - console.info('getAlbumsDemo') - let AlbumNoArgsfetchOp = { - selections: '', - selectionArgs: [], - }; - try { - let albumList = await userFileMgr.getAlbums([userfile_manager.MediaType.IMAGE], AlbumNoArgsfetchOp); - const album = albumList[0]; - console.info('first album.albumName = ' + album.albumName); - console.info('album.count = ' + albumList.length); - } catch (err) { - console.info('getAlbum fail, message = ' + err); - } +async function example() { + console.info('deleteDemo') + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions = { + fetchColumns: [], + predicates: predicates + }; + try { + const fetchResult = await mgr.getPhotoAssets(fetchOptions); + var asset = await fetchResult.getFirstObject(); + } catch (err) { + console.info('fetch failed, message =', err) + } + + if (asset == undefined) { + console.error('asset not exist') + return; + } + try { + await mgr.delete(asset.uri); + console.info("delete successfully"); + } catch (err) { + console.info("delete failed with error:" + err); + } } ``` -### getPrivateAlbum - -getPrivateAlbum(type: VirtualAlbumType, callback: AsyncCallback): void +### on -获取系统相册,使用 callback 方式返回系统相册的数组。 +on(type: ChangeEvent, callback: Callback<void>): void -此接口为系统接口。 +打开文件管理库变更通知,使用callback方式返回异步结果。 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core -**需要权限**:ohos.permission.READ_IMAGEVIDEO 或 ohos.permission.READ_AUDIO 或 ohos.permission.READ_DOCUMENTS - **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------- | ---- | ---------------------------------- | -| type | [VirtualAlbumType](#virtualalbumtype) | 是 | 系统相册类型 | -| callback | AsyncCallback> | 是 | 异步获取VirtualAlbum数组之后的回调 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ------------------------------------------------------------ | +| type | [ChangeEvent](#changeevent) | 是 | 媒体类型
'deviceChange': 注册设备变更
'albumChange': 相册变更
'imageChange': 图片文件变更
'audioChange':  音频文件变更
'videoChange':  视频文件变更
'remoteFileChange': 注册设备上文件变更 | +| callback | Callback<void> | 是 | 回调返回空 | **示例:** ```ts -async function getPrivateAlbumDemoCallback() { - console.info('getPrivateAlbumDemo') - userFileMgr.getPrivateAlbum(userfile_manager.VirtualAlbumType.TYPE_TRASH, async (err, albumArray) => { - if (err == undefined) { - console.info('getPrivateAlbum ok'); - try { - let fetchOpt = { - selections: '', - selectionArgs: [], - }; - let trashAlbum = albumArray[0]; - var fetchResult = await trashAlbum.getFileAssets([userfile_manager.MediaType.IMAGE], fetchOpt); - } catch (err) { - console.info('getFileAssets failed. message = ', err); - } - // Get file count in trash album - let count = fetchResult.getCount(); - console.info('fetchResult count = ', count) - // Get fileAssets in trash album - let trashAsset = await fetchResult.getFirstObject(); - // Get file trashed date - let isTrash = trashAsset.isTrash(); - console.info('is trashed', isTrash) - } else { - console.info('getPrivateAlbum failed. message = ', err); - } +async function example() { + console.info('onDemo') + userFileMgr.on('imageChange', () => { + // image file had changed, do something }); } ``` -### getPrivateAlbum - -getPrivateAlbum(type: VirtualAlbumType): Promise +### off -获取系统相册,使用 Promise 方式返回系统相册的数组。 +off(type: ChangeEvent, callback?: Callback<void>): void -此接口为系统接口。 +关闭文件管理库变更通知,使用callback方式返回异步结果。 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core -**需要权限**:ohos.permission.READ_IMAGEVIDEO 或 ohos.permission.READ_AUDIO 或 ohos.permission.READ_DOCUMENTS - **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ---------------- | ---- | ------------ | -| type | [VirtualAlbumType](#virtualalbumtype) | 是 | 系统相册类型 | - -**返回值:** - -| 类型 | 说明 | -| ------------------------------- | --------------------------------- | -| Promise> | Promise实例,返回VirtualAlbum数组 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ------------------------------------------------------------ | +| type | [ChangeEvent](#changeevent) | 是 | 媒体类型
'deviceChange': 注册设备变更
'albumChange': 相册变更
'imageChange': 图片文件变更
'audioChange':  音频文件变更
'videoChange':  视频文件变更
'remoteFileChange': 注册设备上文件变更 | +| callback | Callback<void> | 否 | 回调返回空 | **示例:** ```ts -async function getPrivateAlbumDemoPromise() { - console.info('getPrivateAlbumDemo'); - try { - var albumArray = await userFileMgr.getPrivateAlbum(userfile_manager.VirtualAlbumType.TYPE_TRASH); - } catch(err) { - console.info('getPrivateAlbum failed. message = ', err); - } - try { - let fetchOpt = { - selections: '', - selectionArgs: [], - }; - let trashAlbum = albumArray[0]; - var fetchResult = await trashAlbum.getFileAssets([userfile_manager.MediaType.IMAGE], fetchOpt); - } catch (err) { - console.info('getFileAssets failed. message = ', err); - } - // Get file count in trash album - let count = fetchResult.getCount(); - console.info('fetchResult count = ', count) - // Get fileAssets in trash album - let trashAsset = await fetchResult.getFirstObject(); - - // Get file trashed date - let isTrash = trashAsset.isTrash(); - console.info('is trashed', isTrash) +async function example() { + console.info('offDemo') + userFileMgr.off('imageChange', () => { + // stop listening success + }); } ``` ### getActivePeers -getActivePeers(callback: AsyncCallback>): void; +getActivePeers(callback: AsyncCallback<Array<PeerInfo>>): void; 获取在线对端设备的信息,使用callback方式返回异步结果。 -此接口为系统接口。 - **系统能力**:SystemCapability.FileManagement.UserFileManager.DistributedCore **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------------- | ---- | ------------ | -| callback | AsyncCallback> | 是 | 系统相册类型 | +| callback | AsyncCallback<Array<[PeerInfo](#peerinfo)>> | 是 | 返回在线设备列表 | **示例:** ```ts -async function getActivePeersDemoCallback() { - console.info('getActivePeersDemo') - var devicesInfo = userFileMgr.getActivePeers((err, devicesInfo) => { - if (err == undefined) { - console.log('getActivePeers succeed.') - for (let i = 0; i < devicesInfo.length; i++) { - console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); - } - } else { - console.info('getActivePeers failed. message = ', err) - } - }); +async function example() { + console.info('getActivePeersDemo') + mgr.getActivePeers((err, devicesInfo) => { + if (devicesInfo != undefined) { + console.log('getActivePeers succeed.') + for (let i = 0; i < devicesInfo.length; i++) { + console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); + } + } else { + console.info('getActivePeers failed. message = ', err) + } + }); } ``` ### getActivePeers -getActivePeers(): Promise>; +getActivePeers(): Promise<Array<PeerInfo>>; 获取在线对端设备的信息,使用promise方式返回异步结果。 -此接口为系统接口。 - **系统能力**:SystemCapability.FileManagement.UserFileManager.DistributedCore **返回值:** | 类型 | 说明 | | --------------------------- | ----------------------------- | -| Promise> | Promise实例,返回在线设备列表 | +| Promise<Array<[PeerInfo](#peerinfo)>> | Promise实例,返回在线设备列表 | **示例:** ```ts -async function getActivePeersDemoPromise() { - console.info('getActivePeersDemo') - try { - var devicesInfo = await userFileMgr.getActivePeers(); - } catch (err) { - console.info('getActivePeers failed. message = ', err) - } - if (devicesInfo != undefined) { - console.log('getActivePeers succeed.') - for (let i = 0; i < devicesInfo.length; i++) { - console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); - } - } else { - console.info('get distributed fail') +async function example() { + console.info('getActivePeersDemo') + try { + var devicesInfo = await mgr.getActivePeers(); + } catch (err) { + console.info('getActivePeers failed. message = ', err) + } + if (devicesInfo != undefined) { + console.log('getActivePeers succeed.') + for (let i = 0; i < devicesInfo.length; i++) { + console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); } + } else { + console.info('get distributed fail') + } } ``` ### getAllPeers -getAllPeers(callback: AsyncCallback>): void; +getAllPeers(callback: AsyncCallback<Array<PeerInfo>>): void; 获取所有对端设备的信息,使用callback方式返回异步结果。 -此接口为系统接口。 - **系统能力**:SystemCapability.FileManagement.UserFileManager.DistributedCore **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------------- | ---- | ------------ | -| callback | AsyncCallback> | 是 | 系统相册类型 | +| callback | AsyncCallback<Array<[PeerInfo](#peerinfo)>> | 是 | 返回在线设备列表 | **示例:** ```ts -async function getAllPeersDemoCallback() { - console.info('getAllPeersDemo') - var devicesInfo = await userFileMgr.getAllPeers((err, devicesInfo) => { - if (err == undefined) { - console.log('getAllPeers succeed.') - for (let i = 0; i < devicesInfo.length; i++) { - console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); - } - } else { - console.info('getAllPeers failed. message = ', err) - } - }); +async function example() { + console.info('getAllPeersDemo') + mgr.getAllPeers((err, devicesInfo) => { + if (devicesInfo != undefined) { + console.log('getAllPeers succeed.') + for (let i = 0; i < devicesInfo.length; i++) { + console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); + } + } else { + console.info('getAllPeers failed. message = ', err) + } + }); } ``` ### getAllPeers -getAllPeers(): Promise>; +getAllPeers(): Promise<Array<PeerInfo>>; 获取所有对端设备的信息,使用promise方式返回异步结果。 -此接口为系统接口。 - **系统能力**:SystemCapability.FileManagement.UserFileManager.DistributedCore **返回值:** | 类型 | 说明 | | --------------------------- | ----------------------------- | -| Promise> | Promise实例,返回所有设备列表 | +| Promise<Array<[PeerInfo](#peerinfo)>> | Promise实例,返回所有设备列表 | **示例:** ```ts -async function getAllPeersDemoPromise() { - console.info('getAllPeersDemo') - try { - var devicesInfo = await userFileMgr.getAllPeers(); - } catch (err) { - console.info('getAllPeers failed. message = ', err) - } - if (devicesInfo != undefined) { - console.log('getAllPeers succeed.') - for (let i = 0; i < devicesInfo.length; i++) { - console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); - } - } else { - console.info('get distributed fail') +async function example() { + console.info('getAllPeersDemo') + try { + var devicesInfo = await mgr.getAllPeers(); + } catch (err) { + console.info('getAllPeers failed. message = ', err) + } + if (devicesInfo != undefined) { + console.log('getAllPeers succeed.') + for (let i = 0; i < devicesInfo.length; i++) { + console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); } + } else { + console.info('get distributed fail') + } } ``` @@ -812,15 +822,15 @@ release(callback: AsyncCallback<void>): void **示例:** ```ts -async function releaseDemoCallback() { - console.info('releaseDemo'); - userFileMgr.release((err) => { - if (err != undefined) { - console.info('release failed. message = ', err); - } else { - console.info('release ok.'); - } - }) +async function example() { + console.info('releaseDemo'); + mgr.release((err) => { + if (err != undefined) { + console.info('release failed. message = ', err); + } else { + console.info('release ok.'); + } + }) } ``` @@ -842,14 +852,14 @@ release(): Promise<void> **示例:** ```ts -async function releaseDemoPromise() { - console.info('releaseDemo'); - try { - await userFileMgr.release(); - console.info('release ok.'); - } catch (err) { - console.info('release failed. message = ', err); - } +async function example() { + console.info('releaseDemo'); + try { + await mgr.release(); + console.info('release ok.'); + } catch (err) { + console.info('release failed. message = ', err); + } } ``` @@ -864,79 +874,77 @@ async function releaseDemoPromise() { | 名称 | 类型 | 可读 | 可写 | 说明 | | ------------------------- | ------------------------ | ---- | ---- | ------------------------------------------------------ | | uri | string | 是 | 否 | 文件资源uri(如:dataability:///media/image/2) | -| mediaType | [MediaType](#mediatype) | 是 | 否 | 媒体类型 | +| fileType | [FileType](#filetype) | 是 | 否 | 媒体文件类型 | | displayName | string | 是 | 是 | 显示文件名,包含后缀名 | -### isDirectory +### get -isDirectory(callback: AsyncCallback<boolean>): void +get(member: string): MemberType; -判断fileAsset是否为目录,使用callback方式返回异步结果。 +获取FileAsset成员参数 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------- | ---- | ------------------- | -| callback | AsyncCallback<boolean> | 是 | 当前FileAsset是否是目录的回调 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ----- | +| member | string | 是 | 成员参数名称例如:ImageVideoKey.URI | **示例:** - -```js +```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", + console.info('fileAssetGetDemo') + try { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const asset = await fetchFileResult.getFirstObject(); - asset.isDirectory((err, isDirectory) => { - // do something - }); + let fetchResult = await mgr.getPhotoAssets(fetchOption); + let fileAsset = await fetchResult.getFirstObject(); + let title = userFileManager.ImageVideoKey.TITLE + let fileAssetTitle = fileAsset.get(title.toString()) + console.info('fileAsset Get fileAssetTitle = ', fileAssetTitle); + } catch (err) { + console.info('release failed. message = ', err); + } } ``` -### isDirectory +### set -isDirectory():Promise<boolean> +set(member: string, value: string): void; -判断fileAsset是否为目录,使用Promise方式返回异步结果。 +设置FileAsset成员参数 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core -**返回值:** +**参数:** -| 类型 | 说明 | -| ---------------------- | ---------------------------- | -| Promise<boolean> | Promise实例,返回当前FileAsset是否是目录 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ----- | +| member | string | 是 | 成员参数名称例如:ImageVideoKey.URI | +| value | string | 是 | 设置成员参数名称,只能修改ImageVideoKey.TITLE的值 | **示例:** - -```js +```ts async function example() { - let fileKeyObj = userfile_manager.FileKey - let imageType = userfile_manager.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", + console.info('fileAssetSetDemo') + try { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const asset = await fetchFileResult.getFirstObject(); - asset.isDirectory().then(function(isDirectory){ - console.info("isDirectory result:"+ isDirectory); - }).catch(function(err){ - console.info("isDirectory failed with error:"+ err); - }); + let fetchResult = await mgr.getPhotoAssets(fetchOption); + let fileAsset = await fetchResult.getFirstObject(); + let title = userFileManager.ImageVideoKey.TITLE + fileAsset.set(title.toString(), "newTitle") + } catch (err) { + console.info('release failed. message = ', err); + } } ``` @@ -946,7 +954,7 @@ commitModify(callback: AsyncCallback<void>): void 修改文件的元数据,使用callback方式返回异步结果。 -**需要权限**:ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO 或 ohos.permission.WRITE_DOCUMENT +**需要权限**:ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO **系统能力**:SystemCapability.FileManagement.UserFileManager.Core @@ -958,23 +966,28 @@ commitModify(callback: AsyncCallback<void>): void **示例:** -```js +```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const asset = await fetchFileResult.getFirstObject(); - asset.title = 'newtitle'; - asset.commitModify(() => { - console.info('commitModify success'); - }); + console.info('commitModifyDemo') + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + let fileAsset = await fetchResult.getFirstObject(); + let title = userFileManager.ImageVideoKey.TITLE + let fileAssetTitle = fileAsset.get(title.toString()) + console.info('fileAsset Get fileAssetTitle = ', fileAssetTitle); + fileAsset.set(title.toString(), "newTitle") + fileAsset.commitModify((err) => { + if (err == undefined) { + let newFileAssetTitle = fileAsset.get(title.toString()) + console.info('fileAsset Get newFileAssetTitle = ', newFileAssetTitle); + } else { + console.info('commitModify failed, message =', err); + } + }); } ``` @@ -984,7 +997,7 @@ commitModify(): Promise<void> 修改文件的元数据,使用promise方式返回异步结果。 -**需要权限**:ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO 或 ohos.permission.WRITE_DOCUMENT +**需要权限**:ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO **系统能力**:SystemCapability.FileManagement.UserFileManager.Core @@ -994,23 +1007,29 @@ commitModify(): Promise<void> | ------------------- | ---------- | | Promise<void> | Promise返回空 | -**示例:** +**示例:** -```js +```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const asset = await fetchFileResult.getFirstObject(); - asset.title = 'newtitle'; - asset.commitModify(); + console.info('commitModifyDemo') + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + let fileAsset = await fetchResult.getFirstObject(); + let title = userFileManager.ImageVideoKey.TITLE + let fileAssetTitle = fileAsset.get(title.toString()) + console.info('fileAsset Get fileAssetTitle = ', fileAssetTitle); + fileAsset.set(title.toString(), "newTitle") + try { + await fileAsset.commitModify() + let newFileAssetTitle = fileAsset.get(title.toString()) + console.info('fileAsset Get newFileAssetTitle = ', newFileAssetTitle); + } catch (err) { + console.info('release failed. message = ', err); + } } ``` @@ -1022,7 +1041,7 @@ open(mode: string, callback: AsyncCallback<number>): void **注意**:当前写操作是互斥的操作,写操作完成后需要调用close进行释放 -**需要权限**:ohos.permission.READ_IMAGEVIDEO 或 ohos.permission.READ_AUDIO 或 ohos.permission.READ_DOCUMENT 或 ohos.permission.WRITE_MEDIA 或 ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO 或 ohos.permission.WRITE_DOCUMENT +**需要权限**:ohos.permission.READ_IMAGEVIDEO 或 ohos.permission.READ_AUDIO 或 ohos.permission.WRITE_MEDIA 或 ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO **系统能力**:SystemCapability.FileManagement.UserFileManager.Core @@ -1036,20 +1055,18 @@ open(mode: string, callback: AsyncCallback<number>): void **示例:** -```js +```ts async function example() { - let mediaType = mediaLibrary.MediaType.IMAGE; - let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const path = await userFileMgr.getPublicDirectory(DIR_IMAGE); - const asset = await userFileMgr.createAsset(mediaType, "image00003.jpg", path); - asset.open('rw', (openError, fd) => { - if(fd > 0){ - asset.close(fd); - }else{ - console.info('File Open Failed!' + openError); - } - }); + console.info('openDemo') + const fileAsset = await mgr.createPhotoAsset("image00003.jpg"); + fileAsset.open('rw', (err, fd) => { + if (fd != undefined) { + console.info('File fd' + fd); + fileAsset.close(fd) + } else { + console.info('File err' + err); + } + }); } ``` @@ -1061,7 +1078,7 @@ open(mode: string): Promise<number> **注意**:当前写操作是互斥的操作,写操作完成后需要调用close进行释放 -**需要权限**:ohos.permission.READ_IMAGEVIDEO 或 ohos.permission.READ_AUDIO 或 ohos.permission.READ_DOCUMENT 或 ohos.permission.WRITE_MEDIA 或 ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO 或 ohos.permission.WRITE_DOCUMENT +**需要权限**:ohos.permission.READ_IMAGEVIDEO 或 ohos.permission.READ_AUDIO 或 ohos.permission.WRITE_MEDIA 或 ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO **系统能力**:SystemCapability.FileManagement.UserFileManager.Core @@ -1079,20 +1096,21 @@ open(mode: string): Promise<number> **示例:** -```js +```ts async function example() { - let mediaType = mediaLibrary.MediaType.IMAGE; - let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const path = await userFileMgr.getPublicDirectory(DIR_IMAGE); - const asset = await userFileMgr.createAsset(mediaType, "image00003.jpg", path); - asset.open('rw') - .then((fd) => { - console.info('File fd!' + fd); - }) - .catch((err) => { - console.info('File err!' + err); - }); + console.info('openDemo') + try { + const fileAsset = await mgr.createPhotoAsset("image00003.jpg"); + let fd = await fileAsset.open('rw') + if (fd != undefined) { + console.info('File fd' + fd); + fileAsset.close(fd) + } else { + console.info(' open File fail'); + } + } catch (err) { + console.info('open Demo err' + err); + } } ``` @@ -1113,33 +1131,29 @@ close(fd: number, callback: AsyncCallback<void>): void **示例:** -```js +```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", + console.info('closeDemo') + try { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const asset = await fetchFileResult.getFirstObject(); - asset.open('rw').then((fd) => { - console.info('File fd!' + fd); - asset.close(fd, (closeErr) => { - if (closeErr != undefined) { - console.info('mediaLibraryTest : close : FAIL ' + closeErr); - console.info('mediaLibraryTest : ASSET_CALLBACK : FAIL'); - } else { - console.info("=======asset.close success====>"); - } - }); - }) - .catch((err) => { - console.info('File err!' + err); + let fetchResult = await mgr.getPhotoAssets(fetchOption); + const fileAsset = await fetchResult.getFirstObject(); + let fd = await fileAsset.open('rw'); + console.info('file fd', fd); + fileAsset.close(fd, (err) => { + if (err == undefined) { + console.info('asset close succeed.'); + } else { + console.info('close failed, message = ' + err); + } }); + } catch (err) { + console.info('close failed, message = ' + err); + } } ``` @@ -1165,34 +1179,24 @@ close(fd: number): Promise<void> **示例:** -```js +```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", + console.info('closeDemo') + try { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const asset = await fetchFileResult.getFirstObject(); - asset.open('rw').then((fd) => { - console.info('File fd!' + fd); - asset.close(fd).then((closeErr) => { - if (closeErr != undefined) { - console.info('mediaLibraryTest : close : FAIL ' + closeErr); - console.info('mediaLibraryTest : ASSET_CALLBACK : FAIL'); - - } else { - console.info("=======asset.close success====>"); - } - }); - }) - .catch((err) => { - console.info('File err!' + err); - }); + let fetchResult = await mgr.getPhotoAssets(fetchOption); + const asset = await fetchResult.getFirstObject(); + let fd = await asset.open('rw'); + console.info('file fd', fd); + await asset.close(fd) + console.info('asset close succeed.'); + } catch (err) { + console.info('close failed, message = ' + err); + } } ``` @@ -1202,7 +1206,7 @@ getThumbnail(callback: AsyncCallback<image.PixelMap>): void 获取文件的缩略图,使用callback方式返回异步结果。 -**需要权限**:ohos.permission.READ_IMAGEVIDEO or ohos.permission.READ_AUDIO or ohos.permission.READ_DOCUMENT +**需要权限**:ohos.permission.READ_IMAGEVIDEO 或 ohos.permission.READ_AUDIO **系统能力**:SystemCapability.FileManagement.UserFileManager.Core @@ -1214,22 +1218,24 @@ getThumbnail(callback: AsyncCallback<image.PixelMap>): void **示例:** -```js +```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const asset = await fetchFileResult.getFirstObject(); - asset.getThumbnail((err, pixelmap) => { - console.info('mediaLibraryTest : getThumbnail Successfull '+ pixelmap); - }); + console.info('getThumbnailDemo') + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + const asset = await fetchResult.getFirstObject(); + console.info('asset displayName = ', asset.displayName) + asset.getThumbnail((err, pixelMap) => { + if (err == undefined) { + console.info('getThumbnail successful ' + pixelMap); + } else { + console.info('getThumbnail fail', err); + } + }); } ``` @@ -1239,7 +1245,7 @@ getThumbnail(size: Size, callback: AsyncCallback<image.PixelMap>): void 获取文件的缩略图,传入缩略图尺寸,使用callback方式返回异步结果。 -**需要权限**:ohos.permission.READ_IMAGEVIDEO or ohos.permission.READ_AUDIO or ohos.permission.READ_DOCUMENT +**需要权限**:ohos.permission.READ_IMAGEVIDEO 或 ohos.permission.READ_AUDIO **系统能力**:SystemCapability.FileManagement.UserFileManager.Core @@ -1247,402 +1253,159 @@ getThumbnail(size: Size, callback: AsyncCallback<image.PixelMap>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------------------- | ---- | ---------------- | -| size | [Size](#size) | 是 | 缩略图尺寸 | +| size | Size | 是 | 缩略图尺寸 | | callback | AsyncCallback<[image.PixelMap](#../apis/js-apis-image.md#pixelmap7)> | 是 | 回调返回缩略图的PixelMap | **示例:** -```js -async function example() { - let fileKeyObj = mediaLibrary.FileKey; - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let size = { width: 720, height: 720 }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const asset = await fetchFileResult.getFirstObject(); - asset.getThumbnail(size, (err, pixelmap) => { - console.info('mediaLibraryTest : getThumbnail Successfull '+ pixelmap); - }); -} -``` - -### getThumbnail - -getThumbnail(size?: Size): Promise<image.PixelMap> - -获取文件的缩略图,传入缩略图尺寸,使用promise方式返回异步结果。 - -**需要权限**:ohos.permission.READ_IMAGEVIDEO or ohos.permission.READ_AUDIO or ohos.permission.READ_DOCUMENT - -**系统能力**:SystemCapability.FileManagement.UserFileManager.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ---- | -------------- | ---- | ----- | -| size | [Size](#size) | 否 | 缩略图尺寸 | - -**返回值:** - -| 类型 | 说明 | -| ----------------------------- | --------------------- | -| Promise<[image.PixelMap](#../apis/js-apis-image.md#pixelmap7)> | Promise返回缩略图的PixelMap | - -**示例:** - -```js -async function example() { - let fileKeyObj = mediaLibrary.FileKey; - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let size = { width: 720, height: 720 }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const asset = await fetchFileResult.getFirstObject(); - asset.getThumbnail(size) - .then((pixelmap) => { - console.info('mediaLibraryTest : getThumbnail Successfull '+ pixelmap); - }) - .catch((err) => { - console.info('mediaLibraryTest : getThumbnail fail'+ err); - }); -} -``` - -### favorite - -favorite(isFavorite: boolean, callback: AsyncCallback<void>): void - -将文件设置为收藏文件,使用callback方式返回异步结果。 - -**需要权限**:ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO 或 ohos.permission.WRITE_DOCUMENT - -**系统能力**:SystemCapability.FileManagement.UserFileManager.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ------------------------- | ---- | ---------------------------------- | -| isFavorite | boolean | 是 | 是否设置为收藏文件, true:设置为收藏文件,false:取消收藏 | -| callback | AsyncCallback<void> | 是 | 回调返回空 | - -**示例:** - -```js -async function example() { - let fileKeyObj = mediaLibrary.FileKey; - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const asset = await fetchFileResult.getFirstObject(); - asset.favorite(true,function(err){ - // do something - }); -} -``` - -### favorite - -favorite(isFavorite: boolean): Promise<void> - -将文件设置为收藏文件,使用promise方式返回异步结果。 - -**需要权限**:ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO 或 ohos.permission.WRITE_DOCUMENT - -**系统能力**:SystemCapability.FileManagement.UserFileManager.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ------- | ---- | ---------------------------------- | -| isFavorite | boolean | 是 | 是否设置为收藏文件, true:设置为收藏文件,false:取消收藏 | - -**返回值:** - -| 类型 | 说明 | -| ------------------- | ---------- | -| Promise<void> | Promise返回空 | - -**示例:** - -```js -async function example() { - let fileKeyObj = mediaLibrary.FileKey; - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const asset = await fetchFileResult.getFirstObject(); - asset.favorite(true).then(function() { - console.info("favorite successfully"); - }).catch(function(err){ - console.info("favorite failed with error:"+ err); - }); -} -``` - -### isFavorite - -isFavorite(callback: AsyncCallback<boolean>): void - -判断该文件是否为收藏文件,使用callback方式返回异步结果。 - -**系统能力**:SystemCapability.FileManagement.UserFileManager.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------- | ---- | ----------- | -| callback | AsyncCallback<boolean> | 是 | 回调表示是否为收藏文件 | - -**示例:** - -```js -async function example() { - let fileKeyObj = mediaLibrary.FileKey; - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const asset = await fetchFileResult.getFirstObject(); - asset.isFavorite((err, isFavorite) => { - if (isFavorite) { - console.info('FileAsset is favorite'); - }else{ - console.info('FileAsset is not favorite'); - } - }); -} -``` - -### isFavorite - -isFavorite():Promise<boolean> - -判断该文件是否为收藏文件,使用promise方式返回异步结果。 - -**系统能力**:SystemCapability.FileManagement.UserFileManager.Core - -**返回值:** - -| 类型 | 说明 | -| ---------------------- | ------------------ | -| Promise<boolean> | Promise回调表示是否是收藏文件 | - -**示例:** - -```js -async function example() { - let fileKeyObj = mediaLibrary.FileKey; - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const asset = await fetchFileResult.getFirstObject(); - asset.isFavorite().then(function(isFavorite){ - console.info("isFavorite result:"+ isFavorite); - }).catch(function(err){ - console.info("isFavorite failed with error:"+ err); - }); -} -``` - -### trash - -trash(isTrash: boolean, callback: AsyncCallback<void>): void - -当文件被定位时,将文件放到垃圾文件夹,使用callback方式返回异步结果。 - -放入垃圾文件夹的文件不会被真正删除,可以通过isTrash = false参数恢复成正常文件。 - -**需要权限**:ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO 或 ohos.permission.WRITE_DOCUMENT - -**系统能力**:SystemCapability.FileManagement.UserFileManager.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------- | ---- | --------- | -| isTrash | boolean | 是 | 是否设置为垃圾文件 | -| callback | AsyncCallback<void> | 是 | 回调返回空 | - -**示例:** - -```js +```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey; - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const asset = await fetchFileResult.getFirstObject(); - asset.trash(true, trashCallBack); - function trashCallBack(err, trash) { - console.info('mediaLibraryTest : ASSET_CALLBACK ASSET_CALLBACK trash'); + console.info('getThumbnailDemo') + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let size = { width: 720, height: 720 }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + const asset = await fetchResult.getFirstObject(); + console.info('asset displayName = ', asset.displayName) + asset.getThumbnail(size, (err, pixelMap) => { + if (err == undefined) { + console.info('getThumbnail successful ' + pixelMap); + } else { + console.info('getThumbnail fail', err); } + }); } ``` -### trash - -trash(isTrash: boolean): Promise<void> +### getThumbnail -当文件被定位时,将文件放到垃圾文件夹,使用promise方式返回异步结果。 +getThumbnail(size?: Size): Promise<image.PixelMap> -放入垃圾文件夹的文件不会被真正删除,可以通过isTrash = false参数恢复成正常文件。 +获取文件的缩略图,传入缩略图尺寸,使用promise方式返回异步结果。 -**需要权限**:ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO 或 ohos.permission.WRITE_DOCUMENT +**需要权限**:ohos.permission.READ_IMAGEVIDEO 或 ohos.permission.READ_AUDIO **系统能力**:SystemCapability.FileManagement.UserFileManager.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------- | ------- | ---- | --------- | -| isTrash | boolean | 是 | 是否设置为垃圾文件 | +| 参数名 | 类型 | 必填 | 说明 | +| ---- | -------------- | ---- | ----- | +| size | Size | 否 | 缩略图尺寸 | **返回值:** -| 类型 | 说明 | -| ------------------- | ---------- | -| Promise<void> | Promise返回空 | +| 类型 | 说明 | +| ----------------------------- | --------------------- | +| Promise<[image.PixelMap](#../apis/js-apis-image.md#pixelmap7)> | Promise返回缩略图的PixelMap | **示例:** -```js +```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey; - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const asset = await fetchFileResult.getFirstObject(); - asset.trash(true).then(function() { - console.info("trash successfully"); - }).catch(function(err){ - console.info("trash failed with error:"+ err); - }); + console.info('getThumbnailDemo') + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let size = { width: 720, height: 720 }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + const asset = await fetchResult.getFirstObject(); + console.info('asset displayName = ', asset.displayName) + asset.getThumbnail(size).then((pixelMap) => { + console.info('getThumbnail successful ' + pixelMap); + }).catch((err) => { + console.info('getThumbnail fail' + err); + }); } ``` -### isTrash +### favorite + +favorite(isFavorite: boolean, callback: AsyncCallback<void>): void -isTrash(callback: AsyncCallback<boolean>): void +将文件设置为收藏文件,使用callback方式返回异步结果。 -当文件被定位,判断文件是否为垃圾文件,使用callback方式返回异步结果。 +**需要权限**:ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO **系统能力**:SystemCapability.FileManagement.UserFileManager.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------- | ---- | --------------- | -| callback | AsyncCallback<boolean> | 是 | 回调返回表示文件是否为垃圾文件 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------- | ---- | ---------------------------------- | +| isFavorite | boolean | 是 | 是否设置为收藏文件, true:设置为收藏文件,false:取消收藏 | +| callback | AsyncCallback<void> | 是 | 回调返回空 | **示例:** -```js +```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey; - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const asset = await fetchFileResult.getFirstObject(); - asset.isTrash((err, isTrash) => { - if (isTrash == undefined) { - console.error('Failed to get trash state: ' + err); - return; - } - console.info('Get trash state success: ' + isTrash); - }); + console.info('favoriteDemo') + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + const asset = await fetchResult.getFirstObject(); + asset.favorite(true, (err) => { + if (err == undefined) { + console.info("favorite successfully"); + } else { + console.info("favorite failed with error:" + err); + } + }); } ``` -### isTrash +### favorite + +favorite(isFavorite: boolean): Promise<void> -isTrash():Promise<boolean> +将文件设置为收藏文件,使用promise方式返回异步结果。 -当文件被定位,判断文件是否为垃圾文件,使用promise方式返回异步结果。 +**需要权限**:ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO **系统能力**:SystemCapability.FileManagement.UserFileManager.Core +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------- | ---- | ---------------------------------- | +| isFavorite | boolean | 是 | 是否设置为收藏文件, true:设置为收藏文件,false:取消收藏 | + **返回值:** -| 类型 | 说明 | -| ------------------- | -------------------- | -| Promise<void> | Promise回调表示文件是否为垃圾文件 | +| 类型 | 说明 | +| ------------------- | ---------- | +| Promise<void> | Promise返回空 | **示例:** -```js +```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey; - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const asset = await fetchFileResult.getFirstObject(); - asset.isTrash().then(function(isTrash){ - console.info("isTrash result: " + isTrash); - }).catch(function(err){ - console.error("isTrash failed with error: " + err); - }); + console.info('favoriteDemo') + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + const asset = await fetchResult.getFirstObject(); + asset.favorite(true).then(function () { + console.info("favorite successfully"); + }).catch(function (err) { + console.info("favorite failed with error:" + err); + }); } ``` -## FetchFileResult +## FetchResult 文件检索结果集。 @@ -1662,19 +1425,17 @@ getCount(): number **示例**: -```js +```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey; - let fileType = mediaLibrary.MediaType.FILE; - let getFileCountOneOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [fileType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - let fetchFileResult = await userFileMgr.getFileAssets(getFileCountOneOp); - const fetchCount = fetchFileResult.getCount(); + console.info('getCountDemo') + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + const fetchCount = fetchResult.getCount(); + console.info('fetchCount = ', fetchCount) } ``` @@ -1694,31 +1455,22 @@ isAfterLast(): boolean **示例**: -```js +```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey; - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const fetchCount = fetchFileResult.getCount(); - console.info('mediaLibraryTest : count:' + fetchCount); - let fileAsset = await fetchFileResult.getFirstObject(); - for (var i = 1; i < fetchCount; i++) { - fileAsset = await fetchFileResult.getNextObject(); - if(i == fetchCount - 1) { - console.info('mediaLibraryTest : isLast'); - var result = fetchFileResult.isAfterLast(); - console.info('mediaLibraryTest : isAfterLast:' + result); - console.info('mediaLibraryTest : isAfterLast end'); - fetchFileResult.close(); - } - } + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + const fetchCount = fetchResult.getCount(); + console.info('count:' + fetchCount); + let fileAsset = await fetchResult.getLastObject(); + if (!fetchResult.isAfterLast()) { + console.info('fileAsset isAfterLast displayName = ', fileAsset.displayName); + } else { + console.info('fileAsset not isAfterLast '); + } } ``` @@ -1732,27 +1484,25 @@ close(): void **示例**: -```js +```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey; - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - fetchFileResult.close(); + console.info('fetchResultCloseDemo') + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + await fetchResult.close(); + console.info('close succeed.') } ``` ### getFirstObject -getFirstObject(callback: AsyncCallback<FileAsset>): void +getFirstObject(callback: AsyncCallback<T>): void -获取文件检索结果中的第一个文件资产。此方法使用回调返回FileAsset。 +获取文件检索结果中的第一个文件资产。此方法使用callback形式返回结果。 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core @@ -1760,37 +1510,34 @@ getFirstObject(callback: AsyncCallback<FileAsset>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------------------------- | ---- | ------------------------------------------- | -| callback | AsyncCallback<[FileAsset](#fileasset)> | 是 | 异步获取结果集中第一个FileAsset完成后的回调 | +| callback | AsyncCallback<T> | 是 | 异步获取结果集中的第一个完成后的回调 | **示例**: -```js +```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey; - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - fetchFileResult.getFirstObject((err, fileAsset) => { - if (err) { - console.error('Failed '); - return; - } - console.log('fileAsset.displayName : ' + fileAsset.displayName); - }) + console.info('getFirstObjectDemo') + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + fetchResult.getFirstObject((err, fileAsset) => { + if (fileAsset != undefined) { + console.info('fileAsset displayName: ', fileAsset.displayName) + } else { + console.info("fileAsset failed with err:" + err); + } + }); } ``` ### getFirstObject -getFirstObject(): Promise<FileAsset> +getFirstObject(): Promise<T> -获取文件检索结果中的第一个文件资产。此方法使用Promise方式返回FileAsset。 +获取文件检索结果中的第一个文件资产。此方法使用promise方式来异步返回。 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core @@ -1798,33 +1545,27 @@ getFirstObject(): Promise<FileAsset> | 类型 | 说明 | | --------------------------------------- | -------------------------- | -| Promise<[FileAsset](#fileasset)> | Promise方式返回FileAsset。 | +| Promise<T> | Promise方式返回。 | **示例**: -```js +```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey; - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - fetchFileResult.getFirstObject().then(function(fileAsset){ - console.info("getFirstObject successfully:"+ JSON.stringify(fileAsset)); - }).catch(function(err){ - console.info("getFirstObject failed with error:"+ err); - }); + console.info('getFirstObjectDemo') + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + let fileAsset = await fetchResult.getFirstObject(); + console.info('fileAsset displayName: ', fileAsset.displayName) } ``` ### getNextObject - getNextObject(callback: AsyncCallback<FileAsset>): void + getNextObject(callback: AsyncCallback<T>): void 获取文件检索结果中的下一个文件资产。此方法使用callback形式返回结果。 @@ -1834,37 +1575,37 @@ async function example() { | 参数名 | 类型 | 必填 | 说明 | | --------- | --------------------------------------------- | ---- | ----------------------------------------- | -| callbacke | AsyncCallback<[FileAsset](#fileasset)> | 是 | 异步返回结果集中下一个FileAsset之后的回调 | +| callbacke | AsyncCallback<T> | 是 | 异步返回结果集中下一个之后的回调 | **示例**: -```js +```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey; - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - fetchFileResult.getNextObject((err, fileAsset) => { - if (err) { - console.error('Failed '); - return; - } - console.log('fileAsset.displayName : ' + fileAsset.displayName); - }) + console.info('getNextObjectDemo') + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + await fetchResult.getFirstObject(); + if (fetchResult.isAfterLast()) { + fetchResult.getNextObject((err, fileAsset) => { + if (fileAsset != undefined) { + console.info('fileAsset displayName: ', fileAsset.displayName) + } else { + console.info("fileAsset failed with err:" + err); + } + }); + } } ``` ### getNextObject - getNextObject(): Promise<FileAsset> + getNextObject(): Promise<T> -获取文件检索结果中的下一个文件资产。此方法使用promise方式来异步返回FileAsset。 +获取文件检索结果中的下一个文件资产。此方法使用promise方式来异步返回。 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core @@ -1872,33 +1613,32 @@ async function example() { | 类型 | 说明 | | --------------------------------------- | ----------------- | -| Promise<[FileAsset](#fileasset)> | 返回FileAsset对象 | +| Promise<T> | 返回结果集中下一个对象 | **示例**: -```js +```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey; - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const fetchCount = fetchFileResult.getCount(); - console.info('mediaLibraryTest : count:' + fetchCount); - let fileAsset = await fetchFileResult.getNextObject(); + console.info('getNextObjectDemo') + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + await fetchResult.getFirstObject(); + if (fetchResult.isAfterLast()) { + let fileAsset = await fetchResult.getNextObject(); + console.info('fileAsset displayName: ', fileAsset.displayName) + } } ``` ### getLastObject -getLastObject(callback: AsyncCallback<FileAsset>): void +getLastObject(callback: AsyncCallback<T>): void -获取文件检索结果中的最后一个文件资产。此方法使用callback回调来返回FileAsset。 +获取文件检索结果中的最后一个文件资产。此方法使用callback回调来返回。 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core @@ -1906,37 +1646,34 @@ getLastObject(callback: AsyncCallback<FileAsset>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------------------------- | ---- | --------------------------- | -| callback | AsyncCallback<[FileAsset](#fileasset)> | 是 | 异步返回FileAsset之后的回调 | +| callback | AsyncCallback<T> | 是 | 异步返回结果集中最后一个的回调 | **示例**: -```js +```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey; - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - fetchFileResult.getLastObject((err, fileAsset) => { - if (err) { - console.error('Failed '); - return; - } - console.log('fileAsset.displayName : ' + fileAsset.displayName); - }) + console.info('getLastObjectDemo') + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + fetchResult.getLastObject((err, fileAsset) => { + if (fileAsset != undefined) { + console.info('fileAsset displayName: ', fileAsset.displayName) + } else { + console.info("fileAsset failed with err:" + err); + } + }); } ``` ### getLastObject -getLastObject(): Promise<FileAsset> +getLastObject(): Promise<T> -获取文件检索结果中的最后一个文件资产。此方法使用Promise方式来返回FileAsset。 +获取文件检索结果中的最后一个文件资产。此方法使用Promise方式来返回。 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core @@ -1944,31 +1681,29 @@ getLastObject(): Promise<FileAsset> | 类型 | 说明 | | --------------------------------------- | ----------------- | -| Promise<[FileAsset](#fileasset)> | 返回FileAsset对象 | +| Promise<T> | 返回结果集中最后一个对象 | **示例**: -```js +```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey; - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - let lastObject = await fetchFileResult.getLastObject(); + console.info('getLastObjectDemo') + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + let fileAsset = await fetchResult.getLastObject(); + console.info('fileAsset displayName: ', fileAsset.displayName) } ``` ### getPositionObject -getPositionObject(index: number, callback: AsyncCallback<FileAsset>): void +getPositionObject(index: number, callback: AsyncCallback<T>): void -获取文件检索结果中具有指定索引的文件资产。此方法使用回调来返回FileAsset。 +获取文件检索结果中具有指定索引的文件资产。此方法使用callback来返回。 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core @@ -1977,35 +1712,32 @@ getPositionObject(index: number, callback: AsyncCallback<FileAsset>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | ------------------ | | index | number | 是 | 要获取的文件的索引,从0开始 | -| callback | AsyncCallback<[FileAsset](#fileasset)> | 是 | 异步返回FileAsset之后的回调 | +| callback | AsyncCallback<T> | 是 | 异步返回指定索引的文件资产的回调 | **示例**: -```js +```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey; - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - fetchFileResult.getPositionObject(0, (err, fileAsset) => { - if (err) { - console.error('Failed '); - return; - } - console.log('fileAsset.displayName : ' + fileAsset.displayName); - }) + console.info('getPositionObjectDemo') + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + fetchResult.getPositionObject(0, (err, fileAsset) => { + if (fileAsset != undefined) { + console.info('fileAsset displayName: ', fileAsset.displayName) + } else { + console.info("fileAsset failed with err:" + err); + } + }); } ``` ### getPositionObject -getPositionObject(index: number): Promise<FileAsset> +getPositionObject(index: number): Promise<T> 获取文件检索结果中具有指定索引的文件资产。此方法使用Promise形式返回文件Asset。 @@ -2021,27 +1753,21 @@ getPositionObject(index: number): Promise<FileAsset> | 类型 | 说明 | | --------------------------------------- | ----------------- | -| Promise<[FileAsset](#fileasset)> | 返回FileAsset对象 | +| Promise<T> | 返回指定索引的文件资产的对象 | **示例**: -```js +```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey; - let imageType = mediaLibrary.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - fetchFileResult.getPositionObject(1) .then(function (fileAsset){ - console.log('fileAsset.displayName : ' + fileAsset.displayName); - }).catch(function (err) { - console.info("getFileAssets failed with error:" + err); - }); + console.info('getPositionObjectDemo') + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + let fileAsset = await fetchResult.getPositionObject(0); + console.info('fileAsset displayName: ', fileAsset.displayName) } ``` @@ -2059,16 +1785,98 @@ async function example() { | albumUri | string | 是 | 否 | 相册Uri | | dateModified | number | 是 | 否 | 修改日期 | | count | number | 是 | 否 | 相册中文件数量 | -| relativePath | string | 是 | 否 | 相对路径 | | coverUri | string | 是 | 否 | 封面文件Uri +### getPhotoAssets + +getPhotoAssets(options: FetchOptions, callback: AsyncCallback<FetchResult<FileAsset>>): void; + +获取相册中的文件。该方法使用callback形式来返回文件 + +**需要权限**:ohos.permission.WRITE_IMAGEVIDEO + +**系统能力**:SystemCapability.FileManagement.UserFileManager.Core + +**参数**: + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ---------- | +| options | [FetchOptions](#fetchoptions) | 是 | 检索选项 | +| callback | AsyncCallback<[FetchResult](#fetchresult)<[FileAsset](#fileasset)>> | 是 | callback 返回图片和视频数据结果集| + +**示例**: + +```ts +async function example() { + console.info('albumGetFileAssetsDemoCallback') + + let predicates = new dataSharePredicates.DataSharePredicates(); + let albumFetchOptions = { + predicates: predicates + }; + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + const albumList = await mgr.getPhotoAlbums(albumFetchOptions); + const album = await albumList.getFirstObject(); + album.getPhotoAssets(fetchOption, (err, albumFetchResult) => { + if (albumFetchResult != undefined) { + console.info("album getPhotoAssets successfully, getCount:" + albumFetchResult.getCount()); + } else { + console.info("album getPhotoAssets failed with error:" + err); + } + }); +} +``` +### getPhotoAssets + +getPhotoAssets(options: FetchOptions): Promise<FetchResult<FileAsset>>; + +获取相册中的文件。该方法使用Promise来返回文件 + +**需要权限**:ohos.permission.WRITE_IMAGEVIDEO + +**系统能力**:SystemCapability.FileManagement.UserFileManager.Core + +**参数**: + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ---------- | +| options | [FetchOptions](#fetchoptions) | 是 | 检索选项 | +| Promise | [FetchResult](#fetchresult)<[FileAsset](#fileasset)> | 是 | 图片和视频数据结果集 | + +**示例**: + +```ts +async function example() { + console.info('albumGetFileAssetsDemoPromise') + + let predicates = new dataSharePredicates.DataSharePredicates(); + let albumFetchOptions = { + predicates: predicates + }; + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + const albumList = await mgr.getPhotoAlbums(albumFetchOptions); + const album = await albumList.getFirstObject(); + album.getPhotoAssets(fetchOption).then((albumFetchResult) => { + console.info("album getFileAssets successfully, getCount:" + albumFetchResult.getCount()); + }).catch((err) => { + console.info("album getFileAssets failed with error:" + err); + }); +} +``` + ### commitModify commitModify(callback: AsyncCallback<void>): void; 更新相册属性修改到数据库中。 -**需要权限**:ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO 或 ohos.permission.WRITE_DOCUMENT +**需要权限**:ohos.permission.WRITE_IMAGEVIDEO **系统能力**:SystemCapability.FileManagement.UserFileManager.Core @@ -2081,28 +1889,22 @@ commitModify(callback: AsyncCallback<void>): void; **示例**: ```ts -async function commitModifyDemoCallback() { - console.info('commitModifyDemo') - let fileKeyObj = userfile_manager.FileKey - let imageType = userfile_manager.MediaType.IMAGE; - let getImageOp = { - selections: '', - selectionArgs: [], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let fetchFileResult = await userFileMgr.getFileAssets([imageType], getImageOp); - let asset = await fetchFileResult.getFirstObject(); - console.info('old displayName:', asset.displayName) - asset.displayName = 'newDisplayName'; - console.info('new displayName:', asset.displayName) - asset.commitModify((err) => { - if (err == undefined) { - console.info('commitModify succeed.') - } else { - console.info('commitModify failed, message =', err); - } - }); +async function example() { + console.info('albumCommitModifyDemo') + let predicates = new dataSharePredicates.DataSharePredicates(); + let albumFetchOptions = { + predicates: predicates + }; + const albumList = await mgr.getPhotoAlbums(albumFetchOptions); + const album = await albumList.getFirstObject(); + album.albumName = 'hello'; + album.commitModify((err) => { + if (err != undefined) { + console.info("commitModify failed with error:" + err); + } else { + console.info("commitModify successfully"); + } + }); } ``` @@ -2112,7 +1914,7 @@ commitModify(): Promise<void>; 更新相册属性修改到数据库中。 -**需要权限**:ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO 或 ohos.permission.WRITE_DOCUMENT +**需要权限**:ohos.permission.WRITE_IMAGEVIDEO **系统能力**:SystemCapability.FileManagement.UserFileManager.Core @@ -2125,265 +1927,323 @@ commitModify(): Promise<void>; **示例**: ```ts -async function commitModifyDemoPromise() { - console.info('commitModifyDemo') - let fileKeyObj = userfile_manager.FileKey - let imageType = userfile_manager.MediaType.IMAGE; - let getImageOp = { - selections: '', - selectionArgs: [], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let fetchFileResult = await userFileMgr.getFileAssets([imageType], getImageOp); - let asset = await fetchFileResult.getFirstObject(); - console.info('old displayName:', asset.displayName) - asset.displayName = 'newDisplayName'; - console.info('new displayName:', asset.displayName) - try { - await asset.commitModify(); - console.info('commitModify succeed.') - } catch (err) { - console.info('commitModify failed, message =', err); - } +async function example() { + console.info('albumCommitModifyDemo') + let predicates = new dataSharePredicates.DataSharePredicates(); + let albumFetchOptions = { + predicates: predicates + }; + try { + var albumList = await mgr.getPhotoAlbums(albumFetchOptions); + } catch (err) { + console.info('getPhotoAlbums failed. message = ', err); + } + const album = await albumList.getFirstObject(); + album.albumName = 'hello'; + album.commitModify().then(() => { + console.info("commitModify successfully"); + }).catch((err) => { + console.info("commitModify failed with error:" + err); + }); } ``` -### getFileAssets +## PrivateAlbum +系统相册 + +### 属性 + +**系统能力:** 以下各项对应的系统能力均为SystemCapability.FileManagement.UserFileManager.Core + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ------------ | ------ | ---- | ---- | ------- | +| albumName | string | 是 | 是 | 相册名称 | +| albumUri | string | 是 | 否 | 相册Uri | +| dateModified | number | 是 | 否 | 修改日期 | +| count | number | 是 | 否 | 相册中文件数量 | +| coverUri | string | 是 | 否 | 封面文件Uri + +### getPhotoAssets -getFileAssets(type: Array<MediaType>, callback: AsyncCallback<FetchFileResult>): void; +getPhotoAssets(options: FetchOptions, callback: AsyncCallback<FetchResult<FileAsset>>): void; -按照检索条件获取相册中的文件。此方法使用Callback回调来返回文件结果集。 +获取系统相册中的文件。该方法使用callback形式来返回文件 -**需要权限**:ohos.permission.READ_IMAGEVIDEO or ohos.permission.READ_AUDIO or ohos.permission.READ_DOCUMENT +**需要权限**:ohos.permission.WRITE_IMAGEVIDEO **系统能力**:SystemCapability.FileManagement.UserFileManager.Core **参数**: -| 参数名 | 类型 | 必填 | 说明 | -| -------- | --------------------------------------------------- | ---- | ----------------------------------- | -| type | Array<[MediaType](#mediatype)> | 是 | 媒体类型检索选项。 | -| callback | AsyncCallback<[FetchFileResult](#fetchfileresult)> | 是 | 异步返回FetchFileResult之后的回调。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ---------- | +| options | [FetchOptions](#fetchoptions) | 是 | 检索选项 | +| callback | AsyncCallback<[FetchResult](#fetchresult)<[FileAsset](#fileasset)>> | 是 | callback返回图片和视频数据结果集 | **示例**: ```ts -async function albumGetFileAssetsDemoCallback() { - console.info('albumGetFileAssetsDemoCallback2') - let imageType = userfile_manager.MediaType.IMAGE; - let AlbumNoArgsfetchOp = { - selections: '', - selectionArgs: [], - }; - const albumList = await userFileMgr.getAlbums([imageType], AlbumNoArgsfetchOp); - const album = albumList[0]; - album.getFileAssets([imageType], (err, albumFetchFileResult) => { - if (err == undefined) { - console.info("getFileAssets successfully:"+ JSON.stringify(albumFetchFileResult)); - } else { - console.info("getFileAssets failed with error:"+ err); - } - }); +async function example() { + console.info('privateAlbumGetFileAssetsDemoCallback') + let albumList = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + const trashAlbum = await albumList.getFirstObject(); + trashAlbum.getPhotoAssets(fetchOption, (err, fetchResult) => { + if (fetchResult != undefined) { + let count = fetchResult.getCount(); + console.info('fetchResult.count = ', count); + } else { + console.info('getFileAssets failed, message = ', err); + } + }); } -``` -### getFileAssets +``` +### getPhotoAssets -getFileAssets(type: Array<MediaType>, options: MediaFetchOptions, callback: AsyncCallback<FetchFileResult>): void; +getPhotoAssets(options: FetchOptions): Promise<FetchResult<FileAsset>>; -按照检索条件获取相册中的文件。此方法使用Callback回调来返回文件结果集。 +获取系统相册中的文件。该方法使用Promise来返回文件 -**需要权限**:ohos.permission.READ_IMAGEVIDEO or ohos.permission.READ_AUDIO or ohos.permission.READ_DOCUMENT +**需要权限**:ohos.permission.WRITE_IMAGEVIDEO **系统能力**:SystemCapability.FileManagement.UserFileManager.Core **参数**: -| 参数名 | 类型 | 必填 | 说明 | -| -------- | --------------------------------------------------- | ---- | ----------------------------------- | -| type | Array<[MediaType](#mediatype)> | 是 | 媒体类型检索选项。 | -| options | [MediaFetchOptions](#mediafetchoptions) | 是 | 媒体检索选项。 | -| callback | AsyncCallback<[FetchFileResult](#fetchfileresult)> | 是 | 异步返回FetchFileResult之后的回调。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ---------- | +| options | [FetchOptions](#fetchoptions) | 是 | 检索选项 | + +**返回值**: + +| 类型 | 说明 | +| --------------------------------------- | ----------------- | +| Promise:[FetchResult](#fetchresult)<[FileAsset](#fileasset)>| 图片和视频数据结果集 | **示例**: ```ts -async function albumGetFileAssetsDemoCallback() { - console.info('albumGetFileAssetsDemoCallback') - let imageType = userfile_manager.MediaType.IMAGE; - let AlbumNoArgsfetchOp = { - selections: '', - selectionArgs: [], - }; - let fileNoArgsfetchOp = { - selections: '', - selectionArgs: [], - } - const albumList = await userFileMgr.getAlbums([imageType], AlbumNoArgsfetchOp); - const album = albumList[0]; - album.getFileAssets([imageType], fileNoArgsfetchOp, (err, albumFetchFileResult) => { - if (err == undefined) { - console.info("getFileAssets successfully:"+ JSON.stringify(albumFetchFileResult)); - } else { - console.info("getFileAssets failed with error:"+ err); - } - }); - } +async function example() { + console.info('privateAlbumGetFileAssetsDemoPromise') + let albumList = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + const trashAlbum = await albumList.getFirstObject(); + let fetchResult = await trashAlbum.getPhotoAssets(fetchOption); + let count = fetchResult.getCount(); + console.info('fetchResult.count = ', count); +} ``` +### delete + +delete(uri: string, callback: AsyncCallback<void>): void; -### getFileAssets +删除系统相册中的文件 -getFileAssets(type: Array<MediaType>, options?: MediaFetchOptions): Promise<FetchFileResult>; +**需要权限**:ohos.permission.READ_IMAGEVIDEO 和 ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.READ_AUDIO 和 ohos.permission.WRITE_AUDIO + +**系统能力**:SystemCapability.FileManagement.UserFileManager.Core + +**参数**: + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ---------- | +| uri | string | 是 | 相册uri | +| callback | AsyncCallback<void> | 是 | 回调返回空 | + +**示例**: + +```ts +async function example() { + console.info('privateAlbumDeleteCallback'); + let albumList = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + const trashAlbum = await albumList.getFirstObject(); + let fetchResult = await trashAlbum.getPhotoAssets(fetchOption); + const fileAsset = await fetchResult.getFirstObject(); + let deleteFileUri = fileAsset.uri; + trashAlbum.delete(deleteFileUri, (err) => { + if (err != undefined) { + console.info('trashAlbum.delete failed, message = ', err); + } else { + console.info('trashAlbum.delete successfully'); + } + }); +} +``` +### delete -按照检索条件获取相册中的文件。此方法使用异步Promise来返回文件结果集。 +delete(uri: string): Promise<void>; -**需要权限**:ohos.permission.READ_IMAGEVIDEO or ohos.permission.READ_AUDIO or ohos.permission.READ_DOCUMENT +删除系统相册中的文件 +**需要权限**:ohos.permission.READ_IMAGEVIDEO 和 ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.READ_AUDIO 和 ohos.permission.WRITE_AUDIO **系统能力**:SystemCapability.FileManagement.UserFileManager.Core **参数**: -| 参数名 | 类型 | 必填 | 说明 | -| ------- | ---------------------------------------- | ---- | -------------- | -| type | Array<[MediaType](#mediatype)> | 是 | 媒体类型检索选项。 | -|options | [MediaFetchOptions](#mediafetchoptions) | 否 | 媒体检索选项。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ---------- | +| uri | string | 是 | 相册uri | **返回值**: -| 类型 | 说明 | -| --------------------------------------------- | ------------------------- | -| Promise<[FetchFileResult](#fetchfileresult)> | 返回FetchFileResult对象。 | +| 类型 | 说明 | +| --------------------------------------- | ----------------- | +| Promise<void>| 回调返回空 | **示例**: ```ts -async function albumGetFileAssetsDemoPromise() { - console.info('albumGetFileAssetsDemoPromise') - let imageType = userfile_manager.MediaType.IMAGE; - let AlbumNoArgsfetchOp = { - selections: '', - selectionArgs: [], - }; - let fileNoArgsfetchOp = { - selections: '', - selectionArgs: [], - } - const albumList = await userFileMgr.getAlbums([imageType], AlbumNoArgsfetchOp); - const album = albumList[0]; - album.getFileAssets([imageType], fileNoArgsfetchOp).then(function(albumFetchFileResult){ - console.info("getFileAssets successfully:"+ JSON.stringify(albumFetchFileResult)); - }).catch(function(err){ - console.info("getFileAssets failed with error:"+ err); - }); -} +async function example() { + console.info('privateAlbumDeleteDemoPromise') + let albumList = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + const trashAlbum = await albumList.getFirstObject(); + let fetchResult = await trashAlbum.getPhotoAssets(fetchOption); + const fileAsset = await fetchResult.getFirstObject(); + let deleteFileUri = fileAsset.uri; + trashAlbum.delete(deleteFileUri).then(() => { + console.info('trashAlbum.delete successfully'); + }).catch((err) => { + console.info('trashAlbum.delete failed, message = ', err); + }); +} ``` -## VirtualAlbum -虚拟相册 - -### getFileAssets - -getFileAssets(type: Array<MediaType>, options: MediaFetchOptions, callback: AsyncCallback<FetchFileResult>): void; -按照检索条件获取虚拟相册中的文件。此方法使用Callback回调来返回文件结果集。 +### recover -此接口为系统接口。 +recover(uri: string, callback: AsyncCallback<void>): void; -**需要权限**:ohos.permission.READ_IMAGEVIDEO or ohos.permission.READ_AUDIO or ohos.permission.READ_DOCUMENTS +恢复系统相册中的文件 -> 说明: -> 本接口所需申请的分类的权限APL等级为system_basic。APL等级为normal的应用需要通过ACL证书方式申请,申请方式请参考[ACL说明](../../security/accesstoken-overview.md#访问控制列表acl说明) -> -> 建议通过options参数显式地指定要访问的文件类型。若无法判断文件类型,则会根据应用实际申请的权限返回对应的文件资源结果集。 +**需要权限**:ohos.permission.WRITE_IMAGEVIDEO **系统能力**:SystemCapability.FileManagement.UserFileManager.Core **参数**: -| 参数名 | 类型 | 必填 | 说明 | -| -------- | --------------------------------------------------- | ---- | ----------------------------------- | -| type | Array<[MediaType](#mediatype)> | 是 | 媒体类型检索选项。 | -| options | [MediaFetchOptions](#mediafetchoptions) | 是 | 媒体检索选项。 | -| callback | AsyncCallback<[FetchFileResult](#fetchfileresult)> | 是 | 异步返回FetchFileResult之后的回调。 | + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ---------- | +| uri | string | 是 | 相册uri | +| callback | AsyncCallback<void> | 是 | 回调返回空 | **示例**: ```ts -async function virtualAlbumGetFileAssetsDemoCallback() { - console.info('virtualAlbumGetFileAssetsDemoCallback') - try { - var albumArray = await userFileMgr.getPrivateAlbum(userfile_manager.VirtualAlbumType.TYPE_TRASH); - } catch (err) { - console.info('getPrivateAlbum failed, message = ', err); +async function example() { + console.info('privateAlbumRecoverDemoCallback'); + let albumList = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + const trashAlbum = await albumList.getFirstObject(); + let fetchResult = await trashAlbum.getPhotoAssets(fetchOption); + const fileAsset = await fetchResult.getFirstObject(); + let recoverFileUri = fileAsset.uri; + trashAlbum.recover(recoverFileUri, (err) => { + if (err != undefined) { + console.info('trashAlbum.recover failed, message = ', err); + } else { + console.info('trashAlbum.recover successfully'); } - let fetchOpt = { - selections: '', - selectionArgs: [], - }; - let trashAlbum = albumArray[0]; - - trashAlbum.getFileAssets([userfile_manager.MediaType.IMAGE], fetchOpt, (err, fetchResult) => { - if (err == undefined) { - let count = fetchResult.getCount(); - console.info('fetchResult.count = ', count); - } else { - console.info('getFileAssets failed, message = ', err); - } - }); + }); } ``` +### recover -### getFileAssets -getFileAssets(type: Array<MediaType>, options: MediaFetchOptions): Promise<FetchFileResult>; - -按照检索条件获取虚拟相中的文件。此方法使用异步Promise来返回文件结果集。 +recover(uri: string): Promise<void>; -此接口为系统接口。 +恢复系统相册中的文件 -**需要权限**:ohos.permission.READ_IMAGEVIDEO or ohos.permission.READ_AUDIO or ohos.permission.READ_DOCUMENTS - -> 说明: -> 本接口所需申请的分类的权限APL等级为system_basic。APL等级为normal的应用需要通过ACL证书方式申请,申请方式请参考[ACL说明](../../security/accesstoken-overview.md#访问控制列表acl说明) -> -> 建议通过options参数显式地指定要访问的文件类型。若无法判断文件类型,则会根据应用实际申请的权限返回对应的文件资源结果集。 +**需要权限**:ohos.permission.WRITE_IMAGEVIDEO **系统能力**:SystemCapability.FileManagement.UserFileManager.Core **参数**: -| 参数名 | 类型 | 必填 | 说明 | -| ------- | ---------------------------------------- | ---- | -------------- | -| type | Array<[MediaType](#mediatype)> | 是 | 媒体类型检索选项。 | -|options | [MediaFetchOptions](#mediafetchoptions) | 否 | 媒体检索选项。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ---------- | +| uri | string | 是 | 相册uri | **返回值**: -| 类型 | 说明 | -| --------------------------------------------- | ------------------------- | -| Promise<[FetchFileResult](#fetchfileresult)> | 返回FetchFileResult对象。 | +| 类型 | 说明 | +| --------------------------------------- | ----------------- | +| Promise<void>| 回调返回空 | **示例**: ```ts -async function virtualAlbumGetFileAssetsDemoPromise() { - console.info('virtualAlbumGetFileAssetsDemoPromise') - let albumArray = await userFileMgr.getPrivateAlbum(userfile_manager.VirtualAlbumType.TYPE_TRASH); - let fetchOpt = { - selections: '', - selectionArgs: [], - }; - let trashAlbum = albumArray[0]; - - let fetchResult = await trashAlbum.getFileAssets([userfile_manager.MediaType.IMAGE], fetchOpt); - let count = fetchResult.getCount(); - console.info('fetchResult.count = ', count); +async function example() { + console.info('privateAlbumRecoverDemoPromise') + let albumList = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + const trashAlbum = await albumList.getFirstObject(); + let fetchResult = await trashAlbum.getPhotoAssets(fetchOption); + const fileAsset = await fetchResult.getFirstObject(); + let recoverFileUri = fileAsset.uri; + trashAlbum.recover(recoverFileUri).then(() => { + console.info('trashAlbum.recover successfully'); + }).catch((err) => { + console.info('trashAlbum.recover failed, message = ', err); + }); } ``` +## MemberType + +成员类型。 + +**系统能力:** 以下各项对应的系统能力均为SystemCapability.FileManagement.UserFileManager.DistributedCore + +| 名称 | 类型 | +| ----- | ---- | +| number | number | +| string | string | +| boolean | boolean | + +## ChangeEvent + +变更监听的媒体文件类型。 + +**系统能力:** 以下各项对应的系统能力均为SystemCapability.FileManagement.UserFileManager.DistributedCore + +| 名称 | 说明 | +| ----- | ---- | +| deviceChange | 设备 | +| albumChange | 相册 | +| imageChange | 图片 | +| audioChange | 音频 | +| videoChange | 视频 | +| remoteFileChange | 远程文件 | + ## PeerInfo 注册设备的信息。 -此接口为系统接口。 **系统能力:** 以下各项对应的系统能力均为SystemCapability.FileManagement.UserFileManager.DistributedCore @@ -2393,33 +2253,31 @@ async function virtualAlbumGetFileAssetsDemoPromise() { | networkId | string | 是 | 否 | 注册设备的网络ID | | isOnline | boolean | 是 | 否 | 是否在线 | -## MediaType -枚举,媒体类型。 +## FileType + +枚举,媒体文件类型。 **系统能力:** 以下各项对应的系统能力均为SystemCapability.FileManagement.UserFileManager.Core | 名称 | 说明 | | ----- | ---- | -| FILE | 文件 | | IMAGE | 图片 | | VIDEO | 视频 | | AUDIO | 音频 | -## FileKey +## PrivateAlbumType -枚举,文件关键信息。 +枚举,系统相册类型。 **系统能力:** 以下各项对应的系统能力均为SystemCapability.FileManagement.UserFileManager.Core -| 名称 | 默认值 | 说明 | -| ------------- | ------------------- | ---------------------------------------------------------- | -| URI | uri | 文件uri | -| RELATIVE_PATH | relative_path | 相对公共目录路径 | -| DISPLAY_NAME | display_name | 显示名字 | -| DATE_ADDED | date_added | 添加日期(添加文件时间到1970年1月1日的秒数值) | -| DATE_MODIFIED | date_modified | 修改日期(修改文件时间到1970年1月1日的秒数值) | -| TITLE | title | 文件标题 | +| 名称 | 说明 | +| ----- | ---- | +| TYPE_FAVORITE | 收藏夹相册 | +| TYPE_TRASH | 回收站相册 | + + ## AudioKey @@ -2430,7 +2288,6 @@ async function virtualAlbumGetFileAssetsDemoPromise() { | 名称 | 默认值 | 说明 | | ------------- | ------------------- | ---------------------------------------------------------- | | URI | uri | 文件uri | -| RELATIVE_PATH | relative_path | 相对公共目录路径 | | DISPLAY_NAME | display_name | 显示名字 | | DATE_ADDED | date_added | 添加日期(添加文件时间到1970年1月1日的秒数值) | | DATE_MODIFIED | date_modified | 修改日期(修改文件时间到1970年1月1日的秒数值) | @@ -2438,6 +2295,7 @@ async function virtualAlbumGetFileAssetsDemoPromise() { | ARTIST | artist | 作者 | | AUDIOALBUM | audio_album | 专辑 | | DURATION | duration | 持续时间(单位:毫秒) | +| FAVORITE | favorite | 收藏 | ## ImageVideoKey @@ -2448,14 +2306,17 @@ async function virtualAlbumGetFileAssetsDemoPromise() { | 名称 | 默认值 | 说明 | | ------------- | ------------------- | ---------------------------------------------------------- | | URI | uri | 文件uri | -| RELATIVE_PATH | relative_path | 相对公共目录路径 | +| FILE_TYPE | file_type | 媒体文件类型 | | DISPLAY_NAME | display_name | 显示名字 | | DATE_ADDED | date_added | 添加日期(添加文件时间到1970年1月1日的秒数值) | | DATE_MODIFIED | date_modified | 修改日期(修改文件时间到1970年1月1日的秒数值) | +| TITLE | title | 文件标题 | | DURATION | duration | 持续时间(单位:毫秒) | | WIDTH | width | 图片宽度(单位:像素) | | HEIGHT | height | 图片高度(单位:像素) | | DATE_TAKEN | date_taken | 拍摄日期(文件拍照时间到1970年1月1日的秒数值) | +| ORIENTATION | orientation | 图片文件的方向 | +| FAVORITE | favorite | 收藏 | ## AlbumKey @@ -2466,56 +2327,30 @@ async function virtualAlbumGetFileAssetsDemoPromise() { | 名称 | 默认值 | 说明 | | ------------- | ------------------- | ---------------------------------------------------------- | | URI | uri | 相册uri | -| RELATIVE_PATH | relative_path | 相对公共目录路径 | -| DISPLAY_NAME | display_name | 显示名字 | +| FILE_TYPE | file_type | 媒体文件类型 | +| ALBUM_NAME | album_name | 相册名字 | | DATE_ADDED | date_added | 添加日期(添加文件时间到1970年1月1日的秒数值) | | DATE_MODIFIED | date_modified | 修改日期(修改文件时间到1970年1月1日的秒数值) | -## DirectoryType -枚举,目录类型。 - -**系统能力:** 以下各项对应的系统能力均为SystemCapability.FileManagement.UserFileManager.Core - -| 名称 | 说明 | -| ------------- | ------------------ | -| DIR_CAMERA | 表示Camera文件路径 | -| DIR_VIDEO | 表示视频路径 | -| DIR_IMAGE | 表示图片路径 | -| DIR_AUDIO | 表示音频路径 | -| DIR_DOCUMENTS | 表示文档路径 | -| DIR_DOWNLOAD | 表示下载路径 | - -## MediaFetchOptions +## FetchOptions 检索条件。 **系统能力:** 以下各项对应的系统能力均为SystemCapability.FileManagement.UserFileManager.Core -| 名称 | 类型 | 可读 | 可写 | 必填 | 说明 | -| ----------------------- | ------------------- | ---- | ---- | ---- | ------------------------------------------------------------ | -| selections | string | 是 | 是 | 是 | 检索条件,使用[FileKey](#filekey)中的枚举值作为检索条件的列名。示例:
selections: mediaLibrary.FileKey.MEDIA_TYPE + '= ? OR' +mediaLibrary.FileKey.MEDIA_TYPE + '= ?‘, | -| selectionArgs | Array<string> | 是 | 是 | 是 | 检索条件的值,对应selections中检索条件列的值。
示例:
selectionArgs: [mediaLibrary.MediaType.IMAGE.toString(), mediaLibrary.MediaType.VIDEO.toString()], | - -## Size - -图片尺寸。 -**系统能力:** 以下各项对应的系统能力均为SystemCapability.FileManagement.UserFileManager.Core - -| 名称 | 类型 | 可读 | 可写 | 说明 | -| ------ | ------ | ---- | ---- | -------- | -| width | number | 是 | 是 | 宽(单位:像素) | -| height | number | 是 | 是 | 高(单位:像素) | +| 名称 | 类型 | 必填 | 说明 | +| ---------------------- | ------------------- | ---- |------------------------------------------------ | +| fetchColumns | Array<string> | 是 | 检索条件,指定列名查询,如果该参数为空时默认查询uri、name、fileType。示例:
fetchColumns: "uri"| +| predicates | [dataSharePredicates.DataSharePredicates](#../js-apis-data-dataSharePredicates.md) | 是 | 谓词查询,显示过滤条件 | -## VirtualAlbumType -枚举,系统相册或虚拟相册类型 +## AlbumFetchOptions -以下接口均为系统接口。 +相册检索条件。 **系统能力:** 以下各项对应的系统能力均为SystemCapability.FileManagement.UserFileManager.Core -| 名称 | 说明 | -| ------------- | ------------------ | -| TYPE_FAVORITE | 系统相册:收藏夹相册
该接口为系统接口。 | -| TYPE_TRASH | 系统相册:回收站相册
该接口为系统接口。 | +| 名称 | 类型 | 必填 | 说明 | +| ---------------------- | ------------------- | ---- |------------------------------------------------ | +| predicates | [dataSharePredicates.DataSharePredicates](#../js-apis-data-dataSharePredicates.md) | 是 | 谓词查询,显示过滤条件 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-window.md b/zh-cn/application-dev/reference/apis/js-apis-window.md index 2e652be786490c6796e8b9860aabd542ed5e5794..35bfb2ce17c34a439c404a78200f9b8a19a0a441 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-window.md +++ b/zh-cn/application-dev/reference/apis/js-apis-window.md @@ -777,10 +777,10 @@ on(type: 'systemBarTintChange', callback: Callback<SystemBarTintState>): v **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | --------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | 是 | 监听事件,固定为'systemBarTintChange',即导航栏、状态栏属性变化事件。 | -| callback | Callback<[SystemBarTintState](#systembartintstate)> | 是 | 回调函数。返回当前的状态栏、导航栏信息集合。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | 是 | 监听事件,固定为'systemBarTintChange',即导航栏、状态栏属性变化事件。 | +| callback | Callback<[SystemBarTintState](#systembartintstate8)> | 是 | 回调函数。返回当前的状态栏、导航栏信息集合。 | **示例:** @@ -806,10 +806,10 @@ off(type: 'systemBarTintChange', callback?: Callback<SystemBarTintState >) **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | --------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | 是 | 监听事件,固定为'systemBarTintChange',即导航栏、状态栏属性变化事件。 | -| callback | Callback<[SystemBarTintState](#systembartintstate)> | 否 | 回调函数。返回当前的状态栏、导航栏信息集合。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | 是 | 监听事件,固定为'systemBarTintChange',即导航栏、状态栏属性变化事件。 | +| callback | Callback<[SystemBarTintState](#systembartintstate8)> | 否 | 回调函数。返回当前的状态栏、导航栏信息集合。 | **示例:** @@ -1638,6 +1638,12 @@ resize(width: number, height: number, callback: AsyncCallback<void>): void 改变当前窗口大小,使用callback异步回调。 +应用主窗口与子窗口存在大小限制,宽度范围:[320, 2560],高度范围:[240, 2560],单位为vp。 + +系统窗口存在大小限制,宽度范围:[0, 2560],高度范围:[0, 2560],单位为vp。 + +设置的宽度与高度受到此约束限制。 + **系统能力:** SystemCapability.WindowManager.WindowManager.Core **参数:** @@ -1679,6 +1685,12 @@ resize(width: number, height: number): Promise<void> 改变当前窗口大小,使用Promise异步回调。 +应用主窗口与子窗口存在大小限制,宽度范围:[320, 2560],高度范围:[240, 2560],单位为vp。 + +系统窗口存在大小限制,宽度范围:[0, 2560],高度范围:[0, 2560],单位为vp。 + +设置的宽度与高度受到此约束限制。 + **系统能力:** SystemCapability.WindowManager.WindowManager.Core **参数:** @@ -4369,6 +4381,12 @@ resetSize(width: number, height: number, callback: AsyncCallback<void>): v 改变当前窗口大小,使用callback异步回调。 +应用主窗口与子窗口存在大小限制,宽度范围:[320, 2560],高度范围:[240, 2560],单位为vp。 + +系统窗口存在大小限制,宽度范围:[0, 2560],高度范围:[0, 2560],单位为vp。 + +设置的宽度与高度受到此约束限制。 + > **说明:** > > 从 API version 7开始支持,从API version 9开始废弃,推荐使用[resize()](#resize9)。 @@ -4401,6 +4419,12 @@ resetSize(width: number, height: number): Promise<void> 改变当前窗口大小,使用Promise异步回调。 +应用主窗口与子窗口存在大小限制,宽度范围:[320, 2560],高度范围:[240, 2560],单位为vp。 + +系统窗口存在大小限制,宽度范围:[0, 2560],高度范围:[0, 2560],单位为vp。 + +设置的宽度与高度受到此约束限制。 + > **说明:** > > 从 API version 7开始支持,从API version 9开始废弃,推荐使用[resize()](#resize9-1)。 diff --git a/zh-cn/application-dev/reference/arkui-js/js-components-basic-slider.md b/zh-cn/application-dev/reference/arkui-js/js-components-basic-slider.md index b7c5fdc2ae5372dde1cea4125843e0a59c381242..142d6c90300829ff945e86886b178c7a0b2fc86d 100644 --- a/zh-cn/application-dev/reference/arkui-js/js-components-basic-slider.md +++ b/zh-cn/application-dev/reference/arkui-js/js-components-basic-slider.md @@ -1,6 +1,7 @@ # slider > **说明:** +> > 从API version 4开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 滑动条组件,用来快速调节设置值,如音量、亮度等。 @@ -94,7 +95,7 @@ export default { } else if (e.mode == "end") { this.value = e.value; this.endValue = e.value; - } else if (e.mode == "click) { + } else if (e.mode == "click") { this.value = e.value; this.currentValue = e.value; } diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-image.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-image.md index e8e04417715a97e95f834d5f3002f9b06c0642dc..95ea376b2a4dec554b07cc11bcb75c95eff7dbf1 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-image.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-image.md @@ -320,7 +320,7 @@ struct ImageExample3 { .onError(() => { console.log('load image fail') }) - .overlay('\nwidth: ' + String(this.width) + ' height: ' + String(this.height), { + .overlay('\nwidth: ' + String(this.widthValue) + ' height: ' + String(this.heightValue), { align: Alignment.Bottom, offset: { x: 0, y: 20 } }) diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-badge.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-badge.md index 43487f3c6d291a02fdc8526423500110b6887bc8..f22276a4149d4b76c62151cd5ca19dd0579ca9f3 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-badge.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-badge.md @@ -51,7 +51,7 @@ | ---------- | ------------------------------------------ | ---- | ----------- | ------------------------------------------- | | color | [ResourceColor](ts-types.md#resourcecolor) | 否 | Color.White | 文本颜色。 | | fontSize | number \| string | 否 | 10 | 文本大小,单位vp。 | -| badgeSize | number \| string | 否 | 16 | Badge的大小,单位vp。不支持百分比形式设置。 | +| badgeSize | number \| string | 否 | 16 | Badge的大小,单位vp。不支持百分比形式设置。当设置为非法值时,按照默认值处理。 | | badgeColor | [ResourceColor](ts-types.md#resourcecolor) | 否 | Color.Red | Badge的颜色。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-waterflow.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-waterflow.md index 4ca95460bcf93cc1c07c5ea44f8de0f412d43f86..425b58cef2a90d2c7089d5ce332e1ed77e5d3153 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-waterflow.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-waterflow.md @@ -25,7 +25,7 @@ WaterFlow(options?: {footer?: CustomBuilder, scroller?: Scroller}) | 参数名 | 参数类型 | 必填 | 参数描述 | | ---------- | ----------------------------------------------- | ------ | -------------------------------------------- | | footer | [CustomBuilder](ts-types.md#custombuilder8) | 否 | 设置WaterFlow尾部组件。 | - | scroller | [Scroller](ts-container-scroll.md#scroller) | 否 | 可滚动组件的控制器,与可滚动组件绑定。 | + | scroller | [Scroller](ts-container-scroll.md#scroller) | 否 | 可滚动组件的控制器,与可滚动组件绑定。
目前瀑布流仅支持Scroller组件的scrollToIndex接口。 | ## 属性 @@ -40,8 +40,21 @@ WaterFlow(options?: {footer?: CustomBuilder, scroller?: Scroller}) | itemConstraintSize | [ConstraintSizeOptions](ts-types.md#constraintsizeoptions) | 设置约束尺寸,子组件布局时,进行尺寸范围限制。 | | columnsGap | Length |设置列与列的间距。
默认值:0| | rowsGap | Length |设置行与行的间距。
默认值:0| -| layoutDirection | [FlexDirection](ts-appendix-enums.md#flexdirection) |设置布局的主轴方向。| +| layoutDirection | [FlexDirection](ts-appendix-enums.md#flexdirection) |设置布局的主轴方向。
默认值:FlexDirection.Column| +layoutDirection优先级高于rowsTemplate和columnsTemplate。根据layoutDirection设置情况,分为以下三种设置模式: + +- layoutDirection设置纵向布局(FlexDirection.Column 或 FlexDirection.ColumnReverse) + + 此时columnsTemplate有效(如果未设置,取默认值)。例如columnsTemplate设置为"1fr 1fr"、rowsTemplate设置为"1fr 1fr 1fr"时,瀑布流组件纵向布局,辅轴均分成横向2列。 + +- layoutDirection设置横向布局(FlexDirection.Row 或 FlexDirection.RowReverse) + + 此时rowsTemplate有效(如果未设置,取默认值)。例如columnsTemplate设置为"1fr 1fr"、rowsTemplate设置为"1fr 1fr 1fr"时,瀑布流组件横向布局,辅轴均分成纵向3列。 + +- layoutDirection未设置布局方向 + + 布局方向为layoutDirection的默认值:FlexDirection.Column,此时columnsTemplate有效。例如columnsTemplate设置为"1fr 1fr"、rowsTemplate设置为"1fr 1fr 1fr"时,瀑布流组件纵向布局,辅轴均分成横向2列。 ## 事件 @@ -79,8 +92,8 @@ export class WaterFlowDataSource implements IDataSource { private listeners: DataChangeListener[] = [] constructor() { - for (let i = 0; i <= 100; i++) { - this.dataArray.push(i); + for (let i = 0; i < 100; i++) { + this.dataArray.push(i) } } @@ -138,7 +151,7 @@ export class WaterFlowDataSource implements IDataSource { // 注销改变数据的控制器 unregisterDataChangeListener(listener: DataChangeListener): void { - const pos = this.listeners.indexOf(listener); + const pos = this.listeners.indexOf(listener) if (pos >= 0) { this.listeners.splice(pos, 1) } @@ -182,9 +195,9 @@ export class WaterFlowDataSource implements IDataSource { // 重新加载数据 public Reload(): void { - this.dataArray.splice(1, 1); - this.dataArray.splice(3, 2); - this.notifyDataReload(); + this.dataArray.splice(1, 1) + this.dataArray.splice(3, 2) + this.notifyDataReload() } } ``` @@ -200,8 +213,10 @@ struct WaterflowDemo { @State maxSize: number = 100 @State fontSize: number = 24 @State colors: number[] = [0xFFC0CB, 0xDA70D6, 0x6B8E23, 0x6A5ACD, 0x00FFFF, 0x00FF7F] - scroller: Scroller = new Scroller(); - datasource: WaterFlowDataSource = new WaterFlowDataSource(); + scroller: Scroller = new Scroller() + datasource: WaterFlowDataSource = new WaterFlowDataSource() + private itemWidthArray: number[] = [] + private itemHeightArray: number[] = [] // 计算flow item宽/高 getSize() { @@ -209,6 +224,18 @@ struct WaterflowDemo { return (ret > this.minSize ? ret : this.minSize) } + // 保存flow item宽/高 + getItemSizeArray() { + for (let i = 0; i < 100; i++) { + this.itemWidthArray.push(this.getSize()) + this.itemHeightArray.push(this.getSize()) + } + } + + aboutToAppear() { + this.getItemSizeArray() + } + @Builder itemFoot() { Column() { Text(`Footer`) @@ -232,8 +259,8 @@ struct WaterflowDemo { .objectFit(ImageFit.Fill) } } - .width(this.getSize()) - .height(this.getSize()) + .width(this.itemWidthtArray[item1]) + .height(this.itemHeightArray[item1]) .backgroundColor(this.colors[item % 5]) }, item => item) } @@ -261,4 +288,4 @@ struct WaterflowDemo { } ``` -![zh-cn_image_WaterFlow.gif](figures/waterflow.gif) \ No newline at end of file +![zh-cn_image_WaterFlow.gif](figures/waterflow.gif) diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-state-management.md b/zh-cn/application-dev/reference/arkui-ts/ts-state-management.md index 11fb2e197ce9d067af664db6c0b96028acce3663..b014e51db0a0cbfa071a32edd98ffbd4aa98e327 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-state-management.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-state-management.md @@ -47,7 +47,7 @@ SetAndLink\(propName: string, defaultValue: T): SubscribedAbstractProperty\(propName: string, defaultValue: S): SubscribedAbstractProperty\(propName: string, newValue: T): void | 类型 | 描述 | | ------- | ------------------------------------------------------------ | -| boolean | 如果已存在与给定键名字相同的属性,更新其值且返回true。如果不存在具有给定名称的属性,在LocalStorage中创建具有给定默认值的新属性,默认值必须是T类型。不允许undefined 或 null 返回true。 | +| boolean | 如果已存在与给定键名字相同的属性,更新其值且返回true。如果不存在具有给定名称的属性,在AppStorage中创建具有给定默认值的新属性,默认值必须是T类型。不允许undefined 或 null 返回true。 | ```ts let simple = AppStorage.SetOrCreate('simpleProp', 121) diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-backgroundBlurStyle.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-backgroundBlurStyle.md index 8ed865870ff7225f38bf74d900c6d39eee0dfc4b..cb368b39322eff4969717eafe7fd80cb7b1af116 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-backgroundBlurStyle.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-backgroundBlurStyle.md @@ -4,7 +4,9 @@ > **说明:** > ->从API Version 9开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 +> 从API Version 9开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 +> +> 此接口为系统接口。 ## 属性 diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-geoLocationManager.md b/zh-cn/application-dev/reference/errorcodes/errorcode-geoLocationManager.md new file mode 100644 index 0000000000000000000000000000000000000000..59e55fbac0939b26f787555c7d46be6bb9158b03 --- /dev/null +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-geoLocationManager.md @@ -0,0 +1,157 @@ +# 位置服务子系统错误码 + +## 3301000 位置服务不可用 + +**错误信息** + +Location service is unavailable. + +**错误描述** + +位置服务不可用,位置服务相关的接口无法调用. + +**可能原因** + +1.位置服务启动异常,导致应用和位置服务子系统通信失败,导致位置服务不可用. + +2.GNSS芯片初始化失败导致GNSS定位功能失效. + +3.网络定位服务异常,导致网络定位功能失效. + +**处理步骤** + +请停止调用该接口. + +## 3301100 位置功能的开关未开启导致功能失败 + +**错误信息** + +The location switch is off. + +**错误描述** + +位置功能的开关未开启导致功能失败. + +**可能原因** + +位置功能的开关未开启,导致持续定位,单次定位等基本功能不可用. + +**处理步骤** + +请提示用户开启位置功能的开关. + +## 3301200 定位失败,未获取到定位结果 + +**错误信息** + +Failed to obtain the geographical location. + +**错误描述** + +定位失败,未获取到定位结果. + +**可能原因** + +1.GNSS信号弱,导致定位超时. + +2.网络定位异常导致定位超时. + +**处理步骤** + +请重新发起定位请求. + +## 3301300 逆地理编码查询失败 + +**错误信息** + +Reverse geocoding query failed. + +**错误描述** + +逆地理编码查询失败. + +**可能原因** + +数据网络比较卡顿,导致端侧的请求发送失败或者云端的结果未返回到端侧. + +**处理步骤** + +请重试逆地理编码查询. + +## 3301400 地理编码查询失败 + +**错误信息** + +Geocoding query failed. + +**错误描述** + +地理编码查询失败. + +**可能原因** + +数据网络比较卡顿,导致端侧的请求发送失败或者云端的结果未返回到端侧. + +**处理步骤** + +请重试地理编码查询. + +## 3301500 区域信息(包含国家码)查询失败 + +**错误信息** + +Failed to query the area information. + +**错误描述** + +区域信息(包含国家码)查询失败. + +**可能原因** + +未查询到正确的区域信息. + +**处理步骤** + +请停止调用查询区域码的接口. + +## 3301600 地理围栏操作失败 + +**错误信息** + +Failed to operate the geofence. + +**错误描述** + +地理围栏操作失败,包含添加,删除,暂停和恢复等操作. + +**可能原因** + +1.GNSS芯片不支持地理围栏功能. + +2.底层业务逻辑异常导致操作地理围栏失败. + +**处理步骤** + +请停止调用地理围栏操作接口. + +## 3301700 请求无响应 + +**错误信息** + +No response to the request. + +**错误描述** + +某些异步请求需要用户点击按钮确认,或者需要GNSS芯片和网络服务器响应,这些场景下未收到响应导致业务失败. + +**可能原因** + +1.用户未点击按钮确认. + +2.GNSS芯片未响应. + +3.网络服务器未响应. + +**处理步骤** + +请停止调用相关接口. \ No newline at end of file diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-nfc.md b/zh-cn/application-dev/reference/errorcodes/errorcode-nfc.md new file mode 100644 index 0000000000000000000000000000000000000000..d6763eebdda0b57f0090abfd2da966f7d31dc40e --- /dev/null +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-nfc.md @@ -0,0 +1,44 @@ +# NFC错误码 + +## 3100101 + +**错误信息** + +NFC opening or closing state is abnormal in service. + +**错误描述** + +NFC服务内部执行NFC打开或关闭异常。 + +**可能原因** + +和NFC服务建立通信异常。 + +**处理步骤** + +重新执行打开或关闭NFC。 + +## 3100201 + +**错误信息** + +Tag running state is abnormal in service. + +**错误描述** + +NFC服务执行Tag业务逻辑遇到错误。 + +**可能原因** +1. Tag参数值和实际调用函数要求不匹配。 +2. Tag操作时,NFC状态是关闭的。 +3. Tag操作前,已经处在断开状态。 +4. Tag芯片返回错误状态或响应超时。 +5. 和NFC服务没有建立绑定关系,无法调用接口。 + +**处理步骤** +1. 检查NFC参数是否和所调用接口匹配。 +2. 打开设备NFC。 +3. 先调用连接,再执行读写操作。 +4. 重新触碰读取卡片。 +5. 退出应用后,重新读取卡片。 + diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/Readme-CN.md b/zh-cn/application-dev/reference/js-service-widget-ui/Readme-CN.md index 57c3e074bd6b50541a4c676d273bff1cb15aa4ff..6810c9398d6dd287ef1351e934b41a7198acb492 100644 --- a/zh-cn/application-dev/reference/js-service-widget-ui/Readme-CN.md +++ b/zh-cn/application-dev/reference/js-service-widget-ui/Readme-CN.md @@ -5,9 +5,9 @@ - 语法 - [HML语法参考](js-service-widget-syntax-hml.md) - [CSS语法参考](js-service-widget-syntax-css.md) - - [配置数据和事件](js-service-widget-configuration.md) - [多语言支持](js-service-widget-multiple-languages.md) - - [低版本兼容](js-service-widget-version-compatibility.md) + - [版本兼容适配](js-service-widget-version-compatibility.md) + - [设置主题样式](js-service-widget-theme.md) - 组件 - 通用 - [通用属性](js-service-widget-common-attributes.md) @@ -19,6 +19,7 @@ - [无障碍](js-service-widget-common-accessibility.md) - [原子布局](js-service-widget-common-atomic-layout.md) - 容器组件 + - [badge](js-service-widget-container-badge.md) - [div](js-service-widget-container-div.md) - [list](js-service-widget-container-list.md) - [list-item](js-service-widget-container-list-item.md) @@ -35,8 +36,5 @@ - [progress](js-service-widget-basic-progress.md) - [span](js-service-widget-basic-span.md) - [text](js-service-widget-basic-text.md) -- 自定义组件 - - [自定义组件基本用法](js-service-widget-custom-basic-usage.md) - - [自定义事件](js-service-widget-custom-events.md) - - [Props](js-service-widget-custom-props.md) +- [自定义组件使用说明](js-service-widget-custom-basic-usage.md) - [数据类型说明](js-service-widget-appendix-types.md) diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/figures/badgeSample.png b/zh-cn/application-dev/reference/js-service-widget-ui/figures/badgeSample.png new file mode 100644 index 0000000000000000000000000000000000000000..d28449df64e90d5f4bd9ac1243090fc13f9c2903 Binary files /dev/null and b/zh-cn/application-dev/reference/js-service-widget-ui/figures/badgeSample.png differ diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-common-mediaquery.md b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-common-mediaquery.md index 1caa03daece18dc5ad40254438e1618572e58717..2e044292a6c5cf5c7c1b2f137a82dc80d97f24e5 100644 --- a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-common-mediaquery.md +++ b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-common-mediaquery.md @@ -1,7 +1,7 @@ # 媒体查询 -媒体查询(Media Query)在移动设备上应用十分广泛,开发者经常需要根据设备的大致类型或者特定的特征和设备参数(例如屏幕分辨率)来修改应用的样式。为此媒体查询提供了如下功能: +媒体查询(MediaQuery)在移动设备上应用十分广泛,开发者经常需要根据设备的大致类型或者特定的特征和设备参数(例如屏幕分辨率)来修改应用的样式。为此媒体查询提供了如下功能: 1. 针对设备和应用的属性信息,可以设计出相匹配的布局样式。 diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-configuration.md b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-configuration.md deleted file mode 100644 index f139c9efc848cff2a6cabf5da8acd5a56699b8c3..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-configuration.md +++ /dev/null @@ -1,36 +0,0 @@ -# 配置数据和事件 - - -卡片使用json文件配置卡片使用的变量和事件,变量的声明在data字段下,事件的声明在actions字段下。 - - -示例: - - - -```json -{ - "data": { - "temperature": "35°C", - "city": "hangzhou" - }, - "actions": { - "routerEventName": { - "action": "router", - "abilityName": "com.example.myapplication.FormAbility", - "params": { - "message": "weather", - "temperature": "{{temperature}}" - } - }, - "messageEventName": { - "action": "message", - "params": { - "message": "weather update" - } - } - } -} -``` - -可参考示例:[input](./js-service-widget-basic-input.md)与[list](js-service-widget-container-list.md)等组件中的用法。 \ No newline at end of file diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-container-badge.md b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-container-badge.md new file mode 100644 index 0000000000000000000000000000000000000000..67d6e7a49f20c1e0d827f83a71b92b93fb8c9395 --- /dev/null +++ b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-container-badge.md @@ -0,0 +1,101 @@ +# badge + + +应用中如果有需用户关注的新事件提醒,可以采用新事件标记来标识。 + +> **说明:** +> +> 从API Version 8 开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 + + +## 子组件 + +仅支持单个子组件。 + + +## 属性 + +除支持[通用属性](js-service-widget-common-attributes.md)外,还支持如下属性: + +| 名称 | 类型 | 默认值 | 必填 | 描述 | +| -------- | -------- | -------- | -------- | -------- | +| placement | string | rightTop | 否 | 事件提醒的数字标记或者圆点标记的位置,可选值为:
- right:位于组件右边框。
- rightTop:位于组件边框右上角。
- left:位于组件左边框。 | +| count | number | 0 | 否 | 设置提醒的消息数,默认为0。当设置相应的提醒消息数大于0时,消息提醒会变成数字标记类型,未设置消息数或者消息数不大于0时,消息提醒将采用圆点标记。
说明:当数字设置为大于maxcount时,将使用maxcount显示。count属性最大支持整数值为2147483647。 | +| visible | boolean | false | 否 | 是否显示消息提醒,当收到新信息提醒时可以设置该属性为true,显示相应的消息提醒,如果需要使用数字标记类型,同时需要设置相应的count属性。 | +| maxcount | number | 99 | 否 | 最大消息数限制,当收到新信息提醒大于该限制时,标识数字会进行省略,仅显示maxcount+。
说明:maxcount属性最大支持整数值为2147483647。 | +| config | BadgeConfig | - | 否 | 设置新事件标记相关配置属性。 | +| label | string | - | 否 | 设置新事件提醒的文本值。
说明:使用该属性时,count和maxcount属性不生效。 | + +### BadgeConfig + +| 名称 | 类型 | 默认值 | 必填 | 描述 | +| -------- | -------- | -------- | -------- | -------- | +| badgeColor | <color> | #fa2a2d | 否 | 新事件标记背景色。 | +| textColor | <color> | #ffffff | 否 | 数字标记的数字文本颜色。 | +| textSize | <length> | 10px | 否 | 数字标记的数字文本大小。 | +| badgeSize | <length> | 6px | 否 | 圆点标记的大小。 | + + +## 样式 + +支持[通用样式](js-service-widget-common-styles.md)。 + + +## 事件 + +支持[通用事件](js-service-widget-common-events.md)。 + + +## 示例 + + ```html + +
+ + example + + + example + +
+ ``` + + ```css + /* xxx.css */ + .container { + flex-direction: column; + width: 100%; + align-items: center; + } + + .badge { + width: 80px; + height: 60px; + margin-top: 30px; + } + + .text1 { + background-color: #f9a01e; + font-size: 19fp; + } + + .text2 { + background-color: #46b1e3; + font-size: 19fp; + } + ``` + + ```json + { + "data":{ + "badgeconfig":{ + "badgeColor":"#0a59f7", + "textColor":"#ffffff", + "textSize":"9px", + "badgeSize": "14px" + } + } + } + ``` + +![badgeSample](figures/badgeSample.png) \ No newline at end of file diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-custom-basic-usage.md b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-custom-basic-usage.md index b32292dc65c4f008ad088f267dcb9d2b2ecb7f09..8b561ee6ed1b0d454514329d27640ee8a303abf7 100644 --- a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-custom-basic-usage.md +++ b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-custom-basic-usage.md @@ -1,11 +1,12 @@ -# 自定义组件基本用法 +# 自定义组件使用说明 > **说明:** +> > 从API Version 8 开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 - 自定义组件是用户根据业务需求,将已有的组件组合,封装成的新组件,可以在工程中多次调用,提高代码的可读性。自定义组件通过element引入到宿主页面,使用方法: +自定义组件是用户根据业务需求,将已有的组件组合,封装成的新组件,可以在工程中多次调用,提高代码的可读性。自定义组件通过element引入到宿主页面,使用方法: ```html @@ -18,10 +19,176 @@ - 事件绑定:自定义组件中绑定子组件事件使用(on|\@)child1语法,子组件中通过{action:"proxy", method: "eventName"}触发事件并进行传值,父组件执行bindParentVmMethod方法并接收子组件传递的参数。 - ## 自定义组件配置文件标签 | 属性 | 类型 | 描述 | | -------- | -------- | -------- | | data | Object | 页面的数据模型,类型是对象。属性名不能以$或_开头,不要使用保留字for, if, show, tid。 | | props | Array/Object | props用于组件之间的通信,可以通过<tag xxxx='value'>方式传递给组件;props名称必须用小写,不能以$或_开头,不要使用保留字for, if, show, tid。目前props的数据类型不支持Function。 | + + +## 添加自定义事件 + +自定义组件内支持自定义事件,该事件的标识需要action类型指定为proxy,事件名则通过method指定。使用该自定义组件的卡片页面可以通过该事件名注册相应的事件回调,当自定义组件内该自定义事件触发时,会触发卡片页面上注册的回调事件。 + +> **说明:** +> +> 事件名不支持大写字母。 + +**自定义子组件示例:** + +```html + +
+
+ +
+
+``` + +```css +/* comp.css */ +.container { + flex-direction:column; + background-color: green; + width: 100%; + height: 100%; +} + +.row-3 { + width: 100%; + height: 50px; + background-color: orange; + font-size:15px; +} +``` + +```json +{ + "data": { + }, + "actions": { + "buttonClicked": { + "action": "proxy", + "method":"event_1" + } + } +} +``` +**父组件示例:** + +```html + + + +
+ + +
+``` + +```css +/* xxx.css */ +.container { + background-color: red; + height: 500px; + width: 500px; +} +``` + +```json +{ + "data": { + }, + "actions": { + "click": { + "action": "message", + "params": { + "message": "click event" + } + }, + "buttonClick": { + "action": "message", + "params": { + "message": "click event 2" + } + } + } +} +``` + + +## props + +自定义组件可以通过props声明自定义属性,父组件通过设置属性向子组件传递参数。 + +### 添加默认值 + +子组件可以通过固定值default设置默认值,当父组件没有设置该属性时,将使用其默认值。此情况下props属性必须为对象形式,不能用数组形式,示例如下: + +```html + +
+
+
+ xiaoziti +
+
+ {{text}} +
+
+ {{textdata[0]}} +
+
+
+ +
+
+ +
+
+``` + +```json +{ + "data": { + "progress": { + "default": "80" + } + }, + "props": { + "textdata": { + "default": ["a","b"] + }, + "progress": { + "default": 60 + }, + "text": { + "default": "ha" + } + }, + "actions": { + "buttonClicked": { + "action": "proxy", + "method": "event_1" + } + } +} +``` + +引用子组件comp的父组件示例如下: + +```html + + + +
+ +
+``` + +### 数据单向性 + +父子组件之间数据的传递是单向的,只能从父组件传递给子组件,子组件不能直接修改父组件传递下来的值,可以将props传入的值用data接收后作为默认值,再对data的值进行修改。 + +更多说明请参考[props](../arkui-js/js-components-custom-props.md)文档。 \ No newline at end of file diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-custom-events.md b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-custom-events.md deleted file mode 100644 index 05287a5e1f56337015048392cdcc11e1cfa617d7..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-custom-events.md +++ /dev/null @@ -1,104 +0,0 @@ -# 自定义事件 - - -自定义组件内支持自定义事件,该事件的标识需要action类型指定为proxy,事件名则通过method指定。使用该自定义组件的卡片页面可以通过该事件名注册相应的事件回调,当自定义组件内该自定义事件触发时,会触发卡片页面上注册的回调事件。 - - -> **说明:** -> -> 事件名不支持大写字母。 - - -## 子组件comp示例: - - -```html - -
-
- -
-
-``` - - - -```css -/* comp.css */ -.container { - flex-direction:column; - background-color: green; - width: 100%; - height: 100%; -} - -.row-3 { - width: 100%; - height: 50px; - background-color: orange; - font-size:15px; -} -``` - - - -```json -{ - "data": { - }, - "actions": { - "buttonClicked": { - "action": "proxy", - "method":"event_1" - } - } -} -``` - - -## 卡片页面示例 - - -```html - - - -
- - -
-``` - - - -```css -/* xxx.css */ -.container { - background-color: red; - height: 500px; - width: 500px; -} -``` - - - -```j'so -{ - "data": { - }, - "actions": { - "click": { - "action": "message", - "params": { - "message": "click event" - } - }, - "buttonClick": { - "action": "message", - "params": { - "message": "click event 2" - } - } - } -} -``` diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-custom-props.md b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-custom-props.md deleted file mode 100644 index 992ed8445e6caf816393a346c18d43339b61640c..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-custom-props.md +++ /dev/null @@ -1,81 +0,0 @@ -# Props - - -自定义组件可以通过props声明属性,父组件通过设置属性向子组件传递参数。通过父组件向下传递参数的示例如下: - -## 添加默认值 - -子组件可以通过固定值default设置默认值,当父组件没有设置该属性时,将使用其默认值。此情况下props属性必须为对象形式,不能用数组形式,示例如下: - - - -```html - -
-
-
- xiaoziti -
-
- {{text}} -
-
- {{textdata[0]}} -
-
-
- -
-
- -
-
-``` - - - -```json -// comp.json -{ - "data": { - "progress": { - "default": "80" - } - }, - "props": { - "textdata": { - "default": ["a","b"] - }, - "progress": { - "default": 60 - }, - "text": { - "default": "ha" - } - }, - "actions": { - "buttonClicked": { - "action": "proxy", - "method": "event_1" - } - } -} -``` - - - -```html - - - -
- -
-``` - - -## 数据单向性 - -父子组件之间数据的传递是单向的,只能从父组件传递给子组件,子组件不能直接修改父组件传递下来的值,可以将props传入的值用data接收后作为默认值,再对data的值进行修改。 - -更多说明请参考[props](../arkui-js/js-components-custom-props.md)。 \ No newline at end of file diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-file.md b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-file.md index 9025d3ad8df2f64ca271fd3dd690c14ca575860d..d6102070dff485d382545b8bc5cfcb9fa8895fc9 100644 --- a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-file.md +++ b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-file.md @@ -25,7 +25,7 @@ JS服务卡片(entry/src/main/js/Widget)的典型开发目录结构如下: - .css结尾的CSS样式文件,这个文件用于描述页面样式。 -- .json结尾的JSON文件,这个文件用于配置卡片中使用的变量action事件。 +- .json结尾的JSON配置文件,这个文件用于配置卡片中使用的变量action事件。 各个文件夹的作用: @@ -41,11 +41,11 @@ JS服务卡片(entry/src/main/js/Widget)的典型开发目录结构如下: - 引用代码文件,需使用相对路径,比如:../common/style.css。 -- 引用资源文件,推荐使用绝对路径。比如:/common/xxx.png。 +- 引用资源文件,推荐使用绝对路径。比如:/common/test.png。 - 公共代码文件和资源文件推荐放在common下,通过规则1和规则2进行访问。 -- CSS样式文件中通过url()函数创建<url>数据类型,如:url(/common/xxx.png)。 +- CSS样式文件中通过url()函数创建<url>数据类型,如:url(/common/test.png)。 > **说明:** > 当代码文件A需要引用代码文件B时: diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-syntax-hml.md b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-syntax-hml.md index 6cd29b1341e3259773fd6212ac188137eec9ea18..e968c2208bd2a9c6b796be6f18223fd48137e50d 100644 --- a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-syntax-hml.md +++ b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-syntax-hml.md @@ -24,15 +24,16 @@ HML(OpenHarmony Markup Language)是一套类HTML的标记语言,通过组 ```html
- {{content}} - {{key1}} {{key2}} - key1 {{key1}} - {{flag1 && flag2}} - {{flag1 || flag2}} - {{!flag1}} + {{content}} + {{key1}} {{key2}} + key1 {{key1}} + {{flag1 && flag2}} + {{flag1 || flag2}} + {{!flag1}}
``` +卡片hml文件中的变量需要在json文件的data字段下进行声明: ```json { @@ -46,18 +47,17 @@ HML(OpenHarmony Markup Language)是一套类HTML的标记语言,通过组 } ``` - > **说明:** > - key值支持对象操作符和数组操作符,如{{key.value}}、{{key[0]}}。 > -> - 从 API Version 6 开始支持字符串拼接、逻辑运算和三元表达式。 +> - 支持字符串拼接、逻辑运算和三元表达式。 > - 字符串拼接: > - 支持变量跟变量:{{key1}}{{key2}}等 > - 支持常量跟变量: "my name is {{name}}, i am from {{city}}." "key1 {{key1}}" > - 逻辑运算: -> - 与:{{flag1 && flag2}}(仅支持两个boolean变量间的与) -> - 或:{{flag1 || flag2}} (仅支持两个boolean变量间的或) -> - 非:{{!flag1}} (仅支持boolean变量的非运行) +> - 与:{{flag1 && flag2}}(仅支持两个boolean变量间的与逻辑运算) +> - 或:{{flag1 || flag2}} (仅支持两个boolean变量间的或逻辑运算) +> - 非:{{!flag1}} (仅支持boolean变量的非逻辑运算) > - 三元表达式 > - {{flag? key1:key2}}(flag为boolean变量,key1和key2可以是变量,也可以是常量) > - 注意事项 @@ -66,7 +66,7 @@ HML(OpenHarmony Markup Language)是一套类HTML的标记语言,通过组 ## 事件绑定 -卡片仅支持click通用事件,事件的定义只能是直接命令式,事件定义必须包含action字段,用以说明事件类型。卡片支持两种事件类型:跳转事件(router)和消息事件(message)。跳转事件可以跳转到卡片提供方的OpenHarmony应用,消息事件可以将开发者自定义信息传递给卡片提供方。事件参数支持变量,变量以"{{}}"修饰。跳转事件中若定义了params字段,则在被拉起应用的onStart的intent中,可用"params"作为key将跳转事件定义的params字段的值取到。 +卡片的事件需要在json文件的actions字段下进行声明。卡片仅支持click通用事件,事件的定义只能是直接命令式,事件定义必须包含action字段,用以说明事件类型。卡片支持两种事件类型:跳转事件(router)和消息事件(message)。跳转事件可以跳转到卡片提供方的OpenHarmony应用,消息事件可以将开发者自定义信息传递给卡片提供方。事件参数支持变量,变量以"{{}}"修饰。跳转事件中若定义了params字段,则在被拉起应用的onStart的intent中,可用"params"作为key将跳转事件定义的params字段的值取到。 - 跳转事件格式 @@ -99,20 +99,7 @@ HML(OpenHarmony Markup Language)是一套类HTML的标记语言,通过组 | 选择器 | 类型 | 默认值 | 样例描述 | | ------ | ------ | -------- | ---------------------------------------- | | action | string | "router" | 事件类型。
- "router":用于应用跳转。
- "message":自定义点击事件。 | - | want | Object | - | 跳转目标应用的信息,参考want格式表。 | - - **表1** want格式 - - | 选择器 | 类型 | 默认值 | 样例描述 | - | ----------- | -------------------- | ------------ | ---------------------------------------- | - | bundleName | string | - | 表示包描述。如果在Want中同时指定了BundleName和AbilityName,则Want可以直接匹配到指定的Ability。 | - | abilityName | string | - | 表示待启动的Ability名称。 | - | action | string | - | 表示action选项描述。 | - | uri | string | - | 表示Uri描述。如果在Want中指定了Uri,则Want将匹配指定的Uri信息,包括scheme, schemeSpecificPart, authority和path信息。 | - | type | string | "text/plain" | 表示MIME type类型描述,比如:"text/plain" 、 "image/*"等。 | - | flags | number | - | 表示处理Want的方式。默认传数字,具体参考[flags说明](../apis/js-apis-featureAbility.md#flags说明)。 | - | entities | Array\ | - | 类别,用于指定Intent的操作类别。 | - | parameters | {[key: string]: any} | - | 表示WantParams描述。 | + | want | [Want](../apis/js-apis-application-Want.md) | - | 跳转目标应用的信息,参考want格式表。 | ```json diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-theme.md b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-theme.md new file mode 100644 index 0000000000000000000000000000000000000000..2373f60ab3dda52851ff3a6336ec8c5d93b4761d --- /dev/null +++ b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-theme.md @@ -0,0 +1,19 @@ +# 设置主题样式 + + +卡片目前支持修改的主题样式如下: + +| 名称 | 描述 | +| ------------------ | ----------------------------- | +| app_background | 设置卡片背景颜色。 | + + +修改主题样式需要在widget文件夹下手动创建与pages同级的resources文件夹,在widget/resources/styles/default.json文件中配置主题样式。例如,修改卡片默认的背景色为浅灰色: + +```json +{ + "style": { + "app_background": "#dcdcdc" + } +} +``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-version-compatibility.md b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-version-compatibility.md index 07b5eca24b2027f8b1045f9c3c74a4ea71bbe200..62f19723b84a962cbdc163e0e74f9d23fbe30e78 100644 --- a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-version-compatibility.md +++ b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-version-compatibility.md @@ -1,62 +1,39 @@ -# 低版本兼容 +# 版本兼容适配 卡片特性不断增加,使用了新特性的卡片,在不支持这些新特性的老系统上可能显示异常。可以在卡片工程中指定最小SDK版本,防止使用新特性的卡片推送安装在老的系统上。也可以参考本章节的内容,在卡片开发阶段做前向兼容适配。 - -> **说明:** -> -> 低版本兼容能力从 API Version 6 开始支持。 - - 开发者可以通过JSON配置文件配置前向兼容能力。该文件提供了apiVersion属性用于兼容版本,该字段和卡片配置文件的数据字段data、事件字段actions同级。在apiVersion标签下定义的内容会基于当前运行版本信息,覆盖原始的data标签内容。 示例如下: - -假设JS服务卡片框架从API Version 6开始,支持引用系统内置资源颜色,从API Version 7开始支持slider组件(仅用于举例,不代表实际情况),则可以按照如下的方式,做前向兼容。 - - +假设JS服务卡片框架从API Version 9开始,支持设置webp格式的图源(仅用于举例,不代表实际情况),则可以按照如下的方式,做前向兼容。 ```html -
- hello world - +
+
``` - -xxx.json配置文件: - - +JSON配置文件: ```json { "data": { - "myBackgroundColor": "#87ceeb", - "canUseSlider": "false" + "imageSrc": "defaultSrc.png" }, "apiVersion": { - "6": { - "myBackgroundColor": "@sys.color.fa_background" - }, - "7": { - "canUseSlider": "true" + "9": { + "imageSrc": "newSrc.webp" } } } ``` - JS服务卡片开发框架会根据应用中的配置及当前系统运行版本,选取最合适的数据。 +假设系统运行版本在8及以下,则实际解析的imageSrc值为defaultSrc.png; -假设系统运行版本在5及以下,则实际解析的myBackgroundColor值为\#87ceeb,canUseSlider值为false; - - -假设系统运行版本为6,则实际解析的myBackgroundColor值为\@sys.color.fa_background,canUseSlider值为false; - - -假设系统运行版本为7及以上,则实际解析的际解析的myBackgroundColor值为\@sys.color.fa_background,canUseSlider值为true。 +假设系统运行版本为9,则实际解析的imageSrc值为newSrc.webp。 diff --git a/zh-cn/application-dev/windowmanager/application-window-fa.md b/zh-cn/application-dev/windowmanager/application-window-fa.md index 77a1755900cdc27ab3ff42aa094d77270c9a1e9e..968540c91ddbf38ebc9ce853cb8a7dbe603a0568 100644 --- a/zh-cn/application-dev/windowmanager/application-window-fa.md +++ b/zh-cn/application-dev/windowmanager/application-window-fa.md @@ -136,16 +136,13 @@ 当不再需要某些子窗口时,可根据场景的具体实现逻辑,使用`destroy`接口销毁子窗口。 ```js - // 销毁子窗口。当不再需要某些子窗口时,可根据场景的具体实现逻辑,使用destroy接口销毁子窗口,此处以监听窗口区域外的点击事件实现子窗口的销毁。 - windowClass.on('touchOutside', () => { - console.info('touch outside'); - windowClass.destroy((err, data) => { - if (err.code) { - console.error('Failed to destroy the subwindow. Cause:' + JSON.stringify(err)); - return; - } - console.info('Succeeded in destroying the subwindow. Data: ' + JSON.stringify(data)); - }); + // 销毁子窗口。当不再需要某些子窗口时,可根据场景的具体实现逻辑,使用destroy接口销毁子窗口。 + windowClass.destroy((err, data) => { + if (err.code) { + console.error('Failed to destroy the subwindow. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in destroying the subwindow. Data: ' + JSON.stringify(data)); }); ``` diff --git a/zh-cn/application-dev/windowmanager/application-window-stage.md b/zh-cn/application-dev/windowmanager/application-window-stage.md index 22276bfd2365379cddbb9c32a8e7ef83008f66a2..1cb4e281f1c78336a50df42cbe79e1e5b7f120f0 100644 --- a/zh-cn/application-dev/windowmanager/application-window-stage.md +++ b/zh-cn/application-dev/windowmanager/application-window-stage.md @@ -127,11 +127,12 @@ class MainAbility extends Ability { ```ts import Ability from '@ohos.application.Ability' + let windowStage_ = null; + let sub_windowClass = null; class MainAbility extends Ability { - onWindowStageCreate(windowStage) { + showSubWindow() { // 1.创建应用子窗口。 - let sub_windowClass = null; - windowStage.createSubWindow("mySubWindow", (err, data) => { + windowStage_.createSubWindow("mySubWindow", (err, data) => { if (err.code) { console.error('Failed to create the subwindow. Cause: ' + JSON.stringify(err)); return; @@ -139,7 +140,7 @@ class MainAbility extends Ability { sub_windowClass = data; console.info('Succeeded in creating the subwindow. Data: ' + JSON.stringify(data)); // 1.获取已创建的应用子窗口。 - windowStage.getSubWindow((err, data) => { + windowStage_.getSubWindow((err, data) => { if (err.code) { console.error('Failed to obtain the subWindow. Cause:' + JSON.stringify(err)); return; @@ -178,16 +179,30 @@ class MainAbility extends Ability { console.info('Succeeded in showing the window. Data: ' + JSON.stringify(data)); }); }); - // 4.销毁子窗口。当不再需要子窗口时,可根据具体实现逻辑,使用destroy对其进行销毁。 - sub_windowClass.destroy((err, data) => { - if (err.code) { - console.error('Failed to destroy the window. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Succeeded in destroying the window. Data: ' + JSON.stringify(data)); - }); }) } + + destroySubWindow() { + // 4.销毁子窗口。当不再需要子窗口时,可根据具体实现逻辑,使用destroy对其进行销毁。 + sub_windowClass.destroy((err, data) => { + if (err.code) { + console.error('Failed to destroy the window. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in destroying the window. Data: ' + JSON.stringify(data)); + }); + } + + onWindowStageCreate(windowStage) { + windowStage_ = windowStage; + // 开发者可以在适当的时机,如主窗口上按钮点击事件等,创建子窗口。并不一定需要在onWindowStageCreate调用,这里仅作展示 + this.showSubWindow(); + } + + onWindowStageDestroy() { + // 开发者可以在适当的时机,如子窗口上点击关闭按钮等,销毁子窗口。并不一定需要在onWindowStageDestroy调用,这里仅作展示 + this.destroySubWindow(); + } }; ``` diff --git a/zh-cn/application-dev/windowmanager/window-overview.md b/zh-cn/application-dev/windowmanager/window-overview.md index 40d122f4bb00a706739c186d14f4cf5e4b8c5160..f98f6d42d9d1130daca4a0c30bed28babc0926e1 100644 --- a/zh-cn/application-dev/windowmanager/window-overview.md +++ b/zh-cn/application-dev/windowmanager/window-overview.md @@ -65,4 +65,8 @@ OpenHarmony的窗口模块将窗口界面分为系统窗口、应用窗口两种 ## 约束与限制 -在FA模型下,不支持系统窗口的相关开发。 +- 在FA模型下,不支持系统窗口的相关开发。 + +- 应用主窗口与子窗口存在大小限制,宽度范围:[320, 2560],高度范围:[240, 2560],单位为vp。 + +- 系统窗口存在大小限制,宽度范围:[0, 2560],高度范围:[0, 2560],单位为vp。 \ No newline at end of file diff --git a/zh-cn/device-dev/reference/hdi-apis/_input_dev_ability.md b/zh-cn/device-dev/reference/hdi-apis/_input_dev_ability.md index 09a32f7c4d89e3e74b1a3a232a213e1b5be07899..fc6af49701af96bf471528f33c670fabffa8f03e 100644 --- a/zh-cn/device-dev/reference/hdi-apis/_input_dev_ability.md +++ b/zh-cn/device-dev/reference/hdi-apis/_input_dev_ability.md @@ -25,7 +25,7 @@ Input设备的能力属性,存储支持事件的位图。用位的方式来表 | [ledCode](#ledcode) [[BITS_TO_UINT64](input.md#bitstouint64)(LED_CNT)] | 记录设备支持的指示灯的位图 | | [miscCode](#misccode) [[BITS_TO_UINT64](input.md#bitstouint64)(MSC_CNT)] | 记录设备支持的其他功能的位图 | | [soundCode](#soundcode) [[BITS_TO_UINT64](input.md#bitstouint64)(SND_CNT)] | 记录设备支持的声音或警报的位图 | -| [forceCode](#forcecode) [[BITS_TO_UINT64](input.md#bitstouint64)([HDF_FF_CNT](input.md#hdfffcnt))] | 记录设备支持的作用力功能的位图 | +| [forceCode](#forcecode) [[BITS_TO_UINT64](input.md#bitstouint64)([HDF_FF_CNT](input.md#hdf_ff_cnt))] | 记录设备支持的作用力功能的位图 | | [switchCode](#switchcode) [[BITS_TO_UINT64](input.md#bitstouint64)(SW_CNT)] | 记录设备支持的开关功能的位图 | | [keyType](#keytype) [[BITS_TO_UINT64](input.md#bitstouint64)(KEY_CNT)] | 按键状态的位图 | | [ledType](#ledtype) [[BITS_TO_UINT64](input.md#bitstouint64)(LED_CNT)] | LED状态的位图 | diff --git a/zh-cn/device-dev/reference/hdi-apis/display__vgu_8h.md b/zh-cn/device-dev/reference/hdi-apis/display__vgu_8h.md index 77ed4834405cd20597f9a5213cb25ccbfb6aa00b..46da91de2d965b8b6655f1a9fb1362f71e31503d 100644 --- a/zh-cn/device-dev/reference/hdi-apis/display__vgu_8h.md +++ b/zh-cn/device-dev/reference/hdi-apis/display__vgu_8h.md @@ -55,7 +55,7 @@ | -------- | -------- | | [VGUScalar](_display.md#vguscalar) | VGU标量 | | [VGUPixelFormat](_display.md#vgupixelformat) | 像素格式。 | -| [VGUBlendType](_display.mdvgublendtype) | 混合操作类型。 | +| [VGUBlendType](_display.md#vgublendtype) | 混合操作类型。 | ### 枚举 diff --git a/zh-cn/device-dev/subsystems/Readme-CN.md b/zh-cn/device-dev/subsystems/Readme-CN.md index 901db72406063e38d4675440075e1b915d050bc3..55484af986e76860b2bfa24072e8b689a45f2ff7 100644 --- a/zh-cn/device-dev/subsystems/Readme-CN.md +++ b/zh-cn/device-dev/subsystems/Readme-CN.md @@ -18,6 +18,7 @@ - [查看NinjaTrace](subsys-build-reference.md#查看ninjatrace) - [HAP编译构建指导](subsys-build-gn-hap-compilation-guide.md) - [ 常见问题](subsys-build-FAQ.md) +- [ArkCompiler](subsys-arkcompiler-guide.md) - [分布式远程启动](subsys-remote-start.md) - 图形图像 - [图形图像概述](subsys-graphics-overview.md) diff --git a/zh-cn/device-dev/subsystems/subsys-arkcompiler-guide.md b/zh-cn/device-dev/subsystems/subsys-arkcompiler-guide.md new file mode 100644 index 0000000000000000000000000000000000000000..71a7dd2efcee380a0fa471e8273a0737db874924 --- /dev/null +++ b/zh-cn/device-dev/subsystems/subsys-arkcompiler-guide.md @@ -0,0 +1,82 @@ +# ArkCompiler开发指导 + +## 概述 +ArkCompiler是一种统一编程平台,包含编译器、工具链、运行时等关键部件,支持高级语言在多种芯片的编译与运行,并支撑应用和服务运行在手机、个人电脑、平板、电视、汽车和智能穿戴等多种设备上的需求。 + +## 编译环境配置 +推荐操作系统Ubuntu18.04及以上。 + +1. 安装依赖工具。 + ```shell + sudo apt-get update && sudo apt-get install python ruby python3-pip git-lfs gcc-multilib g++-multilib zlib1g-dev libc++1 curl nodejs + ``` +2. 安装repo工具。 + ```shell + mkdir ~/bin/ + curl https://gitee.com/oschina/repo/raw/fork_flow/repo-py3 > ~/bin/repo + chmod a+x ~/bin/repo + export PATH=~/bin:$PATH + pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple requests + ``` +3. 下载源码。 + ```shell + repo init -u https://gitee.com/ark-standalone-build/manifest.git -b master + repo sync -c -j8 + repo forall -c 'git lfs pull' + ``` + +4. 安装编译器及二进制工具。 + ```shell + ./prebuilts_download.sh + ``` + +## 开发步骤 + +1. 生成编译产物ark_js_vm及js2abc。 + ```shell + python ark.py x64.release + ``` + - ark_js_vm:运行abc文件的可执行程序。 + - js2abc:将ArkTS文件转换生成ArkCompiler字节码文件的工具。 + +2. 将TypeScript文件转换为abc文件。 + ```shell + prebuilts/build-tools/common/nodejs/node-v12.18.4-linux-x64/bin/node --expose-gc out/x64.release/clang_x64/obj/arkcompiler/ets_frontend/ts2panda/build/src/index.js helloworld.ts --opt-level 0 + ``` + TypeScript用例文件helloworld.ts源码。 + ```JavaScript + declare function print(arg:any):string; + print("Hello world!"); + ``` + +3. 执行生成的abc文件。 + ```shell + out/x64.release/clang_x64/arkcompiler/ets_runtime/ark_js_vm helloworld.abc + ``` + abc文件:ArkCompiler字节码文件。 + + 执行结果: + ``` + Hello world! + ``` + +## 执行Test262测试套 +``` +python ark.py x64.release test262 +``` + +## 编译选项 + +交叉编译可根据目标选择不同平台,如在x64平台构建arm64目标平台,更多平台选择可参考下方获取更多编译说明。 +``` +python ark.py arm64.release +``` +编译模式选择,如在x64平台构建debug版本。 +``` +python ark.py x64.debug +``` +获取更多编译说明。 +``` +python ark.py --help +``` + diff --git a/zh-cn/release-notes/OpenHarmony-v3.2-beta3.md b/zh-cn/release-notes/OpenHarmony-v3.2-beta3.md index 16c8318d068221441622c4b6ac881424c84c6bde..a182e7442718d4e0205aebf6ad07c449a97b3907 100644 --- a/zh-cn/release-notes/OpenHarmony-v3.2-beta3.md +++ b/zh-cn/release-notes/OpenHarmony-v3.2-beta3.md @@ -167,7 +167,7 @@ DeviceProfile适配分布式数据库自动同步策略,以及采集信息补 | 语言编译运行时子系统 | 前端编译性能提升,如es2abc。
运行时性能提升优化,如ISA重构优化、汇编解释器、TSAOT等。
新增功能,如支持严格模式的ES2021、模块化支持、Runtime 调试调优增强、字节码热重载等。
具体如下:
I5MYM9 【新增规格】运行时多模块单abc文件合并适配
I59TAQ【新增规格】支持TSAOT优化编译器标准编译lowering和优化pass(规格)描述
I5OJ8Q【新增规格】IDE属性查看功能补齐已支持的2021规范定义的类型
I5ODV4 【新增特性】 支持字节码补丁文件卸载功能
I5OXSC 【新增特性】 支持字节码补丁文件加载功能
I5HNNZ 【新增特性】使能加载器的命名空间
I5HVQE  【新增特性】线程stacksize根据产品配置,增加stack pageguard保护
I5MCUF【增强特性】libc增加CAPI接口,支持pthread等符号
I5HVNH【新增特性】RM.006.增强动态库符号管理
I5HVQ0 【新增特性】RM.008.musl支持fortify功能
I5KT7X 【新增特性】RM.002.提供API头文件API检测功能
I5TB3Y 【新增特性】ABI默认使用emutls特性
I5R119  【增强特性】拆分加载器与libc内存使用
支持clang工具链的开源构建
I5MYM9【新增规格】前端编译工具链支持模块化编译
I5IKO1【新增规格】前端abc支持commonjs模块
I5RRAJ【新增规格】补丁文件源码识别工具
I5PRFT【新增规格】补丁字节码编译工具
I5RHDH【新增规格】支持方舟字节码热加载
I5RA7C【新增规格】支持strict模式2021
I5HRUY【新增规格】es2abc支持js转换方舟字节码 | NA | | 帐号&程序访问控制子系统 | 帐号服务新增用户身份认证服务;权限服务新增支持精准定位或模糊定位,以及其他能力增强;新增隐私管理服务。
主要涉及如下需求:
I5N90B【新增规格】应用帐号适配沙箱应用
I5N90O【新增规格】帐号子系统新增用户身份认证服务
I5NOQI【新增特性】权限服务支持精准定位或模糊定位
I5NT1X【新增特性】权限使用记录管理增强
I5NU8U【新增特性】权限弹框UX界面增强
I5P4IU【新增特性】新增隐私管理服务
I5P530【新增特性】位置服务使用状态管理 | NA | | 全球化子系统 | 新增支持翻译伪本地化能力。
涉及如下需求:
I4WLSJ 【新增特性】翻译伪本地化能力 | NA | -| Misc服务子系统 | 新增剪贴板、上传下载、锁屏、输入法框架等模块基础特性。
主要涉及如下需求:
I5JPMG 【request部件】【download】后台任务通知
I5NXHK 【input_method_fwk部件】输入法框架支持仅绑定输入法innerkits接口和独立控制软键盘显隐的js接口
I5NG2X 【theme_screenlock部件】支持特定系统应用请求锁定屏幕
I5IU1Z  支持向剪贴板数据增加图片内容的数据项
I5OGA3  支持设备级的跨设备剪贴板开关
I5NMKI 【pasteboard部件】支持向剪贴板数据增加二进制数据
I5MAMN  支持剪贴板数据范围限制在应用内
I5OX20 【input_method_fwk部件】输入法框架支持获取输入法扩展 | NA | +| Misc服务子系统 | 新增剪贴板、上传下载、锁屏、输入法框架等模块基础特性。
主要涉及如下需求:
I5JPMG 【request部件】【download】后台任务通知
I5NXHK 【input_method_fwk部件】输入法框架支持仅绑定输入法innerkits接口和独立控制软键盘显隐的js接口
I5NG2X 【theme_screenlock部件】支持特定系统应用请求锁定屏幕
I5IU1Z  支持向剪贴板数据增加图片内容的数据项
I5OGA3  支持剪贴板插件加载开关
I5NMKI 【pasteboard部件】支持向剪贴板数据增加二进制数据
I5MAMN  支持剪贴板数据范围限制在应用内
I5OX20 【input_method_fwk部件】输入法框架支持获取输入法扩展 | NA | | ArkUI子系统 | ArkUI组件能力增强;资源、媒体查询能力增强;内存、性能优化;DFX能力增强;工具链能力增强。
主要涉及如下需求:
I5IZZ7 【ace_engine_standard部件】panel组件支持单独设置每个角的borderRadius
I5JQ1R 【ace_engine_standard部件】支持图片复制粘贴
I5JQ3F 【ace_engine_standard部件】输入框能力增强
I5JQ3J 【ace_engine_standard部件】stack组件新增事件拓传机制
I5JQ54 【ace_engine_standard部件】指定控件获取焦点
I5MX7J 【ace_engine_standard部件】list列表支持左滑/右滑及回弹效果
I5MWS0 【ace_engine_standard部件】panel组件弹出高度通知给开发者
I5IZVY 【ace_engine_standard部件】键鼠接入时支持组件刷新
I5JQ5Y 【ace_engine_standard部件】走焦能力增强
I5IY7K 【新增需求】【ace_engine_standard部件】主题能力支持
I5MWTB 【ace_engine_standard部件】媒体查询支持vp查询
I5IZU9 【ace_engine_standard部件】ui_service常驻内存优化
I5JQ26 【ace_engine_standard部件】Vsync请求机制流程优化
I5JQ2O 【ace_engine部件】公共资源预加载
I5JQ2D 【ace_engine_standard部件】Move事件重采样优化
I5IZXS 【toolchain部件】DFX打印错误堆栈时支持显示开发者变量名称原文
I5IZYG 【toolchain部件】DFX打印错误堆栈时支持显示开发者变量名称原文
I5IZX0 【toolchain部件】编译支持解析$r新增bundleName和moduleName参数
I5J09I 【toolchain部件】\@Builder 支持export导出 | NA | API变更请参考: @@ -188,7 +188,7 @@ API变更请参考: | -------- | -------- | -------- | -------- | | ArkUI | [HealthyDiet:健康饮食](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/HealthyDiet) | 这是一个记录饮食和查看食物信息的应用,主要用于管理饮食健康。可以添加饮食信息,包括食物的种类、重量以及用餐时间,如早餐、 午餐、晚餐和夜宵,并能统计得到相应用餐时间的总热量值、总蛋白质、总脂肪和总碳水值,并且用柱状图的形式展示出来。 | eTS | | ArkUI | [MusicAlbum:一多音乐专辑主页](https://gitee.com/openharmony/applications_app_samples/tree/master/MultiDeviceAppDev/MusicAlbum) | 本示例展示了音乐专辑主页,使用一次开发多端部署中介绍的自适应布局能力和响应式布局能力进行多设备(或多窗口尺寸)适配,保证应用在不同设备或不同窗口尺寸下可以正常显示。 | eTS | -| 元能力、文件管理 | [Share:分享](https://gitee.com/openharmony/applications_app_samples/tree/master/Share/Share) | 分享的主要工作是实现:发送方将文本,链接,图片文件三种类型分享给三方应用,同时能够在三方应用中分别呈现出来。 | eTS | +| 元能力、文件管理 | [Share:分享](https://gitee.com/openharmony/applications_app_samples/tree/master/Share/CustomShare) | 分享的主要工作是实现:发送方将文本,链接,图片文件三种类型分享给三方应用,同时能够在三方应用中分别呈现出来。 | eTS | | 元能力 | [GalleryForm:图库卡片](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/GalleryForm) | 本示例是模拟图库卡片,实现对图库中的照片在卡片中显示,定时刷新卡片内容等功能。 | eTS | | ArkUI | [AppMarket:一多应用市场首页](https://gitee.com/openharmony/applications_app_samples/tree/master/MultiDeviceAppDev/AppMarket) | 本示例展示了应用市场首页,页面中包括Tab栏、运营横幅、精品应用、精品游戏等。 | eTS | | ArkUI | [Weather:一多天气](https://gitee.com/openharmony/applications_app_samples/tree/master/MultiDeviceAppDev/Weather) | 本示例展示一个天气应用界面,包括首页、城市管理、添加城市、更新时间弹窗,体现一次开发,多端部署的能力。 | eTS |