2016년 4월 4일 월요일

앱을 위한 자동 백업 설정하기

Configuring Auto Backup for Apps

사용자들은 그들이 좋아하는 방식으로 앱을 설정하는데 시간과 노력을 투자한다. 새로운 장치로 변경하는 것은 모든 중요한 설정들을 무효화할 수 있다. target SDK version 이 안드로이드 6.0(API level 23) 이상인 앱으 경우 안드로이드 6.0이상을 실행하는 장치들은 자동적으로 앱 데이터를 클라우드로 백업한다. 시스템은 기본으로 거의 모든 앱 데이터에 대해 자동 백업을 수행한다. 그리고 이것은 당신이 추가적인 앱 코드를 작성할 필요가 없다.
Users frequently invest time and effort to configure apps just the way they like them. Switching to a new device can cancel out all that careful configuration. For apps whose target SDK version is Android 6.0 (API level 23) and higher, devices running Android 6.0 and higher automatically back up app data to the cloud. The system performs this automatic backup for nearly all app data by default, and does so without your having to write any additional app code.
Note: 사용자 프라이버시를 보호하기 위해 장치 사용자는 자동 백업이 동작하는 구글 서비스에 동의해야 한다. 구글 서비스 동의 다이얼로그는 사용자가 셋업 위자드를 거쳐가거나 장치의 첫 구글 계정을 설정할 때 나타난다.
To protect user privacy, the device user must have opted in to Google services for Auto Backup to work. The Google services opt-in dialog appears when the user goes through the Setup Wizard or configures the first Google account on the device.
사용자가 새로운  새로운 장치에 당신의 앱을 설치하거나 하나의 장치에 당신 앱을 재설치할 때(예를 들어 공장 초기화 이후) 시스템은 자동적으로 클라우드로 부터 앱 데이터를 복구한다. 이 수업은 어떻게 앱 특성을 위한 자동 백업을 설정하고 기본 동작은 무엇이며 어떻게 백업을 원치않는 데이터를 시스템이 제외하는지에 대한 정보를 제공한다.
When a user installs your app on a new device, or reinstalls your app on one (for example, after a factory reset), the system automatically restores the app data from the cloud. This lesson provides information about how to configure the Auto Backup for Apps feature, explaining its default behavior and how to exclude data that you don't want the system to back up.
자동 백업 특성은 당신의 앱이 사용자 장치에 생성한 데이터를 구글 드라이브 계정에 올리고 암호화하여 보존한다. 데이터 저장을 위해 당신이나 사용자는 어떤 변경도 필요없으며 저장된 데이터는 사용자의 개인 구글 드라이브 용량에 포함되지 않는다. 각 앱들은 25MB까지 저장할 수 있고 백업된 데이터가 25MB에 도달하면 더 이상 데이터를 클라우드로 보내지 않는다. 만약 시스템이 데이터 복구를 수행하는 경우, 앱이 마지막으로 클라우드에 보낸 데이터 스탭샷을 사용한다.
The automatic backup feature preserves the data your app creates on a user device by uploading it to the user’s Google Drive account and encrypting it. There is no charge to you or the user for data storage, and the saved data does not count towards the user's personal Google Drive quota. Each app can store up to 25MB. Once its backed-up data reaches 25MB, the app no longer sends data to the cloud. If the system performs a data restore, it uses the last data snapshot that the app had sent to the cloud.
자동 백업은 다음의 상태가 충족될 때 발생한다.
Automatic backups occur when the following conditions are met:
  • The device is idle.
  • The device is charging.
  • The device is connected to a Wi-Fi network.
  • At least 24 hours have elapsed since the last backup.

Configure Data Backup


장치가 안드로이드 6.0 이상에서 실행될 때 장치의 기본 동작은 앱이 생성한 거의 모든 데이터를 백업하는 것이다. 예외는 자동적으로 제외된 데이터 파일들이다. 이 절은 시스템이 백업할 데이터를 제한하고 설정하기 위해 어떻게 app manifest의 셋팅을 사용하는지 설명한다.
On devices running Android 6.0 (API level 23) or higher, the default system behavior is to back up almost all data that an app creates. The exception is automatically excluded data files. This section explains how you can use settings in your app manifest to further limit and configure what data the system backs up.

Including or excluding data

당신 앱이 필요로하는 데이터와 그것을 저장하는 방법에 따라 당신은 특정 파일이나 디렉토리를 포함하거나 배제하는 등의 구체적인 규칙을 셋팅할 필요가 있을 것이다. 앱을 위한 자동 백업은 당신이 이들 백업 규칙을 app manifest 를 통해 설정 가능케한다. 거기에 당신은 backup scheme configuration XML 파일을 지정한다. 예를 들어:
Depending on what data your app needs and how you save it, you may need to set specific rules for including or excluding certain files or directories. Auto Backup for Apps lets you set these backup rules through the app manifest, in which you specify a backup scheme configuration XML file. For example:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        package="com.my.appexample">
    <uses-sdk android:minSdkVersion="23"/>
    <uses-sdk android:targetSdkVersion="23"/>
    <application ...        android:fullBackupContent="@xml/mybackupscheme">
    </app>
    ...</manifest>
