HarmonyOS运动开发:如何选择并上传运动记录

##鸿蒙核心技术##运动开发##Core File Kit(文件基础服务)

前言

在运动类应用中,能够快速导入和分析其他应用的运动记录是一个极具吸引力的功能。这不仅为用户提供便利,还能增强应用的实用性和吸引力。本文将结合鸿蒙(HarmonyOS)开发实战经验,深入解析如何实现一个运动记录选择与上传功能,让运动数据的管理更加高效。

一、为什么需要运动记录上传功能

运动记录上传功能允许用户将其他应用(如 Keep)的运动数据导入到我们的应用中进行分析和管理。这不仅可以丰富我们的应用数据,还能为用户提供更全面的运动分析和建议。此外,通过上传功能,用户可以轻松备份和同步他们的运动记录,无论何时何地都能查看自己的运动历史。

二、核心功能实现

1.文件选择

为了实现文件选择功能,我们使用了鸿蒙的DocumentViewPickerAPI。以下是文件选择的核心代码:

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,我们可以轻松实现运动记录的选择功能。

相关推荐
二流小码农13 小时前
鸿蒙开发:router组件升级,彻底告别手动配置
android·ios·harmonyos
威哥爱编程21 小时前
模拟面试智能体开发实战 09:把面试官装进手机,鸿蒙端聊天界面用 SSE 流式输出让回复逐字滚出来
python·agent·harmonyos
威哥爱编程21 小时前
模拟面试智能体开发实战 10:配置写死在代码里还怎么换服务端,把设置和简历做成界面可配、可存
python·agent·harmonyos
Sirius_Ji2 天前
# 一份鸿蒙原生支持硬解的 ffmpeg 开发基座
harmonyos
贾伟康2 天前
HarmonyOS API 26 Navigation路由栈上限:stackSizeLimit、过载保护与容量观测
harmonyos·arkts·navigation·navpathstack·api26
江华森2 天前
把鸿蒙云手机调试的 5 个坑写成 Skill:12 项检查清单与报错决策树
harmonyos
木木子222 天前
用华为云码道构建校园导航应用「新生通」:从需求分析到工程落地
华为·华为云·harmonyos
贾伟康2 天前
HarmonyOS API 26 Navigation 自适应模式:mode、分栏切换与窗口断点治理
harmonyos·arkts·arkui·navigation·自适应布局
贾伟康2 天前
【转盘决定吧|07】HarmonyOS ArkTS 6.0.2.130 趣味题库:场景分类、随机选择与详情页解耦
harmonyos·arkts·路由·数据建模·arkui
贾伟康2 天前
【电路实验模拟|03】HarmonyOS ArkTS 交通灯实战:用定时状态切换红黄绿灯
harmonyos·arkts·canvas·arkui·交通灯