【木棉花】HarmonyOS电量卡片 原创 精华

木棉花_小蓝
发布于 2023-10-28 15:18
浏览
0收藏

介绍

本期笔者将分享一个基于ArkTS的HarmonyOS电量卡片开发案例,而案例实现的过程也是超级简单。



【木棉花】HarmonyOS电量卡片-鸿蒙开发者社区


【木棉花】HarmonyOS电量卡片-鸿蒙开发者社区


开发环境要求

● DevEco Studio版本:DevEco Studio 3.1 Release

● HarmonyOS SDK版本:API version 9

工程要求

● API9

● Stage模型


【木棉花】HarmonyOS电量卡片-鸿蒙开发者社区


正文

实现逻辑

电量卡片的开发逻辑非常简单,首先要在工程已有的模块中新建一个ArkTS卡片;接着在卡片对应的EntryFormAbility类中编写一个获取电池信息的成员方法,并重写onAddForm方法(这个方法会在卡片被创建时执行),使得formData(携带了设备的电池信息)经处理后传递给卡片页面的本地数据库;最后,在卡片页面中声明一些变量,将它们与本地数据库绑定,同时在UI描述中将变量所携带的数据(与电池信息相关)通过组件渲染出来。


代码结构

main
├─ module.json5
├─ resources
│  ├─ zh_CN
│  ├─ rawfile
│  │  ├─ charging.png
│  │  └─ logo.png
│  ├─ en_US
│  └─ base
│     ├─ profile
│     │  ├─ form_config.json
│     │  └─ main_pages.json
│     ├─ media
│     └─ element
└─ ets
   ├─ widget
   │  └─ pages
   │     └─ WidgetCard.ets
   ├─ pages
   │  └─ Index.ets
   ├─ entryformability
   │  └─ EntryFormAbility.ts
   └─ entryability
      └─ EntryAbility.ts


关键代码

form_config.json

{
  "forms": [
    {
      "name": "widget",
      "description": "This is a service widget.",
      "src": "./ets/widget/pages/WidgetCard.ets",
      "uiSyntax": "arkts",
      "window": {
        "designWidth": 720,
        "autoDesignWidth": true
      },
      "colorMode": "auto",
      "isDefault": true,
      "updateEnabled": true,
      "scheduledUpdateTime": "07:30",
      "updateDuration": 1,
      "defaultDimension": "2*2",
      "supportDimensions": [
        "2*2"
      ]
    }
  ]
}


EntryFormAbility.ts

import formInfo from '@ohos.app.form.formInfo';
import formBindingData from '@ohos.app.form.formBindingData';
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';

import formProvider from '@ohos.app.form.formProvider';

//导入电池信息模块
import batteryInfo from '@ohos.batteryInfo';

export default class EntryFormAbility extends FormExtensionAbility {
  onAddForm(want) {

    //初始化卡片所携带的数据
    let formData = this.getBatteryInfo()
    return formBindingData.createFormBindingData(formData);
  }

  onCastToNormalForm(formId) {

  }

  onUpdateForm(formId) {
    //更新卡片所携带的数据
		let data = formBindingData.createFormBindingData(this.getBatteryInfo())
    formProvider.updateForm(formId,data)
  }

  onChangeFormVisibility(newStatus) {

  }

  onFormEvent(formId, message) {

  }

  onRemoveForm(formId) {

  }

  onAcquireFormState(want) {
    return formInfo.FormState.READY;
  }

  //新声明一个成员方法, 通过batteryInfo模块获取电池信息
  private getBatteryInfo(){
    return {
      'BatterySOC':batteryInfo.batterySOC,
      'BatteryTemperature':batteryInfo.batteryTemperature*0.1,
      'ChargingStatus':batteryInfo.chargingStatus,
      'BatteryHealthState':batteryInfo.BatteryHealthState
    }
  }

};



Index.ets

//实例化LocalStorage
var Store = new LocalStorage()

@Entry(Store)
@Component
struct WidgetCard {
  /*
   * The title.
   */
  readonly TITLE: string = 'Hello World';

  /*
   * The action type.
   */
  readonly ACTION_TYPE: string = 'router';

  /*
   * The ability name.
   */
  readonly ABILITY_NAME: string = 'EntryAbility';

  /*
   * The message.
   */
  readonly MESSAGE: string = 'add detail';

  /*
   * The with percentage setting.
   */
  readonly FULL_WIDTH_PERCENT: string = '100%';

  /*
   * The height percentage setting.
   */
  readonly FULL_HEIGHT_PERCENT: string = '100%';

  //变量与本地数据库绑定
  @LocalStorageProp('BatterySOC') BatterySOC: number = 30
  @LocalStorageProp('BatteryTemperature') BatteryTemperature: number = 20
  @LocalStorageProp('ChargingStatus') ChargingStatus: boolean = true
  @LocalStorageProp('BatteryHealthState') BatteryHealthState: number = 1

  //用Array储存批量数据
  HealthState: Array<string> = ['正常', '未知', '过热', '过压', '低温', '僵死']

  build() {
    Row() {
      Column() {

        //Stack组件,使得其子组件可以层叠布局
        Stack() {

          //Progress组件用于实现进度条
          Progress({
            total: 100,
            value: this.BatterySOC,
            type: ProgressType.Capsule
          })
            .width('89%')
            .height(30)
            .color(Color.Pink)

          //电量文本和充电图标
          Row() {

            Text(this.BatterySOC + '%')
              .fontSize(14)
              .fontWeight(700)

            if (this.ChargingStatus) {
              Image($rawfile('charging.png'))
                .height(20)
                .width(10)
                .margin({
                  left: 2
                })
            }

          }

        }.layoutWeight(2)
        .width(this.FULL_WIDTH_PERCENT)

        Row() {

          //Image组件
          Image($rawfile('logo.png'))
            .height('60%')
            .margin({
              left: 6
            })
            .layoutWeight(2)

          Column({
            space: 7
          }) {

            Text('电池温度: ' + this.BatteryTemperature + '℃')
              .fontSize(10)
              .fontWeight(700)
              .margin({
                top: 19
              })

            Text('电池状态: ' + this.HealthState[this.BatteryHealthState])
              .fontSize(10)
              .fontWeight(700)

            if (this.ChargingStatus) {
              Text('正在充电')
                .fontSize(10)
                .fontWeight(700)
            } else {
              Text('正在耗电')
                .fontSize(10)
                .fontWeight(700)
            }

          }
          .height(this.FULL_HEIGHT_PERCENT)
          .layoutWeight(3)

        }.layoutWeight(3)
        .width(this.FULL_WIDTH_PERCENT)

      }
      .width(this.FULL_WIDTH_PERCENT)
    }
    .height(this.FULL_HEIGHT_PERCENT)
    .onClick(() => {
      postCardAction(this, {
        "action": this.ACTION_TYPE,
        "abilityName": this.ABILITY_NAME,
        "params": {
          "message": this.MESSAGE
        }
      });
    })
  }
}



结尾

文章所述仅代表个人理解,如有不足恳请读者不吝赐教。


【木棉花】HarmonyOS电量卡片-鸿蒙开发者社区

©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
Demo_51CTO_BatteryInfo.zip 731.27K 59次下载
已于2023-10-28 15:54:41修改
3
收藏
回复
举报
2条回复
按时间正序
/
按时间倒序
红叶亦知秋
红叶亦知秋

作者最近创作热情很高呀

回复
2023-10-28 16:05:55
木棉花_小蓝
木棉花_小蓝 回复了 红叶亦知秋
作者最近创作热情很高呀

最近比较有空qwq

回复
2023-10-28 16:25:25
回复
    相关推荐