鸿蒙跨端计算器:多设备协同运算实现 原创

进修的泡芙
发布于 2025-6-18 21:02
浏览
0收藏

鸿蒙跨端计算器:多设备协同运算实现

本文将基于HarmonyOS 5的分布式能力和ArkUI框架,实现一个支持多设备协同的计算器应用。当主设备执行计算操作时,其他设备可以实时同步显示计算过程和结果。

技术架构
计算逻辑层:处理加减乘除运算和表达式解析

分布式同步层:通过分布式数据管理同步计算状态

UI展示层:响应式UI展示计算过程和结果

完整代码实现
计算器数据模型定义

// model/CalculatorState.ts
export class CalculatorState {
currentInput: string = ‘0’; // 当前输入
previousInput: string = ‘’; // 上一个输入
operation: string | null = null; // 当前操作符
result: string = ‘0’; // 计算结果
deviceId: string = ‘’; // 最后操作的设备ID

constructor(data?: Partial<CalculatorState>) {
if (data) {
Object.assign(this, data);
}

分布式计算同步服务

// service/CalculatorSyncService.ts
import distributedData from ‘@ohos.data.distributedData’;
import deviceInfo from ‘@ohos.deviceInfo’;

const STORE_ID = ‘calculator_sync_store’;
const CALCULATOR_KEY = ‘calculator_state’;

export class CalculatorSyncService {
private kvManager: distributedData.KVManager;
private kvStore: distributedData.SingleKVStore;
private localDeviceId: string = deviceInfo.deviceId;

// 初始化分布式数据存储
async init() {
const config = {
bundleName: ‘com.example.calculator’,
userInfo: {
userId: ‘defaultUser’,
userType: distributedData.UserType.SAME_USER_ID
};

this.kvManager = distributedData.createKVManager(config);
const options = {
  createIfMissing: true,
  encrypt: false,
  backup: false,
  autoSync: true,
  kvStoreType: distributedData.KVStoreType.SINGLE_VERSION
};

this.kvStore = await this.kvManager.getKVStore(STORE_ID, options);

// 订阅数据变更
this.kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_ALL, (data) => {
  this.handleDataChange(data);
});

// 处理数据变更

private handleDataChange(data: distributedData.ChangeNotification) {
if (data.insertEntries.length > 0 && data.insertEntries[0].key === CALCULATOR_KEY) {
const newState = JSON.parse(data.insertEntries[0].value.value);
AppStorage.setOrCreate(‘calculatorState’, new CalculatorState(newState));
}

// 同步计算器状态
async syncCalculatorState(state: CalculatorState) {
state.deviceId = this.localDeviceId;
await this.kvStore.put(CALCULATOR_KEY, JSON.stringify(state));
// 获取当前设备ID

getLocalDeviceId(): string {
return this.localDeviceId;
}

计算器逻辑服务

// service/CalculatorService.ts
import { CalculatorState } from ‘…/model/CalculatorState’;

export class CalculatorService {
private state: CalculatorState = new CalculatorState();
private syncService: CalculatorSyncService;

constructor(syncService: CalculatorSyncService) {
this.syncService = syncService;
// 处理数字输入

async inputDigit(digit: string) {
if (this.state.currentInput === ‘0’) {
this.state.currentInput = digit;
else {

  this.state.currentInput += digit;

await this.syncState();

// 处理小数点输入

async inputDecimal() {
if (!this.state.currentInput.includes(‘.’)) {
this.state.currentInput += ‘.’;
await this.syncState();
}

// 处理操作符输入
async inputOperator(op: string) {
if (this.state.operation && this.state.previousInput) {
await this.calculate();
this.state.previousInput = this.state.currentInput;

this.state.currentInput = '0';
this.state.operation = op;
await this.syncState();

// 执行计算

async calculate() {
if (!this.state.operation || !this.state.previousInput) return;

const prev = parseFloat(this.state.previousInput);
const current = parseFloat(this.state.currentInput);
let result: number;

switch (this.state.operation) {
  case '+':
    result = prev + current;
    break;
  case '-':
    result = prev - current;
    break;
  case '×':
    result = prev * current;
    break;
  case '÷':
    result = prev / current;
    break;
  default:
    return;

this.state.result = result.toString();

this.state.previousInput = '';
this.state.currentInput = this.state.result;
this.state.operation = null;
await this.syncState();

// 清除计算器状态

async clear() {
this.state = new CalculatorState();
await this.syncState();
// 同步状态到其他设备

private async syncState() {
await this.syncService.syncCalculatorState(this.state);
// 获取当前状态

getState(): CalculatorState {
return this.state;
}

计算器页面实现

// pages/CalculatorPage.ets
import { CalculatorService } from ‘…/service/CalculatorService’;
import { CalculatorSyncService } from ‘…/service/CalculatorSyncService’;

@Entry
@Component
struct CalculatorPage {
private calculatorService: CalculatorService = new CalculatorService(new CalculatorSyncService());
@StorageLink(‘calculatorState’) calculatorState: CalculatorState = new CalculatorState();
@State isSynced: boolean = false;

async aboutToAppear() {
await this.calculatorService.syncService.init();
this.isSynced = true;
build() {

Column() {
  // 显示计算过程
  Row() {
    Text({this.calculatorState.previousInput} {this.calculatorState.operation || ''})
      .fontSize(18)
      .fontColor('#888888')
      .layoutWeight(1)
      .textAlign(TextAlign.End)

.width(‘90%’)

  .margin({ top: 20 })

  // 显示当前输入/结果
  Row() {
    Text(this.calculatorState.currentInput)
      .fontSize(36)
      .fontWeight(FontWeight.Bold)
      .layoutWeight(1)
      .textAlign(TextAlign.End)

.width(‘90%’)

  .margin({ bottom: 20 })

  // 操作来源提示
  if (this.calculatorState.deviceId && 
      this.calculatorState.deviceId !== this.calculatorService.syncService.getLocalDeviceId()) {
    Text('来自其他设备的计算')
      .fontSize(12)
      .fontColor('#FF5722')

// 计算器按钮

  Grid() {
    GridItem() {
      CalculatorButton('C', () => this.calculatorService.clear())

GridItem() {

      CalculatorButton('⌫', () => { / 实现退格逻辑 / })

GridItem() {

      CalculatorButton('%', () => { / 实现百分比逻辑 / })

GridItem() {

      CalculatorButton('÷', () => this.calculatorService.inputOperator('÷'))

GridItem() {

      CalculatorButton('7', () => this.calculatorService.inputDigit('7'))

GridItem() {

      CalculatorButton('8', () => this.calculatorService.inputDigit('8'))

GridItem() {

      CalculatorButton('9', () => this.calculatorService.inputDigit('9'))

GridItem() {

      CalculatorButton('×', () => this.calculatorService.inputOperator('×'))

GridItem() {

      CalculatorButton('4', () => this.calculatorService.inputDigit('4'))

GridItem() {

      CalculatorButton('5', () => this.calculatorService.inputDigit('5'))

GridItem() {

      CalculatorButton('6', () => this.calculatorService.inputDigit('6'))

GridItem() {

      CalculatorButton('-', () => this.calculatorService.inputOperator('-'))

GridItem() {

      CalculatorButton('1', () => this.calculatorService.inputDigit('1'))

GridItem() {

      CalculatorButton('2', () => this.calculatorService.inputDigit('2'))

GridItem() {

      CalculatorButton('3', () => this.calculatorService.inputDigit('3'))

GridItem() {

      CalculatorButton('+', () => this.calculatorService.inputOperator('+'))

GridItem() {

      CalculatorButton('0', () => this.calculatorService.inputDigit('0'))

GridItem() {

      CalculatorButton('.', () => this.calculatorService.inputDecimal())

GridItem() {

      CalculatorButton('=', () => this.calculatorService.calculate())

}

  .columnsGap(10)
  .rowsGap(10)
  .width('90%')
  .margin({ top: 20 })

  // 同步状态指示器
  Row() {
    Circle()
      .width(10)
      .height(10)
      .fill(this.isSynced ? '#4CAF50' : '#F44336')
      .margin({ right: 5 })
    Text(this.isSynced ? '已连接' : '连接中...')
      .fontSize(12)

.margin({ top: 20 })

.width(‘100%’)

.height('100%')
.backgroundColor('#F5F5F5')

}

@Component
struct CalculatorButton {
private label: string;
private onClick: () => void;

build() {
Button(this.label)
.width(‘100%’)
.height(60)
.fontSize(24)
.fontColor(this.isOperator() ? ‘#FFFFFF’ : ‘#333333’)
.backgroundColor(this.isOperator() ? ‘#FF5722’ : ‘#FFFFFF’)
.borderRadius(8)
.onClick(() => this.onClick())
private isOperator(): boolean {

return ['+', '-', '×', '÷', '=', 'C', '⌫', '%'].includes(this.label);

}

计算器样式定义

// resources/base/element/calculator_styles.json
“calculator-button”: {

"width": "100%",
"height": 60,
"fontSize": 24,
"borderRadius": 8

},
“operator-button”: {
“extends”: “calculator-button”,
“fontColor”: “#FFFFFF”,
“backgroundColor”: “#FF5722”
},
“number-button”: {
“extends”: “calculator-button”,
“fontColor”: “#333333”,
“backgroundColor”: “#FFFFFF”
}

实现原理详解
分布式同步机制:

每个计算操作都会触发状态同步

通过分布式KVStore实时同步到其他设备

设备接收到更新后刷新UI
计算逻辑流程:

用户输入数字或操作符

更新本地计算器状态

同步状态到分布式数据库

其他设备接收并应用新状态
UI响应式更新:

使用@StorageLink绑定计算器状态

状态变更自动触发UI更新

显示操作来源设备信息

扩展功能建议
计算历史记录:

  // 在CalculatorService中添加历史记录

private history: string[] = [];

async addToHistory(expression: string) {
this.history.push(expression);
await this.syncHistory();

多设备协同计算:

  // 实现分布式计算任务分配

async distributeCalculation(task: string) {
await this.syncService.sendCalculationTask(task);

主题切换功能:

  // 添加主题切换支持

async switchTheme(theme: ‘light’ | ‘dark’) {
this.state.theme = theme;
await this.syncState();

总结

本文展示了如何利用HarmonyOS的分布式能力构建一个多设备协同的计算器应用。通过将计算器状态存储在分布式数据库中,实现了计算过程和结果的实时同步。这种架构不仅适用于计算器应用,也可以扩展到其他需要多设备协同的工具类应用。

©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
收藏
回复
举报
回复
    相关推荐