For details, refer to the Development notes of an Android tablet project-scheduled task backup
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 context mcontext; public backuptask (context) {This. mcontext = context;} @ override protected integer doinbackground (string... params) {// todo auto-generated method stub
// Obtain the path of the database in use. My path is/dlion/db_dlion.db under the sdcard directory.
// The default path is/data/(package name)/databases /*. DB file dbfile = mcontext. getdatabasepath (environment. getexternalstoragedirectory (). getabsolutepath () + "/dlion/db_dlion.db"); file exportdir = new file (environment. getexternalstoragedirectory (), "dlionbackup"); 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");} catch (exception e) {// todo: handle exception E. printstacktrace (); Return log. D ("backup", "fail") ;}} else if (command. equals (command_restore) {T Ry {filecopy (backup, dbfile); Return log. D ("Restore", "success");} catch (exception e) {// todo: handle exception E. printstacktrace (); Return log. D ("Restore", "fail") ;}} else {return NULL ;}} private void filecopy (File dbfile, file backup) throws ioexception {// todo auto-generated method stub filechannel inchannel = new fileinputstream (dbfile ). getchannel (); filechannel outchannel = new fi Leoutputstream (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 ();}}}}
Asynchronously load backup and restoration in mainactivity:
// Data recovery private void datarecover () {// todo auto-generated method stub new backuptask(this).exe cute ("restroedatabase");} // data backup private void databackup () {// todo auto-generated method stub new backuptask(thiscmd.exe cute ("backupdatabase ");}