Recipe Creating a Backup of Runtime Data

Android provides the BackupManager class for developers to notify the Backup service to do backup and restore operations. After the notification is received, the backup manager requests backup data from the application and delivers it to a cloud storage server during backup. It also retrieves backup data from the backup transport and returns it to applications during a restore process.

A backup agent is the interface where the BackupManager communicates with the applications.To create a backup agent for applications, developers can extend the BackupAgent in their class. Inside any class that extends BackupAgent, two methods need to be overridden: onBackup() and onRestore() .The onBackup() method is triggered whenever there is a dataChanged() method call.The onRestore() method is triggered whenever there is a requestRestore() method call:

public class MyBackupAgent extends BackupAgent { ^Override public void onCreate() { }

^Override public void onBackup(ParcelFileDescriptor oldState, BackupDataOutput data, ParcelFileDescriptor newState){

^Override public void onRestore(BackupDataInput data, int appVersionCode, ParcelFileDescriptor newState){

The onBackup() method has three parameters that are passed and used by the backup manager:

■ oldState—Return the state from the last backup

■ newState—Write the current state of the backup, which becomes the oldState for the next backup

In implementing the onBackup() method, the oldState that the BackupManager passes in should be checked against the current data state. If it is the same, there is no need to do the backup. If it is not the same, the data passed to the method should be written, and the newState should be updated for the backup.

The onRestore() method has three parameters passed and used by the backup manager as well:

■ appVersionCode—The application's version code during the backup operation. The version code is defined as the attribute android:versionCode in the Android-Manifest XML file.

■ newState—Write the current state as the restore point.

Any data conversions required in changes from version to version should be done in the onRestore() method.That is the reason the BackupManager passes the appVersionCode. After the data is restored to the application, the state of the application changes.At this point, a newState needs to be written.

Character Building Thought Power

Character Building Thought Power

Character-Building Thought Power by Ralph Waldo Trine. Ralph draws a distinct line between bad and good habits. In this book, every effort is made by the writer to explain what comprises good habits and why every one needs it early in life. It draws the conclusion that habits nurtured in early life concretize into impulses in future for the good or bad of the subject.

Get My Free Ebook


Post a comment