且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Android的备份和恢复的数据库和SD卡

更新时间:2022-11-03 09:02:46

我总是用1)。下面是一类矿井,做一个DB到SD卡的备份。我使用从Apache公地IO这里文件实用,你需要改变,如果你不使用的罐子。此外,还有的需要的一种方法,你SQLiteOpenHelper类(这里MySQLiteOpenHelper.getDatabaseName()),返回你的数据库文件的名称。

I always use 1.). Here's a class of mine that does backup of a DB to SD-card. I'm using FileUtils from the Apache commons-io here, you need to change that if you don't use that jar. In addition there's need for a method in your SQLiteOpenHelper class (here MySQLiteOpenHelper.getDatabaseName()) that returns the name of your database file.

您将调用来自内部的AsyncTask的,在你的活动之一......

You will call that from within an AsyncTask in one of your activities...

public class MyDatabaseTools {
  private String appName = "";
  private String packageName = "";

  public boolean backup() {
    boolean rc = false;

    boolean writeable = isSDCardWriteable();
    if (writeable) {
      File file = new File(Environment.getDataDirectory() + "/data/" + packageName + "/databases/" + MySQLiteOpenHelper.getDatabaseName());

      File fileBackupDir = new File(Environment.getExternalStorageDirectory(), appName + "/backup");
      if (!fileBackupDir.exists()) {
        fileBackupDir.mkdirs();
      }

      if (file.exists()) {
        File fileBackup = new File(fileBackupDir, MySQLiteOpenHelper.getDatabaseName());
        try {
          fileBackup.createNewFile();
          FileUtils.copyFile(file, fileBackup);
          rc = true;
        } catch (IOException ioException) {
          //
        } catch (Exception exception) {
          //
        }
      }
    }

    return rc;
  }

  private boolean isSDCardWriteable() {
    boolean rc = false;

    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
      rc = true;
    }

    return rc;
  }

    public MyDatabaseTools(final Context context, final String appName) {
        this.appName = appName;
        packageName = context.getPackageName();
    }
}