##鸿蒙核心技术##运动开发##Core File Kit(文件基础服务)
前言
在运动类应用中,能够快速导入和分析其他应用的运动记录是一个极具吸引力的功能。这不仅为用户提供便利,还能增强应用的实用性和吸引力。本文将结合鸿蒙(HarmonyOS)开发实战经验,深入解析如何实现一个运动记录选择与上传功能,让运动数据的管理更加高效。
一、为什么需要运动记录上传功能
运动记录上传功能允许用户将其他应用(如 Keep)的运动数据导入到我们的应用中进行分析和管理。这不仅可以丰富我们的应用数据,还能为用户提供更全面的运动分析和建议。此外,通过上传功能,用户可以轻松备份和同步他们的运动记录,无论何时何地都能查看自己的运动历史。
二、核心功能实现
1.文件选择
为了实现文件选择功能,我们使用了鸿蒙的DocumentViewPicker
API。以下是文件选择的核心代码:
typescript
async selectFile() {
if (this.isLoading) return;
this.isLoading = true;
try {
let context = getContext(this) as common.Context; // 请确保getContext(this)返回结果为UIAbilityContext
let documentPicker = new picker.DocumentViewPicker(context);
let documentSelectOptions = new picker.DocumentSelectOptions();
// 选择文档的最大数目(可选)
documentSelectOptions.maxSelectNumber = 1;
// 选择文件的后缀类型['后缀类型描述|后缀类型'](可选) 若选择项存在多个后缀名,则每一个后缀名之间用英文逗号进行分隔(可选),后缀类型名不能超过100,选择所有文件:'所有文件(*.*)|.*';
documentSelectOptions.fileSuffixFilters = ['图片(.png, .jpg)|.png,.jpg', '文档|.txt', '视频|.mp4', '.pdf','运动数据文件|.gpx,.tcx'];
const result = await documentPicker.select(documentSelectOptions);
if (result && result.length > 0) {
const fileUri = result[0];
this.selectedFilePath = fileUri;
// 获取文件名
this.fileName = fileUri.split('/').pop() || '未知文件';
// 获取文件大小
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 = '大小未知';
}
promptAction.showToast({ message: '文件选择成功', duration: 2000 });
}
} catch (err) {
console.error('Failed to select file. Cause: ' + (err as BusinessError).message);
promptAction.showToast({ message: '文件选择失败', duration: 2000 });
} finally {
this.isLoading = false;
}
}
核心点解析
• DocumentViewPicker
:用于选择文件的组件,支持多种文件类型。
• fileSuffixFilters
:设置可选择的文件类型,如图片、文档、视频等。
• fs.openSync
和fs.stat
:用于获取文件的大小和状态信息。
• promptAction.showToast
:用于显示提示信息,告知用户文件选择的结果。
2.文件上传
文件上传功能是将用户选择的文件上传到服务器进行进一步处理。这里就不多写了
三、用户界面设计
为了让用户能够方便地选择和上传文件,我们需要设计一个简洁直观的用户界面。以下是用户界面的核心代码:
typescript
@Builder
pageContentBuilder() {
Column() {
Text('选择运动记录的文件:')
.fontSize(20)
.margin({ top: 20, bottom: 10 })
.width('100%')
.textAlign(TextAlign.Center);
// 文件选择区域
Column() {
if (!this.selectedFilePath) {
Image($r('app.media.szxd_sport_home_setting_icon')) // 替换为你的文件图标资源
.width(80)
.height(80)
.margin({ bottom: 10 });
}
Text(this.selectedFilePath ? this.fileName : '请选择文件')
.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 });
// 文件信息展示
this.fileInfoBuilder();
// 选择文件按钮
Button(this.selectedFilePath ? '重新选择文件' : '选择文件')
.onClick(() => this.selectFile())
.width('60%')
.height(40)
.fontSize(16)
.backgroundColor('#007dff')
.borderRadius(8)
.opacity(this.isLoading ? 0.5 : 1)
.enabled(!this.isLoading);
// 上传按钮(如果有上传功能)
if (this.selectedFilePath) {
Button('上传文件')
.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);
}
核心点解析
• 文件选择区域:通过Image
和Text
组件展示文件选择的状态,用户点击时触发文件选择逻辑。
• 文件信息展示:通过Text
组件展示文件的名称和大小信息。
• 选择文件按钮:允许用户重新选择文件。
• 上传按钮:允许用户上传已选择的文件。
四、总结
通过鸿蒙的DocumentViewPicker
和相关文件操作 API,我们可以轻松实现运动记录的选择功能。