android – 如何在ContentProvider中缓存位图?

前端之家收集整理的这篇文章主要介绍了android – 如何在ContentProvider中缓存位图?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

你怎么理解这个笔记

Note: A ContentProvider might be a more appropriate place to store
cached images if they are accessed more frequently,for example in an
image gallery application.

在这篇培训文章https://developer.android.com/training/displaying-bitmaps/cache-bitmap.html中?由于我无法从Cursor获取Bitmap或File,我如何通过ContentProvider缓存位图?

最佳答案
实际上,您可以使用ContentProvider读取和写入文件.

要在您自己的ContentProvider中支持功能,您必须在getStreamTypes()方法中包含支持文件MIME类型.检查Android ContentProvider tutorial here for more info的MIME类型部分.

您还需要实现openFile(Uri uri,String mode) method,您可以根据提供给ContentResolver的Uri实际选择文件目录和名称.以下是该方法的示例实现:

  @Override
  public ParcelFileDescriptor openFile(Uri uri,String mode) throws FileNotFoundException {
      File root = getContext().getFilesDir();
      File path = new File(root,uri.getEncodedPath());
      path.mkdirs();
      File file = new File(path,"file_"+uri.getLastPathSegment());

      int imode = 0;
      if (mode.contains("w")) {
        imode |= ParcelFileDescriptor.MODE_WRITE_ONLY;
        if (!file.exists()) {
          try {
            file.createNewFile();
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
      }
      if (mode.contains("r"))
        imode |= ParcelFileDescriptor.MODE_READ_ONLY;
      if (mode.contains("+"))
        imode |= ParcelFileDescriptor.MODE_APPEND;

      return ParcelFileDescriptor.open(file,imode);
  }

您可以使用此处的任何逻辑来选择文件目录.此代码只使用应用程序文件目录,但出于Bitmap缓存的目的,这应该使用临时缓存目录.

最后,访问ContentProvider文件数据的代码应如下所示:

ContentResolver cr = getContext().getContentResolver();
InputStream inputStream = cr.openInputStream(uri);

或者,您可以使用ContentResolver.openOutputStream(uri)将文件数据写入ContentProvider.

Bitmap缓存教程需要进行相当多的修改才能将ContentProvider用作磁盘缓存,但我确实认为这是该笔记所指的内容.

原文链接:https://www.f2er.com/android/430715.html

猜你在找的Android相关文章