做鸿蒙元服务和万能卡片时,产品常想把通勤或订单卡片做成“每五分钟自动刷新”。但 FormKit 对被动定时刷新设了硬红线:每张卡片每天最多触发 50 次定时刷新,配额把 form_config.json 里的 updateDuration 周期定时和代码里的 formProvider.setFormNextRefreshTime 合并计算,零点才重置。一旦撞线,当天后续定时刷新会被系统直接拦截。

配额之外还有三道隐形约束。系统定时共用同一个计时器,卡片刚添加时的首次刷新最多存在 30 分钟偏差;卡片处于锁屏或被遮挡的不可见状态时,定时和定点刷新只记录动作与数据,待桌面重新可见时再统一刷新布局;设备重启后系统回调的是 onAddForm 而非 onUpdateForm,若提供方未做本地持久化,卡片就会退回初始占位文案。

随着 API 20 到 API 26.0.0 演进,我开始把每日 50 次配额当作稀缺预算来分配:用端侧轻量意图预测接管 setFormNextRefreshTime 间隔,避开夜间和不可见时段,把刷新集中在高峰窗口,再叠加 API 26.0.0 放开的代理刷新与网络变化条件刷新共存能力。

FormKit 50 次配额约束下的主动智能卡片端侧按需调度

一、API 20 至 API 26.0.0 的 FormKit 刷新边界演进

对比近期几个 API 版本的官方指南后,我把直接决定智能卡片调度架构的几项关键变化整理在下表,方便团队技术选型时快速对齐边界。

能力维度早期版本(API 19 及以前)API 20 至 API 26.0.0 演进边界对调度架构的工程意义
定时与下次刷新配额每卡每日合计上限 50 次,零点重置维持每日 50 次刚性上限,同计时器首刷偏差最多 30 分钟不能靠固定高频轮询硬扛,须按场景密度动态分配
共享内存刷新上限最多 5 张图片,单张内存限 2MB自 API 20 起总数据上限扩至 10MB,图片最多 20 张端侧路线缩略图与状态图标可一次推入
互动卡片动效静态布局与基础点击跳转自 API 20 起支持互动卡片与破框动效,业务不可强依赖关键提醒可借破框增强注意,同时保底常规卡片展示
代理与定时共存三方应用开代理刷新后,定时与下次刷新失效自 API 26.0.0 起,三方应用代理、定时与下次刷新可同时生效突发变更走代理通道,周期场景兜底继续走定时通道
网络恢复条件刷新早期仅系统应用支持网络条件触发自 API 26.0.0 起支持 conditionUpdate 配置 network断网超 10 分钟后重连网络时自动拉起 onUpdateForm

这里最关键的突破是 API 26.0.0 的三通道共存。过去三方应用一旦开启代理刷新,updateDuration 和 setFormNextRefreshTime 就会失效;现在终于可以把“突发事件”和“周期保鲜”拆开治理。

OpenHarmony FormKit 卡片代理刷新工作原理

图注:引用自 OpenHarmony 官方文档(openharmony/docs,CC-BY-4.0 协议)的卡片代理刷新原理图,展示数据提供方、数据管理服务与卡片管理/渲染服务的解耦链路。

从原理图可以看到,代理刷新由数据提供方将状态写入数据管理服务,再由卡片管理服务按需通知渲染服务更新,不频繁唤醒 FormExtensionAbility,也不占这 50 次定时配额。需要留意,FormExtensionAbility 被拉起后后台存活时间很短(官方网络图片刷新指南提示仅 5 秒),耗时拉取和端侧模型推理绝不能堵在回调里,应当提前在宿主应用进程算完再写入共享存储或数据管理服务。

另外,在 API 20 及以上版本用共享内存推送高密度图文卡片时,有一个细节很容易踩坑。卡片侧的 Image 组件通过 memory://fileName 加载远端内存图片时,渲染引擎靠传入的图片名称是否发生变化来决定要不要重绘;如果每次刷新都沿用同一个图片键名,即使底层像素换了,桌面卡片也不会刷新图像。工程里需要把时间戳或版本号拼进键名,同时控制在 20 张图和 10MB 共享内存总上限之内,避免把内存通道撑爆。

