空气质量检测 - 鸿蒙KMP跨端方案

目录
- 概述
- 功能设计
- Kotlin 实现代码(KMP)
- JavaScript 调用示例
- ArkTS 页面集成与调用
- 数据输入与交互体验
- 编译与自动复制流程
- 总结
概述
本案例在 Kotlin Multiplatform (KMP) 工程中实现了一个 环境工具 - 空气质量检测工具:
- 输入:用户的空气质量检测数据(PM2.5、PM10、NO2、O3、SO2),使用空格分隔,例如:
35 25 45 120 8。 - 输出:
- 污染物浓度分析:各污染物的浓度和AQI指数
- 空气质量评估:综合AQI、空气质量等级、主要污染物
- 健康风险评估:根据空气质量评估的健康风险
- 防护建议:针对空气污染的具体防护方案
- 详细分析:污染物的医学解释和健康指导
- 技术路径:Kotlin → Kotlin/JS → JavaScript 模块 → ArkTS 页面调用。
这个案例展示了 KMP 跨端开发在环境监测领域的应用:
把空气质量检测逻辑写在 Kotlin 里,一次实现,多端复用;把检测界面写在 ArkTS 里,专注 UI 和体验。
Kotlin 侧负责解析空气质量数据、计算AQI指数、评估健康风险和生成个性化建议;ArkTS 侧只需要把输入字符串传给 Kotlin 函数,并把返回结果原样展示出来即可。借助 KMP 的 Kotlin/JS 能力,这个空气质量检测工具可以在 Node.js、Web 前端以及 OpenHarmony 中复用相同的代码逻辑。
功能设计
输入数据格式
空气质量检测工具采用简单直观的输入格式:
- 使用 空格分隔 各个参数。
- 第一个参数是 PM2.5(整数或浮点数,单位:μg/m³)。
- 第二个参数是 PM10(整数或浮点数,单位:μg/m³)。
- 第三个参数是 NO2(整数或浮点数,单位:μg/m³)。
- 第四个参数是 O3(整数或浮点数,单位:μg/m³)。
- 第五个参数是 SO2(整数或浮点数,单位:μg/m³)。
- 输入示例:
35 25 45 120 8
这可以理解为:
- PM2.5:35 μg/m³
- PM10:25 μg/m³
- NO2:45 μg/m³
- O3:120 μg/m³
- SO2:8 μg/m³
工具会基于这些数据计算出:
- 各污染物的AQI指数
- 综合AQI指数
- 空气质量等级:优秀/良好/轻度污染/中度污染/重度污染/严重污染
- 主要污染物识别
- 健康风险评估
- 防护建议
输出信息结构
为了便于在 ArkTS 页面以及终端中直接展示,Kotlin 函数返回的是一段结构化的多行文本,划分为几个分区:
- 标题区:例如"🌍 空气质量检测与健康评估",一眼看出工具用途。
- 污染物浓度:各污染物的浓度和AQI指数。
- 空气质量评估:综合AQI、空气质量等级、主要污染物。
- 健康分析:健康风险评估、相关疾病风险。
- 防护建议:针对空气污染的具体防护方案。
- 参考标准:AQI分类标准、污染物标准参考。
这样的输出结构使得:
- 在 ArkTS 中可以直接把整段文本绑定到
Text组件,配合monospace字体,阅读体验类似终端报告。 - 如果将来想把结果保存到日志或者后端,直接保存字符串即可。
- 需要更精细的 UI 时,也可以在前端根据分隔符进行拆分,再按块展示。
Kotlin 实现代码(KMP)
核心代码在 src/jsMain/kotlin/App.kt 中,通过 @JsExport 导出。以下是完整的 Kotlin 实现:
@OptIn(ExperimentalJsExport::class)
@JsExport
fun airQualityAnalyzer(inputData: String = "35 25 45 120 8"): String {
// 输入格式: PM2.5 PM10 NO2 O3 SO2 (单位: μg/m³)
val parts = inputData.trim().split(" ").filter { it.isNotEmpty() }
if (parts.size < 5) {
return "❌ 错误: 请输入完整的信息,格式: PM2.5 PM10 NO2 O3 SO2\n例如: 35 25 45 120 8"
}
val pm25 = parts[0].toDoubleOrNull() ?: return "❌ 错误: PM2.5 必须是数字"
val pm10 = parts[1].toDoubleOrNull() ?: return "❌ 错误: PM10 必须是数字"
val no2 = parts[2].toDoubleOrNull() ?: return "❌ 错误: NO2 必须是数字"
val o3 = parts[3].toDoubleOrNull() ?: return "❌ 错误: O3 必须是数字"
val so2 = parts[4].toDoubleOrNull() ?: return "❌ 错误: SO2 必须是数字"
if (pm25 < 0 || pm25 > 1000) {
return "❌ 错误: PM2.5 必须在 0-1000 μg/m³ 之间"
}
if (pm10 < 0 || pm10 > 1000) {
return "❌ 错误: PM10 必须在 0-1000 μg/m³ 之间"
}
if (no2 < 0 || no2 > 500) {
return "❌ 错误: NO2 必须在 0-500 μg/m³ 之间"
}
if (o3 < 0 || o3 > 500) {
return "❌ 错误: O3 必须在 0-500 μg/m³ 之间"
}
if (so2 < 0 || so2 > 500) {
return "❌ 错误: SO2 必须在 0-500 μg/m³ 之间"
}
// 计算各污染物的 AQI 指数
fun calculateAQI(concentration: Double, pollutantType: String): Int {
return when (pollutantType) {
"PM2.5" -> when {
concentration <= 35 -> ((concentration / 35) * 50).toInt()
concentration <= 75 -> (50 + ((concentration - 35) / 40) * 50).toInt()
concentration <= 115 -> (100 + ((concentration - 75) / 40) * 50).toInt()
concentration <= 150 -> (150 + ((concentration - 115) / 35) * 50).toInt()
concentration <= 250 -> (200 + ((concentration - 150) / 100) * 50).toInt()
else -> (250 + ((concentration - 250) / 750) * 50).toInt()
}
"PM10" -> when {
concentration <= 50 -> ((concentration / 50) * 50).toInt()
concentration <= 150 -> (50 + ((concentration - 50) / 100) * 50).toInt()
concentration <= 250 -> (100 + ((concentration - 150) / 100) * 50).toInt()
concentration <= 350 -> (150 + ((concentration - 250) / 100) * 50).toInt()
concentration <= 420 -> (200 + ((concentration - 350) / 70) * 50).toInt()
else -> (250 + ((concentration - 420) / 580) * 50).toInt()
}
"NO2" -> when {
concentration <= 40 -> ((concentration / 40) * 50).toInt()
concentration <= 80 -> (50 + ((concentration - 40) / 40) * 50).toInt()
concentration <= 180 -> (100 + ((concentration - 80) / 100) * 50).toInt()
concentration <= 280 -> (150 + ((concentration - 180) / 100) * 50).toInt()
concentration <= 565 -> (200 + ((concentration - 280) / 285) * 50).toInt()
else -> (250 + ((concentration - 565) / 435) * 50).toInt()
}
"O3" -> when {
concentration <= 100 -> ((concentration / 100) * 50).toInt()
concentration <= 160 -> (50 + ((concentration - 100) / 60) * 50).toInt()
concentration <= 215 -> (100 + ((concentration - 160) / 55) * 50).toInt()
concentration <= 265 -> (150 + ((concentration - 215) / 50) * 50).toInt()
concentration <= 800 -> (200 + ((concentration - 265) / 535) * 50).toInt()
else -> (250 + ((concentration - 800) / 200) * 50).toInt()
}
"SO2" -> when {
concentration <= 50 -> ((concentration / 50) * 50).toInt()
concentration <= 100 -> (50 + ((concentration - 50) / 50) * 50).toInt()
concentration <= 350 -> (100 + ((concentration - 100) / 250) * 50).toInt()
concentration <= 500 -> (150 + ((concentration - 350) / 150) * 50).toInt()
concentration <= 750 -> (200 + ((concentration - 500) / 250) * 50).toInt()
else -> (250 + ((concentration - 750) / 250) * 50).toInt()
}
else -> 0
}
}
val aqi_pm25 = calculateAQI(pm25, "PM2.5")
val aqi_pm10 = calculateAQI(pm10, "PM10")
val aqi_no2 = calculateAQI(no2, "NO2")
val aqi_o3 = calculateAQI(o3, "O3")
val aqi_so2 = calculateAQI(so2, "SO2")
// 综合 AQI 为各污染物 AQI 的最大值
val overallAQI = maxOf(aqi_pm25, aqi_pm10, aqi_no2, aqi_o3, aqi_so2)
// 判断空气质量等级
val airQuality = when {
overallAQI <= 50 -> "优秀"
overallAQI <= 100 -> "良好"
overallAQI <= 150 -> "轻度污染"
overallAQI <= 200 -> "中度污染"
overallAQI <= 300 -> "重度污染"
else -> "严重污染"
}
// 识别主要污染物
val mainPollutant = when (overallAQI) {
aqi_pm25 -> "PM2.5"
aqi_pm10 -> "PM10"
aqi_no2 -> "NO2"
aqi_o3 -> "O3"
aqi_so2 -> "SO2"
else -> "未知"
}
// 健康风险评估
val healthRisk = when {
overallAQI <= 50 -> "无健康风险"
overallAQI <= 100 -> "敏感人群可能受影响"
overallAQI <= 150 -> "敏感人群健康受影响,一般人群可能受影响"
overallAQI <= 200 -> "一般人群健康受影响,敏感人群严重受影响"
overallAQI <= 300 -> "全民健康受影响"
else -> "严重危害全民健康"
}
// 相关疾病风险
val diseaseRisk = when {
overallAQI <= 50 -> "无明显风险"
overallAQI <= 100 -> "呼吸道疾病风险轻微增加"
overallAQI <= 150 -> "呼吸道疾病、心脏病风险增加"
overallAQI <= 200 -> "呼吸道疾病、心脏病、肺病风险明显增加"
overallAQI <= 300 -> "呼吸道疾病、心脏病、肺病、脑卒中风险显著增加"
else -> "多种疾病风险极高"
}
// 生成建议
val suggestions = when {
overallAQI <= 50 -> "✨ 空气质量优秀!可以正常进行户外活动。"
overallAQI <= 100 -> "👍 空气质量良好。敏感人群应减少户外活动。"
overallAQI <= 150 -> "⚠️ 空气质量轻度污染。敏感人群应避免户外活动,一般人群应减少户外活动。"
overallAQI <= 200 -> "🔴 空气质量中度污染。一般人群应减少户外活动,敏感人群应避免户外活动。"
overallAQI <= 300 -> "🚨 空气质量重度污染。所有人群应避免户外活动。"
else -> "🆘 空气质量严重污染。所有人群应留在室内,关闭门窗。"
}
// 防护建议
val protectionAdvice = when {
overallAQI <= 50 -> "无需特殊防护措施"
overallAQI <= 100 -> "敏感人群应佩戴 N95 口罩,避免剧烈运动"
overallAQI <= 150 -> "所有人群应佩戴 N95 口罩,避免户外活动"
overallAQI <= 200 -> "所有人群应佩戴 N95 口罩,避免户外活动,使用空气净化器"
overallAQI <= 300 -> "所有人群应佩戴 N95 口罩,避免户外活动,使用空气净化器,关闭门窗"
else -> "所有人群应佩戴 N95 口罩,避免户外活动,使用空气净化器,关闭门窗,减少外出"
}
// 构建输出文本
val result = StringBuilder()
result.append("🌍 空气质量检测与健康评估\n")
result.append("═".repeat(60)).append("\n\n")
result.append("📊 污染物浓度\n")
result.append("─".repeat(60)).append("\n")
result.append("PM2.5: ${String.format("%.1f", pm25)} μg/m³ (AQI: ${aqi_pm25})\n")
result.append("PM10: ${String.format("%.1f", pm10)} μg/m³ (AQI: ${aqi_pm10})\n")
result.append("NO2: ${String.format("%.1f", no2)} μg/m³ (AQI: ${aqi_no2})\n")
result.append("O3: ${String.format("%.1f", o3)} μg/m³ (AQI: ${aqi_o3})\n")
result.append("SO2: ${String.format("%.1f", so2)} μg/m³ (AQI: ${aqi_so2})\n\n")
result.append("🏆 空气质量评估\n")
result.append("─".repeat(60)).append("\n")
result.append("综合 AQI: ${overallAQI}\n")
result.append("空气质量等级: ${airQuality}\n")
result.append("主要污染物: ${mainPollutant}\n\n")
result.append("⚕️ 健康分析\n")
result.append("─".repeat(60)).append("\n")
result.append("健康风险: ${healthRisk}\n")
result.append("相关疾病风险: ${diseaseRisk}\n\n")
result.append("💡 个性化建议\n")
result.append("─".repeat(60)).append("\n")
result.append("${suggestions}\n\n")
result.append("🛡️ 防护建议\n")
result.append("─".repeat(60)).append("\n")
result.append("${protectionAdvice}\n\n")
result.append("📈 AQI 等级标准\n")
result.append("─".repeat(60)).append("\n")
result.append("• 优秀: AQI 0-50\n")
result.append("• 良好: AQI 51-100\n")
result.append("• 轻度污染: AQI 101-150\n")
result.append("• 中度污染: AQI 151-200\n")
result.append("• 重度污染: AQI 201-300\n")
result.append("• 严重污染: AQI > 300\n\n")
result.append("🌱 污染物标准参考\n")
result.append("─".repeat(60)).append("\n")
result.append("• PM2.5 一级标准: ≤ 35 μg/m³\n")
result.append("• PM10 一级标准: ≤ 50 μg/m³\n")
result.append("• NO2 一级标准: ≤ 40 μg/m³\n")
result.append("• O3 一级标准: ≤ 100 μg/m³\n")
result.append("• SO2 一级标准: ≤ 50 μg/m³\n\n")
result.append("🎯 日常防护建议\n")
result.append("─".repeat(60)).append("\n")
result.append("1. 定期检查空气质量指数\n")
result.append("2. 根据 AQI 调整户外活动计划\n")
result.append("3. 敏感人群应随身携带口罩\n")
result.append("4. 在家使用空气净化器\n")
result.append("5. 定期更换空气净化器滤芯\n")
result.append("6. 避免在污染高峰期户外活动\n")
result.append("7. 进行户外运动时选择空气质量好的时间\n")
result.append("8. 保持室内通风,但在污染严重时关闭门窗\n")
result.append("9. 多喝水,增强身体抵抗力\n")
result.append("10. 如有呼吸不适,立即就医\n")
return result.toString()
}
代码说明
这段 Kotlin 代码实现了完整的空气质量检测分析和健康评估功能。让我详细解释关键部分:
数据验证:首先验证输入的五个污染物浓度是否有效,确保数据在合理范围内。每个污染物都有明确的范围限制。
AQI 计算:根据国际标准的 AQI 计算方法,将各污染物浓度转换为 AQI 指数。不同污染物有不同的转换标准,这些标准基于对人体健康的影响程度。
综合 AQI:取各污染物 AQI 的最大值作为综合 AQI,这反映了当前空气质量中最严重的污染物。
空气质量等级:根据综合 AQI 将空气质量分为六个等级,从优秀到严重污染。
主要污染物识别:识别出导致综合 AQI 最高的污染物,帮助用户了解当前最主要的污染源。
健康风险评估:根据 AQI 等级评估对不同人群的健康影响,包括敏感人群和一般人群。
防护建议:根据空气质量等级提供相应的防护措施,包括口罩选择、户外活动建议等。
JavaScript 调用示例
编译后的 JavaScript 代码可以在 Node.js 或浏览器中直接调用。以下是 JavaScript 的使用示例:
// 导入编译后的 Kotlin/JS 模块
const { airQualityAnalyzer } = require('./hellokjs.js');
// 示例 1:优秀空气质量
const result1 = airQualityAnalyzer("15 20 20 50 5");
console.log("示例 1 - 优秀空气质量:");
console.log(result1);
console.log("\n");
// 示例 2:良好空气质量
const result2 = airQualityAnalyzer("35 45 35 80 20");
console.log("示例 2 - 良好空气质量:");
console.log(result2);
console.log("\n");
// 示例 3:轻度污染
const result3 = airQualityAnalyzer("60 80 70 120 40");
console.log("示例 3 - 轻度污染:");
console.log(result3);
console.log("\n");
// 示例 4:中度污染
const result4 = airQualityAnalyzer("100 150 150 180 80");
console.log("示例 4 - 中度污染:");
console.log(result4);
console.log("\n");
// 示例 5:重度污染
const result5 = airQualityAnalyzer("200 250 250 300 150");
console.log("示例 5 - 重度污染:");
console.log(result5);
console.log("\n");
// 示例 6:使用默认参数
const result6 = airQualityAnalyzer();
console.log("示例 6 - 使用默认参数:");
console.log(result6);
// 实际应用场景:从用户输入获取数据
function analyzeUserAirQuality(userInput) {
try {
const result = airQualityAnalyzer(userInput);
return {
success: true,
data: result
};
} catch (error) {
return {
success: false,
error: error.message
};
}
}
// 测试实际应用
const userInput = "40 50 60 100 15";
const analysis = analyzeUserAirQuality(userInput);
if (analysis.success) {
console.log("用户空气质量分析结果:");
console.log(analysis.data);
} else {
console.log("分析失败:", analysis.error);
}
// 空气质量监测追踪应用示例
function trackAirQuality(readings) {
console.log("\n空气质量监测记录:");
console.log("═".repeat(60));
const results = readings.map((reading, index) => {
const analysis = airQualityAnalyzer(reading);
return {
day: index + 1,
reading,
analysis
};
});
results.forEach(result => {
console.log(`\n第 ${result.day} 天 (${result.reading}):`);
console.log(result.analysis);
});
return results;
}
// 测试空气质量监测追踪
const readings = [
"15 20 20 50 5",
"35 45 35 80 20",
"60 80 70 120 40",
"100 150 150 180 80",
"200 250 250 300 150"
];
trackAirQuality(readings);
// 空气质量趋势分析
function analyzeAirTrend(readings) {
const analyses = readings.map(reading => {
const parts = reading.split(' ').map(Number);
return {
pm25: parts[0],
pm10: parts[1],
no2: parts[2],
o3: parts[3],
so2: parts[4]
};
});
const avgPm25 = analyses.reduce((sum, a) => sum + a.pm25, 0) / analyses.length;
const avgPm10 = analyses.reduce((sum, a) => sum + a.pm10, 0) / analyses.length;
const avgNo2 = analyses.reduce((sum, a) => sum + a.no2, 0) / analyses.length;
const avgO3 = analyses.reduce((sum, a) => sum + a.o3, 0) / analyses.length;
const avgSo2 = analyses.reduce((sum, a) => sum + a.so2, 0) / analyses.length;
console.log("\n空气质量趋势分析:");
console.log(`平均 PM2.5: ${avgPm25.toFixed(1)} μg/m³`);
console.log(`平均 PM10: ${avgPm10.toFixed(1)} μg/m³`);
console.log(`平均 NO2: ${avgNo2.toFixed(1)} μg/m³`);
console.log(`平均 O3: ${avgO3.toFixed(1)} μg/m³`);
console.log(`平均 SO2: ${avgSo2.toFixed(1)} μg/m³`);
}
analyzeAirTrend(readings);
JavaScript 代码说明
这段 JavaScript 代码展示了如何在 Node.js 环境中调用编译后的 Kotlin 函数。关键点包括:
模块导入:使用 require 导入编译后的 JavaScript 模块,获取导出的 airQualityAnalyzer 函数。
多个示例:展示了不同空气质量等级(优秀、良好、轻度污染、中度污染、重度污染)的调用方式。
错误处理:在实际应用中,使用 try-catch 块来处理可能的错误,确保程序的稳定性。
空气质量监测追踪:trackAirQuality 函数展示了如何处理多天的空气质量监测记录,这在实际的环保监测应用中很常见。
趋势分析:analyzeAirTrend 函数演示了如何进行空气质量的长期趋势分析,计算各污染物的平均值。
ArkTS 页面集成与调用
在 OpenHarmony 的 ArkTS 页面中集成这个空气质量检测工具。以下是完整的 ArkTS 实现代码:
import { airQualityAnalyzer } from './hellokjs';
@Entry
@Component
struct AirQualityAnalyzerPage {
@State pm25: string = "35";
@State pm10: string = "25";
@State no2: string = "45";
@State o3: string = "120";
@State so2: string = "8";
@State analysisResult: string = "";
@State isLoading: boolean = false;
build() {
Column() {
// 顶部栏
Row() {
Text("🌍 空气质量检测")
.fontSize(24)
.fontWeight(FontWeight.Bold)
.fontColor(Color.White)
}
.width("100%")
.height(60)
.backgroundColor("#4E342E")
.justifyContent(FlexAlign.Center)
.padding({ top: 10, bottom: 10 })
// 主容器
Scroll() {
Column() {
// PM2.5 输入
Text("PM2.5 (μg/m³)")
.fontSize(14)
.fontColor("#333333")
.margin({ top: 20, left: 15 })
TextInput({
placeholder: "例如: 35",
text: this.pm25
})
.width("90%")
.height(45)
.margin({ top: 8, bottom: 15, left: 15, right: 15 })
.padding({ left: 10, right: 10 })
.backgroundColor("#D7CCC8")
.border({ width: 1, color: "#4E342E" })
.onChange((value: string) => {
this.pm25 = value;
})
// PM10 输入
Text("PM10 (μg/m³)")
.fontSize(14)
.fontColor("#333333")
.margin({ left: 15 })
TextInput({
placeholder: "例如: 25",
text: this.pm10
})
.width("90%")
.height(45)
.margin({ top: 8, bottom: 15, left: 15, right: 15 })
.padding({ left: 10, right: 10 })
.backgroundColor("#D7CCC8")
.border({ width: 1, color: "#4E342E" })
.onChange((value: string) => {
this.pm10 = value;
})
// NO2 输入
Text("NO2 (μg/m³)")
.fontSize(14)
.fontColor("#333333")
.margin({ left: 15 })
TextInput({
placeholder: "例如: 45",
text: this.no2
})
.width("90%")
.height(45)
.margin({ top: 8, bottom: 15, left: 15, right: 15 })
.padding({ left: 10, right: 10 })
.backgroundColor("#D7CCC8")
.border({ width: 1, color: "#4E342E" })
.onChange((value: string) => {
this.no2 = value;
})
// O3 输入
Text("O3 (μg/m³)")
.fontSize(14)
.fontColor("#333333")
.margin({ left: 15 })
TextInput({
placeholder: "例如: 120",
text: this.o3
})
.width("90%")
.height(45)
.margin({ top: 8, bottom: 15, left: 15, right: 15 })
.padding({ left: 10, right: 10 })
.backgroundColor("#D7CCC8")
.border({ width: 1, color: "#4E342E" })
.onChange((value: string) => {
this.o3 = value;
})
// SO2 输入
Text("SO2 (μg/m³)")
.fontSize(14)
.fontColor("#333333")
.margin({ left: 15 })
TextInput({
placeholder: "例如: 8",
text: this.so2
})
.width("90%")
.height(45)
.margin({ top: 8, bottom: 15, left: 15, right: 15 })
.padding({ left: 10, right: 10 })
.backgroundColor("#D7CCC8")
.border({ width: 1, color: "#4E342E" })
.onChange((value: string) => {
this.so2 = value;
})
// 按钮区域
Row() {
Button("📊 检测分析")
.width("45%")
.height(45)
.backgroundColor("#4E342E")
.fontColor(Color.White)
.fontSize(16)
.fontWeight(FontWeight.Bold)
.onClick(() => {
this.isLoading = true;
setTimeout(() => {
const input = `${this.pm25} ${this.pm10} ${this.no2} ${this.o3} ${this.so2}`;
this.analysisResult = airQualityAnalyzer(input);
this.isLoading = false;
}, 300);
})
Blank()
Button("🔄 重置")
.width("45%")
.height(45)
.backgroundColor("#2196F3")
.fontColor(Color.White)
.fontSize(16)
.fontWeight(FontWeight.Bold)
.onClick(() => {
this.pm25 = "35";
this.pm10 = "25";
this.no2 = "45";
this.o3 = "120";
this.so2 = "8";
this.analysisResult = "";
this.isLoading = false;
})
}
.width("90%")
.margin({ top: 10, bottom: 20, left: 15, right: 15 })
.justifyContent(FlexAlign.SpaceBetween)
// 加载指示器
if (this.isLoading) {
Row() {
LoadingProgress()
.width(40)
.height(40)
.color("#4E342E")
Text(" 正在检测中...")
.fontSize(14)
.fontColor("#666666")
}
.width("90%")
.height(50)
.margin({ bottom: 15, left: 15, right: 15 })
.justifyContent(FlexAlign.Center)
.backgroundColor("#D7CCC8")
.borderRadius(8)
}
// 结果显示区域
if (this.analysisResult.length > 0) {
Column() {
Text("📈 检测结果")
.fontSize(16)
.fontWeight(FontWeight.Bold)
.fontColor("#4E342E")
.margin({ bottom: 10 })
Text(this.analysisResult)
.width("100%")
.fontSize(12)
.fontFamily("monospace")
.fontColor("#333333")
.lineHeight(1.6)
.padding(10)
.backgroundColor("#FAFAFA")
.border({ width: 1, color: "#E0E0E0" })
.borderRadius(8)
}
.width("90%")
.margin({ top: 20, bottom: 30, left: 15, right: 15 })
.padding(15)
.backgroundColor("#D7CCC8")
.borderRadius(8)
.border({ width: 1, color: "#4E342E" })
}
}
.width("100%")
}
.layoutWeight(1)
.backgroundColor("#FFFFFF")
}
.width("100%")
.height("100%")
.backgroundColor("#F5F5F5")
}
}
ArkTS 代码说明
这段 ArkTS 代码实现了完整的用户界面和交互逻辑。关键点包括:
导入函数:从编译后的 JavaScript 模块中导入 airQualityAnalyzer 函数。
状态管理:使用 @State 装饰器管理七个状态:五个污染物浓度、分析结果和加载状态。
UI 布局:包含顶部栏、五个污染物输入框、检测和重置按钮、加载指示器和结果显示区域。
交互逻辑:用户输入五个污染物浓度后,点击检测按钮。应用会调用 Kotlin 函数进行分析,显示加载动画,最后展示详细的检测结果。
样式设计:使用棕色主题,与环保和自然相关的主题相符。所有输入框、按钮和结果显示区域都有相应的样式设置,提供清晰的视觉层次。
数据输入与交互体验
输入数据格式规范
为了确保工具能够正确处理用户输入,用户应该遵循以下规范:
- PM2.5:整数或浮点数,单位 μg/m³,范围 0-1000。
- PM10:整数或浮点数,单位 μg/m³,范围 0-1000。
- NO2:整数或浮点数,单位 μg/m³,范围 0-500。
- O3:整数或浮点数,单位 μg/m³,范围 0-500。
- SO2:整数或浮点数,单位 μg/m³,范围 0-500。
- 分隔符:使用空格分隔各个参数。
示例输入
- 优秀空气质量:
15 20 20 50 5 - 良好空气质量:
35 45 35 80 20 - 轻度污染:
60 80 70 120 40 - 中度污染:
100 150 150 180 80 - 重度污染:
200 250 250 300 150
交互流程
- 用户打开应用,看到输入框和默认数据
- 用户输入五个污染物浓度
- 点击"检测分析"按钮,应用调用 Kotlin 函数进行分析
- 应用显示加载动画,表示正在处理
- 分析完成后,显示详细的检测结果,包括污染物浓度、AQI指数、空气质量等级、健康风险、防护建议等
- 用户可以点击"重置"按钮清空数据,重新开始
编译与自动复制流程
编译步骤
-
编译 Kotlin 代码:
./gradlew build -
生成 JavaScript 文件:
编译过程会自动生成hellokjs.d.ts和hellokjs.js文件。 -
复制到 ArkTS 项目:
使用提供的脚本自动复制生成的文件到 ArkTS 项目的 pages 目录:./build-and-copy.bat
文件结构
编译完成后,项目结构如下:
kmp_openharmony/
├── src/
│ └── jsMain/
│ └── kotlin/
│ └── App.kt (包含 airQualityAnalyzer 函数)
├── build/
│ └── js/
│ └── packages/
│ └── hellokjs/
│ ├── hellokjs.d.ts
│ └── hellokjs.js
└── kmp_ceshiapp/
└── entry/
└── src/
└── main/
└── ets/
└── pages/
├── hellokjs.d.ts (复制后)
├── hellokjs.js (复制后)
└── Index.ets (ArkTS 页面)
总结
这个案例展示了如何使用 Kotlin Multiplatform 技术实现一个跨端的环境工具 - 空气质量检测工具。通过将核心逻辑写在 Kotlin 中,然后编译为 JavaScript,最后在 ArkTS 中调用,我们实现了代码的一次编写、多端复用。
核心优势
- 代码复用:Kotlin 代码可以在 JVM、JavaScript 和其他平台上运行,避免重复开发。
- 类型安全:Kotlin 的类型系统确保了代码的安全性和可维护性。
- 性能优化:Kotlin 编译为 JavaScript 后,性能与手写 JavaScript 相当。
- 易于维护:集中管理业务逻辑,使得维护和更新变得更加容易。
- 用户体验:通过 ArkTS 提供的丰富 UI 组件,可以创建美观、易用的用户界面。
扩展方向
- 数据持久化:将用户的空气质量检测记录保存到本地存储或云端。
- 数据可视化:使用图表库展示空气质量指数的变化趋势。
- 多点监测:支持多个地点的空气质量监测和对比。
- 智能预警:根据空气质量数据提供自动预警和建议。
- 社交功能:允许用户分享空气质量信息和相互提醒。
- 集成第三方 API:连接专业空气质量监测设备和数据库。
- AI 分析:使用机器学习进行空气质量异常检测和预测。
- 环保协作:与环保部门协作,上报空气质量数据进行监管。
通过这个案例,开发者可以学到如何在 KMP 项目中实现复杂的环境监测计算逻辑,以及如何在 OpenHarmony 平台上构建高效的跨端应用。这个空气质量检测工具可以作为环保监测应用、城市空气质量管理系统或个人健康防护应用的核心模块。
欢迎加入开源鸿蒙跨平台社区:https://openharmonycrossplatform.csdn.net
AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐


所有评论(0)