我总是使用1.).这是我的一类,它将DB备份到SD卡.我在这里使用来自Apache commons-io的FileUtils,如果你不使用那个jar,你需要改变它.此外,SQLiteOpenHelper类(此处为MySQLiteOpenHelper.getDatabaseName())中需要一个返回数据库文件名称的方法.
你将在你的一个活动中从AsyncTask中调用它…
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();
}
}