二、固定轮询为什么总在高峰期掉链子

很多工程直接把 form_config.json 里的 updateDuration 设为 1(每 30 分钟一次),一天 48 次看似刚好卡在 50 次以内。放到通勤或实时订单这类强时段场景里,这种等间隔做法会同时暴露两个问题。

一是夜间和后台空转。零点到清晨六点半手机通常锁屏,固定 30 分钟轮询照样消耗十几次配额;而早高峰七点半到九点半之间,用户对信息新鲜度的容忍度往往在 5 分钟左右,30 分钟一次根本追不上状态变化。如果改用 setFormNextRefreshTime 固定每 20 分钟强刷,第 50 次配额在下午四点二十分就会耗尽,晚高峰直接断更。如果再叠加上同计时器带来的首次最多 30 分钟偏差,用户刚把卡片添加到桌面时往往要等很久才看到第一帧有效数据。

用端侧轻量意图预测替代固定周期,不需要往扩展进程里塞大模型。只靠本地近 7 天分时段亮屏先验概率、当前桌面可见状态、数据陈旧度以及剩余配额余量,就能动态算出 10 分钟、15 分钟、60 分钟或夜间 180 分钟的下一次间隔。再配合卡片上的主动刷新按钮:当用户顺手点击卡片触发 postCardAction 的 message 事件进入 onFormEvent 时,应用方可以直接调用 updateForm 完成一次即时主动刷新并把最新的数据时间戳记回持久化快照,让被动定时调度器顺势重置下一轮等待窗口,不必再多花一次定时配额。

固定轮询与端侧意图按需调度在 50 次配额下的全天投放对比

图注:左为固定周期轮询在低谷空转或下午耗尽配额的典型模式,右为端侧意图预测结合 API 26.0.0 代理刷新与网络恢复事件的高峰聚焦投放架构。

三、ArkTS 卡片提供方与页面侧结构范式

接入 Stage 模型时要管住三件事:form_config.json 互斥配置、FormExtensionAbility 重启恢复与动态定时、以及独立进程下的纯 V1 UI 接收。下面代码仅作生命周期持久化与按需调度结构范式展示,不包含真机功耗实测,实际工程导入与存储接口请以当前 SDK 文档为准。由于卡片运行在独立进程且须通过 LocalStorageProp 接收字符串化数据,页面侧严格采用纯 ArkUI V1 装饰器,不混用 V2。

// 结构范式:form_config.json(使用定点或动态定时时须将 updateDuration 置为 0)
{
  "forms": [
    {
      "name": "SmartScheduleCard",
      "description": "$string:smart_card_desc",
      "src": "./ets/widget/pages/SmartScheduleCard.ets",
      "uiSyntax": "arkts",
      "window": { "designWidth": 720, "autoDesignWidth": true },
      "isDefault": true,
      "updateEnabled": true,
      "updateDuration": 0,
      "scheduledUpdateTime": "07:25",
      "conditionUpdate": ["network"],
      "defaultDimension": "2*4",
      "supportDimensions": ["2*2", "2*4"]
    }
  ]
}
// 结构范式:FormExtensionAbility 意图调度与重启缓存恢复(非真机功耗实测)
import { formBindingData, FormExtensionAbility, formInfo, formProvider } from '@kit.FormKit';
import { Want } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';

const TAG: string = 'SmartFormAbility';
const DOMAIN: number = 0xFF00;

interface CardDispatchState {
  remainingQuota: number;
  isDesktopVisible: boolean;
  lastSummary: string;
  lastUpdateClock: string;
}

export default class SmartFormAbility extends FormExtensionAbility {
  // 计算下一次间隔(分钟,最短须 >= 5 分钟)
  private calcNextIntervalMinutes(hour: number, state: CardDispatchState): number {
    if (state.remainingQuota <= 1) {
      return 180;
    }
    const isPeak: boolean = (hour >= 7 && hour < 10) || (hour >= 17 && hour < 21);
    const isNoon: boolean = hour >= 11 && hour < 14;

    if (!state.isDesktopVisible && !isPeak) {
      return 120; // 非高峰不可见时跳过空刷
    }
    if (isPeak && state.remainingQuota >= 12) {
      return 10;
    }
    if (isNoon && state.remainingQuota >= 8) {
      return 15;
    }
    return (hour >= 23 || hour < 6) ? 180 : 60;
  }

