• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

wkin

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

ImageKnif自定义下载(待完成)

自定义下载函数


ImageKnife.getInstance().initFileCache(this.getUIContext().getHostContext(), 256, 256 * 1024 * 1024);

//ui....
      ImageKnifeComponent({
        syncLoad: true,
        imageKnifeOption: ({
          loadSrc: this.fileBean?.thumbnailUrl ? this.fileBean?.thumbnailUrl :
            $r('app.media.ic_new_media_placeholder_dark_512'),
          placeholderSrc: $r('app.media.ic_new_media_placeholder_dark_512'),
          errorholderSrc: $r('app.media.ic_new_media_placeholder_dark_512'),
          border: { radius: 5 },
          customGetImage: custom,
          objectFit: ImageFit.Cover,
          onLoadListener: {
            onLoadStart: () => {
              Logger.d(TAG, "Load start: " + this.fileBean.thumbnailUrl);
            },
            // 这里很坑,请求相机资源不能太频繁,加个判断,如果请求失败就延时重试。
            onLoadFailed: (err) => {
              Logger.d(TAG,
                "Load Failed Reason: " + err + ",fileBean:" + this.fileBean.thumbnailUrl);
            },
            onLoadSuccess: (data, imageData) => {
              Logger.d(TAG,
                "Load Successful: cost " + ",fileBean:" + this.fileBean.thumbnailUrl);
              return data;
            }
          }
        })
      })
        .width(Constants.FULL_WIDTH)
//....
// 自定义下载方法
@Concurrent
export async function custom(context: Context, src: string | PixelMap | Resource,
  headers?: Record<string, Object>): Promise<ArrayBuffer | undefined> {
  return new Promise((resolve, reject) => {
    if (typeof src == "string") {
      const session = rcp.createSession();
      const req = new rcp.Request(src, "GET");
      let reloadNumber = 0;
      const MAX_RETRY = 5;

      const attemptFetch = () => {
        session.fetch(req).then((response) => {
          if (response.statusCode === 200) {
            Logger.d('[CameraMediaList]', `Load success: ${src}`);
            resolve(response.body);
          } else {
            throw new Error(`HTTP ${response.statusCode}`);
          }
        }).catch((err: BusinessError) => {
          if (reloadNumber < MAX_RETRY) {
            reloadNumber++;
            Logger.d("[CameraMediaList]", `Retry ${reloadNumber} for ${src}`);
            setTimeout(attemptFetch, 300 * reloadNumber); // 指数退避
          } else {
            Logger.d('[CameraMediaList]', `Load fail: ${src}`);
            reject(`Request failed after ${MAX_RETRY} retries: ${JSON.stringify(err)}`);
          }
        });
      };

      attemptFetch(); // 启动首次请求
    }
  });
}

posted on 2026-01-13 21:33  带头大哥d小弟  阅读(6)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3