2016-04-03 94 views
1

的Android保存共享偏好在我backupagent類我有這樣的:使用備份代理

import android.app.backup.BackupAgentHelper; 
import android.app.backup.SharedPreferencesBackupHelper; 

public class TheBackupAgent extends BackupAgentHelper { 
    // The names of the SharedPreferences groups that the application maintains. These 
    // are the same strings that are passed to getSharedPreferences(String, int). 
    static final String RECIPE_NAMES = "MyRecipeNames"; 
    static final String TEST = "testSave"; 

    // An arbitrary string used within the BackupAgentHelper implementation to 
    // identify the SharedPreferencesBackupHelper's data. 
    static final String MY_PREFS_BACKUP_KEY = "myprefs"; 

    // Simply allocate a helper and install it 
    public void onCreate() { 
     SharedPreferencesBackupHelper helper = 
       new SharedPreferencesBackupHelper(this, TEST); 
     addHelper(MY_PREFS_BACKUP_KEY, helper); 
    } 
} 

然後我有一些代碼來存儲串入testSave共享偏好並要求偏好的備份:

public void requestBackup() { 
    BackupManager bm = new BackupManager(this); 
    bm.dataChanged(); 
} 

public void saveRecipe (View v) { 

    SharedPreferences prefs = getApplicationContext().getSharedPreferences("testSave", 0); 
    SharedPreferences.Editor editor = prefs.edit(); 
    editor.putString("testString", "This is my saved data."); 
    editor.apply(); 

    requestBackup(); 
} 

然後我嘗試卸載並重新安裝應用程序,保存的數據消失了。我已將所需的代碼添加到清單中,但它不起作用。我的應用程序需要在Play商店嗎?我真的不知道爲什麼它不起作用。

回答

0

您可以使用作爲Android SDK一部分的bmgr工具(它是adb中的命令)測試備份代理。 See here how it can be used.

+0

我已經使用adb來手動備份和恢復,但是當我重新安裝時,sharedPrefs仍然爲空。 – tgreen

+1

'editor.putString(「testString」,「這是我保存的數據。」);'應該是'editor.putString(「myprefs」,「這是我保存的數據。」);'因爲這是你給的關鍵名在助手。 –