HarmonyOS NEXT 跨设备接续(onContinue)与 DistributedDataObject 状态无缝流转避坑实战【鸿蒙心迹】
上个月给团队的富文本笔记应用适配 HarmonyOS NEXT 跨设备接续时,原本以为照着官方文档配个 continuable: true、在 onContinue 里塞几个字段就能收工。结果真机联调第一天就在 Mate 60 Pro 流转到 MatePad Pro 时栽了跟头:纯文本草稿流转很顺,只要正文里插了两张高清图或者贴了一段长 Markdown,点击平板 Dock 栏的接续图标后,要么直接拉起失败,要么平板打开后只剩半截文字、图片全裂成占位符,偶尔还会把手机上刚写的内容反向洗白。
折腾了一周真机日志和 HiTrace 埋点,我们才把整条链路摸透。这篇文章不复述文档里的概念定义,直接按线上真实改造的顺序,拆解 UIAbility.onContinue 到 onCreate/onNewWant 的完整恢复链路、突破 WantParam 100KB 上限的 DistributedDataObject + Asset 落地方案、各阶段耗时埋点实测数据,以及四个很容易在评审和测试阶段漏掉的线上避坑点。
一、从一次 100KB 超载崩溃说起:接续链路到底怎么走
在 HarmonyOS NEXT 里,应用接续本质上是系统分布式调度服务帮你完成了设备发现、软总线组网和目标端拉起,应用层负责两件事:源端打包状态和目标端还原现场。
先看工程配置。在 entry/src/main/module.json5 里给目标 UIAbility 打开接续开关是第一步。从 API 12 开始,应用接续本身已经不需要再动态申请 ohos.permission.DISTRIBUTED_DATASYNC 权限(API 11 及以前才需要弹窗授权),配置比早期版本清爽很多:
{
"module": {
"abilities": [
{
"name": "EntryAbility",
"srcEntry": "./ets/entryability/EntryAbility.ets",
"launchType": "singleton",
"continuable": true,
"exported": true
}
]
}
}
真正容易出问题的是生命周期分叉。当用户在平板 Dock 栏点击接续图标时,源端和目标端的执行顺序并不是一条直线,目标端是否存在存活实例会走完全不同的回调:
- 源端触发:系统回调源端
UIAbility.onContinue(wantParam)。我们在这里做版本协商、数据落盘,并返回AGREE、REJECT或MISMATCH。 - 目标端冷启动:目标设备进程未启动时,依次走
onCreate(want, launchParam)->onWindowStageRestore(windowStage)。注意,冷启动接续不会执行onWindowStageCreate,且必须在onCreate()返回前同步调用this.context.restoreWindowStage(this.localStorage)才能触发onWindowStageRestore(),否则目标端会直接卡在白屏。 - 目标端热启动:目标设备已存在
singleton实例时,直接走onNewWant(want, launchParam),同样需要在onNewWant()返回前同步调用this.context.restoreWindowStage(this.localStorage)触发界面恢复。
我们最初偷懒,把整篇富文本草稿的 JSON 和缩略图 Base64 直接塞进了 wantParam。结果文档刚过 8000 字带两张图,序列化体积就飙到了 140KB 以上,直接撞上 wantParam 的 100KB 上限红线,Binder 传输直接拒收。
工程上正确的分层方式非常明确:
wantParam只传轻量元数据(控制在几 KB 以内):草稿 ID、协议版本号、业务账号哈希、滚动偏移量、光标位置,以及分布式数据对象的自定义sessionId。- 大文本与实体图片走
DistributedDataObject+commonType.Asset:正文 Markdown、结构化块数据放到分布式数据对象里;图片、PDF 附件先拷贝进应用沙箱的distributedFilesDir目录,再封装为commonType.Asset随对象一起同步。
二、突破 100KB 上限:DistributedDataObject 与 Asset 完整实战代码
落地这套方案时,有三个硬性约束必须提前写进代码结构里:
wantParam里的"sessionId"字段可能被系统服务占用,必须换用业务自定义键名(下文使用draftSessionId)。commonType.Asset仅支持同步位于this.context.distributedFilesDir目录下的文件,本地相册或缓存目录里的图片必须先拷贝进去,且文件名拼接前必须对draftId做严格净化,杜绝路径穿越。- API 20 之前不支持
commonType.Assets资产数组,如果需要一次带走多张图片,必须在数据模型里拆成多个独立的commonType.Asset根属性(如coverAsset、extraAsset);API 20 及以上才可以直接用数组。为了兼容目前主流存量设备,下面按单资产字段写法给出完整实现。
1. 定义可接续的数据模型
把普通字段和资产字段分离,并专门为接收端提供一个“空壳构造器”。这里埋着后面要重点讲的一个大坑:接收端普通字段必须初始化为 undefined,但 Asset 字段绝对不能设为 undefined,必须把内部属性全置为空字符串。
// ets/model/DraftContinuationModel.ets
import { commonType } from '@kit.ArkData';
export class DraftPayload {
draftId: string | undefined;
title: string | undefined;
markdownBody: string | undefined;
cursorOffset: number | undefined;
revision: number | undefined;
coverAsset: commonType.Asset;
constructor(
draftId: string | undefined,
title: string | undefined,
markdownBody: string | undefined,
cursorOffset: number | undefined,
revision: number | undefined,
coverAsset: commonType.Asset
) {
this.draftId = draftId;
this.title = title;
this.markdownBody = markdownBody;
this.cursorOffset = cursorOffset;
this.revision = revision;
this.coverAsset = coverAsset;
}
static createEmptyAsset(): commonType.Asset {
return {
name: '',
uri: '',
path: '',
createTime: '',
modifyTime: '',
size: ''
};
}
static createEmptyPayload(): DraftPayload {
return new DraftPayload(
undefined,
undefined,
undefined,
undefined,
undefined,
DraftPayload.createEmptyAsset()
);
}
}
2. 封装资产拷贝与分布式对象管理类
把文件拷贝、对象创建、持久化保存和接收端恢复监听收口到一个管理器里,避免 EntryAbility 膨胀成几百行的面条代码。同时在管理器内部维护 restoreTimerId 和 restoreGeneration 代际号:无论发生快速二次热启动、setSessionId() 异常、超时兜底还是 onDestroy() 销毁,都会统一通过 release() 清掉旧定时器、摘除状态监听并断开远端会话,彻底杜绝过期的 SYNC_TIMEOUT 覆盖正常状态或后台监听泄漏。
// ets/manager/ContinuationDataManager.ets
import { common } from '@kit.AbilityKit';
import { commonType, distributedDataObject } from '@kit.ArkData';
import { fileIo, fileUri } from '@kit.CoreFileKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { DraftPayload } from '../model/DraftContinuationModel';
const DOMAIN = 0x1001;
const TAG = 'ContinuationDataManager';
const SAFE_ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
const ASSET_PREFIX = 'continue_';
const DEFAULT_ASSET_MAX_AGE_MS = 24 * 60 * 60 * 1000;
export interface LocalDraftState {
draftId: string;
title: string;
markdownBody: string;
cursorOffset: number;
revision: number;
localCoverPath: string;
}
export class ContinuationDataManager {
private dataObject: distributedDataObject.DataObject | undefined = undefined;
private statusCallback: ((sessionId: string, networkId: string, status: 'online' | 'offline' | 'restored') => void) | undefined = undefined;
private restoreTimerId: number | undefined = undefined;
private restoreGeneration: number = 0;
/**
* 校验并净化草稿 ID,阻止路径穿越字符进入 distributedFilesDir
*/
private sanitizeDraftId(rawDraftId: string): string {
const trimmed = rawDraftId.trim();
if (SAFE_ID_PATTERN.test(trimmed)) {
return trimmed;
}
const cleaned = trimmed.replace(/[^A-Za-z0-9_-]/g, '_').slice(0, 64);
return cleaned.length > 0 ? cleaned : 'draft_default';
}
/**
* 源端:将本地封面图复制到 distributedFilesDir 并构造 Asset
*/
async prepareAsset(context: common.UIAbilityContext, localFilePath: string, fileName: string): Promise<commonType.Asset> {
if (!localFilePath || !fileName || fileName.includes('/') || fileName.includes('\\') || fileName.includes('..')) {
return DraftPayload.createEmptyAsset();
}
const targetPath = `${context.distributedFilesDir}/${fileName}`;
try {
// 若封面图已在编辑阶段预置到目标路径,跳过自拷贝避免文件被截断为 0 字节
if (localFilePath !== targetPath) {
await fileIo.copyFile(localFilePath, targetPath);
}
const stat = await fileIo.stat(targetPath);
const uri = fileUri.getUriFromPath(targetPath);
return {
name: fileName,
uri: uri,
path: targetPath,
createTime: stat.ctime.toString(),
modifyTime: stat.mtime.toString(),
size: stat.size.toString()
};
} catch (err) {
const error = err as BusinessError;
hilog.error(DOMAIN, TAG, 'prepareAsset failed, code=%{public}d, msg=%{public}s', error.code, error.message);
return DraftPayload.createEmptyAsset();
}
}
/**
* 清理 distributedFilesDir 中过期的接续临时副本,防止沙箱膨胀
*/
async cleanupStaleAssets(
context: common.UIAbilityContext,
maxAgeMs: number = DEFAULT_ASSET_MAX_AGE_MS
): Promise<void> {
const dir = context.distributedFilesDir;
try {
const entries = await fileIo.listFile(dir);
const nowSec = Math.floor(Date.now() / 1000);
const maxAgeSec = Math.floor(maxAgeMs / 1000);
for (const name of entries) {
if (!name.startsWith(ASSET_PREFIX)) {
continue;
}
const fullPath = `${dir}/${name}`;
try {
const stat = await fileIo.stat(fullPath);
if (nowSec - stat.mtime > maxAgeSec) {
await fileIo.unlink(fullPath);
}
} catch (fileErr) {
const err = fileErr as BusinessError;
hilog.warn(DOMAIN, TAG, 'cleanupStaleAssets skip %{public}s: %{public}d', name, err.code);
}
}
} catch (err) {
const error = err as BusinessError;
hilog.warn(DOMAIN, TAG, 'cleanupStaleAssets listFile failed: %{public}d', error.code);
}
}
/**
* 源端:创建分布式数据对象并 save 到目标设备
*/
async saveForContinuation(
context: common.UIAbilityContext,
draft: LocalDraftState,
targetDeviceId: string
): Promise<string> {
this.release();
const safeDraftId = this.sanitizeDraftId(draft.draftId);
const assetName = `${ASSET_PREFIX}${safeDraftId}_cover.jpg`;
const coverAsset = await this.prepareAsset(context, draft.localCoverPath, assetName);
const payload = new DraftPayload(
draft.draftId,
draft.title,
draft.markdownBody,
draft.cursorOffset,
draft.revision,
coverAsset
);
const sessionId = distributedDataObject.genSessionId();
this.dataObject = distributedDataObject.create(context, payload);
try {
await this.dataObject.setSessionId(sessionId);
await this.dataObject.save(targetDeviceId);
hilog.info(DOMAIN, TAG, 'saveForContinuation success, sessionId=%{private}s', sessionId);
return sessionId;
} catch (err) {
this.release();
const error = err as BusinessError;
hilog.error(DOMAIN, TAG, 'saveForContinuation failed: %{public}d, %{public}s', error.code, error.message);
throw error;
}
}
/**
* 目标端:监听 restored 状态,确认数据与资产到达后再回调业务层
*/
async restoreFromContinuation(
context: common.UIAbilityContext,
sessionId: string,
onRestored: (draft: DraftPayload) => void,
onTimeout: () => void,
timeoutMs: number = 6000
): Promise<void> {
this.release();
const currentGen = ++this.restoreGeneration;
const emptyPayload = DraftPayload.createEmptyPayload();
this.dataObject = distributedDataObject.create(context, emptyPayload);
let finished = false;
this.restoreTimerId = setTimeout(() => {
if (!finished && currentGen === this.restoreGeneration) {
finished = true;
this.release();
hilog.warn(DOMAIN, TAG, 'restoreFromContinuation timeout after %{public}dms', timeoutMs);
onTimeout();
}
}, timeoutMs);
this.statusCallback = (_sid: string, _networkId: string, status: 'online' | 'offline' | 'restored') => {
if (currentGen !== this.restoreGeneration) {
return;
}
hilog.info(DOMAIN, TAG, 'distributed object status changed: %{public}s', status);
if (status === 'restored' && !finished && this.dataObject) {
finished = true;
this.clearRestoreTimer();
const restored = new DraftPayload(
this.dataObject['draftId'] as string | undefined,
this.dataObject['title'] as string | undefined,
this.dataObject['markdownBody'] as string | undefined,
this.dataObject['cursorOffset'] as number | undefined,
this.dataObject['revision'] as number | undefined,
(this.dataObject['coverAsset'] as commonType.Asset) ?? DraftPayload.createEmptyAsset()
);
this.detachStatusListener();
onRestored(restored);
}
};
this.dataObject.on('status', this.statusCallback);
try {
await this.dataObject.setSessionId(sessionId);
} catch (err) {
finished = true;
this.release();
const error = err as BusinessError;
hilog.error(DOMAIN, TAG, 'restore setSessionId failed: %{public}d, %{public}s', error.code, error.message);
throw error;
}
}
private clearRestoreTimer(): void {
if (this.restoreTimerId !== undefined) {
clearTimeout(this.restoreTimerId);
this.restoreTimerId = undefined;
}
}
private detachStatusListener(): void {
if (this.dataObject && this.statusCallback) {
this.dataObject.off('status', this.statusCallback);
this.statusCallback = undefined;
}
}
/**
* 断开同步、清理超时定时器与监听,避免后台幽灵同步或内存泄漏
*/
release(): void {
this.restoreGeneration++;
this.clearRestoreTimer();
this.detachStatusListener();
if (this.dataObject) {
this.dataObject.setSessionId('').catch((err: BusinessError) => {
hilog.warn(DOMAIN, TAG, 'clear sessionId failed: %{public}d', err.code);
});
this.dataObject = undefined;
}
}
}
3. UIAbility 完整接续与恢复链路
把版本校验、业务账号哈希持久化读取(优先读内存 AppStorage,冷启动内存为空时同步回退读 preferences 持久化存储)、退后台取消接续、冷/热启动无条件 restoreWindowStage 以及 onWindowStageRestore 补齐初始化全部串进 EntryAbility。页面侧 EditorPage 需要在 onPageShow / onPageHide 中同步更新 AppStorage.setOrCreate('isEditingPageActive', true/false),确保前后台切回时 onForeground() 读到真实的编辑状态。
另外,API 18 起官方才正式支持 onContinue 返回 Promise<AbilityConstant.OnContinueResult>;如果你的应用 compatibleSdkVersion 还要覆盖 API 12 到 API 17,就不能把耗时的文件拷贝留在 onContinue 里现做,而应该在用户插入图片时就提前异步写入 distributedFilesDir,保证 onContinue 内部只做轻量的对象绑定与触发。
// ets/entryability/EntryAbility.ets
import { AbilityConstant, UIAbility, Want, wantConstant } from '@kit.AbilityKit';
import { preferences } from '@kit.ArkData';
import { window } from '@kit.ArkUI';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { ContinuationDataManager, LocalDraftState } from '../manager/ContinuationDataManager';
import { DraftPayload } from '../model/DraftContinuationModel';
const DOMAIN = 0x1001;
const TAG = 'EntryAbility';
const MIN_SUPPORTED_VERSION_CODE = 20300;
const CONTINUATION_SCHEMA_VERSION = 2;
const AUTH_PREFS_NAME = 'auth_prefs';
export default class EntryAbility extends UIAbility {
private continuationManager: ContinuationDataManager = new ContinuationDataManager();
private localStorage: LocalStorage = new LocalStorage();
private currentAccountHash: string = '';
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
this.initAppDependencies();
if (launchParam.launchReason === AbilityConstant.LaunchReason.CONTINUATION) {
this.handleContinuationRestore(want);
this.context.restoreWindowStage(this.localStorage);
}
}
onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void {
if (launchParam.launchReason === AbilityConstant.LaunchReason.CONTINUATION) {
this.handleContinuationRestore(want);
this.context.restoreWindowStage(this.localStorage);
}
}
onWindowStageCreate(windowStage: window.WindowStage): void {
this.configureWindowStage(windowStage);
windowStage.loadContent('pages/EditorPage', this.localStorage, (err: BusinessError) => {
if (err.code) {
hilog.error(DOMAIN, TAG, 'loadContent failed: %{public}d', err.code);
}
});
}
onWindowStageRestore(windowStage: window.WindowStage): void {
// 冷启动接续不走 onWindowStageCreate,窗口沉浸式与布局配置必须在此补齐
this.configureWindowStage(windowStage);
windowStage.loadContent('pages/EditorPage', this.localStorage, (err: BusinessError) => {
if (err.code) {
hilog.error(DOMAIN, TAG, 'restore loadContent failed: %{public}d', err.code);
}
});
}
onForeground(): void {
const editing = AppStorage.get<boolean>('isEditingPageActive') ?? false;
this.syncContinueState(editing);
}
onBackground(): void {
// 退后台后主动挂起接续能力,防止对端 Dock 残留不可用入口
this.syncContinueState(false);
}
onDestroy(): void {
this.continuationManager.release();
}
/**
* 源端打包回调(API 18+ 支持 Promise 异步返回)
*/
async onContinue(wantParam: Record<string, Object>): Promise<AbilityConstant.OnContinueResult> {
const targetVersion = Number(wantParam.version ?? 0);
if (!Number.isFinite(targetVersion) || targetVersion < MIN_SUPPORTED_VERSION_CODE) {
hilog.warn(DOMAIN, TAG, 'target version too low or invalid: %{public}s', String(wantParam.version ?? ''));
return AbilityConstant.OnContinueResult.MISMATCH;
}
const localAccountHash = this.resolveCurrentAccountHash();
if (!localAccountHash) {
hilog.warn(DOMAIN, TAG, 'no logged-in business account, reject continuation');
return AbilityConstant.OnContinueResult.REJECT;
}
const targetDevice = wantParam.targetDevice as string | undefined;
if (!targetDevice) {
return AbilityConstant.OnContinueResult.REJECT;
}
const activeDraft = this.getActiveDraftFromStore();
if (!activeDraft) {
return AbilityConstant.OnContinueResult.REJECT;
}
try {
const startTs = Date.now();
const sessionId = await this.continuationManager.saveForContinuation(
this.context,
activeDraft,
targetDevice
);
// 仅通过 wantParam 传递轻量元数据,严禁超过 100KB
wantParam['draftSessionId'] = sessionId;
wantParam['schemaVersion'] = CONTINUATION_SCHEMA_VERSION;
wantParam['accountHash'] = localAccountHash;
wantParam['continueStartTs'] = startTs;
// 自定义目标端落点页,关闭系统默认页面栈恢复
wantParam[wantConstant.Params.SUPPORT_CONTINUE_PAGE_STACK_KEY] = false;
// 接续完成后退出源端,防止双端并发编辑导致数据覆盖
wantParam[wantConstant.Params.SUPPORT_CONTINUE_SOURCE_EXIT_KEY] = true;
return AbilityConstant.OnContinueResult.AGREE;
} catch (err) {
const error = err as BusinessError;
hilog.error(DOMAIN, TAG, 'onContinue error: %{public}d, %{public}s', error.code, error.message);
return AbilityConstant.OnContinueResult.REJECT;
}
}
private handleContinuationRestore(want: Want): void {
// 清理上一次热启动残留的错误态,避免旧提示覆盖新接续
this.localStorage.setOrCreate('continueError', '');
const params = want.parameters;
if (!params) {
this.continuationManager.release();
this.localStorage.setOrCreate('continueLoading', false);
this.localStorage.setOrCreate('continueError', 'INVALID_PARAMS');
return;
}
const remoteSchema = Number(params['schemaVersion'] ?? 0);
if (!Number.isInteger(remoteSchema) || remoteSchema < 1 || remoteSchema > CONTINUATION_SCHEMA_VERSION) {
hilog.warn(DOMAIN, TAG, 'unsupported remote schemaVersion: %{public}s', String(params['schemaVersion'] ?? ''));
this.continuationManager.release();
this.localStorage.setOrCreate('continueLoading', false);
this.localStorage.setOrCreate('continueError', 'SCHEMA_UNSUPPORTED');
return;
}
const localAccountHash = this.resolveCurrentAccountHash();
const remoteAccountHash = (params['accountHash'] as string) ?? '';
if (!localAccountHash || !remoteAccountHash || remoteAccountHash !== localAccountHash) {
hilog.warn(DOMAIN, TAG, 'business account mismatch, abort restore');
this.continuationManager.release();
this.localStorage.setOrCreate('continueLoading', false);
this.localStorage.setOrCreate('continueError', 'ACCOUNT_MISMATCH');
return;
}
const sessionId = (params['draftSessionId'] as string) ?? '';
if (!sessionId) {
this.continuationManager.release();
this.localStorage.setOrCreate('continueLoading', false);
this.localStorage.setOrCreate('continueError', 'MISSING_SESSION');
return;
}
this.localStorage.setOrCreate('continueLoading', true);
this.continuationManager.restoreFromContinuation(
this.context,
sessionId,
(restoredDraft: DraftPayload) => {
const localDraft = this.getActiveDraftFromStore();
if (
localDraft &&
restoredDraft.draftId === localDraft.draftId &&
restoredDraft.revision !== undefined &&
restoredDraft.revision < localDraft.revision
) {
hilog.warn(DOMAIN, TAG, 'stale remote revision detected, prompt conflict');
this.localStorage.setOrCreate('continueLoading', false);
this.localStorage.setOrCreate('continueError', 'REVISION_CONFLICT');
return;
}
this.localStorage.setOrCreate('restoredDraft', restoredDraft);
this.localStorage.setOrCreate('continueLoading', false);
},
() => {
this.localStorage.setOrCreate('continueLoading', false);
this.localStorage.setOrCreate('continueError', 'SYNC_TIMEOUT');
}
).catch((err: BusinessError) => {
hilog.error(DOMAIN, TAG, 'restoreFromContinuation failed: %{public}d', err.code);
this.localStorage.setOrCreate('continueLoading', false);
this.localStorage.setOrCreate('continueError', 'SYNC_ERROR');
});
}
private resolveCurrentAccountHash(): string {
const inMem = AppStorage.get<string>('accountHash');
if (inMem) {
this.currentAccountHash = inMem;
return inMem;
}
try {
const pref = preferences.getPreferencesSync(this.context, { name: AUTH_PREFS_NAME });
const persisted = pref.getSync('accountHash', '') as string;
this.currentAccountHash = persisted;
if (persisted) {
AppStorage.setOrCreate('accountHash', persisted);
}
return persisted;
} catch (err) {
const error = err as BusinessError;
hilog.error(DOMAIN, TAG, 'resolveCurrentAccountHash failed: %{public}d', error.code);
this.currentAccountHash = '';
return '';
}
}
private syncContinueState(active: boolean): void {
const targetState = active
? AbilityConstant.ContinueState.ACTIVE
: AbilityConstant.ContinueState.INACTIVE;
this.context.setMissionContinueState(targetState).catch((err: BusinessError) => {
hilog.warn(DOMAIN, TAG, 'setMissionContinueState failed: %{public}d', err.code);
});
}
private initAppDependencies(): void {
this.resolveCurrentAccountHash();
this.continuationManager.cleanupStaleAssets(this.context).catch((err: BusinessError) => {
hilog.warn(DOMAIN, TAG, 'cleanupStaleAssets failed: %{public}d', err.code);
});
}
private configureWindowStage(windowStage: window.WindowStage): void {
windowStage.getMainWindow().then((win: window.Window) => {
win.setWindowLayoutFullScreen(false).catch(() => {});
}).catch(() => {});
}
private getActiveDraftFromStore(): LocalDraftState | undefined {
return AppStorage.get<LocalDraftState>('activeDraft');
}
}
三、接续耗时分段埋点数据对比
代码跑通只是第一步。接续这件事的用户体感非常敏感:如果点了平板 Dock 栏之后转圈超过 2 秒,用户就会以为卡死了直接划掉重开。
我们在同一套测试环境(Mate 60 Pro + MatePad Pro 13.2,双端接入同一 5GHz Wi-Fi 局域网,测试样本为 12,000 字 Markdown 草稿 + 1 张 2.8MB 高清封面图,连续接续 20 次取 P50 / P90)下做了分段埋点对比:
- 优化前(基线方案):在
onContinue触发时现场压缩图片、同步拷贝进distributedFilesDir,目标端等全部数据就绪才加载页面,且开启了默认整栈恢复。 - 优化后(分层预备方案):图片插入编辑页时已在后台预拷至
distributedFilesDir;onContinue仅绑定Asset元信息与文本;关闭默认页面栈恢复,目标端先渲染骨架屏再监听restored填充内容。
| 接续阶段 | 优化前 P50 (ms) | 优化前 P90 (ms) | 优化后 P50 (ms) | 优化后 P90 (ms) | 核心优化动作 |
|---|---|---|---|---|---|
源端资产准备与 save() | 640 | 980 | 115 | 185 | 图片预置 distributedFilesDir,消除现场拷贝 I/O |
| 跨端调度与目标端拉起(冷启动) | 510 | 720 | 480 | 660 | 关闭默认页面栈恢复,减少序列化开销 |
分布式对象同步与 Asset 落盘 | 1120 | 1890 | 420 | 790 | 封面图预压缩至 800KB 内 + 仅同步当前活动草稿 |
| 目标端首帧渲染与正文上屏 | 390 | 560 | 165 | 240 | onWindowStageRestore 先出骨架屏,restored 后增量刷新 |
| 端到端总耗时(点击到可编辑) | 2660 | 4150 | 1180 | 1875 | 总耗时下降约 55.6%,消除白屏卡顿感 |
这里必须说一句实话,也是这套机制的真实局限与取舍:上面的 1.18 秒是在双端同 5GHz 局域网下的成绩。一旦切到双端不在同一 Wi-Fi(仅靠蓝牙发现再临时拉起 Wi-Fi Direct/P2P 建链)的弱网环境,仅“跨端调度 + 资产落盘”这两段就会出现 1.8 秒到 3.5 秒的明显抖动,甚至偶发超时。所以目标端千万不能把 restored 当成必然在几百毫秒内到达的同步事件,代码里那层 6 秒超时兜底和“重试拉取 / 切换云端草稿”的降级按钮,线上真的救过命。
四、线上踩出的 4 个真实避坑点
坑 1:华为账号一致,不等于业务账号一致
系统层面的应用接续前提是“双端登录同一华为账号”,但绝大多数商业应用都有自己的账号体系(手机号、微信登录或企业 SSO)。我们在灰度期间就遇到过真实客诉:用户手机和平板登的是同一个华为账号,但应用里手机登的是个人号、平板登的是公司工作号。点接续后,如果直接把草稿塞进平板的本地数据库,不仅会出现跨账号数据泄露,用户点保存时还会因为鉴权主体不匹配直接报 403。
解法:千万别把原始 userId 或 token 明文塞进 wantParam,也千万别只在 onCreate 里读一次内存 AppStorage——冷启动时内存 AppStorage 是空的,直接比对会导致 100% 误判 ACCOUNT_MISMATCH。正确做法是登录成功时把带盐的 accountHash(如 SHA-256 截断前 16 位)同步写入 preferences 持久化存储;每次 onContinue 和 handleContinuationRestore 都通过 resolveCurrentAccountHash() 实时读取(优先内存,冷启动回退读 preferences)。一旦两端哈希对不上,立刻拦截 restoreFromContinuation 并调用 release() 断开会话,在界面上提示用户切换账号。
坑 2:退后台或停在非编辑页,对端仍挂着“幽灵接续图标”
module.json5 里配了 continuable: true 后,MissionContinueState 默认就是 ACTIVE。这意味着哪怕用户当前停留在登录页、支付确认页、设置页,甚至已经把应用切到了后台,旁边的平板 Dock 栏依然会亮着接续图标。一旦用户顺手点了,目标端拉起来根本没东西可恢复,只能给个尴尬的报错或者直接闪退。
解法:把接续状态当成页面级开关来管,而不是应用级常驻开关。
EditorPage在onPageShow时执行AppStorage.setOrCreate('isEditingPageActive', true)并同步激活接续态,onPageHide时置为false并关闭接续态。UIAbility.onForeground()从AppStorage读取isEditingPageActive决定是否激活,切勿在 Ability 里写死不可变的私有布尔字段;onBackground()触发时无条件切为AbilityConstant.ContinueState.INACTIVE。- 接续取消或冷启动初始化时,调用
cleanupStaleAssets()清理distributedFilesDir里超过 24 小时的continue_*临时副本,避免沙箱缓存持续膨胀。
坑 3:目标端版本兼容与多 API 版本的隐形断层
手机和平板的应用版本不同步是常态——手机刚升了新版支持多栏排版和新的草稿协议,平板还停在两个月前的老版本。如果不做拦截,老版本强行解析新版数据结构,轻则丢样式,重则直接 JSON 解析异常崩溃。
解法:在源端 onContinue 里做好两层校验。第一层读系统传入的 wantParam.version(对应目标端应用的 versionCode),低于最低兼容版本号直接返回 AbilityConstant.OnContinueResult.MISMATCH,让系统层面直接提示用户升级,不要返回模糊的 REJECT。第二层在 wantParam 里自带 schemaVersion,目标端遇到高于自身支持上限的 schemaVersion 时直接拦截并提示升级。另外编码时要盯紧两个系统 API 分水岭:
- API 18:
onContinue从此版本起才支持Promise异步返回;低版本必须保证onContinue同步返回,重 IO 必须前置。 - API 20:此前不支持
commonType.Assets数组,多附件必须拆成多字段定义。
坑 4:接收端对象初始化写错导致“反向覆盖”,以及冷启动漏掉 restoreWindowStage
这是最隐蔽、排查最费劲的两个坑。第一个坑出在 DistributedDataObject 的同步机制上:接收端在调用 distributedDataObject.create(context, emptyPayload) 时,如果给普通字段赋了默认值(比如 title: ''、cursorOffset: 0),分布式对象会认为接收端也有合法新值,在组网瞬间反向把源端刚写的数据覆盖掉;反过来,如果是 commonType.Asset 字段,直接赋 undefined 又会导致资产元数据槽位无法匹配,图片根本同步不过来。记住这条铁律:普通字段填 undefined,Asset 对象的每个子属性填 ''。
第二个坑出在冷启动生命周期。Stage 模型下,冷启动接续根本不走 onWindowStageCreate,而是依赖 onCreate() 返回前同步调用 this.context.restoreWindowStage(this.localStorage) 来拉起 onWindowStageRestore。只要漏调这一句(哪怕关闭了 SUPPORT_CONTINUE_PAGE_STACK_KEY),目标端就会直接黑屏或白屏;同时,平时写在 onWindowStageCreate 里的窗口沉浸式配置和断点监听,也必须抽成独立的 configureWindowStage() 在两边同时调用,才不会在冷启动接续时掉进空指针陷阱。
五、一点架构取舍的收尾思考
最后顺带提一个产品评审时经常被问到的问题:“能不能手机接续到平板后,手机不退出,两台设备一起改同一篇文档?”技术上把 wantParam[wantConstant.Params.SUPPORT_CONTINUE_SOURCE_EXIT_KEY] 设为 false 确实能让源端留在前台,但强烈不建议拿应用接续硬做双端并发编辑。
应用接续和 DistributedDataObject 解决的是“单任务跨端接力”和最终一致性问题,系统底层并不会帮你做文本冲突合并(CRDT/OT)。只要两端同时敲字,后写入的一端就会直接覆盖先写入的内容。如果业务真的有“平板画草图、手机实时看并批注”这类并发协同诉求,老老实实切到多端协同的 abilityConnectionManager 建通道做增量同步,或者走云端带 revision 校验的协作服务,别在 onContinue 里硬拧。把接续的边界守干净,该退源端就干脆退出,该做预拷贝和超时降级就一步到位,跨设备体验才能真正稳得住。
更多推荐




所有评论(0)