Android Backup of Shared Preferences to Google Backup Service not working
I've researched and followed how to get my android app to backup the data to google backup so if user loses phone or upgrades to a new phone, they don't lose their data开发者_开发知识库. However, when I test it out (by using the app myself, then uninstalling and reinstalling), no data is restored. Here's what I've done. Perhaps someone can figure out what is wrong.
- Applied for a backup key from google
Placed following code in Manifest File (in place of key I did add the key value and for packageName I used my app package name)
android:backupAgent="packageName.MyPrefsBackup"> <meta-data android:name="com.google.android.backup.api_key" android:value="key" />
Created class
MyPrefsBackup
with following code. The name of the sharedpreference file I want to backup is called UserDB. As far as thePREFS_BACKIP_KEY
, I just called it prefs. From what I understand, this is not the same key as the one that goes in the manifest file.
Code:
package packageName;
import android.app.backup.BackupAgentHelper;
import android.app.backup.SharedPreferencesBackupHelper;
public class MyPrefsBackup extends BackupAgentHelper {
// The name of the SharedPreferences file
static final String PREFS = "UserDB";
// A key to uniquely identify the set of backup data
static final String PREFS_BACKUP_KEY = "prefs";
// Allocate a helper and add it to the backup agent
public void onCreate() {
SharedPreferencesBackupHelper helper = new SharedPreferencesBackupHelper(this, PREFS);
addHelper(PREFS_BACKUP_KEY, helper);
}
}
Added
BackupManager mBackupManager = new BackupManager(this);
in my main class where I call the backup manager in next stepLastly, in my main program I call the
backupHelper
when data is changed by the following line:mBackupManager.dataChanged();
Any help is much appreciated.
try new BackupManager(this).dataChanged()
If you are testing this from AVD - you'll need to enable backups - AVD are disabled for backups by default. adb shell bmgr enable true
Then you can actually debug it to see if the onCreate is called after running adb shell bmgr run
精彩评论