Practical HarmonyOS Sports Development: How to Select and Upload Sports Records
Foreword
In sports applications, the ability to quickly import and analyze sports records from other applications is a highly attractive feature. It not only provides convenience for users but also enhances the utility and appeal of the application. This article will combine practical HarmonyOS development experience to delve into how to implement a sports record selection and upload feature, making sports data management more efficient.
I. Why We Need Sports Record Upload Functionality
The sports record upload feature allows users to import sports data from other applications (such as Keep) into our application for analysis and management. This not only enriches our application data but also provides users with more comprehensive sports analysis and recommendations. Additionally, through the upload feature, users can easily back up and synchronize their sports records, allowing them to view their sports history anytime and anywhere.
II. Core Function Implementation
- File Selection
To implement the file selection feature, we used HarmonyOS's DocumentViewPicker
API. Below is the core code for file selection:
async selectFile() {
if (this.isLoading) return;
this.isLoading = true;
try {
let context = getContext(this) as common.Context; // Ensure getContext(this) returns a UIAbilityContext
let documentPicker = new picker.DocumentViewPicker(context);
let documentSelectOptions = new picker.DocumentSelectOptions();
// Maximum number of documents to select (optional)
documentSelectOptions.maxSelectNumber = 1;
// File suffix filters ['Suffix description|Suffix'] (optional) If there are multiple suffixes, separate each with a comma (optional), and the suffix name should not exceed 100 characters. To select all files: 'All files(*.*)|.*';
documentSelectOptions.fileSuffixFilters = ['Images(.png, .jpg)|.png,.jpg', 'Documents|.txt', 'Videos|.mp4', '.pdf', 'Sports data files|.gpx,.tcx'];
const result = await documentPicker.select(documentSelectOptions);
if (result && result.length > 0) {
const fileUri = result[0];
this.selectedFilePath = fileUri;
// Get the file name
this.fileName = fileUri.split('/').pop() || 'Unknown file';
// Get the file size
try {
let file = fs.openSync(fileUri, fs.OpenMode.READ_ONLY);
const stat = await fs.stat(file.fd);
this.fileSize = this.formatFileSize(stat.size);
} catch (error) {
console.error('Failed to get file size:', error);
this.fileSize = 'Size unknown';
}
promptAction.showToast({ message: 'File selection successful', duration: 2000 });
}
} catch (err) {
console.error('Failed to select file. Cause: ' + (err as BusinessError).message);
promptAction.showToast({ message: 'File selection failed', duration: 2000 });
} finally {
this.isLoading = false;
}
}
Core Points Analysis
DocumentViewPicker: A component used for file selection, supporting various file types.
fileSuffixFilters: Set the types of files that can be selected, such as images, documents, videos, etc.
fs.openSync and fs.stat: Used to get the size and status information of the file.
promptAction.showToast: Used to display a toast message to inform the user of the result of the file selection.
- File Upload
The file upload feature allows users to upload the selected file to the server for further processing. The details of this are not covered here.
III. User Interface Design
To enable users to conveniently select and upload files, we need to design a simple and intuitive user interface. Below is the core code for the user interface:
@Builder
pageContentBuilder() {
Column() {
Text('Select the file for sports records:')
.fontSize(20)
.margin({ top: 20, bottom: 10 })
.width('100%')
.textAlign(TextAlign.Center);
// File selection area
Column() {
if (!this.selectedFilePath) {
Image($r('app.media.szxd_sport_home_setting_icon')) // Replace with your file icon resource
.width(80)
.height(80)
.margin({ bottom: 10 });
}
Text(this.selectedFilePath ? this.fileName : 'Please select a file')
.fontSize(16)
.width('90%')
.height(40)
.backgroundColor('#f0f0f0')
.borderRadius(8)
.padding(10)
.textAlign(TextAlign.Center)
.margin({ bottom: 10 });
}
.width('90%')
.height(150)
.border({ width: 1, color: '#ddd', style: BorderStyle.Dashed })
.borderRadius(8)
.justifyContent(FlexAlign.Center)
.onClick(() => this.selectFile())
.margin({ bottom: 20 });
// File information display
this.fileInfoBuilder();
// Select file button
Button(this.selectedFilePath ? 'Re-select file' : 'Select file')
.onClick(() => this.selectFile())
.width('60%')
.height(40)
.fontSize(16)
.backgroundColor('#007dff')
.borderRadius(8)
.opacity(this.isLoading ? 0.5 : 1)
.enabled(!this.isLoading);
// Upload button (if upload functionality is available)
if (this.selectedFilePath) {
Button('Upload file')
.onClick(() => this.uploadFile())
.width('60%')
.height(40)
.fontSize(16)
.backgroundColor('#07c160')
.borderRadius(8)
.margin({ top: 20 })
.opacity(this.isLoading ? 0.5 : 1)
.enabled(!this.isLoading);
}
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Start)
.alignItems(HorizontalAlign.Center);
}
Core Points Analysis
File Selection Area: Display the status of file selection using
Image
andText
components, triggering file selection logic when the user clicks.File Information Display: Display the file's name and size information using
Text
components.Select File Button: Allows users to re-select a file.
Upload Button: Allows users to upload the selected file.
IV. Summary
Using HarmonyOS's DocumentViewPicker
and related file operation APIs, we can easily implement the feature for selecting sports records.
Top comments (0)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.