ExoPlayer 提供了下载媒体以供离线播放的功能。在大多数用例中,即使您的应用处于后台,也希望下载能够继续进行。对于这些用例,您的应用应继承 DownloadService 并向该服务发送命令,以添加、移除和控制下载。下图显示了所涉及的主要类。
DownloadService:封装了一个DownloadManager并将命令转发给它。该服务允许DownloadManager即使在应用处于后台时也能继续运行。DownloadManager:管理多个下载任务,从DownloadIndex加载(并存储)其状态,并根据网络连接等要求启动和停止下载。为了下载内容,管理器通常会从HttpDataSource读取正在下载的数据,并将其写入Cache。DownloadIndex:持久化保存下载状态。
创建 DownloadService
要创建 DownloadService,请继承它并实现其抽象方法:
getDownloadManager():返回要使用的DownloadManager。getScheduler():返回一个可选的Scheduler,当满足挂起下载所需的条件时,它可以重启服务。ExoPlayer 提供了以下实现:PlatformScheduler,使用 JobScheduler(最低 API 级别为 21)。有关应用权限要求,请参阅 PlatformScheduler 的 Javadoc。WorkManagerScheduler,使用 WorkManager。
getForegroundNotification():返回服务在前台运行时要显示的通知。您可以使用DownloadNotificationHelper.buildProgressNotification来创建默认样式的通知。
最后,在您的 AndroidManifest.xml 文件中定义该服务:
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC"/>
<application>
<service android:name="com.myapp.MyDownloadService"
android:exported="false"
android:foregroundServiceType="dataSync">
<!-- This is needed for Scheduler -->
<intent-filter>
<action android:name="androidx.media3.exoplayer.downloadService.action.RESTART"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</service>
</application>
请参阅 ExoPlayer 示例应用中的 DemoDownloadService 和 AndroidManifest.xml 以获取具体示例。
创建 DownloadManager
以下代码片段演示了如何实例化 DownloadManager,该管理器可以由您的 DownloadService 中的 getDownloadManager() 返回:
Kotlin
// Note: This should be a singleton in your app. val databaseProvider = StandaloneDatabaseProvider(context) // A download cache should not evict media, so should use a NoopCacheEvictor. val downloadCache = SimpleCache(downloadDirectory, NoOpCacheEvictor(), databaseProvider) // Create a factory for reading the data from the network. val dataSourceFactory = DefaultHttpDataSource.Factory() // Choose an executor for downloading data. Using Runnable::run will cause each download task to // download data on its own thread. Passing an executor that uses multiple threads will speed up // download tasks that can be split into smaller parts for parallel execution. Applications that // already have an executor for background downloads may wish to reuse their existing executor. val downloadExecutor = Executor(Runnable::run) // Create the download manager. val downloadManager = DownloadManager(context, databaseProvider, downloadCache, dataSourceFactory, downloadExecutor) // Optionally, properties can be assigned to configure the download manager. downloadManager.requirements = requirements downloadManager.maxParallelDownloads = 3
Java
// Note: This should be a singleton in your app. databaseProvider = new StandaloneDatabaseProvider(context); // A download cache should not evict media, so should use a NoopCacheEvictor. downloadCache = new SimpleCache(downloadDirectory, new NoOpCacheEvictor(), databaseProvider); // Create a factory for reading the data from the network. dataSourceFactory = new DefaultHttpDataSource.Factory(); // Choose an executor for downloading data. Using Runnable::run will cause each download task to // download data on its own thread. Passing an executor that uses multiple threads will speed up // download tasks that can be split into smaller parts for parallel execution. Applications that // already have an executor for background downloads may wish to reuse their existing executor. Executor downloadExecutor = Runnable::run; // Create the download manager. downloadManager = new DownloadManager( context, databaseProvider, downloadCache, dataSourceFactory, downloadExecutor); // Optionally, setters can be called to configure the download manager. downloadManager.setRequirements(requirements); downloadManager.setMaxParallelDownloads(3);
请参阅示例应用中的 DemoUtil 以获取具体示例。
添加下载
要添加下载,请创建一个 DownloadRequest 并将其发送到您的 DownloadService。对于自适应流,使用 DownloadHelper 帮助构建 DownloadRequest。以下示例显示了如何创建下载请求:
Kotlin
val downloadRequest = DownloadRequest.Builder(contentId, contentUri).build()
Java
DownloadRequest downloadRequest = new DownloadRequest.Builder(contentId, contentUri).build();
在此示例中,contentId 是内容的唯一标识符。在简单情况下,通常可以使用 contentUri 作为 contentId,但应用可以自由使用最适合其用例的任何 ID 方案。DownloadRequest.Builder 还提供了一些可选的 setter 方法。例如,setKeySetId 和 setData 可分别用于设置 DRM 和应用希望与下载关联的自定义数据。还可以使用 setMimeType 指定内容的 MIME 类型,作为无法从 contentUri 推断出内容类型的情况下的提示。
创建完成后,可以将请求发送到 DownloadService 以添加下载:
Kotlin
DownloadService.sendAddDownload( context, MyDownloadService::class.java, downloadRequest, /* foreground= */ false, )
Java
DownloadService.sendAddDownload( context, MyDownloadService.class, downloadRequest, /* foreground= */ false);
在此示例中,MyDownloadService 是应用的 DownloadService 子类,foreground 参数控制是否在前台启动服务。如果您的应用已处于前台,则通常应将 foreground 参数设置为 false,因为如果 DownloadService 确定有工作要做,它会自动将自己置于前台。
移除下载
可以通过向 DownloadService 发送移除命令来移除下载,其中 contentId 用于标识要移除的下载:
Kotlin
DownloadService.sendRemoveDownload( context, MyDownloadService::class.java, contentId, /* foreground= */ false, )
Java
DownloadService.sendRemoveDownload( context, MyDownloadService.class, contentId, /* foreground= */ false);
您也可以使用 DownloadService.sendRemoveAllDownloads 移除所有下载的数据。
启动和停止下载
下载仅在满足以下四个条件时才会进行:
- 下载没有停止原因。
- 下载未暂停。
- 满足下载进行的条件。这些条件可以指定对允许的网络类型的限制,以及设备是否应处于空闲状态或连接到充电器。
- 未超过并行下载的最大数量。
所有这些条件都可以通过向您的 DownloadService 发送命令来控制。
设置和清除下载停止原因
可以为单个或所有下载设置停止原因:
Kotlin
// Set the stop reason for a single download. DownloadService.sendSetStopReason( context, MyDownloadService::class.java, contentId, stopReason, /* foreground= */ false, ) // Clear the stop reason for a single download. DownloadService.sendSetStopReason( context, MyDownloadService::class.java, contentId, Download.STOP_REASON_NONE, /* foreground= */ false, )
Java
// Set the stop reason for a single download. DownloadService.sendSetStopReason( context, MyDownloadService.class, contentId, stopReason, /* foreground= */ false); // Clear the stop reason for a single download. DownloadService.sendSetStopReason( context, MyDownloadService.class, contentId, Download.STOP_REASON_NONE, /* foreground= */ false);
stopReason 可以是任何非零值(Download.STOP_REASON_NONE = 0 是一个特殊值,表示下载未停止)。具有多种停止下载原因的应用可以使用不同的值来跟踪每个下载停止的原因。设置和清除所有下载的停止原因的方法与设置和清除单个下载的停止原因相同,只是 contentId 应设置为 null。
当下载具有非零停止原因时,它将处于 Download.STATE_STOPPED 状态。停止原因会持久化在 DownloadIndex 中,因此即使应用程序进程被杀死并随后重启,它们也会被保留。
暂停和恢复所有下载
可以按如下方式暂停和恢复所有下载:
Kotlin
// Pause all downloads. DownloadService.sendPauseDownloads( context, MyDownloadService::class.java, /* foreground= */ false, ) // Resume all downloads. DownloadService.sendResumeDownloads( context, MyDownloadService::class.java, /* foreground= */ false, )
Java
// Pause all downloads. DownloadService.sendPauseDownloads(context, MyDownloadService.class, /* foreground= */ false); // Resume all downloads. DownloadService.sendResumeDownloads(context, MyDownloadService.class, /* foreground= */ false);
当下载暂停时,它们将处于 Download.STATE_QUEUED 状态。与设置停止原因不同,此方法不会持久化任何状态更改。它仅影响 DownloadManager 的运行时状态。
设置下载进行的条件
Requirements 可用于指定下载继续进行必须满足的限制。可以在创建 DownloadManager 时通过调用 DownloadManager.setRequirements() 来设置这些要求,如上文示例所示。也可以通过向 DownloadService 发送命令来动态更改它们:
Kotlin
// Set the download requirements. DownloadService.sendSetRequirements( context, MyDownloadService::class.java, requirements, /* foreground= */ false, )
Java
// Set the download requirements. DownloadService.sendSetRequirements( context, MyDownloadService.class, requirements, /* foreground= */ false);
当下载因未满足要求而无法进行时,它将处于 Download.STATE_QUEUED 状态。您可以使用 DownloadManager.getNotMetRequirements() 查询未满足的要求。
设置最大并行下载数量
可以通过调用 DownloadManager.setMaxParallelDownloads() 来设置最大并行下载数量。通常在创建 DownloadManager 时执行此操作,如上文示例所示。
当下载因已达到最大并行下载数量而无法进行时,它将处于 Download.STATE_QUEUED 状态。
查询下载
可以查询 DownloadManager 的 DownloadIndex 以获取所有下载的状态,包括已完成或失败的下载。可以通过调用 DownloadManager.getDownloadIndex() 来获取 DownloadIndex。然后,可以通过调用 DownloadIndex.getDownloads() 获取一个遍历所有下载的游标。或者,可以通过调用 DownloadIndex.getDownload() 来查询单个下载的状态。
DownloadManager 还提供了 DownloadManager.getCurrentDownloads(),它仅返回当前(即未完成或失败)下载的状态。此方法对于更新通知和显示当前下载进度及状态的其他 UI 组件非常有用。
监听下载
您可以向 DownloadManager 添加监听器,以便在当前下载更改状态时收到通知:
Kotlin
downloadManager.addListener( object : DownloadManager.Listener { // Override methods of interest here. } )
Java
downloadManager.addListener( new DownloadManager.Listener() { // Override methods of interest here. });
请参阅示例应用 DownloadTracker 类中的 DownloadManagerListener 以获取具体示例。
播放已下载的内容
播放已下载的内容与播放在线内容类似,区别在于数据是从下载 Cache 中读取,而不是通过网络读取。
要播放已下载的内容,请使用下载时使用的相同 Cache 实例创建一个 CacheDataSource.Factory,并在构建播放器时将其注入 DefaultMediaSourceFactory:
Kotlin
// Create a read-only cache data source factory using the download cache. val cacheDataSourceFactory: DataSource.Factory = CacheDataSource.Factory() .setCache(downloadCache) .setUpstreamDataSourceFactory(httpDataSourceFactory) .setCacheWriteDataSinkFactory(null) // Disable writing. val player = ExoPlayer.Builder(context) .setMediaSourceFactory( DefaultMediaSourceFactory(context).setDataSourceFactory(cacheDataSourceFactory) ) .build()
Java
// Create a read-only cache data source factory using the download cache. DataSource.Factory cacheDataSourceFactory = new CacheDataSource.Factory() .setCache(downloadCache) .setUpstreamDataSourceFactory(httpDataSourceFactory) .setCacheWriteDataSinkFactory(null); // Disable writing. ExoPlayer player = new ExoPlayer.Builder(context) .setMediaSourceFactory( new DefaultMediaSourceFactory(context).setDataSourceFactory(cacheDataSourceFactory)) .build();
如果同一个播放器实例也将用于播放未下载的内容,则应将 CacheDataSource.Factory 配置为只读,以避免在播放过程中也下载这些内容。
一旦播放器配置了 CacheDataSource.Factory,它就能够访问已下载的内容进行播放。播放下载内容就像将相应的 MediaItem 传递给播放器一样简单。可以使用 Download.request.toMediaItem 从 Download 获取 MediaItem,也可以直接使用 DownloadRequest.toMediaItem 从 DownloadRequest 获取。
MediaSource 配置
前面的示例使下载缓存可用于播放所有 MediaItem。您还可以使下载缓存可用于单个 MediaSource 实例,该实例可以直接传递给播放器:
Kotlin
val mediaSource = ProgressiveMediaSource.Factory(cacheDataSourceFactory) .createMediaSource(MediaItem.fromUri(contentUri)) player.setMediaSource(mediaSource) player.prepare()
Java
ProgressiveMediaSource mediaSource = new ProgressiveMediaSource.Factory(cacheDataSourceFactory) .createMediaSource(MediaItem.fromUri(contentUri)); player.setMediaSource(mediaSource); player.prepare();
下载和播放自适应流
自适应流(例如 DASH、SmoothStreaming 和 HLS)通常包含多个媒体轨道。通常有多个轨道包含相同内容但质量不同(例如 SD、HD 和 4K 视频轨道)。可能还有多个相同类型的轨道包含不同内容(例如不同语言的多个音轨)。
对于流式播放,可以使用轨道选择器来选择播放哪些轨道。同样,对于下载,可以使用 DownloadHelper 来选择下载哪些轨道。DownloadHelper 的典型用法遵循以下步骤:
- 使用
DownloadHelper.Factory实例构建DownloadHelper。准备辅助类并等待回调。 - (可选)使用
getMappedTrackInfo和getTrackSelections检查默认选择的轨道,并使用clearTrackSelections、replaceTrackSelections和addTrackSelection进行调整。 - 通过调用
getDownloadRequest为所选轨道创建DownloadRequest。可以将该请求传递给您的DownloadService以添加下载,如上所述。 - 使用
release()释放辅助类。
Kotlin
val downloadHelper = DownloadHelper.Factory() .setRenderersFactory(DefaultRenderersFactory(context)) .setDataSourceFactory(dataSourceFactory) .create(MediaItem.fromUri(contentUri)) downloadHelper.prepare(callback)
Java
DownloadHelper downloadHelper = new DownloadHelper.Factory() .setRenderersFactory(new DefaultRenderersFactory(context)) .setDataSourceFactory(dataSourceFactory) .create(MediaItem.fromUri(contentUri)); downloadHelper.prepare(callback);
播放已下载的自适应内容需要按照上述说明配置播放器并传递相应的 MediaItem。
构建 MediaItem 时,必须设置 MediaItem.localConfiguration.streamKeys 以匹配 DownloadRequest 中的设置,这样播放器只会尝试播放已下载的轨道子集。使用 Download.request.toMediaItem 和 DownloadRequest.toMediaItem 构建 MediaItem 会为您处理此操作。