  // 读取持久化快照(工程中对接 Preferences/RDB)
  private loadPersistedState(formId: string): CardDispatchState {
    return {
      remainingQuota: 42,
      isDesktopVisible: true,
      lastSummary: `已恢复卡片[${formId}]缓存摘要`,
      lastUpdateClock: '07:25'
    };
  }

  onAddForm(want: Want): formBindingData.FormBindingData {
    const formId: string = (want.parameters?.[formInfo.FormParam.IDENTITY_KEY] as string) ?? 'unknown';
    const restored: CardDispatchState = this.loadPersistedState(formId);
    // 设备重启走 onAddForm 而非 onUpdateForm,直接回填缓存防退回初始态
    const payload: Record<string, string> = {
      'title': '智能日程卡片',
      'summary': restored.lastSummary,
      'updatedAt': restored.lastUpdateClock
    };
    return formBindingData.createFormBindingData(payload);
  }

  onUpdateForm(formId: string): void {
    const now: Date = new Date();
    const state: CardDispatchState = this.loadPersistedState(formId);
    const clockText: string = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;

    const payload: Record<string, string> = {
      'title': '智能日程卡片',
      'summary': '已按高峰意图窗口完成刷新',
      'updatedAt': clockText
    };
    formProvider.updateForm(formId, formBindingData.createFormBindingData(payload)).catch((err: BusinessError) => {
      hilog.error(DOMAIN, TAG, `updateForm failed: ${err.code}, ${err.message}`);
    });

    const nextMinutes: number = this.calcNextIntervalMinutes(now.getHours(), state);
    try {
      formProvider.setFormNextRefreshTime(formId, nextMinutes, (err: BusinessError) => {
        if (err) {
          hilog.error(DOMAIN, TAG, `setFormNextRefreshTime failed: ${err.code}, ${err.message}`);
        }
      });
    } catch (err) {
      hilog.error(DOMAIN, TAG, `setFormNextRefreshTime exception: ${(err as BusinessError).code}`);
    }
  }
}
// 结构范式:纯 ArkUI V1 卡片页面(不混用 V2 装饰器)
let cardStorage = new LocalStorage();

@Entry(cardStorage)
@Component
struct SmartScheduleCard {
  @LocalStorageProp('title') title: string = '智能日程卡片';
  @LocalStorageProp('summary') summary: string = '等待首次同步';
  @LocalStorageProp('updatedAt') updatedAt: string = '--:--';

  build() {
    Column({ space: 6 }) {
      Row() {
        Text(this.title).fontSize(14).fontWeight(FontWeight.Medium).maxLines(1)
        Blank()
        Text(this.updatedAt).fontSize(12).opacity(0.65)
      }.width('100%')

      Text(this.summary).fontSize(13).maxLines(2).textOverflow({ overflow: TextOverflow.Ellipsis }).width('100%')

      Row() {
        Button('立即校准').height(28).fontSize(12).onClick(() => {
          postCardAction(this, { action: 'message', params: { trigger: 'manual_sync' } });
        })
      }.width('100%').justifyContent(FlexAlign.End)
    }.width('100%').height('100%').padding(12)
  }
}

四、50 次配额约束下的调度对比仿真与剖析

为了量化不同策略的配额耗尽时刻与高峰新鲜度差距,我用纯 Python 3 标准库写了一个调度仿真器。全天 1440 分钟按 5 分钟步长切为 288 个时间片,覆盖早高峰(07:30–09:30)、午间时段(11:45–13:15)、晚高峰(17:30–20:30)、日间间歇可见与夜间锁屏五个阶段,新鲜度阈值设为数据年龄不超过 5 分钟。需要说明,该脚本采用合成的确定性时间线验证配额分配与窗口对齐逻辑,不代表真实线上日活点击率或真机功耗。

from dataclasses import dataclass
from typing import Dict, List

STEP_MINUTES = 5
TOTAL_MINUTES = 24 * 60
DAILY_QUOTA = 50
FRESHNESS_THRESHOLD_MIN = 5


