On Android, there is a primary thread which runs all UI stuff. If a GUI operation is ran in a different thread, it just won't work, and may throw an error. If you block this thread with too much processing... well... bad things happen. Due to this design, you have to push all UI operations to this main thread using Looper.run().
Runnables pushed to this thread are always ran in FIFO execution order, which is a useful guarantee for programming.
So I decided to get smart and create the following function to add asynchronous calls that needed to be run on the primary thread. It takes a Runnable and either runs it immediately, if already on the Primary thread, or otherwise adds it to the Primary Thread’s queue.
//Run a function on primary threadpublicstaticvoid RunOnPrimary(RunnableR)
//Start commenting here so that items are always added to the queue, forcing in-order processesingif(Looper.myLooper()==Looper.getMainLooper())
else//End commenting herenewHandler(Looper.getMainLooper()).post(R);
I found it kind of irritating that I had to add actions to the queue when it could have been run immediately on the current thread, but oh well, I didn’t really have a choice if I want to make sure everything is always run in order across the system.
To add comments, please go to the forum page for this post (guest comments are allowed for the Projects, Posts, and Updates Forums). Comments are owned by the user who posted them. We accept no responsibility for the contents of these comments.