Painless threads
In the event you begin an Android application, a thread known to as “primary” is rapidly produced. The primary thread, also known as the UI thread, is essential since it handles dispatching the occasions for that appropriate symbols including enter occasions. It’s also the thread you contact Android symbols on. For example, in case you touch the control button on-screen, the UI thread dispatches the touch event for that widget which sets its pressed condition and posts an invalidate request the big event queue. The UI thread dequeues the request and notifies the widget to redraw itself.
This single thread model can yield poor performance in Android programs that don’t think about the implications. Since everything happens on one thread undertaking extended techniques, like network access or database queries, relevant for this thread will block the entire interface. No event may be sent, including drawing occasions, since the extended operation goes ahead. Inside the user’s perspective, the using seems hung.
If you wish to observe how bad this may look, write an easy application getting some control that creates Thread.
The button will stay within the pressed condition for roughly 2 seconds before returning for the normal condition. At these occasions, it’s very feasible for the client to see the using as slow.
You now know you must avoid extended techniques across the UI thread, you’ll most likely use extra threads (background or worker threads) to accomplish these techniques, and correctly so.
public void onClick(View v)
).start()
In the beginning, this code appears being good strategy to your condition, because it doesn’t block the UI thread. Sadly, it violates really the only thread model: the Android UI toolkit isn’t thread-safe and may constantly be transformed across the UI thread. During this bit of code, the ImageView
is transformed round the worker thread, that may cause really strange problems. Looking for and fixing such bugs can be hard and time-consuming.
Android provides several methods for getting in to the UI thread business threads. You might learn about most of them but this is often a comprehensive list:
- Activity.runOnUiThread(Runnable)
- View.publish(Runnable)
- View.postDelayed(Runnable, extended)
- Handler
These classes and techniques could know about correct our previous code example:
public void onClick(View v) publish(new Runnable()
)
).start()
Sadly, these classes and techniques also makes your code harder and even more hard to read. It might be worse when your implement complex techniques that need frequent UI updates. To cope with this issue, Android 1.5 offers a new utility class, known to as AsyncTask, that simplifies the development of extended-running tasks that require to speak to the interface.
Read Full Story at Android developers blog asynctask
No comments:
Post a Comment