@dataclass(frozen=True)
class ViewSlot:
    """时间片内的桌面可见性与看卡事件"""
    minute: int
    period_name: str
    is_peak: bool
    desktop_visible: bool
    user_views: int
    network_recovered: bool = False
    proxy_pushed: bool = False


@dataclass
class SimulationSummary:
    """单种策略全天仿真结果"""
    strategy_name: str
    quota_used: int
    exhausted_time: str
    effective_refresh_count: int
    wasted_quota_count: int
    total_views: int
    fresh_hit_views: int
    peak_views: int
    peak_fresh_hits: int
    avg_staleness_min: float

    @property
    def overall_hit_rate(self) -> float:
        return (self.fresh_hit_views / self.total_views * 100.0) if self.total_views else 0.0

    @property
    def peak_hit_rate(self) -> float:
        return (self.peak_fresh_hits / self.peak_views * 100.0) if self.peak_views else 0.0


def format_clock(minute: int) -> str:
    """格式化为时钟文本"""
    return f"{minute // 60:02d}:{minute % 60:02d}"


def build_daily_timeline() -> List[ViewSlot]:
    """构建24小时确定性看卡与网络事件时间线(非真实线上日活)"""
    slots: List[ViewSlot] = []
    proxy_slots = {455, 485, 515, 545, 735, 1065, 1095, 1125, 1155, 1185, 1215}
    net_recover_slots = {505, 765, 1105, 1195}

    for m in range(0, TOTAL_MINUTES, STEP_MINUTES):
        if 450 <= m < 570:
            period, is_peak, visible = "早高峰", True, True
            views = 2 if (m in proxy_slots or m in net_recover_slots or m % 20 == 0) else 1
        elif 705 <= m < 795:
            period, is_peak, visible = "午间时段", True, True
            views = 1 if (m in proxy_slots or m in net_recover_slots or m % 15 == 5) else 0
        elif 1050 <= m < 1230:
            period, is_peak, visible = "晚高峰", True, True
            views = 2 if (m in proxy_slots or m in net_recover_slots or m % 20 == 10) else 1
        elif 0 <= m < 390 or m >= 1380:
            period, is_peak, visible = "夜间低谷", False, False
            views = 1 if m in (30, 1410) else 0
        else:
            period, is_peak = "日间常规", False
            visible = (m % 30) in (10, 15)
            views = 1 if (m % 60 == 15) else 0

        slots.append(
            ViewSlot(
                minute=m,
                period_name=period,
                is_peak=is_peak,
                desktop_visible=visible,
                user_views=views,
                network_recovered=(m in net_recover_slots),
                proxy_pushed=(m in proxy_slots),
            )
        )
    return slots


def predict_intent_score(slot: ViewSlot, data_age_min: int) -> float:
    """结合先验权重、可见性与陈旧度计算意图得分"""
    prior_map: Dict[str, float] = {
        "早高峰": 0.90,
        "午间时段": 0.72,
        "晚高峰": 0.88,
        "日间常规": 0.30,
        "夜间低谷": 0.04,
    }
    score = prior_map[slot.period_name]
    if not slot.desktop_visible:
        score *= 0.25
    if data_age_min >= 40:
        score = min(1.0, score + 0.12)
    return score


def compute_next_interval_min(current_minute: int, intent_score: float, remaining_quota: int) -> int:
    """动态计算下一次刷新间隔并对齐下一高峰起点"""
    if remaining_quota <= 0:
        return 24 * 60

    peak_windows = [(450, 570), (705, 795), (1050, 1230)]
    next_peak_start = next((s for s, _ in peak_windows if current_minute < s), None)

    if intent_score >= 0.80:
        return 10 if remaining_quota >= 12 else 15
    if intent_score >= 0.65:
        return 15 if remaining_quota >= 8 else 20

    base_sleep = 60 if intent_score >= 0.25 else 180
    if next_peak_start is not None and current_minute + base_sleep > next_peak_start:
        return max(5, next_peak_start - current_minute)
    return base_sleep


