SlideShare a Scribd company logo
1 of 24
Download to read offline
Data Backup

Kewang
What is Backup Service ?


Backup data to the cloud
Restore data when reinstalled app
Requires API Level 8+


                                    2
Getting Started




                  3
Getting Started


Register service & declare agent
Extend backup agent
 BackupAgent
 BackupAgentHelper

                                   4
Register service & declare agent




                              5
Register service & declare agent
<manifest>

  <application android:backupAgent="ExampleAgent" >
    <meta-data
android:name="com.google.android.backup.api_key"
android:value="AEdPqrEAAAAIW4p30C1GTNjzBOqWrb0clI7_O
CWxm3ddIgkKhw" />

  </application>

</manifest>            backupAgent
                       backup.api_key
                                                       6
Extend backup agent


BackupAgent
 Version data format
 Back up the portions of data
 Back up data in a database

                                7
Extend BackupAgent
public class ExampleAgent extends BackupAgent {
  @Override
  public void onBackup(ParcelFileDescriptor oldState,
BackupDataOutput data, ParcelFileDescriptor newState) {
    // TODO
  }

  @Override
  public void onRestore(BackupDataInput data, int
appVersionCode, ParcelFileDescriptor newState) {
    // TODO
  }
}

                                                      8
Extend BackupAgent

onBackup
 ParcelFileDescriptor oldState
   read-only last backup state, may be null
   contains representation of the data
   from the last onBackup's newState

 BackupDataOutput data
   use to deliver backup data

 ParcelFileDescriptor newState
   record the final backup state after writing data   9
Extend BackupAgent

onRestore
 BackupDataInput data
   can read backup data

 int appVersionCode
   Manifest attribute when data was backed up
   can cross-check app version

 ParcelFileDescriptor newState
   write the state of data
                                                10
Implement onBackup (1/2)
boolean doBackup = (oldState == null);

synchronized (BackupRestoreActivity.sDataLock) {
  RandomAccessFile f = new RandomAccessFile(mFile, "r");

    mFilling = f.readInt();
    mAddMayo = f.readBoolean();
    mAddTomato = f.readBoolean();


}
    f.close();               read local file
if (!doBackup) {
                             is newest
  doBackup = compareStateFile(oldState);
}                                                    11
Implement onBackup (2/2)
if (doBackup) {
  ByteArrayOutputStream buf = new ByteArrayOutputStream();
  DataOutputStream out = new DataOutputStream(buf);

    out.writeInt(mFilling);
    out.writeBoolean(mAddMayo);
    out.writeBoolean(mAddTomato);        back up
    byte[] buffer = buf.toByteArray();
    int len = buffer.length;

    data.writeEntityHeader(APP_DATA_KEY, len);
    data.writeEntityData(buffer, len);
}

writeStateFile(newState);                              12
Implement onRestore (1/3)


String key = data.getKey();
int size = data.getDataSize();

if (!APP_DATA_KEY.equals(key)) {
  data.skipEntityData();
}

           data is invalid, skip it

                                      13
Implement onRestore (2/3)
if (APP_DATA_KEY.equals(key)) {
  byte[] buf = new byte[size];

 data.readEntityData(buf, 0, size);

  ByteArrayInputStream is = new
ByteArrayInputStream(buf);
  DataInputStream in = new DataInputStream(is);

 mFilling = in.readInt();
 mAddMayo = in.readBoolean();
 mAddTomato = in.readBoolean();


                data is valid, read it            14
Implement onRestore (3/3)

    synchronized (BackupRestoreActivity.sDataLock) {
      RandomAccessFile f = new RandomAccessFile(mFile, "rw");

        f.setLength(0L);
        f.writeInt(mFilling);
        f.writeBoolean(mAddMayo);
        f.writeBoolean(mAddTomato);

        f.close();

}
    }                 write data to local file
writeStateFile(newState);
                                                         15
Another backup agent


BackupAgentHelper
 Back up SharedPreferences
 Back up a file


                             16
Extend BackupAgentHelper
public class ExampleAgent extends BackupAgentHelper {
  @Override
  public void onCreate() {
    FileBackupHelper helper = new FileBackupHelper(this,
"file");

        addHelper("key", helper);
    }
}

can also use
SharedPreferencesBackupHelper
                                                      17
How to using & testing it ?




                              18
How to using & testing it ?


mBackupManager.dataChanged();



                   Request backup


                                    19
