How can an Android app back up an SQLite database that's larger than 25MB?

219 Views Asked by At

On iOS, there's an iCloud Backup feature that will automatically make a daily copy of an app's documents and store it in the user's iCloud drive. The backup size is limited only by the space available in the user's iCloud account. My app uses an SQLite database that will probably end up storing something like 100 - 200MB for the average user.

I found some documentation on Android Backup but it says:

Auto Backup can store up to 25 MB of file-based data per app.

That's not enough for my needs. What do Android apps do to back up their local SQLite data if they need more than 25MB?

Am I supposed to use Google Drive to store application data?

1

There are 1 best solutions below

2
ΓDΛ On

The comment you made in your question is quite correct. In addition I agree with @Robert comment.

For a custom solution with Google Drive.

Using the Google Drive API, you can develop a custom solution to back up database specific data

  1. Creating the OAuth 2.0 Client - To access the google drive API via Google Cloud Console.
  2. Google Drive API Integration
  3. Scheduled Tasks - WorkManager

Automatic backup varies depending on certain reasons.

Backups occur automatically when all of the following conditions are met:

  • The user has enabled backup on the device.In Android 9, this setting is in Settings > System > Backup.
  • At least 24 hours have elapsed since the last backup.
  • The device is idle.
  • The device is connected to a Wi-Fi network (if the device user hasn't opted in to mobile-data backups).

You can make a backup by checking these scenarios or every time the application is opened.

Remember, we do not use automatic backup, which is a feature of the system.

Sample code for periodic backup

val driveResourceClient = Drive.getDriveResourceClient(context, GoogleSignIn.getLastSignedInAccount(context))
val file = File(pathToYourDatabase) 
val fileContent = FileContent(databaseMimeType, file)
driveResourceClient
    .createFile(driveFolder, fileMetaData, fileContent)
    .addOnSuccessListener { Log.i(TAG, "backup uploaded") }
    .addOnFailureListener { e -> Log.e(TAG, "upload database backup", e) }

Sample Worker

class BackupWorker(appContext: Context, workerParams: WorkerParameters)
    : CoroutineWorker(appContext, workerParams) {

    override suspend fun doWork(): Result {
        return try {
            uploadToDrive()
            Result.success()
        } catch (e: Exception) {
            Result.failure()
        }
    }
    
    suspend fun uploadToDrive() {
        // google drive upload code
    }
}

WorkManager

val periodicBackupRequest = PeriodicWorkRequestBuilder<BackupWorker>(24, TimeUnit.HOURS).build()
WorkManager.getInstance(this).enqueue(periodicBackupRequest)

Note;

Finally, using firebase may be the healthiest way. Just a suggestion.