Search code examples
androidmultithreadingprogress-barlinear-search

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

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

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?


Solution

  • 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