Testing Android Backup and Restore With AndroidX

Getting a new phone is exciting. You take it out of the box, peel off the protective film, and sign in. Your apps begin downloading, your wallpaper shows up, and before long it looks like your phone again.

You open an app. Sign in. Open another one. Sign in again. What was the password for this one? Now you’re digging through your password manager and waiting for verification codes.

Even after you’re signed in, things aren’t quite right. Your settings are back to their defaults. The book you were reading has forgotten your page. The draft you hadn’t finished is gone. The app made it to your new phone, but it doesn’t feel like your app anymore.

Google is pushing developers to fix this. Its August app quality announcement says that starting in April 2027, apps with sign-in will need to support restoring sign-in with the Restore Credentials API to keep Play Store visibility.

Getting the user signed back in is one half of the problem. Getting their data back is the other half, and in my experience it’s the half that quietly breaks. Someone adds a new preferences file and forgets to update the backup rules. An installation ID gets copied to a new device, and now two phones look like the same install. Data encrypted with an Android Keystore key gets restored onto a device that doesn’t have that key, and the app crashes on first launch. None of these show up in a normal unit test.

Fortunately, AndroidX now has a backup testing library that lets us automate the whole round trip. Let’s take a look.

Testing it the old way

Before this library, testing backup meant running a few adb commands by hand, roughly following the backup testing guide:

1
2
3
4
adb shell bmgr enable true
adb shell bmgr backupnow com.example.backupdemo
adb uninstall com.example.backupdemo
adb install app-debug.apk

Then you’d open the app and poke around to see whether your data came back. That works, but it’s manual, it’s easy to forget, and “poke around” isn’t a great assertion. It’s the kind of check that gets done once when backup is first set up and never again.

How the library works

The library splits the test into two halves:

  • backup-host runs on your development machine (or CI) and drives the whole process over ADB: run some code in the app, trigger a backup, wipe the app’s data, restore it, run more code.
  • backup runs inside the app on the device. This is where you write data before the backup and check it afterwards.

Why split things up? Clearing app data kills the process that would normally be running your instrumentation test. Keeping the orchestration on your computer lets the test keep going across that wipe and pick back up inside the restored app.

Android decides what gets backed up, based on your app’s backup rules. The library doesn’t fake any of that; it just gives you a way to test the rules you’ve written.

Version note: This post uses 1.0.0-alpha01, released September 23, 2026. It’s an early alpha, so expect some of this to change. Check the release notes if you’re on a newer version.

Decide what should come back

Before writing any test code, it’s worth writing down what should survive a restore. It’s tempting to check that everything comes back and call it a day, but restoring the wrong thing is a bug too.

For this post, let’s use a reading app that lets you take notes:

  • Should come back: the current book and page, plus the user’s notes.
  • Should stay behind: an installation ID that’s generated fresh on each install.

When you do this for your own app, a few things almost always belong in the “stay behind” list:

  • Installation IDs, push tokens, and other per-device identifiers
  • Anything encrypted with a Keystore key, since Keystore keys don’t move to the new device
  • Auth tokens, which should go through Restore Credentials instead of a file backup
  • Caches that can just be rebuilt

For an app targeting API 31 or higher, point the manifest at the Android 12+ rules, and keep the legacy rules for older devices:

1
2
3
4
<application
    android:allowBackup="true"
    android:dataExtractionRules="@xml/data_extraction_rules"
    android:fullBackupContent="@xml/backup_rules" />

In res/xml/data_extraction_rules.xml:

1
2
3
4
5
6
7
8
9
10
11
12
<data-extraction-rules>
    <cloud-backup>
        <include domain="sharedpref" path="." />
        <exclude domain="sharedpref" path="device_state.xml" />
        <include domain="file" path="notes/" />
    </cloud-backup>
    <device-transfer>
        <include domain="sharedpref" path="." />
        <exclude domain="sharedpref" path="device_state.xml" />
        <include domain="file" path="notes/" />
    </device-transfer>
</data-extraction-rules>

Cloud backup and device-to-device transfer have separate rule sets, so you need to configure both. One thing that trips people up: once you add an include, only the included locations are backed up for that rule set. The Auto Backup documentation covers the defaults and the available domains.

And the legacy version in res/xml/backup_rules.xml:

1
2
3
4
5
<full-backup-content>
    <include domain="sharedpref" path="." />
    <exclude domain="sharedpref" path="device_state.xml" />
    <include domain="file" path="notes/" />
</full-backup-content>

The test below runs on an API 31+ device, so it only exercises the modern rules. If you care about the legacy rules, you’ll want to test those on an older device separately.

Setting up the tests

You’ll need a disposable, unlocked device or emulator running API 31 or higher. And I mean disposable: the test wipes your app’s data, including once before it starts. For the cloud and device-transfer modes, use a debuggable build and an emulator image with Google Play services.

The app module

In the app module’s build.gradle.kts:

