Home | History | Annotate | Download | only in backup
      1 page.title=Using the Backup API
      2 parent.title=Backing up App Data to the Cloud
      3 parent.link=index.html
      4 
      5 trainingnavtop=true
      6 
      7 next.title=Making the Most of Google Cloud Messaging
      8 next.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
     32 expect that when Google Play restores your app back to their device during the
     33 initial setup, the previous data associated with the app restores as well. On versions of Android
     34 prior to 6.0 (API level 23), app data is not restored by default, and all the user's accomplishments
     35 or settings in your app are lost.</p>
     36 <p>For situations where the volume of data is relatively light (less than a
     37 megabyte), like the user's preferences, notes, game high scores or other
     38 stats, the Backup API provides a lightweight solution.  This lesson walks you
     39 through integrating the Backup API into your application, and restoring data to
     40 new 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>
     45 nearly 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
     53 that's done, the service pre-populates an XML tag for insertion in your Android
     54 Manifest, which looks like this:</p>
     55 <pre>
     56 &lt;meta-data android:name="com.google.android.backup.api_key"
     57 android:value="ABcDe1FGHij2KlmN3oPQRs4TUvW5xYZ" /&gt;
     58 </pre>
     59 <p>Note that each backup key works with a specific package name.  If you have
     60 different 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
     65 manifest.  First, declare the name of the class that acts as your backup agent,
     66 then add the snippet above as a child element of the Application tag.  Assuming
     67 your backup agent is going to be called {@code TheBackupAgent}, here's an example of
     68 what the manifest looks like with this tag included:</p>
     69 
     70 <pre>
     71 &lt;application android:label="MyApp"
     72              android:backupAgent="TheBackupAgent"&gt;
     73     ...
     74     &lt;meta-data android:name="com.google.android.backup.api_key"
     75     android:value="ABcDe1FGHij2KlmN3oPQRs4TUvW5xYZ" /&gt;
     76     ...
     77 &lt;/application&gt;
     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
     82 actually a very simple process.  Just create a class with the same name as you
     83 used in the manifest in the previous step (in this example, {@code
     84 TheBackupAgent}),
     85 and extend {@code BackupAgentHelper}.  Then override the {@link
     86 android.app.backup.BackupAgent#onCreate()}.</p>
     87 
     88 <p>Inside the {@link android.app.backup.BackupAgent#onCreate()} method, create a {@link
     89 android.app.backup.BackupHelper}.  These helpers are
     90 specialized classes for backing up certain kinds of data.  The Android framework
     91 currently includes two such helpers:  {@link
     92 android.app.backup.FileBackupHelper} and {@link
     93 android.app.backup.SharedPreferencesBackupHelper}.  After you create the helper
     94 and point it at the data you want to back up, just add it to the
     95 BackupAgentHelper using the {@link android.app.backup.BackupAgentHelper#addHelper(String, BackupHelper) addHelper()}
     96 method, adding a key which is used to
     97 retrieve the data later.  In most cases the entire
     98 implementation 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>
    103 import android.app.backup.BackupAgentHelper;
    104 import android.app.backup.FileBackupHelper;
    105 
    106 
    107 public 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   &#64;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
    123 constructor can take a variable number of filenames.  You could just as easily
    124 have backed up both a high scores file and a game progress file just by adding
    125 an extra parameter, like this:</p>
    126 <pre>
    127 &#64;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
    134 android.app.backup.SharedPreferencesBackupHelper}  the same way you did a {@link
    135 android.app.backup.FileBackupHelper}.  In this case, instead of adding filenames
    136 to the constructor, add the names of the shared preference groups being used by
    137 your application.  Here's an example of how your backup agent helper might look if
    138 high scores are implemented as preferences instead of a flat file:</p>
    139 
    140 <pre>
    141 import android.app.backup.BackupAgentHelper;
    142 import android.app.backup.SharedPreferencesBackupHelper;
    143 
    144 public 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
    164 like, but remember that you only need one of each type.  One {@link
    165 android.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
    167 preferencegroups 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
    173 android.app.backup.BackupManager}, and call it's {@link
    174 android.app.backup.BackupManager#dataChanged()} method.</p>
    175 
    176 <pre>
    177 import android.app.backup.BackupManager;
    178 ...
    179 
    180 public 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
    187 up to the cloud.  At some point in the future, the backup manager then calls
    188 your backup agent's {@link
    189 android.app.backup.BackupAgent#onBackup(ParcelFileDescriptor, BackupDataOutput,
    190 ParcelFileDescriptor) onBackup()} method.  You can make
    191 the call whenever your data has changed, without having to worry about causing
    192 excessive network activity.  If you request a backup twice before a backup
    193 occurs, 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
    198 happens automatically when your application is installed on a device.  However,
    199 if 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