BackupAgent


public abstract class BackupAgent
extends ContextWrapper

java.lang.Object
   ↳ android.content.Context
     ↳ android.content.ContextWrapper
       ↳ android.app.backup.BackupAgent


Provides the central interface between an application and Android's data backup infrastructure. An application that wishes to participate in the backup and restore mechanism will declare a subclass of BackupAgent, implement the onBackup() and onRestore() methods, and provide the name of its backup agent class in its AndroidManifest.xml file via the <application> tag's android:backupAgent attribute.

Developer Guides

For more information about using BackupAgent, read the Data Backup developer guide.

Basic Operation

When the application makes changes to data that it wishes to keep backed up, it should call the BackupManager.dataChanged() method. This notifies the Android Backup Manager that the application needs an opportunity to update its backup image. The Backup Manager, in turn, schedules a backup pass to be performed at an opportune time.

Restore operations are typically performed only when applications are first installed on a device. At that time, the operating system checks to see whether there is a previously-saved data set available for the application being installed, and if so, begins an immediate restore pass to deliver the backup data as part of the installation process.

When a backup or restore pass is run, the application's process is launched (if not already running), the manifest-declared backup agent class (in the android:backupAgent attribute) is instantiated within that process, and the agent's onCreate() method is invoked. This prepares the agent instance to run the actual backup or restore logic. At this point the agent's onBackup() or onRestore() method will be invoked as appropriate for the operation being performed.

A backup data set consists of one or more "entities," flattened binary data records that are each identified with a key string unique within the data set. Adding a record to the active data set or updating an existing record is done by simply writing new entity data under the desired key. Deleting an entity from the data set is done by writing an entity under that key with header specifying a negative data size, and no actual entity data.

Helper Classes

An extensible agent based on convenient helper classes is available in BackupAgentHelper. That class is particularly suited to handling of simple file or SharedPreferences backup and restore.

Threading

The constructor, as well as onCreate() and onDestroy() lifecycle callbacks run on the main thread (UI thread) of the application that implements the BackupAgent. The data-handling callbacks: onBackup(), onFullBackup(android.app.backup.FullBackupDataOutput), onRestore(), onRestoreFile(), onRestoreFinished(), and onQuotaExceeded() run on binder pool threads.

Summary

Constants

int FLAG_CLIENT_SIDE_ENCRYPTION_ENABLED

Flag for BackupDataOutput#getTransportFlags() and FullBackupDataOutput#getTransportFlags() only.

int FLAG_DEVICE_TO_DEVICE_TRANSFER

Flag for BackupDataOutput#getTransportFlags() and FullBackupDataOutput#getTransportFlags() only.

int TYPE_DIRECTORY

During a full restore, indicates that the file system object being restored is a directory.

int TYPE_FILE

During a full restore, indicates that the file system object being restored is an ordinary file.

Inherited constants

Public constructors

BackupAgent()

Public methods

final void fullBackupFile(File file, FullBackupDataOutput output)

Write an entire file as part of a full-backup operation.

abstract void onBackup(ParcelFileDescriptor oldState, BackupDataOutput data, ParcelFileDescriptor newState)

The application is being asked to write any data changed since the last time it performed a backup operation.

void onCreate()

Provided as a convenience for agent implementations that need an opportunity to do one-time initialization before the actual backup or restore operation is begun.

void onDestroy()

Provided as a convenience for agent implementations that need to do some sort of shutdown process after backup or restore is completed.

void onFullBackup(FullBackupDataOutput data)

The application is having its entire file system contents backed up.

void onQuotaExceeded(long backupDataBytes, long quotaBytes)

Notification that the application's current backup operation causes it to exceed the maximum size permitted by the transport.

abstract void onRestore(BackupDataInput data, int appVersionCode, ParcelFileDescriptor newState)

The application is being restored from backup and should replace any existing data with the contents of the backup.

void onRestore(BackupDataInput data, long appVersionCode, ParcelFileDescriptor newState)

New version of onRestore(android.app.backup.BackupDataInput, int, android.os.ParcelFileDescriptor) that handles a long app version code.

void onRestoreFile(ParcelFileDescriptor data, long size, File destination, int type, long mode, long mtime)

Handle the data delivered via the given file descriptor during a full restore operation.

void onRestoreFinished()

The application's restore operation has completed.

Inherited methods

Constants

FLAG_CLIENT_SIDE_ENCRYPTION_ENABLED

Added in API level 28
public static final int FLAG_CLIENT_SIDE_ENCRYPTION_ENABLED

