Android Loaders, first introduced in Honeycomb (API 11), enable app devs to use a more robust pattern for handling data loading. Data loading is (generally) easy, so why was this needed? To answer that, we first have to take a step back and take a glimpse at an app’s internals.
Android App Context of Execution
It’s very common in Android app development to see references to the “UI thread”. This is the main thread of an application and how the framework notifies the app of events. Take an Activity for example: its lifecycle callbacks as well as UI event callbacks (onTouch(), onClick(), etc.) are all executed on the main thread. Why is this relevant to a data discussion? Two reasons:
While executing a lifecycle or UI callback, all other similar events for your app are waiting to be processed
The current state of your Activity (or Fragment can change and has to be coordinated with background threads
Let’s start with the first item. If the Activity is in the running state (e.g. onResume() has run) and a click listener’s onClick() is called, any additional touch, click or lifecycle changes are queued for processing after the listener returns. If the onClick() takes a long time to complete, the other events are sitting in the queue waiting to be processed. If we have even a moderately sized app there’s a chance we also have a BroadcastReceiver or Service which could have events pending as well. These components are also called on the main thread of our app’s process. It should be pretty obvious how long running operations on the main thread can cause problems. Even small data loads, such as from an internal SQLite database, can take time due to I/O or processing. So, […]