In Media3, a learner downloads a course for a flight; how do DownloadManager, DownloadService and SimpleCache fit together, and why does a second SimpleCache on that folder crash?
answer
- one folder, one cache instance
- a process-wide singleton
- no eviction for downloads
- service in the foreground as dataSync
- read-only CacheDataSource for playback
basics
~20 sDownloadService wraps a DownloadManager that writes segments into a SimpleCache and records state in a DownloadIndex; playback reads that cache through a CacheDataSource.Factory. SimpleCache locks its folder, so a second instance throws IllegalStateException; keep one per process.
solid answer
~50 sI keep one process-wide holder with a `StandaloneDatabaseProvider`, a `SimpleCache` on a dedicated folder with `NoOpCacheEvictor`, and a `DownloadManager` built from them, an HTTP data source factory and an executor. A `DownloadService` subclass returns that manager from `getDownloadManager()`, a `Scheduler` from `getScheduler()` and a progress notification; it runs in the foreground as `dataSync`, so the course keeps downloading after the app goes to the background. For HLS, `DownloadHelper.Factory` builds the `DownloadRequest` with the chosen renditions, which I send with `DownloadService.sendAddDownload`. To play offline, the player gets a `CacheDataSource.Factory` over the same cache with writing disabled. `SimpleCache` allows one instance per directory at a time: a second constructor call throws `IllegalStateException` "Another SimpleCache instance uses the folder", typically because an activity, a view model or the player factory built its own cache instead of sharing the singleton.
code
kotlin · 53 linesimport android.content.Context
import androidx.annotation.OptIn
import androidx.media3.common.util.UnstableApi
import androidx.media3.database.StandaloneDatabaseProvider
import androidx.media3.datasource.DefaultHttpDataSource
import androidx.media3.datasource.cache.CacheDataSource
import androidx.media3.datasource.cache.NoOpCacheEvictor
import androidx.media3.datasource.cache.SimpleCache
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.exoplayer.offline.DownloadManager
import androidx.media3.exoplayer.scheduler.Requirements
import androidx.media3.exoplayer.source.DefaultMediaSourceFactory
import java.io.File
import java.util.concurrent.Executors
@OptIn(UnstableApi::class)
object OfflineMedia {
private var downloadCache: SimpleCache? = null
private var downloadManager: DownloadManager? = null
private val httpFactory = DefaultHttpDataSource.Factory()
@Synchronized
fun downloadManager(context: Context): DownloadManager {
downloadManager?.let { return it }
val appContext = context.applicationContext
val databaseProvider = StandaloneDatabaseProvider(appContext)
val cache = SimpleCache(
File(appContext.filesDir, "course_downloads"),
NoOpCacheEvictor(),
databaseProvider,
)
val manager = DownloadManager(
appContext, databaseProvider, cache, httpFactory, Executors.newFixedThreadPool(2),
)
manager.requirements = Requirements(Requirements.NETWORK_UNMETERED)
downloadCache = cache
downloadManager = manager
return manager
}
fun buildPlayer(context: Context): ExoPlayer {
downloadManager(context)
val cacheFactory = CacheDataSource.Factory()
.setCache(checkNotNull(downloadCache))
.setUpstreamDataSourceFactory(httpFactory)
.setCacheWriteDataSinkFactory(null)
return ExoPlayer.Builder(context)
.setMediaSourceFactory(
DefaultMediaSourceFactory(context).setDataSourceFactory(cacheFactory),
)
.build()
}
}go deeper
Recall that DownloadService wraps DownloadManager, that downloads land in a SimpleCache, and that offline playback reads that cache.
Explain the roles of DownloadIndex, Requirements and the Scheduler, and why playback reads through a CacheDataSource.Factory rather than from files.
Diagnose the folder-lock crash, choose evictors and folders correctly, and keep one process-wide holder shared by the service and every player.
Own the offline storage contract: where caches live, who may construct them, and how the app removes downloads cleanly with SimpleCache.delete.
## The pieces In the language-learning app, a learner taps **Download course** before a flight. Media3 splits that job across four classes in `media3-exoplayer` and `media3-datasource`, all marked `@UnstableApi`, so Kotlin callers opt in with `@OptIn(UnstableApi::class)`: | Class | Job | |---|---| | `SimpleCache` | Stores downloaded bytes in a dedicated folder and keeps an index of what is cached. | | `DownloadManager` | Runs downloads, persists their state in a `DownloadIndex`, and starts or stops them as requirements change. | | `DownloadService` | An Android service that wraps the manager so downloads continue while the app is in the background. | | `CacheDataSource` | Reads media for the player from the cache, falling back to an upstream source on a miss. | ## One cache per folder, one holder per process `SimpleCache` documents that **only one instance is allowed for a given directory at a given time**. Its constructor locks the folder in a process-wide set; a second constructor call on the same folder throws `IllegalStateException` with the message "Another SimpleCache instance uses the folder". The lock is freed only by `release()`. The usual causes in an app: - an activity or view model constructs the cache, and the next screen or a configuration change constructs it again; - the `DownloadService` and the player's data source factory each build their own; - a test builds a cache per test without releasing the previous one. The fix is structural: build the database provider, the cache and the `DownloadManager` **once per process**, in an application-scoped holder or a dependency-injection singleton, and hand the same instances to the service and to the player. Two related rules: - Use a **separate folder** for any streaming cache. Downloads need `NoOpCacheEvictor`, so nothing is evicted; a streaming cache uses `LeastRecentlyUsedCacheEvictor(maxBytes)`. - Never read or delete files in the folder directly. The cache deletes unrecognised files, and removing it properly means `SimpleCache.delete(folder, databaseProvider)` so the index goes too. ## Downloading the course 1. **Build the manager**: `DownloadManager(context, databaseProvider, downloadCache, httpDataSourceFactory, executor)`. Its defaults are three parallel downloads and `Requirements(Requirements.NETWORK)`; set `Requirements(Requirements.NETWORK_UNMETERED)` to download only on unmetered networks. 2. **Subclass `DownloadService`**: return the shared manager from `getDownloadManager()`; return a `Scheduler` from `getScheduler()`, such as `PlatformScheduler` (JobScheduler) or `WorkManagerScheduler` from `media3-exoplayer-workmanager`, which restarts the service when requirements are met again; build the notification in `getForegroundNotification(downloads, notMetRequirements)`, for example with `DownloadNotificationHelper.buildProgressNotification`. 3. **Declare it**: the service uses `android:foregroundServiceType="dataSync"` with the `FOREGROUND_SERVICE` and `FOREGROUND_SERVICE_DATA_SYNC` permissions, plus the `androidx.media3.exoplayer.downloadService.action.RESTART` intent filter if it has a scheduler. 4. **Create requests**: an HLS lesson needs its playlist resolved and renditions chosen. `DownloadHelper.Factory().setDataSourceFactory(...).create(mediaItem)`, then `prepare(callback)`, then `getDownloadRequest(data)` produces the request. `DownloadHelper.Factory` replaced the static `DownloadHelper.forMediaItem` methods in 1.8.0. 5. **Send commands**: `DownloadService.sendAddDownload(context, CourseDownloadService::class.java, request, false)`. Pause, resume, remove and stop reasons are sent the same way. ## Pausing, stopping and removing Commands that change downloads go through static `DownloadService` methods rather than direct calls on the manager: - `sendSetStopReason` with a non-zero reason stops one download, keeps its partial data and persists the reason; `Download.STOP_REASON_NONE` lets it continue. - `sendPauseDownloads` and `sendResumeDownloads` pause everything, but only in memory; a restarted process resumes. - `sendRemoveDownload` deletes one course lesson's data from the cache, and `sendRemoveAllDownloads` deletes everything. - The `foreground` argument is normally `false` while the app is visible, because the service promotes itself to the foreground when it has work. ## Download states - `STATE_QUEUED`: waiting, because downloads are paused, requirements are not met, or the parallel limit is reached. - `STATE_STOPPED`: a non-zero stop reason is set; it persists across process death. - `STATE_DOWNLOADING`, `STATE_COMPLETED` and `STATE_FAILED` (after the manager's retries). A `DownloadManager.Listener` hears state changes but not progress; poll `currentDownloads` to update a progress bar. ## Playing offline Build the player's media source factory from a `CacheDataSource.Factory` that uses **the same cache instance**: - `setCache(downloadCache)` points at the download cache; - `setUpstreamDataSourceFactory(httpFactory)` lets non-downloaded lessons still stream; - `setCacheWriteDataSinkFactory(null)` makes the cache read-only, so streaming other lessons does not fill the download folder. Pass it with `DefaultMediaSourceFactory(context).setDataSourceFactory(...)` to `ExoPlayer.Builder.setMediaSourceFactory`, and play `download.request.toMediaItem()`. ## Where this stops How many episodes to allow offline, when licences expire and how much storage to budget are product design decisions. This API is how the app carries them out.
- Why does the course download use DownloadService instead of a WorkManager worker that fetches the segments?`DownloadService` keeps the shared `DownloadManager` running in a foreground service, persists each download's state in the `DownloadIndex`, retries, and writes segments into the cache layout the player reads back. A worker would have to rebuild all of that. WorkManager still has a role through `WorkManagerScheduler`, which only restarts the service when requirements such as an unmetered network are met again.
- A downloaded lesson plays fine, but streaming a new lesson keeps growing the download folder; why?The player's `CacheDataSource.Factory` writes to the cache by default, so every streamed lesson is cached into the download folder, which uses `NoOpCacheEvictor` and never evicts. Call `setCacheWriteDataSinkFactory(null)` to make that factory read-only, and give any streaming cache its own folder with `LeastRecentlyUsedCacheEvictor`.
- Each screen can create its own SimpleCache on the download folder as long as it closes it later.
- Downloaded lessons can be played by pointing a MediaItem at files in the cache folder.
- A download cache should use LeastRecentlyUsedCacheEvictor to keep storage bounded.
- DownloadManager.Listener reports byte progress, so no polling is needed.
- Pausing all downloads persists across process death like a stop reason does.
- DownloadService is a WorkManager worker, so it shares WorkManager's scheduling limits.
Assumes Media3 1.11; DownloadHelper.Factory replaced the static DownloadHelper.forMediaItem methods in 1.8.0.