androidadbandroid-permissionsandroid-storagescoped-storage

Automated screenshots - Which Storage API?


I'm automating the creation of screenshots using instrumented tests (androidTest) on a debug version of my app using UiAutomator and a shell script that uses adb pull.

Once each screenshot has been taken, I need to be given access to a directory on the Android device to write each image to, that:

The Android docs for choosing a storage API are centred around normal usage by a user of the production app, and don't specify whether adb can access them.

There is so much outdated advice (thanks to the many, many breaking changes to the Android storage APIs over the last 10 years) that the signal-to-noise ratio for existing advice is very low, and checking whether each found solution still works is non-trivial.

Which storage API should/can I use that satisfies the above requirements?


Solution

  • After posting my original answer, I found a new AndroidX library called TestStorage which seems purpose-built by Google for this scenario (source code).

    Note that it's only available during an androidTest run (not in production or local unit tests).

    Usage:

    
        private fun saveScreenshot(bm: Bitmap, fileName: String) {
    
            val testStorage: PlatformTestStorage = PlatformTestStorageRegistry.getInstance()
    
            try {
                val fOut = testStorage.openOutputFile(fileName)
                bm.compress(Bitmap.CompressFormat.PNG, 85, fOut)
                fOut.flush()
                fOut.close()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    
    

    The file(s) created this way during the test run are automatically copied back from the android device to your development machine, and saved in

    <project root>/<module, eg app>/build/outputs/connected_android_test_additional_output/