从零开始:搭建完整的HarmonyOS 5 + AGC开发环境

前言
本文将全面指导你从零开始搭建完整的HarmonyOS 5开发环境,并集成AppGallery Connect(AGC)服务。我们将涵盖环境配置、项目创建、AGC集成以及一个完整的示例应用开发过程。

第一部分:环境搭建
1.1 硬件和软件要求
操作系统:Windows 10/11 64位 或 macOS 10.14及以上
内存:8GB及以上(推荐16GB)
硬盘空间:至少10GB可用空间
JDK:OpenJDK 17
1.2 安装DevEco Studio 5.0
访问华为开发者官网下载DevEco Studio 5.0
运行安装程序,按照向导完成安装
首次启动时,配置HarmonyOS SDK:
选择"Standard"安装模式
确保勾选HarmonyOS SDK 5.0和Toolchains
1.3 配置环境变量
对于Windows用户:

将以下路径添加到系统环境变量PATH中

DevEco Studio安装路径

JDK安装路径

Node.js路径(如果使用)

示例(根据实际路径调整):

$env:Path += ";C:\Program Files\DevEco Studio\jbr\bin"
$env:Path += ";C:\Program Files\Java\jdk-17\bin"
对于macOS用户:

编辑/.zshrc或/.bash_profile

export PATH="/Applications/DevEco Studio.app/Contents/jbr/Contents/Home/bin:$PATH"
export PATH="/Library/Java/JavaVirtualMachines/jdk-17.jdk/Contents/Home/bin:$PATH"
1.4 验证安装
在终端运行以下命令验证安装:

java -version
node -v # 如果安装了Node.js
npm -v # 如果安装了Node.js
第二部分:创建HarmonyOS 5项目
2.1 初始化项目
打开DevEco Studio,选择"Create Project"
选择"Application" → "Empty Ability"
配置项目:
{
"projectName": "HarmonyAGC",
"projectType": "Application",
"bundleName": "com.example.harmonyagc",
"runtimeOS": "HarmonyOS",
"compatibleApiVersion": 5,
"language": "ArkTS",
"deviceTypes": ["phone", "tablet"]
}
点击"Finish"完成创建
2.2 项目结构说明
HarmonyAGC/
├── entry/ # 主模块
│ ├── src/
│ │ ├── main/
│ │ │ ├── ets/ # ArkTS代码
│ │ │ ├── resources/ # 资源文件
│ │ │ └── module.json # 模块配置
│ └── build-profile.json5 # 模块构建配置
├── oh-package.json5 # 依赖管理
└── build-profile.json5 # 项目构建配置
第三部分:集成AppGallery Connect
3.1 注册华为开发者账号
访问华为开发者网站
注册并完成实名认证
3.2 在AGC创建项目和应用
登录AppGallery Connect
创建新项目"HarmonyAGC"
添加应用:
平台:HarmonyOS
包名:com.example.harmonyagc
应用名称:HarmonyAGC Demo
3.3 配置AGC SDK
修改oh-package.json5添加依赖:
{
"dependencies": {
"@hw-agconnect/api-ohos": "^1.8.0",
"@hw-agconnect/core-ohos": "^1.8.0",
"@hw-agconnect/auth-ohos": "^1.8.0",
"@hw-agconnect/clouddb-ohos": "^1.8.0",
"@hw-agconnect/function-ohos": "^1.8.0"
}
}
运行依赖安装:
ohpm install
从AGC控制台下载agconnect-services.json,放入entry/src/main/resources/rawfile/
3.4 配置签名
生成签名证书:
keytool -genkeypair -alias harmonyagc -keyalg RSA -keysize 2048 -validity 9125 -keystore harmonyagc.p12 -storetype PKCS12
在DevEco Studio中配置签名:
File → Project Structure → Project → Signing Configs
添加签名配置,选择生成的.p12文件
第四部分:开发完整示例应用
4.1 用户认证功能
修改entry/src/main/ets/pages/Index.ets:

import { agconnect } from '@hw-agconnect/api-ohos';
import '@hw-agconnect/core-ohos';
import { AGCAuth, AGCAuthError, AGCSignInResult } from '@hw-agconnect/auth-ohos';

