Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 系統教學 >> 系統備份

安卓開發實作:以 AsyncTask 實現資料庫的備份與還原

編輯:系統備份

資料的備份與還原是許多應用必備的功能。由於讀寫檔案屬於耗時操作,若放在主線程會造成卡頓,因此適合以 AsyncTask 在背景執行。以下示範如何實作資料庫的備份與還原。

首先建立一個繼承自 AsyncTask 的類別,透過 FileChannel 進行檔案複製:

 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 context) { this.mContext = context; } @Override protected Integer doInBackground(String... params) { // 取得正在使用的資料庫路徑 // 預設路徑為 /data/data/(包名)/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 1; } catch (Exception e) { e.printStackTrace(); return 0; } } else if (command.equals(COMMAND_RESTORE)) { try { fileCopy(backup, dbFile); return 1; } catch (Exception e) { e.printStackTrace(); return 0; } } 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(); } } } }

接著在 MainActivity 中以非同步方式觸發備份與還原:

 // 數據恢復 private void dataRecover() { new BackupTask(this).execute("restroeDatabase"); } // 數據備份 private void dataBackup() { new BackupTask(this).execute("backupDatabase"); }

核心技巧在於用 FileChannel.transferTo() 高效地複製整個資料庫檔,並以命令字串區分「備份」與「還原」兩種行為。透過 AsyncTask 包裝後,檔案操作在背景執行,不影響 UI 流暢度。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved