我一直试图让我的android应用程序中的sharedpreferences文件的备份工作,但到目前为止还没有。我使用的是开发者指南中的简单google代码。下面是MyPrefsBackup类的代码。

public class MyPrefsBackup extends BackupAgentHelper {

    // The name of the SharedPreferences file

    static final String PREFS = "UserDB";

    // 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

  public  void onCreate() {

        SharedPreferencesBackupHelper helper = new SharedPreferencesBackupHelper(this, PREFS);
        addHelper(PREFS_BACKUP_KEY, helper);


    }

我想我终于意识到PREFS_BACKUP_KEY实际上必须是我存储数据的特定键。我只是在用“prefs”,所以我想这就是为什么没有备份数据的原因。但是,我在SharedPreferences文件中存储了相当多的数据,所以我如何在不指定每个单独键的情况下继续保存整个SharedPreferences文件。(有些密钥是由应用程序生成的,因此在用户输入数据之前,我甚至不知道它们是否正在使用)。
我想知道有没有办法告诉BackupHelper类备份整个SharedPreferences文件?

最佳答案

示例共享引用

SharedPreferences preferences=getSharedPreferences("Test", getApplicationContext().MODE_MULTI_PROCESS)

备份文件夹的日期
Calendar c = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("dd_MMMM_yyyy HH_mm_ss");
            String strDate = sdf.format(c.getTime());

导出共享引用
exportSH("Test.xml", strDate);

将文件夹中的sharedpreferences.xml文件导出到下载目录
private void exportSH(String sh_name, String strDate){




        File sd = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) +
                File.separator + "Backup Folder "+strDate+
                File.separator );

          boolean success = true;
           if (!sd.exists()) {
               success = sd.mkdir();
           }
           if (success) {

        File data = Environment.getDataDirectory();
       FileChannel source=null;
       FileChannel destination=null;
       String currentDBPath = "/data/"+ context.getPackageName() +"/shared_prefs/"+ sh_name;
       String backupDBPath = sh_name;
       File currentDB = new File(data, currentDBPath);
       File backupDB = new File(sd, backupDBPath);
       try {
            source = new FileInputStream(currentDB).getChannel();
            destination = new FileOutputStream(backupDB).getChannel();
            destination.transferFrom(source, 0, source.size());
            source.close();
            destination.close();
            Toast.makeText(this, "Done", Toast.LENGTH_SHORT).show();
        } catch(IOException e) {
            e.printStackTrace();
Toast.makeText(this, "Failed", Toast.LENGTH_SHORT).show();
        }
           }}

您可以通过一些小的更改导入文件。有人说它不会那么容易工作,但它确实会。只需确保在导入之前创建一个空的sharedpreferences文件,否则它将不起作用。
例如,你可以这样做
    SharedPreferences dummy = getSharedPreferences("dummy", getApplicationContext().MODE_MULTI_PROCESS);
                Editor editor = dummy.edit();
editor.putBoolean("asdf", true);

    editor.commit();

如果将其导入到使用sharedpreferences的同一布局中,则可以使用此刷新
                        finish();
                        startActivity(getIntent());

10-08 17:34