def simulate_strategy(timeline: List[ViewSlot], mode: str) -> SimulationSummary:
    """运行单种调度策略的全天仿真"""
    quota_used = 0
    exhausted_time = "全天未耗尽"
    last_data_update_min = -999
    effective_refreshes = 0
    wasted_quota_count = 0
    active_quota_served = True
    pending_deferred_update = False

    total_views = fresh_hit_views = peak_views = peak_fresh_hits = staleness_sum = 0
    # 固定30分钟含首刷20分钟偏差;意图调度从07:30早高峰起动
    next_timer_min = 20 if mode == "fixed_30m" else (0 if mode == "fixed_20m" else 450)

    for slot in timeline:
        m = slot.minute
        triggered_timer = False

        if m >= next_timer_min and quota_used < DAILY_QUOTA:
            if not active_quota_served:
                wasted_quota_count += 1
            quota_used += 1
            active_quota_served = False
            if quota_used == DAILY_QUOTA:
                exhausted_time = format_clock(m)

            if slot.desktop_visible:
                last_data_update_min = m
                effective_refreshes += 1
                pending_deferred_update = False
            else:
                pending_deferred_update = True  # 不可见时延后至可见再刷新布局

            if mode == "fixed_30m":
                next_timer_min = m + 30
            elif mode == "fixed_20m":
                next_timer_min = m + 20
            else:
                score = predict_intent_score(slot, m - last_data_update_min)
                next_timer_min = m + compute_next_interval_min(m, score, DAILY_QUOTA - quota_used)
            triggered_timer = True

        if pending_deferred_update and slot.desktop_visible and not triggered_timer:
            last_data_update_min = m
            effective_refreshes += 1
            pending_deferred_update = False

        if mode == "intent_plus_api26" and (slot.proxy_pushed or slot.network_recovered):
            last_data_update_min = m
            effective_refreshes += 1  # 代理与网络条件刷新不占50次定时配额

        if slot.user_views > 0:
            data_age = m - last_data_update_min if last_data_update_min >= 0 else 999
            is_fresh = data_age <= FRESHNESS_THRESHOLD_MIN
            active_quota_served = True
            total_views += slot.user_views
            staleness_sum += min(data_age, 180) * slot.user_views
            if is_fresh:
                fresh_hit_views += slot.user_views
            if slot.is_peak:
                peak_views += slot.user_views
                if is_fresh:
                    peak_fresh_hits += slot.user_views

    if not active_quota_served:
        wasted_quota_count += 1

    labels = {
        "fixed_30m": "固定30分钟(updateDuration=1)",
        "fixed_20m": "固定20分钟高频轮询",
        "intent_adaptive": "端侧意图预测按需调度",
        "intent_plus_api26": "意图预测+API26代理/网络协同",
    }
    return SimulationSummary(
        strategy_name=labels[mode],
        quota_used=quota_used,
        exhausted_time=exhausted_time,
        effective_refresh_count=effective_refreshes,
        wasted_quota_count=wasted_quota_count,
        total_views=total_views,
        fresh_hit_views=fresh_hit_views,
        peak_views=peak_views,
        peak_fresh_hits=peak_fresh_hits,
        avg_staleness_min=(staleness_sum / total_views if total_views else 0.0),
    )


if __name__ == "__main__":
    timeline = build_daily_timeline()
    modes = ["fixed_30m", "fixed_20m", "intent_adaptive", "intent_plus_api26"]
    results = [simulate_strategy(timeline, m) for m in modes]

    print(f"=== 50次配额调度对比(288时间片,阈值<={FRESHNESS_THRESHOLD_MIN}分钟) ===")
    for r in results:
        print(
            f"[{r.strategy_name}] 配额={r.quota_used}/50 | 耗尽={r.exhausted_time} | "
            f"有效={r.effective_refresh_count}次 | 浪费={r.wasted_quota_count}次 | "
            f"全天={r.overall_hit_rate:.1f}%({r.fresh_hit_views}/{r.total_views}) | "
            f"高峰={r.peak_hit_rate:.1f}%({r.peak_fresh_hits}/{r.peak_views}) | "
            f"陈旧={r.avg_staleness_min:.1f}分钟"
        )

    fixed_30, fixed_20, intent_only, intent_api26 = results
    assert fixed_20.quota_used == 50 and fixed_20.exhausted_time != "全天未耗尽"
    assert intent_only.quota_used < 50 and intent_only.exhausted_time == "全天未耗尽"
    assert intent_only.peak_hit_rate > fixed_30.peak_hit_rate
    assert intent_api26.peak_hit_rate > intent_only.peak_hit_rate
    assert intent_only.wasted_quota_count < fixed_30.wasted_quota_count
    print("全部调度配额与命中率断言校验通过")

