【HarmonyOS】关于鸿蒙原生多环境的设置和管理

打印 上一主题 下一主题

主题 880|帖子 880|积分 2640

开发语言:ArkTs
开发工具:DevEco Studio 5.0.0 Release
API版本:API 12
demo演示Gitee:harmony-multiEnv.git
在开发中为了数据隔离和开发规范,一般环境下都必要设置多环境,方便开发、测试、部署,比如:dev、test、sit、gray、release等,差别公司在多环境利用上不尽雷同,本文利用dev、test、release三个环境演示鸿蒙的多环境。
一、开发工具设置多环境

1、环境切换入口

在DevEco Studio开发工具的工具条中,点击瞄准镜图标即可进行环境的切换。

2、设置签名(debug和release)

打开工具栏File - Project Structure - Project - Signing Configs,默认工程只有一个default签名设置,可点击+或-添加删除设置,签名设置完成后,在工程目次下的build-profile.json5文件中可查看signingConfigs字段的签名设置。

本文演示设置debug和release两个签名。

  1. {
  2.   "app": {
  3.     "signingConfigs": [
  4.       {
  5.         "name": "debug",
  6.         "type": "HarmonyOS",
  7.         "material": {
  8.           "certpath": "./debug.cer",
  9.           "storePassword": "xxxx",
  10.           "keyAlias": "debugKey",
  11.           "keyPassword": "xxxx",
  12.           "profile": "./debug.p7b",
  13.           "signAlg": "SHA256withECDSA",
  14.           "storeFile": "./debug.p12"
  15.         }
  16.       },
  17.       {
  18.         "name": "release",
  19.         "type": "HarmonyOS",
  20.         "material": {
  21.           "certpath": "./release.cer",
  22.           "storePassword": "xxxx",
  23.           "keyAlias": "debugKey",
  24.           "keyPassword": "xxxx",
  25.           "profile": "./release.p7b",
  26.           "signAlg": "SHA256withECDSA",
  27.           "storeFile": "./release.p12"
  28.         }
  29.       }
  30.     ],
  31.     "products": [
  32.       //...
  33.     ],
  34.     "buildModeSet": [
  35.       //...
  36.     ]
  37.   },
  38.   "modules": [
  39.      //...
  40.   ]
  41. }
复制代码
3、创建多环境设置文件

在entry/src/main/resources/rawfile目次下创建三个环境对应的设置文件,取名为app_config_dev.json、app_config_test.json和app_config_release.json。

每个设置文件包含雷同的三个字段:

ServerUrl表现请求服务器地点、ResourceUrl表现资源服务器地点、release表现是否为生产环境。

  1. {
  2.   "ServerUrl": "https://www.dev.com/api/",
  3.   "ResourceUrl": "https://www.dev.com/resource/",
  4.   "release": false
  5. }
复制代码
4、设置工程支持多环境



  • 设置products
在工程目次下的build-profile.json5文件中设置products字段,可在默认的数据中新增arkOptions - buildProfileFields - APP_CONFIG字段,用来设置每个环境对应的设置文件。APP_CONFIG为自界说,可自行改名。


  • 设置modules
在工程目次下的build-profile.json5文件中设置modules字段,在默认的数据targets - applyToProducts中新增步骤1中的各个环境。

  1. {
  2.   "app": {
  3.     "signingConfigs": [
  4.       // ...
  5.     ],
  6.     "products": [
  7.       {
  8.         "name": "default",
  9.         "signingConfig": "debug",
  10.         "compatibleSdkVersion": "5.0.0(12)",
  11.         "runtimeOS": "HarmonyOS",
  12.         "buildOption": {
  13.           "strictMode": {
  14.             "caseSensitiveCheck": true,
  15.             "useNormalizedOHMUrl": true
  16.           },
  17.           "arkOptions": {
  18.             "buildProfileFields": {
  19.               "APP_CONFIG": "app_config_release.json"
  20.             }
  21.           }
  22.         }
  23.       },
  24.       {
  25.         "name": "dev",
  26.         "signingConfig": "debug",
  27.         "compatibleSdkVersion": "5.0.0(12)",
  28.         "runtimeOS": "HarmonyOS",
  29.         "buildOption": {
  30.           "strictMode": {
  31.             "caseSensitiveCheck": true,
  32.             "useNormalizedOHMUrl": true
  33.           },
  34.           "arkOptions": {
  35.             "buildProfileFields": {
  36.               "APP_CONFIG": "app_config_dev.json"
  37.             }
  38.           }
  39.         }
  40.       },
  41.       {
  42.         "name": "test",
  43.         "signingConfig": "debug",
  44.         "compatibleSdkVersion": "5.0.0(12)",
  45.         "runtimeOS": "HarmonyOS",
  46.         "buildOption": {
  47.           "strictMode": {
  48.             "caseSensitiveCheck": true,
  49.             "useNormalizedOHMUrl": true
  50.           },
  51.           "arkOptions": {
  52.             "buildProfileFields": {
  53.               "APP_CONFIG": "app_config_test.json"
  54.             }
  55.           }
  56.         }
  57.       },
  58.       {
  59.         "name": "release",
  60.         "signingConfig": "release",
  61.         "compatibleSdkVersion": "5.0.0(12)",
  62.         "runtimeOS": "HarmonyOS",
  63.         "buildOption": {
  64.           "strictMode": {
  65.             "caseSensitiveCheck": true,
  66.             "useNormalizedOHMUrl": true
  67.           },
  68.           "arkOptions": {
  69.             "buildProfileFields": {
  70.               "APP_CONFIG": "app_config_prod.json"
  71.             }
  72.           }
  73.         }
  74.       }
  75.     ],
  76.     "buildModeSet": [
  77.       // ...
  78.     ]
  79.   },
  80.   "modules": [
  81.     {
  82.       "name": "entry",
  83.       "srcPath": "./entry",
  84.       "targets": [
  85.         {
  86.           "name": "default",
  87.           "applyToProducts": [
  88.             "default",
  89.             "dev",
  90.             "test",
  91.             "release"
  92.           ]
  93.         }
  94.       ]
  95.     }
  96.   ]
  97. }
