I'll repeat myself from another answer:
Starting from API level 8 (Android 2.2), if you build the application as debuggable, you can use the shell run-as
command to run a command or executable as a specific user/application or just switch to the UID
of your application so you can access its data
directory.
Copy files to external storage on the device
So if you wish to pull your application database from the device you can launch a debug build of the application from Android Studio, connect with adb shell
and run the following command:
run-as com.your.package sh -c "cat ~/databases/db-file.db" > /sdcard/db-file.db
or you can use a shorter version which uses relative paths and by skipping the reference to the home directory ~
can omit the sh -c
part too:
run-as com.your.package cat databases/db-file.db > /sdcard/db-file.db
This will copy your db-file.db
to the root of your SD card / external storage. Now you can easily get it from there by using file manager, adb pull
or whatever else you like. Note that with this approach, there is NO need for your app to have WRITE_EXTERNAL_STORAGE
permission, as the copying is done by the shell
user who can always write to the external storage.
Copy files directly to the computer
You can also copy a database directly to your computer with the following command:
adb shell 'run-as com.your.package cat databases/db-file.db' > db-file.db
The adb shell
command above will not work correctly on Windows host because of the CR/LF
symbols conversion, unless you run it from a bash
shell or use the undocumented adb exec-out
command instead (some comments mention they still cannot get it to work correctly on a Windows machine, so your mileage may vary):
adb exec-out 'run-as com.your.package cat databases/db-file.db' > db-file.db
Write files back to the device
If you modified the file on your computer and wish to write the modifications back to the device use the following command:
adb exec-in 'run-as com.your.package tee databases/db-file.db' < db-file.db
or if you prefer an adb shell
version over undocumented exec-in
, use the following (but read the concern about the Windows CR/LF
conversion above):
adb shell 'run-as com.your.package tee databases/db-file.db' < db-file.db >/dev/null
Status update
All the commands above are still working as of July, 2023