Home > Net >  Forcing runOnUiThread
Forcing runOnUiThread

Time:10-06

I am trying to force a background thread to publish progress, like an AsyncTask, but I am failing miserably. I don't understand why it does not work.

I begin the background thread like this:

new Thread(() -> {
    doInBackground();
}).start();

Inside doInBackground(), I have a loop like this:

...
synchronized (this) {
    ...
    for (int i = 0; i < 100000; i  ) {
        ...
        if (i % 100 == 0) {
           System.out.println("### INNER ### ");
           activity.runOnUiThread(this::onProgressUpdate);
        }
    }
 }

And onProgressUpdate() is simply

onProgressUpdate() {
     System.out.println("-------------");
}

What I expect is that, for each ### INNER ### I see an intercalated -------------. Yet, I see all the ### INNER ### first, and then all the -------------. So the line

activity.runOnUiThread(this::onProgressUpdate);

is not being executed at the moment I want. I tried adding and removing several synchronized (this) everywhere, without success.

What I am doing wrong?

CodePudding user response:

May be you can try something like below for your use case.

  val semaphore = Semaphore(1)
        val mainHandler = Handler(Looper.getMainLooper())
        for (your logic) {
            try {
                semaphore.acquire()
                mainHandler.post {
                    /* do your main ui work*/
                    semaphore.release()
                }
            } catch (e: Exception) {

            } 
        }
        
  • Related