1
2
3
4
5
6
7
8
9
10
11
android {
    defaultConfig {
        testApplicationId = "com.example.backupdemo.test"
        testInstrumentationRunner =
            "androidx.test.backup.BackupRestoreTestRunner"
    }
}

dependencies {
    androidTestImplementation("androidx.test.backup:backup:1.0.0-alpha01")
}

Two things to watch out for here:

  1. In alpha01, the host expects the test APK’s package to be exactly <applicationId>.test. If your debug build adds an application ID suffix, account for it in both places: testApplicationId here, and @BackupRestoreConfig(applicationId) in the host test.
  2. BackupRestoreTestRunner replaces your normal instrumentation runner. If you already have Espresso or Compose UI tests in this module, you’ll probably want a dedicated build variant for backup tests.

The host module

Next, add a plain Kotlin/JVM module named backup-host-tests and include it in settings.gradle.kts. Here’s its build.gradle.kts (if your root build already declares the Kotlin JVM plugin, drop the version here):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
plugins {
    kotlin("jvm") version "2.2.21"
}

kotlin { jvmToolchain(17) }

dependencies {
    testImplementation("androidx.test.backup:backup-host:1.0.0-alpha01")
    testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.2")
    testImplementation(platform("org.junit:junit-bom:5.11.4"))
    testImplementation("org.junit.jupiter:junit-jupiter")
    testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}

tasks.test {
    useJUnitPlatform()
    outputs.upToDateWhen { false }
    outputs.cacheIf { false }
    val serial = providers.gradleProperty("backupSerial")
    doFirst {
        val value = serial.orNull
        require(!value.isNullOrBlank()) { "Pass -PbackupSerial=<serial>" }
        systemProperty("androidx.test.backup.device.serial", value)
    }
}

The host tests use JUnit 5, so this module needs the JUnit Platform setup above. I’m also doing two things that aren’t strictly required, but that I’d recommend:

  • Requiring a device serial. This test wipes app data, so I’d rather it fail loudly than wipe whatever device happens to be plugged in.
  • Turning off up-to-date checks and caching. Changing your backup rules and reinstalling doesn’t change anything in this module, so without these lines Gradle will skip the test and report it as passing.

Writing the device actions

The device side is made up of actions: small classes that the host asks the app to run. Each one needs a public no-argument constructor so the runner can create it, and the Context it gets belongs to your app.

Put these in the app’s src/androidTest/java/com/example/backupdemo/BackupActions.kt. First, an action that writes our test data:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.example.backupdemo

import android.content.Context
import androidx.test.backup.BackupDeviceAction
import androidx.test.backup.BackupDeviceActionArgs
import androidx.test.backup.BackupDeviceActionResult
import java.io.File

class SeedReadingState : BackupDeviceAction {
    override val phase = BackupDeviceAction.PHASE_POPULATE

    override fun execute(
        context: Context,
        args: BackupDeviceActionArgs,
    ): BackupDeviceActionResult {
        check(context.getSharedPreferences("reading_progress", 0).edit()
            .putString("book", "the-hobbit")
            .putInt("page", 137)
            .commit())
        check(context.getSharedPreferences("device_state", 0).edit()
            .putString("installation_id", "old-installation")
            .commit())
        val note = File(context.filesDir, "notes/current.txt")
        check(note.parentFile!!.isDirectory || note.parentFile!!.mkdirs())
        note.writeText("Thoughts about chapter seven")
        return BackupDeviceActionResult()
    }
}

Note that we’re using commit() instead of apply(), so the data is definitely on disk before the backup starts. In a real app you’d use whatever persistence you actually use (Room, DataStore, etc.), but the same rule applies: make sure the writes have finished.

Next, an action that checks the data. We’ll run it three times: right after seeding, after wiping, and after restoring. The host tells it which one via a stage argument:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class VerifyReadingState : BackupDeviceAction {
    override val phase = BackupDeviceAction.PHASE_VERIFY

    override fun execute(
        context: Context,
        args: BackupDeviceActionArgs,
    ): BackupDeviceActionResult {
        val stage = args.payload.getValue("stage")
        val progress = context.getSharedPreferences("reading_progress", 0)
        val device = context.getSharedPreferences("device_state", 0)
        val note = File(context.filesDir, "notes/current.txt")

        when (stage) {
            "seeded", "restored" -> {
                check(progress.getString("book", null) == "the-hobbit") {
                    "Wrong or missing book at $stage"
                }
                check(progress.getInt("page", -1) == 137) {
                    "Wrong or missing page at $stage"
                }
                check(note.exists() &&
                    note.readText() == "Thoughts about chapter seven") {
                    "Wrong or missing note at $stage"
                }
            }
            "cleared" -> {
                check(!progress.contains("book")) { "Book survived clear" }
                check(!progress.contains("page")) { "Page survived clear" }
                check(!note.exists()) { "Note survived clear" }
            }
            else -> error("Unknown stage: $stage")
        }

        if (stage == "seeded") {
            check(device.getString("installation_id", null) == "old-installation")
        } else {
            check(!device.contains("installation_id")) {
                "Installation ID should be absent at $stage"
            }
        }
        return BackupDeviceActionResult()
    }
}

