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 href="{@docRoot}guide/topics/data/backup.html">Data Backup</a></li> 25 <li><a href="{@docRoot}training/backup/autosyncapi.html">Configuring Auto Backup for Apps</a> 26 (Android 6.0 (API level 23) and higher)</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. On versions of Android 34prior to 6.0 (API level 23), app data is not restored by default, and all the user's accomplishments 35or settings in your 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. 41 42<p class="note"> 43<strong>Note:</strong> Devices running Android 6.0 and higher 44<a href="{@docRoot}training/backup/autosyncapi.html">automatically back up</a> 45nearly all data by default. 46</p> 47 48<h2 id="register">Register for the Android Backup Service</h2> 49<p>This lesson requires the use of the <a 50 href="{@docRoot}google/backup/index.html">Android Backup 51 Service</a>, which requires registration. Go ahead and <a 52 href="http://code.google.com/android/backup/signup.html">register here</a>. Once 53that's done, the service pre-populates an XML tag for insertion in your Android 54Manifest, which looks like this:</p> 55<pre> 56<meta-data android:name="com.google.android.backup.api_key" 57android:value="ABcDe1FGHij2KlmN3oPQRs4TUvW5xYZ" /> 58</pre> 59<p>Note that each backup key works with a specific package name. If you have 60different applications, register separate keys for each one.</p> 61 62 63<h2 id="manifest">Configure Your Manifest</h2> 64<p>Use of the Android Backup Service requires two additions to your application 65manifest. First, declare the name of the class that acts as your backup agent, 66then add the snippet above as a child element of the Application tag. Assuming 67your backup agent is going to be called {@code TheBackupAgent}, here's an example of 68what the manifest looks like with this tag included:</p> 69 70<pre> 71<application android:label="MyApp" 72 android:backupAgent="TheBackupAgent"> 73 ... 74 <meta-data android:name="com.google.android.backup.api_key" 75 android:value="ABcDe1FGHij2KlmN3oPQRs4TUvW5xYZ" /> 76 ... 77</application> 78</pre> 79<h2 id="agent">Write Your Backup Agent</h2> 80<p>The easiest way to create your backup agent is by extending the wrapper class 81{@link android.app.backup.BackupAgentHelper}. Creating this helper class is 82actually a very simple process. Just create a class with the same name as you 83used in the manifest in the previous step (in this example, {@code 84TheBackupAgent}), 85and extend {@code BackupAgentHelper}. Then override the {@link 86android.app.backup.BackupAgent#onCreate()}.</p> 87 88<p>Inside the {@link android.app.backup.BackupAgent#onCreate()} method, create a {@link 89android.app.backup.BackupHelper}. These helpers are 90specialized classes for backing up certain kinds of data. The Android framework 91currently includes two such helpers: {@link 92android.app.backup.FileBackupHelper} and {@link 93android.app.backup.SharedPreferencesBackupHelper}. After you create the helper 94and point it at the data you want to back up, just add it to the 95BackupAgentHelper using the {@link android.app.backup.BackupAgentHelper#addHelper(String, BackupHelper) addHelper()} 96method, adding a key which is used to 97retrieve the data later. In most cases the entire 98implementation is perhaps 10 lines of code.</p> 99 100<p>Here's an example that backs up a high scores file.</p> 101 102<pre> 103import android.app.backup.BackupAgentHelper; 104import android.app.backup.FileBackupHelper; 105 106 107public class TheBackupAgent extends BackupAgentHelper { 108 // The name of the SharedPreferences file 109 static final String HIGH_SCORES_FILENAME = "scores"; 110 111 // A key to uniquely identify the set of backup data 112 static final String FILES_BACKUP_KEY = "myfiles"; 113 114 // Allocate a helper and add it to the backup agent 115 @Override 116 void onCreate() { 117 FileBackupHelper helper = new FileBackupHelper(this, HIGH_SCORES_FILENAME); 118 addHelper(FILES_BACKUP_KEY, helper); 119 } 120} 121</pre> 122<p>For added flexibility, {@link android.app.backup.FileBackupHelper}'s 123constructor can take a variable number of filenames. You could just as easily 124have backed up both a high scores file and a game progress file just by adding 125an extra parameter, like this:</p> 126<pre> 127@Override 128 void onCreate() { 129 FileBackupHelper helper = new FileBackupHelper(this, HIGH_SCORES_FILENAME, PROGRESS_FILENAME); 130 addHelper(FILES_BACKUP_KEY, helper); 131 } 132</pre> 133<p>Backing up preferences is similarly easy. Create a {@link 134android.app.backup.SharedPreferencesBackupHelper} the same way you did a {@link 135android.app.backup.FileBackupHelper}. In this case, instead of adding filenames 136to the constructor, add the names of the shared preference groups being used by 137your application. Here's an example of how your backup agent helper might look if 138high scores are implemented as preferences instead of a flat file:</p> 139 140<pre> 141import android.app.backup.BackupAgentHelper; 142import android.app.backup.SharedPreferencesBackupHelper; 143 144public class TheBackupAgent extends BackupAgentHelper { 145 // The names of the SharedPreferences groups that the application maintains. These 146 // are the same strings that are passed to getSharedPreferences(String, int). 147 static final String PREFS_DISPLAY = "displayprefs"; 148 static final String PREFS_SCORES = "highscores"; 149 150 // An arbitrary string used within the BackupAgentHelper implementation to 151 // identify the SharedPreferencesBackupHelper's data. 152 static final String MY_PREFS_BACKUP_KEY = "myprefs"; 153 154 // Simply allocate a helper and install it 155 void onCreate() { 156 SharedPreferencesBackupHelper helper = 157 new SharedPreferencesBackupHelper(this, PREFS_DISPLAY, PREFS_SCORES); 158 addHelper(MY_PREFS_BACKUP_KEY, helper); 159 } 160} 161</pre> 162 163<p>You can add as many backup helper instances to your backup agent helper as you 164like, but remember that you only need one of each type. One {@link 165android.app.backup.FileBackupHelper} handles all the files that you need to back up, and one 166{@link android.app.backup.SharedPreferencesBackupHelper} handles all the shared 167preferencegroups you need backed up. 168</p> 169 170 171<h2 id="backup">Request a Backup</h2> 172<p>In order to request a backup, just create an instance of the {@link 173android.app.backup.BackupManager}, and call it's {@link 174android.app.backup.BackupManager#dataChanged()} method.</p> 175 176<pre> 177import android.app.backup.BackupManager; 178... 179 180public void requestBackup() { 181 BackupManager bm = new BackupManager(this); 182 bm.dataChanged(); 183} 184</pre> 185 186<p>This call notifies the backup manager that there is data ready to be backed 187up to the cloud. At some point in the future, the backup manager then calls 188your backup agent's {@link 189android.app.backup.BackupAgent#onBackup(ParcelFileDescriptor, BackupDataOutput, 190ParcelFileDescriptor) onBackup()} method. You can make 191the call whenever your data has changed, without having to worry about causing 192excessive network activity. If you request a backup twice before a backup 193occurs, the backup only occurs once.</p> 194 195 196<h2 id="restore">Restore from a Backup</h2> 197<p>Typically you shouldn't ever have to manually request a restore, as it 198happens automatically when your application is installed on a device. However, 199if it <em>is</em> necessary to trigger a manual restore, just call the 200{@link android.app.backup.BackupManager#requestRestore(RestoreObserver) requestRestore()} method.</p> 201