Android进阶——借助Loader机制以一种更优美的方式异步加载数据(一)
引言
无论是App抑或是PC应用都离不开数据加载这个主题,没有了数据一切都将华而不实毫无意义,而Android由于其特殊性使得对数据的加载处理要求更为严格些,如果使用不当会造成OverDraw导致APP UI渲染过慢和OverLoad(OverLoad通常是由于开发者在主线程操作耗时操作)导致程序变慢甚至出现的ANR的现象,庆幸的是Android早已为这种现象提供了的解决方案,AsyncTask大家都应该很熟悉,但是在针对一些频繁的数据更新的时候使用起来不那么优雅,今天给大家说的是Android3.0提供的的Loader机制——它提供了一套在UI的主线程中异步加载数据的框架。使用Loaders可以非常简单的在Activity或者Fragment中异步加载数据,一般适用于大量的数据查询,或者需要经常修改并及时展示的数据显示到UI上,这样可以避免查询数据的时候,造成主线程的卡顿。
一、Loader机制概述
Loader直接继承Object负责执行异步加载数据的实体类(A class that performs asynchronous loading of data),拥有一个直接子类AsyncTaskLoader< D >和一个继承AsyncTaskLoader< D >的间接子类CursorLoader,而且在他们处于活动状态时应该监听对应的数据源且在内容发生变化时传递新的数据。(While Loaders are active they should monitor the source of their data and deliver new results when the contents change)。
1、Loader机制中通常会涉及到以下角色
Loader、LoaderManager、LoaderManager.LoaderCallbacks、AsyncTaskLoader、CursorLoader和自定义Loader,详细分工见下文。
2、Loader在尤其是在线程中使用时注意事项
使用Loader的客户端应该从其进程的主线程(即指Activity 回调 和其他事件发生的线程,那不就是主线程么) 执行 任何对Loader的调用(即线程活动回调和其他事件发生),通俗来说就是对于Loader的使用应该再主线程mainThread中。
Loader的子类通常在另一个独立的子线程会执行他们自己的任务(这点特性应该是和AsyncTask机制差不多),但是在执行完耗时操作之后,数据的传递应当在主线程完成。
使用Loader时,通常使用其子类,而子类必须重写Loader中的 onStartLoading(), onStopLoading(), onForceLoad()和 onReset()四个方法,其他方法根据业务需要重写AsyncTaskLoader< D >中的相关方法。
二、Loader
Loader一个用于执行异步加载数据的抽象类,是所有加载器的基类(系统目前已实现的子类有AsyncTaskLoader、CursorLoader),可以监视数据源的改变和在内容改变后,以新数据的内容改变UI的展示。它是一个Loader的抽象接口,所有需要实现的Loader功能的类都需要实现这个接口,但是如果需要自己开发一个装载机的话,一般并不推荐继承Loader接口,而是继承它的子类AsyncTaskLoader(一个以AsyncTask框架执行的异步加载)。一旦加载器被激活,它们将监视它们的数据源并且在数据改变时发送新的结果将新的数据发布到UI上。Loaders使用Cursor加载数据,在更改Cursor的时候,会自动重新连接到最后配置的Cursor中读取数据,因此不需要重新查询数据。
再从Loader 源码结构来看,Loader设计逻辑很简单:首先是定义了OnLoadCanceledListener< D >(用于检测Loader在加载数据完成之前,是否已被取消)、OnLoadCompleteListener< D>(用于检测Loader在加载数据工作是否已经完成)两个接口用于监听Loader的工作状态以及一个内部类ForceLoadContentObserver(当观察者被告知它时,负责将它连接到Loader以使加载器重新加载其数据),并开放了对应的回调方法用于给用户实现具体的业务逻辑,这本质上就是个回调的思想,然后既然有监听接口就需要有对应的方法去初始化,注意看源码onStartLoading(), onStopLoading(), onForceLoad()和 onReset()四个方法的实现是空的,这也是为什么继承Loader的时候必须重写的原因之一。
public class Loader<D> { int mId; OnLoadCompleteListener mListener; OnLoadCanceledListener mOnLoadCanceledListener; /** * An implementation of a ContentObserver that takes care of connecting * it to the Loader to have the loader re-load its data when the observer * is told it has changed. You do not normally need to use this yourself; * it is used for you by {@link CursorLoader} to take care of executing * an update when the cursor's backing data changes. */ public final class ForceLoadContentObserver extends ContentObserver { public ForceLoadContentObserver() { super(new Handler()); } @Override public boolean deliverSelfNotifications() { return true; } @Override public void onChange(boolean selfChange) { onContentChanged(); } } /** * Interface that is implemented to discover when a Loader has finished * loading its data. You do not normally need to implement this yourself; * it is used in the implementation of {@link android.support.v4.app.LoaderManager} * to find out when a Loader it is managing has completed so that this can * be reported to its client. This interface should only be used if a * Loader is not being used in conjunction with LoaderManager. */ public interface OnLoadCompleteListener { /** * Called on the thread that created the Loader when the load is complete. * * @param loader the loader that completed the load * @param data the result of the load */ public void onLoadComplete(Loader loader, D data); } /** * Interface that is implemented to discover when a Loader has been canceled * before it finished loading its data. You do not normally need to implement * this yourself; it is used in the implementation of {@link android.support.v4.app.LoaderManager} * to find out when a Loader it is managing has been canceled so that it * can schedule the next Loader. This interface should only be used if a * Loader is not being used in conjunction with LoaderManager. */ public interface OnLoadCanceledListener { /** * Called on the thread that created the Loader when the load is canceled. * * @param loader the loader that canceled the load */ public void onLoadCanceled(Loader loader); } /** * Stores away the application context associated with context. * Since Loaders can be used across multiple activities it's dangerous to * store the context directly; always use {@link #getContext()} to retrieve * the Loader's Context, don't use the constructor argument directly. * The Context returned by {@link #getContext} is safe to use across * Activity instances. * * @param context used to retrieve the application context. */ public Loader(Context context) { mContext = context.getApplicationContext(); } /** * Sends the result of the load to the registered listener. Should only be called by subclasses. * Must be called from the process's main thread. * @param data the result of the load */ public void deliverResult(D data) { if (mListener != null) { mListener.onLoadComplete(this, data); } } /** * Informs the registered {@link OnLoadCanceledListener} that the load has been canceled. * Should only be called by subclasses. * * Must be called from the process's main thread. */ public void deliverCancellation() { if (mOnLoadCanceledListener != null) { mOnLoadCanceledListener.onLoadCanceled(this); } } /** * Registers a class that will receive callbacks when a load is complete. * The callback will be called on the process's main thread so it's safe to * pass the results to widgets. * * Must be called from the process's main thread. */
public void registerListener(int id, OnLoadCompleteListener listener) { if (mListener != null) { throw new IllegalStateException("There is already a listener registered"); } mListener = listener; mId = id; } /** * Remove a listener that was previously added with {@link #registerListener}. * * Must be called from the process's main thread. */ public void unregisterListener(OnLoadCompleteListener listener) { if (mListener == null) { throw new IllegalStateException("No listener register"); } if (mListener != listener) { throw new IllegalArgumentException("Attempting to unregister the wrong listener"); } mListener = null; } /** * Registers a listener that will receive callbacks when a load is canceled. * The callback will be called on the process's main thread so it's safe to * pass the results to widgets. * * Must be called from the process's main thread. * * @param listener The listener to register. */ public void registerOnLoadCanceledListener(OnLoadCanceledListener listener) { if (mOnLoadCanceledListener != null) { throw new IllegalStateException("There is already a listener registered"); } mOnLoadCanceledListener = listener; } /** * Unregisters a listener that was previously added with * {@link #registerOnLoadCanceledListener}. * * Must be called from the process's main thread. * * @param listener The listener to unregister. */ public void unregisterOnLoadCanceledListener(OnLoadCanceledListener listener) { if (mOnLoadCanceledListener == null) { throw new IllegalStateException("No listener register"); } if (mOnLoadCanceledListener != listener) { throw new IllegalArgumentException("Attempting to unregister the wrong listener"); } mOnLoadCanceledListener = null; } /** * This function will normally be called for you automatically by * {@link android.support.v4.app.LoaderManager} when the associated fragment/activity * is being started. When using a Loader with {@link android.support.v4.app.LoaderManager}, * you must not call this method yourself, or you will conflict * with its management of the Loader. * * Starts an asynchronous load of the Loader's data. When the result * is ready the callbacks will be called on the process's main thread. * If a previous load has been completed and is still valid * the result may be passed to the callbacks immediately. * The loader will monitor the source of * the data set and may deliver future callbacks if the source changes. * Calling {@link #stopLoading} will stop the delivery of callbacks. * * This updates the Loader's internal state so that * {@link #isStarted()} and {@link #isReset()} will return the correct * values, and then calls the implementation's {@link #onStartLoading()}. * *
Must be called from the process's main thread. */
public final void startLoading() { mStarted = true; mReset = false; mAbandoned = false; onStartLoading(); } /** * Subclasses must implement this to take care of loading their data, * as per {@link #startLoading()}. This is not called by clients directly, * but as a result of a call to {@link #startLoading()}. */ protected void onStartLoading() { } /** * Attempt to cancel the current load task. * Must be called on the main thread of the process. * * Cancellation is not an immediate operation, since the load is performed * in a background thread. If there is currently a load in progress, this * method requests that the load be canceled, and notes this is the case; * once the background thread has completed its work its remaining state * will be cleared. If another load request comes in during this time, * it will be held until the canceled load is complete. * @return Returns false if the task could not be canceled, * typically because it has already completed normally, or * because {@link #startLoading()} hasn't been called; returns * true otherwise. When true is returned, the task * is still running and the {@link OnLoadCanceledListener} will be called * when the task completes. */
public boolean cancelLoad() { return onCancelLoad(); } /** * Force an asynchronous load. Unlike {@link #startLoading()} this will ignore a previously * loaded data set and load a new one. This simply calls through to the * implementation's {@link #onForceLoad()}. You generally should only call this * when the loader is started -- that is, {@link #isStarted()} returns true. * Must be called from the process's main thread. */
public void forceLoad() { onForceLoad(); } /** * Subclasses must implement this to take care of requests to {@link #forceLoad()}. * This will always be called from the process's main thread. */ protected void onForceLoad() { } /** * Take the current flag indicating whether the loader's content had * changed while it was stopped. If it had, true is returned and the * flag is cleared. */ public boolean takeContentChanged() { boolean res = mContentChanged; mContentChanged = false; mProcessingChange |= res; return res; } /** * Commit that you have actually fully processed a content change that * was returned by {@link #takeContentChanged}. This is for use with * {@link #rollbackContentChanged()} to handle situations where a load * is cancelled. Call this when you have completely processed a load * without it being cancelled. */ public void commitContentChanged() { mProcessingChange = false; } /** * Report that you have abandoned the processing of a content change that * was returned by {@link #takeContentChanged()} and would like to rollback * to the state where there is again a pending content change. This is * to handle the case where a data load due to a content change has been * canceled before its data was delivered back to the loader. */ public void rollbackContentChanged() { if (mProcessingChange) { onContentChanged(); } } /** * Called when {@link ForceLoadContentObserver} detects a change. The * default implementation checks to see if the loader is currently started; * if so, it simply calls {@link #forceLoad()}; otherwise, it sets a flag * so that {@link #takeContentChanged()} returns true. * Must be called from the process's main thread. */
public void onContentChanged() { if (mStarted) { forceLoad(); } else { // This loader has been stopped, so we don't want to load // new data right now... but keep track of it changing to // refresh later if we start again. mContentChanged = true; } } public void deliverResult(D data) { if (mListener != null) { mListener.onLoadComplete(this, data); } } //部分代码略...}
3、Loader 主要公共成员方法
方法名 | 说明 |
---|---|
void abandon() | 当LoaderManager 重新启动一个Loader的时候这个方法被LoaderManager 自动调用 |
boolean cancelLoad() | 尝试去中止当前的load任务,返回true则中止成功,必须在主线程调用 |
void deliverCancellation() | 通知绑定的OnLoadCanceledListener Loader已经取消了,实际上就是调用onCanceled方法 |
void deliverResult(D data) | 通知绑定的OnLoadCompleteListener Loader已经完成了,实际上就是调用onLoadComplete方法 |
void registerListener(int id, OnLoadCompleteListener< D> listener) | 注册Loader完成监听 |
void registerOnLoadCanceledListener(OnLoadCanceledListener< D> listener) | 注册Loader完成取消监听 |
二、LoaderManager和LoaderManager.LoaderCallbacks
LoaderManager是Activity 或 Fragment 相关联的的抽象类,对Loader的操作的抽象和封装,用于管理一个或多个 Loader 实例,简单来说和其他XxxxManager一样角色很简单就是负责管理Loader,同时为了与客户端进行交互定义了LoaderManager.LoaderCallbacks回调接口,至于LoaderManager的具体实现是在LoaderManagerImpl 里(由于篇幅问题不便贴出)主要方便我们在上层写回调实现累操作,但真正是由他的实现类LoaderManagerImpl去完成操作的,LoaderManagerImpl 记录着一组LoaderInfo信息,(如果看过源码电话会发现类似的东西:Activity也是拥有activityInfo一样,只不过通过Activityrecord来记录,类比着阅读源码你会发现思想才是最重要的),同时持有LoaderManager.LoaderCallbacks, mLoader等成员,负责对Loader和LoaderCallbacks的对应回调,内部基于观察者模式实现,这就是核心思想。
LoaderManager主要方法 | 说明 |
---|---|
Loader< D > initLoader(int id,Bundle bundle,LoaderCallbacks< D > callback) | 初始化一个Loader,并注册回调事件,Loader的唯一标识Id,若指定的Id已存在,则将重复使用上次创建的加载器;若Id不存在则,则initLoader() 将触发 LoaderManager.LoaderCallbacks 方法 onCreateLoader()。并在这个方法里实现实例化并返回已创建的 Loader,但我们不必捕获其引用。LoaderManager 将自动管理加载器的生命周期。 *LoaderManager 将根据需要启动和停止加载,并维护加载器的状态及其相关内容而参数bundle 作为可选参数提供给构造方法,如果一个Loader已经存在(或者一个新的Loader没有必要创建)该参数将被忽略,所以传如null也可,通常应该在组件初始化时使用这个函数,以确保它所依赖的Loader被创建 |
Loader< D > restartLoader(int id,Bundle bundle,LoaderCallbacks< D > callback) | 重新启动或创建一个Loader,并注册回调事件,在这个LoaderManager里开启新的Loader或者重新启动一个已经存在的Loader且在当前Activity或Fragment已经启动的情况下开始执行加载 |
Loader< D > getLoader(int id) | 返回给定Id的Loader,如果没有找到则返回Null。 |
void destroyLoader(int id) | 根据指定Id,停止和销毁Loader。 |
其中id参数,这个Id是Loader的标识,因为LoaderManager可以管理一个或多个Loader,所以必须通过这个Id参数来唯一确定一个Loader。而InitLoader()、restartLoader()中的bundle参数,传递一个Bundle对象给LoaderCallbacks中的onCreateLoader()去获取。
/**以下是5.0系统源码LoaderManagerImpl是LoaderManger的一个内部类,而6.0之后就把定义和实现分开了PS:英文注释值得一看*/public abstract class LoaderManager { /** * Callback interface for a client to interact with the manager. */ public interface LoaderCallbacks { /** * @return Return a new Loader instance that is ready to start loading. */ public Loader onCreateLoader(int id, Bundle args); /** * Called when a previously created loader has finished its load. Note * that normally an application is not allowed to commit fragment * transactions while in this call, since it can happen after an * activity's state is saved. See {@link FragmentManager#beginTransaction() * FragmentManager.openTransaction()} for further discussion on this. * * This function is guaranteed to be called prior to the release of * the last data that was supplied for this Loader. At this point * you should remove all use of the old data (since it will be released * soon), but should not do your own release of the data since its Loader * owns it and will take care of that. The Loader will take care of * management of its data so you don't have to. In particular: * * The Loader will monitor for changes to the data, and report * them to you through new calls here. You should not monitor the * data yourself. For example, if the data is a {@link android.database.Cursor} * and you place it in a {@link android.widget.CursorAdapter}, use * the {@link android.widget.CursorAdapter#CursorAdapter(android.content.Context, * android.database.Cursor, int)} constructor without passing * in either {@link android.widget.CursorAdapter#FLAG_AUTO_REQUERY} * or {@link android.widget.CursorAdapter#FLAG_REGISTER_CONTENT_OBSERVER} * (that is, use 0 for the flags argument). This prevents the CursorAdapter * from doing its own observing of the Cursor, which is not needed since * when a change happens you will get a new Cursor throw another call * here. *
The Loader will release the data once it knows the application * is no longer using it. For example, if the data is * a {@link android.database.Cursor} from a {@link android.content.CursorLoader}, * you should not call close() on it yourself. If the Cursor is being placed in a * {@link android.widget.CursorAdapter}, you should use the * {@link android.widget.CursorAdapter#swapCursor(android.database.Cursor)} * method so that the old Cursor is not closed. * * * @param loader The Loader that has finished. * @param data The data generated by the Loader. */ public void onLoadFinished(Loader loader, D data); /** * Called when a previously created loader is being reset, and thus * making its data unavailable. The application should at this point * remove any references it has to the Loader's data. * * @param loader The Loader that is being reset. */ public void onLoaderReset(Loader loader); } /** * Ensures a loader is initialized and active. If the loader doesn't * already exist, one is created and (if the activity/fragment is currently * started) starts the loader. Otherwise the last created * loader is re-used. * * In either case, the given callback is associated with the loader, and * will be called as the loader state changes. If at the point of call * the caller is in its started state, and the requested loader * already exists and has generated its data, then * callback {@link LoaderCallbacks#onLoadFinished} will * be called immediately (inside of this function), so you must be prepared * for this to happen. * * @param id A unique identifier for this loader. Can be whatever you want. * Identifiers are scoped to a particular LoaderManager instance. * @param args Optional arguments to supply to the loader at construction. * If a loader already exists (a new one does not need to be created), this * parameter will be ignored and the last arguments continue to be used. * @param callback Interface the LoaderManager will call to report about * changes in the state of the loader. Required. */
public abstract Loader initLoader(int id, Bundle args, LoaderManager.LoaderCallbacks callback); /** * Starts a new or restarts an existing {@link android.content.Loader} in * this manager, registers the callbacks to it, * and (if the activity/fragment is currently started) starts loading it. * If a loader with the same id has previously been * started it will automatically be destroyed when the new loader completes * its work. The callback will be delivered before the old loader * is destroyed. * * @param id A unique identifier for this loader. Can be whatever you want. * Identifiers are scoped to a particular LoaderManager instance. * @param args Optional arguments to supply to the loader at construction. * @param callback Interface the LoaderManager will call to report about * changes in the state of the loader. Required. */ public abstract Loader restartLoader(int id, Bundle args, LoaderManager.LoaderCallbacks callback); /** * Stops and removes the loader with the given ID. If this loader * had previously reported data to the client through * {@link LoaderCallbacks#onLoadFinished(Loader, Object)}, a call * will be made to {@link LoaderCallbacks#onLoaderReset(Loader)}. */ public abstract void destroyLoader(int id); /** * Return the Loader with the given id or null if no matching Loader * is found. */ public abstract Loader getLoader(int id); /** * Print the LoaderManager's state into the given stream. * * @param prefix Text to print at the front of each line. * @param fd The raw file descriptor that the dump is being sent to. * @param writer A PrintWriter to which the dump is to be set. * @param args Additional arguments to the dump request. */ public abstract void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args); /** * Control whether the framework's internal loader manager debugging * logs are turned on. If enabled, you will see output in logcat as * the framework performs loader operations. */ public static void enableDebugLogging(boolean enabled) { LoaderManagerImpl.DEBUG = enabled; }}class LoaderManagerImpl extends LoaderManager { static final String TAG = "LoaderManager"; static boolean DEBUG = false; // These are the currently active loaders. A loader is here // from the time its load is started until it has been explicitly // stopped or restarted by the application. final SparseArray mLoaders = new SparseArray(0); // These are previously run loaders. This list is maintained internally // to avoid destroying a loader while an application is still using it. // It allows an application to restart a loader, but continue using its // previously run loader until the new loader's data is available. final SparseArray mInactiveLoaders = new SparseArray(0); final String mWho; Activity mActivity; boolean mStarted; boolean mRetaining; boolean mRetainingStarted; boolean mCreatingLoader; final class LoaderInfo implements Loader.OnLoadCompleteListener<Object>, Loader.OnLoadCanceledListener
LoaderManager.LoaderCallbacks重要的三个回调方法:
LoaderManager.LoaderCallbacks 是一个支持客户端与 LoaderManager 交互的回调接口。Loader(特别是 CursorLoader)在停止运行后,仍需保留其数据。这样,应用即可保留 Activity 或Fragment的 onStop() 和 onStart() 方法中的数据。当用户返回应用时,无需等待它重新加载这些数据
public Loader< D > onCreateLoader(int id, Bundle args)——当初始化并且返回指定id的新的Loader之时被调用,第一个参数为Loader的id,第二个参数作为可选参数提供给构造方法,如果一个Loader已经存在(或者一个新的Loader没有必要创建)该参数将被忽略,所以传如null也可。其实这就对应着LoaderManager的initLoader方法中的参数。
public void onLoadFinished(Loader< D > loader, D data)——当前一个Loader完成load任务之时被调用,需要注意的是通常是不允许在这个方法里提交Fragment事务的(因为这个方法有可能在Activity状态保存后触发),这个方法被优先调用来确保这个Loader的最后一条数据被释放。
public void onLoaderReset(Loader< D > loader)——当前一个Loader被重置时被调用,此时Loader的数据不可用,通常可以在这里删除该Loader数据的所有引用。
三、CursorLoader及简单应用
Android中还提供了一个CursorLoader类继承自AsyncTaskLoader,一个异步的加载游标类型数据的类,通过ContentResolver的标准查询并返回一个Cursor。以一种标准的方式查询Cursor,CursorLoader类有两个构造函数,推荐使用第二个,因为使用第一个构造函数,需要还需要通过CursorLoader提供的一些了getXxx()方法设置对应的属性:
CursorLoader(Context context)
CursorLoader(Context context,Uri uri,String[] projection,String selection ,String[] selectionArgs,String sortOrder)
比如说在Android中AdapterView类控件展示数据的时候都需要使用一个Adapter适配器,而Loader一般返回可以返回任何类型的数据(只需要在回调接口的泛型中指定即可),下面将展示通过CursorLoader快速完成手机通讯录的展示,先简单了解下SimpleCursorAdapter的基本用法,首先可以通过SimpleCursorAdapter(Context context,int layout,Cursor c,String[] from,int[] to,int flags).其中参数flags是一个标识,标识当数据改变调用onContentChanged()的时候,是否通知ContentProvider数据的改变,如果无需监听ContentProvider的改变,则可以传0。对于SimpleCursorAdapter适配器的Cursor的改变,可以使用SimpleCursorAdapter.swapCursor(Cursor)方法,它会与旧的Cursor互换,并且返回旧的Cursor。
/** * Auther: Crazy.Mo * DateTime: 2018/1/3 9:47 * Summary: */public class LoaderActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> ,SearchView.OnQueryTextListener{ private ListView listview; private SimpleCursorAdapter adapter; private LoaderManager manager; private int loaderId=100; private String curFilter; private SearchView searchView; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_loader); init(); } @Override protected void onResume() { super.onResume(); //使用android自带的布局资源simple_list_item_1, android.R.id.text1 为simple_list_item_1中TextView的Id构造SimpleCursorAdapter adapter= new SimpleCursorAdapter(LoaderActivity.this,android.R.layout.simple_list_item_1, null, new String[] { ContactsContract.Contacts.DISPLAY_NAME}, new int[] { android.R.id.text1 },0); listview.setAdapter(adapter); } private void init(){ listview= (ListView) findViewById(R.id.lv_contacts); searchView= (SearchView) findViewById(R.id.search_contacts); searchView.setOnQueryTextListener(this); manager=getLoaderManager();//1、获取LoaderManager实例 manager.initLoader(loaderId,null,this);//2、使用LoaderManager实例初始化创建Loader确保Loader处于活跃状态,通常在组件初始化时使用,以确保它所依赖的Loader被创建 } @Override public Loader onCreateLoader(int i, Bundle bundle) { Uri baseUri; if (curFilter != null) { baseUri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_FILTER_URI, Uri.encode(curFilter)); } else { baseUri = ContactsContract.Contacts.CONTENT_URI; } //3、实现LoaderManager.LoaderCallbacks接口并在onCreateLoader方法中真正用于数据加载的Loader String select = "((" + ContactsContract.Contacts.DISPLAY_NAME + " NOTNULL) AND (" + ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1) AND (" + ContactsContract.Contacts.DISPLAY_NAME + " != '' ))"; return new CursorLoader(this, baseUri,CONTACTS_SUMMARY_PROJECTION, select, null, ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC"); } @Override public void onLoadFinished(Loader loader, Cursor data) { //4、接收到Loader加载完毕之后传回的数据刷新SimpleCursorAdapter adapter.swapCursor(data); } @Override public void onLoaderReset(Loader loader) { adapter.swapCursor(null); } static final String[] CONTACTS_SUMMARY_PROJECTION = new String[]{ ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.Contacts.CONTACT_STATUS, ContactsContract.Contacts.CONTACT_PRESENCE, ContactsContract.Contacts.PHOTO_ID, ContactsContract.Contacts.LOOKUP_KEY, }; @Override public boolean onQueryTextSubmit(String query) { return true; } @Override public boolean onQueryTextChange(String newText) { curFilter=!TextUtils.isEmpty(newText) ? newText : null; getLoaderManager().restartLoader(0, null, this); return true; }}
四、AsyncTaskLoader
AsyncTaskLoader作为Loader的唯一直接子类,承担着具体执行异步加载数据操作(Abstract Loader that provides an AsyncTask to do the work),由于AsyncTaskLoader是一个抽象类不能直接使用,所以在真正使用的时候是使用其子类,比如说CursorLoader(一个查询ContentResolver并返回一个Cursor的加载器),就是系统提供专门用于处理与游标相关的数据异步加载的情景。(自定义Loader详细应用见下篇文章。)
public abstract class AsyncTaskLoader extends Loader { public AsyncTaskLoader(Context context) { super((Context)null); throw new RuntimeException("Stub!"); } public void setUpdateThrottle(long delayMS) { throw new RuntimeException("Stub!"); } protected void onForceLoad() { throw new RuntimeException("Stub!"); } protected boolean onCancelLoad() { throw new RuntimeException("Stub!"); } public void onCanceled(D data) { throw new RuntimeException("Stub!"); } /** *调用工作线程上执行真正的load操作并返回load的数据 */ public abstract D loadInBackground(); protected D onLoadInBackground() { throw new RuntimeException("Stub!"); } /** *在主线程中被调用来中止正在进行的load操作,重写这个方法可以中止当前正在工作线程执行的load操作, *但如果当前Loader还未启动或者已经停止那么这个方法不应该做任何操作 */ public void cancelLoadInBackground() { throw new RuntimeException("Stub!"); } public boolean isLoadInBackgroundCanceled() { throw new RuntimeException("Stub!"); } public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) { throw new RuntimeException("Stub!"); }}
PS:下篇文章详解自定义Loader完成更多数据类型的优雅的异步加载。
更多相关文章
- 一句话锁定MySQL数据占用元凶
- Android的签名文件生成两种方法
- android mpeg2ts 流媒体打包MediaMuxer 和 录制MPEG2TSWriter 以
- ANDROID+SQLITE详解2
- Android(安卓)数据表的更新的 解决方案?
- Android(安卓)Activity 与Service进行数据交互详解
- Android(安卓)Studio导入Project、Module的正确方法
- 传智播客—Android(三)数据存储之XML解析技术
- Android开发从零开始之java-数据类型