
1. 引言
在鸿蒙(HarmonyOS)应用开发中,配置文件扮演着至关重要的角色,它们定义了应用的基本信息、能力权限、界面样式、多设备适配策略等关键属性。鸿蒙系统采用了一套结构化的JSON配置体系,通过不同层级的配置文件协同工作,确保应用能够在各种鸿蒙设备上正常运行并提供一致的用户体验。本文将全面深入地解析鸿蒙应用的JSON配置文件体系,从基础概念到高级特性,帮助开发者掌握配置文件的设计理念和最佳实践。
2. 鸿蒙配置文件体系架构
2.1 配置文件类型与层级关系
鸿蒙应用的配置文件体系采用了清晰的分层结构,从应用级到模块级再到具体的资源配置,形成了完整的配置树。这种分层设计使得配置管理更加清晰、灵活,同时也便于实现多设备适配和模块化开发。
鸿蒙配置文件主要包括以下几个层级:
- 应用级配置:定义整个应用的全局属性,位于
AppScope/app.json5,主要包括应用名称、版本、图标、权限等基础信息 - 模块级配置:定义应用内各个模块的具体配置,位于各个模块目录下的
module.json5,包括页面路由、组件声明、模块依赖等 - 资源配置:位于各模块的
resources目录下,通过不同限定词目录组织多语言、多设备的资源文件 - 项目级配置:位于项目根目录,如
build-profile.json5等,主要用于构建配置和项目管理
这种层级关系可以用下图表示:
项目根目录/
├── AppScope/
│ └── app.json5 # 应用级配置
├── entry/ # 主模块
│ ├── module.json5 # 主模块配置
│ └── src/main/resources/ # 主模块资源
├── feature/ # 功能模块
│ ├── module.json5 # 功能模块配置
│ └── src/main/resources/ # 功能模块资源
└── build-profile.json5 # 项目级配置
2.2 JSON5格式解析
鸿蒙应用的配置文件采用JSON5(JavaScript Object Notation 5)格式,这是JSON的超集,提供了更多便捷的语法特性,使得配置文件的编写和维护更加友好。
JSON5相比标准JSON的主要增强特性包括:
- 注释支持:允许在配置文件中添加单行注释(
//)和多行注释(/* */),便于开发者添加说明和文档 - 尾随逗号:允许在对象和数组的最后一个元素后添加逗号,减少版本控制时的差异
- 单引号字符串:除了双引号外,还支持使用单引号定义字符串
- 多行字符串:支持使用反斜杠(
\)实现多行字符串,提高长文本的可读性 - 十六进制数字:支持使用十六进制表示数字
- 对象键名可以不带引号:对于合法的标识符,可以省略键名的引号
- undefined和NaN值:支持这些特殊值
下面是一个JSON5格式的配置示例:
{
// 这是应用配置示例
app: {
bundleName: 'com.example.myapp',
versionName: '1.0.0',
versionCode: 1,
apiVersion: {
compatible: 9,
target: 9,
},
// 配置数组,注意尾随逗号
permissions: [
'ohos.permission.INTERNET',
'ohos.permission.READ_USER_STORAGE',
],
},
}
JSON5格式的引入大大提升了鸿蒙配置文件的可读性和可维护性,特别是对于大型项目中的复杂配置。
2.3 配置文件加载机制
鸿蒙系统在应用启动和运行过程中,会按照特定的顺序和规则加载配置文件,确保配置的正确性和一致性。
配置文件加载的主要流程包括:
- 初始化阶段:应用启动时,系统首先加载应用级配置(app.json5),获取应用的基本信息和全局配置
- 模块加载阶段:随后加载各个模块的配置文件(module.json5),解析页面路由、组件声明等信息
- 资源加载阶段:根据设备特性(如语言、屏幕尺寸等),加载对应的资源配置文件
- 配置合并阶段:系统会将不同层级的配置进行合并,解决配置冲突,生成最终的应用配置
配置合并遵循以下规则:
- 优先级规则:低层级配置可以覆盖高层级配置中的同名项
- 继承规则:未在低层级配置中定义的项,会自动继承高层级配置的值
- 数组合并:对于数组类型的配置,通常采用追加的方式进行合并,而非替换
这种灵活的加载机制使得开发者可以在不同层级的配置文件中分别定义不同粒度的配置,既保证了全局一致性,又允许模块进行个性化定制。同时,系统会对配置进行验证,确保格式正确、依赖完整、权限合理等,以避免潜在的问题。
3. 应用配置文件(app.json5)详解
应用配置文件(app.json5)是鸿蒙应用的核心配置文件,位于AppScope目录下,定义了应用的全局属性和基本信息。这个文件对整个应用至关重要,因为它包含了系统识别和管理应用所需的基本元数据。
3.1 基础配置信息
基础配置信息是app.json5中最核心的部分,主要通过app对象定义,包含以下关键字段:
- bundleName:应用的包名,必须使用反向域名格式(如com.example.myapp),在整个鸿蒙生态中唯一标识一个应用
- versionName:应用的版本名称,用于向用户展示的版本号,如"1.0.0"
- versionCode:应用的版本代码,用于版本更新控制的整数,每次更新时必须大于上一版本
- minCompatibleVersionCode:最小兼容版本代码,用于限制应用的回退范围
- apiVersion:API版本配置,包含:
- compatible:兼容的最低API版本
- target:目标API版本
- releaseType:版本类型,可选值为"Canary"、“Beta”、"Release"等
下面是一个基础配置的示例:
{
"app": {
"bundleName": "com.example.harmonyapp",
"versionName": "1.2.3",
"versionCode": 103,
"minCompatibleVersionCode": 101,
"apiVersion": {
"compatible": 9,
"target": 9,
"releaseType": "Release"
}
}
}
3.2 能力配置
能力配置定义了应用可以提供和使用的各种系统能力,主要通过abilities和extensionAbilities两个数组进行配置。
3.2.1 UIAbility配置
UIAbility是鸿蒙应用中提供界面交互的组件,在app.json5中可以定义全局的UIAbility配置:
{
"abilities": [
{
"name": "MainAbility",
"srcEntry": "./ets/entryability/EntryAbility.ts",
"label": "MainAbility",
"description": "Main entry of the application",
"icon": "$media:icon",
"visible": true,
"skills": [
{
"entities": ["entity.system.home"],
"actions": ["action.system.home"]
}
]
}
]
}
常用的UIAbility配置项包括:
- name:Ability名称,在应用内唯一
- srcEntry:Ability源码入口路径
- label:在系统中显示的Ability名称
- description:Ability的描述信息
- icon:Ability图标
- visible:是否对其他应用可见
- skills:Ability支持的技能,用于隐式启动
3.2.2 扩展能力配置
扩展能力(ExtensionAbility)是鸿蒙系统提供的一种扩展机制,用于实现特定的系统功能,如输入法、桌面小部件等:
{
"extensionAbilities": [
{
"name": "WidgetExtension",
"type": "widget",
"srcEntry": "./ets/widget/WidgetExtension.ts",
"label": "MyWidget",
"description": "Home screen widget",
"icon": "$media:widget_icon",
"metadata": [
{
"name": "ohos.extension.widget.size",
"value": "2*2"
}
]
}
]
}
3.3 权限配置
权限配置定义了应用需要使用的系统权限,这是保护用户隐私和系统安全的重要机制。权限配置主要通过permissions数组定义:
{
"module": {
"requestPermissions": [
{
"name": "ohos.permission.INTERNET",
"reason": "需要访问网络获取数据",
"usedScene": {
"ability": ["MainAbility"],
"when": "inuse"
}
},
{
"name": "ohos.permission.READ_USER_STORAGE",
"reason": "需要读取本地文件",
"usedScene": {
"ability": ["MainAbility"],
"when": "inuse"
}
}
]
}
}
权限配置的主要字段包括:
- name:权限名称,如ohos.permission.INTERNET
- reason:申请权限的原因,会向用户展示
- usedScene:使用场景,包括:
- ability:使用该权限的Ability列表
- when:使用时机,可选值为"inuse"(使用中)和"always"(始终)
鸿蒙系统将权限分为不同的等级,从低到高包括:
- normal:普通权限,系统自动授予
- system_grant:系统授权权限,需要在应用安装时声明
- user_grant:用户授权权限,需要在运行时请求用户授权
3.4 界面配置
界面配置定义了应用的全局界面样式和行为,主要包括以下几个方面:
3.4.1 全局样式配置
{
"module": {
"metaData": {
"customizeData": [
{
"name": "hwc-theme",
"value": "@ohos:color:ohos_id_color_primary"
}
]
},
"theme": "@ohos:appcompat"
}
}
3.4.2 页面配置
在app.json5中可以定义应用的页面配置,包括默认页面、页面路由等:
{
"module": {
"pages": [
"pages/Index",
"pages/Detail",
"pages/Settings"
],
"mainElement": "pages/Index"
}
}
3.5 应用图标与启动页配置
应用图标和启动页是用户对应用的第一印象,在app.json5中可以进行详细配置:
3.5.1 应用图标配置
{
"module": {
"abilities": [
{
"icon": "$media:icon",
"roundIcon": "$media:round_icon",
"label": "我的应用"
}
]
}
}
应用图标通常需要提供多种尺寸和形状,以适应不同设备和场景的需求。鸿蒙系统支持通过资源限定词目录提供不同尺寸的图标。
3.5.2 启动页配置
启动页(Splash Screen)配置可以提升应用的启动体验:
{
"module": {
"abilities": [
{
"splashScreen": {
"backgroundColor": "#FFFFFF",
"image": "$media:splash",
"isAlwaysShow": false,
"windowBackgroundColor": "#FFFFFF"
}
}
]
}
}
启动页配置的主要字段包括:
- backgroundColor:启动页背景色
- image:启动页图片
- isAlwaysShow:是否总是显示启动页
- windowBackgroundColor:窗口背景色
通过合理配置app.json5,开发者可以定义应用的基本信息、功能范围、访问权限和界面表现,为应用的正常运行和良好用户体验奠定基础。
4. 模块配置文件(module.json5)深入分析
模块配置文件(module.json5)是鸿蒙应用中定义各个功能模块属性的配置文件,位于每个模块的根目录下。在鸿蒙的模块化架构中,module.json5扮演着至关重要的角色,它定义了模块的基本信息、页面结构、依赖关系和权限需求等。
4.1 模块标识与基础信息
模块的基础信息定义了模块的身份标识和基本属性,主要通过module对象中的关键字段配置:
{
"module": {
"name": "entry",
"type": "entry",
"description": "主入口模块",
"mainElement": "EntryAbility",
"deviceTypes": ["phone", "tablet", "tv", "car"],
"deliveryWithInstall": true,
"installationFree": false,
"pages": ["pages/Index"]
}
}
主要配置项包括:
- name:模块名称,在应用内唯一
- type:模块类型,可选值为:
- entry:应用入口模块,一个应用必须且只能有一个
- feature:功能模块,可以有多个
- shared:共享模块,用于代码共享
- description:模块描述信息
- mainElement:模块的主入口元素,通常是Ability名称
- deviceTypes:支持的设备类型列表
- deliveryWithInstall:是否随应用安装
- installationFree:是否支持免安装运行
- pages:模块包含的页面列表
4.2 页面路由配置
页面路由配置定义了模块内的页面结构和导航关系,是实现页面跳转的基础。在module.json5中,主要通过pages数组和abilities中的配置实现:
4.2.1 页面注册
{
"module": {
"pages": [
"pages/Index",
"pages/DetailPage",
"pages/SettingsPage",
"pages/user/ProfilePage",
"pages/product/ListPage"
]
}
}
页面路径通常遵循以下规则:
- 相对路径,相对于模块的src/main/ets目录
- 页面文件的扩展名(如.ets)通常省略
- 可以使用多级目录结构组织页面
4.2.2 路由相关配置
在Ability配置中,可以通过元数据进一步定制路由行为:
{
"module": {
"abilities": [
{
"name": "EntryAbility",
"srcEntry": "./ets/entryability/EntryAbility.ts",
"metaData": [
{
"name": "ohos.meta.data.params.uri",
"value": "pages/Index"
}
],
"skills": [
{
"entities": ["entity.system.home"],
"actions": ["action.system.home"]
},
{
"entities": ["entity.system.default"],
"actions": ["ohos.want.action.viewData"],
"uris": [
{
"scheme": "https",
"host": "example.com",
"path": "/detail/*"
}
]
}
]
}
]
}
}
这种配置允许应用响应外部的URL请求,实现深度链接功能。
4.3 模块依赖关系
在大型应用中,模块之间通常存在依赖关系。鸿蒙系统通过module.json5中的配置管理这些依赖:
4.3.1 内部模块依赖
应用内部的模块之间可以相互依赖:
{
"module": {
"name": "feature1",
"type": "feature",
"dependencies": [
{
"moduleName": "shared",
"type": "shared"
}
]
}
}
4.3.2 外部包依赖
除了内部模块,鸿蒙应用还可以依赖外部包:
{
"module": {
"reqCapabilities": [
"internet"
],
"localDependencies": [
{
"name": "@ohos/router",
"version": "^1.0.0"
},
{
"name": "@ohos/hilog",
"version": "^1.0.0"
}
]
}
}
依赖管理的主要配置项包括:
- dependencies:内部模块依赖列表
- reqCapabilities:请求的系统能力列表
- localDependencies:本地依赖包列表
4.4 模块级权限与能力
模块配置文件允许为特定模块配置权限和能力,这与应用级配置相互补充:
4.4.1 权限配置
{
"module": {
"requestPermissions": [
{
"name": "ohos.permission.CAMERA",
"reason": "需要使用相机进行扫码",
"usedScene": {
"ability": ["ScanAbility"],
"when": "inuse"
}
},
{
"name": "ohos.permission.RECORD_AUDIO",
"reason": "需要录音功能",
"usedScene": {
"ability": ["AudioRecordAbility"],
"when": "inuse"
}
}
]
}
}
4.4.2 能力配置
{
"module": {
"abilities": [
{
"name": "ScanAbility",
"srcEntry": "./ets/scan/ScanAbility.ts",
"label": "扫码功能",
"description": "提供二维码扫描能力",
"icon": "$media:scan_icon",
"visible": true,
"skills": [
{
"entities": ["entity.system.default"],
"actions": ["com.example.action.SCAN"]
}
]
}
],
"extensionAbilities": [
{
"name": "NotificationExtension",
"type": "notification",
"srcEntry": "./ets/notification/NotificationExtension.ts",
"label": "通知扩展",
"description": "自定义通知显示"
}
]
}
}
4.5 UIAbility配置详解
UIAbility是鸿蒙应用中负责页面生命周期管理的核心组件,其配置非常详细和灵活:
{
"module": {
"abilities": [
{
"name": "MainAbility",
"srcEntry": "./ets/entryability/MainAbility.ts",
"label": "主应用",
"description": "应用主入口",
"icon": "$media:icon",
"roundIcon": "$media:round_icon",
"visible": true,
"orientation": "unspecified",
"launchType": "standard",
"process": "com.example.main",
"permission": "",
"backgroundModes": [],
"skills": [
{
"entities": ["entity.system.home"],
"actions": ["action.system.home"]
}
],
"splashScreen": {
"backgroundColor": "#FFFFFF",
"image": "$media:splash",
"displayDuration": 2000,
"autoHide": true
},
"metadata": [
{
"name": "ohos.extension.form.size",
"value": "2*2,4*4"
}
]
}
]
}
}
UIAbility的主要配置项包括:
- name:Ability名称
- srcEntry:源码入口路径
- label:显示名称
- description:描述信息
- icon/roundIcon:图标配置
- visible:是否可见
- orientation:屏幕方向,可选值为:
- “unspecified”
- “portrait”
- “landscape”
- “followRecent”
- launchType:启动模式,可选值为:
- “standard”:标准模式
- “singletop”:单顶模式
- “singletask”:单任务模式
- “singleinstance”:单实例模式
- process:所属进程名
- permission:访问权限
- backgroundModes:后台运行模式
- skills:支持的技能列表
- splashScreen:启动页配置
- metadata:元数据配置
通过对module.json5的深入理解和合理配置,开发者可以构建出结构清晰、功能丰富、高度模块化的鸿蒙应用。模块配置文件是实现鸿蒙应用模块化架构的关键所在,对于大型应用的开发和维护尤为重要。
5. 资源配置与多设备适配
在鸿蒙应用开发中,资源配置是实现多设备适配和灵活应用开发的关键组成部分。资源配置文件与JSON配置文件协同工作,为应用提供了丰富的资源支持和设备适配能力。鸿蒙系统支持多种资源类型和丰富的限定词,使得开发者能够构建出在各种设备和场景下都能良好运行的应用。
5.1 资源文件目录结构
鸿蒙应用的资源文件采用了一种层次化的目录结构,通过限定词机制实现对不同设备、不同语言和不同场景的资源适配。
5.1.1 基础资源目录结构
标准的资源目录结构如下:
src/main/resources/
├── base/ # 基础资源目录
│ ├── element/ # 元素资源(颜色、字符串等)
│ ├── media/ # 媒体资源(图片、音频等)
│ ├── layout/ # 布局资源
│ ├── profile/ # 配置文件
│ ├── animation/ # 动画资源
│ └── rawfile/ # 原始文件
├── en_US/ # 英语资源(美国)
│ └── element/
├── zh_CN/ # 中文资源(中国)
│ └── element/
├── zh_Hant/ # 繁体中文资源
│ └── element/
├── zh_HK/ # 香港中文资源
│ └── element/
├── zh_TW/ # 台湾中文资源
│ └── element/
├── zh_SG/ # 新加坡中文资源
│ └── element/
├── zh_MO/ # 澳门中文资源
│ └── element/
├── phone/ # 手机设备资源
│ └── element/
├── tablet/ # 平板设备资源
│ └── element/
├── tv/ # 电视设备资源
│ └── element/
├── watch/ # 手表设备资源
│ └── element/
├── car/ # 车载设备资源
│ └── element/
├── hdpi/ # 高密度屏幕资源
│ └── media/
├── xhdpi/ # 超高密度屏幕资源
│ └── media/
└── zh_CN-phone/ # 中文手机设备资源(组合限定词)
└── element/
5.1.2 资源目录作用说明
- base目录:存放默认资源,当没有匹配的限定词资源时,系统会使用base目录中的资源
- 限定词目录:使用限定词命名的目录,如语言、地区、设备类型等
- 组合限定词目录:可以使用多个限定词组合命名目录,如"zh_CN-phone"表示中文(中国)手机设备资源
5.1.3 资源文件类型与用途
鸿蒙系统支持以下主要资源类型:
-
element目录:
string.json:字符串资源color.json:颜色资源float.json:尺寸资源(浮点型)integer.json:整数资源boolean.json:布尔值资源style.json:样式资源
-
media目录:
- 图片资源(.png、.jpg、.svg等)
- 音频资源(.mp3、.wav等)
- 视频资源(.mp4等)
-
layout目录:
- UI布局文件(.xml)
-
profile目录:
- 功能配置文件
-
rawfile目录:
- 直接打包的原始文件,访问时保持文件名不变
5.2 多语言配置
鸿蒙系统提供了完善的多语言支持机制,通过资源限定词和字符串资源文件,可以轻松实现应用的国际化和本地化。
5.2.1 语言资源组织
多语言资源通过语言限定词目录进行组织,常用的语言限定词包括:
zh_CN:简体中文(中国大陆)zh_HK:繁体中文(中国香港)zh_TW:繁体中文(中国台湾)zh_SG:简体中文(新加坡)zh_MO:繁体中文(中国澳门)en_US:英语(美国)en_GB:英语(英国)ja_JP:日语(日本)ko_KR:韩语(韩国)fr_FR:法语(法国)de_DE:德语(德国)ru_RU:俄语(俄罗斯)es_ES:西班牙语(西班牙)ar_SA:阿拉伯语(沙特阿拉伯)
5.2.2 字符串资源配置示例
创建多语言字符串资源的示例:
// src/main/resources/base/element/string.json
{
"string": [
{ "name": "app_name", "value": "示例应用" },
{ "name": "welcome_message", "value": "欢迎使用示例应用" },
{ "name": "login_button", "value": "登录" },
{ "name": "register_button", "value": "注册" }
]
}
// src/main/resources/en_US/element/string.json
{
"string": [
{ "name": "app_name", "value": "Sample App" },
{ "name": "welcome_message", "value": "Welcome to Sample App" },
{ "name": "login_button", "value": "Login" },
{ "name": "register_button", "value": "Register" }
]
}
// src/main/resources/zh_HK/element/string.json
{
"string": [
{ "name": "app_name", "value": "示例應用" },
{ "name": "welcome_message", "value": "歡迎使用示例應用" },
{ "name": "login_button", "value": "登錄" },
{ "name": "register_button", "value": "註冊" }
]
}
5.2.3 字符串资源引用
在代码中引用字符串资源的方法:
// ArkTS中引用字符串资源
import { Resource } from '@ohos.resource';
// 获取字符串资源
const appName: Resource = $r('app.string.app_name');
const welcomeMsg: Resource = $r('app.string.welcome_message');
// 在UI组件中使用
Text($r('app.string.login_button'))
.fontSize(16)
.fontColor($r('app.color.primary_color'));
在配置文件中引用字符串资源:
{
"module": {
"abilities": [
{
"name": "MainAbility",
"label": "$string:app_name",
"description": "$string:app_description"
}
]
}
}
5.2.4 复数形式处理
不同语言对复数的处理方式不同,鸿蒙提供了复数形式的支持:
// src/main/resources/base/element/string.json
{
"string": [
{
"name": "message_count",
"value": {
"zero": "您没有新消息",
"one": "您有1条新消息",
"two": "您有2条新消息",
"few": "您有%d条新消息",
"many": "您有%d条新消息",
"other": "您有%d条新消息"
}
}
]
}
在代码中使用复数形式:
// 获取带参数的字符串
const messageCount = 5;
const messageText = $r('app.string.message_count');
const formattedText = TextUtils.format(messageText, messageCount);
5.3 多设备适配配置策略
鸿蒙系统作为一个全场景分布式操作系统,支持多种设备类型,包括手机、平板、电视、手表、车载设备等。多设备适配是鸿蒙应用开发中的重要环节。
5.3.1 设备类型限定词
鸿蒙支持的主要设备类型限定词包括:
phone:手机设备tablet:平板设备tv:电视设备watch:手表设备car:车载设备default:默认设备类型
5.3.2 多设备适配配置示例
为不同设备类型配置不同的资源:
// src/main/resources/phone/element/dimension.json
{
"float": [
{ "name": "font_size_title", "value": "20fp" },
{ "name": "spacing_card", "value": "12dp" },
{ "name": "button_height", "value": "48dp" }
]
}
// src/main/resources/tablet/element/dimension.json
{
"float": [
{ "name": "font_size_title", "value": "24fp" },
{ "name": "spacing_card", "value": "16dp" },
{ "name": "button_height", "value": "52dp" }
]
}
// src/main/resources/watch/element/dimension.json
{
"float": [
{ "name": "font_size_title", "value": "16fp" },
{ "name": "spacing_card", "value": "8dp" },
{ "name": "button_height", "value": "40dp" }
]
}
5.3.3 屏幕密度适配
不同设备的屏幕密度不同,需要提供适配的图片资源:
// 不同密度的图片资源目录
resources/
├── base/media/icon.png # 默认密度
├── mdpi/media/icon.png # 中等密度 (1.0x)
├── hdpi/media/icon.png # 高密度 (1.5x)
├── xhdpi/media/icon.png # 超高密度 (2.0x)
├── xxhdpi/media/icon.png # 超超高密度 (3.0x)
└── xxxhdpi/media/icon.png # 超超超高密度 (4.0x)
5.3.4 屏幕方向适配
设备可能在横屏和竖屏状态之间切换,需要提供适配的布局:
// src/main/resources/base/element/string.json
{
"string": [
{ "name": "orientation_hint", "value": "默认方向" }
]
}
// src/main/resources/landscape/element/string.json
{
"string": [
{ "name": "orientation_hint", "value": "横屏模式" }
]
}
// src/main/resources/portrait/element/string.json
{
"string": [
{ "name": "orientation_hint", "value": "竖屏模式" }
]
}
5.3.5 组合限定词适配
鸿蒙支持使用多个限定词组合来实现更精确的资源匹配:
// src/main/resources/zh_CN-phone/element/string.json
{
"string": [
{ "name": "device_info", "value": "当前设备:中文手机" }
]
}
// src/main/resources/en_US-tablet/element/string.json
{
"string": [
{ "name": "device_info", "value": "Current Device: English Tablet" }
]
}
5.3.6 代码中的设备适配
在代码中也可以进行设备类型和屏幕特性的适配:
import deviceInfo from '@ohos.deviceInfo';
import window from '@ohos.window';
// 获取设备类型
const deviceType = deviceInfo.deviceType;
console.log(`Device type: ${deviceType}`);
// 根据设备类型调整UI
function adjustUIByDeviceType() {
switch (deviceType) {
case 'phone':
// 手机设备UI适配
break;
case 'tablet':
// 平板设备UI适配
break;
case 'tv':
// 电视设备UI适配
break;
case 'watch':
// 手表设备UI适配
break;
case 'car':
// 车载设备UI适配
break;
default:
break;
}
}
// 监听屏幕尺寸变化
async function observeScreenSize() {
const windowClass = await window.getLastWindow();
windowClass.on('windowSizeChange', (size) => {
console.log(`Window size: width=${size.width}, height=${size.height}`);
const isLandscape = size.width > size.height;
// 根据横竖屏状态调整UI
updateUIByOrientation(isLandscape);
});
}
5.4 主题配置
主题配置是实现应用视觉风格统一和灵活切换的重要机制。鸿蒙系统提供了完善的主题支持,可以通过资源配置和样式系统实现主题定制。
5.4.1 颜色资源配置
主题的核心是颜色系统,可以通过颜色资源文件定义主题色彩:
// src/main/resources/base/element/color.json
{
"color": [
// 主题色
{ "name": "color_primary", "value": "#007AFF" },
{ "name": "color_primary_dark", "value": "#0051D5" },
{ "name": "color_primary_light", "value": "#4DA3FF" },
// 功能色
{ "name": "color_success", "value": "#34C759" },
{ "name": "color_warning", "value": "#FF9500" },
{ "name": "color_error", "value": "#FF3B30" },
// 背景色
{ "name": "color_background", "value": "#FFFFFF" },
{ "name": "color_surface", "value": "#F2F2F7" },
// 文字色
{ "name": "color_text_primary", "value": "#000000" },
{ "name": "color_text_secondary", "value": "#8E8E93" },
{ "name": "color_text_disabled", "value": "#C7C7CC" },
// 边框色
{ "name": "color_border", "value": "#E5E5EA" },
{ "name": "color_divider", "value": "#C6C6C8" }
]
}
5.4.2 样式资源配置
样式资源可以定义可复用的组件样式,与主题紧密配合:
// src/main/resources/base/element/style.json
{
"style": [
// 文本样式
{
"name": "text_title",
"values": [
{ "attr": "fontSize", "value": "$float:font_size_title" },
{ "attr": "fontWeight", "value": "700" },
{ "attr": "fontColor", "value": "$color:color_text_primary" }
]
},
{
"name": "text_body",
"values": [
{ "attr": "fontSize", "value": "$float:font_size_body" },
{ "attr": "fontColor", "value": "$color:color_text_secondary" }
]
},
// 按钮样式
{
"name": "button_primary",
"values": [
{ "attr": "backgroundColor", "value": "$color:color_primary" },
{ "attr": "fontColor", "value": "#FFFFFF" },
{ "attr": "borderRadius", "value": "$float:border_radius_medium" },
{ "attr": "height", "value": "$float:button_height" }
]
},
// 卡片样式
{
"name": "card_style",
"values": [
{ "attr": "backgroundColor", "value": "$color:color_surface" },
{ "attr": "borderRadius", "value": "$float:border_radius_large" },
{ "attr": "padding", "value": "$float:spacing_medium" },
{ "attr": "shadowColor", "value": "rgba(0, 0, 0, 0.1)" },
{ "attr": "shadowRadius", "value": "4px" },
{ "attr": "shadowOffsetX", "value": "0px" },
{ "attr": "shadowOffsetY", "value": "2px" }
]
}
]
}
5.4.3 深色模式支持
鸿蒙系统支持深色模式,可以通过资源限定词为深色模式提供适配的资源:
// src/main/resources/base/element/color.json (浅色主题)
{
"color": [
{ "name": "color_background", "value": "#FFFFFF" },
{ "name": "color_text_primary", "value": "#000000" }
// 其他颜色...
]
}
// src/main/resources/dark/element/color.json (深色主题)
{
"color": [
{ "name": "color_background", "value": "#121212" },
{ "name": "color_text_primary", "value": "#FFFFFF" }
// 其他颜色...
]
}
5.4.4 自定义主题
开发者可以创建多个自定义主题,并通过配置文件进行切换:
// src/main/resources/theme1/element/color.json (主题1)
{
"color": [
{ "name": "color_primary", "value": "#FF6B6B" }
// 其他主题1颜色...
]
}
// src/main/resources/theme2/element/color.json (主题2)
{
"color": [
{ "name": "color_primary", "value": "#48DBFB" }
// 其他主题2颜色...
]
}
在代码中切换主题:
import abilityAccessCtrl from '@ohos.abilityAccessCtrl';
import { Configuration, UIContext } from '@ohos.arkui.UIContext';
// 切换主题的示例函数
async function switchTheme(uiContext: UIContext, theme: string) {
try {
// 创建配置对象
const config: Configuration = {
// 根据主题设置不同的限定词
theme: theme === 'theme1' ? 'theme1' : 'theme2'
};
// 应用配置
await uiContext.applyConfiguration(config);
console.log(`Theme switched to ${theme}`);
} catch (error) {
console.error(`Failed to switch theme: ${error}`);
}
}
通过灵活的主题配置,开发者可以实现应用的个性化定制,提升用户体验。主题配置与资源系统的结合,使得鸿蒙应用能够轻松支持明暗模式切换和多风格主题,满足不同用户的偏好和需求。
6. 高级配置特性
在鸿蒙应用开发中,了解和掌握高级配置特性对于构建高性能、可靠且功能丰富的应用至关重要。本章将深入探讨鸿蒙应用json配置文件中的一些高级特性,以及如何利用这些特性来优化应用性能、增强安全性和扩展功能。
6.1 组件配置与生命周期管理
组件是鸿蒙应用的基本构建单元,包括UIAbility、ExtensionAbility等。通过json配置文件,可以对组件的生命周期、启动模式和通信方式进行精细的控制。
6.1.1 UIAbility启动模式配置
UIAbility支持多种启动模式,可以通过配置文件进行设置:
{
"module": {
"abilities": [
{
"name": "MainAbility",
"launchType": "singleton", // 单例模式
"skills": [
{
"entities": ["entity.system.home"],
"actions": ["action.system.home"]
}
]
},
{
"name": "DetailAbility",
"launchType": "multiton", // 多实例模式
"skills": [
{
"entities": ["entity.system.home"],
"actions": ["ability.detail.action"]
}
]
},
{
"name": "DocumentAbility",
"launchType": "specified", // 指定实例模式
"skills": [
{
"entities": ["entity.system.home"],
"actions": ["ability.document.action"]
}
]
}
]
}
}
启动模式说明:
- singleton(单例模式):全局只存在一个该类型的UIAbility实例
- multiton(多实例模式):每次启动都会创建一个新的UIAbility实例
- specified(指定实例模式):通过Intent指定特定实例进行启动
6.1.2 组件生命周期回调配置
可以通过配置文件定义组件的生命周期回调函数:
{
"module": {
"abilities": [
{
"name": "MainAbility",
"description": "主页面功能",
"icon": "$media:icon",
"label": "$string:app_name",
"orientation": "unspecified",
"formsEnabled": true,
"formEnabledItems": {
"defaultDimension": "dimensions_2_2",
"supportDimensions": ["dimensions_1_2", "dimensions_2_2"],
"formVisibleNotify": true,
"formVisibleNotifyEvents": ["formAdd", "formRemove", "formUpdate"]
},
"metadata": [
{
"name": "ohos.meta.ability_lifecycle",
"resource": "$profile:lifecycle_config"
}
]
}
]
}
}
对应的生命周期配置文件(profile/lifecycle_config.json):
{
"lifecycle": {
"onCreate": true,
"onWindowStageCreate": true,
"onForeground": true,
"onBackground": true,
"onWindowStageDestroy": true,
"onDestroy": true,
"maxLifecycleCallbacks": 10
}
}
6.1.3 组件间通信配置
通过配置文件设置组件间的通信权限和方式:
{
"module": {
"abilities": [
{
"name": "DataServiceAbility",
"type": "service",
"visible": true, // 设置为true允许其他应用访问
"exported": true,
"skills": [
{
"entities": ["entity.system.service"],
"actions": ["ability.data.action.GET_DATA", "ability.data.action.SAVE_DATA"]
}
],
"metadata": [
{
"name": "ohos.meta.ability.communication",
"resource": "$profile:communication_config"
}
]
}
]
}
}
通信配置文件(profile/communication_config.json):
{
"communication": {
"localIPCEnabled": true,
"remoteIPCEnabled": true,
"maxConcurrentIPC": 5,
"allowBundleNames": ["com.example.allow_app"],
"denyBundleNames": ["com.example.deny_app"]
}
}
6.2 应用权限与安全配置
鸿蒙系统提供了完善的权限管理机制,通过json配置文件可以声明和管理应用所需的权限,确保应用安全性。
6.2.1 权限声明与分级
在module.json5中声明应用所需的权限:
{
"module": {
"abilities": [
{
"name": "MainAbility",
"description": "主页面功能",
"icon": "$media:icon",
"label": "$string:app_name",
"orientation": "unspecified",
"formsEnabled": true
}
],
"requestPermissions": [
// 系统级权限
{
"name": "ohos.permission.GET_BUNDLE_INFO_PRIVILEGED",
"reason": "获取应用信息以提供更好的体验",
"usedScene": {
"abilities": ["MainAbility"],
"when": "inuse"
}
},
// 敏感权限
{
"name": "ohos.permission.CAMERA",
"reason": "用于扫描二维码",
"usedScene": {
"abilities": ["MainAbility"],
"when": "inuse"
}
},
{
"name": "ohos.permission.MICROPHONE",
"reason": "用于语音输入",
"usedScene": {
"abilities": ["MainAbility"],
"when": "inuse"
}
},
// 普通权限
{
"name": "ohos.permission.GET_NETWORK_INFO",
"reason": "获取网络状态",
"usedScene": {
"abilities": ["MainAbility"],
"when": "always"
}
}
]
}
}
权限等级说明:
- 系统级权限:涉及系统核心功能,通常需要系统签名
- 敏感权限:涉及用户隐私,需要在运行时动态申请并获得用户授权
- 普通权限:常规功能权限,安装时自动授予
6.2.2 数据安全配置
配置应用的数据安全策略:
{
"module": {
"abilities": [
// 能力配置...
],
"metadata": [
{
"name": "ohos.meta.data_security",
"resource": "$profile:data_security_config"
}
]
}
}
数据安全配置文件(profile/data_security_config.json):
{
"dataSecurity": {
"encryptedStorage": {
"enabled": true,
"keyAlias": "app_secure_storage_key",
"algorithm": "AES_256_GCM"
},
"networkSecurity": {
"tlsMinimumVersion": "TLSv1.2",
"allowedCipherSuites": [
"TLS_AES_256_GCM_SHA384",
"TLS_CHACHA20_POLY1305_SHA256",
"TLS_AES_128_GCM_SHA256"
],
"cleartextTrafficPermitted": false
},
"appDataIsolation": true,
"appDataBackup": {
"enabled": true,
"includeDirectories": ["/data/storage/el2/base/files"],
"excludeDirectories": ["/data/storage/el2/base/temp"]
}
}
}
6.2.3 应用签名与完整性校验配置
在app.json5中配置应用的签名信息:
{
"app": {
"bundleName": "com.example.harmonyapp",
"vendor": "example",
"versionCode": 1000000,
"versionName": "1.0.0",
"icon": "$media:icon",
"label": "$string:app_name",
"description": "$string:app_description",
"metadata": [
{
"name": "ohos.meta.app_signature",
"resource": "$profile:signature_config"
}
],
"distributedNotificationEnabled": false
}
}
签名配置文件(profile/signature_config.json):
{
"signature": {
"signatureEnabled": true,
"integrityCheck": true,
"antiDebug": true,
"antiReverseEngineering": true,
"signingConfigs": [
{
"name": "debug",
"certificatePath": "/path/to/debug.cer",
"keyPath": "/path/to/debug.p12",
"keyPassword": "password",
"storePassword": "password"
},
{
"name": "release",
"certificatePath": "/path/to/release.cer",
"keyPath": "/path/to/release.p12",
"keyPassword": "password",
"storePassword": "password"
}
]
}
}
6.3 性能优化配置
性能优化是应用开发中的重要环节,通过json配置文件可以对应用的性能进行调优,提升用户体验。
6.3.1 内存与资源限制配置
设置应用的内存和资源使用限制:
{
"module": {
"abilities": [
// 能力配置...
],
"metadata": [
{
"name": "ohos.meta.performance",
"resource": "$profile:performance_config"
}
]
}
}
性能配置文件(profile/performance_config.json):
{
"performance": {
"memoryLimit": {
"heapSize": 512, // 单位MB
"nativeHeapSize": 256, // 单位MB
"totalSize": 768 // 单位MB
},
"resourceQuota": {
"maxBackgroundTime": 1800000, // 最大后台运行时间,单位ms
"maxProcessCount": 4,
"maxThreadCount": 16,
"maxServiceCount": 8
},
"rendering": {
"maxFrameRate": 90,
"renderThreadPriority": 2,
"enableHardwareAcceleration": true
},
"batterySaver": {
"lowBatteryModeEnabled": true,
"backgroundTasksSuspended": true,
"animationReduced": true
}
}
}
6.3.2 启动优化配置
配置应用的启动优化参数:
{
"module": {
"abilities": [
{
"name": "MainAbility",
"description": "主页面功能",
"icon": "$media:icon",
"label": "$string:app_name",
"orientation": "unspecified",
"formsEnabled": true,
"launchMode": "singleton",
"metadata": [
{
"name": "ohos.meta.startup_optimization",
"resource": "$profile:startup_config"
}
]
}
]
}
}
启动配置文件(profile/startup_config.json):
{
"startup": {
"preloadModules": ["com.example.common", "com.example.utils"],
"warmStartEnabled": true,
"startupTasks": [
{
"name": "dataLoadingTask",
"delay": 1000, // 延迟执行时间,单位ms
"priority": "high",
"type": "background"
},
{
"name": "analyticsInitTask",
"delay": 3000,
"priority": "low",
"type": "background"
}
],
"splashScreen": {
"autoHide": true,
"hideDelay": 1000,
"enableAnimation": true
},
"renderingPriority": "high"
}
}
6.3.3 缓存与存储优化配置
配置应用的缓存和存储策略:
{
"module": {
"abilities": [
// 能力配置...
],
"metadata": [
{
"name": "ohos.meta.storage_optimization",
"resource": "$profile:storage_config"
}
]
}
}
存储配置文件(profile/storage_config.json):
{
"storage": {
"cache": {
"maxCacheSize": 1024, // 单位MB
"cacheExpiryTime": 604800, // 缓存过期时间,单位秒
"autoCleanupEnabled": true,
"cleanupThreshold": 80 // 缓存占用超过80%时自动清理
},
"database": {
"connectionPoolSize": 5,
"maxConcurrentTransactions": 3,
"enableEncryption": true,
"optimizeOnStart": true
},
"fileSystem": {
"maxFileHandleCount": 256,
"bufferSize": 8192, // 单位KB
"compressionEnabled": true,
"compressThreshold": 1024 // 大于1024KB的文件启用压缩
},
"sharedPreferences": {
"syncInterval": 60000, // 自动同步间隔,单位ms
"backupEnabled": true
}
}
}
6.4 分布式能力配置
鸿蒙系统的一大特色是分布式能力,通过json配置文件可以开启和配置应用的分布式功能。
6.4.1 分布式数据管理配置
配置应用的分布式数据能力:
{
"module": {
"abilities": [
// 能力配置...
],
"metadata": [
{
"name": "ohos.meta.distributed_data",
"resource": "$profile:distributed_data_config"
}
]
}
}
分布式数据配置文件(profile/distributed_data_config.json):
{
"distributedData": {
"enabled": true,
"syncStrategy": "manual", // manual, auto, onwifi
"conflictResolution": "latest_wins", // latest_wins, user_decision, custom
"syncTimeout": 30000, // 同步超时时间,单位ms
"dataGroups": [
{
"name": "user_preferences",
"syncEnabled": true,
"conflictStrategy": "custom",
"customResolver": "com.example.sync.resolver.UserPrefsResolver"
},
{
"name": "app_settings",
"syncEnabled": true,
"conflictStrategy": "latest_wins"
}
],
"allowedDevices": {
"includeTypes": ["phone", "tablet", "tv", "watch", "car"],
"includeModels": ["Mate", "P", "Nova"],
"excludeModels": []
}
}
}
6.4.2 分布式设备管理配置
配置应用的分布式设备发现和管理能力:
{
"module": {
"abilities": [
// 能力配置...
],
"metadata": [
{
"name": "ohos.meta.distributed_device",
"resource": "$profile:distributed_device_config"
}
]
}
}
分布式设备配置文件(profile/distributed_device_config.json):
{
"distributedDevice": {
"deviceDiscovery": {
"enabled": true,
"discoveryType": "active", // active, passive
"maxDiscoveredDevices": 10,
"scanInterval": 30000 // 扫描间隔,单位ms
},
"deviceAuthentication": {
"enabled": true,
"authType": "pin", // pin, qrcode, bluetooth
"maxAuthAttempts": 3,
"authTimeout": 60000 // 认证超时时间,单位ms
},
"deviceStatus": {
"monitorEnabled": true,
"statusUpdateInterval": 5000,
"trackBattery": true,
"trackNetwork": true,
"trackStorage": true
},
"deviceSharing": {
"enabled": true,
"allowScreenMirroring": true,
"allowFileTransfer": true,
"allowRemoteControl": false
}
}
}
6.4.3 分布式服务配置
配置应用的分布式服务能力:
{
"module": {
"abilities": [
{
"name": "RemoteServiceAbility",
"type": "service",
"visible": true,
"exported": true,
"skills": [
{
"entities": ["entity.system.service"],
"actions": ["ability.remote.action.SERVICE"]
}
],
"metadata": [
{
"name": "ohos.meta.distributed_service",
"resource": "$profile:distributed_service_config"
}
]
}
]
}
}
分布式服务配置文件(profile/distributed_service_config.json):
{
"distributedService": {
"enabled": true,
"serviceDiscovery": true,
"maxConnections": 5,
"retryPolicy": {
"maxRetries": 3,
"retryInterval": 1000
},
"security": {
"encryptCommunication": true,
"verifyDeviceIdentity": true,
"allowedDevices": ["phone", "tablet"]
},
"services": [
{
"name": "remoteDataService",
"interface": "com.example.service.IDataService",
"version": "1.0.0",
"securityLevel": "high"
},
{
"name": "remoteMediaService",
"interface": "com.example.service.IMediaService",
"version": "1.0.0",
"securityLevel": "medium"
}
]
}
}
6.5 调试与诊断配置
调试与诊断功能对于应用开发和问题排查至关重要,通过json配置文件可以配置应用的调试和诊断能力。
6.5.1 调试模式配置
配置应用的调试模式和相关参数:
{
"module": {
"abilities": [
// 能力配置...
],
"metadata": [
{
"name": "ohos.meta.debug_config",
"resource": "$profile:debug_config"
}
]
}
}
调试配置文件(profile/debug_config.json):
{
"debug": {
"debuggable": true,
"enableNativeDebug": true,
"enableJSProfiler": true,
"enableUIAnalyzer": true,
"enableLayoutInspector": true,
"logLevel": "debug", // verbose, debug, info, warn, error
"persistentLogging": false,
"logMaxSize": 10, // 单位MB
"enableExceptionCapture": true,
"enablePerformanceTraces": true,
"tracesSamplingRate": 100 // 1-100%
}
}
6.5.2 性能监控配置
配置应用的性能监控参数:
{
"module": {
"abilities": [
// 能力配置...
],
"metadata": [
{
"name": "ohos.meta.performance_monitor",
"resource": "$profile:perf_monitor_config"
}
]
}
}
性能监控配置文件(profile/perf_monitor_config.json):
{
"performanceMonitor": {
"enabled": true,
"fpsMonitor": {
"enabled": true,
"samplingRate": 60,
"anomalyThreshold": 30 // FPS低于30时报警
},
"memoryMonitor": {
"enabled": true,
"samplingInterval": 5000,
"leakDetection": true,
"heapDumpOnOOM": true
},
"cpuMonitor": {
"enabled": true,
"samplingInterval": 2000,
"threshold": 80 // CPU使用率超过80%时报警
},
"batteryMonitor": {
"enabled": true,
"samplingInterval": 30000,
"threshold": 5 // 每分钟耗电量超过5%时报警
},
"networkMonitor": {
"enabled": true,
"samplingInterval": 10000,
"trackRequests": true,
"threshold": 500 // 请求延迟超过500ms时报警
},
"reporting": {
"enabled": true,
"interval": 60000,
"maxReports": 100
}
}
}
6.5.3 崩溃与异常诊断配置
配置应用的崩溃和异常诊断参数:
{
"module": {
"abilities": [
// 能力配置...
],
"metadata": [
{
"name": "ohos.meta.crash_diagnosis",
"resource": "$profile:crash_diagnosis_config"
}
]
}
}
崩溃诊断配置文件(profile/crash_diagnosis_config.json):
{
"crashDiagnosis": {
"enabled": true,
"autoCapture": true,
"collectDeviceInfo": true,
"collectAppInfo": true,
"collectSystemLogs": true,
"collectMemoryDump": true,
"collectNetworkInfo": false,
"maxLogSize": 5, // 单位MB
"maxCrashReports": 50,
"anonymizeData": true,
"reporting": {
"enabled": true,
"endPoint": "https://example.com/crash-reporting",
"reportImmediately": true,
"includeScreenshots": true,
"maxRetries": 3
},
"alerting": {
"enabled": true,
"threshold": 5, // 每小时崩溃超过5次时告警
"alertChannels": ["email", "sms", "push"]
}
}
}
通过上述高级配置特性,开发者可以构建更加健壮、高性能、安全且功能丰富的鸿蒙应用。这些配置选项提供了对应用各个方面的精细控制,使得开发者能够根据具体需求进行针对性的优化和定制。理解并灵活运用这些高级配置特性,是成为一名优秀的鸿蒙应用开发者的重要条件。
2113

被折叠的 条评论
为什么被折叠?



