Where Oh Where Has My UI Thread Gone

Sometimes, you may not know if you are currently executing on the UI thread of your application. For example, if you package some of your code in a JAR for others to reuse, you might not know whether your code is being executed on the UI thread or from a background thread.

To help combat this problem, Activity offers runOnUiThread(). This works similar to the post() methods on Handler and View, in that it queues up a Runnable to run on the UI thread, if you are not on the UI thread right now. If you already are on the UI thread, it invokes the Runnable immediately. This gives you the best of both worlds: no delay if you are on the UI thread, yet safety in case you are not.

0 0

Post a comment