Skip to content
Tutorials Center
My learning

Topics

Lesson 70 of 104 ยท Local Data

Files, Scoped Storage and Media

Understand internal and external storage, scoped storage, MediaStore, the Storage Access Framework, cache directories and backup rules on Android.

Sooner or later an app has to save a file: a downloaded PDF, a photo the user took, an exported report, a cache of thumbnails. On Android the question is never just "where do I write?" but "who is allowed to read it, how long will it live and who pays for the space?" Over the years the platform has answered those questions more and more strictly, and the current model is called scoped storage.

In this lesson you will learn the storage areas your app can use, how to save and open shared files without broad permissions, and how backups and cache cleanup affect your data. The real APIs need a device, so they are read-only here. The TryIt blocks are Kotlin stand-ins: a small virtual file system with private areas, quotas and cache eviction, which shows the rules without touching a real disk.

Internal and external app storage

Every app gets a private folder inside its sandbox. Other apps cannot read it, and it is deleted when the app is uninstalled. You reach it through the Context:

Kotlin
// read-only example: needs Android
val notes = File(context.filesDir, "notes/today.txt")
notes.parentFile?.mkdirs()
notes.writeText("Buy milk")

val thumbnail = File(context.cacheDir, "thumbs/cat.jpg")
Location API Lives until Notes
Internal files filesDir uninstall or clear data Private, no permission needed
Internal cache cacheDir system may delete it any time For data you can recreate
External app files getExternalFilesDir(type) uninstall Reachable over USB; still no permission
External cache externalCacheDir system may delete it Larger, but may be on removable media

Two points trip people up. Cache really is disposable: when the device runs low on space, Android deletes cache files, oldest first, without telling you. Never keep user data there. And external app-specific storage is only "external" in location; it is still tied to your app, and no permission is required to use it.

Do disk work off the main thread, for example withContext(Dispatchers.IO), as covered in Coroutines on Android.

What scoped storage changed

Before Android 10 an app with the READ_EXTERNAL_STORAGE permission could wander through the whole shared storage, including other apps' downloads and photos. That was a privacy problem, so scoped storage limits each app to two things: its own app-specific folders (always) and the media files it created itself in shared collections (always); anything else needs the user's involvement. It has been enforced for apps targeting Android 11 and up.

In practice, you pick the approach by the kind of file:

  • Private working data goes in filesDir. Nobody else needs it.
  • Photos, video and audio the user should see in other apps go to MediaStore.
  • Documents the user chooses go through the Storage Access Framework.
  • Photos the user picks from the library use the photo picker, which needs no permission at all.

MediaStore: saving shared media

MediaStore is the system's database of media files. You insert a row, write bytes into the stream you receive and the file shows up in the Gallery or Music app. You need no storage permission to add your own files on Android 10 and newer:

Kotlin
// read-only example: needs Android
fun savePhoto(context: Context, bytes: ByteArray): Uri? {
    val values = ContentValues().apply {
        put(MediaStore.Images.Media.DISPLAY_NAME, "sunset.jpg")
        put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
        put(MediaStore.Images.Media.RELATIVE_PATH, "Pictures/MyApp")
        put(MediaStore.Images.Media.IS_PENDING, 1)
    }
    val resolver = context.contentResolver
    val uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values) ?: return null

    resolver.openOutputStream(uri)?.use { it.write(bytes) }

    values.clear()
    values.put(MediaStore.Images.Media.IS_PENDING, 0)
    resolver.update(uri, values, null, null)
    return uri
}

IS_PENDING = 1 hides the half-written file from other apps; you clear it when the write is complete. You never get a raw path back, only a content Uri, so treat it as an opaque handle and use the ContentResolver to open it. Reading media that other apps created needs READ_MEDIA_IMAGES and friends on Android 13+, and from Android 14 the user can grant only selected photos.

The Storage Access Framework

When the user should choose where a document goes, or which one to open, use the system file picker through the Activity Result API from Intents:

Kotlin
// read-only example: needs Android
val createReport = rememberLauncherForActivityResult(
    ActivityResultContracts.CreateDocument("text/csv")
) { uri: Uri? ->
    uri?.let { scope.launch(Dispatchers.IO) { writeCsv(context, it) } }
}

fun writeCsv(context: Context, uri: Uri) {
    context.contentResolver.openOutputStream(uri)?.use { out ->
        out.writer().use { it.write("name,qty\nmilk,2\n") }
    }
}