@Entry
@Component
struct Index {
@State message: string = '欢迎使用HarmonyAGC';
@State isLoggedIn: boolean = false;
@State userName: string = '';

onPageShow() {
// 初始化AGC
agconnect.instance().init(this.context);

// 检查登录状态
this.checkLoginStatus();

}

// 检查登录状态
async checkLoginStatus() {
try {
const user = await AGCAuth.getInstance().getCurrentUser();
if (user) {
this.isLoggedIn = true;
this.userName = user.getDisplayName() || user.getEmail() || user.getPhone();
this.message = 欢迎回来, ${this.userName};
}
} catch (error) {
console.error("检查登录状态失败:", error);
}
}

// 匿名登录
async anonymousLogin() {
try {
const result: AGCSignInResult = await AGCAuth.getInstance().signInAnonymously();
this.isLoggedIn = true;
this.userName = "匿名用户";
this.message = 欢迎, ${this.userName};
} catch (error) {
if (error instanceof AGCAuthError) {
console.error("匿名登录失败:", error.message);
}
}
}

// 退出登录
async logout() {
try {
await AGCAuth.getInstance().signOut();
this.isLoggedIn = false;
this.userName = '';
this.message = '欢迎使用HarmonyAGC';
} catch (error) {
console.error("退出登录失败:", error);
}
}

build() {
Column() {
Text(this.message)
.fontSize(30)
.fontWeight(FontWeight.Bold)
.margin({ bottom: 40 })

  if (!this.isLoggedIn) {
    Button('匿名登录')
      .width(200)
      .height(50)
      .onClick(() => this.anonymousLogin())
      .margin({ bottom: 20 })
  } else {
    Button('退出登录')
      .width(200)
      .height(50)
      .onClick(() => this.logout())
      .margin({ bottom: 20 })
  }
  
  // 更多功能区域
  Column() {
    Text('AGC功能列表')
      .fontSize(20)
      .margin({ bottom: 20 })
    
    Navigation() {
      Button('云数据库示例')
        .width(200)
        .height(50)
        .margin({ bottom: 10 })
        .onClick(() => {
          // 跳转到云数据库示例页面
          router.pushUrl({ url: 'pages/CloudDBPage' });
        })
        
      Button('云函数示例')
        .width(200)
        .height(50)
        .margin({ bottom: 10 })
        .onClick(() => {
          // 跳转到云函数示例页面
          router.pushUrl({ url: 'pages/CloudFunctionPage' });
        })
    }
  }
  .width('100%')
  .margin({ top: 50 })
}
.width('100%')
.height('100%')
.padding(20)
.justifyContent(FlexAlign.Start)

}
}
4.2 云数据库功能
创建entry/src/main/ets/pages/CloudDBPage.ets:

import { agconnect } from '@hw-agconnect/api-ohos';
import { AGCCloudDB, CloudDBZone, CloudDBZoneConfig, CloudDBZoneError } from '@hw-agconnect/clouddb-ohos';

// 定义数据模型
@Class
class Book {
id?: number = undefined;
bookName?: string = undefined;
author?: string = undefined;
price?: number = undefined;
publishTime?: number = undefined;

constructor(bookName?: string, author?: string, price?: number) {
this.bookName = bookName;
this.author = author;
this.price = price;
this.publishTime = new Date().getTime();
}
}

@Entry
@Component
struct CloudDBPage {
private cloudDBZone?: CloudDBZone = undefined;
@State books: Book[] = [];
@State newBookName: string = '';
@State newBookAuthor: string = '';
@State newBookPrice: string = '';

async onPageShow() {
await this.initCloudDB();
await this.queryBooks();
}

// 初始化云数据库
async initCloudDB() {
try {
// 1. 创建对象类型
await AGCCloudDB.initAGConnectCloudDB(agconnect.instance());
AGCCloudDB.createObjectType(Book);

  // 2. 打开数据库区域
  const config: CloudDBZoneConfig = {
    zoneName: "QuickStartDemo",
    syncProperty: CloudDBZone.SYNC_CLOUD_PRIOR
  };
  this.cloudDBZone = await AGCCloudDB.openCloudDBZone(config);
} catch (error) {
  console.error("初始化云数据库失败:", error);
}

}

// 查询书籍
async queryBooks() {
if (!this.cloudDBZone) return;

try {
  const snapshot = await this.cloudDBZone.executeQuery(Book, "id != null");
  this.books = snapshot.getSnapshotObjects() as Book[];
} catch (error) {
  if (error instanceof CloudDBZoneError) {
    console.error("查询书籍失败:", error.message);
  }
}

}

// 添加书籍
async addBook() {
if (!this.cloudDBZone || !this.newBookName || !this.newBookAuthor || !this.newBookPrice) return;

const price = parseFloat(this.newBookPrice);
if (isNaN(price)) return;

const book = new Book(this.newBookName, this.newBookAuthor, price);

try {
  await this.cloudDBZone.executeUpsert(book);
  this.newBookName = '';
  this.newBookAuthor = '';
  this.newBookPrice = '';
  await this.queryBooks(); // 刷新列表
} catch (error) {
  if (error instanceof CloudDBZoneError) {
    console.error("添加书籍失败:", error.message);
  }
}

}

// 删除书籍
async deleteBook(book: Book) {
if (!this.cloudDBZone || !book.id) return;

try {
  await this.cloudDBZone.executeDelete(book);
  await this.queryBooks(); // 刷新列表
} catch (error) {
  if (error instanceof CloudDBZoneError) {
    console.error("删除书籍失败:", error.message);
  }
}

}

build() {
Column() {
Text('云数据库示例')
.fontSize(25)
.fontWeight(FontWeight.Bold)
.margin({ bottom: 30 })

  // 添加新书表单
  Column() {
    TextInput({ placeholder: '书名' })
      .width('80%')
      .height(50)
      .margin({ bottom: 10 })
      .onChange((value: string) => this.newBookName = value)
    
    TextInput({ placeholder: '作者' })
      .width('80%')
      .height(50)
      .margin({ bottom: 10 })
      .onChange((value: string) => this.newBookAuthor = value)
    
    TextInput({ placeholder: '价格' })
      .width('80%')
      .height(50)
      .margin({ bottom: 20 })
      .type(InputType.Number)
      .onChange((value: string) => this.newBookPrice = value)
    
    Button('添加书籍')
      .width(200)
      .height(50)
      .onClick(() => this.addBook())
  }
  .width('100%')
  .margin({ bottom: 30 })
  
  // 书籍列表
  List({ space: 10 }) {
    ForEach(this.books, (book: Book) => {
      ListItem() {
        Row() {
          Column() {
            Text(book.bookName || '未知书名')
              .fontSize(18)
              .fontWeight(FontWeight.Bold)
            
            Text(`作者: ${book.author || '未知'} | 价格: ¥${book.price?.toFixed(2) || '0.00'}`)
              .fontSize(14)
              .margin({ top: 5 })
          }
          .layoutWeight(1)
          
          Button('删除')
            .width(80)
            .height(40)
            .onClick(() => this.deleteBook(book))
        }
        .width('100%')
        .padding(10)
        .borderRadius(10)
        .backgroundColor('#f5f5f5')
      }
    }, (book: Book) => book.id?.toString() || '')
  }
  .width('100%')
  .layoutWeight(1)
}
.width('100%')
.height('100%')
.padding(20)

}
}
4.3 云函数功能
创建entry/src/main/ets/pages/CloudFunctionPage.ets:

