blob: fd35ada63bda31f1f07f4ccec7f651887e4346d3 [file] [log] [blame]
page.title=Using the Backup API
parent.title=Syncing to the Cloud
parent.link=index.html
trainingnavtop=true
next.title=Making the Most of Google Cloud Messaging
next.link=gcm.html
@jd:body
<div id="tb-wrapper">
<div id="tb">
<h2>This lesson teaches you to</h2>
<ol>
<li><a href="#register">Register for the Android Backup Service</a></li>
<li><a href="#manifest">Configure Your Manifest</a></li>
<li><a href="#agent">Write Your Backup Agent</a></li>
<li><a href="#backup">Request a Backup</a></li>
<li><a href="#restore">Restore from a Backup</a></li>
</ol>
<h2>You should also read</h2>
<ul>
<li><a
href="http://developer.android.com/guide/topics/data/backup.html">Data
Backup</a></li>
</ul>
</div>
</div>
<p>When a user purchases a new device or resets their existing one, they might
expect that when Google Play restores your app back to their device during the
initial setup, the previous data associated with the app restores as well. By
default, that doesn't happen and all the user's accomplishments or settings in
your app are lost.</p>
<p>For situations where the volume of data is relatively light (less than a
megabyte), like the user's preferences, notes, game high scores or other
stats, the Backup API provides a lightweight solution. This lesson walks you
through integrating the Backup API into your application, and restoring data to
new devices using the Backup API.</p>
<h2 id="register">Register for the Android Backup Service</h2>
<p>This lesson requires the use of the <a
href="{@docRoot}google/backup/index.html">Android Backup
Service</a>, which requires registration. Go ahead and <a
href="http://code.google.com/android/backup/signup.html">register here</a>. Once
that's done, the service pre-populates an XML tag for insertion in your Android
Manifest, which looks like this:</p>
<pre>
&lt;meta-data android:name="com.google.android.backup.api_key"
android:value="ABcDe1FGHij2KlmN3oPQRs4TUvW5xYZ" /&gt;
</pre>
<p>Note that each backup key works with a specific package name. If you have
different applications, register separate keys for each one.</p>
<h2 id="manifest">Configure Your Manifest</h2>
<p>Use of the Android Backup Service requires two additions to your application
manifest. First, declare the name of the class that acts as your backup agent,
then add the snippet above as a child element of the Application tag. Assuming
your backup agent is going to be called {@code TheBackupAgent}, here's an example of
what the manifest looks like with this tag included:</p>
<pre>
&lt;application android:label="MyApp"
android:backupAgent="TheBackupAgent"&gt;
...
&lt;meta-data android:name="com.google.android.backup.api_key"
android:value="ABcDe1FGHij2KlmN3oPQRs4TUvW5xYZ" /&gt;
...
&lt;/application&gt;
</pre>
<h2 id="agent">Write Your Backup Agent</h2>
<p>The easiest way to create your backup agent is by extending the wrapper class
{@link android.app.backup.BackupAgentHelper}. Creating this helper class is
actually a very simple process. Just create a class with the same name as you
used in the manifest in the previous step (in this example, {@code
TheBackupAgent}),
and extend {@code BackupAgentHelper}. Then override the {@link
android.app.backup.BackupAgent#onCreate()}.</p>
<p>Inside the {@link android.app.backup.BackupAgent#onCreate()} method, create a {@link
android.app.backup.BackupHelper}. These helpers are
specialized classes for backing up certain kinds of data. The Android framework
currently includes two such helpers: {@link
android.app.backup.FileBackupHelper} and {@link
android.app.backup.SharedPreferencesBackupHelper}. After you create the helper
and point it at the data you want to back up, just add it to the
BackupAgentHelper using the {@link android.app.backup.BackupAgentHelper#addHelper(String, BackupHelper) addHelper()}
method, adding a key which is used to
retrieve the data later. In most cases the entire
implementation is perhaps 10 lines of code.</p>
<p>Here's an example that backs up a high scores file.</p>
<pre>
import android.app.backup.BackupAgentHelper;
import android.app.backup.FileBackupHelper;
public class TheBackupAgent extends BackupAgentHelper {
// The name of the SharedPreferences file
static final String HIGH_SCORES_FILENAME = "scores";
// A key to uniquely identify the set of backup data
static final String FILES_BACKUP_KEY = "myfiles";
// Allocate a helper and add it to the backup agent
&#64;Override
void onCreate() {
FileBackupHelper helper = new FileBackupHelper(this, HIGH_SCORES_FILENAME);
addHelper(FILES_BACKUP_KEY, helper);
}
}
</pre>
<p>For added flexibility, {@link android.app.backup.FileBackupHelper}'s
constructor can take a variable number of filenames. You could just as easily
have backed up both a high scores file and a game progress file just by adding
an extra parameter, like this:</p>
<pre>
&#64;Override
void onCreate() {
FileBackupHelper helper = new FileBackupHelper(this, HIGH_SCORES_FILENAME, PROGRESS_FILENAME);
addHelper(FILES_BACKUP_KEY, helper);
}
</pre>
<p>Backing up preferences is similarly easy. Create a {@link
android.app.backup.SharedPreferencesBackupHelper} the same way you did a {@link
android.app.backup.FileBackupHelper}. In this case, instead of adding filenames
to the constructor, add the names of the shared preference groups being used by
your application. Here's an example of how your backup agent helper might look if
high scores are implemented as preferences instead of a flat file:</p>
<pre>
import android.app.backup.BackupAgentHelper;
import android.app.backup.SharedPreferencesBackupHelper;
public class TheBackupAgent extends BackupAgentHelper {
// The names of the SharedPreferences groups that the application maintains. These
// are the same strings that are passed to getSharedPreferences(String, int).
static final String PREFS_DISPLAY = "displayprefs";
static final String PREFS_SCORES = "highscores";
// An arbitrary string used within the BackupAgentHelper implementation to
// identify the SharedPreferencesBackupHelper's data.
static final String MY_PREFS_BACKUP_KEY = "myprefs";
// Simply allocate a helper and install it
void onCreate() {
SharedPreferencesBackupHelper helper =
new SharedPreferencesBackupHelper(this, PREFS_DISPLAY, PREFS_SCORES);
addHelper(MY_PREFS_BACKUP_KEY, helper);
}
}
</pre>
<p>You can add as many backup helper instances to your backup agent helper as you
like, but remember that you only need one of each type. One {@link
android.app.backup.FileBackupHelper} handles all the files that you need to back up, and one
{@link android.app.backup.SharedPreferencesBackupHelper} handles all the shared
preferencegroups you need backed up.
</p>
<h2 id="backup">Request a Backup</h2>
<p>In order to request a backup, just create an instance of the {@link
android.app.backup.BackupManager}, and call it's {@link
android.app.backup.BackupManager#dataChanged()} method.</p>
<pre>
import android.app.backup.BackupManager;
...
public void requestBackup() {
BackupManager bm = new BackupManager(this);
bm.dataChanged();
}
</pre>
<p>This call notifies the backup manager that there is data ready to be backed
up to the cloud. At some point in the future, the backup manager then calls
your backup agent's {@link
android.app.backup.BackupAgent#onBackup(ParcelFileDescriptor, BackupDataOutput,
ParcelFileDescriptor) onBackup()} method. You can make
the call whenever your data has changed, without having to worry about causing
excessive network activity. If you request a backup twice before a backup
occurs, the backup only occurs once.</p>
<h2 id="restore">Restore from a Backup</h2>
<p>Typically you shouldn't ever have to manually request a restore, as it
happens automatically when your application is installed on a device. However,
if it <em>is</em> necessary to trigger a manual restore, just call the
{@link android.app.backup.BackupManager#requestRestore(RestoreObserver) requestRestore()} method.</p>