Flag for BackupDataOutput#getTransportFlags() and FullBackupDataOutput#getTransportFlags() only.

The transport has client-side encryption enabled. i.e., the user's backup has been encrypted with a key known only to the device, and not to the remote storage solution. Even if an attacker had root access to the remote storage provider they should not be able to decrypt the user's backup data.

Constant Value: 1 (0x00000001)

FLAG_DEVICE_TO_DEVICE_TRANSFER

Added in API level 28
public static final int FLAG_DEVICE_TO_DEVICE_TRANSFER

Flag for BackupDataOutput#getTransportFlags() and FullBackupDataOutput#getTransportFlags() only.

The transport is for a device-to-device transfer. There is no third party or intermediate storage. The user's backup data is sent directly to another device over e.g., USB or WiFi.

Constant Value: 2 (0x00000002)

TYPE_DIRECTORY

Added in API level 14
public static final int TYPE_DIRECTORY

During a full restore, indicates that the file system object being restored is a directory.

Constant Value: 2 (0x00000002)

TYPE_FILE

Added in API level 14
public static final int TYPE_FILE

During a full restore, indicates that the file system object being restored is an ordinary file.

Constant Value: 1 (0x00000001)

Public constructors

BackupAgent

Added in API level 8
public BackupAgent ()

Public methods

fullBackupFile

Added in API level 14
public final void fullBackupFile (File file, 
                FullBackupDataOutput output)

Write an entire file as part of a full-backup operation. The file's contents will be delivered to the backup destination along with the metadata necessary to place it with the proper location and permissions on the device where the data is restored.

Attempting to back up files in directories that are ignored by the backup system will have no effect. For example, if the app calls this method with a file inside the ContextWrapper.getNoBackupFilesDir() directory, it will be ignored. See onFullBackup(android.app.backup.FullBackupDataOutput) for details on what directories are excluded from backups.

Parameters
file File: The file to be backed up. The file must exist and be readable by the caller.

output FullBackupDataOutput: The destination to which the backed-up file data will be sent.

onBackup

Added in API level 8
public abstract void onBackup (ParcelFileDescriptor oldState, 
                BackupDataOutput data, 
                ParcelFileDescriptor newState)

The application is being asked to write any data changed since the last time it performed a backup operation. The state data recorded during the last backup pass is provided in the oldState file descriptor. If oldState is null, no old state is available and the application should perform a full backup. In both cases, a representation of the final backup state after this pass should be written to the file pointed to by the file descriptor wrapped in newState.

Each entity written to the BackupDataOutput data stream will be transmitted over the current backup transport and stored in the remote data set under the key supplied as part of the entity. Writing an entity with a negative data size instructs the transport to delete whatever entity currently exists under that key from the remote data set.

Parameters
oldState ParcelFileDescriptor: An open, read-only ParcelFileDescriptor pointing to the last backup state provided by the application. May be null, in which case no prior state is being provided and the application should perform a full backup.

data BackupDataOutput: A structured wrapper around an open, read/write file descriptor pointing to the backup data destination. Typically the application will use backup helper classes to write to this file.

newState ParcelFileDescriptor: An open, read/write ParcelFileDescriptor pointing to an empty file. The application should record the final backup state here after writing the requested data to the data output stream.

Throws
IOException

onCreate

Added in API level 8
public void onCreate ()

Provided as a convenience for agent implementations that need an opportunity to do one-time initialization before the actual backup or restore operation is begun.

onDestroy

Added in API level 8
public void onDestroy ()

Provided as a convenience for agent implementations that need to do some sort of shutdown process after backup or restore is completed.

Agents do not need to override this method.

onFullBackup

Added in API level 14
public void onFullBackup (FullBackupDataOutput data)

The application is having its entire file system contents backed up. data points to the backup destination, and the app has the opportunity to choose which files are to be stored. To commit a file as part of the backup, call the fullBackupFile(java.io.File, android.app.backup.FullBackupDataOutput) helper method. After all file data is written to the output, the agent returns from this method and the backup operation concludes.

Certain parts of the app's data are never backed up even if the app explicitly sends them to the output:

The default implementation of this method backs up the entirety of the application's "owned" file system trees to the output other than the few exceptions listed above. Apps only need to override this method if they need to impose special limitations on which files are being stored beyond the control that ContextWrapper.getNoBackupFilesDir() offers. Alternatively they can provide an xml resource to specify what data to include or exclude.

