android 加載器loader詳解

xiaobin710 8年前發布 | 8K 次閱讀 Android開發 移動開發

來自: http://www.jcodecraeer.com//a/anzhuokaifa/developer/2014/0325/1602.html


Loaders

loader在android 3.0之后才被引入,它簡化了在activity和fragment中異步加載數據的步驟(個人認為簡化是次要的,更重要的是優雅的實現了異步加載),loader有如下特點:

適用于每個activity和fragment

提供異步加載的實現方法

監聽數據源的一舉一動,在數據發生變更時自動返回新的結果

當由于配置改變而被重新創建后,它們自動重連到上一個加載器的游標,所以不必重新查詢數據

loader api簡要說明


使用loader的過程中可能會遇到這些類和接口:

Class/Interface 描述
LoaderManager

一個與activity和fragment相關聯的抽象類,它管理一個或多個loader實例,幫助一個應用管理那些與Activity或Fragment的生命周期相關的長時間運行的的操作。最常見的方式是與一個CursorLoader一起使用,然而應用也可以自己寫一個加載其他數據類型或者數據源的loader。

每個activity或fragment只有一個LoaderManager。但是一個LoaderManager可以擁有多個加載器。



LoaderManager.LoaderCallbacks

一個用于客戶端與LoaderManager交互的回調接口。例如,你使用回調方法onCreateLoader()來創建一個新的加載器。


Loader

一個執行異步數據加載的抽象類。它是加載器的基類。你可以使用典型的CursorLoader,但是你也可以實現你自己的子類。一旦加載器被激活,它們將監視它們的數據源并且在數據改變時發送新的結果。

AsyncTaskLoader

提供一個AsyncTask來執行異步加載工作的抽象類。

CursorLoader

AsyncTaskLoader的子類,它查詢ContentResolver然后返回一個Cursor。這個類為查詢cursor以標準的方式實現了加載器的協議,它的游標查詢是通過AsyncTaskLoader在后臺線程中執行,從而不會阻塞界面。使用這個加載器是從一個ContentProvider異步加載數據的最好方式。相比之下,通過fragment或activity的API來執行一個被管理的查詢就不行了。

上面所列的類和接口們是你在你的應用中要實現加載器時的核心組件。你的每個加載器并不一定需要所有的組件,但是你總是需要引用LoaderManager來初始化一個加載器。

 

使用加載器


一個使用加載器的應用會典型的包含如下組件:

  • 一個Activity或Fragment.

  • 一個LoaderManager的實例.

  • 一個加載被ContentProvider所支持的數據的CursorLoader.或者,你可以從Loader或AsyncTaskLoader實現你自己的加載器來從其它源加載數據.

  • 一個LoaderManager.LoaderCallbacks的實現.這是你創建新的加載器以及管理你的已有加載器的引用的地方.

  • 一個顯示加載器的數據的途徑,例如使用一個SimpleCursorAdapter.

  • 一個數據源,比如當是用CursorLoader時,它將是一個ContentProvider.

啟動加載器

LoaderManager管理一個Activiry或Fragment中的一個或多個加載器.但每個activity或fragment只擁有一個LoaderManager.

你通常要在activity的onCreate()方法中或fragment的onActivityCreated()方法中初始化一個加載器.你可以如下創建:

// Prepare the loader.  Either re-connect with an existing one,
// or start a new one.
getLoaderManager().initLoader(0, null, this);

initLoader()方法有以下參數:

  • 一個唯一ID來標志加載器.在這個例子中,ID是0.

  • 可選的參數,用于加載器初始化時(本例中是null).

  • 一個LoaderManager.LoaderCallbacks的實現.被LoaderManager調用以報告加載器的事件,在這個例子中,類本實現了這個接口,所以傳的是它自己:this.


initLoader()保證一個加載器被初始化并激活.它具有兩種可能的結果:

  • 如果ID所指的加載器已經存在,那么這個加載器將被重用.

  • 如果加載器不存在,initLoader()就觸發LoaderManager.LoaderCallbacks的方法onCreateLoader().這是你實例化并返回一個新加載器的地方.

 

在這兩種情況中,傳入的LoaderManager.LoaderCallbacks的實現都與加載器綁定在一起.并且會在加載器狀態變化時被調用.如果在調用這個方法時,調用者正處于啟動狀態,并且所請求的加載器已存在并產生了數據,那么系統會馬上調用onLoadFinished()(也就是說在initLoader()還在執行時).所以你必須為這種情況的發生做好準備.