이 예제에서 android:fullBackupContent 속성은 mybackupscheme.xml이라는 XML 파일을 지정했다. 파일은 res/xml 디렉토리에 위치하고 있다. 이 설정파일은 어떤 파일들이 백업될지 제어하는 규칙을 포함한다. 다음 예제 코드는 특정 파일, device_info.db를 제외하는 설정 파일을 보여준다.
In this example, the android:fullBackupContent attribute specifies an XML file called mybackupscheme.xml, which resides in the res/xml/ directory of your app development project. This configuration file contains rules controlling which files are backed up. The following example code shows a configuration file that excludes a specific file, device_info.db:
<?xml version="1.0" encoding="utf-8"?>
<full-backup-content>
    <exclude domain="database" path="device_info.db"/>
</full-backup-content>

Automatically excluded data files

대부분의 앱들은 모든 데이터를 백업할 필요가 없으며 사실상 그렇게 해서는 안된다. 예를 들어 시스템은 임시 파일과 캐시를 백업해서는 안된다. 이러한 이유로 자동 백업 서비스는 기본으로 특정 데이터 파일을 제외한다.
Most apps do not need to, and in fact should not, back up all data. For example, the system should not back up temporary files and caches. For this reason, the automatic backup service excludes certain data files by default:
  • getCacheDir() 와 getCodeCacheDir() 메소드가 참조하는 디렉토리에 들어있는 파일들.
    Files in the directories to which the getCacheDir() and getCodeCacheDir() methods refer.
  • 외부 저장소에 위치하는 파일들, 그것들이 getExternalFileDir() 메소드가 참조하는 디렉토리에 위치하지 않는 한
    Files located on external storage, unless they reside in the directory to which the getExternalFilesDir()method refers.
  • getNoBackupFileDir() 메소드가 참조하는 디렉토리에 위치하고 있는 파일들
    Files located in the directory to which the getNoBackupFilesDir() method refers.

Backup Configuration Syntax

백업 서비스 설정은 당신이 어떤 파일들을 백업으로 부터 포함하고 제외할 것인지 지정할 수 있도록 한다. 데이터 백업 설정 XML 파일의 문법은 다음과 같다:
The backup service configuration allows you to specify what files to include or exclude from backup. The syntax for the data backup configuration XML file is as follows:
<full-backup-content>
    <include domain=["file" | "database" | "sharedpref" | "external" | "root"]
    path="string" />
    <exclude domain=["file" | "database" | "sharedpref" | "external" | "root"]
    path="string" />
</full-backup-content>
다음의 요소들과 속성들은 백업으로부터 포함될 파일들과 제외될 파일들을 명세하고 있다.
The following elements and attributes allow you to specify the files to include in, and exclude from, backup:
  • <include>: 기본으로 시스템이 당신 앱의 모든 데이터를 백업하는 것 대신에 백업할 리소스들의 집합을 명세한다.  만약 <include> 요소를 명세하면 시스템은 오직 이 요소에 명세된 리소스들만을 백업한다. 당신은 복수의 <include> 요소들을 사용하여 백업할 여러 집합의 리소스를 명세할 수 있다.
    Specifies a set of resources to back up, instead of having the system back up all data in your app by default. If you specify an <include> element, the system backs up only the resources specified with this element. You can specify multiple sets of resources to back up by using multiple <include> elements
  • <exclude>:  전체 백업시에 시스템이 제외시킬 데이터를 지정한다. 만약 당신이 <include>와 <exclude> 요소 두개에 동일한 집합의 타겟을 설정했다면 <exclude>가 우선권을 가질 것이다.
    Specifies any data you want the system to exclude when it does a full backup. If you target the same set of resources with both the <include> and <exclude> elements, <exclude> takes precedence.
  • domain:백업에서 포함하거나 제외하고자 하는 리소스의 타입을 지정한다. 이 속성들의 유효한 속성들은 다음을 과 같다:
    Specifies the type of resource you want to include in, or exclude from, backup. Valid values for this attribute include:
    • root: 앱의 루트 디렉토리에 있는 리소스를 명세한다.
      Specifies that the resource is in the app’s root directory.
    • file: getFilesDir() 메소드가 리턴하는 디렉토리에 있는 리소스
      Specifies a resource in the directory returned by the getFilesDir() method.
    • database: getDatabasePath() 메소드가 리턴하거나 앱이 SQLiteOpenHalper 클래스를 통해 상호작용하는 데이터베이스를 지정한다.
      Specifies a database that the getDatabasePath() method returns, or that the app interacts with via the SQLiteOpenHelper class.
    • sharedpref: getSharedPreferences() 메소드가 리턴하는 SharedPreferences 객체를 지정한다.
      Specifies a SharedPreferences object that the getSharedPreferences() method returns.
    • external: 외부 저장소에 있는 리소스를 지정한다. 그리고 getExternalFilesDir() 메소드가 리턴하는 디렉토리에 있는 파일에 대응한다.
      Specifies that the resource is in external storage, and corresponds to a file in the directory that the getExternalFilesDir() method returns.
  • path: 백업에 포함하거나 제외시키길 원하는 리소스의 파일 패스를 지정한다.
    Specifies the file path to a resource that you want to include in, or exclude from, backup.

