For details, refer to a android tablet Project Development notes-scheduled task backup http://www.bkjia.com/kf/201204/128614.html
Create a class to inherit from AsyncTask
Public class BackupTask extends AsyncTask <String, Void, Integer> {
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 mContext;
Public BackupTask (Context context ){
This. mContext = context;
}
@ Override
Protected Integer doInBackground (String... params ){
// TODO Auto-generated method stub
File dbFile = mContext. getDatabasePath ("db_dlion.db"); // obtain the database path. The default value is/data/(package name) org. dlion/databases/
File exportDir = new File (Environment. getExternalStorageDirectory (),
"DbBackup ");
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 BACKUP_SUCCESS;
} Catch (Exception e ){
// TODO: handle exception
E. printStackTrace ();
Return BACKUP_ERROR;
}
} Else if (command. equals (COMMAND_RESTORE )){
Try {
FileCopy (backup, dbFile );
Return RESTORE_SUCCESS;
} Catch (Exception e ){
// TODO: handle exception
E. printStackTrace ();
Return RESTORE_NOFLEERROR;
}
} Else {
Return BACKUP_ERROR;
}
}
Private void fileCopy (File dbFile, File backup) throws IOException {
// TODO Auto-generated method stub
FileChannel inChannel = new FileInputStream (dbFile). getChannel ();
FileChannel outChannel = new FileOutputStream (backup). getChannel ();
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 ();
}
}
}
Protected void onPostExecute (Integer result ){
// TODO Auto-generated method stub
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;
}
}
}
Asynchronously load backup and restoration in mainActivity:
// Data recovery
Private void dataRecover (){
// TODO Auto-generated method stub
New backuptask(thisw..exe cute ("restroeDatabase ");
}
// Data backup
Private void dataBackup (){
// TODO Auto-generated method stub
New backuptask(thisw..exe cute ("backupDatabase ");
}
From oldfeel