HarmonyOS 6进阶:原子化服务与智能能力(2026版)

3 阅读5分钟

HarmonyOS 6进阶:原子化服务与智能能力(2026版)

基于 HarmonyOS 6.1 | 纯血鸿蒙 | 2025-2026 新体系

目录

  1. 原子化服务概述
  2. 创建原子化服务
  3. 卡片开发(Form)
  4. HarmonyOS Intelligence(AI能力)
  5. 智能体框架(2026新增)
  6. 实战案例:美食推荐原子化服务

原子化服务概述

什么是原子化服务?

原子化服务(Atomic Services) 是鸿蒙6的核心特性(2025-2026纯血鸿蒙战略重点)。

核心特点:

  • 免安装:用户无需下载安装,即点即用
  • 系统级入口:桌面、服务中心、搜索、语音等多入口
  • 主动服务:场景感知,主动推荐
  • 卡片化:支持桌面卡片、锁屏卡片等多形态展示

原子化服务 vs 传统应用:

特性传统应用原子化服务
安装方式应用市场下载免安装,即点即用
入口桌面图标多入口(桌面、搜索、语音等)
服务形态全功能应用轻量化服务
主动推荐不支持支持(场景感知)
开发框架UIAbilityUIAbility + FormExtension

原子化服务架构(HarmonyOS 6.1)

原子化服务
├── UIAbility(主界面)
├── FormExtensionAbility(卡片)
├── 服务中心入口
├── 搜索入口
└── 语音入口(小艺)

创建原子化服务

配置 module.json5

{
  "module": {
    "name": "entry",
    "type": "entry",
    "description": "原子化服务示例",
    "mainElement": "EntryAbility",
    "atomicService": {
      "preloads": [  // 预加载配置(2026新增)
        {
          "type": "form",
          "uri": "pages/FormPage"
        }
      ]
    },
    "abilities": [
      {
        "name": "EntryAbility",
        "srcEntry": "./ets/entryability/EntryAbility.ets",
        "description": "主能力",
        "visible": true,
        "exported": true,
        "skills": [
          {
            "entities": ["entity.system.home"],
            "actions": ["action.system.home"]
          }
        ]
      }
    ],
    "extensionAbilities": [
      {
        "name": "EntryFormAbility",
        "srcEntry": "./ets/entryformability/EntryFormAbility.ets",
        "description": "卡片能力",
        "type": "form",
        "exported": false,
        "metadata": [
          {
            "name": "ohos.extension.form",
            "resource": "$profile:form_config"
          }
        ]
      }
    ]
  }
}

卡片配置文件(resources/base/profile/form_config.json)

{
  "forms": [
    {
      "name": "widget",
      "description": "我的卡片",
      "type": "JS",
      "colorMode": "auto",
      "isDefault": true,
      "updateEnabled": true,
      "scheduledUpdateTime": "10:30",
      "updateDuration": 1,
      "defaultDimension": "2*2",
      "supportDimensions": [
        "1*2",
        "2*2",
        "2*4",
        "4*4"
      ]
    }
  ]
}

卡片开发(Form)

卡片生命周期

// entryformability/EntryFormAbility.ets
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'
import formBindingData from '@ohos.app.form.formBindingData'
import formProvider from '@ohos.app.form.formProvider'

export default class EntryFormAbility extends FormExtensionAbility {
  onAddForm(want: Want) {
    console.log('卡片添加:' + JSON.stringify(want))

    // 返回卡片数据
    const formData = {
      'title': '我的服务',
      'content': '点击使用',
      'count': 0
    }
    return formBindingData.createFormBindingData(formData)
  }

  onUpdateForm(formId: string) {
    console.log('卡片更新:' + formId)

    // 更新卡片数据
    const formData = formBindingData.createFormBindingData({
      'title': '我的服务',
      'content': '已更新 ' + new Date().toLocaleTimeString(),
      'count': Math.floor(Math.random() * 100)
    })

    formProvider.updateForm(formId, formData)
      .then(() => console.log('卡片更新成功'))
      .catch((err: BusinessError) => console.error('卡片更新失败:' + JSON.stringify(err)))
  }

  onRemoveForm(formId: string) {
    console.log('卡片移除:' + formId)
  }

  onFormEvent(formId: string, message: string) {
    console.log('卡片事件:' + formId + ',消息:' + message)

    // 处理卡片点击事件
    if (message === 'refresh') {
      this.onUpdateForm(formId)
    }
  }
}

卡片UI(ArkTS卡片,2026版)

// entryformability/pages/WidgetCard.ets
@Entry
@Component
struct WidgetCard {
  @StorageLink('title') title: string = '默认标题'
  @StorageLink('content') content: string = '默认内容'
  @StorageLink('count') count: number = 0