Disabling data backups

manifest의 app요소에 있는 android:allowBackup 속성을 false로 셋팅하여 모든 앱 데이터가 자동 백업되지 않도록 선택할 수 있다. 이 셋팅은 다음 예제가 나타내고 있다.
You can choose to prevent automatic backups of any of your app data by setting the android:allowBackupattribute to false in the app element of your manifest. This setting is illustrated in the following example:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        package="com.my.appexample">
    <uses-sdk android:minSdkVersion="23"/>
    <uses-sdk android:targetSdkVersion="23"/>
    <application ...        android:allowBackup="false">
    </application>
    ...</manifest>

Support Lower Versions of Android


6.0 버전이하의 안드로이드 버전을 지원할 필요가 있는 두가지 시나리오가 있다. 당신은 당신의 존재하는 앱이 안드로이드 6.0의 자동 백업 기능의 이점을 취하도록 업데이트 할 것이다. 이전 버전의 안드로이드를 계속 지원해 가면서. 또는 새로운 앱을 릴리즈할 것이다. 그러나 안드로이드 6.0 이전 버전에서도 돌아가고 백업 기능을 갖길 원한다.
There are two scenarios in which you may also need to support versions of Android lower than 6.0 (API level 23): You may be updating your existing app to take advantage of the new auto backup functionality in Android 6.0, while wanting to continue supporting earlier versions of Android. Or you may be releasing a new app, but want to make sure devices running on versions of Android predating 6.0 also have backup functionality.

Updating an existing app to support auto backup

Earlier versions of Android supported a key/value-pair-based backup mechanism, in which the app defines a subclass of BackupAgent and sets android:backupAgent in its app manifest. If your app used this legacy approach, you can transition to full-data backups by adding the android:fullBackupOnly="true" attribute to the <application/> element in the manifest. When running on a device with Android 5.1 (API level 22) or lower, your app ignores this value in the manifest, and continues performing backups in the previous manner.
Even if you’re not using key/value backups, you can still use the approach described above to do any custom processing in onCreate() or onFullBackup(). You can also use that approach to receive a notification when a restore operation happens in onRestoreFinished(). If you want to retain the system's default implementation of XML include/exclude rules handling, call super.onFullBackup().

Giving your new app support for lower versions of Android

If you are creating a new app that targets Android 6.0, but you also want to enable cloud backup for devices running on Android 5.1 (API level 22) and lower, you must also implement the Backup API.

Test Backup Configuration


Once you have created a backup configuration, you should test it to make sure your app saves data and can restore it properly.

Enabling Backup Logging

To help determine how the backup feature is parsing your XML file, enable logging before performing a test backup:
$ adb shell setprop log.tag.BackupXmlParserLogging VERBOSE

Testing Backup

To manually run a backup, first initialize the Backup Manager by executing the following command:
$ adb shell bmgr run
Next, manually back up your application using the following command. Use the <PACKAGE> parameter to specify the package name for your app:
$ adb shell bmgr fullbackup <PACKAGE>

Testing restore

To manually initiate a restore after the system has backed up your app data, execute the following command, using the <PACKAGE> parameter to specify the package name for your app:
$ adb shell bmgr restore <PACKAGE>
Warning: This action stops your app and wipes its data before performing the restore operation.
You can test automatic restore for your app by uninstalling and reinstalling your app. The app data is automatically restored from the cloud once the app installation is complete.

Troubleshooting backups

If backup fails, you can clear the backup data and associated metadata either by turning backup off and on inSettings > Backup, factory-resetting the device, or executing this command:
$ adb shell bmgr wipe <TRANSPORT> <PACKAGE>
You must prepend com.google.android.gms to the <TRANSPORT> value. To get the list of transports, execute the following command:
$ adb shell bmgr list transports

Handle Google Cloud Messaging


For apps that use Google Cloud Messaging (GCM) for push notifications, backing up the registration token that Google Cloud Messaging registration returned can cause unexpected behavior in notifications for the restored app. This is because when a user installs your app on a new device, the app must query the GCM API for a new registration token. If the old registration is present, because the system had backed it up and restored it, the app doesn't seek the new token. To prevent this issue from arising, exclude the registration token from the set of backed-up files.