public classDataBaseUtils {//当前数据库地址
privateString DB_PATH;//备份后数据库保存地址
privateString DB_BACKUP_PATH;privateContext context;privateMessageShow ms;//备份成功状态
private final int BACKUP_OK = 1;//备份失败状态
private final int BACKUP_FAIL = -1;//恢复成功状态
private final int RECOVER_OK = 2;//恢复失败状态
private final int RECOVER_FAIL = -2;public interfaceMessageShow{public voidonPepare();public voidonSuccess();public voidonFail();
}publicDataBaseUtils(Context context) {this.context =context;
}/*** @Title: doDataBackUp
* @Description: TODO(数据备份)
*@param*@returnvoid 返回类型
*@author@throws
*/
public voiddoDataBackUp(String DB_PATH, String DB_BACKUP_PATH,MessageShow ms) {this.DB_PATH =DB_PATH;this.DB_BACKUP_PATH =DB_BACKUP_PATH;this.ms=ms;newBackUpTask().execute();
}/*** @ClassName: BackUpTask
* @Description: TODO(数据库备份异步任务)
*@author[email protected]/273219
* @date 2015-12-25 上午11:10:58
**/@TargetApi(Build.VERSION_CODES.CUPCAKE)class BackUpTask extends AsyncTask{
@Overrideprotected voidonPreExecute() {//TODO Auto-generated method stub
super.onPreExecute();if(ms!=null) {
ms.onPepare();
}
}
@OverrideprotectedInteger doInBackground(String... params) {//TODO Auto-generated method stub//默认路径 /data/data/(包名)/databases/*.db
File dbFile =context.getDatabasePath(DB_PATH);
File exportDir= newFile(DB_BACKUP_PATH);int result = 0;if (!exportDir.exists()) {
exportDir.mkdirs();
}
File backup= newFile(exportDir, dbFile.getName());try{
backup.createNewFile();
fileCopy(dbFile, backup);
result=BACKUP_OK;
}catch(Exception e) {
Log.e("backup_error", e.getMessage());
result=BACKUP_FAIL;
}returnresult;
}
@Overrideprotected voidonPostExecute(Integer result) {//TODO Auto-generated method stub
super.onPostExecute(result);switch(result) {caseBACKUP_OK:if(ms!=null) {
ms.onSuccess();
}break;caseBACKUP_FAIL:if(ms!=null) {
ms.onFail();
}break;
}
}
}/*** @Title: fileCopy
* @Description: TODO(文件拷贝方法)
*@param @paramdbFile
*@param @parambackup
*@param @throwsIOException 设定文件
*@returnvoid 返回类型
*@author@throws
*/
private void fileCopy(File dbFile, File backup) throwsIOException {//TODO Auto-generated method stub
FileChannel inChannel = newFileInputStream(dbFile).getChannel();
FileChannel outChannel= newFileOutputStream(backup).getChannel();try{
inChannel.transferTo(0, inChannel.size(), outChannel);
}catch(IOException e) {//TODO Auto-generated catch block
Log.e("fileCopy_error", e.getMessage());
}finally{if (inChannel != null) {
inChannel.close();
}if (outChannel != null) {
outChannel.close();
}
}
}
}