HarmonyOS 鸿蒙Next worker.ts中如何获取context

发布于 1周前 作者 yuanlaile 来自 鸿蒙OS

HarmonyOS 鸿蒙Next worker.ts中如何获取context
找HarmonyOS工作还需要会Flutter技术的哦,有需要Flutter教程的可以学学大地老师的教程,很不错,B站免费学的哦:https://www.bilibili.com/video/BV1S4411E7LY/?p=17

关于HarmonyOS 鸿蒙Next worker.ts中如何获取context的问题,您也可以访问:https://www.itying.com/category-93-b0.html 联系官网客服。

4 回复
  1. 从主线程通过worker.postMessage(context)发送到worker子线程。
let worker = new worker.ThreadWorker('entry/ets/workers/Worker.ts', {name:"first worker in Stage model"});

let context = getContext(this)

worker.postMessage(context);<button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 8px; right: 8px; font-size: 14px;">复制</button>

  1. 从worker线程中通过workerPort.onmessage接受context。
workerPort.onmessage = function(e : MessageEvents) {

    let context = e.data

    console.info(${TAG} onmessage:${<span class="hljs-built_in"><span class="hljs-built_in">JSON</span></span>.stringify(context.cacheDir)})

}<button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 8px; right: 8px; font-size: 14px;">复制</button>

升级HarmonyOS后,感觉手机的整体性能都有了很大的提升。

作者试过了吗,两个context一样吗,因为worker.postMessage(object);其中要求object中的内容可以序列化,而context显然不行

楼主这方法不太好,建议如下写法

export default class GlobalThis {
  private constructor() {};
  private static instance: GlobalThis;
  private _uiContexts = new Map<string, common.UIAbilityContext>();
  private _appContexts = new Map<string, Context>();
  static readonly ConttextKey="globalContext";
  static readonly AppConttextKey="appContext";

public static getInstance(): GlobalThis { if (!GlobalThis.instance) { GlobalThis.instance = new GlobalThis(); } return GlobalThis.instance; } setApplicationContext(appContent:Context){ this._appContexts.set(GlobalThis.AppConttextKey,appContent); } getApplicationContext():Context | undefined { return this._appContexts.get(GlobalThis.AppConttextKey); } setContext(key: string, value: common.UIAbilityContext): void { this._uiContexts.set(key, value); } getContext(key: string): common.UIAbilityContext | undefined { return this._uiContexts.get(key); } setWorker(key:string,worker:worker.ThreadWorker){ this._workers.set(key,worker); } } <button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 8px; right: 8px; font-size: 14px;">复制</button>

然后程序启动的时候保存context

export default class EntryAbility extends UIAbility{

onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { let globalThis=GlobalThis.getInstance(); let mainAbilityContext = this.context.getApplicationContext(); globalThis.setApplicationContext(mainAbilityContext); }<button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 8px; right: 8px; font-size: 14px;">复制</button>

使用方法

let globalThis=GlobalThis.getInstance();
let pathDir = globalThis.getApplicationContext().filesDir;
}<button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 8px; right: 8px; font-size: 14px;">复制</button>

回到顶部