94 Star 364 Fork 200

HarmonyOS-Cases / Cases

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
README.md 2.76 KB
一键复制 编辑 原始数据 按行查看 历史
kenneth 提交于 2024-03-26 14:19 . 代码检视问题修复

在Native侧实现进度通知功能

介绍

本示例通过模拟下载场景介绍如何将Native的进度信息实时同步到ArkTS侧。

效果图预览

使用说明

  1. 点击“Start Download“按钮后,Native侧启动子线程模拟下载任务
  2. Native侧启动子线程模拟下载,并通过Arkts的回调函数将进度信息实时传递到Arkts侧

实现思路

  1. 前端进度条使用Progress绘制
    Progress({ value: this.progress, total: 100, type: ProgressType.Ring })
        .width($r("app.integer.progress_size"))
        .height($r("app.integer.progress_size"))
        .animation({ duration: NativeProgressNotifyConstants.PROGRESS_ANIMATION_DURATION, curve: Curve.Ease })
        .style({ strokeWidth: 15 })
  2. JS侧调用Native侧方法,并传入用于接收下载进度的回调函数,在该回调函数中更改状态变量
    naitiveprogressnotify.startDownload((data: number) => {
        this.progress = data;
        console.info("[NativeProgressNotify]progress:" + this.progress);
    })
  3. Naitive侧使用std::thread创建子线程执行模拟下载的任务
    std::thread downloadThread(downloadTask, asyncContext);
    downloadThread.detach();
  4. Native侧模拟下载的线程中,每100ms执行一次uv_queue_work;向eventloop事件堆栈push异步任务。
     while (context && context->progress < 100) {
         context->progress += 1;
         napi_acquire_threadsafe_function(tsfn);
         napi_call_threadsafe_function(tsfn, (void *)context, napi_tsfn_blocking);
         std::this_thread::sleep_for(std::chrono::milliseconds(100));
     }
  5. 在模拟下载任务的子线程中,调用napi_call_function来执行Arkts回调,向Arkts侧传递进度信息
     napi_create_int32(arg->env, arg->progress, &progress);
     napi_call_function(arg->env, nullptr, jsCb, 1, &progress, nullptr);

高性能知识点

本例中,在Native侧使用子线程执行下载任务,从而避免对主线程资源的占用,能有效提升性能

工程结构&模块类型

verifycode                                       // har类型
|---constants
|   |---NativeProgressNotifyContants.ets         // 常量
|---view
|   |---NativeProgressNotify.ets                 // 视图层

模块依赖

不涉及

参考资料

  1. Progress
  2. Napi
  3. libuv
JavaScript
1
https://gitee.com/harmonyos-cases/cases.git
git@gitee.com:harmonyos-cases/cases.git
harmonyos-cases
cases
Cases
master

搜索帮助