Android in-depth understanding of the loader mechanism to make apps light

Source: Internet
Author: User

This article is published in parallel, thank you for your attention.

-http://www.jianshu.com/p/385327e35711

Android developers have experienced the improper development of the app UI will cause overdraw, resulting in the app UI rendering too slow, but many people have not heard overload,overload is generally due to developers in the main thread operation time-consuming operation, causing the program to become slow or even the appearance of the ANR phenomenon, Then Android has already provided the perfect solution for this phenomenon, which is the loader mechanism that we are talking about today.

A Loader

The Android Loader (loader) is a newly introduced API from Android 3.0, which mainly completes the function of single-threaded time-consuming data asynchronous loading and updates the UI refreshed automatically when the data has been updated. The industry is also called loader, loader,
Loader use
Loader generally used in activity and fragment asynchronously load data, do not need to restart a thread to perform data loading, asynchronous loading can be used asynctask, but the loader comes with the data result monitoring mechanism, it is convenient to make UI update gracefully.

Functions and Advantages:

Provides the ability to load data asynchronously
Monitor data source changes to update data in real time
Do not load data repeatedly when the activity configuration changes (such as portrait to landscape toggle)
Supports any activity and fragment

Common ways to load time-consuming data
Android developers are aware that the UI thread can no longer perform time-consuming operations, and even in 4.0 of the main thread can no longer access the network, the general load time-consuming operation has the following methods.

1 2B Load

2 Normal load

3 Literary Loading

Why is it that 1 and 2 are not to be taken, we look at the source of loader

**

Two loader realization

**
Loader source under the android.content, it can be seen that its weight is multiple, Loader mechanism, including the loadermanager,loader,loadercallbacks three parts,
Loadermanager to manage our laoder instances, get to initialize, restart a loader,
Loader to perform our asynchronous operations, with start, finish, background and other interface implementations
Loadercallbacks to perform our loader callbacks, mainly binding distribution loader, loading, resetting data, and so on.
Processes such as:

1 Loadermanager

Loadermanager is an abstract class that manages a set of abstract methods that loader the main definition of execution loader, such as:

From the look to see, ta inside the main initialization loader, get restarted, destroy a loader, also contains an internal member variable Loadercallback callback, mainly to facilitate our operation in the upper layer, But it really was done by his implementation class Loadermanagerimpl.
Loadermanagerimpl records a set of loaderinfo information, holding Loadermanager.loadercallbacks, Mloader and other members, responsible for loader and loadercallbacks corresponding callbacks, Internal based on the observer pattern implementation, the source code is not interpreted;

2 Loader

Loader is the class that specifically operates the task, and is responsible for invoking different channels of the data interface, such as databases, contentprovider, files, etc.

From the approximate UML diagram I can understand that loader holds an internal observer, and some registers the listener's internal side, has exposed the state steps of the load operation, has loaded, canceled loading, forced loading, content changes, etc.
In the usual development, Google asked us to provide Laoder sub-class, Asynctaskloader,cursorloader and other sub-categories, the source is not introduced, now say their different points. Cursorloader is the Asynctaskloader subclass, which is responsible for the asynchronous loading of database queries, Asynctaskloader can be used to load all asynchronously.