createReport.launch("expenses.csv")

The user picks the folder and file name, and you receive access to that one document. Other contracts are OpenDocument, OpenMultipleDocuments and OpenDocumentTree (access to a whole folder). The grant normally ends when your process dies; if you need the document tomorrow, call contentResolver.takePersistableUriPermission(uri, flags) and store the Uri.

The first TryIt is a stand-in virtual file system. It models the access rules: private areas belong to the app, other apps are refused, and cache files are tagged as deletable. It is a simplified model of the rules, not a model of real paths.

Kotlin Private areas and access rules (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

In real Android the private-area check is enforced by Linux user ids, and shared media is gated by the permission model and content URIs rather than a boolean.

Quotas, cache and keeping data tidy

Storage is a shared, limited resource. Android tells you how much space an app may use for cache (StorageManager.getCacheQuotaBytes), and the system clears the cache of apps in the background when space runs out, starting with the apps that exceed their quota. Good citizens do three things:

  1. Keep a size limit on their own cache (an LRU cache with a maximum, like the one in Loading Images with Coil) and delete old entries.
  2. Put only recreatable data in cacheDir.
  3. Remove temporary files, for example exported files that were shared once, when they are no longer needed.

The second TryIt is a stand-in for a storage with a total quota and an evicting cache. Writing to files fails when the quota is full, while writing to the cache makes room by deleting the oldest cache entries first.

Kotlin Quota and cache eviction (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Real Android evicts cache on its own schedule and by app-wide rules, so treat the stand-in's "oldest first" as the idea, not the exact policy.

Backup rules

Android can back up app data to the user's Google account and restore it on a new phone. By default your files, DataStore files and databases are included, which is often what you want. It is not what you want for caches, device-specific tokens or large re-downloadable files. You describe the rules in XML and point to them from the manifest:

XML
<!-- read-only example: res/xml/data_extraction_rules.xml -->
<data-extraction-rules>
    <cloud-backup>
        <include domain="sharedpref" path="."/>
        <exclude domain="file" path="downloads/"/>
        <exclude domain="database" path="cache.db"/>
    </cloud-backup>
    <device-transfer>
        <include domain="file" path="."/>
    </device-transfer>
</data-extraction-rules>

On Android 12 and newer this file is wired up with android:dataExtractionRules; older versions use android:fullBackupContent. Setting android:allowBackup="false" turns backup off entirely. Remember that restored data may arrive on a different device, so do not back up anything that only makes sense on the original one, such as auth tokens bound to the hardware.

flowchart TD
    Q{"What are you saving?"}
    Q -->|"private working data"| A["filesDir"]
    Q -->|"recreatable data"| B["cacheDir"]
    Q -->|"photo, video or audio others should see"| C["MediaStore"]
    Q -->|"document the user chooses"| D["Storage Access Framework"]

Choose the storage area by who needs the file and how long it must live.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which location is safest for a user's draft notes that must not disappear unexpectedly?

    filesDir is private, needs no permission and is only removed on uninstall or clear data. Cache directories can be emptied by the system whenever space is low.
  2. 2. How do you let a photo you saved appear in the user's gallery on Android 10+ without requesting a storage permission?

    Apps can add their own media through MediaStore without permission. You receive a content Uri, write bytes through the ContentResolver and clear IS_PENDING when done.
  3. 3. What does the Storage Access Framework give your app?

    The user chooses, and your app receives a Uri for exactly that document or tree. That is why no broad permission is needed.
  4. 4. Which data should be excluded from cloud backup?

    Backups are for data that matters on a new phone. Caches can be rebuilt and device-bound secrets are useless or unsafe on another device.

Summary

  • Each app has private internal storage (filesDir, cacheDir); cache is disposable and the system may clear it.
  • Scoped storage limits apps to their own folders and their own media; broad access is replaced by explicit mechanisms.
  • Use MediaStore for shared photos, video and audio, the Storage Access Framework for user-chosen documents and the photo picker for reading images with no permission.
  • You get content Uri handles, not file paths; open them through ContentResolver.
  • Keep your own cache bounded, and describe backup rules in data_extraction_rules.xml.
  • The real APIs are read-only here; the TryIt blocks are stand-ins for access rules and quota behavior.

Next: Paging 3 for Large Lists