import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
public class BackupTask extends
AsyncTask
{
private static final String COMMAND_BACKUP =
"backupDatabase";
public static final String COMMAND_RESTORE =
"restroeDatabase";
private static final int BACKUP_SUCCESS = 1;
public static final int RESTORE_SUCCESS =
2;
private static final int BACKUP_ERROR = 3;
public static final int RESTORE_NOFLEERROR =
4;
private Context myContext;
public BackupTask(Context context) {
this.myContext = context;
}
@Override
protected Integer doInBackground(String... params) {
// 默认路径是
data/data/honglin.doors/databases/HonglinDoors.db
File dbFile =
myContext.getDatabasePath("HonglinDoors.db");
// 创建目录
File exportDir = new
File(Environment.getExternalStorageDirectory(),
"DoorsDB");
if (!exportDir.exists()) {
exportDir.mkdirs();
}
File backup = new File(exportDir, dbFile.getName());
String command = params[0];
if (command.equals(COMMAND_BACKUP)) {
try {
backup.createNewFile();
fileCopy(dbFile, backup);
//return Log.d("backup", "ok");
return BACKUP_SUCCESS;
} catch (Exception e) {
e.printStackTrace();
//return Log.d("backup", "fail");
return BACKUP_ERROR;
}
} else if (command.equals(COMMAND_RESTORE)) {
try {
fileCopy(backup, dbFile);
//return Log.d("restore", "success");
return RESTORE_SUCCESS;
} catch (Exception e) {
e.printStackTrace();
//return Log.d("restore", "fail");
return RESTORE_NOFLEERROR;
}
} else {
return null;
}
}
private void fileCopy(File dbFile, File backup) throws
IOException {
FileChannel inChannel = new
FileInputStream(dbFile).getChannel();
FileChannel outChannel = new
FileOutputStream(backup).getChannel();
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inChannel != null) {
inChannel.close();
}
if (outChannel != null) {
outChannel.close();
}
}
}
@Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
switch (result) {
case BACKUP_SUCCESS:
Log.d("backup", "ok");
break;
case BACKUP_ERROR:
Log.d("backup", "fail");
break;
case RESTORE_SUCCESS:
Log.d("restore", "success");
break;
case RESTORE_NOFLEERROR:
Log.d("restore", "fail");
break;
default:
break;
}
}
}
在mainActivity里实现备份、还原
//数据恢复
private void dataResume(){
new
BackupTask(this).execute("restroeDatabase");
}
//数据备份
private void
dataBackup(){
new
BackupTask(this).execute("backupDatabase");
}