确定。我阅读了文档:here和here,无论如何都无法备份我的偏好。我的代码: AndroidManifest:
<application android:allowBackup="true" android:label="@string/app_name"
android:icon="@mipmap/ic_launcher" android:theme="@style/AppTheme"
android:backupAgent="TheBackupAgent" android:restoreAnyVersion="true">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<meta-data android:name="com.google.android.backup.api_key" android:value="AEdPqrEAAAAIGyGIg_B8K6KrtT06kRX_YljuwtOxzKYHBZ_H0A" />
</application>
我的主要活动:
package com.settings.backup.casper.backupsettings;
public class MainActivity extends Activity{
private EditText txtContainer;
private Button btnSave;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
BackupManager bm = new BackupManager(this);
bm.dataChanged();
bm.requestRestore(new RestoreObserver() {
@Override
public void restoreStarting(int numPackages) {
super.restoreStarting(numPackages);
}
});
txtContainer = (EditText) findViewById(R.id.txtPreferences);
btnSave = (Button) findViewById(R.id.btnSave);
SharedPreferences preferences = getSharedPreferences(TheBackupAgent.PREFS_NAME, MODE_PRIVATE);
txtContainer.setText(preferences.getString("prf", ""));
btnSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences preferences = getSharedPreferences(TheBackupAgent.PREFS_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("prf", txtContainer.getText().toString());
editor.commit();
TheBackupAgent.requestBackup(getBaseContext());
}
});
}
}
我的BackupAgentHelper工具:
package com.settings.backup.casper.backupsettings;
public class TheBackupAgent extends BackupAgentHelper {
// The name of the SharedPreferences file
static final String PREFS_NAME = "myprefs";
// A key to uniquely identify the set of backup data
static final String PREFS_BACKUP_KEY = "myprefs";
@Override
public void onCreate() {
SharedPreferencesBackupHelper helper = new SharedPreferencesBackupHelper(this, PREFS_NAME);
addHelper(PREFS_BACKUP_KEY, helper);
Log.d("Test", "Adding backupagent...");
}
@Override
public void onRestore(BackupDataInput data, int appVersionCode, ParcelFileDescriptor newState) throws IOException {
super.onRestore(data, appVersionCode, newState);
}
@Override
public void onBackup(ParcelFileDescriptor oldState, BackupDataOutput data, ParcelFileDescriptor newState) throws IOException {
super.onBackup(oldState, data, newState);
}
public static void requestBackup(Context context) {
BackupManager bm = new BackupManager(context);
bm.dataChanged();
}
}
我知道android在调用dataChanged()之后不会立即背包数据;这就是我在android.dev上使用adb shell的原因,但是当我重新安装应用程序时它没有恢复。在手机选项中,我启用备份。我试过3个不同的手机这个代码。有谁知道它为什么不起作用?