Checking all three stages might look like overkill, but each one guards against a test that passes for the wrong reason:

  • Seeded proves the installation ID existed. Otherwise the “it didn’t come back” check would pass even if we never wrote it.
  • Cleared proves the wipe worked, so whatever we see afterwards really came from the restore.
  • Restored is the one we care about.

If your app generates a new installation ID on startup, change the cleared and restored checks to assert that the ID isn’t "old-installation", rather than that it’s missing.

Wiring it all together

Now for the host side. In backup-host-tests/src/test/kotlin/com/example/backupdemo/ReadingStateBackupTest.kt:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package com.example.backupdemo

import androidx.test.backup.host.BackupActionResult
import androidx.test.backup.host.BackupRestoreConfig
import androidx.test.backup.host.BackupRestoreController
import androidx.test.backup.host.BackupRestoreExtension
import androidx.test.backup.host.BackupTransportMode
import java.nio.file.Path
import kotlinx.coroutines.runBlocking
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.junit.jupiter.api.io.TempDir

@ExtendWith(BackupRestoreExtension::class)
@BackupRestoreConfig(applicationId = "com.example.backupdemo")
class ReadingStateBackupTest {
    @TempDir
    lateinit var outputDir: Path

    @Test
    fun readingStateSurvives(controller: BackupRestoreController) {
        runBlocking {
            suspend fun action(name: String, stage: String = "") {
                val result = controller.runOnDevice(
                    actionClassName = "com.example.backupdemo.$name",
                    args = mapOf("stage" to stage),
                )
                check(result is BackupActionResult.Success) {
                    "$name ($stage) failed: $result"
                }
            }

            action("SeedReadingState")
            action("VerifyReadingState", "seeded")
            controller.stopApp()
            val archive = controller.performBackup(
                mode = BackupTransportMode.CLOUD_ENCRYPTED,
                outputDir = outputDir,
            )
            controller.clearAppData()
            action("VerifyReadingState", "cleared")
            controller.performRestore(archive)
            action("VerifyReadingState", "restored")
        }
    }
}

I like how this reads: it’s the same sequence as the real thing. Write data, back up, wipe, restore, check. When it fails, the failure message tells you which step and which piece of data went wrong.

A few notes on the details:

  • BackupRestoreExtension injects the BackupRestoreController, and its APIs are suspending, which is why everything is wrapped in runBlocking.
  • The little action() helper checks every result. When a check() throws on the device, the host gets back a failure result, not an exception, so if you forget to check the result your test will pass no matter what happened on the device.

Running it (and breaking it)

Build and install both APKs, then run the host tests. Grab your device’s serial from adb devices. These paths assume a standard app module without product flavors:

1
2
3
4
./gradlew :app:assembleDebug :app:assembleDebugAndroidTest
adb -s emulator-5554 install -r app/build/outputs/apk/debug/app-debug.apk
adb -s emulator-5554 install -r -t app/build/outputs/apk/androidTest/debug/app-debug-androidTest.apk
./gradlew :backup-host-tests:test -PbackupSerial=emulator-5554

Once it passes, break it on purpose. A test you’ve never seen fail hasn’t proven much yet.

  1. Add <exclude domain="sharedpref" path="reading_progress.xml" /> to the cloud-backup rules, rebuild, reinstall, and rerun. The book/page check should fail after restore.
  2. Put that back, then remove the device_state.xml exclusion. Now the installation ID check should fail.
  3. Restore the original rules.

If both of those fail the way you’d expect, you can trust the test to catch the regressions you actually care about.

Other transport modes

The test above uses CLOUD_ENCRYPTED, but you can swap in CLOUD_UNENCRYPTED or DEVICE_TO_DEVICE to test the other paths. There’s also LOCAL, which is handy as a quick smoke test, but the archive it gives you isn’t a real portable backup.

It’s worth being clear about what these modes don’t do: they simulate the backup policies, but they don’t send anything to a real Google account or a real second phone.

Running in CI

A couple of tips if you want to run this in CI:

  • Run backup tests one at a time per device. Backup configuration is shared device state, so parallel runs will trip over each other.
  • Put a timeout on the whole CI job. The library has its own timeout settings, but it’s an alpha, and I wouldn’t rely on them alone to keep a hung device from eating your build minutes.

Wrap-up

Backup is one of those features that’s easy to forget about, because nothing tells you it’s broken. You usually find out from a one-star review written by someone who just got a new phone.

I wouldn’t try to cover every file in your app on day one. I’d pick the one or two things your users would be most annoyed to lose (their place in a book, their notes, their settings) and the one or two things that should never follow them (installation IDs, anything tied to the Keystore), and write a test for those. Once that’s in place, adding a check is a few lines every time someone adds a new preferences file.

Combined with Restore Credentials for sign-in, that gets you a lot closer to an app that just picks up where the user left off. Hopefully it saves a few of your users an evening of setting things up again!