// 参考: http://code.google.com/p/and-examples/source/browse/#svn/trunk/database/src/com/totsp/database
private class ExportDatabaseTask extends AsyncTask<Void, Void, String> {
private final ProgressDialog dialog = new ProgressDialog(mContext);
// can use UI thread here
@Override
protected void onPreExecute() {
this.dialog.setMessage("正在导出数据库文件至SD卡,请稍候...");
this.dialog.show();
}
// automatically done on worker thread (separate from UI thread)
@Override
protected String doInBackground(final Void... args) {
if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
return "未找到SD卡";
}
//setting.db为apk里的一个数据库文件
File dbFile = new File(Environment.getDataDirectory() + "/data/com.goodboyenglish.leo/databases/setting.db");
//"goodboyenglish_setting.db"为要备份至SD卡上的数据库文件名称
File file = new File(Environment.getExternalStorageDirectory(), "goodboyenglish_setting.db");
try {
//创建一个文件,如果文件存在的话会自动把原来的覆盖掉
file.createNewFile();
//拷贝文件
copyFile(dbFile, file);
return "成功导出数据库文件至SD卡!";
} catch (IOException e) {
return "导出失败!";
}
}
// can use UI thread here
@Override
protected void onPostExecute(final String msg) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
}
}
//拷贝文件的函数 src 为需要复制的文件,dst为目标文件(被src覆盖的文件)
//拷贝的过程其实就是把src文件里内容写入dst文件里的过程(从头写到尾)
public static void copyFile(File src, File dst) throws IOException {
FileChannel inChannel = new FileInputStream(src).getChannel();
FileChannel outChannel = new FileOutputStream(dst).getChannel();
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} finally {
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
}
}
调用方式:new ExportDatabaseTask().execute();