Search code examples
javaandroidviewillegalstateexception

ProgressDialog.setMessage(String) doesn't throw IllegalStateException


I am calling Progressdialog.setMessage(String) method from a worker Thread in the following code but Android doesn't throw IllegalStateException which should say "java.lang.IllegalStateException: Calling View methods on another thread than the UI thread" because I am modifying UI from outside the UI thread which is forbidden in Android.

Here is the runnable of my worker thread as an inner class :

public class HostOnHoldRunnable implements Runnable {

    @Override
    public void run() {
            hostOnHoldDialog.setMessage("Game is on hold because the host paused the app (" + currentTimeLeftForHostOnHoldTimeOut / 1000 + ")");
        }
    }
}

Note: hostOnHoldDialog is the ProgressDialog member of my Activity.

Instead of throwing IllegalStateException, android just doesn't update the UI according to the message.

Is this a bug?

If I use runOnUiThread in the Runnable, everything works fine e.g.

public class HostOnHoldRunnable implements Runnable {

    @Override
    public void run() {
         runOnUiThread(new Runnable() { 
             public void run() { 
            hostOnHoldDialog.setMessage("Game is on hold because the" + 
            " host paused the app (" + 
            currentTimeLeftForHostOnHoldTimeOut / 1000 + ")");

             }
         });
    }
}

Solution

  • Hmm, you see Handler works with Looper for running messages, Handler runs on the UI thread, every View has a handler attached to it, that enables it to post methods/functions on the UI thread, any newly created Thread that wants to run messages or run on the UI thread has to call a Handler or Looper.prepare() which later handler will be implemented. On a multi-threaded app, the use of Handler().post() or Handler().postDelayed() or View.post() or View.postDelayed() or Context.getMainLooper() are all functions that aid you to post on UI thread, so if you call methods with this approach you will not get an exception. so there is not problem or bug here, just read some few lines of the Docs on Looper, Hanlder and View