メディア アイテムのアートワークは、ContentResolver.SCHEME_CONTENT
または ContentResolver.SCHEME_ANDROID_RESOURCE
を使用してローカル URI として渡す必要があります。このローカル URI は、ビットマップまたはベクター型ドローアブルに解決される必要があります。
コンテンツ階層内のアイテムを表す
MediaDescriptionCompat
オブジェクトの場合は、setIconUri
を介して URI を渡します。再生中のアイテムを表す
MediaMetadataCompat
オブジェクトの場合は、次のいずれかのキーを使用して、putString
を介して URI を渡します。
アプリのリソースからアートワークを提供する
アプリのリソースからドローアブルを提供するには、次の形式で URI を渡します。
android.resource://PACKAGE_NAME/RESOURCE_TYPE/RESOURCE_NAME
// Example URI - note that there is no file extension at the end of the URI
android.resource://com.example.app/drawable/example_drawable
次のスニペットは、リソース ID からこの形式の URI を作成する方法を示しています。
val resources = context.resources
val resourceId: Int = R.drawable.example_drawable
Uri.Builder()
.scheme(ContentResolver.SCHEME_ANDROID_RESOURCE)
.authority(resources.getResourcePackageName(resourceId))
.appendPath(resources.getResourceTypeName(resourceId))
.appendPath(resources.getResourceEntryName(resourceId))
.build()
コンテンツ プロバイダを使用してアートワークを提供する
次の手順では、コンテンツ プロバイダを使用して、ウェブ URI からアートをダウンロードし、ローカル URI で公開する方法について説明します。完全な例については、Universal Android Music Player サンプルアプリの openFile
の実装と関連メソッドをご覧ください。
ウェブ URI に対応する
content://
URI を作成します。メディア ブラウザ サービスとメディア セッションは、このコンテンツ URI を Android Auto と AAOS に渡します。Kotlin
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() }
Java
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(); }
ContentProvider.openFile
の実装で、対応する URI のファイルが存在するかどうかを確認します。存在しない場合、画像ファイルをダウンロードしてキャッシュに保存します。このコード スニペットでは Glide を使用しています。Kotlin
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) }
Java
@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); }