Google Drive auto-backup for React Native on Android
Davyd NRB
Posted on December 28, 2022
What if async storage values were to persist when a user changed devices or installed an app again?
You won't believe it, but it works with Android right out of the box!
First we need to enable a backup option in the android/app/src/main/AndroidManifest.xml
file:
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/backup_rules"
Then create android/app/src/main/res/xml/backup_rules.xml
file with the list of files that should be added to backup:
<?xml version="1.0" encoding="utf-8"?>
<data-extraction-rules>
<cloud-backup>
<!-- your rules -->
</cloud-backup>
<device-transfer>
<!-- your rules -->
</device-transfer>
</data-extraction-rules>
docs: Backup and restore
Testing
More rules are listed below, but first, let's look at how to test them.
- You can use Simulator or Real device
- Need to enable Backups:
Setting
=>System
=>Backup
- Then using
adb
you can create/restore backup:
# Replace `com.mycompany.myapp` with your app package!!!
adb shell bmgr backupnow com.mycompany.myapp # Create backup
adb shell bmgr restore 1 com.mycompany.myapp
# ^^^ use a fake id `1` to show list of available sets
# No matching restore set token. Available sets:
# 3a945fc11efadf47 : Google Pixel 7 Pro
# done
adb shell bmgr restore 3a945fc11efadf47 com.mycompany.myapp # Now use a real id, to restore backup
Rules
I've compiled a list of guidelines for the most popular React Native packages for your convenience.
@react-native-async-storage/async-storage
<include domain="database" path="RKStorage"/>
<include domain="database" path="RKStorage-journal"/>
react-native-shared-preferences
SharedPreferences.setName("my_name"); // js part
<include domain="sharedpref" path="my_name.xml" /> // android part
<include domain="file" path="./mmkv" />
react-native-webview
cookies
<include domain="root" path="./app_webview"/>
<include domain="file" path="./default.realm" />
<include domain="file" path="./default.realm.lock" />
<include domain="file" path="./default.realm.management" />
<include domain="file" path="./default.realm.note" />
<include domain="root" path="./watermelon.db"/>
<include domain="root" path="./watermelon.db-wal"/>
<include domain="root" path="./watermelon.db-shm"/>
How create own rule
adb shell
run-as com.mycompany.myapp # Replace `com.mycompany.myapp` with your app package!!!
find . -type f # will print all files
# 1) For files in directory `./files/*`
# <include domain="file" path="./mmkv" />
# ^^^^^^ ./files/mmkv
# 2) For `./shared_prefs/*.xml`
# <include domain="sharedpref" path="my_name.xml" />
# ^^^^^^^^^ ./shared_prefs/my_name.xml
# ...
Posted on December 28, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.