  build() {
    Column() {
      // 标题
      Text(this.title)
        .fontSize(16)
        .fontWeight(FontWeight.Bold)
        .margin({ bottom: 8 })

      // 内容
      Text(this.content)
        .fontSize(14)
        .fontColor('#666')
        .margin({ bottom: 12 })

      // 计数
      Text(`计数:${this.count}`)
        .fontSize(12)
        .fontColor('#409eff')

      // 操作按钮
      Row() {
        Button('刷新')
          .width(60)
          .height(30)
          .onClick(() => {
            // 触发卡片事件
            postCardAction(this, {
              action: 'message',
              params: {
                msg: 'refresh'
              }
            })
          })

        Button('打开应用')
          .width(80)
          .height(30)
          .margin({ left: 8 })
          .onClick(() => {
            // 打开主应用
            postCardAction(this, {
              action: 'router',
              params: {
                targetPage: 'pages/Index'
              }
            })
          })
      }
      .margin({ top: 8 })
    }
    .width('100%')
    .height('100%')
    .padding(12)
    .backgroundColor('#ffffff')
    .borderRadius(12)
  }
}

HarmonyOS Intelligence(AI能力)

端侧AI能力(2025-2026新增)

// 使用鸿蒙智能能力(HarmonyOS Intelligence)
import mindSporeLite from '@ohos.mindSporeLite'

@Entry
@Component
struct AIDemo {
  private context = getContext(this) as common.UIAbilityContext

  async runOnDeviceAI() {
    try {
      // 1. 加载本地AI模型(端侧推理,无需联网)
      const modelPath = this.context.filesDir + '/mymodel.ms'
      const model = await mindSporeLite.loadModel(modelPath)

      // 2. 准备输入数据
      const inputTensor: mindSporeLite.Tensor = {
        data: new Float32Array([1.0, 2.0, 3.0]),
        shape: [1, 3],
        dataType: mindSporeLite.DataType.FLOAT32
      }

      // 3. 执行推理
      const outputTensor = await model.predict([inputTensor])

      console.log('AI推理结果:' + JSON.stringify(outputTensor))

      // 4. 释放模型
      model.release()

    } catch (err) {
      console.error('AI推理失败:' + JSON.stringify(err))
    }
  }

  build() {
    Column() {
      Button('运行端侧AI推理')
        .onClick(() => this.runOnDeviceAI())
        .width('100%')
    }
    .padding(16)
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

接入小艺(Celia)智能助手(2026版)

// 注册小艺技能
import insightIntent from '@ohos.insightIntent'

@Entry
@Component
struct InsightIntentDemo {
  private context = getContext(this) as common.UIAbilityContext

  async registerInsightIntent() {
    try {
      // 注册意图(让用户可以通过小艺语音使用你的服务)
      const intent: insightIntent.Intent = {
        intentName: 'orderCoffee',
        domain: 'coffee',
        description: '点咖啡',
        parameters: [
          {
            name: 'type',
            description: '咖啡类型',
            required: true
          },
          {
            name: 'size',
            description: '杯型',
            required: false
          }
        ]
      }

      await insightIntent.registerIntent(this.context, intent)
      console.log('小艺技能注册成功')

    } catch (err) {
      console.error('注册失败:' + JSON.stringify(err))
    }
  }

  build() {
    Column() {
      Button('注册小艺技能')
        .onClick(() => this.registerInsightIntent())
        .width('100%')
    }
    .padding(16)
  }
}

智能体框架

创建智能体(Agent,2026新增)

// 智能体框架(HarmonyOS 6.1新增)
import agent from '@ohos.agent'

@Entry
@Component
struct AgentDemo {
  private context = getContext(this) as common.UIAbilityContext

  async createAgent() {
    try {
      // 创建智能体
      const myAgent: agent.AgentInfo = {
        name: 'MyAssistant',
        description: '我的智能助手',
        capabilities: [
          agent.Capability.TEXT_PROCESSING,
          agent.Capability.IMAGE_RECOGNITION
        ],
        model: 'gemma-2b'  // 端侧小模型(2026新增)
      }

      const agentInstance = await agent.createAgent(this.context, myAgent)

      // 与智能体对话
      const response = await agentInstance.chat('帮我写一段代码')
      console.log('智能体回复:' + response)

      // 释放智能体
      await agentInstance.release()

    } catch (err) {
      console.error('智能体创建失败:' + JSON.stringify(err))
    }
  }

  build() {
    Column() {
      Button('创建并使用智能体')
        .onClick(() => this.createAgent())
        .width('100%')
    }
    .padding(16)
  }
}

实战案例:美食推荐原子化服务

完整实现

// entryability/EntryAbility.ets
import UIAbility from '@ohos.app.ability.UIAbility'
import window from '@ohos.window'

export default class EntryAbility extends UIAbility {
  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
    console.log('美食推荐服务启动')
    
    // 从意图参数获取推荐类型
    const recommendType = want.parameters?.recommendType
    if (recommendType) {
      AppStorage.SetOrCreate('recommendType', recommendType)
    }
  }

  onWindowStageCreate(windowStage: window.WindowStage) {
    windowStage.loadContent('pages/Index')
  }
}
// pages/Index.ets
@Entry
@Component
struct FoodRecommendation {
  @State foodList: Array<{ name: string, rating: number, distance: number }> = [
    { name: '川菜馆', rating: 4.5, distance: 500 },
    { name: '粤菜厅', rating: 4.2, distance: 800 },
    { name: '快餐店', rating: 3.8, distance: 200 }
  ]
  @State recommendType: string = ''

