无法备份我的应用数据库

时间:2017-04-11 02:34:29

标签: android android-backup-service

我有以下代码:

MyBackupPlace

public class MyBackupPlace extends BackupAgentHelper {
    static final String FILES_BACKUP_KEY = "myfiles";

    // Allocate a helper and add it to the backup agent
    @Override
    public void onCreate() {
        DbBackupHelper helper = new DbBackupHelper(this, DBHelper.DATABASE_NAME);
        addHelper(FILES_BACKUP_KEY, helper);
    }

    /**
     * We want to ensure that the UI is not trying to rewrite the data file
     * while we're reading it for backup, so we override this method to
     * supply the necessary locking.
     */
    @Override
    public void onBackup(ParcelFileDescriptor oldState, BackupDataOutput data,
                         ParcelFileDescriptor newState) throws IOException {
        System.out.println("onBackup");
        synchronized (MainActivity.sDataLock) {
            super.onBackup(oldState, data, newState);
        }
    }

    /**
     * Adding locking around the file rewrite that happens during restore is
     * similarly straightforward.
     */
    @Override
    public void onRestore(BackupDataInput data, int appVersionCode,
                          ParcelFileDescriptor newState) throws IOException {
        synchronized (MainActivity.sDataLock) {
            System.out.println("onRestore");
            super.onRestore(data, appVersionCode, newState);
        }
    }
}

DBBackupHelper

public class DbBackupHelper extends FileBackupHelper {

    public DbBackupHelper(Context ctx, String dbName) {
        super(ctx, ctx.getDatabasePath(dbName).getAbsolutePath());
    }
}

DBHelper

public class DBHelper extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "testDB.db";
    ....
}

AndroidManifest

<activity
    android:name=".MainActivity"
    android:allowBackup="true"
    android:backupAgent="MyBackupPlace"
    android:restoreAnyVersion="true">
    ...    
</activity

<meta-data
    android:name="com.google.android.backup.api_key"
    android:value="..." />

我从here获得了备用密钥。

然后我试着跑:

  

adb shell bmgr transport   com.google.android.gms / .backup.BackupTransportService

     

adb shell bmgr backupnow my_package_name

它让我回复:

Running backup for 1 requested packages.
Package @pm@ with result: Transport error
Backup finished with result: Transport error

如果我使用其他交通工具:

  

adb shell bmgr transport   机器人/ com.android.internal.backup.LocalTransport

     

adb shell bmgr backupnow my_package_name

它让我回复:

Running backup for 1 requested packages.
Package @pm@ with result: Success
Backup finished with result: Backup is not allowed

我的代码可能有什么问题?

3 个答案:

答案 0 :(得分:1)

我需要在我的设备上启用一些设置:

  

设置&gt;备份我的数据

答案 1 :(得分:0)

如果您使用的是测试设备,则可能未启用“备份”。例如,这是模拟器的“ Android系统设置->备份”的默认设置。

要启用它,您将必须使用Google帐户登录(因为每个用户的备份数据都存储在Google云端硬盘中)。我最终只是使用我的个人电话来进行测试。

enter image description here

答案 2 :(得分:0)

我解决了禁用高级保护(加密技术)的问题,如所附图片所示:

enter image description here