2.1 Asynctaskloader

  AsyncTaskLoader集成Loader, 除了拥有loader的功能,还有executePendingTask(), dispatchOnCancelled(),onLoadInBackground(),最神奇的是他拥有AsyncTask的实例,并且实现Runnable,这是他能进行异步的原因所在,看代码,对AsyncTask不熟悉的请移步安卓 [《AsyncTask深度解析》](http://blog.csdn.net/sk719887916/article/details/40073747)自我补脑,

The author read the source code, Asynctaskloader has Asynctask, in its own instance after the opening of a thread, self-executependingtask (), This method is actually executing Asynctask's Mtask.executeonexecutor (Mexecutor, (void[]) null), to implement the Asynctaskloader self-monitoring mechanism, Of course, its own polling and transmission is inseparable from handler Mhandler because the entire Android communication is based on the handler (bottom binder), which is no longer analyzed.

2.2 Cursorloader
Cursorloader is a subclass of Asynctaskloader, internal holding forceloadcontentobserver variable, for the realization of data source data update, the execution of loading data operation can not be separated from the query operation, the internal main code:

Three how to use loader

1 Register Loader

 Activity初始化在oncreate()初始化,一个Activity或Fragment中LoaderManager管理一个或多个Loader实例,每个Activity或Fragment只有一个LoaderManager,我们可以在Activity的onCreate()或Fragment的onActivityCreated()里初始化一个Loader。例如:

Getloadermanager (). Initloader (0, NULL, new Dataloadercallback ());

You can see that the Initloader () method above has three parameters:

The first parameter represents the ID of the current loader, which is used to differentiate the loader;

The second parameter represents the arguments supplied to the loader constructor, and the bundle object type
Optional;

The third parameter represents the callback implementation of Loadermanager.loadercallbacks and requires me to implement it myself. ;

The above Initloader () method calls a loader initialized and activated state, the method is dispatched with the following two kinds of results:

If the ID that represents the loader already exists, then the loader created later will be reused directly;

If the ID representing the loader does not exist, Initloader () triggers the loadermanager.loadercallbacks callback Oncreateloader () method to create a loader;

You can see that the Loadermanager.loadercallbacks instance can be associated with loader by using the Initloader () method and is called back when the state of the loader changes. So, if the caller is in its starting state and the requested loader already exists and the data has been generated, then the system immediately calls Onloadfinished () (During the Initloader () call), so you have to take this into account.

Of course, Intiloader () will return a created loader, but you don't have to get a reference to it, because Loademanager will automatically manage the loader life cycle, and you can only do the processing of your own data logic in the life-cycle method that the callback provides.

2 * Implement Loadermanager Callbacks interface *

Loadermanager.loadercallbacks is the callback interface for Loadermanager. The loadermanager.loadercallbacks consists of the following three methods:

Oncreateloader ()
Instantiates and returns a new loader object created to the specified ID, first created as a callback;

Onloadfinished ()
Callback this method after the data load is completed;

Onloaderreset ()
This method is called when the created loader is reset, re-clearly binds the data, reloads the data;

3 Loader usage examples

1 "Initialize Loader

Getloadermanager (). Initloader (0, NULL, new Dataloadercallback ());

2 "Implement callback interface, handle callback

Of course you can also be used to bind Google provides cursorloader, loader created when the time is called, here Use a contentprovider to get the data, so use Cursorloader return data

3 "Inherit loader, data binding, and data adaptation


Here we simulate the construction of a set of data, of course, you can also read files in Loadinbackgruond, access the network, query the database

4 Development

1 for automatic refresh of Contentporvider

When we use Cursorloader, we all think of a situation-how to automatically refresh the current UI when the database changes, and the database notifies through Contentporvider and Contentresolver when the data changes. Then ContentProvider notifies the cursor that the observer data has changed, and the cursor notifies cursorloader that the observer data has changed, and then Cursorloader loads the new data through ContentProvider. After that, call CursorAdapter's Changecursor () to replace the old data display with the new data.

This process is implemented in the following steps:

The cursor data is set to the retrieved Uri (that is, the cursor's setnotificationuri is called in the ContentProvider query () method or in the loader Loadingbackground () method. ) method);

Call Contentresolver's Notifychange () method in ContentProvider's Insert (), update (), delete () method;

We can enjoy the Cursorloader automatic data refresh function through the above two steps, and we can find that the so-called Cursorloader auto-Refresh is also the observer pattern at the beginning of the article, so it is no longer explained too much.
2 "Automatic refresh without using Contentporvider

Four loaders related source flow:

Through the above analysis and analysis of our source code before the figure can be summed up the following conclusions:

A complete data loading process calls Loadermanager's Dostart () method for activity, and then Loadermanager calls Loader's startloading () method, Then the loader dispatching Asynctaskloader Doingbackground () method for time-consuming data loading, and then Asynctaskloader callback Loadermanager The complete data loading method, Then Loadermanager callback the Onloadfinish () method in the callback that we implemented in the activity.

The life cycle of acivity and fragment actively managed the Loadermanager, Each activity uses a arraymap Mallloadermanager to preserve the unique loadermanager of the current activity and its affiliated frament, and when the activity configuration is changed, Activity will save Mallloadermanager before Destory, and when activity is re-created, it will be Onattcach (), OnCreate (), Performstart () in activity. method to recover the Mallloadermanager.

Loadermanager provides the activity with some methods of managing itself, while actively managing the corresponding loader, which encapsulates each loader as a Loadinfo object, while it is responsible for the loader () of the active dispatching Management startloading (), Stoploading (),, Forceload () and other methods.

As the whole activity and fragment actively manage the loader, the release of loader (for example, the cursor close of Cursorloader) does not require us to deal with it, and the loader framework will help us handle it very well, paying special attention to For Cursorloader, when our data source changes, the loader framework re-requests the data for callback flushing by Contentobserver calling Oncontentchanged's Forceload method.

Five summary

Above loader mechanism, source code analysis, expand you will find loader powerful, such as the general display of an Android phone how many applications, loading installed apps, in fact loader can come in handy, see Google on the introduction:
Https://developer.android.com/reference/android/content/AsyncTaskLoader.html.

PS: By the way, the difference between Asynctaskloader and asynctask, read the source we go back to the summary of the two differences, the following:

The most important is to load the data, using loader we do not have to pay attention to when the data changes, do not have to pay attention to the activity of the life cycle, so that the data is not repeated multiple loading situation, to do a load multiple use of the effect, we can take loader to live informed, The depth and breadth of the place also requires the reader's own experience.

**

Instance code download

: Https://github.com/NeglectedByBoss/Loader

**

Android in-depth understanding of loader mechanism to make apps light up

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.