我正在上课,它需要备份数据并恢复相同的数据。我参考了 api demos 中给出的示例。但它根本不起作用。
有人可以帮我解决这个问题吗?
安卓清单.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.kpbird.backupdemo"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name" android:backupAgent="MyBackupAgent" android:restoreAnyVersion="true" android:allowBackup="true" android:enabled="true">
<activity android:name=".BackupServiceDemo"
android:label="@string/app_name">
<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="AEdPqrEAAAAIAjALiYV5vv5cRGD5L649XByQMnFFYfApskNIfg" />
</application>
</manifest>
我的活动.class
public class BackupRestoreActivity extends Activity implements OnClickListener {
BackupManager mBackupManager;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mBackupManager = new BackupManager(this);
mBackupManager.dataChanged();
}
}
MyBackupAgent.class
public class MyBackupAgent extends BackupAgentHelper {
static final String MY_PREFS_BACKUP_KEY = "AEdPqrEAAAAIAjALiYV5vv5cRGD5L649XByQMnFFYfApskNIfg";
static final String APP_DATA_KEY = "mydata";
String TAG = this.getClass().getSimpleName();
@Override
public void onCreate() {
Log.i("MyBackupAgent >>>>>> ","into Oncreate() of my Backup Agent >>>>");
}
@Override
public void onBackup(ParcelFileDescriptor oldState, BackupDataOutput data,ParcelFileDescriptor newState) throws IOException {
Log.i(TAG, "I m onBackup");
ByteArrayOutputStream bufStream = new ByteArrayOutputStream();
DataOutputStream outWriter = new DataOutputStream(bufStream);
outWriter.writeUTF("Hello Backup Service!");
byte[] buffer = bufStream.toByteArray();
int len = buffer.length;
data.writeEntityHeader(APP_DATA_KEY, len);
data.writeEntityData(buffer, len);
FileOutputStream outstream = new FileOutputStream(newState.getFileDescriptor());
DataOutputStream out = new DataOutputStream(outstream);
out.writeUTF("Hello Backup Service!");
Log.i(TAG, "Backup Message Completed");
}
@Override
public void onRestore(BackupDataInput data, int appVersionCode,ParcelFileDescriptor newState) throws IOException {
Log.i(TAG, "I m onRestore");
while (data.readNextHeader()) {
String key = data.getKey();
int dataSize = data.getDataSize();
if(key.equals(APP_DATA_KEY)){
byte[] dataBuf = new byte[dataSize];
data.readEntityData(dataBuf, 0, dataSize);
ByteArrayInputStream baStream = new ByteArrayInputStream(dataBuf);
DataInputStream in = new DataInputStream(baStream);
String read = in.readUTF();
Log.i(TAG, "Restored Message :" + read);
}
else{
data.skipEntityData();
}
}
}
}