在这里插入图片描述

📌 模块概述

智能洞察页面在统计数据和行为记录的基础上,为用户生成一系列「提示卡片」,例如「您还没有收藏任何菜谱,建议为常做菜添加收藏标记」「您的平均烹饪时间偏长,可以尝试快手菜」等。这些洞察完全由 Web 层根据当前数据计算得出,无需复杂算法即可提供实用建议;若要进一步优化,可以在 ArkTS 层接入更高级的推荐或机器学习模型。

🔗 洞察生成流程

  1. renderInsights() 从数据库读取所有菜谱和收藏列表;
  2. 根据菜谱数量、收藏数量、平均烹饪时间等条件构造一组洞察对象;
  3. 每个洞察对象包含类型(成功、警告、信息等)、标题与描述;
  4. 页面根据洞察数组渲染一组提示卡片;
  5. 如需更复杂的洞察逻辑,可以在 ArkTS 层进行模型推理,并将结果回传给 Web 层展示。

🔧 洞察卡片结构(HTML 片段)

<div class="alert alert-info">
  <div class="alert-icon"></div>
  <div class="alert-content">
    <div class="alert-title">开始创建菜谱</div>
    <div class="alert-message">您还没有创建任何菜谱,点击“添加菜谱”开始吧!</div>
  </div>
</div>

这段 HTML 片段展示了信息类型洞察卡片的样式,包含图标、标题和详细说明。通过不同的 alert-* 样式可以区分成功、警告、信息等不同级别。

🔧 Web 层生成洞察逻辑(JavaScript 片段)

async function renderInsights() {
  const recipes = await db.getAllRecipes();
  const favorites = recipes.filter(r => r.isFavorite);
  const insights = [];

  if (recipes.length === 0) {
    insights.push({
      type: 'info',
      title: '开始创建菜谱',
      description: '您还没有创建任何菜谱,点击“添加菜谱”开始吧!'
    });
  }

  if (recipes.length > 0 && favorites.length === 0) {
    insights.push({
      type: 'warning',
      title: '收藏您喜欢的菜谱',
      description: '为常做菜添加收藏标记,方便快速找到。'
    });
  }

  // 省略渲染 HTML 的部分
}

这段代码展示了一些简单但实用的规则:当菜谱数为 0 时提示用户开始创建,当存在菜谱但收藏为空时提醒使用收藏功能。通过增加更多规则,可以逐步丰富洞察内容。

🔌 在鸿蒙原生层执行高级分析(ArkTS 片段)

// entry/src/main/ets/plugins/InsightPlugin.ets
import plugin from '@ohos.plugin';

export interface NativeInsight {
  type: string;
  title: string;
  description: string;
}

@plugin
export default class InsightPlugin {
  async analyze(recipesJson: string): Promise<NativeInsight[]> {
    // 示例:在原生层进行更复杂的分析
    const result: NativeInsight[] = [];
    result.push({
      type: 'info',
      title: '示例洞察',
      description: '这是由 ArkTS 插件返回的一条示例洞察。'
    });
    return result;
  }
}

ArkTS 的 InsightPlugin 提供 analyze 方法,可以接收完整菜谱 JSON 并返回一组洞察对象。在真实项目中,你可以在这里接入机器学习模型或云端推荐服务。

async function loadNativeInsights() {
  if (!window.cordova) return [];
  const recipes = await db.getAllRecipes();
  const json = JSON.stringify(recipes);

  return new Promise(resolve => {
    cordova.exec(resolve, () => resolve([]), 'InsightPlugin', 'analyze', [json]);
  });
}

在 Web 层,我们可以在生成本地洞察之后调用 loadNativeInsights,将 ArkTS 返回的高级洞察与本地规则生成的洞察合并展示,从而实现「规则 + 模型」混合的智能提示体验。

📝 小结

智能洞察页面通过一系列规则和可扩展的分析接口,为家庭成员提供了贴近实际使用场景的建议与提醒。依托 Cordova&OpenHarmony 混合架构,我们在 Web 层实现基础规则引擎,在 ArkTS 原生层保留接入更高级算法或云端服务的能力,为应用后续的智能化演进留足空间。

欢迎加入开源鸿蒙跨平台社区:https://openharmonycrossplatform.csdn.net

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