import { agconnect } from '@hw-agconnect/api-ohos';
import { AGCFunction, AGCFunctionError } from '@hw-agconnect/function-ohos';

@Entry
@Component
struct CloudFunctionPage {
@State inputText: string = '';
@State resultText: string = '点击"调用云函数"按钮测试';
@State isLoading: boolean = false;

// 调用云函数
async callCloudFunction() {
if (!this.inputText.trim()) {
this.resultText = '请输入一些文本';
return;
}

this.isLoading = true;
this.resultText = '正在调用云函数...';

try {
  const functionCallable = AGCFunction.getInstance().wrap("helloWorld-$latest");
  const result = await functionCallable.call({
    text: this.inputText
  });
  
  this.resultText = `云函数返回: ${JSON.stringify(result.getValue())}`;
} catch (error) {
  if (error instanceof AGCFunctionError) {
    this.resultText = `调用失败: ${error.message}`;
  } else {
    this.resultText = `发生未知错误: ${error}`;
  }
} finally {
  this.isLoading = false;
}

}

build() {
Column() {
Text('云函数示例')
.fontSize(25)
.fontWeight(FontWeight.Bold)
.margin({ bottom: 30 })

  TextInput({ placeholder: '输入要发送到云函数的文本' })
    .width('90%')
    .height(60)
    .margin({ bottom: 20 })
    .onChange((value: string) => this.inputText = value)
  
  Button(this.isLoading ? '处理中...' : '调用云函数')
    .width(200)
    .height(50)
    .margin({ bottom: 30 })
    .enabled(!this.isLoading)
    .onClick(() => this.callCloudFunction())
  
  Text(this.resultText)
    .fontSize(18)
    .width('90%')
    .margin({ top: 20 })
    .textAlign(TextAlign.Center)
  
  if (this.isLoading) {
    LoadingProgress()
      .width(50)
      .height(50)
      .margin({ top: 20 })
  }
}
.width('100%')
.height('100%')
.padding(20)

}
}
第五部分:构建和发布
5.1 构建应用
在DevEco Studio中,选择Build → Build HAP(s)
选择Release模式,生成签名的HAP文件
5.2 在AGC上配置应用
在AGC控制台中,进入"HarmonyAGC"应用
配置所需服务:
认证服务:启用匿名登录
云数据库:创建对象类型Book
云函数:创建helloWorld函数
5.3 测试云函数
在AGC控制台中创建helloWorld云函数:

exports.helloWorld = async function(param) {
return {
originalText: param.text,
processedText: param.text.toUpperCase(),
timestamp: new Date().toISOString(),
message: "Hello from HarmonyOS Cloud Function!"
};
};
5.4 发布应用到AppGallery
在AGC控制台中,进入"我的应用"
选择"版本发布" → "添加版本"
上传签名的HAP文件
填写版本信息并提交审核
总结
通过本文,你已经完成了:

HarmonyOS 5开发环境的搭建
创建了一个完整的HarmonyOS应用
集成了AGC的多项核心服务
实现了用户认证、云数据库和云函数功能

posted @ 2025-06-28 22:21  暗雨YA  阅读(51)  评论(0)    收藏  举报