How to using & testing it ?
mBackupManager.requestRestore(new RestoreObserver() {
  @Override
  public void restoreStarting(int numPackages) {
  }

  @Override
  public void onUpdate(int nowBeingRestored,
String currentPackage) {
  }
                         Request restore
  @Override
  public void restoreFinished(int error) {
  }
});
                                                        20
How to using & testing it ?

adb shell bmgr run
adb shell bmgr backup <package>
adb shell bmgr restore <package>
adb shell bmgr wipe <package>
adb shell bmgr enable <boolean>
                                   21
FAQ

Storage size ?
 unknown
Backup data TTL ?
 unknown
Can synchronizing ?
 CANNOT               22
References


Android Backup Service
Data Backup
Using the Backup API
Sample Project->BackupRestore
                                23
24

More Related Content

What's hot

Cloudcamp scotland - Using cloud without losing control
Cloudcamp scotland - Using cloud without losing controlCloudcamp scotland - Using cloud without losing control
Cloudcamp scotland - Using cloud without losing control
Duncan Johnston-Watt
 

What's hot (20)

JavaScript client API for Google Apps Script API primer
JavaScript client API for Google Apps Script API primerJavaScript client API for Google Apps Script API primer
JavaScript client API for Google Apps Script API primer
 
Intoroduce milkcocoa for english
Intoroduce milkcocoa for englishIntoroduce milkcocoa for english
Intoroduce milkcocoa for english
 
Bootstrap
BootstrapBootstrap
Bootstrap
 
Dbabstraction
DbabstractionDbabstraction
Dbabstraction
 
Caching a page
Caching a pageCaching a page
Caching a page
 
Bulk copy
Bulk copyBulk copy
Bulk copy
 
Do something in 5 with gas 8-copy between databases
Do something in 5 with gas 8-copy between databasesDo something in 5 with gas 8-copy between databases
Do something in 5 with gas 8-copy between databases
 
Getting your data in and out of elasticsearch: let me count the ways
Getting your data in and out of elasticsearch: let me count the waysGetting your data in and out of elasticsearch: let me count the ways
Getting your data in and out of elasticsearch: let me count the ways
 
Streaming using Kafka Flink & Elasticsearch
Streaming using Kafka Flink & ElasticsearchStreaming using Kafka Flink & Elasticsearch
Streaming using Kafka Flink & Elasticsearch
 
Cloudcamp scotland - Using cloud without losing control
Cloudcamp scotland - Using cloud without losing controlCloudcamp scotland - Using cloud without losing control
Cloudcamp scotland - Using cloud without losing control
 
Dynamically Evolving Systems: Cluster Analysis Using Time
Dynamically Evolving Systems: Cluster Analysis Using TimeDynamically Evolving Systems: Cluster Analysis Using Time
Dynamically Evolving Systems: Cluster Analysis Using Time
 
Node collaboration - Exported Resources and PuppetDB
Node collaboration - Exported Resources and PuppetDBNode collaboration - Exported Resources and PuppetDB
Node collaboration - Exported Resources and PuppetDB
 
Realtime Database with iOS and Firebase
Realtime Database with iOS and FirebaseRealtime Database with iOS and Firebase
Realtime Database with iOS and Firebase
 
Ajax - a quick introduction
Ajax - a quick introductionAjax - a quick introduction
Ajax - a quick introduction
 
NHibernate Configuration Patterns
NHibernate Configuration PatternsNHibernate Configuration Patterns
NHibernate Configuration Patterns
 
Do something in 5 with apps scripts number 6 - fusion crossfilter
Do something in 5 with apps scripts number 6 - fusion crossfilterDo something in 5 with apps scripts number 6 - fusion crossfilter
Do something in 5 with apps scripts number 6 - fusion crossfilter
 
Sibelius Seraphini - Relay Modern
Sibelius Seraphini - Relay ModernSibelius Seraphini - Relay Modern
Sibelius Seraphini - Relay Modern
 
Spring data ii
Spring data iiSpring data ii
Spring data ii
 
HeadCouch - CouchDB PHP Client
HeadCouch - CouchDB PHP ClientHeadCouch - CouchDB PHP Client
HeadCouch - CouchDB PHP Client
 
Testowanie JavaScript
Testowanie JavaScriptTestowanie JavaScript
Testowanie JavaScript
 

Similar to Data backup

