且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在更新进度条时在单独的线程上运行算法

更新时间:2023-01-13 09:54:40

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

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>