当前位置: 首页 > article >正文

安卓端使用线程下载文件卡滞

需求:从阿里云oss下载大量的图片(4000+)到手机的内部存储

  /// <summary>
    /// 指定要下载的文件列表
    /// </summary>
    /// <param name="aliyunFile">阿里云上要下载文件所在文件夹</param>
    /// <param name="saveFile">下载文件存储文件夹(Application.streamingAssetsPath下)</param>
    /// <param name="completedCallback">下载完成回调事件</param>
    /// <param name="needUI">下载过程中是否需要展示UI</param>
    public void StartDownloadFileList(List<string> downloadFileList, string saveFile, Action completedCallback = null, bool needUI = true)
    {
        if (NetworkStatus.IsNetNotReachable())
        {
            TipsManager.Instance.ShowTip("当前设备网络未连接,请检查网络");
            return;
        }

        Debug.Log(TAG + "StartDownloadFileList by list");
        if (needUI)
        {
            StatusText.text = "资源下载中...";
        }
        curDownloadIndex = lastDownloadIndex = 0;
        if (completedCallback != null)
        {
            DownloadCompletedCallback = completedCallback;
        }
        ShowDownloadUI = needUI;
        allFileList = downloadFileList;
        if (allFileList.Count > 0)
        {
            DownloadSingleObj(saveFile, allFileList[curDownloadIndex]);
        }
    }


 /// <summary>
    /// 下载单个文件
    /// </summary>
    /// <param name="targetFile">本地存储路径文件夹</param>
    /// <param name="filePath">oss上文件存储路径</param>
    /// <param name="savePath">直接指定的存储路径</param>
    public void DownloadSingleObj(string targetFile, string filePath, string savePath = "")
    {
        Debug.Log("下载单个文件: " + filePath);
        string dir = StringTranslation.GetStoragePath() + "/" + targetFile + "/" + filePath.Substring(0, filePath.LastIndexOf("/"));
        thread = new Thread(GetObject);
        if (string.IsNullOrEmpty(savePath))
        {
            FileHelper.CreateDirectory(dir);
            GetObjectByThread(targetFile, filePath, StringTranslation.GetStoragePath() + "/" + targetFile + "/" + filePath);
        }
        else
        {
            GetObjectByThread(targetFile, filePath, savePath);
        }
    }

  private void GetObjectByThread(string targetFile, string filePath, string savePath)
    {
        this.targetFile = targetFile;
        this.filePath = filePath;
        this.savePath = savePath;
        //thread = new Thread(GetObject);
        thread.Start();
    }

 private void GetObject()
    {
        try
        {
            GetObjectRequest getObjectRequest = new GetObjectRequest(AliyunConfig.BucketName, filePath);
            getObjectRequest.StreamTransferProgress += StreamProcess;
            OssObject result = client.GetObject(getObjectRequest);
            using (var resultStream = result.Content)
            {
                string directory = savePath.Substring(0, savePath.LastIndexOf("/"));
                FileHelper.CreateDirectory(directory);

                using (var fs = File.Open(savePath, FileMode.OpenOrCreate))
                {
                    int length = (int)resultStream.Length;
                    byte[] bytes = new byte[length];
                    do
                    {
                        length = resultStream.Read(bytes, 0, length);
                        fs.Write(bytes, 0, length);

                    } while (length != 0);
                }
                print(string.Format("第{0}个下载成功 。", curDownloadIndex + 1));

                if (curDownloadIndex < allFileList.Count - 1)
                {
                    {
                        curDownloadIndex++;
                    }
                    DownloadSingleObj(targetFile, allFileList[curDownloadIndex]);
                }
                else
                {
                    Loom.QueueOnMainThread(() =>
                    {
                        print("所有文件下载完毕 " + (curDownloadIndex + 1));
                        if (ShowDownloadUI)
                        {
                            StatusText.text = "资源下载完毕";
                        }
                        DownloadCompletedCallback?.Invoke();
                        DownloadCompletedCallback = null;
                        CancelInvoke("CheckDownloadProcess");
                    });
                    thread.Abort();
                }
            }
        }
        catch (OssException e)
        {
            print("进度下载文件出错:" + e.Message);
        }
    }

问题:下载一部分之后,下载进度会停止;

解决办法: 检测下载进度是否停止,如果停止,则重启线程继续下载;

    IEnumerator RestartThread()
    {
        thread.Abort();
        yield return new WaitForSeconds(Time.deltaTime);
        thread = new Thread(GetObject);
        thread.Start();
        DownloadSingleObj(targetFile, allFileList[curDownloadIndex]);
    }

    InvokeRepeating("CheckDownloadProcess", 0, 3);


http://www.kler.cn/a/508159.html

相关文章:

  • Linux网络 TCP socket
  • 【机器学习实战入门】使用OpenCV和Keras的驾驶员疲劳检测系统
  • Oracle 批量投入数据方法总结
  • WPF实现动态四宫格布局
  • QT 如何禁止QComboBox鼠标滚轮
  • 森林网络部署,工业4G路由器实现林区组网远程监控
  • 基于javaweb的SpringBoot景区旅游管理系统设计和实现(源码+文档+部署讲解)
  • Biotin sulfo-N-hydroxysuccinimide ester ;生物素磺基-N-羟基琥珀酰亚胺酯;生物素衍生物;190598-55-1
  • [Azure] 如何解决个人账号无法直接登录的问题:利用曲线救国方法访问Speech Studio
  • 利用爬虫获取某学习软件的考试题库(带源码)
  • LLM(大语言模型)支撑下的传统工作流转型发展为AI工作流
  • linux的用户管理和权限设置相关命令
  • 工业视觉5-工业视觉选型
  • C++(二十一)
  • DNS服务学习
  • 基于微信小程序教学辅助系统设计与实现(LW+源码+讲解)
  • ChatGPT升级AI私人助理功能:新增定时播报全网热点与定制每日学习健身计划
  • Spring Boot中Tomcat配置
  • AF3 TriangleMultiplicativeUpdate类代码解读
  • CVPR 2024 图像处理方向总汇(图像去噪、图像增强、图像分割和图像恢复等)
  • ChatGPT结合Excel辅助学术数据分析详细步骤分享!
  • 洛谷 P2392 kkksc03考前临时抱佛脚 刷题笔记 dfs
  • 先进制造aps专题二十七 西门子opcenter aps架构分析
  • 考研数据结构线性表之顺序表
  • Azure Synapse Dedicated SQL Pool通过配置选项和参数优化性能
  • python http server运行Angular 单页面路由时重定向,解决404问题