必须使用 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
的实现以及相关方法。
构建与 Web 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); }