Users invest a lot of time customizing settings in their apps. Restoring settings data for users when they upgrade to a new device is an important aspect of ensuring a great user experience. It's therefore important to minimize the number of steps that a user has to go through to pick up where they left off on their previous device. You can use Auto Backup to restore settings data even if a user doesn't log in to your app.

To restore an existing user's settings data on a new device, make sure you backup the following user settings:

Auto Backup is available on devices running Android 6.0 (API 23) and higher.

What you'll learn

What you'll need

How will you use this tutorial?

Read it through only Read it and complete the exercises

How would rate your experience with building Android apps?

Novice Intermediate Proficient

Download ZIP

...or clone the GitHub repository from the command line by using the following command:

$ git clone https://github.com/googlecodelabs/android-backup-codelab

Frequently asked questions

The first step is to turn on Auto Backup within your app. Turning on Auto Backup is controlled via an attribute named allowBackup on the <application> element.

  1. If you downloaded the android-backup-codelab-master zip file, unzip the file.
  2. Open the android-backup-codelab folder to see the backup-codelab-start folder. android_studio_folder.png
  3. Open the sample using File -> New -> Import Project and select the android_studio_folder.png backup-codelab-start.
  4. Open manifests/AndroidManifest.xml from the Project pane
  5. Navigate to the <application> element.
  6. Ensure that allowBackup="true". Screen Shot 2017-08-08 at 11.16.35 PM.png
  7. Click the execute.pngRun button, and choose an emulator, which must be capable of running Android Oreo (API level 26). The login screen should appear.

Frequently asked questions

Log in to sample app

Let's take a detour from implementing Auto Backup and understand the sample app, which includes a main login screen that accepts a username and a password. You can imagine a real world app accepting other forms of login such as Twitter, facebook or Google. You will implement login hinting in this code lab to remind users what email address they last used to log in.

