>
2024 年华为发布 HarmonyOS NEXT(纯血鸿蒙),彻底摆脱 Android 兼容。2026 年 6 月,鸿蒙生态设备已超 12 亿台,是国内信创移动端的绝对主力。
鸿蒙在 AI 领域的三大优势:
本文手把手教你开发一个调用盘古大模型的鸿蒙原生 AI 应用。
# 1. 下载 DevEco Studio NEXT 5.0+
# 官方地址:https://developer.huawei.com/consumer/cn/deveco-studio/
# 2. 国内镜像(信创环境推荐)
wget https://mirrors.huaweicloud.com/deveco-studio/5.0.3.800/deveco-studio-5.0.3.800.exe
# 3. macOS
wget https://mirrors.huaweicloud.com/deveco-studio/5.0.3.800/deveco-studio-5.0.3.800.dmg
# 4. Linux
wget https://mirrors.huaweicloud.com/deveco-studio/5.0.3.800/deveco-studio-5.0.3.800.tar.gz
tar -xzf deveco-studio-5.0.3.800.tar.gz
cd deveco-studio
./deveco-studio.sh
~/Huawei/Sdk)# 项目结构
MyAIApp/
├── AppScope/ # 应用配置
│ ├── app.json5 # 应用元数据
│ └── resources/ # 资源
├── entry/ # 主模块
│ ├── src/main/
│ │ ├── ets/ # ArkTS 源码
│ │ │ ├── entryability/ # UIAbility
│ │ │ ├── pages/ # 页面
│ │ │ └── ai/ # AI 模块
│ │ ├── resources/ # 资源
│ │ └── module.json5 # 模块配置
│ └── build-profile.json5
├── oh-package.json5 # 依赖
└── build-profile.json5 # 构建配置
@Entry
@Component
struct Index {
@State userInput: string = '';
@State aiResponse: string = '';
@State isLoading: boolean = false;
build() {
Column() {
// 标题
Text('盘古 AI 对话')
.fontSize(24)
.fontWeight(FontWeight.Bold)
.margin({ top: 20, bottom: 20 })
// 输入框
TextArea({ placeholder: '请输入问题...' })
.width('90%')
.height(120)
.margin(10)
.onChange((value: string) => {
this.userInput = value;
})
// 发送按钮
Button('发送给盘古')
.width('90%')
.height(50)
.margin(10)
.onClick(async () => {
await this.callPangu();
})
// 加载中
if (this.isLoading) {
LoadingProgress()
.width(50)
.height(50)
.margin(20)
}
// 响应显示
if (this.aiResponse) {
Scroll() {
Text(this.aiResponse)
.fontSize(16)
.padding(15)
.width('100%')
}
.layoutWeight(1)
.margin(10)
.backgroundColor('#f5f5f5')
.borderRadius(8)
}
}
.width('100%')
.height('100%')
}
async callPangu() {
if (!this.userInput.trim()) {
promptAction.showToast({ message: '请输入问题' });
return;
}
this.isLoading = true;
try {
const response = await PanguAI.chat(this.userInput);
this.aiResponse = response;
} catch (e) {
this.aiResponse = `错误: ${JSON.stringify(e)}`;
} finally {
this.isLoading = false;
}
}
}
entry/src/main/ets/ai/PanguAI.ets:
import { http } from '@kit.NetworkKit';
import { preferences } from '@kit.ArkData';
// 盘古 API 配置
const PANGU_ENDPOINT = 'https://pangu-nlp.cn-north-4.myhuaweicloud.com';
const PANGU_MODEL = 'pangu-nlp-4-nxt-128k';
@Observed
export class PanguAI {
private static apiKey: string = '';
private static conversationHistory: Array<{role: string, content: string}> = [];
static async init(context: Context) {
// 从本地读取 API Key
const prefs = await preferences.getPreferences(context, 'pangu');
this.apiKey = (await prefs.get('apiKey', '')) as string;
}
static async setApiKey(key: string) {
this.apiKey = key;
// 持久化
}
static async chat(userMessage: string): Promise<string> {
if (!this.apiKey) {
throw new Error('请先设置 API Key');
}
// 添加用户消息到历史
this.conversationHistory.push({
role: 'user',
content: userMessage
});
// 构造请求体
const requestBody = {
model: PANGU_MODEL,
messages: this.conversationHistory,
temperature: 0.7,
max_tokens: 2000,
top_p: 0.9
};
// 发送 HTTP 请求
const httpRequest = http.createHttp();
const response = await httpRequest.request(PANGU_ENDPOINT + '/v1/chat/completions', {
method: http.RequestMethod.POST,
header: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.apiKey}`
},
extraData: JSON.stringify(requestBody)
});
if (response.responseCode !== 200) {
throw new Error(`API 错误: ${response.responseCode}`);
}
const result = JSON.parse(response.result as string);
const aiMessage = result.choices[0].message.content;
// 添加到历史
this.conversationHistory.push({
role: 'assistant',
content: aiMessage
});
return aiMessage;
}
static clearHistory() {
this.conversationHistory = [];
}
}
static async streamChat(
userMessage: string,
onChunk: (text: string) => void
): Promise<void> {
const requestBody = {
model: PANGU_MODEL,
messages: [{ role: 'user', content: userMessage }],
stream: true // 启用流式
};
// 使用 EventSource 实现 SSE
const events = await httpRequest.request(
PANGU_ENDPOINT + '/v1/chat/completions',
{
method: 'POST',
header: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.apiKey}`,
'Accept': 'text/event-stream'
},
extraData: JSON.stringify(requestBody)
}
);
// 逐 chunk 处理
for (const chunk of events) {
const data = chunk.toString().replace(/^data: /, '');
if (data === '[DONE]') break;
const parsed = JSON.parse(data);
const delta = parsed.choices[0]?.delta?.content || '';
onChunk(delta);
}
}
鸿蒙 NEXT 提供了强大的端侧 AI 框架(AI Framework),支持 NPU 加速:
import { aiEngine } from '@kit.AIEngine';
async function localTextUnderstanding(text: string) {
// 1. 创建文本理解智能体
const agent = await aiEngine.createTextUnderstandingAgent({
model: 'nlp-mind' // 端侧轻量模型
});
// 2. 文本分类
const result = await agent.classify(text, [
'科技', '娱乐', '体育', '财经', '其他'
]);
console.log('分类结果:', result);
// 3. 情感分析
const sentiment = await agent.analyzeSentiment(text);
console.log('情感倾向:', sentiment);
// 4. 关键词提取
const keywords = await agent.extractKeywords(text, 5);
console.log('关键词:', keywords);
}
import { vision } from '@kit.VisionKit';
async function recognizeImage(imageBuffer: ArrayBuffer) {
// 1. 物体检测
const objects = await vision.detectObjects(imageBuffer);
// 2. 人脸识别(端侧,保护隐私)
const faces = await vision.detectFaces(imageBuffer);
// 3. 文字识别 OCR
const text = await vision.recognizeText(imageBuffer);
return { objects, faces, text };
}
实际项目通常采用"端侧预处理 + 云端精修"模式:
async function hybridAI(text: string) {
// 1. 端侧快速意图识别(10ms)
const intent = await localTextUnderstanding(text);
if (intent.confidence > 0.9) {
// 高置信度,直接用端侧结果
return intent;
} else {
// 低置信度,调用云端盘古精修(500ms)
return await PanguAI.chat(text);
}
}
# 1. 鸿蒙设备开启 USB 调试
# 设置 → 开发者选项 → USB 调试
# 2. hdc 工具连接
hdc list targets
# 输出:xxx.xxx.xxx.xxx device
# 3. 安装应用到设备
hdc install entry/build/default/outputs/default/entry-default-signed.hap
# 4. 启动应用
hdc shell aa start -b com.example.myaiapp -a EntryAbility
*.app 文件(HAP + 资源 + 签名)# 1. 生成密钥
keytool -genkey -alias myai -keyalg RSA -keysize 2048 -validity 36500 -keystore myai.p12
# 2. 在 DevEco Studio 配置签名
# File → Project Structure → Signing Configs
# 3. 申请发布证书
# AGC → 用户与访问 → 证书管理 → 申请发布证书
| 芯片 | 架构 | 适配状态 | 性能参考 |
|---|---|---|---|
| 麒麟 9000s/9010 | ARM | 原生支持 | A17 级别 |
| 麒麟 990 | ARM | 完整支持 | Snapdragon 855 级别 |
| 飞腾 FT-2000+ | ARM | 支持(需 SDK 适配) | 服务器级 |
| 龙芯 3A6000 | LoongArch | 模拟器支持 | i5 级别 |
| 海光 7285 | x86 | 完整支持 | 服务器级 |
# 在 module.json5 中声明
{
"deviceTypes": [
"phone", "tablet", "2in1", "tv", "wearable"
],
"abilities": [...],
"distribution": {
"systemApps": [],
"bundleType": "app"
}
}
# 多端部署
# - 手机/平板:HarmonyOS NEXT
# - PC:HarmonyOS PC 版
# - 智能座舱:HarmonyOS Auto
# - IoT:OpenHarmony
某三甲医院用鸿蒙 + 盘古医疗大模型开发的医生助手 APP:
某新能源车企基于鸿蒙座舱开发 AI 助手:
某工厂用鸿蒙 + 盘古时序大模型做设备预测性维护:
一个 ArkTS 代码可同时跑在手机、平板、PC、手表、智慧屏:
// deviceType 分发
import { deviceInfo } from '@kit.DeviceInfo';
@Entry
@Component
struct AdaptiveUI {
build() {
if (deviceInfo.deviceType === 'tablet') {
TabletLayout() // 平板布局
} else if (deviceInfo.deviceType === '2in1') {
PCLayout() // PC 布局
} else {
PhoneLayout() // 手机布局
}
}
}
// 一套代码多端部署,节约 70% 开发量
免安装、即用即走的"轻量应用":
// 在 config.json 中声明原子化服务
{
"abilities": [
{
"name": "EntryAbility",
"type": "service",
"atomicService": {
"preload": true,
"resizeable": true
}
}
]
}
// 用户无需下载安装,下拉控制中心直接用
智能调度:简单任务端侧(10ms),复杂任务云端(500ms),用户无感:
// 智能路由
async function smartAI(prompt: string) {
// 1. 端侧快速判断
const localResult = await localAI.quickAnswer(prompt);
if (localResult.confidence > 0.85) {
return localResult.answer; // 端侧返回
}
// 2. 云端精修
const cloudResult = await PanguAI.chat(prompt);
return cloudResult;
}
// 效果:
// - 80% 请求端侧返回(隐私+低延迟)
// - 20% 复杂请求云端处理(高质量)
❌ 错误做法:把 API Key 写在 .ets 文件中
✅ 正确做法:用 @ohos.security.cryptoFramework 加密存储到 Preferences
很多开发者写完代码发现端侧 AI 跑得很慢,因为没用 HiAI Foundation 框架。开启 NPU 加速性能提升 10-50 倍:
// 启用 NPU
import { hiAiEngine } from '@kit.HiAiEngine';
const model = await hiAiEngine.loadModel({
modelPath: 'nlp-mind.om',
deviceType: 'NPU' // 关键:指定 NPU 而非 CPU
});
鸿蒙 NEXT 的控件和 Android 不完全一样。常见问题:
常见原因:
鸿蒙 HarmonyOS 是国内信创的标杆,AI 能力是其核心优势。本指南覆盖了从环境搭建、盘古大模型调用、端侧 AI 集成到打包发布的全流程。
2026 年鸿蒙 AI 生态趋势:
建议你立即行动:
需要完整的代码模板+信创适配清单+华为云代金券?
📱 加微信 toukenai 咨询