Android應用資料備份

來源:互聯網
上載者:User

Android應用資料備份

在Android上可以很方便地管理資料備份,那些不慎丟失裝置的使用者會對該功能感激不盡。備份資料會很安全地儲存在雲端,並且只在具有相同GoogleID裝置上恢複資料。

下面是典型的AndroidManifest.xml檔案片段:

android:allowBackup="true"

android:backupAgent="MyBackupAgent"

android:icon="@drawable/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme">

android:value="backup-key_string"/>

.......

 

要開啟應用程式的備份功能,只需要在android:backupAgent屬性中指定備份代理的類名。該類會處理應用資料的備份與恢複。前例的meta_data屬性指定了在Google備份服務中註冊API密匙。具體註冊網址為:https://developer.android.com/google/backup/signup.html。

註冊並擷取API密匙後,把它賦值給android:value屬性,如上面所示。雖然密匙是和應用程式的包名綁定的,不能用於其他應用程式,開發人員還是要注意不要在發布的任何代碼中公開分享它。

下面的類是一個簡單的備份代理,用於備份和恢複預設的偏好檔案。

注意:從PreferenceManager.getDefaultPreferences()得到的偏好檔案名稱為_preferences,API文檔中並沒說明,瞭解這一點對備份偏好檔案有很大的協助。

public class MyBackupAgent extends BackupAgentHelper{

public static final String PREFS_BACKUP_KEY="prefsBackup";

 

@Override

public void onCreate(){

super.onCreate();

SharedPreferencesBackupHelper sharedPreferencesBackupHelper=new SharedPreferencesBackupHelper(this,getPackageName()+"_preferences");

addHelper(PREFS_BACKUP_KEY,sharedPreferencesBackupHelper);

}

}

BackupAgentHelper類會自動備份與恢複選擇的偏好檔案。也可以使用FileBackupHelper類為其他常規檔案添加備份。

Google為Android應用提供的備份代理適合少量的資料。雖然備份SQLite資料庫在技術上是可行的,但是最好還是先把資料庫的內容轉成序列化格式,然後壓縮內容,最後備份檔案。

Android SDK提供了bmgr命令列工具,它允許對應用程式強制執行備份與恢複。這對開發應用很有用,因為可以用它檢查一切是否正常。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.