This article aims to deeply explore the technical details of the Huawei HarmonyOS Next system (up to API 12 as of now) in developing multilingual e-commerce platforms, and is summarized based on actual development practices. It mainly serves as a vehicle for technical sharing and communication. Mistakes and omissions are inevitable. Colleagues are welcome to put forward valuable opinions and questions so that we can make progress together. This article is original content, and any form of reprint must indicate the source and the original author.
In the security and user interaction system of HarmonyOS Next, the location control and the system Picker play unique and important roles. They respectively provide convenient and secure ways for applications to implement functions in terms of location acquisition and resource selection. Next, let's explore their functions and usage methods in depth.I. Location Control: A Temporary Authorization Assistant for Precise Location
(I) The Function of the Location Control
The location control provides applications with an intuitive and user-controllable way to obtain location information. In many applications today, the demand for location services is becoming increasingly diverse. However, not all applications need to continuously obtain precise locations for a long time or in the background. The emergence of the location control enables applications to obtain precise location authorization only when they are in the foreground and with the explicit knowledge and consent of the user, so as to obtain location information to complete the corresponding service functions. This not only meets the functional requirements of the application but, more importantly, fully respects the privacy of the user, allowing the user to decide for themselves when and where to share their location information.
(II) The Method of Obtaining Temporary Precise Location Authorization Using the Location Control
- Introduce Location Service Dependencies First, introduce the dependency modules related to location services in the application's code file. For example:
import { geoLocationManager } from '@kit.LocationKit';
This step is like building a bridge for obtaining location information, ensuring that the application can interact with the system's location services.
- Add the Location Control and Handle the Click Event Add the location control to the user interface layout of the application and handle its click event. The location control also consists of an icon, text, and a background. Developers can choose the appropriate style according to their needs. For example:
import { geoLocationManager } from '@kit.LocationKit';
import { promptAction } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';
// Function to obtain current location information
function getCurrentLocationInfo() {
const requestInfo: geoLocationManager.LocationRequest = {
'priority': geoLocationManager.LocationRequestPriority.FIRST_FIX,
'scenario': geoLocationManager.LocationRequestScenario.UNSET,
'timeInterval': 1,
'distanceInterval': 0,
'maxAccuracy': 0
};
try {
geoLocationManager.getCurrentLocation(requestInfo)
.then((location: geoLocationManager.Location) => {
promptAction.showToast({ message: JSON.stringify(location) });
})
.catch((err: BusinessError) => {
console.error(`Failed to get current location. Code is ${err.code}, message is ${err.message}`);
});
} catch (err) {
console.error(`Failed to get current location. Code is ${err.code}, message is ${err.message}`);
}
}
@Entry
@Component
struct Index {
build() {
Row() {
Column({ space: 10 }) {
LocationButton({
icon: LocationIconStyle.LINES,
text: LocationDescription.CURRENT_LOCATION,
buttonType: ButtonType.Normal
})
.padding({ top: 12, bottom: 12, left: 24, right: 24 })
.onClick((event: ClickEvent, result: LocationButtonOnClickResult) => {
if (result === LocationButtonOnClickResult.SUCCESS) {
// After successfully clicking the location control, call the function to obtain current location information
getCurrentLocationInfo();
} else {
promptAction.showToast({ message: 'Failed to obtain location information!' });
}
})
}
.width('100%')
}
.height('100%')
.backgroundColor(0xF1F3F5)
}
}
In the above code, we added the location control to the interface and, in the click event handling function of the location control, when the user clicks the location control and the authorization is successful, we call the getCurrentLocationInfo()
function to obtain the current location information.
-
Obtain and Process Location Information
In the
getCurrentLocationInfo()
function, by configuring theLocationRequest
parameters, we request the system location service to obtain the current location information. After successful acquisition, we can process the location information according to actual needs. For example, in the above example, we display the location information to the user in the form of a pop-up window throughpromptAction.showToast()
. ### (III) Display of Location Control Usage Limitations and Development Steps in a Table | Usage Limitations | Development Steps | |---|---| | When the user clicks the location control in the application for the first time, the system will pop up a window to request the user's authorization. If the user clicks "Cancel", clicking again will pop up the window again; if the user clicks "Allow", the application will be granted temporary location authorization, and no window will pop up when clicking again. The temporary authorization for precise location will last until any of the following situations occurs: the screen is turned off, the application is switched to the background, or the application exits. Then it will revert to the authorization state before the temporary authorization. There is no limit on the number of calls by the application during the authorization period. To protect user privacy, the application needs to ensure that the security control is visible and recognizable by the user, avoiding authorization failure due to control style issues. | 1. Introduce location service dependencies. 2. Add the location control and the processing logic for obtaining current location information to the interface. 3. In the click event handling function of the location control, obtain and process the location information. | ### (IV) Example Code: Obtaining the Current Location Using the Location Control The following is a complete example code of obtaining the current location using the location control:
import { geoLocationManager } from '@kit.LocationKit';
import { promptAction } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct Index {
build() {
Row() {
Column({ space: 10 }) {
LocationButton({
icon: LocationIconStyle.LINES,
text: LocationDescription.CURRENT_LOCATION,
buttonType: ButtonType.Normal
})
.padding({ top: 12, bottom: 12, left: 24, right: 24 })
.onClick((event: ClickEvent, result: LocationButtonOnClickResult) => {
if (result === LocationButtonOnClickResult.SUCCESS) {
const requestInfo: geoLocationManager.LocationRequest = {
'priority': geoLocationManager.LocationRequestPriority.FIRST_FIX,
'scenario': geoLocationManager.LocationRequestScenario.UNSET,
'timeInterval': 1,
'distanceInterval': 0,
'maxAccuracy': 0
};
try {
geoLocationManager.getCurrentLocation(requestInfo)
.then((location: geoLocationManager.Location) => {
promptAction.showToast({ message: JSON.stringify(location) });
})
.catch((err: BusinessError) => {
console.error(`Failed to get current location. Code is ${err.code}, message is ${err.message}`);
});
} catch (err) {
console_error(`Failed to get current location. Code is ${err.code}, message is ${err.message}`);
}
} else {
promptAction.showToast({ message: 'Failed to obtain location information!' });
}
})
}
.width('100%')
}
.height('100%')
.backgroundColor(0xF1F3F5)
}
}
In this example, after the user clicks the location control, if the authorization is successful, the application will obtain the current location information and display it to the user in the form of a pop-up window.
II. System Picker: A Powerful Tool for Secure Resource Selection
(I) The Concept and Function of the System Picker
The system Picker is a system-level component provided by HarmonyOS Next, implemented by an independent process. Its core function is to allow applications to select specific resources, such as files, photos, contacts, etc., through user interaction without directly obtaining relevant permissions. It is like an intelligent resource intermediary, building a secure bridge between the user and the application. When the application needs to access these resources, it only needs to launch the system Picker, and the user can perform the selection operation on the Picker interface. The application can then obtain the result of the user's selected resource without applying for the permission to read the entire resource library. This greatly improves the security and flexibility of resource access, while also optimizing the user experience.
(II) The Method of Selecting Different Resources Using the System Picker
- Selecting User Files (FilePicker) When an application needs to obtain user files, it can use FilePicker. For example, a document editing application that needs to open a user-specified document for editing can operate as follows:
// Assume that the relevant Picker modules have been imported
import { filePicker } from '@kit.SomeFilePickerKit';
async function openUserFile() {
try {
const fileUri = await filePicker.showOpenDialog({
// You can set parameters such as file type filters. Here is just an example.
filters: [
{
name: 'Documents',
extensions: ['txt', 'pdf', 'docx']
}
]
});
if (fileUri) {
// The user has selected a file, and the application can perform subsequent operations according to the fileUri, such as reading the file content.
console.log('The file path selected by the user:', fileUri);
}
} catch (error) {
console.error('Failed to open the file selector:', error);
}
}
In the above code, by calling the filePicker.showOpenDialog()
method, a file selector dialog box is popped up. The user can select a file that meets the specified filters in the dialog box. After the application obtains the file path (fileUri
) selected by the user, it can perform subsequent file operations, such as reading the file content for editing.
- Selecting Photos (PhotoViewPicker) For applications that need to obtain user photos, such as photo editing applications or social sharing applications, PhotoViewPicker can be used. Here is a simple example:
import { photoViewPicker } from '@kit.SomePhotoPickerKit';
async function selectUserPhoto() {
try {
const photoUri = await photoViewPicker.showPhotoPicker();
if (photoUri) {
// The user has selected a photo, and the application can perform operations such as displaying, editing, or sharing according to the photoUri.
console.log('The photo path selected by the user:', photoUri);
}
} catch (error) {
console.error('Failed to open the photo selector:', error);
}
}
By calling the photoViewPicker.showPhotoPicker()
method, the application can launch the photo selector. After the user selects a photo, the application obtains the photo path (photoUri
) for subsequent processing, such as loading the photo for editing in a photo editing application or sharing the selected photo in a social sharing application.
- Selecting Contacts (Contact Picker) When an application needs to obtain contact information, for example, when adding contacts or selecting recipients in a communication application, the Contact Picker can be used. The example code is as follows:
import { contactPicker } from '@kit.SomeContactPickerKit';
async function selectContact() {
try:
const contact = await contactPicker.showContactPicker();
if (contact) {
// The user has selected a contact, and the application can obtain relevant information about the contact, such as name, phone number, etc.
console.log('The contact selected by the user:', contact);
}
} catch (error) {
console.error('Failed to open the contact selector:', error);
}
}
After calling the contactPicker.showContactPicker()
method, the user can select the required contact in the contact selector. The application obtains the contact object (contact
) and performs corresponding operations, such as filling in the recipient information in a communication application or obtaining the detailed contact information for display.
(III) Display of System Picker Usage Limitations and Development Steps in a Table
Usage Limitations | Development Steps |
---|---|
The system Picker has obtained pre-authorization for corresponding permissions, but developers still need to follow the system security specifications when using it. | 1. Select the appropriate Picker according to needs (such as FilePicker, PhotoViewPicker, Contact Picker, etc.). 2. According to the API calling method of the corresponding Picker, launch the selector and handle the result of the user's selection. |
(IV) Example Code: Selecting Photos Using the PhotoViewPicker
The following is an example code of selecting photos using the PhotoViewPicker:
import { photoViewPicker } from '@kit.SomePhotoPickerKit';
@Entry
@Component
struct Index {
build() {
Row() {
Column({ space: 10 }) {
Button('Select Photos')
.onClick(async () => {
try {
const photoUri = await photoViewPicker.showPhotoPicker();
if (photoUri) {
console.log('The photo path selected by the user:', photoUri);
// Here, you can perform further processing on the selected photo, such as displaying the photo, uploading the photo, etc.
}
} catch (error) {
console.error('Failed to open the photo selector:', error);
}
})
}
.width('100%')
}
.height('100%')
}
}
In this example, after the user clicks the "Select Photos" button, the application will launch the photo selector. After the user selects a photo, the application obtains the photo path and prints it out on the console. Developers can perform further processing on the photo path according to actual needs, such as displaying the selected photo on the interface or uploading the photo to the server.
In conclusion, the location control and the system Picker in the HarmonyOS Next system provide powerful and secure function expansion capabilities for applications. By mastering their usage methods and precautions, we can improve the application's functions while better protecting user privacy and ensuring system security. We hope that through the introduction of this article, colleagues can use these functional components more efficiently to create higher-quality HarmonyOS Next applications.
Top comments (0)