Parameters
data FullBackupDataOutput: A structured wrapper pointing to the backup destination.

Throws
java.io.IOException
IOException

onQuotaExceeded

Added in API level 24
public void onQuotaExceeded (long backupDataBytes, 
                long quotaBytes)

Notification that the application's current backup operation causes it to exceed the maximum size permitted by the transport. The ongoing backup operation is halted and rolled back: any data that had been stored by a previous backup operation is still intact. Typically the quota-exceeded state will be detected before any data is actually transmitted over the network.

The quotaBytes value is the total data size currently permitted for this application. If desired, the application can use this as a hint for determining how much data to store. For example, a messaging application might choose to store only the newest messages, dropping enough older content to stay under the quota.

Note that the maximum quota for the application can change over time. In particular, in the future the quota may grow. Applications that adapt to the quota when deciding what data to store should be aware of this and implement their data storage mechanisms in a way that can take advantage of additional quota.

Parameters
backupDataBytes long: The amount of data measured while initializing the backup operation, if the total exceeds the app's alloted quota. If initial measurement suggested that the data would fit but then too much data was actually submitted as part of the operation, then this value is the amount of data that had been streamed into the transport at the time the quota was reached.

quotaBytes long: The maximum data size that the transport currently permits this application to store as a backup.

onRestore

Added in API level 8
public abstract void onRestore (BackupDataInput data, 
                int appVersionCode, 
                ParcelFileDescriptor newState)

The application is being restored from backup and should replace any existing data with the contents of the backup. The backup data is provided through the data parameter. Once the restore is finished, the application should write a representation of the final state to the newState file descriptor.

The application is responsible for properly erasing its old data and replacing it with the data supplied to this method. No "clear user data" operation will be performed automatically by the operating system. The exception to this is in the case of a failed restore attempt: if onRestore() throws an exception, the OS will assume that the application's data may now be in an incoherent state, and will clear it before proceeding.

Parameters
data BackupDataInput: A structured wrapper around an open, read-only file descriptor pointing to a full snapshot of the application's data. The application should consume every entity represented in this data stream.

appVersionCode int: The value of the android:versionCode manifest attribute, from the application that backed up this particular data set. This makes it possible for an application's agent to distinguish among any possible older data versions when asked to perform the restore operation.

newState ParcelFileDescriptor: An open, read/write ParcelFileDescriptor pointing to an empty file. The application should record the final backup state here after restoring its data from the data stream. When a full-backup dataset is being restored, this will be null.

Throws
IOException

onRestore

Added in API level 28
public void onRestore (BackupDataInput data, 
                long appVersionCode, 
                ParcelFileDescriptor newState)

New version of onRestore(android.app.backup.BackupDataInput, int, android.os.ParcelFileDescriptor) that handles a long app version code. Default implementation casts the version code to an int and calls onRestore(android.app.backup.BackupDataInput, int, android.os.ParcelFileDescriptor).

Parameters
data BackupDataInput

appVersionCode long

newState ParcelFileDescriptor

Throws
IOException

onRestoreFile

Added in API level 14
public void onRestoreFile (ParcelFileDescriptor data, 
                long size, 
                File destination, 
                int type, 
                long mode, 
                long mtime)

Handle the data delivered via the given file descriptor during a full restore operation. The agent is given the path to the file's original location as well as its size and metadata.

The file descriptor can only be read for size bytes; attempting to read more data has undefined behavior.

The default implementation creates the destination file/directory and populates it with the data from the file descriptor, then sets the file's access mode and modification time to match the restore arguments.

Parameters
data ParcelFileDescriptor: A read-only file descriptor from which the agent can read size bytes of file data.

size long: The number of bytes of file content to be restored to the given destination. If the file system object being restored is a directory, size will be zero.

destination File: The File on disk to be restored with the given data.

type int: The kind of file system object being restored. This will be either BackupAgent#TYPE_FILE or BackupAgent#TYPE_DIRECTORY.

mode long: The access mode to be assigned to the destination after its data is written. This is in the standard format used by chmod().

mtime long: The modification time of the file when it was backed up, suitable to be assigned to the file after its data is written.

Throws
java.io.IOException
IOException

onRestoreFinished

Added in API level 21
public void onRestoreFinished ()

The application's restore operation has completed. This method is called after all available data has been delivered to the application for restore (via either the onRestore() or onRestoreFile() callbacks). This provides the app with a stable end-of-restore opportunity to perform any appropriate post-processing on the data that was just delivered.