This article aims to deeply explore the technical details of the Huawei HarmonyOS Next system (as of API12 currently) in developing a multilingual e-commerce platform, and is summarized based on actual development practices. It mainly serves as a technical sharing and communication vehicle, and inevitably has omissions and errors. Colleagues are welcome to put forward valuable opinions and questions so that we can make progress together. This is original content, and any form of reproduction must indicate the source and the original author.
In today’s digital age, user privacy and data security are of great concern. The HarmonyOS Next system, with its innovative secure access mechanism, provides users with a more secure and convenient operation experience. Today, we will explore in depth the secure access mechanism of HarmonyOS Next, focusing on how the system Picker and security controls achieve precise permission management and control.
1. Overview of the HarmonyOS Next Secure Access Mechanism
The secure access mechanism of HarmonyOS Next aims to change the traditional way applications obtain user data, from extensive management to fine-grained control, ensuring that user privacy is fully protected. The system enables users to more precisely control the access permissions of applications to sensitive data through mechanisms such as the system Picker and security controls, achieving on-demand authorization and keeping the interaction between data and applications in a controlled state. It is like setting up intelligent checkpoints for user data, and only with the user’s explicit authorization can the application obtain the corresponding data resources.
2. System Picker: Convenient Resource Selection and Permission Isolation
(1) Concept and Function of System Picker
The system Picker is a system-level component provided by HarmonyOS Next, implemented by an independent process, and its function is similar to that of an intelligent resource selector. It allows applications to select specific resources, such as files, photos, contacts, etc., through user interaction without directly obtaining the relevant permissions. When an 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-selected resource without having to apply for the permission to read the entire resource library. It is like in a large library, an application does not need to obtain the borrowing permission for all books, but only needs the librarian (system Picker) to help the user pick out the required books (resources).
(2) Methods for 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 use FilePicker in the following way:
// Assume that the relevant Picker module has been imported
import { filePicker } from '@kit.SomeFilePickerKit';
async function openUserFile() {
try {
const fileUri = await filePicker.showOpenDialog({
// Parameters such as file type filters can be set. This is only an example.
filters: [
{
name: 'Documents',
extensions: ['txt', 'pdf', 'docx']
}
]
});
if (fileUri) {
// The user has selected a file, and the application can perform subsequent operations such as reading the file content based on the fileUri.
console.log('The file path selected by the user:', fileUri);
}
} catch (error) {
console.error('Failed to open the file picker:', error);
}
}
In the above code, by calling the filePicker.showOpenDialog()
method, a file selection dialog box is popped up. The user can select a file that meets the specified filter in the dialog box, and after the application obtains the file path (fileUri
) selected by the user, it can perform subsequent file operations.
-
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 based on the photoUri.
console.log('The photo path selected by the user:', photoUri);
}
} catch (error) {
console.error('Failed to open the photo picker:', error);
}
}
By calling the photoViewPicker.showPhotoPicker()
method, the application can launch the photo picker. After the user selects a photo, the application obtains the photo path (photoUri
) for subsequent processing.
-
Selecting Contacts (Contact Picker)
When an application needs to obtain contact information, for example, when a communication application adds a contact or selects a recipient when sending a message, the contact Picker can be used. The sample 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 the relevant information of the contact, such as the name, phone number, etc.
console.log('The contact selected by the user:', contact);
}
} catch (error) {
console.error('Failed to open the contact picker:', error);
}
}
After calling the contactPicker.showContactPicker()
method, the user can select the required contact in the contact picker, and the application obtains the contact object (contact
) and performs corresponding operations.
3. Security Controls: A Powerful Assistant for Temporary Authorization
(1) Concept and Types of Security Controls
Security controls are a set of special ArkUI components provided by HarmonyOS Next. They are integrated into the application interface in an intuitive and convenient way, realizing an authorization mode where the user clicks to permit. Currently, HarmonyOS Next provides three main security controls: the PasteButton (Paste Control), the SaveButton (Save Control), and the LocationButton (Location Control). These security controls provide users with more fine-grained permission control, making the application more flexible and secure when obtaining specific permissions.
(2) Functions and Usage Scenarios of the Three Security Controls
-
PasteButton (Paste Control)
– Function: The paste control is used to simplify the operation of an application reading clipboard data. When an application integrates the paste control, the user can click the control, and the application can read the clipboard data without a pop-up prompt, providing a more seamless user experience.
– Usage Scenario: Applicable to various scenarios where clipboard data needs to be read, such as quickly pasting copied text content in an input box. For example, on a login interface, the user can conveniently paste the account or password without the need for cumbersome long-press operations on the input box. -
SaveButton (Save Control)
– Function: The save control allows the user to temporarily obtain storage permission by clicking the button and save the file to the media library. Unlike the traditional save method, it does not require the user to manually select the save path and directly saves the file to the specified media library path, making the operation faster.
– Usage Scenario: Commonly used in scenarios where files need to be saved to the media library, such as saving pictures and videos. For example, in a camera application, after the user takes a photo, clicking the save control can quickly save the photo to the album. -
LocationButton (Location Control)
– Function: The location control enables the user to clearly understand the intention of the application to obtain location information. When the user clicks the control, regardless of whether the application has applied for the precise location permission, it can obtain the precise location authorization during the current foreground period and call the location service to obtain the location information.
– Usage Scenario: Applicable to scenarios where non-strongly location-related applications need to use location information in some foreground scenarios, such as locating a city, clocking in, sharing a location, etc. For example, in a travel application, the user can click the location control to share the current location with friends.
### (3) Table of Security Control Usage Scenarios
| Security Control | Function | Usage Scenario |
|—|—|—|
| PasteButton (Paste Control) | Read clipboard data without a pop-up | Quickly paste text, such as pasting an account password on a login interface, etc. |
| SaveButton (Save Control) | Temporarily obtain storage permission to save a file to the media library | Save pictures and videos, such as saving a photo in a camera application, etc. |
| LocationButton (Location Control) | Click to obtain temporary precise location authorization | Locate a city, clock in, share a location, such as sharing a location in a travel application, etc. |
### (4) Example Code: Saving a Photo to the Media Library Using the SaveButton
The following is an example code for saving a photo to the media library using the SaveButton:
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { fileIo } from '@kit.CoreFileKit';
import { common } from '@kit.AbilityKit';
import { promptAction } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';
// Function to save a photo to the media library
async function savePhotoToGallery(context: common.UIAbilityContext) {
let helper = photoAccessHelper.getPhotoAccessHelper(context);
try {
// Create a photo file resource path. Here, the default photo type and format are used. In actual applications, it can be adjusted according to requirements.
let uri = await helper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'jpg');
// Open the file and prepare to write content.
let file = await fileIo.open(uri, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
// Assume there is a photo resource here. In actual applications, it should be replaced with a real photo resource.
context.resourceManager.getMediaContent($r('app.media.startIcon').id, 0)
.then(async value => {
let media = value.buffer;
// Write the photo data to the media library file.
await fileIo.write(file.fd, media);
await fileIo.close(file.fd);
promptAction.showToast({ message: 'Saved to the album!' });
});
} catch (error) {
const err: BusinessError = error as BusinessError;
console.error(`Failed to save the photo. Code is ${err.code}, message is ${err.message}`);
}
}
@Entry
@Component
struct Index {
build() {
Row() {
Column({ space: 10 }) {
// Assume there is already a photo component here for displaying the photo to be saved. In actual applications, it should be replaced with a real photo component.
Image($r('app.media.startIcon'))
.height(400)
.width('100%')
SaveButton()
.padding({ top: 12, bottom: 12, left: 24, right: 24 })
.onClick(async (event: ClickEvent, result: SaveButtonOnClickResult) => {
if (result === SaveButtonOnClickResult.SUCCESS) {
const context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
// When the save control is clicked, call the function to save the photo to the media library.
await savePhotoToGallery(context);
} else {
promptAction.showToast({ message: 'Failed to set permissions!' });
}
})
}
.width('100%')
}
.height('100%')
.backgroundColor(0xF1F3F5)
}
}
In the above code, first, a resource path (uri
) for a photo file is created through photoAccessHelper
. Then, the file is opened using fileIo
and prepared for writing data. Next, a photo resource is obtained (here, assumed to be $r('app.media.startIcon')
, which should be replaced with a real photo in actual applications), and it is written to the media library file. Finally, in the onClick
event handler of the SaveButton
, when the user clicks the save control and the authorization is successful, the savePhotoToGallery()
function is called to save the photo to the media library, and a corresponding prompt message is displayed according to the save result.
In conclusion, the secure access mechanism of HarmonyOS Next provides applications with a more secure and convenient way to access resources through the system Picker and security controls. We can rationally use these mechanisms according to the actual needs of the application to achieve precise permission management and control, improve the user experience, and protect user privacy. I hope this article can help colleagues better understand and use the secure access mechanism of HarmonyOS Next and create more secure and reliable applications for users.
Source link
lol