Отображение медиа-иллюстраций

Графические элементы для медиа-объектов должны передаваться как локальный URI с помощью метода ContentResolver.SCHEME_CONTENT или ContentResolver.SCHEME_ANDROID_RESOURCE . Этот локальный URI должен быть преобразован в растровое или векторное изображение, доступное для рисования в ресурсах приложения. Для объектов MediaDescriptionCompat , представляющих элементы в иерархии контента, URI передается через setIconUri .

Для объектов MediaMetadataCompat , представляющих воспроизводимый элемент, используйте любой из этих ключей для передачи URI через putString :

Эти шаги описывают, как загрузить изображение с веб-URI и предоставить его через локальный URI. Полный пример см. в реализации openFile и окружающих его методов в примере приложения Universal Android Music Player.

  1. Создайте URI content:// соответствующий веб-URI. Служба медиабраузера и медиасеанс передают этот URI контента в Android Auto и Android Automotive OS (AAOS).

    Котлин

    fun Uri.asAlbumArtContentURI(): Uri {
          return Uri.Builder()
            .scheme(ContentResolver.SCHEME_CONTENT)
            .authority(CONTENT_PROVIDER_AUTHORITY)
            .appendPath(this.getPath()) // Make sure you trust the URI
            .build()
      }
    

    Ява

    public static Uri asAlbumArtContentURI(Uri webUri) {
          return new Uri.Builder()
            .scheme(ContentResolver.SCHEME_CONTENT)
            .authority(CONTENT_PROVIDER_AUTHORITY)
            .appendPath(webUri.getPath()) // Make sure you trust the URI!
            .build();
     }
    
  2. В вашей реализации ContentProvider.openFile проверьте, существует ли файл для соответствующего URI. Если нет, загрузите и кешируйте файл изображения. В этом фрагменте кода используется Glide .

    Котлин

    override fun openFile(uri: Uri, mode: String): ParcelFileDescriptor? {
          val context = this.context ?: return null
          val file = File(context.cacheDir, uri.path)
          if (!file.exists()) {
            val remoteUri = Uri.Builder()
                .scheme("https")
                .authority("my-image-site")
                .appendPath(uri.path)
                .build()
            val cacheFile = Glide.with(context)
                .asFile()
                .load(remoteUri)
                .submit()
                .get(DOWNLOAD_TIMEOUT_SECONDS, TimeUnit.SECONDS)
    
            cacheFile.renameTo(file)
             file = cacheFile
          }
          return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY)
     }
    

    Ява

    @Nullable
      @Override
      public ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode)
            throws FileNotFoundException {
          Context context = this.getContext();
          File file = new File(context.getCacheDir(), uri.getPath());
          if (!file.exists()) {
            Uri remoteUri = new Uri.Builder()
                .scheme("https")
                .authority("my-image-site")
                .appendPath(uri.getPath())
                .build();
            File cacheFile = Glide.with(context)
                .asFile()
                .load(remoteUri)
                .submit()
                .get(DOWNLOAD_TIMEOUT_SECONDS, TimeUnit.SECONDS);
    
            cacheFile.renameTo(file);
            file = cacheFile;
          }
          return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
      }
    

Подробную информацию о поставщиках контента см. в разделе Создание поставщика контента .

,

Графические элементы для медиа-объектов должны передаваться как локальный URI с помощью метода ContentResolver.SCHEME_CONTENT или ContentResolver.SCHEME_ANDROID_RESOURCE . Этот локальный URI должен быть преобразован в растровое или векторное изображение, доступное для рисования в ресурсах приложения. Для объектов MediaDescriptionCompat , представляющих элементы в иерархии контента, URI передается через setIconUri .

Для объектов MediaMetadataCompat , представляющих воспроизводимый элемент, используйте любой из этих ключей для передачи URI через putString :

Эти шаги описывают, как загрузить изображение с веб-URI и предоставить его через локальный URI. Полный пример см. в реализации openFile и окружающих его методов в примере приложения Universal Android Music Player.

  1. Создайте URI content:// соответствующий веб-URI. Служба медиабраузера и медиасеанс передают этот URI контента в Android Auto и Android Automotive OS (AAOS).

    Котлин

    fun Uri.asAlbumArtContentURI(): Uri {
          return Uri.Builder()
            .scheme(ContentResolver.SCHEME_CONTENT)
            .authority(CONTENT_PROVIDER_AUTHORITY)
            .appendPath(this.getPath()) // Make sure you trust the URI
            .build()
      }
    

    Ява

    public static Uri asAlbumArtContentURI(Uri webUri) {
          return new Uri.Builder()
            .scheme(ContentResolver.SCHEME_CONTENT)
            .authority(CONTENT_PROVIDER_AUTHORITY)
            .appendPath(webUri.getPath()) // Make sure you trust the URI!
            .build();
     }
    
  2. В вашей реализации ContentProvider.openFile проверьте, существует ли файл для соответствующего URI. Если нет, загрузите и кешируйте файл изображения. В этом фрагменте кода используется Glide .

    Котлин

    override fun openFile(uri: Uri, mode: String): ParcelFileDescriptor? {
          val context = this.context ?: return null
          val file = File(context.cacheDir, uri.path)
          if (!file.exists()) {
            val remoteUri = Uri.Builder()
                .scheme("https")
                .authority("my-image-site")
                .appendPath(uri.path)
                .build()
            val cacheFile = Glide.with(context)
                .asFile()
                .load(remoteUri)
                .submit()
                .get(DOWNLOAD_TIMEOUT_SECONDS, TimeUnit.SECONDS)
    
            cacheFile.renameTo(file)
             file = cacheFile
          }
          return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY)
     }
    

    Ява

    @Nullable
      @Override
      public ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode)
            throws FileNotFoundException {
          Context context = this.getContext();
          File file = new File(context.getCacheDir(), uri.getPath());
          if (!file.exists()) {
            Uri remoteUri = new Uri.Builder()
                .scheme("https")
                .authority("my-image-site")
                .appendPath(uri.getPath())
                .build();
            File cacheFile = Glide.with(context)
                .asFile()
                .load(remoteUri)
                .submit()
                .get(DOWNLOAD_TIMEOUT_SECONDS, TimeUnit.SECONDS);
    
            cacheFile.renameTo(file);
            file = cacheFile;
          }
          return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
      }
    

Подробную информацию о поставщиках контента см. в разделе Создание поставщика контента .