After you launch the example app, log in with username ‘foo@example.com` and password `hello`. The example app will save your login in shared prefs. In a real world app, the auth key would be derived by sending the username and password to the server.

Examine Shared Prefs

To simplify this codelab, the example app shows the state of shared preferences on the login screen and when logged in. You can see all three shared pref values in the debug text visible in-app.

In this step, we look at how to manually create and restore a backup of an app for testing purposes. We also examine the contents of the backup. After a user installs your app, the system backs up the app's data once a day to the user's Google Drive storage.

Complete the following steps to create backup:

Check to see if backups are enabled on your current device or emulator

$ adb shell bmgr enabled
Backup Manager currently enabled

$ adb shell bmgr list transports
    android/com.android.internal.backup.LocalTransport
  * com.google.android.gms/.backup.BackupTransportService
  1. Physical devices without Google Play and emulators without Google APIs might not include the Google Backup Transport.
  2. If you do not see the output above, create a new emulator with Google Play for any API, level 24 or higher, before continuing with this codelab. If you already have Google Play but backups are not enabled, ensure that you're logged into a Google Account with backups enabled

Force a backup of your application

$ adb shell bmgr backupnow com.googlecodelabs.example.backupexample
Running incremental backup for 1 requested packages.

Running this command will force Auto Backup to back up your application immediately.

Uninstall your application

Ensure that the app is uninstalled. You can uninstall the app inside the emulator or via adb. To uninstall via adb, issue the following command:

$ adb uninstall com.googlecodelabs.example.backupexample

By uninstalling, you are able to confirm that restoring the backup on a new install restores your data.

Re-install your application without restore

  1. Open Android Studio and click Run to install the app to the emulator.

Restore your app's data

  1. To restore data from a backup, first fetch your backup token from Auto Backup.
# see all backup information (optional)
$ adb shell dumpsys backup

# or use grep to find the current token only
$ adb shell dumpsys backup | grep "com.googlecodelabs.example.backupexample" -A 4 | grep Current

Current:   <hexadecimal token>
  1. Tell backup manager to restore your app to the hexidecimal token found in the previous step
$ adb shell bmgr restore <token> com.googlecodelabs.example.backupexample
Scheduling restore: Android SDK built for x86
restoreStarting: 0 packages
restoreFinished: 0
done

Performing a restore operation kills your app.

What we covered in this section

In the previous section, we saw how to manually back up and restore your app data. In this section we'll first examine the data that was restored and then customize it to only include specific files and values.

Checking the data restored from a backup

After the data is restored, open the app on the emulator and notice that the Login screen is not shown at all. This is because all the data from the app was backed up as part of the adb backup operation.

In a real application, you should not backup sensitive information like an access token. To configure our application to exclude some data we will create an exclude.

In the case of the sample app, we want the user to log in to the app but we can aid the user by hinting about the login provider or email address that was last used to log in to the app. This suggests that we should only backup com.googlecodelabs.example.backupexample.PREF_APP_INFO.xml which contains our hint, and not PREF_LOGIN_DETAILS.xml which contains our username and access token.

Auto Backup lets you configure the specific files that should either be included or excluded from a backup. By default, all files in your data folder are backed up. To configure it you use the include and exclude rules specified in a descriptor declared in the android:fullBackupContent attribute of the <application> element.

Complete the following steps to create the backup descriptor:

  1. Open manifests/AndroidManifest.xml
  2. Navigate to the <application> element and notice the lint warning.

Screen Shot 2017-08-26 at 11.47.00 PM.png

  1. Use Opt-Enter (Alt-Enter on windows) to select one of the quick-fixes. Screen Shot 2017-08-26 at 11.47.17 PM.png
  2. Click Set fullBackupContent attribute and generate descriptor. This option in studio examines the entire app and populates a list of shared preferences and database files within the descriptor.
  3. Examine the opened descriptor res/xml/backup_descriptor.xml and modify it to suit your needs.

The generated file looks as follows:

<?xml version="1.0" encoding="utf-8"?>
<full-backup-content>
   <!-- TODO Remove the following "exclude" elements to make them a part of the auto backup -->
   <!-- Exclude the shared preferences file that contains the GCM registrationId -->
   <exclude
       domain="sharedpref"
       path="com.googlecodelabs.example.backupexample.PREF_LOGIN_DETAILS.xml" />
   <exclude
       domain="sharedpref"
       path="com.googlecodelabs.example.backupexample.PREF_APP_INFO.xml" />
</full-backup-content>

Since we only need to exclude the PREF_LOGIN_DETAILS.xml, we keep that exclude and remove the other exclude for PREF_APP_INFO.xml. After editing our file should look as follows:

<?xml version="1.0" encoding="utf-8"?>
<full-backup-content>
   <exclude
       domain="sharedpref"
       path="com.googlecodelabs.example.backupexample.PREF_LOGIN_DETAILS.xml" />
</full-backup-content>

You can specify multiple exclude elements for files:

The backup descriptor alternatively also lets you include specific files that should be part of the backup. If you specify an <include> element, the system no longer includes any files by default and backs up only the files specified. To include multiple files, use multiple <include> elements.

Finally we follow the steps outlined in "Manually creating and restoring from a backup" to see the contents of the backup.

  1. From your desktop, run:
$ adb shell bmgr backupnow com.googlecodelabs.example.backupexample
Running incremental backup for 1 requested packages.
  1. Uninstall the app from the emulator by issuing the following command (or alternatively clear the data of the app):
$ adb uninstall com.googlecodelabs.example.backupexample
  1. Click Run in Android Studio to install the app on the emulator.
  2. Run the following commands to restore the backup:
# see all backup information (optional)
$ adb shell dumpsys backup

# or use grep to find the current token only
$ adb shell dumpsys backup | grep "com.googlecodelabs.example.backupexample" -A 4 | grep Current

Current:   <hexadecimal token>

and

$ adb shell bmgr restore <token> com.googlecodelabs.example.backupexample
Scheduling restore: Android SDK built for x86
restoreStarting: 0 packages
restoreFinished: 0
done

Notice that only the preferences namely PREF_APP_INFO.xml was restored from the backup as intended.

What we learnt in this section

In this section, we look at how to help users of your app after they've migrated to a new device. Instead of showing just a Login screen to the user, we can remind them of the provider they used for logging into the app the last time. For instance, your app could be using one of multiple providers such as Login with Twitter, Facebook, Google or just an email address.

Complete the following steps to modify the LoginActivity.java file to set the hint on the email AutoCompleteTextView:

  1. Open LoginActivity.java in the Android Studio project.
  2. Navigate to the section for implementing Login Hinting in onCreate()
if (!PrefUtils.needsLogin(this)) {
   startActivity(new Intent(this, SettingsActivity.class));
   finish();
}

//******************* Implement Login Hinting *****************

//******************* End implement Login Hinting *************
  1. In the marked section add code to get the masked login hint from PrefUtils
//******************* Implement Login Hinting *****************
String accountHint = PrefUtils.getLoginHint(this);
if (accountHint != null) {
   mEmailView.setHint(accountHint);
}
//******************* End implement Login Hinting *************
  1. Let's finally see this in action. Since we already restored the backup that contains the PREF_APP_DETAILS shared preference, we simply have to install the updated version of our code.

If your app were using other login providers, you would similarly store the provider name in a backed up shared preference and show the provider login as the first option to make it easier for users to login.

Congratulations, you finished! You're now ready to configure Auto Backup for your apps.

What we've covered

Next Steps

You can use the following APIs to improve the restore user experience for your apps:

Learn More

To learn more about Auto Backup, see the following resources:

All rights reserved. Java is a registered trademark of Oracle and/or its affiliates.