[关闭]
@flyouting 2014-03-19T06:58:40.000000Z 字数 2345 阅读 3253

Android相机开发指南(二)

这是基于Android Studio及Fragment的相机开发的第二章,如果你还没准备好,先去github上拉一下我的一个示例工程。本章主要包含“SimplePhotoGalleryListFragment.

AsyncTaskLoaders and Fragments

把我们所有的图片加载到Android Studio的一个list里是一项繁杂的任务。因此,我们需要使用一个在Android体系中被称为AsyncTaskLoader的类,在这个例子里,我专门写了一个自定义的AsyncTaskLoader。通过PhotoGalleryImageProvider这个工具类调用去加载相册图片。

Fragments 中提供一个特别的接口去启动async task loaders并与其交互。在我们的文件中如此:

  1. @Override
  2. public void onCreate(Bundle savedInstanceState)
  3. {
  4. super.onCreate(savedInstanceState);
  5. // Create an empty loader and pre-initialize the photo list items as an empty list.
  6. Context context = getActivity().getBaseContext();
  7. // Set up empty mAdapter
  8. mPhotoListItem = new ArrayList() ;
  9. mAdapter = new PhotoAdapter(context, R.layout.photo_item, mPhotoListItem, false);
  10. // Prepare the loader. Either re-connect with an existing one,
  11. // or start a new one.
  12. getLoaderManager().initLoader(0, null, this); }
  13. }

注意最后这行代码,“getLoaderManager().initLoader(0, null, this);”这会自动启动指定的AsyncLoader:

  1. /**
  2. * Loader Handlers for loading the photos in the background.
  3. */
  4. @Override
  5. public Loader<List> onCreateLoader(int id, Bundle args) {
  6. // This is called when a new Loader needs to be created. This
  7. // sample only has one Loader with no arguments, so it is simple.
  8. return new PhotoGalleryAsyncLoader(getActivity());
  9. }

Once the background task has finished gathering the gallery images, it returns in this method:

当后台任务执行完,获取到了相册图片时,会回调这个方法:

  1. @Override
  2. public void onLoadFinished(Loader<List> loader, List data) {
  3. // Set the new data in the mAdapter.
  4. mPhotoListItem.clear();
  5. for (int i = 0; i < data.size(); i++) {
  6. PhotoItem item = data.get(i);
  7. mPhotoListItem.add(item);
  8. }
  9. mAdapter.notifyDataSetChanged();
  10. resolveEmptyText();
  11. cancelProgressDialog();
  12. }

PhotoItems这个模型类包括了图片的缩略图和原始图的url,当这些数据获取后,可以执行notifyDataSetChanged()去加载图片了。

使用cursors获取图片缩略图

我之前提到过,我提供了一个工具类PhotoGalleryImageProvider用以获取相册中图片的缩略图的cursor。方法如下:

  1. /**
  2. * Fetch both full sized images and thumbnails via a single query. Returns
  3. * all images not in the Camera Roll.
  4. *
  5. * @param context
  6. * @return
  7. */
  8. public static List getAlbumThumbnails(Context context){
  9. final String[] projection = {MediaStore.Images.Thumbnails.DATA,MediaStore.Images.Thumbnails.IMAGE_ID};
  10. Cursor thumbnailsCursor = context.getContentResolver().query( MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
  11. projection, // Which columns to return
  12. null, // Return all rows
  13. null,
  14. null);
  15. ...
  16. return result;
  17. }

Android中的Cursors是后台获取图片的一般方法,更高级的使用时CursorLoader。其内置有AsyncTaskLoader,用于自动处理负载转移到后台。可能我通过AsyncTask和CursorLoader也能获取同样的结果,但是我想在列表中渲染获得的图片的缩略图和原始图,所以我使用自定义的 task loader。

详细请查看项目中代码。

翻译:@flyouting
时间:2014/03/19
源地址

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注