Beginning with Android 6.0 (API level 23), Android offers the Auto Backup for Apps feature as a way to back up and restore the user's data in your app. Auto Backup preserves app data by uploading it to the user's Google Drive account, where it is protected by the user's Google account credentials. The amount of data is limited to 25MB per user of your app and there is no charge for storing backup data.
For an overview of Android's backup options and guidance about which data you should back up and restore, see the Data Backup Overview.
For a walk-through on setting up Auto Backup, also try the Auto Backup for Android Codelab.
Files that are backed up
By default, Auto Backup includes files in most of the directories that are assigned to your app by the system:
- Shared preferences files.
- Files saved to your app's internal storage, accessed by
getFilesDir()
orgetDir(String, int)
. - Files in the directory returned by
getDatabasePath(String)
, which also includes files created with theSQLiteOpenHelper
class. - Files on external storage in the directory returned by
getExternalFilesDir(String)
.
Auto Backup excludes files in directories returned by getCacheDir()
, getCodeCacheDir()
, or getNoBackupFilesDir()
. The files saved in these
locations are only needed temporarily, or are intentionally excluded from
backup operations.
You can configure your app to include and exclude particular files. For more information, see the Include and exclude files section.
Note: Android does not treat the configuration of components as user data. If your app enables or disables specific components in its manifest while it is running, do not expect AutoBackup to save and restore the configuration. To preserve the configuration state, save it in Shared Preferences and recover Shared Preferences on restore. If you want your app to save its state, store state in Shared Preferences and recover Shared Preferences on restore.
Backup location
Backup data is stored in a private folder in the user's Google Drive account, limited to 25MB per app. The saved data does not count towards the user's personal Google Drive quota. Only the most recent backup is stored. When a backup is made, the previous backup (if one exists) is deleted.
Users can see a list of apps that have been backed up in the Google Drive app under Settings -> Auto Backup for apps -> Manage backup. The backup data cannot be read by the user or other apps on the device.
Backups from each device-setup-lifetime are stored in separate datasets as shown in the following examples:
- If the user owns two devices, then a backup dataset exists for each device.
- If the user factory resets a device and then sets up the device with the same account, the backup is stored in a new dataset. Obsolete datasets are automatically deleted after a period of inactivity.
Caution: If the amount of data is over 25MB, the system
fires the onQuotaExceeded(long, long)
callback and does not backup data to the cloud. The system
periodically checks whether the amount of data later falls under the 25MB
threshold and continues Auto Backup when it does.
Backup schedule
Backups occur automatically when all of the following conditions are met:
- The user has enabled backup on the device in Settings > Backup & Reset.
- At least 24 hours have elapsed since the last backup.
- The device is idle and charging.
- The device is connected to a Wi-Fi network. If the device is never connected to a wifi network, then Auto Backup never occurs.
In practice, these conditions occur roughly every night. To conserve network bandwidth, upload takes place only if app data has changed.
During Auto Backup, the system shuts down the app to make sure it is no
longer writing to the file system. By default, the backup system ignores
apps that are running in the foreground because users would notice their
apps being shut down. You can override the default behavior by setting
the
backupInForeground
attribute to true.
To simplify testing, Android includes tools that let you manually initiate a backup of your app. For more information, see Testing Backup and Restore.
Restore schedule
Data is restored whenever the app is installed, either from the Play store, during device setup (when the system installs previously installed apps), or from running adb install. The restore operation occurs after the APK is installed, but before the app is available to be launched by the user.
During the initial device setup wizard, the user is shown a list of available backup datasets and is asked which one to restore the data from. Whichever backup dataset is selected becomes the ancestral dataset for the device. The device can restore from either its own backups or the ancestral dataset. The device prioritize its own backup if backups from both sources are available. If the user didn't go through the device setup wizard, then the device can restore only from its own backups.
To simplify testing, Android includes tools that let you manually initiate a restore of your app. For more information, see Testing Backup and Restore.
Enabling and disabling backup
Apps that target Android 6.0 (API level 23) or higher automatically
participate in Auto Backup because the
android:allowBackup
attribute defaults to true
.
To avoid any confusion, you should explicitly set the
attribute in your manifest as follows:
<manifest ... >
...
<application android:allowBackup="true" ... >
...
</application>
</manifest>
You might want to disable backups by setting this to false
if your app can
recreate its state through some other mechanism or when your app deals
with sensitive information that should not be backed up.
Including and excluding files
By default, the system backs up almost all app data. For more information, see Files that are backed up. This section shows you how to define custom XML rules to control what gets backed up.
- In
AndroidManifest.xml
, add theandroid:fullBackupContent
attribute to the<application>
element. This attribute points to an XML file that contains backup rules. For example:<application ... android:fullBackupContent="@xml/my_backup_rules"> </app>
- Create an XML file called
my_backup_rules.xml
in theres/xml/
directory. Inside the file, add rules with the<include>
and<exclude>
elements. The following sample backs up all shared preferences exceptdevice.xml
:<?xml version="1.0" encoding="utf-8"?> <full-backup-content> <include domain="sharedpref" path="."/> <exclude domain="sharedpref" path="device.xml"/> </full-backup-content>
XML Config Syntax
The XML syntax for the configuration file is shown below:
<full-backup-content> <include domain=["file" | "database" | "sharedpref" | "external" | "root"] path="string" /> <exclude domain=["file" | "database" | "sharedpref" | "external" | "root"] path="string" /> </full-backup-content>
Inside the <full-backup-content>
tag, you can define
<include>
and <exclude>
elements:
-
<include>
- Specifies a file or folder to backup. By default, Auto Backup includes almost all app files. If you specify an <include> element, the system no longer includes any files by default and backs up only the files specified. To include multiple files, use multiple <include> elements.Note: Files in directories returned by
getCacheDir()
,getCodeCacheDir()
, orgetNoBackupFilesDir()
are always excluded even if you try to include them. -
<exclude>
- Specifies a file or folder to exclude during backup. Here are some files that are typically excluded from backup:- Files that have device specific identifiers, either issued by a server or generated on the device. For example, Google Cloud Messaging (GCM) needs to generate a registration token every time a user installs your app on a new device. If the old registration token is restored, the app may behave unexpectedly.
- Account credentials or other sensitive information. Consider asking the user to reauthenticate the first time they launch a restored app rather than allowing for storage of such information in the backup.
- Files related to app debugging, such as instant run files. To
exclude instant run files, add the rule
<exclude domain="file" path="instant-run"/>
- Large files that cause the app to exceed the 25MB backup quota.
Note: If your configuration file specifies both
elements, then the backup contains everything captured by the
<include>
elements minus the resources named in the
<exclude>
elements. In other words,
<exclude>
takes precedence.
Each element must include the following two attributes:
-
domain
- specifies the location of resource. Valid values for this attribute include the following:-
root
- the directory on the filesystem where all private files belonging to this app are stored. -
file
- directories returned bygetFilesDir()
. -
database
- directories returned bygetDatabasePath()
. Databases created withSQLiteOpenHelper
are stored here. -
sharedpref
- the directory whereSharedPreferences
are stored. -
external
the directory returned bygetExternalFilesDir()
-
-
path
: Specifies a file or folder to include in or exclude from backup. Note that:- This attribute does not support wildcard or regex syntax.
- You can use
.
to reference the current directory, however, you cannot reference the parent directory..
for security reasons. - If you specify a directory, then the rule applies to all files in the directory and recursive sub-directories.
Note: You cannot back up files outside of these locations.
Implementing BackupAgent
Apps that implement Auto Backup do not need to implement a BackupAgent
. However, you can optionally implement a
custom BackupAgent
. Typically, there are two
reasons for doing this:
- You want to receive notification of backup events such as,
onRestoreFinished()
oronQuotaExceeded(long, long)
. These callback methods are executed even if the app is not running. - You can't easily express the set of files you want to backup with XML
rules. In these rare cases, you can implement a BackupAgent that
overrides
onFullBackup(FullBackupDataOutput)
to store what you want. To retain the system's default implementation, call the corresponding method on the superclass withsuper.onFullBackup()
.
If you implement a BackupAgent, by default the system expects your app to
perform key/value backup and
restore. To use the file-based Auto Backup instead, set the
android:fullBackupOnly
attribute to true
in your app's manifest.
During auto backup and restore operations, the system launches the app in
a restricted mode to both prevent the app from accessing files that could
cause conflicts and let the app execute callback methods in its BackupAgent
. In this restricted mode, the app's main
activity is not automatically launched, its Content Providers
are not initialized, and the base-class Application
is instantiated instead of any subclass declared in the app's manifest.
Caution: To avoid errors, make sure that the parts of your app
that execute in the restricted mode (mostly your BackupAgent
) do not access content providers in the
same app or attempt to cast the Application
object.
If you cannot avoid those patterns, then consider implementing Key/Value backup or
disabling backup entirely.
Your BackupAgent
must implement the
abstract methods onBackup()
and onRestore()
, which are used for key-value backup. But if
you don't want to perform key-value backup, you can just leave your
implementation of those methods blank.
For more information, see Extending BackupAgent.