安卓mysql类库_Android数据库备份类

[android]代码库/**

* Android数据库备份类

*/

public class BackupTask extends AsyncTask implements

CompletionListener {

// 定义常量

public static final int BACKUP_SUCCESS = 1;

public static final int RESTORE_SUCCESS = 2;

public static final int BACKUP_ERROR = 3;

public static final int RESTORE_NOFLEERROR = 4;

public static final String COMMAND_BACKUP = "backupDatabase";

public static final String COMMAND_RESTORE = "restroeDatabase";

private Context mContext;

public BackupTask(Context context) {

this.mContext = context;

}

@Override

protected Integer doInBackground(String... params) {

// 1,获得数据库路径

File dbFile = mContext.getDatabasePath("xxx.db");

// 2,创建保存的数据库的路径

File exportDir = new File(Environment.getExternalStorageDirectory(),

"shopBackup");

if (!exportDir.exists()) {

exportDir.mkdirs();

}

File backup = new File(exportDir, dbFile.getName());

// 3,检查操作

String command = params[0];

if (command.equals(COMMAND_BACKUP)) {

// 复制文件

try {

backup.createNewFile();

fileCopy(dbFile, backup);

return BACKUP_SUCCESS;

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

return BACKUP_ERROR;

}

} else {

return BACKUP_ERROR;

}

}

private void fileCopy(File source, File dest) throws IOException {

FileChannel inChannel = new FileInputStream(source).getChannel();

FileChannel outChannel = new FileOutputStream(dest).getChannel();

// FileInputStream fis = new FileInputStream(dbFile);

// FileOutputStream fos = new FileOutputStream(backup);

// byte buffer[] = new byte[4 * 1024];

// while(fis.read(buffer) != -1){

// fos.write(buffer);

// }

// fos.flush();

//

long size = inChannel.size();

try {

inChannel.transferTo(0, inChannel.size(), outChannel);

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} finally {

if (inChannel != null) {

inChannel.close();

}

if (outChannel != null) {

outChannel.close();

}

}

}

@Override

protected void onPostExecute(Integer result) {

// TODO Auto-generated method stub

super.onPostExecute(result);

switch (result) {

case BACKUP_SUCCESS:

onBackupComplete();

break;

default:

break;

}

}

@Override

public void onBackupComplete() {

Log.d("backup", "ok");

}

@Override

public void onRestoreComplete() {

// TODO Auto-generated method stub

}

@Override

public void onError(int errorCode) {

// TODO Auto-generated method stub

}

}

694748ed64b9390909c0d88230893790.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值