复制代码
5、获取当前环境设置信息

创建AppConfig.ets文件,用来获取环境设置文件,并剖析文件数据。BuildProfile为利用开发工具切换环境后,build工程生成的编译文件,用来获取当前环境下的环境设置信息。

  1. import BuildProfile from 'BuildProfile'
  2. import { HashMap } from '@kit.ArkTS';
  3. export class AppConfig {
  4.   // 单例
  5.   private static config: AppConfig;
  6.   static getInstance(): AppConfig {
  7.     if (AppConfig.config === undefined) {
  8.       AppConfig.config = new AppConfig();
  9.     }
  10.     return AppConfig.config;
  11.   }
  12.   // 请求服务器地址
  13.   public baseServerUrl: string = '';
  14.   // 资源服务器地址
  15.   public resourceServerUrl: string = '';
  16.   // 是否为生产环境
  17.   public isRelease: boolean = true;
  18.   // 记录context,后面方法使用
  19.   private context?: Context;
  20.   /**
  21.    * 初始化方法
  22.    */
  23.   init(context: Context, filePath?: string): void {
  24.     try {
  25.       this.context = context;
  26.       // 配置文件路径(从环境配置中获取)
  27.       let configFilePath: string = filePath ?? BuildProfile.APP_CONFIG;
  28.       // 解析配置文件
  29.       let bytes: Uint8Array = context.resourceManager.getRawFileContentSync(configFilePath);
  30.       let content = this.bytesToString(bytes);
  31.       let jsonObj: object = JSON.parse(content);
  32.       // 重新组装map对象
  33.       let configMap: HashMap<string, string|boolean> = new HashMap();
  34.       let keys: string[] = Object.keys(jsonObj);
  35.       keys.forEach(key => {
  36.         let value: string|boolean = jsonObj[key];
  37.         configMap.set(key, value);
  38.       })
  39.       // 获取配置文件字段值
  40.       this.baseServerUrl = configMap.get("ServerUrl") as string;
  41.       this.resourceServerUrl = configMap.get("ResourceUrl") as string;
  42.       this.isRelease = configMap.get("release") as boolean;
  43.     } catch (e) {
  44.     }
  45.   }
  46.   
  47.   /**
  48.    * Uint8Array类型转换String
  49.    * @param input bytes数据
  50.    * @returns 返回字符串
  51.    */
  52.   public static bytesToString(input: Uint8Array): string {
  53.     let output: string = '';
  54.     try {
  55.       let textDecoder = util.TextDecoder.create("utf-8",{ignoreBOM: true});
  56.       output = textDecoder.decodeToString(input , {stream: false});
  57.     } catch (err) {}
  58.     return output;
  59.   }
  60. }
复制代码
6、生效当前环境信息

本文利用AbilityStage作为初始化环境信息的类,关于AbilityStage的先容可查看官方文档先容。


  • 创建HMAbilityStage.ets类,继续AbilityStage,重写onCreate()方法。
  • 在entry/src/main/module.json5文件中的设置srcEntry字段值为HMAbilityStage.ets文件的相对路径。

  1. {
  2.   "module": {
  3.     "name": "entry",
  4.     "type": "entry",
  5.     "srcEntry": "./ets/stage/HMAbilityStage.ets",
  6.     "description": "$string:module_desc",
  7.     "mainElement": "EntryAbility",
  8.     "deviceTypes": [
  9.       "phone",
  10.       "tablet",
  11.       "2in1"
  12.     ],
  13.     "deliveryWithInstall": true,
  14.     "installationFree": false,
  15.     "pages": "$profile:main_pages",
  16.     // ...
  17.   }
  18. }
复制代码
二、APP内动态切换环境

创建环境切换页面,用于切换差别环境,切换环境时再次调用AppConfig的初始化方法,传入指定设置文件路径即可。
  1. AppConfig.getInstance().init(getContext(this), 'app_config_test.json')
复制代码
示例中未进行数据长期化记录上次选中的环境,真正项目中可本地存储环境,下次启动利用切换后的环境设置信息

结尾

如各人发现文章形貌有问题或有更好的方案,还请批评回复,一起探究学习,感谢!

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

盛世宏图

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表