5

再インストール後にこの値を読み取れるように、SharedPreferences の値をバックアップしたいと思います。

コードが機能せず、何が間違っているのかわかりません。

MyBackupAgent

package com.app.appname;
import android.app.backup.BackupAgentHelper;
import android.app.backup.BackupManager;
import android.app.backup.SharedPreferencesBackupHelper;
import android.content.Context;

public class MyBackupAgent extends BackupAgentHelper{
 static final String PREFS_DISPLAY = "AppName"; 
 private Context context;
 static final String MY_PREFS_BACKUP_KEY = "keyToStore"; 

    public MyBackupAgent(Context context){
        this.context = context;
        SharedPreferencesBackupHelper helper = 
              new SharedPreferencesBackupHelper(context, PREFS_DISPLAY);
        addHelper(MY_PREFS_BACKUP_KEY, helper);
    }

   public void storeData(){
        BackupManager backupManager = new BackupManager(context);
        backupManager.dataChanged();
    } 
}

データの保存方法:

 ...
 SharedPreferences settings = getSharedPreferences("AppName", 0);
 SharedPreferences.Editor editor = settings.edit();
 editor.putBoolean("keyToStore", true);
 editor.commit();
 new MyBackupAgent(this).storeData();
 ...

データの受け取り方法:

 ...
 SharedPreferences settings = getSharedPreferences("AppName", 0);
 boolean value = settings.getBoolean("keyToStore", false);
 ...

また、Android マニフェストに API を追加しました。

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

私が間違っていることと、それがどのように機能するか分かりますか? それは本当に機能しますか?

4

1 に答える 1

6

SharedPreferences のバックアップ エージェント クラスは次のようになります。

public class MyPrefsBackupAgent extends BackupAgentHelper {
    // The name of the SharedPreferences file
    static final String PREFS = "user_preferences";

    // 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
    @Override
    public void onCreate() {
        SharedPreferencesBackupHelper helper = new SharedPreferencesBackupHelper(this, PREFS);
        addHelper(PREFS_BACKUP_KEY, helper);
    }
}

次に、次のような方法でクラウド バックアップを要求する必要があります (非同期で実行されます)。

import android.app.backup.BackupManager;
 ...

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

SharedPreferencesBackupHelperSharedPreferences はクラスによって自動的に管理されるため、手動で復元する必要はありません。

バックアップ API キーの他に、バックアップ エージェント クラスをマニフェストに追加することを忘れないでください。

<application android:label="MyApplication"
             android:backupAgent="MyBackupAgent">

このすべての詳細については、http ://developer.android.com/guide/topics/data/backup.htmlおよびhttp://developer.android.com/training/cloudsync/backupapi.htmlを参照してください。

于 2013-09-03T07:07:02.977 に答える