注意initLoader()返回所創建的加載器,但是你不需保存一個對它的引用.LoaderManager自動管理加載器的生命.LoaderManager會在需要時開始和停止裝載動作,并且維護加載器的狀態和它所關聯的內容.這意味著,你很少與加載器直接交互.你通常都是使用LoaderManager.LoaderCallbacks的方法們在某個事件發生時介入到數據加載的過程中.

 

loader的重啟與回調


重啟

當你使用initLoader()時,如果指定ID的加載器已經存在,則它使用這個加載器.如果不存在呢,它將創建一個新的.但是有時你卻是想丟棄舊的然后開始新的數據.

要想丟棄舊數據,你應使用restartLoader().例如,下面這個SearchView.OnQueryTextListener的實現在用戶查詢發生改變時重啟了加載器,加載器于是需重啟從而能使用新的搜索過慮來進行一次新的查詢.

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;
}
回調LoaderManager.LoaderCallbacks是一個回調接口,它使得客戶端可以與LoaderManager進行交互.加載器,一般指的是CursorLoader,我們希望在它停止后依然保持數據.這使得應用可以在activity或fragment的 onStop()和onStart()之間保持數據,所以當用戶回到一個應用時,它們不需等待數據加載.你使用LoaderManager.LoaderCallbacks的方法們,在需要時創建新的加載器,并且告訴應用什么時候要停止使用加載器的數據.LoaderManager.LoaderCallbacks包含以下方法們:

 onCreateLoader() ―跟據傳入的ID,初始化并返回一個新的加載器.
 onLoadFinished() ―當一個加載器完成了它的裝載過程后被調用.
 onLoaderReset() ―當一個加載器被重置而什其數據無效時被調用.
onCreateLoader當你試圖去操作一個加載器時(比如,通過initLoader()),會檢查是否指定ID的加載器已經存在.如果它不存在,將會觸發LoaderManager.LoaderCallbacks的方法onCreateLoader().這是你創建一個新加載器的地方.通常這個加載器是一個CursorLoader,但是你也可以實現你自己的加載器.在下面的例子中,回調方法onCreateLoader()創建一個CursorLoader.你必須使用構造方法來建立CursorLoader,構造方法需要向ContentProvider執行一次查詢的完整信息作為參數,它尤其需要:

 uri ―要獲取的內容的URI.
 projection ―要返回的列組成的列被.傳入null將會返回所有的列,但這是低效的.
 selection ―一個過濾器,表明哪些行將被返回.格式化成類似SQLWHERE 語句的樣子(除了沒有WHERE).傳入null將返回所有的行.
 selectionArgs ―你可以在selection中包含一些'?',它將被本參數的值替換掉.這些值出現的順序與'?'在selection中出現的順序一至.值將作為字符串.
 sortOrder ―如何為行們排序.格式化成類似于SQLORDER BY 語句的樣字(除了沒有ORDERBY).傳入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");
}

onLoadFinished

這個方法是在前面已創建的加載器已經完成其加載過程后被調用.這個方法保證會在應用到加載器上的數據被釋放之前被調用.在此方法中,你必須刪除所有對舊數據的使用(因為它將很快會被刪除),但是不要自己去釋放它們,因為它們的加載器會做這些事情.

加載器一旦了解到應用不再使用數據時,將馬上釋放這些數據.例如,如果數據是一個從CursorLoader來的游標,你不應調用游標的close().如果游標被放置在一個CursorAdapter中,你應使用swapCursor()方法,以使舊的游標不被關閉.例如:

//這個Adapter被用于顯示列表的數據.
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);
}

onLoaderReset

當一個已創建的加載器被重置從而使其數據無效時,此方法被調用.此回調使你能發現什么時候數據將被?放于是你可以?放對它的引用.

下面這個實現調用參數為nullswapCursor()

// 這個Adapter被用于顯示列表的數據.
SimpleCursorAdapter mAdapter;
...
public void onLoaderReset(Loader<Cursor> loader) {
    //此處是用于上面的onLoadFinished()的游標將被關閉時執行, 我們需確保我們不再使用它.
    mAdapter.swapCursor(null);
}

 

完整例子


這個例子實現了一個Fragment顯示一個包含從聯系人contentprovider返回查詢數據的ListView的內容的功能.它使用一個CursorLoader來管理對provider的查詢.


為了能從用戶的聯系人中取得數據,本例的manifest必須包含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);
    }
}

 

 

 本文由用戶 xiaobin710 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!