Android programming -_pushing_the_limits
Android programming -_pushing_the_limitsAndroid programming -_pushing_the_limits
Android programming -_pushing_the_limits
Droidcon Berlin
 
Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best Practices
Yekmer Simsek
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
Alexey Buzdin
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
C.T.Co
 
Droidcon2013 android experience lahoda
Droidcon2013 android experience lahodaDroidcon2013 android experience lahoda
Droidcon2013 android experience lahoda
Droidcon Berlin
 
Android Support Library
Android Support LibraryAndroid Support Library
Android Support Library
Alexey Ustenko
 
Android Studio Assignment HelpCan someone who is familiar with And.pdf
Android Studio Assignment HelpCan someone who is familiar with And.pdfAndroid Studio Assignment HelpCan someone who is familiar with And.pdf
Android Studio Assignment HelpCan someone who is familiar with And.pdf
feelinggift
 

Similar to Data backup (20)

Android workshop
Android workshopAndroid workshop
Android workshop
 
Android programming -_pushing_the_limits
Android programming -_pushing_the_limitsAndroid programming -_pushing_the_limits
Android programming -_pushing_the_limits
 
Spring and Cloud Foundry; a Marriage Made in Heaven
Spring and Cloud Foundry; a Marriage Made in HeavenSpring and Cloud Foundry; a Marriage Made in Heaven
Spring and Cloud Foundry; a Marriage Made in Heaven
 
Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best Practices
 
Android Froyo
Android FroyoAndroid Froyo
Android Froyo
 
Androidaop 170105090257
Androidaop 170105090257Androidaop 170105090257
Androidaop 170105090257
 
S03 hybrid app_and_gae_datastore_v1.0
S03 hybrid app_and_gae_datastore_v1.0S03 hybrid app_and_gae_datastore_v1.0
S03 hybrid app_and_gae_datastore_v1.0
 
That’s My App - Running in Your Background - Draining Your Battery
That’s My App - Running in Your Background - Draining Your BatteryThat’s My App - Running in Your Background - Draining Your Battery
That’s My App - Running in Your Background - Draining Your Battery
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 
Modern Android app library stack
Modern Android app library stackModern Android app library stack
Modern Android app library stack
 
Backendless apps
Backendless appsBackendless apps
Backendless apps
 
Improving android experience for both users and developers
Improving android experience for both users and developersImproving android experience for both users and developers
Improving android experience for both users and developers
 
Droidcon2013 android experience lahoda
Droidcon2013 android experience lahodaDroidcon2013 android experience lahoda
Droidcon2013 android experience lahoda
 
Dicoding Developer Coaching #27: Android | Membuat Aplikasi Support Online Ma...
Dicoding Developer Coaching #27: Android | Membuat Aplikasi Support Online Ma...Dicoding Developer Coaching #27: Android | Membuat Aplikasi Support Online Ma...
Dicoding Developer Coaching #27: Android | Membuat Aplikasi Support Online Ma...
 
Android Support Library
Android Support LibraryAndroid Support Library
Android Support Library
 
Lviv MDDay 2014. Ігор Коробка “забезпечення базової безпеки в андроїд аплікац...
Lviv MDDay 2014. Ігор Коробка “забезпечення базової безпеки в андроїд аплікац...Lviv MDDay 2014. Ігор Коробка “забезпечення базової безпеки в андроїд аплікац...
Lviv MDDay 2014. Ігор Коробка “забезпечення базової безпеки в андроїд аплікац...
 
Android Studio Assignment HelpCan someone who is familiar with And.pdf
Android Studio Assignment HelpCan someone who is familiar with And.pdfAndroid Studio Assignment HelpCan someone who is familiar with And.pdf
Android Studio Assignment HelpCan someone who is familiar with And.pdf
 
深入淺出談Fragment
深入淺出談Fragment深入淺出談Fragment
深入淺出談Fragment
 
F# in the enterprise
F# in the enterpriseF# in the enterprise
F# in the enterprise
 

More from Mu Chun Wang

More from Mu Chun Wang (20)

如何在有限資源下實現十年的後端服務演進
如何在有限資源下實現十年的後端服務演進如何在有限資源下實現十年的後端服務演進
如何在有限資源下實現十年的後端服務演進
 
深入淺出 autocomplete
深入淺出 autocomplete深入淺出 autocomplete
深入淺出 autocomplete
 
你畢業後要任職的軟體業到底都在做些什麼事
你畢業後要任職的軟體業到底都在做些什麼事你畢業後要任職的軟體業到底都在做些什麼事
你畢業後要任職的軟體業到底都在做些什麼事
 
