- Rahul Singh
When you purchase a new device, we hate to lose the High scores of our favorite games on the old device.
Guess what!! Google Backup API is there to help!!
Register for the Android Backup Service
Add the snippet below as a child element of the Application tag.
Assuming
your backup agent is going to be called TheBackupAgent
, here's an example of
what the manifest looks like with this tag included:
<application android:label="MyApp"
android:backupAgent="TheBackupAgent">
...
<meta-data android:name="com.google.android.backup.api_key"
android:value="ABcDe1FGHij2KlmN3oPQRs4TUvW5xYZ" />
...
</application>
import android.app.backup.BackupAgentHelper;
import android.app.backup.FileBackupHelper;
public class TheBackupAgent extends BackupAgentHelper {
static final String HIGH_SCORES_FILENAME = "scores";
static final String FILES_BACKUP_KEY = "myfiles";
@Override
void onCreate() {
FileBackupHelper helper = new FileBackupHelper(this, HIGH_SCORES_FILENAME);
addHelper(FILES_BACKUP_KEY, helper);
}
}
FileBackupHelper's constructor can take a variable number of filenames. You could just as easily have backed up both a high scores file and a game progress file just by adding an extra parameter, like this :
@Override
void onCreate() {
FileBackupHelper helper = new FileBackupHelper(this, HIGH_SCORES_FILENAME, PROGRESS_FILENAME);
addHelper(FILES_BACKUP_KEY, helper);
}
So, that was about backing up files. Lets backup the SharedPreferences.
import android.app.backup.BackupAgentHelper;
import android.app.backup.SharedPreferencesBackupHelper;
public class TheBackupAgent extends BackupAgentHelper {
static final String PREFS_DISPLAY = "displayprefs";
static final String PREFS_SCORES = "highscores";
static final String MY_PREFS_BACKUP_KEY = "myprefs";
void onCreate() {
SharedPreferencesBackupHelper helper =
new SharedPreferencesBackupHelper(this, PREFS_DISPLAY, PREFS_SCORES);
addHelper(MY_PREFS_BACKUP_KEY, helper);
}
}
We are done with the backup, lets restore the data.
In order to request a backup, just create an instance of the BackupManager, and call it's dataChanged() method.
import android.app.backup.BackupManager;
...
public void requestBackup() {
BackupManager bm = new BackupManager(this);
bm.dataChanged();
}
Ensure data backup is enabled.
adb shell bmgr enable true
Performing backup
adb shell bmgr backup your.package.name
adb shell bmgr run
Uninstall and reinstall your application
adb uninstall your.package.name
Thanks :-)