Using Backup Services Android

Android backup services were introduced in Android 2.2 (API Level 8).Applications can use the backup system service to request that application data such as shared preferences and files be backed up or restored. The backup service handles things from there, sending or retrieving the appropriate backup archives to a remote backup service.

Backup services should not be used for syncing application content. Backup and restore operations do not occur on demand. Use a synchronization strategy such as the sync adapter discussed earlier in this chapter in this case. Use Android backup services only to back up important application data.

Choosing a Remote Backup Service

One of the most important decisions when it comes to backing up application data is deciding where to back it up to. The remote backup service you choose should be secure, reliable, and always available. Many developers will likely choose the solution provided by Google: Android Backup Service.

In order for your application to use Android Backup Service, you must register your application with Google and acquire a unique backup service key for use within the application’s manifest file.

You can sign up for Google’s backup service at the Android Backup Service website.

Registering with Android Backup Service

After you have chosen a remote backup service, you might need to jump through a few more hoops. With Google’s Android Backup Service, you need to register for a special key to use. After you’ve acquired this key, you can use it within your application’s manifest file using the <meta-data> tag within the <application> block, like this:

<meta-data android:name="com.google.android.backup.api_key"
android:value="KEY HERE" />

Implementing a Backup Agent

The backup system service relies upon an application’s backup agent to determine what application data should be archived for backup and restore purposes.

Providing a Backup Agent Implementation

Now it’s time to implement the backup agent for your particular application. The backup agent determines what application data to send to the backup service. If you only want to back up shared preference data and application files, you can simply use the BackupAgentHelper class.

Here is a sample implementation of a backup agent class:

public class SimpleBackupAgent extends BackupAgentHelper {
@Override
public void onCreate() {
// Register helpers here
}
}

Your application’s backup agent needs to include a backup helper for each type of data it wants to back up.

Implementing a Backup Helper for Shared Preferences

To back up shared preferences files, you need to use the SharedPreferencesBackupHelper class. Adding support for shared preferences is very straightforward. Simply update the backup agent’s onCreate() method, create a valid SharedPreferencesBackupHelper object, and use the addHelper() method to add it to the agent:

SharedPreferencesBackupHelper prefshelper = new
SharedPreferencesBackupHelper(this,
PREFERENCE_FILENAME);
addHelper(BACKUP_PREFERENCE_KEY, prefshelper);

This particular helper backs up all shared preferences by name. In this case, the addHelper() method takes two parameters:

  • A unique name for this helper (in this case, the backup key is stored as a String variable called BACKUP_PREFERENCE_KEY).
  • A valid SharedPreferencesBackupHelper object configured to control backups and restores on a specific set of shared preferences by name (in this case, the preference filename is stored in a String variable called PREFERENCE_FILENAME).

That’s it. In fact, if your application is only backing up shared preferences, you don’t even need to implement the onBackup() and onRestore() methods of your backup agent class.

Implementing a Backup Helper for Files

To back up application files, use the FileBackupHelper class. Files are a bit trickier to handle than shared preferences because they are not thread-safe. Begin by updating the backup agent’s onCreate() method, create a valid FileBackupHelper object, and use the addHelper() method to add it to the agent:

FileBackupHelper filehelper = new FileBackupHelper(this, APP_FILE_NAME);
addHelper(BACKUP_FILE_KEY, filehelper);

The file helper backs up specific files by name. In this case, the addHelper() method takes two parameters:

  • A unique name for this helper (in this case, the backup key is stored as a String variable called BACKUP_FILE_KEY).
  • A valid FileBackupHelper object configured to control backups and restores on a specific file by name (in this case, the filename is stored in a String variable called APP_FILE_NAME).

You also need to make sure that all file operations within your application are thread-safe as it’s possible a backup will be requested while a file is being accessed. The Android website suggests the following method for defining a lock from a simple Object array within your Activity, as follows:

static final Object[] fileLock = new Object[0];

Use this lock each and every time you are performing file operations, either in your application logic, or within the backup agent. For example:

synchronized(fileLock){
// Do app logic file operations here
}