在本机执行该 Python 3 脚本(返回码 0,全部断言通过),四种策略实跑数据如下:

调度策略定时配额消耗配额耗尽时刻有效落盘次数浪费配额次数全天 5 分钟新鲜命中率高峰期 5 分钟新鲜命中率全天平均数据陈旧度
固定 30 分钟(updateDuration=1)48 / 50全天未耗尽33 次22 次42.6%(46 / 108)38.5%(37 / 96)13.0 分钟
固定 20 分钟高频轮询50 / 5016:2025 次30 次31.5%(34 / 108)29.2%(28 / 96)74.1 分钟
端侧意图预测按需调度43 / 50全天未耗尽42 次1 次90.7%(98 / 108)96.9%(93 / 96)9.8 分钟
意图预测 + API 26 代理/网络协同43 / 50全天未耗尽57 次1 次93.5%(101 / 108)100.0%(96 / 96)8.5 分钟

从这组输出能看到三个明确的工程反差。固定 20 分钟强刷浪费了 30 次配额并在 16:20 提前见底,晚高峰直接断更,全天平均陈旧度飙升到 74.1 分钟;固定 30 分钟轮询虽然未耗尽,却把 22 次配额空转在不可见时段,高峰 5 分钟命中率只有 38.5%。改用端侧意图预测后,全天只消耗 43 次配额,浪费压到 1 次,高峰命中率跃升至 96.9%(均值 9.8 分钟偏高是因为凌晨 00:30 预热前的低频查看按 180 分钟截断计入);叠加 API 26.0.0 代理刷新和断网重连刷新后,高峰命中率进一步拉满到 100.0%,有效落盘达到 57 次。

写调度器时我特意加了 next_peak_start 窗口对齐限制。如果不做这层截断,低谷期睡上 60 分钟或 180 分钟,很容易从 06:50 直接跨过 07:30 早高峰开局。

五、上线前必须锁死的 4 个工程边界

  1. 避免在 form_config.json 中同时启用非零 updateDuration 与 scheduledUpdateTime。两者同时存在时系统优先执行 updateDuration,定点唤醒会直接失效,走动态调度须将 updateDuration 显式设为 0。
  2. onAddForm 必须接入本地快速可读的持久化快照。设备重启或桌面进程重建时系统走 onAddForm 建卡回调,只依赖 onUpdateForm 推送会导致重启后界面退回初始占位。
  3. 严控共享内存图文载荷与回调时长。API 20 及以上版本虽将共享内存放宽至 10MB 和 20 张图,网络图下载和渲染预处理仍应留在宿主进程,让 FormExtensionAbility 在 5 秒存活窗口内只做轻读取。
  4. 做好 API 26.0.0 前后的版本分流。在低于 API 26.0.0 的旧系统上,开启代理刷新会屏蔽定时和下次刷新;上线前应按系统 API 版本隔离调度策略,低版本设备退回到纯代理推送或纯意图定时单轨方案,别让双通道在老系统上互相哑火。

把每日 50 次配额当成有限的调度预算来分配,把用户看卡习惯统计留在设备本地算清,再把突发变动和断网重连交给代理与系统条件通道。这样处理之后,万能卡片不必靠蛮力轮询,也能在用户抬眼看过来的那一秒保持足够高的鲜活度。


参考资料:

  1. 华为开发者文档:定时或定点刷新卡片(HarmonyOS V13)
  2. OpenHarmony 官方文档:ArkTS 卡片被动刷新指南
  3. OpenHarmony 官方文档:ArkTS 卡片主动刷新指南
Logo

作为“人工智能6S店”的官方数字引擎,为AI开发者与企业提供一个覆盖软硬件全栈、一站式门户。

更多推荐