【问题标题】:Android 3.0 - what are the advantages of using LoaderManager instances exactly?Android 3.0 - 究竟使用 LoaderManager 实例有什么优势?
【发布时间】:2011-08-01 23:44:38
【问题描述】:

在 3.0 中,我们得到了花哨的 LoaderManager,它使用 AsyncTaskLoaderCursorLoader 和其他自定义 Loader 实例处理数据加载。但是阅读这些文档我只是无法理解:这些比仅使用旧的 AsyncTask 进行数据加载更好吗?

【问题讨论】:

标签: android android-asynctask android-loadermanager android-cursorloader


【解决方案1】:

嗯,它们实现起来要简单得多,并且可以处理有关生命周期管理的所有事情,因此更不容易出错。

看看示例代码,它显示了一个游标查询的结果,它允许用户通过操作栏中的查询输入字段交互式地过滤结果集:

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);
    }
}

使用 AsyncTask 自己正确实现这个完整的示例将涉及更多代码......即使那样,您是否要实现一些完整且运行良好的东西?例如,您的实现是否会在活动配置更改时保留已加载的游标,以便在创建新实例时不需要重新查询它? LoaderManager/Loader 会自动为您完成这项工作,并根据活动生命周期正确创建和关闭游标。

还请注意,使用此代码根本不需要您考虑确保在主 UI 线程之外执行长时间运行的工作。 LoaderManager 和 CursorLoader 为您处理所有这些,确保您在与光标交互时永远不会阻塞主线程。要正确执行此操作,您实际上需要在点上同时激活两个 Cursor 对象,这样您就可以在加载下一个要显示的 Cursor 时继续显示具有当前 Cursor 的交互式 UI。 LoaderManager 为您完成所有这些工作。

这只是一个简单得多的 API——无需了解 AsyncTask 并考虑需要在后台运行什么,无需考虑 Activity 生命周期或如何在 Activity 中使用旧的“托管游标”API(无论如何,它的效果不如 LoaderManager)。

(顺便说一句,不要忘记新的“支持”静态库,它可以让您在低至 1.6 的旧版本 Android 上使用完整的 LoaderManager API!)

【讨论】:

  • 很好的答案!是的,对于初学者来说,滥用 AsyncTask 仍然太容易了——它无法轻松处理配置更改,如果您需要在 onProgressUpdate 等中带有上下文的任何内容,您必须小心,以确保您不会导致内存泄漏.
  • 也许是我,但这似乎远非易事!
  • @hackbod 我已经尝试过 Android 4.0 和支持库,看起来光标 没有 在配置更改时保留。我什至发现了一个相关的错误:code.google.com/p/android/issues/detail?id=25112
  • 我知道这是一个老问题,但即使 Loader 似乎更容易实现和处理配置更改,但如果您需要更新 UI,它似乎并不是最好的选择没有 AsyncTask's onProgressUpdate 的等价物。很难知道,因为关于它的文档很少,什么是最佳实践。在我看来,LoadersAsyncTasks 很相似,但各有各的取舍。
  • 它们确实通常会在配置更改时保留。此时,Android 中的大多数 UI 都使用它们,并且在您更改方向时依靠它不会重新加载。就进度更新而言,自己实现这一点很简单——只需向主线程发布一条消息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-07
  • 2014-10-26
  • 2014-01-08
  • 2012-01-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多