媒體項目的圖片必須使用 ContentResolver.SCHEME_CONTENT
或 ContentResolver.SCHEME_ANDROID_RESOURCE
做為本機 URI 傳遞。此本機 URI 必須解析為應用程式資源中的點陣圖或向量可繪項目。針對內容階層中代表項目的 MediaDescriptionCompat
物件,請透過 setIconUri
傳遞 URI。
針對代表播放中項目的 MediaMetadataCompat
物件,請使用下列任一索引鍵透過 putString
傳遞 URI:
MediaMetadataCompat.METADATA_KEY_DISPLAY_ICON_URI
MediaMetadataCompat.METADATA_KEY_ART_URI
MediaMetadataCompat.METADATA_KEY_ALBUM_ART_URI
下列步驟說明如何從網路 URI 下載圖片,並透過本機 URI 公開。如需完整範例,請參閱 Android 通用音樂播放器範例應用程式中 openFile
的實作和相關方法。
建立與網路 URI 對應的
content://
URI。媒體瀏覽器服務和媒體工作階段會將此內容 URI 傳遞至 Android Auto 和 Android Automotive OS (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); }
如要進一步瞭解內容供應者,請參閱「建立內容供應者」。