網路服務就是一連串搜尋的集合體
網路服務就是一連串搜尋的集合體網路服務就是一連串搜尋的集合體
網路服務就是一連串搜尋的集合體
 
老司機帶你上手 PostgreSQL 關聯式資料庫系統
老司機帶你上手 PostgreSQL 關聯式資料庫系統老司機帶你上手 PostgreSQL 關聯式資料庫系統
老司機帶你上手 PostgreSQL 關聯式資料庫系統
 
使用 PostgreSQL 及 MongoDB 從零開始建置社群必備的按讚追蹤功能
使用 PostgreSQL 及 MongoDB 從零開始建置社群必備的按讚追蹤功能使用 PostgreSQL 及 MongoDB 從零開始建置社群必備的按讚追蹤功能
使用 PostgreSQL 及 MongoDB 從零開始建置社群必備的按讚追蹤功能
 
Funliday 新創生活甘苦談
Funliday 新創生活甘苦談Funliday 新創生活甘苦談
Funliday 新創生活甘苦談
 
大解密!用 PostgreSQL 提升 350 倍的 Funliday 推薦景點計算速度
大解密!用 PostgreSQL 提升 350 倍的 Funliday 推薦景點計算速度大解密!用 PostgreSQL 提升 350 倍的 Funliday 推薦景點計算速度
大解密!用 PostgreSQL 提升 350 倍的 Funliday 推薦景點計算速度
 
如何使用 iframe 製作一個易於更新及更安全的前端套件
如何使用 iframe 製作一個易於更新及更安全的前端套件如何使用 iframe 製作一個易於更新及更安全的前端套件
如何使用 iframe 製作一個易於更新及更安全的前端套件
 
pppr - 解決 JavaScript 無法被搜尋引擎正確索引的問題
pppr - 解決 JavaScript 無法被搜尋引擎正確索引的問題pppr - 解決 JavaScript 無法被搜尋引擎正確索引的問題
pppr - 解決 JavaScript 無法被搜尋引擎正確索引的問題
 
模糊也是一種美 - 從 BlurHash 探討前後端上傳圖片架構
模糊也是一種美 - 從 BlurHash 探討前後端上傳圖片架構模糊也是一種美 - 從 BlurHash 探討前後端上傳圖片架構
模糊也是一種美 - 從 BlurHash 探討前後端上傳圖片架構
 
Google Maps 開始收費了該怎麼辦?
Google Maps 開始收費了該怎麼辦?Google Maps 開始收費了該怎麼辦?
Google Maps 開始收費了該怎麼辦?
 
Git 可以做到的事
Git 可以做到的事Git 可以做到的事
Git 可以做到的事
 
那些大家常忽略的 Cache-Control
那些大家常忽略的 Cache-Control那些大家常忽略的 Cache-Control
那些大家常忽略的 Cache-Control
 
如何利用 OpenAPI 及 WebHooks 讓老舊的網路服務也可程式化
如何利用 OpenAPI 及 WebHooks 讓老舊的網路服務也可程式化如何利用 OpenAPI 及 WebHooks 讓老舊的網路服務也可程式化
如何利用 OpenAPI 及 WebHooks 讓老舊的網路服務也可程式化
 
如何與全世界分享你的 Library
如何與全世界分享你的 Library如何與全世界分享你的 Library
如何與全世界分享你的 Library
 
如何與 Git 優雅地在樹上唱歌
如何與 Git 優雅地在樹上唱歌如何與 Git 優雅地在樹上唱歌
如何與 Git 優雅地在樹上唱歌
 
API Blueprint - API 文件規範的三大領頭之一
API Blueprint - API 文件規範的三大領頭之一API Blueprint - API 文件規範的三大領頭之一
API Blueprint - API 文件規範的三大領頭之一
 
團體共同協作與版本管理 - 01認識共同協作
團體共同協作與版本管理 - 01認識共同協作團體共同協作與版本管理 - 01認識共同協作
團體共同協作與版本管理 - 01認識共同協作
 
Git 經驗分享
Git 經驗分享Git 經驗分享
Git 經驗分享
 

Recently uploaded

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Recently uploaded (20)

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 

