如何在更新进度条时在单独的线程上运行算法 [英] how to run a algorithm on a separate thread while updating a progressBar

查看:51
本文介绍了如何在更新进度条时在单独的线程上运行算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 android 线性搜索算法,用于查找重复文件并将其打包到函数中

I have an android linear search algorithm for finding duplicate files and packed it in the function

public void startSearch()

public void startSearch()

我能够像这样在一个单独的线程中运行它

I was able to run it in a separate thread like this

class ThreadTest extends Thread { 
public void run() {
startSearch()
}
}

但是当我尝试更新该线程中的进度条时,它抛出一个异常并说我的 ui 线程只能触摸它的视图

but when i try to update the progressbar in that thread,it throws a exeption and says i the ui thread can only touch it's views

有没有其他方法可以做到这一点?

is there any other way to do this?

推荐答案

有很多方法可以做到,其中一些已被弃用,一些为您的应用程序增加了不必要的复杂性.我会给你一些我最喜欢的简单选项:

There are so many ways to do it, some of them are deprecated, some add unnecessary complexitiy to you app. I'm gonna give you few simple options that i like the most:

  • 构建一个新线程或线程池,执行繁重的工作并使用主循环程序的处理程序更新 UI:

  • Build a new thread or thread pool, execute the heavy work and update the UI with a handler for the main looper:

  Executors.newSingleThreadExecutor().execute(() -> {

      //Long running operation

      new Handler(Looper.getMainLooper()).post(() -> {
          //Update ui on the main thread
      });
  });   

  • 将结果发布到一个 MutableLiveData 并在主线程上观察:

  • Post the result to a MutableLiveData and observe it on the main thread:

      MutableLiveData<Double> progressLiveData = new MutableLiveData<>();
    
      progressLiveData.observe(this, progress -> {
          //update ui with result
      });
    
      Executors.newSingleThreadExecutor().execute(() -> {
    
          //Long running operation
    
          progressLiveData.postValue(progress);
      });
    

  • 导入 WorkManager 库,为您的进程构建一个工作线程并观察主线程上的实时数据结果:https://developer.android.com/topic/libraries/architecture/workmanager/how-to/intermediate-progress#java>

  • 这篇关于如何在更新进度条时在单独的线程上运行算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