How to BackUp user’s data programatically in Android?

By | January 25, 2018

Android’s Backup service allows you to persist the data in a Google cloud storage. Android does this with the help of a BackUpAgent in the SDK.
If we want to backup the data, then extend the BackupAgent.

Lets see how we can do this.

Benefits

  • Reduce user frustration
  • Increase login-rate.
  • Reduce support calls
  • Minimize user attrition
  • Sustain user engagement
  • Increase user retention rate

Implementation

Register

To use the backup service you have to register your application package for it, via the Backup service registration. This webpage allows you to get a backup key for a application package.

Android Manifest

Once you register with the BackUp service, you will get a BackUp Key.

You will get something like this

<meta-data android:name="com.google.android.backup.api_key"
            android:value="AEdPqrEAAAAIIOrdswuHXMDSVQrLudj3vEUedTk0n29UVkB1Ew" />

You have to put this inside the application tag in the manifest.

Here is a sample Android Manifest file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.coderzheaven.databackupdemo">

    <application
        android:allowBackup="true"
        android:backupAgent=".DemoBackUpAgent"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <meta-data android:name="com.google.android.backup.api_key"
            android:value="AEdPqrEAAAAIIOrdswuHXMDSVQrLudj3vEUedTk0n29UVkB1Ew" />

    </application>

</manifest>

BackUp Agent

In the above manifest file, we can see a DemoBackUpAgent in the android:backupagent property.

The implementation goes like this.

package com.coderzheaven.databackupdemo;

import android.app.backup.BackupAgentHelper;
import android.app.backup.BackupDataInput;
import android.app.backup.BackupDataOutput;
import android.app.backup.SharedPreferencesBackupHelper;
import android.content.SharedPreferences;
import android.os.ParcelFileDescriptor;
import android.util.Log;

import java.io.IOException;

public class DemoBackUpAgent extends BackupAgentHelper {

    // The name of the SharedPreferences file
    static final String PREFS = "myprefs";

    // A key to uniquely identify the set of backup data
    static final String PREFS_BACKUP_KEY = "myprefs";

    @Override
    public void onCreate() {
        SharedPreferencesBackupHelper helper = new SharedPreferencesBackupHelper(this, PREFS);
        addHelper(PREFS_BACKUP_KEY, helper);

        SharedPreferences pref = getApplicationContext().getSharedPreferences(PREFS, 0); 
        SharedPreferences.Editor editor = pref.edit();
        editor.putBoolean("key_name1", true);
        editor.commit();
    }

    @Override
    public void onBackup(ParcelFileDescriptor oldState, BackupDataOutput data, ParcelFileDescriptor newState) throws IOException {
        super.onBackup(oldState, data, newState);
        Log.i("backup", "OnBackUp");
    }

    @Override
    public void onRestore(BackupDataInput data, int appVersionCode, ParcelFileDescriptor newState) throws IOException {
        super.onRestore(data, appVersionCode, newState);
        Log.i("restore", "onRestore");
    }

    @Override
    public void onRestoreFinished() {
        super.onRestoreFinished();
        Log.i("restore", "onRestoreFinished");
    }
}

Testing the BackUp.

By default the BackUp Agent automatically does the backup via wifi once in a day.

For testing we can trigger it using adb command.

First thing is, if you are using the emulator, then you have to enabled the backup.

Enable Backup

Use the below command for this.

adb shell bmgr enable true

If you are testing in real device, then make sure you have enabled backup.
To do this, open the system Settings, select Privacy, then enable Back up my data and Automatic restore.

To start backup

<strong>./adb shell bmgr backup com.coderzheaven.databackupdemo</strong>

Run the backup

adb shell bmgr run

Now to backup has been done.

To see the restore process, make some changes in the preferences like this…

SharedPreferences pref = getApplicationContext().getSharedPreferences(PREFS, 0); 
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("key_name1", true);
editor.putString("key_name2", "Coderz");
editor.putString("key_name3", "Heaven");
editor.commit();

Now uninstall the application

adb uninstall com.coderzheaven.databackupdemo

Reinstall the application and Do a restore

adb shell bmgr restore com.coderzheaven.databackupdemo

Data will be restored in the device.

Source Code

You can download the source code from here.

3 thoughts on “How to BackUp user’s data programatically in Android?

  1. Jan Bos

    How do I call DemoBackUpAgent from another class ?

    Doesn’t work:
    Intent intenttest=new Intent(this, DemoBackUpAgent.class);
    intenttest.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); //
    startActivity(intenttest);
    finish();

    Reply
    1. James Post author

      Dear Jan,

      You cannot call the Demo BackUp agent as such..I have given the testing methods in the post itself. Please check how to trigger the backup.

      Testing the BackUp.

      By default the BackUp Agent automatically does the backup via wifi once in a day.

      For testing we can trigger it using adb command.

      First thing is, if you are using the emulator, then you have to enabled the backup.

      Check rest above…

      Reply

Leave a Reply to Jan Bos Cancel reply

Your email address will not be published. Required fields are marked *