• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1page.title=Using the Backup API
2parent.title=Syncing to the Cloud
3parent.link=index.html
4
5trainingnavtop=true
6
7next.title=Making the Most of Google Cloud Messaging
8next.link=gcm.html
9
10@jd:body
11
12<div id="tb-wrapper">
13  <div id="tb">
14    <h2>This lesson teaches you to</h2>
15    <ol>
16      <li><a href="#register">Register for the Android Backup Service</a></li>
17      <li><a href="#manifest">Configure Your Manifest</a></li>
18      <li><a href="#agent">Write Your Backup Agent</a></li>
19      <li><a href="#backup">Request a Backup</a></li>
20      <li><a href="#restore">Restore from a Backup</a></li>
21    </ol>
22    <h2>You should also read</h2>
23    <ul>
24      <li><a
25        href="http://developer.android.com/guide/topics/data/backup.html">Data
26        Backup</a></li>
27    </ul>
28  </div>
29</div>
30
31<p>When a user purchases a new device or resets their existing one, they might
32expect that when Google Play restores your app back to their device during the
33initial setup, the previous data associated with the app restores as well.  By
34default, that doesn't happen and all the user's accomplishments or settings in
35your app are lost.</p>
36<p>For situations where the volume of data is relatively light (less than a
37megabyte), like the user's preferences, notes, game high scores or other
38stats, the Backup API provides a lightweight solution.  This lesson walks you
39through integrating the Backup API into your application, and restoring data to
40new devices using the Backup API.</p>
41
42<h2 id="register">Register for the Android Backup Service</h2>
43<p>This lesson requires the use of the <a
44  href="http://code.google.com/android/backup/index.html">Android Backup
45  Service</a>, which requires registration.  Go ahead and <a
46  href="http://code.google.com/android/backup/signup.html">register here</a>.  Once
47that's done, the service pre-populates an XML tag for insertion in your Android
48Manifest, which looks like this:</p>
49<pre>
50&lt;meta-data android:name="com.google.android.backup.api_key"
51android:value="ABcDe1FGHij2KlmN3oPQRs4TUvW5xYZ" /&gt;
52</pre>
53<p>Note that each backup key works with a specific package name.  If you have
54different applications, register separate keys for each one.</p>
55
56
57<h2 id="manifest">Configure Your Manifest</h2>
58<p>Use of the Android Backup Service requires two additions to your application
59manifest.  First, declare the name of the class that acts as your backup agent,
60then add the snippet above as a child element of the Application tag.  Assuming
61your backup agent is going to be called {@code TheBackupAgent}, here's an example of
62what the manifest looks like with this tag included:</p>
63
64<pre>
65&lt;application android:label="MyApp"
66             android:backupAgent="TheBackupAgent"&gt;
67    ...
68    &lt;meta-data android:name="com.google.android.backup.api_key"
69    android:value="ABcDe1FGHij2KlmN3oPQRs4TUvW5xYZ" /&gt;
70    ...
71&lt;/application&gt;
72</pre>
73<h2 id="agent">Write Your Backup Agent</h2>
74<p>The easiest way to create your backup agent is by extending the wrapper class
75{@link android.app.backup.BackupAgentHelper}.  Creating this helper class is
76actually a very simple process.  Just create a class with the same name as you
77used in the manifest in the previous step (in this example, {@code
78TheBackupAgent}),
79and extend {@code BackupAgentHelper}.  Then override the {@link
80android.app.backup.BackupAgent#onCreate()}.</p>
81
82<p>Inside the {@link android.app.backup.BackupAgent#onCreate()} method, create a {@link
83android.app.backup.BackupHelper}.  These helpers are
84specialized classes for backing up certain kinds of data.  The Android framework
85currently includes two such helpers:  {@link
86android.app.backup.FileBackupHelper} and {@link
87android.app.backup.SharedPreferencesBackupHelper}.  After you create the helper
88and point it at the data you want to back up, just add it to the
89BackupAgentHelper using the {@link android.app.backup.BackupAgentHelper#addHelper(String, BackupHelper) addHelper()}
90method, adding a key which is used to
91retrieve the data later.  In most cases the entire
92implementation is perhaps 10 lines of code.</p>
93
94<p>Here's an example that backs up a high scores file.</p>
95
96<pre>
97 import android.app.backup.BackupAgentHelper;
98 import android.app.backup.FileBackupHelper;
99
100
101 public class TheBackupAgent extends BackupAgentHelper {
102    // The name of the SharedPreferences file
103    static final String HIGH_SCORES_FILENAME = "scores";
104
105    // A key to uniquely identify the set of backup data
106    static final String FILES_BACKUP_KEY = "myfiles";
107
108    // Allocate a helper and add it to the backup agent
109    &#64;Override
110    void onCreate() {
111        FileBackupHelper helper = new FileBackupHelper(this, HIGH_SCORES_FILENAME);
112        addHelper(FILES_BACKUP_KEY, helper);
113    }
114}
115</pre>
116<p>For added flexibility, {@link android.app.backup.FileBackupHelper}'s
117constructor can take a variable number of filenames.  You could just as easily
118have backed up both a high scores file and a game progress file just by adding
119an extra parameter, like this:</p>
120<pre>
121    &#64;Override
122    void onCreate() {
123        FileBackupHelper helper = new FileBackupHelper(this, HIGH_SCORES_FILENAME, PROGRESS_FILENAME);
124        addHelper(FILES_BACKUP_KEY, helper);
125    }
126</pre>
127<p>Backing up preferences is similarly easy.  Create a {@link
128android.app.backup.SharedPreferencesBackupHelper}  the same way you did a {@link
129android.app.backup.FileBackupHelper}.  In this case, instead of adding filenames
130to the constructor, add the names of the shared preference groups being used by
131your application.  Here's an example of how your backup agent helper might look if
132high scores are implemented as preferences instead of a flat file:</p>
133
134<pre>
135 import android.app.backup.BackupAgentHelper;
136 import android.app.backup.SharedPreferencesBackupHelper;
137
138 public class TheBackupAgent extends BackupAgentHelper {
139     // The names of the SharedPreferences groups that the application maintains.  These
140     // are the same strings that are passed to getSharedPreferences(String, int).
141     static final String PREFS_DISPLAY = "displayprefs";
142     static final String PREFS_SCORES = "highscores";
143
144     // An arbitrary string used within the BackupAgentHelper implementation to
145     // identify the SharedPreferencesBackupHelper's data.
146     static final String MY_PREFS_BACKUP_KEY = "myprefs";
147
148     // Simply allocate a helper and install it
149     void onCreate() {
150         SharedPreferencesBackupHelper helper =
151                 new SharedPreferencesBackupHelper(this, PREFS_DISPLAY, PREFS_SCORES);
152         addHelper(MY_PREFS_BACKUP_KEY, helper);
153     }
154 }
155</pre>
156
157<p>You can add as many backup helper instances to your backup agent helper as you
158like, but remember that you only need one of each type.  One {@link
159android.app.backup.FileBackupHelper} handles all the files that you need to back up, and one
160{@link android.app.backup.SharedPreferencesBackupHelper} handles all the shared
161preferencegroups you need backed up.
162</p>
163
164
165<h2 id="backup">Request a Backup</h2>
166<p>In order to request a backup, just create an instance of the {@link
167android.app.backup.BackupManager}, and call it's {@link
168android.app.backup.BackupManager#dataChanged()} method.</p>
169
170<pre>
171 import android.app.backup.BackupManager;
172 ...
173
174 public void requestBackup() {
175   BackupManager bm = new BackupManager(this);
176   bm.dataChanged();
177 }
178</pre>
179
180<p>This call notifies the backup manager that there is data ready to be backed
181up to the cloud.  At some point in the future, the backup manager then calls
182your backup agent's {@link
183android.app.backup.BackupAgent#onBackup(ParcelFileDescriptor, BackupDataOutput,
184ParcelFileDescriptor) onBackup()} method.  You can make
185the call whenever your data has changed, without having to worry about causing
186excessive network activity.  If you request a backup twice before a backup
187occurs, the backup only occurs once.</p>
188
189
190<h2 id="restore">Restore from a Backup</h2>
191<p>Typically you shouldn't ever have to manually request a restore, as it
192happens automatically when your application is installed on a device.  However,
193if it <em>is</em> necessary to trigger a manual restore, just call the
194{@link android.app.backup.BackupManager#requestRestore(RestoreObserver) requestRestore()} method.</p>
195