Skip to content Skip to sidebar Skip to footer

How To Run A Algorithm On A Separate Thread While Updating A Progressbar

I have an android linear search algorithm for finding duplicate files and packed it in the function public void startSearch() I was able to run it in a separate thread like this cl

Solution 1:

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:

  • 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
          });
      });   
    
  • 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);
      });
    
  • Import the WorkManager library build a worker for your process and observe the live data result on the main thread: https://developer.android.com/topic/libraries/architecture/workmanager/how-to/intermediate-progress#java

Solution 2:

Complex can have different interpretations. The best way is to have Kotlin Courtines, RxJava with dispatchers.What you have mentioned is a way but if you have multiple threads dependent on each other, then thread management becomes trickier. On professional apps, you would want to avoid the method that you have mentioned because of scalability in future.

Post a Comment for "How To Run A Algorithm On A Separate Thread While Updating A Progressbar"