how to run a algorithm on a separate thread while updating a progressBar
Asked Answered
B

2

0

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?

Bosomy answered 31/10, 2020 at 4:44 Comment(0)
W
2

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

Wasserman answered 31/10, 2020 at 6:47 Comment(0)
D
0

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.

Diminish answered 31/10, 2020 at 6:29 Comment(2)
sorry, using "complex" I meant that the algorithm is too big to run in the UI thread the app freezes when it's in UI threadBosomy
if you mean time taking, then it does not matter what you use because its not running on UI thread.you can start your thread from foreground service if you still wanna run when you r exited from the applicatiob.if multiple threads ate competing for same resources in your codem preferusing coroutines or rxjava .Since background service has limitation from adrod 8.0 and you dont wanna use foreground service , then instead of service you can use wORKManager API if your task is not urgent.Diminish

© 2022 - 2024 — McMap. All rights reserved.