  aboutToAppear() {
    // 获取推荐类型(从桌面图标/服务中心/搜索进入)
    this.recommendType = AppStorage.Get('recommendType') as string || 'nearby'
  }

  build() {
    Column() {
      // 标题
      Text('美食推荐')
        .fontSize(24)
        .fontWeight(FontWeight.Bold)
        .margin({ bottom: 16 })
      
      // 推荐类型
      if (this.recommendType === 'nearby') {
        Text('附近推荐')
          .fontSize(14)
          .fontColor('#409eff')
          .margin({ bottom: 12 })
      }

      // 列表
      List() {
        ForEach(this.foodList, (food: { name: string, rating: number, distance: number }) => {
          ListItem() {
            Row() {
              Column() {
                Text(food.name)
                  .fontSize(16)
                  .fontWeight(FontWeight.Bold)
                
                Text(`评分:${food.rating} | 距离:${food.distance}m`)
                  .fontSize(12)
                  .fontColor('#666')
                  .margin({ top: 4 })
              }
              .alignItems(HorizontalAlign.Start)

              Blank()

              Button('导航')
                .width(60)
                .height(30)
                .onClick(() => {
                  // 打开地图导航
                  const want: Want = {
                    bundleName: 'com.huawei.hmos.maps',
                    abilityName: 'MainAbility',
                    parameters: {
                      destination: food.name
                    }
                  }
                  getContext(this).startAbility(want)
                })
            }
            .width('100%')
            .padding(12)
          }
          .border({ width: { bottom: 1 }, color: '#eee' })
        }, (food: { name: string }) => food.name)
      }
      .width('100%')
      .layoutWeight(1)
    }
    .padding(16)
    .width('100%')
    .height('100%')
  }
}

卡片实现

// entryformability/EntryFormAbility.ets
export default class EntryFormAbility extends FormExtensionAbility {
  onAddForm(want: Want) {
    const formData = {
      'title': '美食推荐',
      'nearbyCount': 3,
      'topName': '川菜馆',
      'topRating': 4.5
    }
    return formBindingData.createFormBindingData(formData)
  }

  onFormEvent(formId: string, message: string) {
    if (message === 'viewMore') {
      // 打开主服务
      postCardAction(this, {
        action: 'router',
        params: {
          targetPage: 'pages/Index'
        }
      })
    }
  }
}
// entryformability/pages/WidgetCard.ets
@Entry
@Component
struct FoodWidgetCard {
  @StorageLink('title') title: string = ''
  @StorageLink('nearbyCount') nearbyCount: number = 0
  @StorageLink('topName') topName: string = ''
  @StorageLink('topRating') topRating: number = 0

  build() {
    Column() {
      Text(this.title)
        .fontSize(16)
        .fontWeight(FontWeight.Bold)

      Divider()
        .margin({ top: 8, bottom: 8 })

      Row() {
        Column() {
          Text(this.topName)
            .fontSize(14)
          
          Text(`评分:${this.topRating}`)
            .fontSize(12)
            .fontColor('#ff6b00')
        }
        .alignItems(HorizontalAlign.Start)

        Blank()

        Text(`附近${this.nearbyCount}家`)
          .fontSize(12)
          .fontColor('#409eff')
      }

      Button('查看更多')
        .width('100%')
        .height(30)
        .margin({ top: 8 })
        .onClick(() => {
          postCardAction(this, {
            action: 'message',
            params: {
              msg: 'viewMore'
            }
          })
        })
    }
    .padding(12)
    .width('100%')
    .height('100%')
    .backgroundColor('#fff')
    .borderRadius(12)
  }
}

总结

本文涵盖的2025-2026纯血鸿蒙进阶核心知识点:

  1. ✅ 原子化服务(免安装、多入口、主动服务)
  2. ✅ 卡片开发(FormExtensionAbility、ArkTS卡片)
  3. ✅ HarmonyOS Intelligence(端侧AI推理)
  4. ✅ 智能体框架(Agent,2026新增)
  5. ✅ 接入小艺(Cel ia)智能助手
  6. ✅ 实战:美食推荐原子化服务

参考资料


最后更新:2026年5月 | 基于 HarmonyOS 6.1