Android – Multithreading in a UI environment

Why do we need multithreading in Android applications? Let’s say you want to do a very long operation when the user pushes a button. If you are not using another thread, it will look something like this: What will happen? The UI freezes. This is a really bad UI experience. The program may even crash. The problem in using threads in a UI environment So what will happen if we use a Thread for a long running operation. Let’s try a simple example: The result in this case is that the application crashes. 12-07 16:24:29.089: ERROR/AndroidRuntime(315): FATAL EXCEPTION: Thread-8 12-07 16:24:29.089: ERROR/AndroidRuntime(315): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. 12-07 16:24:29.089: ERROR/AndroidRuntime(315): at … Clearly the Android OS wont let threads other than the main thread change UI elements. But why? Android UI toolkit, like many other UI environments, is not thread-safe. The solution A queue of messages. Each message is a job to be handled. Threads can add messages. Only a single thread pulls messages one by one from the queue. The same solution was implemented in swing (Event dispatching thread and SwingUtilities.invokeLater() ) Handler The Handler is the middleman between a Continue reading Android – Multithreading in a UI environment