媒體項目的圖片必須使用 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 公開。如需完整範例,請參閱 Android 通用音樂播放器範例應用程式中 openFile
的實作和相關方法。
建立與網路 URI 對應的
content://
URI。媒體瀏覽器服務和媒體工作階段會將此內容 URI 傳遞至 Android Auto 和 Android Automotive OS。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); }