其乐融融的IT技术小站

HarmonyOS电量卡片

想了解更多关于开源的内容,请访问:

51CTO 开源基础软件社区

https://ost.51cto.com

介绍

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


开发环境要求

● DevEco Studio版本:DevEco Studio 3.1 Release

● HarmonyOS SDK版本:API version 9

工程要求

● API9

● Stage模型

正文

实现逻辑

电量卡片的开发逻辑非常简单,首先要在工程已有的模块中新建一个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 = ['正常', '未知', '过热', '过压', '低温', '僵死']

  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
        }
      });
    })
  }
}

想了解更多关于开源的内容,请访问:

51CTO 开源基础软件社区

https://ost.51cto.com

赞 ()
分享到:更多 ()

相关推荐

内容页底部广告位3
留言与评论(共有 0 条评论)
   
验证码: