初始提交:HarmonyOS GameLobby项目

This commit is contained in:
2025-07-12 14:24:31 +08:00
commit 588adb6442
42 changed files with 5714 additions and 0 deletions

12
.gitignore vendored Normal file
View File

@@ -0,0 +1,12 @@
/node_modules
/oh_modules
/local.properties
/.idea
**/build
/.hvigor
.cxx
/.clangd
/.clang-format
/.clang-tidy
**/.test
/.appanalyzer

37
.vscode/settings.json vendored Normal file
View File

@@ -0,0 +1,37 @@
{
"files.associations": {
"*.json5": "json"
},
"json.schemas": [
{
"fileMatch": [
"build-profile.json5"
],
"url": "file:///c:/Users/Joywayer/.vscode/extensions/shenkaihong.arkts-project-manager-0.7.2/templates/schemas/ohos-project-build-profile-schema.json"
},
{
"fileMatch": [
"AppScope/app.json5"
],
"url": "file:///11/toolchains/modulecheck/app.json"
},
{
"fileMatch": [
"oh-package.json5"
],
"url": "file:///c:/Users/Joywayer/.vscode/extensions/shenkaihong.arkts-project-manager-0.7.2/templates/schemas/oh-package-json5-schema.json"
},
{
"fileMatch": [
"**/src/main/module.json5"
],
"url": "file:///11/toolchains/modulecheck/module.json"
},
{
"fileMatch": [
"**/build-profile.json5"
],
"url": "file:///c:/Users/Joywayer/.vscode/extensions/shenkaihong.arkts-project-manager-0.7.2/templates/schemas/ohos-module-build-profile-schema.json"
}
]
}

10
AppScope/app.json5 Normal file
View File

@@ -0,0 +1,10 @@
{
"app": {
"bundleName": "com.daoqi.gamelobby",
"vendor": "example",
"versionCode": 1000000,
"versionName": "1.0.0",
"icon": "$media:app_layered_image",
"label": "$string:app_name"
}
}

View File

@@ -0,0 +1,8 @@
{
"string": [
{
"name": "app_name",
"value": "GameLobby"
}
]
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

View File

@@ -0,0 +1,7 @@
{
"layered-image":
{
"background" : "$media:app_background",
"foreground" : "$media:app_foreground"
}
}

42
build-profile.json5 Normal file
View File

@@ -0,0 +1,42 @@
{
"app": {
"signingConfigs": [],
"products": [
{
"name": "default",
"signingConfig": "default",
"targetSdkVersion": "5.1.0(18)",
"compatibleSdkVersion": "5.1.0(18)",
"runtimeOS": "HarmonyOS",
"buildOption": {
"strictMode": {
"caseSensitiveCheck": true,
"useNormalizedOHMUrl": true
}
}
}
],
"buildModeSet": [
{
"name": "debug",
},
{
"name": "release"
}
]
},
"modules": [
{
"name": "entry",
"srcPath": "./entry",
"targets": [
{
"name": "default",
"applyToProducts": [
"default"
]
}
]
}
]
}

32
code-linter.json5 Normal file
View File

@@ -0,0 +1,32 @@
{
"files": [
"**/*.ets"
],
"ignore": [
"**/src/ohosTest/**/*",
"**/src/test/**/*",
"**/src/mock/**/*",
"**/node_modules/**/*",
"**/oh_modules/**/*",
"**/build/**/*",
"**/.preview/**/*"
],
"ruleSet": [
"plugin:@performance/recommended",
"plugin:@typescript-eslint/recommended"
],
"rules": {
"@security/no-unsafe-aes": "error",
"@security/no-unsafe-hash": "error",
"@security/no-unsafe-mac": "warn",
"@security/no-unsafe-dh": "error",
"@security/no-unsafe-dsa": "error",
"@security/no-unsafe-ecdsa": "error",
"@security/no-unsafe-rsa-encrypt": "error",
"@security/no-unsafe-rsa-sign": "error",
"@security/no-unsafe-rsa-key": "error",
"@security/no-unsafe-dsa-key": "error",
"@security/no-unsafe-dh-key": "error",
"@security/no-unsafe-3des": "error"
}
}

View File

@@ -0,0 +1,236 @@
# HarmonyOS 5.0 官方开发者资源快速参考手册
## 🎯 使用说明
本文档为"进贤聚友棋牌 (HarmonyOS版)"项目提供官方开发者资源的快速索引和使用指导。**开发过程中必须优先参考官方文档**,本文档仅作为导航和补充。
---
## 📚 一、核心官方文档(优先级排序)
### ⭐⭐⭐⭐⭐ 最高优先级 - 日常开发必备
#### 1. **HarmonyOS API参考文档**
- **官方链接**: https://developer.huawei.com/consumer/cn/doc/harmonyos-references/development-intro-api
- **使用场景**: 所有API调用前必须查阅
- **重点关注**:
- Web组件API: `ts-basic-components-web`
- WebviewController: `js-apis-webview`
- 文件管理: `js-apis-file-fs`
- 网络请求: `js-apis-http`
- **开发建议**: 收藏并设为浏览器首页,开发过程中随时查阅
#### 2. **HarmonyOS应用开发指南**
- **官方链接**: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/application-dev-guide
- **使用场景**: 项目架构设计、功能实现方案设计
- **重点关注**:
- 应用工程结构: `application-project-structure`
- WebView开发: `webview-js-interaction`
- 数据管理: `data-mgmt-overview`
- 网络管理: `network-connection-overview`
- **开发建议**: 项目启动前通读相关章节,设计阶段重点参考
### ⭐⭐⭐⭐ 高优先级 - 技术决策参考
#### 3. **HarmonyOS最佳实践**
- **官方链接**: https://developer.huawei.com/consumer/cn/doc/best-practices/bpta-best-practices-overview
- **使用场景**: 架构设计、性能优化、代码质量提升
- **重点关注**:
- WebView性能优化: `bpta-webview-performance`
- 网络请求优化: `bpta-network-request`
- 内存管理: `bpta-memory-management`
- ArkTS开发规范: `bpta-arkts-guidelines`
- **开发建议**: 每个功能模块设计前查阅相关最佳实践
#### 4. **HarmonyOS版本发布说明**
- **官方链接**: https://developer.huawei.com/consumer/cn/doc/harmonyos-releases/overview-allversion
- **使用场景**: 版本兼容性确认、API变更跟踪
- **重点关注**:
- API 12新特性和变更
- 兼容性要求
- 废弃API列表
- **开发建议**: 项目开始前确认目标版本,定期检查更新
### ⭐⭐⭐ 中等优先级 - 问题解决工具
#### 5. **HarmonyOS开发FAQ**
- **官方链接**: https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs/faqs-ux-design
- **使用场景**: 遇到问题时的第一参考资料
- **重点关注**:
- WebView相关FAQ
- ArkTS编译错误FAQ
- 性能问题FAQ
- **开发建议**: 遇到问题先查FAQ再搜索或提问
---
## 🛠️ 二、开发工具官方资源
### DevEco Studio
- **官方下载**: https://developer.huawei.com/consumer/cn/deveco-studio/
- **文档**: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/ide-guide
- **版本要求**: 支持HarmonyOS 5.0的最新版本
- **关键功能**: 代码编辑、调试、模拟器、性能分析
### SDK管理
- **官方指南**: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/ide-sdk-manager
- **版本选择**: API 12+ for HarmonyOS 5.0
- **更新策略**: 定期检查更新,关注兼容性变更
---
## 🎯 三、项目关键功能的官方资源映射
### WebView与JSBridge开发
```
功能需求 → 官方资源
├── WebView基础配置 → Web组件API参考
├── JSBridge通信 → JavaScript与应用交互指南
├── WebView控制器 → WebviewController API参考
├── 性能优化 → WebView性能优化最佳实践
└── 问题排查 → WebView FAQ专区
```
### 资源管理与文件操作
```
功能需求 → 官方资源
├── 文件读写 → 文件管理API参考
├── 网络下载 → 网络请求API + 最佳实践
├── 资源解压 → 文件系统API + ZIP处理示例
├── 缓存管理 → 数据管理指南
└── 权限申请 → 权限管理指南
```
### 应用架构与状态管理
```
功能需求 → 官方资源
├── 页面导航 → 页面路由开发指南
├── 状态管理 → ArkUI状态管理
├── 组件通信 → 组件化开发指南
├── 生命周期 → 应用/组件生命周期
└── 数据持久化 → 数据管理overview
```
---
## 📋 四、开发阶段的官方资源使用计划
### 第一阶段:环境搭建
**主要参考**:
1. DevEco Studio安装指南
2. SDK管理文档
3. 项目创建向导
4. 开发环境配置FAQ
**使用策略**: 严格按照官方指南操作遇到问题优先查阅FAQ
### 第二阶段:核心功能开发
**主要参考**:
1. API参考文档日常查阅
2. 开发指南(设计参考)
3. 最佳实践(质量保证)
4. 示例代码(快速上手)
**使用策略**: API文档作为编码标准最佳实践指导架构设计
### 第三阶段:功能完善
**主要参考**:
1. 性能优化最佳实践
2. 用户体验设计指南
3. 兼容性测试指南
4. 错误处理最佳实践
**使用策略**: 对照最佳实践优化代码质量和用户体验
### 第四阶段:测试与优化
**主要参考**:
1. 测试框架文档
2. 性能分析工具指南
3. 调试技巧文档
4. 发布前检查清单
**使用策略**: 使用官方工具进行全面测试和性能优化
---
## 🔍 五、快速查找指南
### 常见问题快速定位
#### WebView相关问题
```
问题类型 → 查找路径
├── 类型错误 → API参考文档 → WebviewController
├── 通信失败 → 开发指南 → JavaScript交互
├── 性能问题 → 最佳实践 → WebView性能优化
├── 兼容性 → 版本说明 → API变更列表
└── 其他 → FAQ → WebView专区
```
#### ArkTS编译错误
```
问题类型 → 查找路径
├── 语法错误 → 开发指南 → ArkTS语法
├── 类型错误 → API参考 → 具体API类型定义
├── 装饰器错误 → 开发指南 → 状态管理
├── 导入错误 → 开发指南 → 模块化开发
└── 其他 → FAQ → 编译错误专区
```
### 搜索关键词建议
#### 中文搜索
- "HarmonyOS WebView"
- "ArkTS WebviewController"
- "HarmonyOS JSBridge"
- "HarmonyOS 文件管理"
- "ArkTS 类型检查"
#### 英文搜索
- "HarmonyOS Web Component"
- "ArkTS WebviewController API"
- "HarmonyOS JavaScript Proxy"
- "HarmonyOS File System"
- "ArkTS Type System"
---
## ⚠️ 重要提醒
### 优先级原则
1. **官方文档 > 第三方资料**:当存在冲突时,以官方文档为准
2. **API参考 > 示例代码**编码时优先查阅API文档确保参数正确
3. **最新版本 > 历史版本**:确保使用与目标版本一致的文档
### 版本一致性
- 确保查阅的文档版本与项目目标版本HarmonyOS 5.0 API 12+)一致
- 关注API变更和废弃通知
- 定期检查文档更新
### 问题反馈
- 通过官方开发者社区反馈技术问题
- 利用DevEco Studio内置的问题报告功能
- 参与官方技术交流群获得及时支持
---
## 📞 官方支持渠道
### 开发者社区
- **HarmonyOS开发者论坛**: https://developer.huawei.com/consumer/cn/forum/block/harmonyos
- **用途**: 技术讨论、问题求助、经验分享
### 官方技术支持
- **在线客服**: DevEco Studio → Help → Contact Support
- **用途**: 紧急技术问题、工具bug反馈
### 官方培训资源
- **在线课程**: https://developer.huawei.com/consumer/cn/training/
- **用途**: 系统学习HarmonyOS开发技能
---
**最后更新**: 2024年12月19日
**文档版本**: v1.0
**适用项目**: 进贤聚友棋牌 (HarmonyOS版)
**目标平台**: HarmonyOS 5.0 (API 12+)

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,842 @@
# TSGame JSBridge 接口详解
## 目录
1. [概述](#概述)
2. [WebView调用App接口](#webview调用app接口)
- [2.1 游戏相关接口](#21-游戏相关接口)
- [2.2 用户信息接口](#22-用户信息接口)
- [2.3 分享接口](#23-分享接口)
- [2.4 媒体播放接口](#24-媒体播放接口)
- [2.5 设备信息接口](#25-设备信息接口)
- [2.6 网络请求接口](#26-网络请求接口)
- [2.7 系统功能接口](#27-系统功能接口)
3. [App调用WebView接口](#app调用webview接口)
- [3.1 页面生命周期](#31-页面生命周期)
- [3.2 网络状态通知](#32-网络状态通知)
- [3.3 数据更新通知](#33-数据更新通知)
4. [数据结构定义](#数据结构定义)
- [4.1 基础数据结构](#41-基础数据结构)
- [4.2 游戏数据结构](#42-游戏数据结构)
- [4.3 分享数据结构](#43-分享数据结构)
- [4.4 媒体数据结构](#44-媒体数据结构)
5. [错误码定义](#错误码定义)
6. [接口调用示例](#接口调用示例)
---
## 概述
TSGame采用JSBridge技术实现JavaScript与Android App之间的双向通信。本文档详细说明了所有可用的接口、参数结构和使用方法。
### 调用方式
**WebView调用App**
```javascript
// 有回调的接口
window.WebViewJavascriptBridge.callHandler('接口名', 参数对象, function(response) {
// 处理回调
});
// 无回调的接口
window.WebViewJavascriptBridge.callHandler('接口名', 参数对象);
```
**App调用WebView**
```java
// 在Android代码中
webView.callHandler("接口名", 参数对象, new CallBackFunction() {
@Override
public void onCallBack(String data) {
// 处理回调
}
});
```
---
## WebView调用App接口
### 2.1 游戏相关接口
#### SwitchOverGameData
**作用:** 切换到指定游戏,传递游戏相关数据
**调用时机:** 用户点击游戏入口时
**回调:**
**参数结构:**
```typescript
interface SwitchOverGameDataParams {
gameId: string; // 游戏ID
gameType: string; // 游戏类型
gameUrl: string; // 游戏链接
gameName: string; // 游戏名称
gameIcon: string; // 游戏图标URL
gameDesc?: string; // 游戏描述(可选)
extraData?: any; // 额外数据(可选)
}
```
**字段说明:**
- `gameId`: 唯一标识游戏的ID用于统计和数据追踪
- `gameType`: 游戏分类,如"H5"、"小游戏"等
- `gameUrl`: 游戏的访问链接
- `gameName`: 游戏显示名称
- `gameIcon`: 游戏图标的URL地址
- `gameDesc`: 游戏的详细描述信息
- `extraData`: 传递给游戏的额外参数
**示例:**
```javascript
window.WebViewJavascriptBridge.callHandler('SwitchOverGameData', {
gameId: "game_001",
gameType: "H5",
gameUrl: "https://game.example.com/game1",
gameName: "消消乐",
gameIcon: "https://cdn.example.com/icons/game1.png",
gameDesc: "经典三消游戏",
extraData: {
level: 1,
userId: "user123"
}
});
```
#### getGameinstall
**作用:** 获取游戏安装状态
**调用时机:** 需要检查游戏是否已安装时
**回调:**
**参数结构:**
```typescript
interface GetGameinstallParams {
gameId: string; // 游戏ID
packageName?: string; // 游戏包名(可选)
}
```
**回调结构:**
```typescript
interface GetGameinstallResponse {
isInstalled: boolean; // 是否已安装
version?: string; // 游戏版本(如果已安装)
lastUpdateTime?: string; // 最后更新时间
}
```
**示例:**
```javascript
window.WebViewJavascriptBridge.callHandler('getGameinstall', {
gameId: "game_001",
packageName: "com.example.game1"
}, function(response) {
if (response.isInstalled) {
console.log('游戏已安装,版本:' + response.version);
} else {
console.log('游戏未安装');
}
});
```
#### downloadGame
**作用:** 下载并安装游戏
**调用时机:** 用户点击下载游戏时
**回调:** 有(下载进度)
**参数结构:**
```typescript
interface DownloadGameParams {
gameId: string; // 游戏ID
downloadUrl: string; // 下载链接
gameName: string; // 游戏名称
gameSize?: number; // 游戏大小(字节)
}
```
### 2.2 用户信息接口
#### getUserInfo
**作用:** 获取当前用户信息
**调用时机:** 需要用户信息时
**回调:**
**参数结构:**
```typescript
interface GetUserInfoParams {
fields?: string[]; // 需要获取的字段列表(可选)
}
```
**回调结构:**
```typescript
interface UserInfo {
userId: string; // 用户ID
nickname: string; // 用户昵称
avatar: string; // 头像URL
gender: number; // 性别 (0:未知, 1:男, 2:女)
age?: number; // 年龄(可选)
phone?: string; // 手机号(可选)
email?: string; // 邮箱(可选)
level: number; // 用户等级
coins: number; // 金币数量
diamonds: number; // 钻石数量
vipLevel: number; // VIP等级
}
```
#### updateUserCoins
**作用:** 更新用户金币
**调用时机:** 游戏中获得或消耗金币时
**回调:**
**参数结构:**
```typescript
interface UpdateUserCoinsParams {
amount: number; // 变更数量(正数为增加,负数为减少)
reason: string; // 变更原因
gameId?: string; // 相关游戏ID可选
}
```
### 2.3 分享接口
#### friendsSharetypeUrlToptitleDescript
**作用:** 分享内容到社交平台
**调用时机:** 用户点击分享按钮时
**回调:**
**参数结构:**
```typescript
interface ShareParams {
shareType: string; // 分享类型:"wechat" | "qq" | "weibo" | "system"
title: string; // 分享标题
description: string; // 分享描述
url: string; // 分享链接
imageUrl?: string; // 分享图片URL可选
thumbUrl?: string; // 缩略图URL可选
extraData?: any; // 额外数据(可选)
}
```
**字段说明:**
- `shareType`: 分享平台类型
- "wechat": 微信分享
- "qq": QQ分享
- "weibo": 微博分享
- "system": 系统分享(调用系统分享面板)
- `title`: 分享卡片显示的标题
- `description`: 分享卡片显示的描述文本
- `url`: 点击分享卡片后跳转的链接
- `imageUrl`: 分享卡片显示的图片
- `thumbUrl`: 分享卡片的缩略图(某些平台需要)
**回调结构:**
```typescript
interface ShareResponse {
success: boolean; // 分享是否成功
platform: string; // 实际分享的平台
errorMsg?: string; // 错误信息(失败时)
}
```
#### getSharePlatforms
**作用:** 获取可用的分享平台列表
**调用时机:** 显示分享面板前
**回调:**
**回调结构:**
```typescript
interface SharePlatform {
type: string; // 平台类型
name: string; // 平台名称
icon: string; // 平台图标URL
available: boolean; // 是否可用
}
interface GetSharePlatformsResponse {
platforms: SharePlatform[];
}
```
### 2.4 媒体播放接口
#### mediaTypeAudio
**作用:** 播放音频文件
**调用时机:** 需要播放背景音乐或音效时
**回调:**
**参数结构:**
```typescript
interface MediaAudioParams {
action: string; // 操作类型:"play" | "pause" | "stop" | "resume"
audioUrl?: string; // 音频URLplay时必需
volume?: number; // 音量 (0.0-1.0)
loop?: boolean; // 是否循环播放
audioId?: string; // 音频ID用于控制特定音频
}
```
**字段说明:**
- `action`: 音频操作类型
- "play": 播放新音频
- "pause": 暂停播放
- "stop": 停止播放
- "resume": 恢复播放
- `audioUrl`: 音频文件的URL地址
- `volume`: 播放音量范围0.0到1.0
- `loop`: 是否循环播放
- `audioId`: 音频标识符,用于同时控制多个音频
**回调结构:**
```typescript
interface MediaAudioResponse {
success: boolean; // 操作是否成功
audioId: string; // 音频ID
status: string; // 当前状态:"playing" | "paused" | "stopped"
duration?: number; // 音频时长(秒)
currentTime?: number; // 当前播放时间(秒)
errorMsg?: string; // 错误信息
}
```
#### mediaTypeVideo
**作用:** 播放视频文件
**调用时机:** 需要播放视频时
**回调:**
**参数结构:**
```typescript
interface MediaVideoParams {
action: string; // 操作类型:"play" | "pause" | "stop" | "fullscreen"
videoUrl?: string; // 视频URLplay时必需
poster?: string; // 视频封面图URL
autoplay?: boolean; // 是否自动播放
controls?: boolean; // 是否显示控制条
muted?: boolean; // 是否静音
}
```
### 2.5 设备信息接口
#### getDeviceInfo
**作用:** 获取设备基本信息
**调用时机:** 需要设备信息进行统计或适配时
**回调:**
**回调结构:**
```typescript
interface DeviceInfo {
deviceId: string; // 设备唯一标识
deviceModel: string; // 设备型号
osVersion: string; // 操作系统版本
appVersion: string; // App版本
screenWidth: number; // 屏幕宽度(像素)
screenHeight: number; // 屏幕高度(像素)
density: number; // 屏幕密度
language: string; // 系统语言
timezone: string; // 时区
networkType: string; // 网络类型:"wifi" | "mobile" | "none"
}
```
#### getPhoneInfo
**作用:** 获取手机详细信息
**调用时机:** 需要详细设备信息时
**回调:**
**回调结构:**
```typescript
interface PhoneInfo {
brand: string; // 手机品牌
manufacturer: string; // 制造商
model: string; // 型号
buildNumber: string; // 构建号
serialNumber: string; // 序列号
imei: string; // IMEI号
androidId: string; // Android ID
macAddress: string; // MAC地址
totalMemory: number; // 总内存MB
availableMemory: number; // 可用内存MB
totalStorage: number; // 总存储MB
availableStorage: number; // 可用存储MB
batteryLevel: number; // 电池电量0-100
isCharging: boolean; // 是否在充电
}
```
### 2.6 网络请求接口
#### httpRequest
**作用:** 发起HTTP网络请求
**调用时机:** 需要请求网络数据时
**回调:**
**参数结构:**
```typescript
interface HttpRequestParams {
url: string; // 请求URL
method: string; // 请求方法:"GET" | "POST" | "PUT" | "DELETE"
headers?: {[key: string]: string}; // 请求头
params?: {[key: string]: any}; // URL参数
data?: any; // 请求体数据
timeout?: number; // 超时时间(毫秒)
responseType?: string; // 响应类型:"json" | "text" | "blob"
}
```
**回调结构:**
```typescript
interface HttpResponse {
success: boolean; // 请求是否成功
statusCode: number; // HTTP状态码
data: any; // 响应数据
headers: {[key: string]: string}; // 响应头
errorMsg?: string; // 错误信息
}
```
### 2.7 系统功能接口
#### showToast
**作用:** 显示Toast提示
**调用时机:** 需要给用户提示信息时
**回调:**
**参数结构:**
```typescript
interface ShowToastParams {
message: string; // 提示信息
duration?: number; // 显示时长毫秒默认2000
position?: string; // 显示位置:"top" | "center" | "bottom"
}
```
#### showDialog
**作用:** 显示对话框
**调用时机:** 需要用户确认或输入时
**回调:**
**参数结构:**
```typescript
interface ShowDialogParams {
title: string; // 对话框标题
message: string; // 对话框内容
buttons: DialogButton[]; // 按钮配置
cancelable?: boolean; // 是否可以取消
inputType?: string; // 输入类型:"text" | "password" | "number"
}
interface DialogButton {
text: string; // 按钮文本
style: string; // 按钮样式:"default" | "cancel" | "destructive"
}
```
**回调结构:**
```typescript
interface ShowDialogResponse {
buttonIndex: number; // 点击的按钮索引
inputText?: string; // 输入的文本(如果有输入框)
dismissed: boolean; // 是否被取消
}
```
#### openUrl
**作用:** 打开外部链接
**调用时机:** 需要跳转到外部页面时
**回调:**
**参数结构:**
```typescript
interface OpenUrlParams {
url: string; // 要打开的URL
openType?: string; // 打开方式:"browser" | "webview" | "system"
}
```
#### saveToGallery
**作用:** 保存图片到相册
**调用时机:** 用户保存图片时
**回调:**
**参数结构:**
```typescript
interface SaveToGalleryParams {
imageUrl: string; // 图片URL
imageName?: string; // 保存的文件名
}
```
---
## App调用WebView接口
### 3.1 页面生命周期
#### onPageResume
**作用:** 通知页面恢复显示
**调用时机:** App从后台回到前台时
**参数结构:**
```typescript
interface PageResumeData {
timestamp: number; // 恢复时间戳
fromBackground: boolean; // 是否从后台恢复
}
```
#### onPagePause
**作用:** 通知页面暂停显示
**调用时机:** App进入后台时
#### onPageDestroy
**作用:** 通知页面即将销毁
**调用时机:** WebView即将被销毁时
### 3.2 网络状态通知
#### onNetworkChanged
**作用:** 通知网络状态变化
**调用时机:** 设备网络状态发生变化时
**参数结构:**
```typescript
interface NetworkStatus {
type: string; // 网络类型:"wifi" | "mobile" | "none"
isConnected: boolean; // 是否连接
strength?: number; // 信号强度0-4
}
```
### 3.3 数据更新通知
#### onUserDataChanged
**作用:** 通知用户数据发生变化
**调用时机:** 用户金币、等级等数据更新时
**参数结构:**
```typescript
interface UserDataChange {
type: string; // 变化类型:"coins" | "level" | "vip"
oldValue: any; // 旧值
newValue: any; // 新值
reason: string; // 变化原因
}
```
---
## 数据结构定义
### 4.1 基础数据结构
#### BaseResponse
所有接口回调的基础结构:
```typescript
interface BaseResponse {
success: boolean; // 操作是否成功
code: number; // 状态码0表示成功
message: string; // 提示信息
data?: any; // 具体数据
}
```
#### Position
位置信息:
```typescript
interface Position {
x: number; // X坐标
y: number; // Y坐标
width?: number; // 宽度
height?: number; // 高度
}
```
#### Size
尺寸信息:
```typescript
interface Size {
width: number; // 宽度
height: number; // 高度
}
```
### 4.2 游戏数据结构
#### GameInfo
游戏信息:
```typescript
interface GameInfo {
gameId: string; // 游戏ID
gameName: string; // 游戏名称
gameType: string; // 游戏类型
gameUrl: string; // 游戏链接
gameIcon: string; // 游戏图标
gameDesc: string; // 游戏描述
version: string; // 游戏版本
size: number; // 游戏大小(字节)
rating: number; // 游戏评分
downloadCount: number; // 下载次数
tags: string[]; // 游戏标签
screenshots: string[]; // 游戏截图
isInstalled: boolean; // 是否已安装
isUpdatable: boolean; // 是否可更新
}
```
#### GameProgress
游戏进度:
```typescript
interface GameProgress {
gameId: string; // 游戏ID
level: number; // 当前关卡
score: number; // 最高分数
playTime: number; // 游戏时长(秒)
achievements: string[]; // 已获得成就
lastPlayTime: string; // 最后游戏时间
}
```
### 4.3 分享数据结构
#### ShareConfig
分享配置:
```typescript
interface ShareConfig {
platforms: string[]; // 支持的平台列表
defaultPlatform: string; // 默认平台
maxTitleLength: number; // 标题最大长度
maxDescLength: number; // 描述最大长度
imageMaxSize: number; // 图片最大尺寸(字节)
supportedImageTypes: string[]; // 支持的图片格式
}
```
#### ShareResult
分享结果:
```typescript
interface ShareResult {
platform: string; // 分享平台
success: boolean; // 是否成功
errorCode?: number; // 错误码
errorMsg?: string; // 错误信息
shareId?: string; // 分享ID用于统计
}
```
### 4.4 媒体数据结构
#### AudioInfo
音频信息:
```typescript
interface AudioInfo {
audioId: string; // 音频ID
url: string; // 音频URL
title: string; // 音频标题
artist?: string; // 艺术家
album?: string; // 专辑
duration: number; // 时长(秒)
size: number; // 文件大小(字节)
format: string; // 音频格式
bitrate: number; // 比特率
}
```
#### VideoInfo
视频信息:
```typescript
interface VideoInfo {
videoId: string; // 视频ID
url: string; // 视频URL
title: string; // 视频标题
poster: string; // 封面图
duration: number; // 时长(秒)
size: number; // 文件大小(字节)
format: string; // 视频格式
resolution: string; // 分辨率
frameRate: number; // 帧率
}
```
---
## 错误码定义
| 错误码 | 说明 | 解决方案 |
|--------|------|----------|
| 0 | 成功 | - |
| 1001 | 参数错误 | 检查传入参数格式和必填字段 |
| 1002 | 接口不存在 | 确认接口名称是否正确 |
| 1003 | 权限不足 | 检查相关权限是否已申请 |
| 2001 | 网络错误 | 检查网络连接 |
| 2002 | 服务器错误 | 稍后重试或联系技术支持 |
| 3001 | 用户未登录 | 引导用户登录 |
| 3002 | 用户信息获取失败 | 重新获取用户信息 |
| 4001 | 文件不存在 | 确认文件路径是否正确 |
| 4002 | 文件读取失败 | 检查文件权限 |
| 4003 | 文件写入失败 | 检查存储权限和空间 |
| 5001 | 分享平台不支持 | 选择其他分享平台 |
| 5002 | 分享内容格式错误 | 检查分享内容格式 |
| 6001 | 媒体文件格式不支持 | 使用支持的媒体格式 |
| 6002 | 媒体播放失败 | 检查文件是否损坏或网络连接 |
---
## 接口调用示例
### 完整的游戏切换示例
```javascript
// 1. 检查游戏是否已安装
window.WebViewJavascriptBridge.callHandler('getGameinstall', {
gameId: "puzzle_game_001"
}, function(response) {
if (response.isInstalled) {
// 游戏已安装,直接切换
switchToGame();
} else {
// 游戏未安装,提示下载
showDownloadDialog();
}
});
// 2. 切换到游戏
function switchToGame() {
window.WebViewJavascriptBridge.callHandler('SwitchOverGameData', {
gameId: "puzzle_game_001",
gameType: "H5",
gameUrl: "https://games.example.com/puzzle",
gameName: "拼图大师",
gameIcon: "https://cdn.example.com/icons/puzzle.png",
gameDesc: "经典拼图游戏,锻炼思维能力",
extraData: {
level: 1,
userId: "user123",
fromPage: "homepage"
}
});
}
```
### 分享功能完整示例
```javascript
// 1. 获取可用分享平台
window.WebViewJavascriptBridge.callHandler('getSharePlatforms', {}, function(response) {
if (response.success) {
showShareDialog(response.platforms);
}
});
// 2. 执行分享
function shareContent(platform) {
window.WebViewJavascriptBridge.callHandler('friendsSharetypeUrlToptitleDescript', {
shareType: platform,
title: "我在玩拼图大师!",
description: "超级好玩的拼图游戏,快来一起挑战吧!",
url: "https://game.example.com/puzzle?invite=user123",
imageUrl: "https://cdn.example.com/share/puzzle_share.png"
}, function(response) {
if (response.success) {
window.WebViewJavascriptBridge.callHandler('showToast', {
message: "分享成功!",
duration: 2000,
position: "center"
});
} else {
window.WebViewJavascriptBridge.callHandler('showToast', {
message: "分享失败:" + response.errorMsg,
duration: 3000,
position: "center"
});
}
});
}
```
### 媒体播放示例
```javascript
// 播放背景音乐
window.WebViewJavascriptBridge.callHandler('mediaTypeAudio', {
action: "play",
audioUrl: "https://cdn.example.com/audio/bg_music.mp3",
volume: 0.5,
loop: true,
audioId: "bg_music"
}, function(response) {
if (response.success) {
console.log("背景音乐开始播放");
// 保存音频ID以便后续控制
window.currentBgMusicId = response.audioId;
}
});
// 暂停背景音乐
function pauseBgMusic() {
window.WebViewJavascriptBridge.callHandler('mediaTypeAudio', {
action: "pause",
audioId: window.currentBgMusicId
});
}
// 恢复背景音乐
function resumeBgMusic() {
window.WebViewJavascriptBridge.callHandler('mediaTypeAudio', {
action: "resume",
audioId: window.currentBgMusicId
});
}
```
### 用户信息和数据更新示例
```javascript
// 获取用户信息
window.WebViewJavascriptBridge.callHandler('getUserInfo', {
fields: ["userId", "nickname", "avatar", "coins", "level"]
}, function(response) {
if (response.success) {
updateUserDisplay(response.data);
}
});
// 更新用户金币
function updateCoins(amount, reason) {
window.WebViewJavascriptBridge.callHandler('updateUserCoins', {
amount: amount,
reason: reason,
gameId: "puzzle_game_001"
}, function(response) {
if (response.success) {
// 更新UI显示
updateCoinDisplay(response.data.newBalance);
}
});
}
// 监听App推送的用户数据变化
window.WebViewJavascriptBridge.registerHandler('onUserDataChanged', function(data) {
if (data.type === 'coins') {
updateCoinDisplay(data.newValue);
showCoinChangeAnimation(data.oldValue, data.newValue);
}
});
```
---
## 注意事项
1. **参数验证**:调用接口前请确保所有必填参数都已提供,参数格式正确
2. **错误处理**:建议对所有接口调用都进行错误处理,提供友好的用户提示
3. **权限检查**某些接口需要特定权限请确保已在AndroidManifest.xml中声明
4. **性能考虑**:频繁调用的接口(如获取用户信息)建议加入缓存机制
5. **版本兼容**不同版本的App可能支持的接口有差异建议加入版本检查
6. **数据大小**:传递大量数据时注意性能影响,考虑分批传输或使用文件传输
7. **回调超时**:长时间无回调的接口建议设置超时处理
8. **内存管理**:及时释放不再使用的回调函数,避免内存泄漏
---
*本文档基于TSGame Android版本如有更新请及时同步修改。*

File diff suppressed because it is too large Load Diff

6
entry/.gitignore vendored Normal file
View File

@@ -0,0 +1,6 @@
/node_modules
/oh_modules
/.preview
/build
/.cxx
/.test

28
entry/build-profile.json5 Normal file
View File

@@ -0,0 +1,28 @@
{
"apiType": "stageMode",
"buildOption": {
},
"buildOptionSet": [
{
"name": "release",
"arkOptions": {
"obfuscation": {
"ruleOptions": {
"enable": false,
"files": [
"./obfuscation-rules.txt"
]
}
}
}
},
],
"targets": [
{
"name": "default"
},
{
"name": "ohosTest",
}
]
}

6
entry/hvigorfile.ts Normal file
View File

@@ -0,0 +1,6 @@
import { hapTasks } from '@ohos/hvigor-ohos-plugin';
export default {
system: hapTasks, /* Built-in plugin of Hvigor. It cannot be modified. */
plugins: [] /* Custom plugin to extend the functionality of Hvigor. */
}

View File

@@ -0,0 +1,23 @@
# Define project specific obfuscation rules here.
# You can include the obfuscation configuration files in the current module's build-profile.json5.
#
# For more details, see
# https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/source-obfuscation-V5
# Obfuscation options:
# -disable-obfuscation: disable all obfuscations
# -enable-property-obfuscation: obfuscate the property names
# -enable-toplevel-obfuscation: obfuscate the names in the global scope
# -compact: remove unnecessary blank spaces and all line feeds
# -remove-log: remove all console.* statements
# -print-namecache: print the name cache that contains the mapping from the old names to new names
# -apply-namecache: reuse the given cache file
# Keep options:
# -keep-property-name: specifies property names that you want to keep
# -keep-global-name: specifies names that you want to keep in the global scope
-enable-property-obfuscation
-enable-toplevel-obfuscation
-enable-filename-obfuscation
-enable-export-obfuscation

10
entry/oh-package.json5 Normal file
View File

@@ -0,0 +1,10 @@
{
"name": "entry",
"version": "1.0.0",
"description": "Please describe the basic information.",
"main": "",
"author": "",
"license": "",
"dependencies": {}
}

View File

@@ -0,0 +1,44 @@
import { AbilityConstant, ConfigurationConstant, UIAbility, Want } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { window } from '@kit.ArkUI';
const DOMAIN = 0x0000;
export default class EntryAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET);
hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onCreate');
}
onDestroy(): void {
hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onDestroy');
}
onWindowStageCreate(windowStage: window.WindowStage): void {
// Main window is created, set main page for this ability
hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
windowStage.loadContent('pages/Index', (err) => {
if (err.code) {
hilog.error(DOMAIN, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err));
return;
}
hilog.info(DOMAIN, 'testTag', 'Succeeded in loading the content.');
});
}
onWindowStageDestroy(): void {
// Main window is destroyed, release UI related resources
hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');
}
onForeground(): void {
// Ability has brought to foreground
hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onForeground');
}
onBackground(): void {
// Ability has back to background
hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onBackground');
}
}

View File

@@ -0,0 +1,16 @@
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BackupExtensionAbility, BundleVersion } from '@kit.CoreFileKit';
const DOMAIN = 0x0000;
export default class EntryBackupAbility extends BackupExtensionAbility {
async onBackup() {
hilog.info(DOMAIN, 'testTag', 'onBackup ok');
await Promise.resolve();
}
async onRestore(bundleVersion: BundleVersion) {
hilog.info(DOMAIN, 'testTag', 'onRestore ok %{public}s', JSON.stringify(bundleVersion));
await Promise.resolve();
}
}

View File

@@ -0,0 +1,23 @@
@Entry
@Component
struct Index {
@State message: string = 'Hello World';
build() {
RelativeContainer() {
Text(this.message)
.id('HelloWorld')
.fontSize($r('app.float.page_text_font_size'))
.fontWeight(FontWeight.Bold)
.alignRules({
center: { anchor: '__container__', align: VerticalAlign.Center },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
})
.onClick(() => {
this.message = 'Welcome';
})
}
.height('100%')
.width('100%')
}
}

View File

@@ -0,0 +1,53 @@
{
"module": {
"name": "entry",
"type": "entry",
"description": "$string:module_desc",
"mainElement": "EntryAbility",
"deviceTypes": [
"phone",
"tablet",
"2in1",
"wearable"
],
"deliveryWithInstall": true,
"installationFree": false,
"pages": "$profile:main_pages",
"abilities": [
{
"name": "EntryAbility",
"srcEntry": "./ets/entryability/EntryAbility.ets",
"description": "$string:EntryAbility_desc",
"icon": "$media:layered_image",
"label": "$string:EntryAbility_label",
"startWindowIcon": "$media:startIcon",
"startWindowBackground": "$color:start_window_background",
"exported": true,
"skills": [
{
"entities": [
"entity.system.home"
],
"actions": [
"action.system.home"
]
}
]
}
],
"extensionAbilities": [
{
"name": "EntryBackupAbility",
"srcEntry": "./ets/entrybackupability/EntryBackupAbility.ets",
"type": "backup",
"exported": false,
"metadata": [
{
"name": "ohos.extension.backup",
"resource": "$profile:backup_config"
}
],
}
]
}
}

View File

@@ -0,0 +1,8 @@
{
"color": [
{
"name": "start_window_background",
"value": "#FFFFFF"
}
]
}

View File

@@ -0,0 +1,8 @@
{
"float": [
{
"name": "page_text_font_size",
"value": "50fp"
}
]
}

View File

@@ -0,0 +1,16 @@
{
"string": [
{
"name": "module_desc",
"value": "module description"
},
{
"name": "EntryAbility_desc",
"value": "description"
},
{
"name": "EntryAbility_label",
"value": "label"
}
]
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.6 KiB

View File

@@ -0,0 +1,7 @@
{
"layered-image":
{
"background" : "$media:background",
"foreground" : "$media:foreground"
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

View File

@@ -0,0 +1,3 @@
{
"allowToBackupRestore": true
}

View File

@@ -0,0 +1,5 @@
{
"src": [
"pages/Index"
]
}

View File

@@ -0,0 +1,8 @@
{
"color": [
{
"name": "start_window_background",
"value": "#000000"
}
]
}

View File

@@ -0,0 +1,2 @@
{
}

View File

@@ -0,0 +1,35 @@
import { hilog } from '@kit.PerformanceAnalysisKit';
import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium';
export default function abilityTest() {
describe('ActsAbilityTest', () => {
// Defines a test suite. Two parameters are supported: test suite name and test suite function.
beforeAll(() => {
// Presets an action, which is performed only once before all test cases of the test suite start.
// This API supports only one parameter: preset action function.
})
beforeEach(() => {
// Presets an action, which is performed before each unit test case starts.
// The number of execution times is the same as the number of test cases defined by **it**.
// This API supports only one parameter: preset action function.
})
afterEach(() => {
// Presets a clear action, which is performed after each unit test case ends.
// The number of execution times is the same as the number of test cases defined by **it**.
// This API supports only one parameter: clear action function.
})
afterAll(() => {
// Presets a clear action, which is performed after all test cases of the test suite end.
// This API supports only one parameter: clear action function.
})
it('assertContain', 0, () => {
// Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function.
hilog.info(0x0000, 'testTag', '%{public}s', 'it begin');
let a = 'abc';
let b = 'b';
// Defines a variety of assertion methods, which are used to declare expected boolean conditions.
expect(a).assertContain(b);
expect(a).assertEqual(a);
})
})
}

View File

@@ -0,0 +1,5 @@
import abilityTest from './Ability.test';
export default function testsuite() {
abilityTest();
}

View File

@@ -0,0 +1,14 @@
{
"module": {
"name": "entry_test",
"type": "feature",
"deviceTypes": [
"phone",
"tablet",
"2in1",
"wearable"
],
"deliveryWithInstall": true,
"installationFree": false
}
}

View File

@@ -0,0 +1,5 @@
import localUnitTest from './LocalUnit.test';
export default function testsuite() {
localUnitTest();
}

View File

@@ -0,0 +1,33 @@
import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium';
export default function localUnitTest() {
describe('localUnitTest', () => {
// Defines a test suite. Two parameters are supported: test suite name and test suite function.
beforeAll(() => {
// Presets an action, which is performed only once before all test cases of the test suite start.
// This API supports only one parameter: preset action function.
});
beforeEach(() => {
// Presets an action, which is performed before each unit test case starts.
// The number of execution times is the same as the number of test cases defined by **it**.
// This API supports only one parameter: preset action function.
});
afterEach(() => {
// Presets a clear action, which is performed after each unit test case ends.
// The number of execution times is the same as the number of test cases defined by **it**.
// This API supports only one parameter: clear action function.
});
afterAll(() => {
// Presets a clear action, which is performed after all test cases of the test suite end.
// This API supports only one parameter: clear action function.
});
it('assertContain', 0, () => {
// Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function.
let a = 'abc';
let b = 'b';
// Defines a variety of assertion methods, which are used to declare expected boolean conditions.
expect(a).assertContain(b);
expect(a).assertEqual(a);
});
});
}

View File

@@ -0,0 +1,22 @@
{
"modelVersion": "5.1.0",
"dependencies": {
},
"execution": {
// "analyze": "normal", /* Define the build analyze mode. Value: [ "normal" | "advanced" | false ]. Default: "normal" */
// "daemon": true, /* Enable daemon compilation. Value: [ true | false ]. Default: true */
// "incremental": true, /* Enable incremental compilation. Value: [ true | false ]. Default: true */
// "parallel": true, /* Enable parallel compilation. Value: [ true | false ]. Default: true */
// "typeCheck": false, /* Enable typeCheck. Value: [ true | false ]. Default: false */
},
"logging": {
// "level": "info" /* Define the log level. Value: [ "debug" | "info" | "warn" | "error" ]. Default: "info" */
},
"debugging": {
// "stacktrace": false /* Disable stacktrace compilation. Value: [ true | false ]. Default: false */
},
"nodeOptions": {
// "maxOldSpaceSize": 8192 /* Enable nodeOptions maxOldSpaceSize compilation. Unit M. Used for the daemon process. Default: 8192*/
// "exposeGC": true /* Enable to trigger garbage collection explicitly. Default: true*/
}
}

6
hvigorfile.ts Normal file
View File

@@ -0,0 +1,6 @@
import { appTasks } from '@ohos/hvigor-ohos-plugin';
export default {
system: appTasks, /* Built-in plugin of Hvigor. It cannot be modified. */
plugins: [] /* Custom plugin to extend the functionality of Hvigor. */
}

28
oh-package-lock.json5 Normal file
View File

@@ -0,0 +1,28 @@
{
"meta": {
"stableOrder": true,
"enableUnifiedLockfile": false
},
"lockfileVersion": 3,
"ATTENTION": "THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.",
"specifiers": {
"@ohos/hamock@1.0.0": "@ohos/hamock@1.0.0",
"@ohos/hypium@1.0.21": "@ohos/hypium@1.0.21"
},
"packages": {
"@ohos/hamock@1.0.0": {
"name": "@ohos/hamock",
"version": "1.0.0",
"integrity": "sha512-K6lDPYc6VkKe6ZBNQa9aoG+ZZMiwqfcR/7yAVFSUGIuOAhPvCJAo9+t1fZnpe0dBRBPxj2bxPPbKh69VuyAtDg==",
"resolved": "https://ohpm.openharmony.cn/ohpm/@ohos/hamock/-/hamock-1.0.0.har",
"registryType": "ohpm"
},
"@ohos/hypium@1.0.21": {
"name": "@ohos/hypium",
"version": "1.0.21",
"integrity": "sha512-iyKGMXxE+9PpCkqEwu0VykN/7hNpb+QOeIuHwkmZnxOpI+dFZt6yhPB7k89EgV1MiSK/ieV/hMjr5Z2mWwRfMQ==",
"resolved": "https://ohpm.openharmony.cn/ohpm/@ohos/hypium/-/hypium-1.0.21.har",
"registryType": "ohpm"
}
}
}

10
oh-package.json5 Normal file
View File

@@ -0,0 +1,10 @@
{
"modelVersion": "5.1.0",
"description": "Please describe the basic information.",
"dependencies": {
},
"devDependencies": {
"@ohos/hypium": "1.0.21",
"@ohos/hamock": "1.0.0"
}
}