Data backup

  • 2. What is Backup Service ? Backup data to the cloud Restore data when reinstalled app Requires API Level 8+ 2
  • 4. Getting Started Register service & declare agent Extend backup agent BackupAgent BackupAgentHelper 4
  • 5. Register service & declare agent 5
  • 6. Register service & declare agent <manifest> <application android:backupAgent="ExampleAgent" > <meta-data android:name="com.google.android.backup.api_key" android:value="AEdPqrEAAAAIW4p30C1GTNjzBOqWrb0clI7_O CWxm3ddIgkKhw" /> </application> </manifest> backupAgent backup.api_key 6
  • 7. Extend backup agent BackupAgent Version data format Back up the portions of data Back up data in a database 7
  • 8. Extend BackupAgent public class ExampleAgent extends BackupAgent { @Override public void onBackup(ParcelFileDescriptor oldState, BackupDataOutput data, ParcelFileDescriptor newState) { // TODO } @Override public void onRestore(BackupDataInput data, int appVersionCode, ParcelFileDescriptor newState) { // TODO } } 8
  • 9. Extend BackupAgent onBackup ParcelFileDescriptor oldState read-only last backup state, may be null contains representation of the data from the last onBackup's newState BackupDataOutput data use to deliver backup data ParcelFileDescriptor newState record the final backup state after writing data 9
  • 10. Extend BackupAgent onRestore BackupDataInput data can read backup data int appVersionCode Manifest attribute when data was backed up can cross-check app version ParcelFileDescriptor newState write the state of data 10
  • 11. Implement onBackup (1/2) boolean doBackup = (oldState == null); synchronized (BackupRestoreActivity.sDataLock) { RandomAccessFile f = new RandomAccessFile(mFile, "r"); mFilling = f.readInt(); mAddMayo = f.readBoolean(); mAddTomato = f.readBoolean(); } f.close(); read local file if (!doBackup) { is newest doBackup = compareStateFile(oldState); } 11
  • 12. Implement onBackup (2/2) if (doBackup) { ByteArrayOutputStream buf = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(buf); out.writeInt(mFilling); out.writeBoolean(mAddMayo); out.writeBoolean(mAddTomato); back up byte[] buffer = buf.toByteArray(); int len = buffer.length; data.writeEntityHeader(APP_DATA_KEY, len); data.writeEntityData(buffer, len); } writeStateFile(newState); 12
  • 13. Implement onRestore (1/3) String key = data.getKey(); int size = data.getDataSize(); if (!APP_DATA_KEY.equals(key)) { data.skipEntityData(); } data is invalid, skip it 13
  • 14. Implement onRestore (2/3) if (APP_DATA_KEY.equals(key)) { byte[] buf = new byte[size]; data.readEntityData(buf, 0, size); ByteArrayInputStream is = new ByteArrayInputStream(buf); DataInputStream in = new DataInputStream(is); mFilling = in.readInt(); mAddMayo = in.readBoolean(); mAddTomato = in.readBoolean(); data is valid, read it 14
  • 15. Implement onRestore (3/3) synchronized (BackupRestoreActivity.sDataLock) { RandomAccessFile f = new RandomAccessFile(mFile, "rw"); f.setLength(0L); f.writeInt(mFilling); f.writeBoolean(mAddMayo); f.writeBoolean(mAddTomato); f.close(); } } write data to local file writeStateFile(newState); 15
  • 16. Another backup agent BackupAgentHelper Back up SharedPreferences Back up a file 16
  • 17. Extend BackupAgentHelper public class ExampleAgent extends BackupAgentHelper { @Override public void onCreate() { FileBackupHelper helper = new FileBackupHelper(this, "file"); addHelper("key", helper); } } can also use SharedPreferencesBackupHelper 17
  • 18. How to using & testing it ? 18
  • 19. How to using & testing it ? mBackupManager.dataChanged(); Request backup 19
  • 20. How to using & testing it ? mBackupManager.requestRestore(new RestoreObserver() { @Override public void restoreStarting(int numPackages) { } @Override public void onUpdate(int nowBeingRestored, String currentPackage) { } Request restore @Override public void restoreFinished(int error) { } }); 20
  • 21. How to using & testing it ? adb shell bmgr run adb shell bmgr backup <package> adb shell bmgr restore <package> adb shell bmgr wipe <package> adb shell bmgr enable <boolean> 21
  • 22. FAQ Storage size ? unknown Backup data TTL ? unknown Can synchronizing ? CANNOT 22
  • 23. References Android Backup Service Data Backup Using the Backup API Sample Project->BackupRestore 23
  • 24. 24