Android中的Loaders機制
Loaders機制在Android 3.0版本後引入。Loaders機制使一個Activity或者一個Fragment更加容易非同步載入資料。Loaders有如下的特性:
Ø 它們適用於任何Activity和Fragment;
Ø 它們提供了非同步載入資料的機制;
Ø 它們檢測資料來源,當資料來源內容改變時它們能夠傳遞新的結果;
Ø 當配置改變後需要重新建立時,它們會重新連線到最後一個loader的遊標。這樣,它們不需要重新查詢它們的資料。
1 Loader API 總結
在app裡可以使用與loaders相關的很多的類和介面。總結如下:
Class/Interface |
描述 |
LoaderManager |
一個與Activity和Fragment有關聯的抽象類,用於管理一個或多個Loader例項。這有助於app管理長執行操作。使用它的最顯著的例子是CursorLoader。每個Activity或Fragment只能有一個LoaderManager。而一個LoaderManager可以有多個loaders。 |
LoaderManager.LoaderCallbacks |
提供給客戶端的一個callback介面,用於和LoaderManager進行互動。例如,你可以使用onCreateLoader() callback來建立一個新的loader。 |
AsyncTaskLoader |
一個抽象Loader,提供一個AsyncTask進行工作。 |
CursorLoader |
AsyncTaskLoader的子類,用於向ContentResover請求,返回一個Cursor。這個類以標準的遊標查詢方式實現了Loader協議,建立了AsyncTaskLoader,使用一個後臺執行緒來進行遊標查詢,不會阻塞app的UI。因此,使用這個loader是從ContentProvider載入非同步資料的最好的方式。 |
上述的class和interface是你在app裡實現一個loader所需要的元件。你不必使用所有的元件,但是你通常需要一個LoaderManager的引用(用於初始化一個loader)和一個Loader實現類(例如CursorLoader)。
2 在APP裡使用Loaders
一個App裡,典型的使用loaders包含的內容如下:
一個Activity或一個Fragment。
一個LoaderManager的例項。
一個CursorLoader,從一個ContentProvider里加載資料。
一個LoaderManager.LoaderCallbacks的實現。在這你建立新的loader,和管理已經存在的loaders。
一種顯示loader載入資料的方式,例如SimpleCursorAdapter。
一種資料來源,例如一個Conterprovider(當使用CursorLoader)。
2.1 啟動一個Loader
在一個Activity或Fragment裡,LoaderManager管理一個或多個loader例項。每個Activity或Fragment只有一個LoaderManager。
你可要在Activity裡的onCreate()方法裡,或者在Fragment裡的onActivityCreated()方法裡初始化一個loader。例如:
// Prepare the loader. Either re-connect with an existing one, |
initLoader()方法有三個引數:
Ø 一個標誌loader的ID。
Ø 提供給loader建構函式的引數,可選。
Ø 一個LoaderManager.LoaderCallbacks的實現。
initLoader()的呼叫確保了一個loader被初始化和啟用。它有兩種結果:
如果標誌loader的ID已經存在,則最後建立的loader被複用。
如果標誌loader的ID不存在,initLoader()會激發LoaderManager.LoaderCallbacks的方法onCreateLoader()。
在這兩種情形下,給定的LoaderManager.LoaderCallbacks例項被關聯到loader,並且當loader狀態變化時被呼叫。如果呼叫者正處於其開始狀態並且被請求的loader已經存在,且已產生了資料,那麼系統立即呼叫onLoadFinished()(在initLoader()呼叫期間),所以你必須準備好這種情況的發生。
記住,intiLoader()會返回一個建立的loader,但是你不需要來獲取它的引用。LoadeManager會自動管理loader的生命週期。LoaderManager會開始loading,結束loading,維護loader的狀態,以及相關的內容。這意味著,你幾乎不用直接和loaders進行互動。當有特定事件發生時,你僅僅需要使用LoaderManager.LoaderCallbacks方法來干預loading的過程。
2.2 重啟一個loader
當你呼叫一個initLoader(),如上述所示,你會得到一個ID已經存在的loader,或者建立一個新的loader。但是有時候,你想丟棄掉你的舊資料,重新開始。
要丟棄掉你的舊資料,你要呼叫restartLoader()。例如,SearchView.OnQueryTextListener的實現重啟了loader,當用戶的查詢發生變化時。loader需要重啟,是由於它要使用修改過的搜尋過濾器來進行新的查詢:
public boolean onQueryTextChanged(String newText) { // Called when the action bar search text has changed. Update // the search filter, and restart the loader to do a new query // with this filter. mCurFilter = !TextUtils.isEmpty(newText) ? newText : null; getLoaderManager().restartLoader(0, null, this); return true; } |
2.3 使用LoaderManagerCallbacks
LoaderManager.LoaderCallbacks是callback介面,給client提供與LoaderManager互動的介面。
Loaders,特別是CursorLoader,在被停止後期望能夠維持它們的資料。這允許apps在actvitiy或fragemnt的onStop()和onStart()方法裡能夠保持它們的資料,它們不需要等待資料重新被載入。你使用LoaderManager.LoaderCallbacks方法,知道什麼時候該建立一個新的loader,告訴apps什麼時候該停止使用一個loader的資料。
LoaderManager.LoaderCallbacks包含了三個方法:
onCreateLoader()--- 例項化和返回一個新建立的給定ID的loader
onLoadFinished()--- 當一個建立好的loader完成了load,呼叫此函式
onLoaderReset()--- 當一個建立好的loader要被reset,呼叫此函式,這樣導致它的資料無效
2.3.1 onCreateLoader
當你嘗試訪問一個loader(例如,通過initLoader()),它會檢查給定的loader的ID是否存在。如果不存在,它會觸發LoaderManager.LoaderCallbacks裡的方法onCreateLoader(),來建立一個新的loader。典型的例子是CursorLoader。
在這個例子裡,onCreateLoader()回撥函式建立一個CursorLoader。你必須使用CursorLoader的建構函式,它需要一些額外的資訊用於查詢一個ContentProvider。它需要:
uri--- 取得內容的URI。
projection--- 要返回的列的list。傳遞null則返回所有的列,這種做法不夠高效。
selectionArgs--- 你也許要在selection裡包含 ?s,被selectionArgs裡的值替換。
sortOrder--- 行的排序由SQL ORDER BY語句來格式化。傳遞null則返回預設的排序,也許無序。
例如:
// If non-null, this is the current filter the user has provided. String mCurFilter; ... public Loader<Cursor> onCreateLoader(int id, Bundle args) { // This is called when a new Loader needs to be created. This // sample only has one Loader, so we don't care about the ID. // First, pick the base URI to use depending on whether we are // currently filtering. Uri baseUri; if (mCurFilter != null) { baseUri = Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI, Uri.encode(mCurFilter)); } else { baseUri = Contacts.CONTENT_URI; } // Now create and return a CursorLoader that will take care of // creating a Cursor for the data being displayed. String select = "((" + Contacts.DISPLAY_NAME + " NOTNULL) AND (" + Contacts.HAS_PHONE_NUMBER + "=1) AND (" + Contacts.DISPLAY_NAME + " != '' ))"; return new CursorLoader(getActivity(), baseUri, CONTACTS_SUMMARY_PROJECTION, select, null, Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC"); } |
2.3.2 onLoadFinished
當一個建立好的loader結束了它的load,此方法被呼叫。這個方法確保在釋放loader維持的資料之前呼叫。在這個點上,你應當移除所有對舊資料的使用(因為舊資料不久就要被釋放),不用釋放舊資料,loader會完成舊資料的釋放。
loader一旦知道app不再使用它,它就會釋放掉資料。例如,如果資料是來自CursorLoader裡的一個cursor,你不應當自己呼叫close()。如果一個cursor正在放置到一個CursorAdapter,你應當使用swapCursor()方法,這樣舊的Cursor就不會被關掉。
例如:
// This is the Adapter being used to display the list's data. SimpleCursorAdapter mAdapter; ... public void onLoadFinished(Loader<Cursor> loader, Cursor data) { // Swap the new cursor in. (The framework will take care of closing the // old cursor once we return.) mAdapter.swapCursor(data); } |
2.3.3onLoaderReset
當建立好的loader正在被重啟時,此方法被呼叫,這樣讓loader的資料置於無效狀態。這個回撥函式讓你發現什麼時候資料要被釋放掉,在這個點上你可要移除對它的引用。
例如:
// This is the Adapter being used to display the list's data. SimpleCursorAdapter mAdapter; ... public void onLoaderReset(Loader<Cursor> loader) { // This is called when the last Cursor provided to onLoadFinished() // above is about to be closed. We need to make sure we are no // longer using it. mAdapter.swapCursor(null); } |
3 樣例
這個樣例是一個Fragment的實現,它使用ListView顯示了通訊錄查詢的結果,使用CursorLoader來管理通訊錄Provider的查詢。app若需要訪問通訊錄,你需要在mainfest裡新增許可權READ_CONTACTS。
public static class CursorLoaderListFragment extends ListFragment implements OnQueryTextListener, LoaderManager.LoaderCallbacks<Cursor> { // This is the Adapter being used to display the list's data. SimpleCursorAdapter mAdapter; // If non-null, this is the current filter the user has provided. String mCurFilter; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // Give some text to display if there is no data. In a real // application this would come from a resource. setEmptyText("No phone numbers"); // We have a menu item to show in action bar. setHasOptionsMenu(true); // Create an empty adapter we will use to display the loaded data. mAdapter = new SimpleCursorAdapter(getActivity(), android.R.layout.simple_list_item_2, null, new String[] { Contacts.DISPLAY_NAME, Contacts.CONTACT_STATUS }, new int[] { android.R.id.text1, android.R.id.text2 }, 0); setListAdapter(mAdapter); // Prepare the loader. Either re-connect with an existing one, // or start a new one. getLoaderManager().initLoader(0, null, this); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { // Place an action bar item for searching. MenuItem item = menu.add("Search"); item.setIcon(android.R.drawable.ic_menu_search); item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); SearchView sv = new SearchView(getActivity()); sv.setOnQueryTextListener(this); item.setActionView(sv); } public boolean onQueryTextChange(String newText) { // Called when the action bar search text has changed. Update // the search filter, and restart the loader to do a new query // with this filter. mCurFilter = !TextUtils.isEmpty(newText) ? newText : null; getLoaderManager().restartLoader(0, null, this); return true; } @Override public boolean onQueryTextSubmit(String query) { // Don't care about this. return true; } @Override public void onListItemClick(ListView l, View v, int position, long id) { // Insert desired behavior here. Log.i("FragmentComplexList", "Item clicked: " + id); } // These are the Contacts rows that we will retrieve. static final String[] CONTACTS_SUMMARY_PROJECTION = new String[] { Contacts._ID, Contacts.DISPLAY_NAME, Contacts.CONTACT_STATUS, Contacts.CONTACT_PRESENCE, Contacts.PHOTO_ID, Contacts.LOOKUP_KEY, }; public Loader<Cursor> onCreateLoader(int id, Bundle args) { // This is called when a new Loader needs to be created. This // sample only has one Loader, so we don't care about the ID. // First, pick the base URI to use depending on whether we are // currently filtering. Uri baseUri; if (mCurFilter != null) { baseUri = Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI, Uri.encode(mCurFilter)); } else { baseUri = Contacts.CONTENT_URI; } // Now create and return a CursorLoader that will take care of // creating a Cursor for the data being displayed. String select = "((" + Contacts.DISPLAY_NAME + " NOTNULL) AND (" + Contacts.HAS_PHONE_NUMBER + "=1) AND (" + Contacts.DISPLAY_NAME + " != '' ))"; return new CursorLoader(getActivity(), baseUri, CONTACTS_SUMMARY_PROJECTION, select, null, Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC"); } public void onLoadFinished(Loader<Cursor> loader, Cursor data) { // Swap the new cursor in. (The framework will take care of closing the // old cursor once we return.) mAdapter.swapCursor(data); } public void onLoaderReset(Loader<Cursor> loader) { // This is called when the last Cursor provided to onLoadFinished() // above is about to be closed. We need to make sure we are no // longer using it. mAdapter.swapCursor(null); } } |
更多的樣例請參考API Demos裡的"LoaderCursor"和"LoaderThrottle"。