In this article, I would like to touch on such an important topic for Android developer as cloud backup of data using the example of using Android Backup Service. This service allows you to store application data for free on a remote cloud storage. According to the
documentation , it allows you to restore data when you reinstall the application, update the device and at the factory reset settings. All that is required of the user is that he had ticks in “Data backup” and “Auto-restore” in Settings / Restore and reset.
Implementation
Before implementation, you need to register your application directly in the
Android Backup Service . The key obtained during registration is used in the manifest, see below.
The easiest way to interact with BackupManager is to inherit from the BackupAgentHelper class.
In this class we use two helpers:
- SharedPreferencesBackupHelper for SharedPreferences backup
- FileBackupHelper for backing up files from internal storage.
public class TheBackupAgent extends BackupAgentHelper { @Override public void onCreate() {
You'd be surprised, but basically that's all. Finally, simply specify the path to the agent backup class in the manifest and additional attributes with the talking name. Also in the meta-data is written the key obtained during the registration of the application.
')
<application android:name=". MyApplication " android:allowBackup="true" android:restoreAnyVersion="true" android:backupAgent=".util.TheBackupAgent" <meta-data android:name="com.google.android.backup.api_key" android:value="AEdPqrEAAAAIDaYEVgU6DJnyJdBmU7KLH3kszDXLv_4DIsEIyQ" /> </application>
Since there is no beautiful solution for determining the application stop in Android, I suggest, as one of the lazy ways, to request a backup at the start of the application.
public class MyApplication extends Application { @Override public void onCreate() { TheBackupAgent.requestBackup(this); } }
Testing.
Do not forget to carefully watch the logs. If you specify incorrect file paths or prefs, you will be informed.
The algorithm is quite simple:
- Enter data / settings in the application.
- We request a backup for the adb shell application bmgr backup your.package.name.
- We start backup manager adb shell bmgr run.
- Delete, set again, PROFIT.
Conclusion
According to personal feelings and googling, this service does not work stably on all devices, however, the implementation of this functionality takes almost no effort and is therefore recommended for use in applications with a database or SharedPreferences by default.