Finally, you need to override the onBackup() and onRestore() methods of your backup agent, if only to make sure all file operations are synchronized using your lock for thread-safe access. Here we have the full implementation of a backup agent that backs up one set of shared preferences called AppPrefs and a file named appfile.txt:

public class SimpleBackupAgent extends BackupAgentHelper {
private static final String PREFERENCE_FILENAME = "AppPrefs";
private static final String APP_FILE_NAME = "appfile.txt";
static final String BACKUP_PREFERENCE_KEY = "BackupAppPrefs";
static final String BACKUP_FILE_KEY = "BackupFile";
@Override
public void onCreate() {
SharedPreferencesBackupHelper prefshelper = new
SharedPreferencesBackupHelper(this,
PREFERENCE_FILENAME);
addHelper(BACKUP_PREFERENCE_KEY, prefshelper);
FileBackupHelper filehelper =
new FileBackupHelper(this, APP_FILE_NAME);
addHelper(BACKUP_FILE_KEY, filehelper);
}
@Override
public void onBackup(ParcelFileDescriptor oldState,
BackupDataOutput data, ParcelFileDescriptor newState)
throws IOException {
synchronized (SimpleBackupActivity.fileLock) {
super.onBackup(oldState, data, newState);
}
}
@Override
public void onRestore(BackupDataInput data, int appVersionCode,
ParcelFileDescriptor newState) throws IOException {
synchronized (SimpleBackupActivity.fileLock) {
super.onRestore(data, appVersionCode, newState);
}
}
}

To make the doBackup() and doRestore() methods thread-safe, we simply wrapped the super class call with a synchronized block using your file lock.

Registering the Backup Agent in the Application Manifest File

Finally, you need to register your backup agent class in your application’s manifest file using the android: backupAgent attribute of the <application> tab. For example, if your backup agent class is called SimpleBackupAgent, you would register it using its fully qualified path name as follows:

<application
android:icon="@drawable/icon"
android:label="@string/app_name"
android:backupAgent="com.androidbook.simplebackup.SimpleBackupAgent">

Backing Up and Restoring Application Data

The BackupManager system service manages backup and restore requests. This service works in the background, on its own schedule. Applications that implement a backup agent can request a backup or restore, but the operations might not happen immediately. To get an instance of the BackupManager, simply create one within your Activity class, as follows:

BackupManager mBackupManager = new BackupManager(this);

Requesting a Backup

An application can request a backup using the dataChanged() method. Generally, this method should be called any time application data that is to be archived changes. It can be called any number of times, but when it’s time to back up, the backup takes place only one time, regardless of how many times dataChanged() was called before the backup.

mBackupManager.dataChanged();

Normally, the user does not initiate a backup. Instead, whenever important application data changes, the dataChanged() method should be called as part of the data saving process. At some point in the future, a backup is performed “behind the scenes” by the backup manager.

Requesting a Restore

Restore operations occur automatically when a user resets his device or upgrades after “accidentally” dropping his old one in a hot tub or runs it through the washing machine (happens more often than you’d think).When a restore occurs, the user’s data is fetched from the remote backup service and the application’s backup agent refreshes the data used by the application, overwriting any data that was there.

An application can directly request a restore using the requestRestore() method as well. The requestRestore() method takes one parameter: a RestoreObserver object. The following code illustrates how to request a restore:

RestoreObserver obs = new RestoreObserver(){
@Override
public void onUpdate(int nowBeingRestored, String currentPackage) {
Log.i(DEBUG_TAG, "RESTORING: " + currentPackage);
}
@Override
public void restoreFinished(int error) {
Log.i(DEBUG_TAG, "RESTORE FINISHED! ("+error+")");
}
@Override
public void restoreStarting(int numPackages) {
Log.i(DEBUG_TAG, "RESTORE STARTING...");
}
};
try {
mBackupManager.requestRestore(obs);
} catch (Exception e) {
Log.i(DEBUG_TAG,
"Failed to request restore. Try adb bmgr restore...");
}



Face Book Twitter Google Plus Instagram Youtube Linkedin Myspace Pinterest Soundcloud Wikipedia

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Android Topics