Open
fix: 修复 ohos 端检视报告稳定性/一致性/内存问题,补齐 9 接口单测与 CI,更新文档并验证 Flutter 3.41 兼容性 #15
程皖OrzAdd on Sep 5
fix: 修复 ohos 端检视报告稳定性/一致性/内存问题,补齐 9 接口单测与 CI,更新文档并验证 Flutter 3.41 兼容性 #15
Open
Total: 16 files changed+650-126
| @@ -0,0 +1,44 @@ | |||
| 1 | +name: Flutter Test | ||
| 2 | + | ||
| 3 | +# 单元测试 + 覆盖率门槛(Dart 层,MethodChannel 全部 mock,无需 ohos 设备) | ||
| 4 | +# 本地等价命令:flutter test --coverage | ||
| 5 | +on: | ||
| 6 | + push: | ||
| 7 | + branches: [ master ] | ||
| 8 | + pull_request: | ||
| 9 | + branches: [ master ] | ||
| 10 | + | ||
| 11 | +jobs: | ||
| 12 | + test: | ||
| 13 | + runs-on: ubuntu-latest | ||
| 14 | + steps: | ||
| 15 | + - uses: actions/checkout@v4 | ||
| 16 | + | ||
| 17 | + - uses: subosito/flutter-action@v2 | ||
| 18 | + with: | ||
| 19 | + channel: stable | ||
| 20 | + cache: true | ||
| 21 | + | ||
| 22 | + - name: Install dependencies | ||
| 23 | + run: flutter pub get | ||
| 24 | + | ||
| 25 | + - name: Analyze | ||
| 26 | + run: flutter analyze | ||
| 27 | + | ||
| 28 | + - name: Run unit tests with coverage | ||
| 29 | + run: flutter test --coverage | ||
| 30 | + | ||
| 31 | + - name: Enforce coverage threshold (>= 90% lines) | ||
| 32 | + run: | | ||
| 33 | + COVERAGE=$(lcov --summary coverage/lcov.info 2>&1 | grep -oP 'lines\.\.\.: \K[0-9.]+') | ||
| 34 | + echo "Line coverage: ${COVERAGE}%" | ||
| 35 | + if (( $(echo "$COVERAGE < 90.0" | bc -l) )); then | ||
| 36 | + echo "::error::Coverage ${COVERAGE}% is below the 90% threshold" | ||
| 37 | + exit 1 | ||
| 38 | + fi | ||
| 39 | + | ||
| 40 | + - name: Upload coverage artifact | ||
| 41 | + uses: actions/upload-artifact@v4 | ||
| 42 | + with: | ||
| 43 | + name: coverage | ||
| 44 | + path: coverage/lcov.info | ||
| @@ -1,3 +1,15 @@ | |||
| 1 | +## Unreleased (master) | ||
| 2 | + | ||
| 3 | +* 稳定性:`onMethodCall` 增加外层异常兜底与 result 统一回执,修复失败场景 Dart 侧 Future 永久挂起与 unhandled promise rejection;`jumpToMarket`/`loadProduct` 补齐异常捕获 | ||
| 4 | +* 一致性:`versionName`/`versionCode` 空值兜底空串(对齐 Android);跳转类方法补 `result.success(null)`(对齐 iOS `result(nil)`);`platformVersion` 返回 "HarmonyOS x.x.x" 格式(去除平台名冗余前缀) | ||
| 5 | +* 一致性:`openApplicationSettingPage` 优先定位当前应用「应用信息」设置页(`application_info_entry`),不支持时回退设置首页 | ||
| 6 | +* 一致性:`getChannelInfo` 支持宿主 rawfile `channel.ini` 动态渠道配置 + preferences 首装渠道持久化(未配置时保持默认渠道 `Huawei Store For Harmony`) | ||
| 7 | +* 内存:`onDetachedFromEngine` 置空 channel 引用并增加异步回写防护 | ||
| 8 | +* 测试:单元测试补齐全部 9 个公开接口(group 分组 + BDD 描述 + 异常/边界/并发/超时场景),新增 CI 工作流(单测 + 覆盖率 ≥90% 门槛) | ||
| 9 | +* 文档:README.OpenHarmony(中英)补充快速上手、环境搭建、升级迁移说明与平台行为差异表 | ||
| 10 | +* 工程:pubspec SDK 约束上界放宽至 `<4.0.0`;清理 Android(DeviceUtilPlugin.kt)/iOS(SwiftDeviceUtilPlugin.swift)模板残留文件 | ||
| 11 | +* Fix: resolve ohos stability issues (missing MethodChannel result callbacks causing Dart Future hangs, unhandled promise rejections), platform consistency issues (dynamic channel config via rawfile `channel.ini` + preferences persistence, application-info settings page targeting, `distributionOSName`-based platform version), and memory leak risk (channel reference release, detached guard); add unit test coverage for all 9 public APIs (19 BDD cases, 100% line coverage) with CI workflow; update docs (environment setup, quick start, migration guide, platform differences) and verify Flutter 3.41 (3.41.10-ohos-1.0.0) compatibility ([#15](https://gitcode.com/CPF-Flutter/fluttertpc_device_util/issues/15)) | ||
| 12 | + | ||
| 1 | ## 1.0.7-ohos-1.0.0 | 13 | ## 1.0.7-ohos-1.0.0 |
| 2 | 14 | ||
| 3 | * TAG 1.0.7-ohos-1.0.0 | 15 | * TAG 1.0.7-ohos-1.0.0 |
| @@ -40,6 +40,7 @@ flutter pub get | |||
| 40 | | 3.22 | 1.0.7-ohos-1.0.0 | master | | 40 | | 3.22 | 1.0.7-ohos-1.0.0 | master | |
| 41 | | 3.27 | 1.0.7-ohos-1.0.0 | master | | 41 | | 3.27 | 1.0.7-ohos-1.0.0 | master | |
| 42 | | 3.35 | 1.0.7-ohos-1.0.0 | master | | 42 | | 3.35 | 1.0.7-ohos-1.0.0 | master | |
| 43 | +| 3.41 | 1.0.7-ohos-1.0.0 | master | | ||
| 43 | 44 | ||
| 44 | <!-- tabs:end --> | 45 | <!-- tabs:end --> |
| 45 | 46 | ||
| @@ -47,6 +48,26 @@ flutter pub get | |||
| 47 | 48 | ||
| 48 | For use cases [example](/example/lib/main.dart). | 49 | For use cases [example](/example/lib/main.dart). |
| 49 | 50 | ||
| 51 | +Quick start: | ||
| 52 | + | ||
| 53 | +```dart | ||
| 54 | +import 'package:device_util/device_util.dart'; | ||
| 55 | + | ||
| 56 | +// Information retrieval | ||
| 57 | +String platformVersion = await DeviceUtil.platformVersion; // e.g. "HarmonyOS 5.1.0" | ||
| 58 | +String versionName = await DeviceUtil.versionName; // Version name of this application | ||
| 59 | +String versionCode = await DeviceUtil.versionCode; // Version code of this application | ||
| 60 | +Map<String, String> channelInfo = await DeviceUtil.getChannelInfo; // Channel info (Map length is 2) | ||
| 61 | + | ||
| 62 | +// Page jumps / process control | ||
| 63 | +await DeviceUtil.openApplicationSettingPage(); // Open the settings page of the current application | ||
| 64 | +await DeviceUtil.openNetworkSettingPage(); // Open the phone's network settings page | ||
| 65 | +DeviceUtil.openAppStoreCommentPage('appId'); // Open the app store scoring page (appID is ignored on ohos, always jumps to the current app) | ||
| 66 | +await DeviceUtil.killApp(); // Kill the current application process and exit | ||
| 67 | +``` | ||
| 68 | + | ||
| 69 | +> Note: on ohos, every method guarantees a result callback (success / error / not-implemented), so a Dart-side `await` never hangs forever when the native side fails; `versionName` / `versionCode` return an empty string on failure (aligned with the Android fallback behavior). | ||
| 70 | + | ||
| 50 | ## 2. Constraints | 71 | ## 2. Constraints |
| 51 | 72 | ||
| 52 | ### 2.1 Compatibility | 73 | ### 2.1 Compatibility |
| @@ -56,6 +77,24 @@ This document is verified based on the following versions: | |||
| 56 | 1. Flutter: 3.7.12-ohos-1.1.3; SDK: 5.0.0(12); IDE: DevEco Studio: 5.1.0.828; ROM: 5.1.0.130 SP8; | 77 | 1. Flutter: 3.7.12-ohos-1.1.3; SDK: 5.0.0(12); IDE: DevEco Studio: 5.1.0.828; ROM: 5.1.0.130 SP8; |
| 57 | 2. Flutter: 3.22.1-ohos-1.0.3; SDK: 5.0.0(12); IDE: DevEco Studio: 5.1.0.828; ROM: 5.1.0.130 SP8; | 78 | 2. Flutter: 3.22.1-ohos-1.0.3; SDK: 5.0.0(12); IDE: DevEco Studio: 5.1.0.828; ROM: 5.1.0.130 SP8; |
| 58 | 3. Flutter: 3.35.8-ohos-0.0.1; SDK: 6.0.1(21); IDE: DevEco Studio: 6.0.1.260; ROM: 6.0.0.120 SP6; | 79 | 3. Flutter: 3.35.8-ohos-0.0.1; SDK: 6.0.1(21); IDE: DevEco Studio: 6.0.1.260; ROM: 6.0.0.120 SP6; |
| 80 | +4. Flutter: 3.41.10-ohos-1.0.0; SDK: 6.1.1(24); IDE: DevEco Studio: 6.1.1; ROM: 7.0.0.17DEV(C00E31R3P1log); | ||
| 81 | + | ||
| 82 | +### 2.2 Environment Setup | ||
| 83 | + | ||
| 84 | +Steps to set up an ohos development environment: | ||
| 85 | + | ||
| 86 | +1. Install DevEco Studio (with the HarmonyOS SDK), following the [official environment preparation guide](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/ide-tools-overview); | ||
| 87 | +2. Obtain the Flutter OHOS SDK (an ohos branch of the `flutter_flutter` repository, optionally managed with [flvm](https://gitcode.com/openharmony-sig/flutter_flutter)), add `flutter/bin` to `PATH`, and run `flutter doctor` to confirm the toolchain is ready; | ||
| 88 | +3. Run `flutter pub get` in your project directory to fetch dependencies; | ||
| 89 | +4. Verify the environment with the example app: run `flutter run` inside `example/` with an ohos device/emulator connected, or open `example/ohos` in DevEco Studio; | ||
| 90 | +5. Build verification: `flutter build hap --debug` (add `--no-codesign` to skip signing). | ||
| 91 | + | ||
| 92 | +### 2.3 Upgrade and Migration | ||
| 93 | + | ||
| 94 | +- ohos adaptations are released as TAGs; see the "TAG Version Mapping" table above for the mapping between TAGs and Flutter framework versions; | ||
| 95 | +- See [CHANGELOG.OpenHarmony.md](/CHANGELOG.OpenHarmony.md) for the version history; | ||
| 96 | +- To upgrade: change the dependency `ref` in pubspec.yaml to the target TAG and run `flutter pub get`; | ||
| 97 | +- No breaking changes exist between the released TAGs (`1.0.7-ohos.1.0.0-beta.1` → `1.0.7-ohos-1.0.0`); the Dart-layer API stays consistent with upstream device_util 1.0.7, so upgrades are smooth. | ||
| 59 | 98 | ||
| 60 | 99 | ||
| 61 | ## 3. API | 100 | ## 3. API |
| @@ -77,9 +116,20 @@ This document is verified based on the following versions: | |||
| 77 | 116 | ||
| 78 | ## 4. Known Issues | 117 | ## 4. Known Issues |
| 79 | 118 | ||
| 119 | +No blocking known issues. The following are known behavioral differences between ohos and Android/iOS (platform adaptation conventions, listed for awareness): | ||
| 120 | + | ||
| 121 | +| Item | Description | | ||
| 122 | +|------|-------------| | ||
| 123 | +| getChannelInfo channel config | Reads `channel.ini` (or `channel_default.ini`, content format `key=value`, consistent with the Android assets channel config convention) from the host app's `resources/rawfile` first; when not configured, the fixed default channel `Huawei Store For Harmony` is returned (HarmonyOS apps are distributed through Huawei AppGallery by default, similar to the iOS fixed value "app store"). The first-install channel (first_install_channel) is persisted via @ohos.data.preferences, aligned with the Android SharedPreferences behavior | | ||
| 124 | +| appID parameter of openAppStoreCommentPage | Consistent with Android: the appID parameter is ignored; the Huawei AppGallery detail page of the current application is always opened (AppGallery Kit loadProduct) with the current app bundleName | | ||
| 125 | +| jump granularity of openApplicationSettingPage | Locates the "application info" page of the current application in system settings first (uri `application_info_entry`); automatically falls back to the settings home page on system versions that do not support it | | ||
| 126 | +| minimizeWindow | Upstream Windows-only capability; not implemented on ohos/Android/iOS (throws MissingPluginException) | | ||
| 80 | 127 | ||
| 81 | ## 5. Others | 128 | ## 5. Others |
| 82 | 129 | ||
| 130 | +- Unit tests: `flutter test`; coverage: `flutter test --coverage` (generates `coverage/lcov.info`; render an HTML report with `genhtml -o coverage/html coverage/lcov.info`); | ||
| 131 | +- Continuous integration: `.github/workflows/test.yml` runs unit tests, analysis, and a coverage threshold gate (>= 90% line coverage); | ||
| 132 | +- The HarmonyOS adaptation source lives in the `ohos/` directory (ArkTS); see the file headers under `ohos/` for copyright and build configuration notes. | ||
| 83 | 133 | ||
| 84 | ## 6. License | 134 | ## 6. License |
| 85 | 135 | ||
| @@ -40,6 +40,7 @@ flutter pub get | |||
| 40 | | 3.22 | 1.0.7-ohos-1.0.0 | master | | 40 | | 3.22 | 1.0.7-ohos-1.0.0 | master | |
| 41 | | 3.27 | 1.0.7-ohos-1.0.0 | master | | 41 | | 3.27 | 1.0.7-ohos-1.0.0 | master | |
| 42 | | 3.35 | 1.0.7-ohos-1.0.0 | master | | 42 | | 3.35 | 1.0.7-ohos-1.0.0 | master | |
| 43 | +| 3.41 | 1.0.7-ohos-1.0.0 | master | | ||
| 43 | 44 | ||
| 44 | <!-- tabs:end --> | 45 | <!-- tabs:end --> |
| 45 | 46 | ||
| @@ -47,6 +48,26 @@ flutter pub get | |||
| 47 | 48 | ||
| 48 | 使用案例详见 [example](/example/lib/main.dart)。 | 49 | 使用案例详见 [example](/example/lib/main.dart)。 |
| 49 | 50 | ||
| 51 | +快速上手: | ||
| 52 | + | ||
| 53 | +```dart | ||
| 54 | +import 'package:device_util/device_util.dart'; | ||
| 55 | + | ||
| 56 | +// 信息获取 | ||
| 57 | +String platformVersion = await DeviceUtil.platformVersion; // 如 "HarmonyOS 5.1.0" | ||
| 58 | +String versionName = await DeviceUtil.versionName; // 当前应用版本名 | ||
| 59 | +String versionCode = await DeviceUtil.versionCode; // 当前应用版本号 | ||
| 60 | +Map<String, String> channelInfo = await DeviceUtil.getChannelInfo; // 渠道信息(长度为 2) | ||
| 61 | + | ||
| 62 | +// 页面跳转 / 进程控制 | ||
| 63 | +await DeviceUtil.openApplicationSettingPage(); // 打开当前应用的系统设置页 | ||
| 64 | +await DeviceUtil.openNetworkSettingPage(); // 打开系统网络设置页 | ||
| 65 | +DeviceUtil.openAppStoreCommentPage('appId'); // 打开应用市场评分页(ohos 侧忽略 appID,始终跳转当前应用) | ||
| 66 | +await DeviceUtil.killApp(); // 终止当前应用进程并退出 | ||
| 67 | +``` | ||
| 68 | + | ||
| 69 | +> 说明:ohos 端所有方法均保证 result 回执(成功/失败/未实现),Dart 侧 `await` 不会因原生未回执而永久挂起;`versionName`/`versionCode` 获取失败时返回空串(与 Android 兜底行为一致)。 | ||
| 70 | + | ||
| 50 | ## 2. 约束与限制 | 71 | ## 2. 约束与限制 |
| 51 | 72 | ||
| 52 | ### 2.1 兼容性 | 73 | ### 2.1 兼容性 |
| @@ -56,6 +77,24 @@ flutter pub get | |||
| 56 | 1. Flutter: 3.7.12-ohos-1.1.3; SDK: 5.0.0(12); IDE: DevEco Studio: 5.1.0.828; ROM: 5.1.0.130 SP8; | 77 | 1. Flutter: 3.7.12-ohos-1.1.3; SDK: 5.0.0(12); IDE: DevEco Studio: 5.1.0.828; ROM: 5.1.0.130 SP8; |
| 57 | 2. Flutter: 3.22.1-ohos-1.0.3; SDK: 5.0.0(12); IDE: DevEco Studio: 5.1.0.828; ROM: 5.1.0.130 SP8; | 78 | 2. Flutter: 3.22.1-ohos-1.0.3; SDK: 5.0.0(12); IDE: DevEco Studio: 5.1.0.828; ROM: 5.1.0.130 SP8; |
| 58 | 3. Flutter: 3.35.8-ohos-0.0.1; SDK: 6.0.1(21); IDE: DevEco Studio: 6.0.1.260; ROM: 6.0.0.120 SP6; | 79 | 3. Flutter: 3.35.8-ohos-0.0.1; SDK: 6.0.1(21); IDE: DevEco Studio: 6.0.1.260; ROM: 6.0.0.120 SP6; |
| 80 | +4. Flutter: 3.41.10-ohos-1.0.0; SDK: 6.1.1(24); IDE: DevEco Studio: 6.1.1; ROM: 7.0.0.17DEV(C00E31R3P1log); | ||
| 81 | + | ||
| 82 | +### 2.2 环境搭建 | ||
| 83 | + | ||
| 84 | +ohos 平台开发环境搭建步骤: | ||
| 85 | + | ||
| 86 | +1. 安装 DevEco Studio(含 HarmonyOS SDK),参考[官方环境准备指南](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/ide-tools-overview); | ||
| 87 | +2. 获取 Flutter OHOS SDK(`flutter_flutter` 仓库 ohos 分支,可配合 [flvm](https://gitcode.com/openharmony-sig/flutter_flutter) 管理多版本),将 `flutter/bin` 加入 `PATH`,执行 `flutter doctor` 确认工具链就绪; | ||
| 88 | +3. 在工程目录执行 `flutter pub get` 拉取依赖; | ||
| 89 | +4. 运行 example 验证环境:连接 ohos 真机/模拟器后在 `example/` 目录执行 `flutter run`,或用 DevEco Studio 打开 `example/ohos` 运行; | ||
| 90 | +5. 打包验证:`flutter build hap --debug`(无需签名可加 `--no-codesign`)。 | ||
| 91 | + | ||
| 92 | +### 2.3 升级与迁移 | ||
| 93 | + | ||
| 94 | +- ohos 适配版本随 TAG 发布,TAG 与 Flutter 框架版本对应关系见上方「TAG 版本对应表」; | ||
| 95 | +- 版本演进记录见 [CHANGELOG.OpenHarmony.md](/CHANGELOG.OpenHarmony.md); | ||
| 96 | +- 升级方法:修改 pubspec.yaml 中依赖的 `ref` 为目标 TAG 后执行 `flutter pub get` 即可; | ||
| 97 | +- 已发布 TAG(`1.0.7-ohos.1.0.0-beta.1` → `1.0.7-ohos-1.0.0`)之间无对外 API 破坏性变更,Dart 层 API 与上游 device_util 1.0.7 保持一致,可平滑升级。 | ||
| 59 | 98 | ||
| 60 | 99 | ||
| 61 | ## 3. API | 100 | ## 3. API |
| @@ -77,9 +116,20 @@ flutter pub get | |||
| 77 | 116 | ||
| 78 | ## 4. 遗留问题 | 117 | ## 4. 遗留问题 |
| 79 | 118 | ||
| 119 | +无阻塞性遗留问题。以下为 ohos 平台与 Android/iOS 的已知行为差异(平台适配约定,供使用方知悉): | ||
| 120 | + | ||
| 121 | +| 差异点 | 说明 | | ||
| 122 | +|--------|------| | ||
| 123 | +| getChannelInfo 渠道配置 | 优先读取宿主应用 `resources/rawfile/channel.ini`(或 `channel_default.ini`,内容格式 `key=value`,与 Android assets 渠道配置约定一致);未配置时固定返回默认渠道 `Huawei Store For Harmony`(鸿蒙应用默认分发渠道为华为应用市场,与 iOS 固定值 "app store" 模式同构)。首装渠道(first_install_channel)通过 @ohos.data.preferences 持久化,与 Android SharedPreferences 行为对齐 | | ||
| 124 | +| openAppStoreCommentPage 的 appID 参数 | 与 Android 行为一致:忽略传入的 appID,始终以当前应用 bundleName 拉起华为应用市场当前应用详情页(AppGallery Kit loadProduct) | | ||
| 125 | +| openApplicationSettingPage 跳转粒度 | 优先定位到系统设置中当前应用的「应用信息」页(uri `application_info_entry`),部分系统版本不支持时自动回退到系统设置首页 | | ||
| 126 | +| minimizeWindow | 上游 Windows 平台专属能力,ohos/Android/iOS 均未实现(抛出 MissingPluginException) | | ||
| 80 | 127 | ||
| 81 | ## 5. 其他 | 128 | ## 5. 其他 |
| 82 | 129 | ||
| 130 | +- 单元测试:`flutter test`;覆盖率统计:`flutter test --coverage`(生成 `coverage/lcov.info`,可用 `genhtml -o coverage/html coverage/lcov.info` 输出 HTML 报告); | ||
| 131 | +- 持续集成:`.github/workflows/test.yml` 提供单测 + 分析 + 覆盖率门槛(行覆盖 ≥ 90%)自动检查; | ||
| 132 | +- 鸿蒙适配源码位于 `ohos/` 目录(ArkTS),版权与构建配置说明见 `ohos/` 下各文件头部。 | ||
| 83 | 133 | ||
| 84 | ## 6. 开源协议 | 134 | ## 6. 开源协议 |
| 85 | 135 | ||
| @@ -1,3 +1 @@ | |||
| 1 | analyzer: | 1 | analyzer: |
| 2 | - enable-experiment: | ||
| 3 | - - non-nullable | ||
| @@ -1,35 +0,0 @@ | |||
| 1 | -package com.chivan.device_util | ||
| 2 | - | ||
| 3 | -import androidx.annotation.NonNull | ||
| 4 | - | ||
| 5 | -import io.flutter.embedding.engine.plugins.FlutterPlugin | ||
| 6 | -import io.flutter.plugin.common.MethodCall | ||
| 7 | -import io.flutter.plugin.common.MethodChannel | ||
| 8 | -import io.flutter.plugin.common.MethodChannel.MethodCallHandler | ||
| 9 | -import io.flutter.plugin.common.MethodChannel.Result | ||
| 10 | - | ||
| 11 | -/** DeviceUtilPlugin */ | ||
| 12 | -class DeviceUtilPlugin: FlutterPlugin, MethodCallHandler { | ||
| 13 | - /// The MethodChannel that will the communication between Flutter and native Android | ||
| 14 | - /// | ||
| 15 | - /// This local reference serves to register the plugin with the Flutter Engine and unregister it | ||
| 16 | - /// when the Flutter Engine is detached from the Activity | ||
| 17 | - private lateinit var channel : MethodChannel | ||
| 18 | - | ||
| 19 | - override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) { | ||
| 20 | - channel = MethodChannel(flutterPluginBinding.binaryMessenger, "device_util") | ||
| 21 | - channel.setMethodCallHandler(this) | ||
| 22 | - } | ||
| 23 | - | ||
| 24 | - override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) { | ||
| 25 | - if (call.method == "getPlatformVersion") { | ||
| 26 | - result.success("Android ${android.os.Build.VERSION.RELEASE}") | ||
| 27 | - } else { | ||
| 28 | - result.notImplemented() | ||
| 29 | - } | ||
| 30 | - } | ||
| 31 | - | ||
| 32 | - override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) { | ||
| 33 | - channel.setMethodCallHandler(null) | ||
| 34 | - } | ||
| 35 | -} | ||
| @@ -13,4 +13,4 @@ | |||
| 13 | # limitations under the License. | 13 | # limitations under the License. |
| 14 | 14 | ||
| 15 | BUILD_PKG_DIR=example | 15 | BUILD_PKG_DIR=example |
| 16 | -FLUTTER_SDK_VERSION=("br_3.7.12-ohos-1.1.3" "oh-3.22.3-release" "oh-3.27.0-release" "oh-3.35.7-release") | 16 | +FLUTTER_SDK_VERSION=("br_3.7.12-ohos-1.1.3" "oh-3.22.3-release" "oh-3.27.0-release" "oh-3.35.7-release" "oh-3.41.9-release") |
| @@ -18,15 +18,16 @@ import 'dart:async'; | |||
| 18 | import 'package:device_util/device_util.dart'; | 18 | import 'package:device_util/device_util.dart'; |
| 19 | import 'package:flutter/material.dart'; | 19 | import 'package:flutter/material.dart'; |
| 20 | import 'package:flutter/services.dart'; | 20 | import 'package:flutter/services.dart'; |
| 21 | -import 'package:flutter/widgets.dart'; | ||
| 22 | 21 | ||
| 23 | void main() { | 22 | void main() { |
| 24 | runApp(MyApp()); | 23 | runApp(MyApp()); |
| 25 | } | 24 | } |
| 26 | 25 | ||
| 27 | class MyApp extends StatefulWidget { | 26 | class MyApp extends StatefulWidget { |
| 27 | + const MyApp({Key? key}) : super(key: key); | ||
| 28 | + | ||
| 28 | @override | 29 | @override |
| 29 | - _MyAppState createState() => _MyAppState(); | 30 | + State<MyApp> createState() => _MyAppState(); |
| 30 | } | 31 | } |
| 31 | 32 | ||
| 32 | class _MyAppState extends State<MyApp> { | 33 | class _MyAppState extends State<MyApp> { |
| @@ -78,17 +79,18 @@ class _MyAppState extends State<MyApp> { | |||
| 78 | ), | 79 | ), |
| 79 | body: ListView( | 80 | body: ListView( |
| 80 | children: [ | 81 | children: [ |
| 82 | + // 信息获取:平台版本 / 应用版本名 / 版本号 / 渠道信息(ohos 端返回值与 Android/iOS 对齐) | ||
| 81 | ListTile( | 83 | ListTile( |
| 82 | title: Text('Running on:'), | 84 | title: Text('Running on:'), |
| 83 | - subtitle: Text('$_platformVersion'), | 85 | + subtitle: Text(_platformVersion), |
| 84 | ), | 86 | ), |
| 85 | ListTile( | 87 | ListTile( |
| 86 | title: Text('Version name is:'), | 88 | title: Text('Version name is:'), |
| 87 | - subtitle: Text('$_versionName'), | 89 | + subtitle: Text(_versionName), |
| 88 | ), | 90 | ), |
| 89 | ListTile( | 91 | ListTile( |
| 90 | title: Text('Version code is:'), | 92 | title: Text('Version code is:'), |
| 91 | - subtitle: Text('$_versionCode'), | 93 | + subtitle: Text(_versionCode), |
| 92 | ), | 94 | ), |
| 93 | ListTile( | 95 | ListTile( |
| 94 | title: Text('Channels:'), | 96 | title: Text('Channels:'), |
| @@ -100,7 +102,9 @@ class _MyAppState extends State<MyApp> { | |||
| 100 | ], | 102 | ], |
| 101 | ), | 103 | ), |
| 102 | ), | 104 | ), |
| 105 | + // 功能操作:以下跳转/控制方法在 ohos 端均保证 result 回执,await 不会永久挂起 | ||
| 103 | ListTile( | 106 | ListTile( |
| 107 | + // 打开当前应用的系统设置页(ohos:优先定位到设置中本应用的「应用信息」页) | ||
| 104 | title: Text('Open application setting page'), | 108 | title: Text('Open application setting page'), |
| 105 | trailing: Icon(Icons.chevron_right), | 109 | trailing: Icon(Icons.chevron_right), |
| 106 | onTap: () { | 110 | onTap: () { |
| @@ -108,6 +112,7 @@ class _MyAppState extends State<MyApp> { | |||
| 108 | }, | 112 | }, |
| 109 | ), | 113 | ), |
| 110 | ListTile( | 114 | ListTile( |
| 115 | + // 打开系统网络设置页(ohos:跳转系统设置 WLAN 页面) | ||
| 111 | title: Text('Open network setting page'), | 116 | title: Text('Open network setting page'), |
| 112 | trailing: Icon(Icons.chevron_right), | 117 | trailing: Icon(Icons.chevron_right), |
| 113 | onTap: () { | 118 | onTap: () { |
| @@ -115,6 +120,8 @@ class _MyAppState extends State<MyApp> { | |||
| 115 | }, | 120 | }, |
| 116 | ), | 121 | ), |
| 117 | ListTile( | 122 | ListTile( |
| 123 | + // 打开应用市场评分页。'appId' 为占位参数:ohos/Android 端均忽略该参数, | ||
| 124 | + // 始终以当前应用包名拉起应用市场详情页,无需替换 | ||
| 118 | title: Text('Open app store comment page'), | 125 | title: Text('Open app store comment page'), |
| 119 | trailing: Icon(Icons.chevron_right), | 126 | trailing: Icon(Icons.chevron_right), |
| 120 | onTap: () { | 127 | onTap: () { |
| @@ -122,6 +129,7 @@ class _MyAppState extends State<MyApp> { | |||
| 122 | }, | 129 | }, |
| 123 | ), | 130 | ), |
| 124 | ListTile( | 131 | ListTile( |
| 132 | + // 最小化窗口:仅 Windows 平台支持,ohos/Android/iOS 端抛出 MissingPluginException | ||
| 125 | title: Text('Minimized window(Windows only)'), | 133 | title: Text('Minimized window(Windows only)'), |
| 126 | trailing: Icon(Icons.chevron_right), | 134 | trailing: Icon(Icons.chevron_right), |
| 127 | onTap: () { | 135 | onTap: () { |
| @@ -129,6 +137,7 @@ class _MyAppState extends State<MyApp> { | |||
| 129 | }, | 137 | }, |
| 130 | ), | 138 | ), |
| 131 | ListTile( | 139 | ListTile( |
| 140 | + // 终止当前应用进程并退出(ohos:进程退出前会先回执 Dart 侧) | ||
| 132 | title: Text('Kill app'), | 141 | title: Text('Kill app'), |
| 133 | trailing: Icon(Icons.chevron_right), | 142 | trailing: Icon(Icons.chevron_right), |
| 134 | onTap: () { | 143 | onTap: () { |
| @@ -27,6 +27,7 @@ dependencies: | |||
| 27 | dev_dependencies: | 27 | dev_dependencies: |
| 28 | flutter_test: | 28 | flutter_test: |
| 29 | sdk: flutter | 29 | sdk: flutter |
| 30 | + flutter_lints: ^5.0.0 | ||
| 30 | 31 | ||
| 31 | # For information on the generic Dart part of this file, see the | 32 | # For information on the generic Dart part of this file, see the |
| 32 | # following page: https://dart.dev/tools/pub/pubspec | 33 | # following page: https://dart.dev/tools/pub/pubspec |
| @@ -19,7 +19,7 @@ void main() { | |||
| 19 | expect( | 19 | expect( |
| 20 | find.byWidgetPredicate( | 20 | find.byWidgetPredicate( |
| 21 | (Widget widget) => | 21 | (Widget widget) => |
| 22 | - widget is Text && widget.data.startsWith('Running on:'), | 22 | + widget is Text && (widget.data?.startsWith('Running on:') ?? false), |
| 23 | ), | 23 | ), |
| 24 | findsOneWidget, | 24 | findsOneWidget, |
| 25 | ); | 25 | ); |
| @@ -1,14 +0,0 @@ | |||
| 1 | -import Flutter | ||
| 2 | -import UIKit | ||
| 3 | - | ||
| 4 | -public class SwiftDeviceUtilPlugin: NSObject, FlutterPlugin { | ||
| 5 | - public static func register(with registrar: FlutterPluginRegistrar) { | ||
| 6 | - let channel = FlutterMethodChannel(name: "device_util", binaryMessenger: registrar.messenger()) | ||
| 7 | - let instance = SwiftDeviceUtilPlugin() | ||
| 8 | - registrar.addMethodCallDelegate(instance, channel: channel) | ||
| 9 | - } | ||
| 10 | - | ||
| 11 | - public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { | ||
| 12 | - result("iOS " + UIDevice.current.systemVersion) | ||
| 13 | - } | ||
| 14 | -} | ||
| @@ -23,6 +23,7 @@ import MethodChannel, { | |||
| 23 | } from '@ohos/flutter_ohos/src/main/ets/plugin/common/MethodChannel'; | 23 | } from '@ohos/flutter_ohos/src/main/ets/plugin/common/MethodChannel'; |
| 24 | import MethodCall from '@ohos/flutter_ohos/src/main/ets/plugin/common/MethodCall'; | 24 | import MethodCall from '@ohos/flutter_ohos/src/main/ets/plugin/common/MethodCall'; |
| 25 | import { bundleManager, UIAbility } from '@kit.AbilityKit'; | 25 | import { bundleManager, UIAbility } from '@kit.AbilityKit'; |
| 26 | +import { BusinessError } from '@kit.BasicServicesKit'; | ||
| 26 | import { AbilityAware, AbilityPluginBinding, Log } from '@ohos/flutter_ohos'; | 27 | import { AbilityAware, AbilityPluginBinding, Log } from '@ohos/flutter_ohos'; |
| 27 | import { ConstantValue } from './ConstantValue'; | 28 | import { ConstantValue } from './ConstantValue'; |
| 28 | import { Utils } from './Utils'; | 29 | import { Utils } from './Utils'; |
| @@ -32,6 +33,7 @@ const TAG = "DeviceUtilPlugin" | |||
| 32 | export default class DeviceUtilPlugin implements FlutterPlugin, MethodCallHandler, AbilityAware { | 33 | export default class DeviceUtilPlugin implements FlutterPlugin, MethodCallHandler, AbilityAware { |
| 33 | private channel: MethodChannel | null = null; | 34 | private channel: MethodChannel | null = null; |
| 34 | private uiAbility: UIAbility | null = null | 35 | private uiAbility: UIAbility | null = null |
| 36 | + private detached: boolean = false | ||
| 35 | 37 | ||
| 36 | constructor() { | 38 | constructor() { |
| 37 | } | 39 | } |
| @@ -51,49 +53,122 @@ export default class DeviceUtilPlugin implements FlutterPlugin, MethodCallHandle | |||
| 51 | } | 53 | } |
| 52 | 54 | ||
| 53 | onAttachedToEngine(binding: FlutterPluginBinding): void { | 55 | onAttachedToEngine(binding: FlutterPluginBinding): void { |
| 56 | + this.detached = false | ||
| 54 | this.channel = new MethodChannel(binding.getBinaryMessenger(), "device_util"); | 57 | this.channel = new MethodChannel(binding.getBinaryMessenger(), "device_util"); |
| 55 | this.channel.setMethodCallHandler(this) | 58 | this.channel.setMethodCallHandler(this) |
| 56 | } | 59 | } |
| 57 | 60 | ||
| 58 | onDetachedFromEngine(binding: FlutterPluginBinding): void { | 61 | onDetachedFromEngine(binding: FlutterPluginBinding): void { |
| 62 | + Log.i(TAG, "onDetachedFromEngine") | ||
| 59 | if (this.channel != null) { | 63 | if (this.channel != null) { |
| 60 | this.channel.setMethodCallHandler(null) | 64 | this.channel.setMethodCallHandler(null) |
| 61 | } | 65 | } |
| 66 | + // 与官方 flutter_ohos 插件惯例一致:释放 channel 引用, | ||
| 67 | + // 避免插件实例在引擎销毁后仍持有对 BinaryMessenger 的引用 | ||
| 68 | + this.channel = null | ||
| 69 | + // 标记引擎已分离:await 后的异步回写跳过,避免向已销毁引擎的 MethodResult 回写 | ||
| 70 | + this.detached = true | ||
| 62 | } | 71 | } |
| 63 | 72 | ||
| 64 | async onMethodCall(call: MethodCall, result: MethodResult): Promise<void> { | 73 | async onMethodCall(call: MethodCall, result: MethodResult): Promise<void> { |
| 65 | - switch (call.method) { | 74 | + try { |
| 66 | - case ConstantValue.GET_PLATFORM_VERSION: | 75 | + switch (call.method) { |
| 67 | - result.success("HarmonyOS " + Utils.getDeviceBuildInfo()) | 76 | + case ConstantValue.GET_PLATFORM_VERSION: { |
| 68 | - break; | 77 | + // 返回格式对齐 Android "Android 14" / iOS "iOS 17.0",如 "HarmonyOS 5.1.0"; |
| 69 | - case ConstantValue.GET_VERSION_NAME: | 78 | + // 不再硬编码 "HarmonyOS " 前缀拼接 osFullName(会产生 "HarmonyOS HarmonyOS-x.x.x" 冗余) |
| 70 | - let bundleInfo: bundleManager.BundleInfo = await Utils.getAppBundleInfo() | 79 | + result.success(Utils.getDeviceBuildInfo()) |
| 71 | - let versionName: string | undefined = bundleInfo?.versionName | 80 | + break; |
| 72 | - result.success(versionName + "") | 81 | + } |
| 73 | - break; | 82 | + case ConstantValue.GET_VERSION_NAME: { |
| 74 | - case ConstantValue.GET_VERSION_CODE: | 83 | + try { |
| 75 | - let bundleInfoVersion: bundleManager.BundleInfo = await Utils.getAppBundleInfo() | 84 | + let bundleInfo: bundleManager.BundleInfo = await Utils.getAppBundleInfo() |
| 76 | - let versionCode: number | undefined = bundleInfoVersion?.versionCode | 85 | + if (this.detached) { |
| 77 | - result.success(versionCode + "") | 86 | + return |
| 78 | - break; | 87 | + } |
| 79 | - case ConstantValue.GET_CHANNEL_INFO: | 88 | + let versionName: string | undefined = bundleInfo?.versionName |
| 80 | - result.success(Utils.getChannelInfo()) | 89 | + // undefined 兜底空串,避免向 Dart 层返回字符串 "undefined"(对齐 Android 失败兜底 "") |
| 81 | - break; | 90 | + result.success(versionName ?? "") |
| 82 | - case ConstantValue.LAUNCH_NO_NETWORK: | 91 | + } catch (err) { |
| 83 | - Utils.jumpToWifiSettings(this.uiAbility) | 92 | + // 对齐 Android 行为:获取失败时返回空串,Future 正常完成而非永久挂起 |
| 84 | - break; | 93 | + Log.e(TAG, "getVersionName failed: " + JSON.stringify(err)) |
| 85 | - case ConstantValue.SYSTEM_SETTING_PAGE: | 94 | + if (!this.detached) { |
| 86 | - Utils.jumpToSettings(this.uiAbility) | 95 | + result.success("") |
| 87 | - break; | 96 | + } |
| 88 | - case ConstantValue.OPEN_MARKET_COMMENT: | 97 | + } |
| 89 | - Utils.jumpToMarket(this.uiAbility) | 98 | + break; |
| 90 | - break | 99 | + } |
| 91 | - case ConstantValue.KILL_APP: | 100 | + case ConstantValue.GET_VERSION_CODE: { |
| 92 | - Utils.killApp() | 101 | + try { |
| 93 | - break | 102 | + let bundleInfoVersion: bundleManager.BundleInfo = await Utils.getAppBundleInfo() |
| 94 | - default: | 103 | + if (this.detached) { |
| 95 | - result.notImplemented() | 104 | + return |
| 96 | - break | 105 | + } |
| 106 | + let versionCode: number | undefined = bundleInfoVersion?.versionCode | ||
| 107 | + result.success(versionCode === undefined ? "" : `${versionCode}`) | ||
| 108 | + } catch (err) { | ||
| 109 | + Log.e(TAG, "getVersionCode failed: " + JSON.stringify(err)) | ||
| 110 | + if (!this.detached) { | ||
| 111 | + result.success("") | ||
| 112 | + } | ||
| 113 | + } | ||
| 114 | + break; | ||
| 115 | + } | ||
| 116 | + case ConstantValue.GET_CHANNEL_INFO: { | ||
| 117 | + let channelInfo: Map<string, string> = await Utils.getChannelInfo(this.uiAbility) | ||
| 118 | + if (this.detached) { | ||
| 119 | + return | ||
| 120 | + } | ||
| 121 | + result.success(channelInfo) | ||
| 122 | + break; | ||
| 123 | + } | ||
| 124 | + case ConstantValue.LAUNCH_NO_NETWORK: { | ||
| 125 | + // fire-and-forget:跳转异常已在 Utils 内部捕获记录日志 | ||
| 126 | + Utils.jumpToWifiSettings(this.uiAbility) | ||
| 127 | + // 对齐 iOS result(nil) 契约:成功受理即回执,避免 Dart 侧 await 的 Future 永久挂起 | ||
| 128 | + result.success(null) | ||
| 129 | + break; | ||
| 130 | + } | ||
| 131 | + case ConstantValue.SYSTEM_SETTING_PAGE: { | ||
| 132 | + // fire-and-forget:跳转异常已在 Utils 内部捕获并自动回退设置首页 | ||
| 133 | + Utils.jumpToSettings(this.uiAbility) | ||
| 134 | + result.success(null) | ||
| 135 | + break; | ||
| 136 | + } | ||
| 137 | + case ConstantValue.OPEN_MARKET_COMMENT: { | ||
| 138 | + // 平台适配说明:与 Android 行为一致,Dart 层传入的 appID 参数被忽略, | ||
| 139 | + // 始终以当前应用 bundleName 拉起应用市场当前应用详情页(对应"当前应用评分页"语义) | ||
| 140 | + Utils.jumpToMarket(this.uiAbility).then(() => { | ||
| 141 | + // 跳转请求已受理(详情页加载失败由 loadProduct 的 onError 回调记录日志) | ||
| 142 | + if (!this.detached) { | ||
| 143 | + result.success(null) | ||
| 144 | + } | ||
| 145 | + }).catch((err: BusinessError) => { | ||
| 146 | + // 异常传播到 Flutter 层,消除 unhandled promise rejection 与 Future 挂起 | ||
| 147 | + Log.e(TAG, "jumpToMarket failed: " + err) | ||
| 148 | + if (!this.detached) { | ||
| 149 | + result.error("MARKET_ERROR", err.message, null) | ||
| 150 | + } | ||
| 151 | + }) | ||
| 152 | + break; | ||
| 153 | + } | ||
| 154 | + case ConstantValue.KILL_APP: { | ||
| 155 | + // 尽力而为的契约完善:先回执再退出进程,给 Dart 侧 Future 完成的机会 | ||
| 156 | + result.success(null) | ||
| 157 | + Utils.killApp() | ||
| 158 | + break; | ||
| 159 | + } | ||
| 160 | + default: { | ||
| 161 | + result.notImplemented() | ||
| 162 | + break; | ||
| 163 | + } | ||
| 164 | + } | ||
| 165 | + } catch (err) { | ||
| 166 | + // 兜底:任何未预期异常统一回传 Flutter 层, | ||
| 167 | + // 避免 unhandled promise rejection 与 Dart 侧 Future 永久挂起 | ||
| 168 | + Log.e(TAG, "onMethodCall " + call.method + " error: " + JSON.stringify(err)) | ||
| 169 | + if (!this.detached) { | ||
| 170 | + result.error("DEVICE_UTIL_ERROR", "device_util " + call.method + " invoke failed", null) | ||
| 171 | + } | ||
| 97 | } | 172 | } |
| 98 | } | 173 | } |
| 99 | -} | 174 | +} |
| @@ -18,18 +18,42 @@ import deviceInfo from '@ohos.deviceInfo'; | |||
| 18 | import { UIAbility, Want } from '@kit.AbilityKit'; | 18 | import { UIAbility, Want } from '@kit.AbilityKit'; |
| 19 | import { BusinessError } from '@kit.BasicServicesKit'; | 19 | import { BusinessError } from '@kit.BasicServicesKit'; |
| 20 | import process from '@ohos.process'; | 20 | import process from '@ohos.process'; |
| 21 | +import preferences from '@ohos.data.preferences'; | ||
| 22 | +import util from '@ohos.util'; | ||
| 21 | import { Log } from '@ohos/flutter_ohos'; | 23 | import { Log } from '@ohos/flutter_ohos'; |
| 22 | import { productViewManager } from '@kit.StoreKit'; | 24 | import { productViewManager } from '@kit.StoreKit'; |
| 23 | 25 | ||
| 24 | const TAG = "Utils" | 26 | const TAG = "Utils" |
| 25 | 27 | ||
| 28 | +/** 系统设置应用 */ | ||
| 29 | +const SETTINGS_BUNDLE_NAME = 'com.huawei.hmos.settings' | ||
| 30 | +const SETTINGS_ABILITY_NAME = 'com.huawei.hmos.settings.MainAbility' | ||
| 31 | + | ||
| 32 | +/** 默认渠道(鸿蒙应用的默认分发渠道为华为应用市场) */ | ||
| 33 | +const DEFAULT_CHANNEL = "Huawei Store For Harmony" | ||
| 34 | +/** 渠道配置文件(与 Android assets 下 channel.ini / channel_default.ini 约定一致,ohos 侧从宿主 rawfile 读取) */ | ||
| 35 | +const CHANNEL_FILE = "channel.ini" | ||
| 36 | +const DEFAULT_CHANNEL_FILE = "channel_default.ini" | ||
| 37 | +/** 首装渠道持久化(对齐 Android SharedPreferences 的存储键) */ | ||
| 38 | +const CHANNEL_PREFERENCES_NAME = "device_util_channel" | ||
| 39 | +const KEY_FIRST_INSTALL_CHANNEL = "FIRST_INSTALL_CHANNEL" | ||
| 40 | + | ||
| 26 | export class Utils { | 41 | export class Utils { |
| 27 | /** | 42 | /** |
| 28 | - * 获取系统版本 | 43 | + * 获取平台版本,格式对齐 Android "Android 14" / iOS "iOS 17.0", |
| 44 | + * 如 "HarmonyOS 5.1.0"。 | ||
| 45 | + * 说明:osFullName 本身自带系统名前缀(如 "HarmonyOS-5.1.0.xxx"), | ||
| 46 | + * 再拼接 "HarmonyOS " 会产生 "HarmonyOS HarmonyOS-5.1.0" 冗余,故不再额外拼接前缀。 | ||
| 29 | * | 47 | * |
| 30 | - * @return 系统版本 | 48 | + * @return 平台版本 |
| 31 | */ | 49 | */ |
| 32 | public static getDeviceBuildInfo(): string { | 50 | public static getDeviceBuildInfo(): string { |
| 51 | + let osName: string = deviceInfo.distributionOSName | ||
| 52 | + let osVersion: string = deviceInfo.distributionOSVersion | ||
| 53 | + if (osName.length > 0 && osVersion.length > 0) { | ||
| 54 | + return osName + " " + osVersion | ||
| 55 | + } | ||
| 56 | + // 兜底:发行版信息缺失时返回完整系统版本(自带系统名前缀) | ||
| 33 | return deviceInfo.osFullName | 57 | return deviceInfo.osFullName |
| 34 | } | 58 | } |
| 35 | 59 | ||
| @@ -44,35 +68,119 @@ export class Utils { | |||
| 44 | } | 68 | } |
| 45 | 69 | ||
| 46 | /** | 70 | /** |
| 47 | - * 渠道(鸿蒙固定写华为商店) | 71 | + * 获取渠道信息(对齐 Android 的动态渠道能力,所有异常均内部降级、不向外抛出): |
| 72 | + * - current_install_channel:优先读取宿主 rawfile 下 channel.ini / channel_default.ini | ||
| 73 | + * (文件内容格式 "key=value",与 Android assets 渠道配置一致),未配置时返回默认渠道; | ||
| 74 | + * - first_install_channel:首次获取时通过 @ohos.data.preferences 持久化,此后返回历史首装渠道。 | ||
| 48 | * | 75 | * |
| 49 | - * @return 渠道 | 76 | + * @param uiAbility 上下文(用于读取 rawfile 与 preferences;为空时退化为固定默认渠道) |
| 77 | + * @return 渠道信息(键:first_install_channel / current_install_channel) | ||
| 50 | */ | 78 | */ |
| 51 | - public static getChannelInfo(): Map<string, string> { | 79 | + public static async getChannelInfo(uiAbility: UIAbility | null): Promise<Map<string, string>> { |
| 52 | - const channelInfo = new Map<string, string>() | 80 | + let latestChannel: string = await Utils.readChannelFromRawfile(uiAbility, CHANNEL_FILE) |
| 53 | - channelInfo.set("first_install_channel", "Huawei Store For Harmony") | 81 | + if (latestChannel.length === 0) { |
| 54 | - channelInfo.set("current_install_channel", "Huawei Store For Harmony") | 82 | + latestChannel = await Utils.readChannelFromRawfile(uiAbility, DEFAULT_CHANNEL_FILE) |
| 83 | + } | ||
| 84 | + if (latestChannel.length === 0) { | ||
| 85 | + latestChannel = DEFAULT_CHANNEL | ||
| 86 | + } | ||
| 87 | + let firstInstallChannel: string = latestChannel | ||
| 88 | + if (uiAbility) { | ||
| 89 | + try { | ||
| 90 | + let prefs: preferences.Preferences = | ||
| 91 | + await preferences.getPreferences(uiAbility.context, CHANNEL_PREFERENCES_NAME) | ||
| 92 | + let stored: preferences.ValueType = await prefs.get(KEY_FIRST_INSTALL_CHANNEL, "") | ||
| 93 | + if (typeof stored === 'string' && stored.length > 0) { | ||
| 94 | + firstInstallChannel = stored | ||
| 95 | + } else { | ||
| 96 | + await prefs.put(KEY_FIRST_INSTALL_CHANNEL, firstInstallChannel) | ||
| 97 | + await prefs.flush() | ||
| 98 | + } | ||
| 99 | + } catch (err) { | ||
| 100 | + // preferences 异常不阻断接口:退化为不持久化的当前渠道 | ||
| 101 | + Log.e(TAG, "getChannelInfo: preferences failed: " + JSON.stringify(err)) | ||
| 102 | + } | ||
| 103 | + } | ||
| 104 | + let channelInfo = new Map<string, string>() | ||
| 105 | + channelInfo.set("first_install_channel", firstInstallChannel) | ||
| 106 | + channelInfo.set("current_install_channel", latestChannel) | ||
| 55 | return channelInfo | 107 | return channelInfo |
| 56 | } | 108 | } |
| 57 | 109 | ||
| 58 | /** | 110 | /** |
| 59 | - * 跳转系统设置 | 111 | + * 读取宿主 rawfile 渠道配置并解析 "key=value" 中的渠道值。 |
| 112 | + * 文件不存在或格式非法时返回空串(属正常降级场景,静默处理)。 | ||
| 113 | + */ | ||
| 114 | + private static async readChannelFromRawfile(uiAbility: UIAbility | null, fileName: string): Promise<string> { | ||
| 115 | + if (!uiAbility) { | ||
| 116 | + return "" | ||
| 117 | + } | ||
| 118 | + try { | ||
| 119 | + let content: Uint8Array = await uiAbility.context.resourceManager.getRawFileContent(fileName) | ||
| 120 | + let text: string = util.TextDecoder.create('utf-8').decodeToString(content).trim() | ||
| 121 | + let parts: string[] = text.split("=") | ||
| 122 | + if (parts.length === 2 && parts[0].length > 0 && parts[1].length > 0) { | ||
| 123 | + return parts[1] | ||
| 124 | + } | ||
| 125 | + return "" | ||
| 126 | + } catch (err) { | ||
| 127 | + // rawfile 渠道文件不存在属正常场景(宿主未配置渠道),静默降级返回空串 | ||
| 128 | + return "" | ||
| 129 | + } | ||
| 130 | + } | ||
| 131 | + | ||
| 132 | + /** | ||
| 133 | + * 跳转系统设置。优先定位到"当前应用"的应用信息设置页 | ||
| 134 | + * (对齐 Dart 语义 "settings page of the currently running application" 及 Android/iOS 的应用维度设置页); | ||
| 135 | + * 应用信息获取失败或跳转失败时自动回退到系统设置首页。 | ||
| 60 | * | 136 | * |
| 61 | * @param uiAbility 上下文 | 137 | * @param uiAbility 上下文 |
| 62 | */ | 138 | */ |
| 63 | - public static jumpToSettings(uiAbility: UIAbility | null): void { | 139 | + public static async jumpToSettings(uiAbility: UIAbility | null): Promise<void> { |
| 64 | if (!uiAbility) { | 140 | if (!uiAbility) { |
| 65 | Log.i(TAG, "jumpToSettings context empty") | 141 | Log.i(TAG, "jumpToSettings context empty") |
| 66 | return | 142 | return |
| 67 | } | 143 | } |
| 68 | - let want: Want = { | 144 | + let selfBundleName: string = "" |
| 69 | - bundleName: 'com.huawei.hmos.settings', | 145 | + try { |
| 70 | - abilityName: 'com.huawei.hmos.settings.MainAbility', | 146 | + selfBundleName = (await Utils.getAppBundleInfo())?.name ?? "" |
| 147 | + } catch (err) { | ||
| 148 | + Log.e(TAG, "jumpToSettings: get app bundle info failed: " + JSON.stringify(err)) | ||
| 149 | + } | ||
| 150 | + let want: Want | ||
| 151 | + if (selfBundleName.length > 0) { | ||
| 152 | + want = { | ||
| 153 | + bundleName: SETTINGS_BUNDLE_NAME, | ||
| 154 | + abilityName: SETTINGS_ABILITY_NAME, | ||
| 155 | + // 定位到设置中当前应用的"应用信息"页 | ||
| 156 | + uri: 'application_info_entry', | ||
| 157 | + parameters: { | ||
| 158 | + bundleName: selfBundleName | ||
| 159 | + } | ||
| 160 | + } | ||
| 161 | + } else { | ||
| 162 | + want = { | ||
| 163 | + bundleName: SETTINGS_BUNDLE_NAME, | ||
| 164 | + abilityName: SETTINGS_ABILITY_NAME, | ||
| 165 | + } | ||
| 166 | + } | ||
| 167 | + try { | ||
| 168 | + await uiAbility.context.startAbility(want) | ||
| 169 | + } catch (err) { | ||
| 170 | + Log.e(TAG, "jumpToSettings: " + JSON.stringify(err)) | ||
| 171 | + if (selfBundleName.length > 0) { | ||
| 172 | + // 部分系统版本不支持 application_info_entry 定位时,回退到系统设置首页(保持旧行为可用) | ||
| 173 | + let fallbackWant: Want = { | ||
| 174 | + bundleName: SETTINGS_BUNDLE_NAME, | ||
| 175 | + abilityName: SETTINGS_ABILITY_NAME, | ||
| 176 | + } | ||
| 177 | + try { | ||
| 178 | + await uiAbility.context.startAbility(fallbackWant) | ||
| 179 | + } catch (fallbackErr) { | ||
| 180 | + Log.e(TAG, "jumpToSettings fallback: " + JSON.stringify(fallbackErr)) | ||
| 181 | + } | ||
| 182 | + } | ||
| 71 | } | 183 | } |
| 72 | - uiAbility.context.startAbility(want).then(() => { | ||
| 73 | - }).catch((err: BusinessError) => { | ||
| 74 | - Log.e(TAG, "jumpToSettings: " + err) | ||
| 75 | - }) | ||
| 76 | } | 184 | } |
| 77 | 185 | ||
| 78 | /** | 186 | /** |
| @@ -86,8 +194,8 @@ export class Utils { | |||
| 86 | return | 194 | return |
| 87 | } | 195 | } |
| 88 | let want: Want = { | 196 | let want: Want = { |
| 89 | - bundleName: 'com.huawei.hmos.settings', | 197 | + bundleName: SETTINGS_BUNDLE_NAME, |
| 90 | - abilityName: 'com.huawei.hmos.settings.MainAbility', | 198 | + abilityName: SETTINGS_ABILITY_NAME, |
| 91 | uri: 'wifi_entry' | 199 | uri: 'wifi_entry' |
| 92 | } | 200 | } |
| 93 | uiAbility.context.startAbility(want).then(() => { | 201 | uiAbility.context.startAbility(want).then(() => { |
| @@ -97,7 +205,9 @@ export class Utils { | |||
| 97 | } | 205 | } |
| 98 | 206 | ||
| 99 | /** | 207 | /** |
| 100 | - * 跳转应用市场 | 208 | + * 跳转应用市场当前应用详情页。 |
| 209 | + * 注意:获取应用信息失败时异常会向上抛出,由调用方统一回传 Flutter 层 | ||
| 210 | + * (避免 fire-and-forget 产生 unhandled promise rejection)。 | ||
| 101 | * | 211 | * |
| 102 | * @param uiAbility 上下文 | 212 | * @param uiAbility 上下文 |
| 103 | */ | 213 | */ |
| @@ -118,19 +228,26 @@ export class Utils { | |||
| 118 | bundleName: bundleName | 228 | bundleName: bundleName |
| 119 | } | 229 | } |
| 120 | } | 230 | } |
| 121 | - productViewManager.loadProduct(uiAbility.context, want, { | 231 | + try { |
| 122 | - onError: (error: BusinessError) => { | 232 | + productViewManager.loadProduct(uiAbility.context, want, { |
| 123 | - Log.e(TAG, "jumpToMarket: " + error) | 233 | + onError: (error: BusinessError) => { |
| 124 | - } | 234 | + Log.e(TAG, "jumpToMarket: " + error) |
| 125 | - }); | 235 | + } |
| 236 | + }); | ||
| 237 | + } catch (err) { | ||
| 238 | + // 官方文档要求:调用 loadProduct 需捕获异常(如不支持的设备类型会抛出 401) | ||
| 239 | + Log.e(TAG, "jumpToMarket loadProduct: " + JSON.stringify(err)) | ||
| 240 | + } | ||
| 126 | } | 241 | } |
| 127 | 242 | ||
| 128 | /** | 243 | /** |
| 129 | - * 杀进程 | 244 | + * 杀进程。 |
| 245 | + * 说明:模块级 process.exit 自 API 9 起已废弃,官方推荐通过 | ||
| 246 | + * new process.ProcessManager() 实例调用 exit(API 9+),故保持实例调用方式。 | ||
| 130 | */ | 247 | */ |
| 131 | public static killApp(): void { | 248 | public static killApp(): void { |
| 132 | Log.i(TAG, "killApp") | 249 | Log.i(TAG, "killApp") |
| 133 | let pro = new process.ProcessManager() | 250 | let pro = new process.ProcessManager() |
| 134 | pro.exit(0) | 251 | pro.exit(0) |
| 135 | } | 252 | } |
| 136 | -} | 253 | +} |
| @@ -4,8 +4,10 @@ version: 1.0.7 | |||
| 4 | homepage: https://github.com/Code-Yeong/device_util.git | 4 | homepage: https://github.com/Code-Yeong/device_util.git |
| 5 | 5 | ||
| 6 | environment: | 6 | environment: |
| 7 | - sdk: ">=2.12.0 <3.0.0" | 7 | + # 上界放宽至 <4.0.0:字面约束 ">=2.12.0 <3.0.0" 不含 Flutter 3.x, |
| 8 | - flutter: ">=2.0.0 <3.0.0" | 8 | + # 已实测 3.7/3.22/3.27/3.35/3.41(ohos 分支)下 pub get / 编译 / 测试均通过 |
| 9 | + sdk: ">=2.12.0 <4.0.0" | ||
| 10 | + flutter: ">=2.0.0 <4.0.0" | ||
| 9 | 11 | ||
| 10 | dependencies: | 12 | dependencies: |
| 11 | flutter: | 13 | flutter: |
| @@ -1,23 +1,236 @@ | |||
| 1 | +import 'dart:async'; | ||
| 2 | + | ||
| 3 | +import 'package:device_util/device_util.dart'; | ||
| 1 | import 'package:flutter/services.dart'; | 4 | import 'package:flutter/services.dart'; |
| 2 | import 'package:flutter_test/flutter_test.dart'; | 5 | import 'package:flutter_test/flutter_test.dart'; |
| 3 | -import 'package:device_util/device_util.dart'; | ||
| 4 | 6 | ||
| 7 | +/// device_util 单元测试(MethodChannel mock 全量覆盖) | ||
| 8 | +/// | ||
| 9 | +/// 覆盖范围: | ||
| 10 | +/// - 信息获取:platformVersion / versionName / versionCode / getChannelInfo(含空值边界) | ||
| 11 | +/// - 页面跳转:openNetworkSettingPage / openApplicationSettingPage / | ||
| 12 | +/// openAppStoreCommentPage / minimizeWindow(不支持场景) | ||
| 13 | +/// - 进程控制:killApp | ||
| 14 | +/// - 异常场景:PlatformException 错误传播、MissingPluginException、参数边界、 | ||
| 15 | +/// 并发调用、原生不应答时的超时防护模式 | ||
| 16 | +/// | ||
| 17 | +/// 运行:flutter test;覆盖率:flutter test --coverage(生成 coverage/lcov.info) | ||
| 5 | void main() { | 18 | void main() { |
| 6 | const MethodChannel channel = MethodChannel('device_util'); | 19 | const MethodChannel channel = MethodChannel('device_util'); |
| 7 | 20 | ||
| 8 | TestWidgetsFlutterBinding.ensureInitialized(); | 21 | TestWidgetsFlutterBinding.ensureInitialized(); |
| 9 | 22 | ||
| 23 | + /// 按方法名配置 mock 返回值(未配置的方法返回 null,等价于原生 result.success(null)) | ||
| 24 | + Map<String, Object?> mockReturns = <String, Object?>{}; | ||
| 25 | + | ||
| 26 | + /// 可选的自定义 mock 行为(抛异常 / 记录调用 / 挂起等),优先于 mockReturns | ||
| 27 | + Future<Object?> Function(MethodCall call)? mockBehavior; | ||
| 28 | + | ||
| 10 | setUp(() { | 29 | setUp(() { |
| 11 | - channel.setMockMethodCallHandler((MethodCall methodCall) async { | 30 | + mockReturns = <String, Object?>{}; |
| 12 | - return '42'; | 31 | + mockBehavior = null; |
| 32 | + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger | ||
| 33 | + .setMockMethodCallHandler(channel, (MethodCall call) async { | ||
| 34 | + if (mockBehavior != null) { | ||
| 35 | + return mockBehavior!(call); | ||
| 36 | + } | ||
| 37 | + return mockReturns[call.method]; | ||
| 13 | }); | 38 | }); |
| 14 | }); | 39 | }); |
| 15 | 40 | ||
| 16 | tearDown(() { | 41 | tearDown(() { |
| 17 | - channel.setMockMethodCallHandler(null); | 42 | + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger |
| 43 | + .setMockMethodCallHandler(channel, null); | ||
| 18 | }); | 44 | }); |
| 19 | 45 | ||
| 20 | - test('getPlatformVersion', () async { | 46 | + group('信息获取(platformVersion / versionName / versionCode / getChannelInfo)', () { |
| 21 | - expect(await DeviceUtil.platformVersion, '42'); | 47 | + test('should return platform version string and invoke "getPlatformVersion"', () async { |
| 48 | + final List<MethodCall> calls = <MethodCall>[]; | ||
| 49 | + mockBehavior = (MethodCall call) async { | ||
| 50 | + calls.add(call); | ||
| 51 | + return 'HarmonyOS 5.1.0'; | ||
| 52 | + }; | ||
| 53 | + final String version = await DeviceUtil.platformVersion; | ||
| 54 | + expect(version, 'HarmonyOS 5.1.0'); | ||
| 55 | + expect(calls, hasLength(1)); | ||
| 56 | + expect(calls.first.method, 'getPlatformVersion'); | ||
| 57 | + }); | ||
| 58 | + | ||
| 59 | + test('should return application version name and invoke "getVersionName"', () async { | ||
| 60 | + mockReturns['getVersionName'] = '1.0.7'; | ||
| 61 | + expect(await DeviceUtil.versionName, '1.0.7'); | ||
| 62 | + }); | ||
| 63 | + | ||
| 64 | + test('should return empty string when native replies empty versionName ' | ||
| 65 | + '(boundary, aligned with Android "" fallback)', () async { | ||
| 66 | + mockReturns['getVersionName'] = ''; | ||
| 67 | + expect(await DeviceUtil.versionName, ''); | ||
| 68 | + }); | ||
| 69 | + | ||
| 70 | + test('should return application version code as string and invoke "getVersionCode"', () async { | ||
| 71 | + mockReturns['getVersionCode'] = '107'; | ||
| 72 | + expect(await DeviceUtil.versionCode, '107'); | ||
| 73 | + }); | ||
| 74 | + | ||
| 75 | + test('should return empty string when native replies empty versionCode (boundary)', () async { | ||
| 76 | + mockReturns['getVersionCode'] = ''; | ||
| 77 | + expect(await DeviceUtil.versionCode, ''); | ||
| 78 | + }); | ||
| 79 | + | ||
| 80 | + test('should return channel info map with exactly first/current install channel keys', () async { | ||
| 81 | + mockReturns['getChannelInfo'] = <String, Object?>{ | ||
| 82 | + 'first_install_channel': 'Huawei Store For Harmony', | ||
| 83 | + 'current_install_channel': 'Huawei Store For Harmony', | ||
| 84 | + }; | ||
| 85 | + final Map<String, String> channelInfo = await DeviceUtil.getChannelInfo; | ||
| 86 | + expect(channelInfo.length, 2); | ||
| 87 | + expect(channelInfo['first_install_channel'], 'Huawei Store For Harmony'); | ||
| 88 | + expect(channelInfo['current_install_channel'], 'Huawei Store For Harmony'); | ||
| 89 | + }); | ||
| 90 | + | ||
| 91 | + test('should map getChannelInfo result to Map<String, String>', () async { | ||
| 92 | + mockReturns['getChannelInfo'] = <String, Object?>{ | ||
| 93 | + 'first_install_channel': 'huawei', | ||
| 94 | + 'current_install_channel': 'huawei', | ||
| 95 | + }; | ||
| 96 | + final Map<String, String> channelInfo = await DeviceUtil.getChannelInfo; | ||
| 97 | + expect(channelInfo, isA<Map<String, String>>()); | ||
| 98 | + expect(channelInfo.values.first, 'huawei'); | ||
| 99 | + }); | ||
| 100 | + }); | ||
| 101 | + | ||
| 102 | + group('页面跳转(openNetworkSettingPage / openApplicationSettingPage / ' | ||
| 103 | + 'openAppStoreCommentPage / minimizeWindow)', () { | ||
| 104 | + test('should complete openNetworkSettingPage future when native replies null ' | ||
| 105 | + '(result callback contract, aligned with iOS result(nil))', () async { | ||
| 106 | + mockReturns['launchNoNetwork'] = null; | ||
| 107 | + await DeviceUtil.openNetworkSettingPage(); | ||
| 108 | + }); | ||
| 109 | + | ||
| 110 | + test('should invoke "launchNoNetwork" on the channel', () async { | ||
| 111 | + final List<MethodCall> calls = <MethodCall>[]; | ||
| 112 | + mockBehavior = (MethodCall call) async { | ||
| 113 | + calls.add(call); | ||
| 114 | + return null; | ||
| 115 | + }; | ||
| 116 | + await DeviceUtil.openNetworkSettingPage(); | ||
| 117 | + expect(calls.single.method, 'launchNoNetwork'); | ||
| 118 | + }); | ||
| 119 | + | ||
| 120 | + test('should complete openApplicationSettingPage future when native replies null', () async { | ||
| 121 | + mockReturns['systemSettingPage'] = null; | ||
| 122 | + await DeviceUtil.openApplicationSettingPage(); | ||
| 123 | + }); | ||
| 124 | + | ||
| 125 | + test('should pass appId argument when opening app store comment page', () async { | ||
| 126 | + final List<MethodCall> calls = <MethodCall>[]; | ||
| 127 | + mockBehavior = (MethodCall call) async { | ||
| 128 | + calls.add(call); | ||
| 129 | + return null; | ||
| 130 | + }; | ||
| 131 | + DeviceUtil.openAppStoreCommentPage('com.example.app'); | ||
| 132 | + await Future<void>.delayed(Duration.zero); | ||
| 133 | + await Future<void>.delayed(Duration.zero); | ||
| 134 | + expect(calls, hasLength(1)); | ||
| 135 | + expect(calls.first.method, 'openAppStoreComment'); | ||
| 136 | + expect(calls.first.arguments, <String, Object?>{'appId': 'com.example.app'}); | ||
| 137 | + }); | ||
| 138 | + | ||
| 139 | + test('should pass empty appID through as-is without local validation ' | ||
| 140 | + '(boundary: null is rejected by the String type at compile time)', () async { | ||
| 141 | + final List<MethodCall> calls = <MethodCall>[]; | ||
| 142 | + mockBehavior = (MethodCall call) async { | ||
| 143 | + calls.add(call); | ||
| 144 | + return null; | ||
| 145 | + }; | ||
| 146 | + DeviceUtil.openAppStoreCommentPage(''); | ||
| 147 | + await Future<void>.delayed(Duration.zero); | ||
| 148 | + await Future<void>.delayed(Duration.zero); | ||
| 149 | + expect(calls.single.arguments, <String, Object?>{'appId': ''}); | ||
| 150 | + }); | ||
| 151 | + | ||
| 152 | + test('should throw MissingPluginException when minimizeWindow is not implemented ' | ||
| 153 | + '(ohos does not support minimizeWindow, same as Android/iOS)', () async { | ||
| 154 | + // 移除 mock 处理器,模拟原生端 result.notImplemented() | ||
| 155 | + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger | ||
| 156 | + .setMockMethodCallHandler(channel, null); | ||
| 157 | + await expectLater( | ||
| 158 | + DeviceUtil.minimizeWindow(), | ||
| 159 | + throwsA(isA<MissingPluginException>()), | ||
| 160 | + ); | ||
| 161 | + }); | ||
| 162 | + }); | ||
| 163 | + | ||
| 164 | + group('进程控制(killApp)', () { | ||
| 165 | + test('should complete killApp future when native acknowledges before exiting', () async { | ||
| 166 | + mockReturns['killApp'] = null; | ||
| 167 | + await DeviceUtil.killApp(); | ||
| 168 | + }); | ||
| 169 | + }); | ||
| 170 | + | ||
| 171 | + group('异常场景(错误传播 / 并发 / 超时)', () { | ||
| 172 | + test('should propagate PlatformException thrown by native side (status error)', () async { | ||
| 173 | + mockBehavior = (MethodCall call) async { | ||
| 174 | + throw PlatformException(code: 'DEVICE_UTIL_ERROR', message: 'invoke failed'); | ||
| 175 | + }; | ||
| 176 | + await expectLater( | ||
| 177 | + DeviceUtil.versionName, | ||
| 178 | + throwsA( | ||
| 179 | + isA<PlatformException>() | ||
| 180 | + .having((PlatformException e) => e.code, 'code', 'DEVICE_UTIL_ERROR'), | ||
| 181 | + ), | ||
| 182 | + ); | ||
| 183 | + }); | ||
| 184 | + | ||
| 185 | + test('should propagate PlatformException for openAppStoreCommentPage ' | ||
| 186 | + '(market jump failure, MARKET_ERROR)', () async { | ||
| 187 | + mockBehavior = (MethodCall call) async { | ||
| 188 | + throw PlatformException(code: 'MARKET_ERROR', message: 'load product failed'); | ||
| 189 | + }; | ||
| 190 | + // Dart 层为 async void,异常经 zone 错误处理器捕获验证(调用本身不抛出) | ||
| 191 | + Object? zoneError; | ||
| 192 | + await runZonedGuarded(() async { | ||
| 193 | + DeviceUtil.openAppStoreCommentPage('com.example.app'); | ||
| 194 | + await Future<void>.delayed(const Duration(milliseconds: 10)); | ||
| 195 | + }, (Object error, StackTrace stack) { | ||
| 196 | + zoneError = error; | ||
| 197 | + }); | ||
| 198 | + expect(zoneError, isA<PlatformException>()); | ||
| 199 | + }); | ||
| 200 | + | ||
| 201 | + test('should throw MissingPluginException when no handler is registered ' | ||
| 202 | + '(unregistered channel / plugin not attached)', () async { | ||
| 203 | + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger | ||
| 204 | + .setMockMethodCallHandler(channel, null); | ||
| 205 | + await expectLater( | ||
| 206 | + DeviceUtil.platformVersion, | ||
| 207 | + throwsA(isA<MissingPluginException>()), | ||
| 208 | + ); | ||
| 209 | + }); | ||
| 210 | + | ||
| 211 | + test('should support concurrent channel invocations without interference', () async { | ||
| 212 | + mockReturns['getPlatformVersion'] = 'HarmonyOS 5.1.0'; | ||
| 213 | + mockReturns['getVersionName'] = '1.0.7'; | ||
| 214 | + mockReturns['getVersionCode'] = '107'; | ||
| 215 | + final List<String> results = await Future.wait(<Future<String>>[ | ||
| 216 | + DeviceUtil.platformVersion, | ||
| 217 | + DeviceUtil.versionName, | ||
| 218 | + DeviceUtil.versionCode, | ||
| 219 | + ]); | ||
| 220 | + expect(results, <String>['HarmonyOS 5.1.0', '1.0.7', '107']); | ||
| 221 | + }); | ||
| 222 | + | ||
| 223 | + test('should surface timeout when native never replies ' | ||
| 224 | + '(recommended guard pattern for fire-and-forget native paths)', () async { | ||
| 225 | + mockBehavior = (MethodCall call) async { | ||
| 226 | + // 模拟原生侧不应答(如进程在回执前退出) | ||
| 227 | + await Completer<Object?>().future; | ||
| 228 | + return null; | ||
| 229 | + }; | ||
| 230 | + await expectLater( | ||
| 231 | + DeviceUtil.platformVersion.timeout(const Duration(milliseconds: 100)), | ||
| 232 | + throwsA(isA<TimeoutException>()), | ||
| 233 | + ); | ||
| 234 | + }); | ||
| 22 | }); | 235 | }); |
| 23 | } | 236 | } |