《Android应用开发攻略》——2.14 备份Android应用程序数据

2.14 备份Android应用程序数据

Pratik Rupwal
2.14.1 问题
当用户恢复出厂设置或者改用新的Android设备时,应用程序丢失存储数据或者应用程序设置。
2.14.2 解决方案
Android的Backup Manager(备份管理器)能够在应用程序重新安装时自动恢复备份数据或者应用程序设置。
2.14.3 讨论
Android的备份管理器本质上以两种模式运行——备份和恢复。在备份操作期间,备份管理器(BackuManager类)询问应用程序所要备份的数据,并将其放入一个备份传输中,备份传输负责将数据发送到基于云的存储中。在恢复操作期间,备份管理器从备份传输中读取备份数据,并将其返回给应用程序,以便将数据恢复到设备上。应用程序可以请求恢复,但是在应用程序安装且与用户关联的备份数据存在时,Android并不一定执行恢复操作。恢复备份数据主要发生在用户重置设备或者升级到新设备,并且重新安装过去安装的应用程序时。
例2-19展示了为应用程序实现备份管理器以保存应用程序当前状态的方法。
以下是这一过程各个步骤的简单描述:
1 . 在Eclipse中创建BackupManagerExample项目。
2 . 打开layout/backup_restore.xml文件,并插入例2-19中的代码。
3 . 打开values/string.xml文件并插入例2-20中的代码。
4 . 清单文件看上去将类似于例2-21。
5 . 例2-22中的代码完成了应用程序备份管理器的实现。
例2-19:备份/恢复布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
   android:layout_width="match_parent"
   android:layout_height="wrap_content">
    <ScrollView
       android:orientation="vertical"
       android:layout_width="fill_parent"
       android:layout_height="fill_parent"
       android:layout_weight="1">
        <LinearLayout
           android:orientation="vertical"
           android:layout_width="match_parent"
           android:layout_height="wrap_content">
            <TextView android:text="@string/filling_text"
               android:textSize="20dp"
               android:layout_marginTop="20dp"
               android:layout_marginBottom="10dp"
               android:layout_width="match_parent"
               android:layout_height="wrap_content"/>
            <RadioGroup android:id="@+id/filling_group"
               android:layout_width="match_parent"
               android:layout_height="wrap_content"
               android:layout_marginLeft="20dp"
               android:orientation="vertical">
                <RadioButton android:id="@+id/bacon"
                   android:text="@string/bacon_label"/>
                <RadioButton android:id="@+id/pastrami"
                   android:text="@string/pastrami_label"/>
                <RadioButton android:id="@+id/hummus"
                   android:text="@string/hummus_label"/>
            </RadioGroup>
            <TextView android:text="@string/extras_text"
               android:textSize="20dp"
               android:layout_marginTop="20dp"
               android:layout_marginBottom="10dp"
               android:layout_width="match_parent"
               android:layout_height="wrap_content"/>
            <CheckBox android:id="@+id/mayo"
               android:text="@string/mayo_text"
               android:layout_marginLeft="20dp"
               android:layout_width="match_parent"
               android:layout_height="wrap_content"/>
            <CheckBox android:id="@+id/tomato"
               android:text="@string/tomato_text"
               android:layout_marginLeft="20dp"
               android:layout_width="match_parent"
               android:layout_height="wrap_content"/>
        </LinearLayout>
    </ScrollView>
</LinearLayout>

例2-20:示例使用的字符串

<resources>
  <string name="hello">Hello World, BackupManager!</string>
  <string name="app_name">BackupManager</string>
  <string name="filling_text">Choose Settings for your application:</string>
  <string name="bacon_label">Sound On</string>
  <string name="pastrami_label">Vibration On</string>
  <string name="hummus_label">Backlight On</string>
  <string name="extras_text">Extras:</string>
  <string name="mayo_text">Use Orientation?</string>
  <string name="tomato_text">Use Camera?</string>
</resources>

例2-21:AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.sym.backupmanager"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="9" />
    <application android:label="Backup/Restore" android:icon="@drawable/icon"
        android:backupAgent="ExampleAgent"> <!-- Here you specify the backup agent-->
        <!--Some backup transports may require API keys or other metadata-->
        <meta-data android:name="com.google.android.backup.api_key"
                android:value="INSERT YOUR API KEY HERE" />
        <activity android:name=".BackupManagerExample">
                <intent-filter>
                        <action android:name="android.intent.action.MAIN" />
                        <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
        </activity> </application>
</manifest>

例2-22:备份/恢复活动

package com.sym.backupmanager;
import android.app.Activity;
import android.app.backup.BackupManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.RadioGroup;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
public class BackupManagerExample extends Activity {
        static final String TAG = "BRActivity";
        static final Object[] sDataLock = new Object[0];
        static final String DATA_FILE_NAME = "saved_data";
        RadioGroup mFillingGroup;
        CheckBox mAddMayoCheckbox;
        CheckBox mAddTomatoCheckbox;
        File mDataFile;
        BackupManager mBackupManager;
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.backup_restore);
            mFillingGroup = (RadioGroup) findViewById(R.id.filling_group);
            mAddMayoCheckbox = (CheckBox) findViewById(R.id.mayo);
            mAddTomatoCheckbox = (CheckBox) findViewById(R.id.tomato);
             mDataFile = new File(getFilesDir(), BackupManagerExample.DATA_FILE_NAME);
             mBackupManager = new BackupManager(this);
            populateUI();
        }
        void populateUI() {
            RandomAccessFile file;
            int whichFilling = R.id.pastrami;
            boolean addMayo = false;
            boolean addTomato = false;
            synchronized (BackupManagerExample.sDataLock) {
                boolean exists = mDataFile.exists();
                try {
                    file = new RandomAccessFile(mDataFile, "rw");
                    if (exists) {
                        Log.v(TAG, "datafile exists");
                        whichFilling = file.readInt();
                        addMayo = file.readBoolean();
                        addTomato = file.readBoolean();
                        Log.v(TAG, " mayo=" + addMayo
                                + " tomato=" + addTomato
                                + " filling=" + whichFilling);
                    } else {
                        Log.v(TAG, "creating default datafile");
                        writeDataToFileLocked(file,
                                addMayo, addTomato, whichFilling);
                        mBackupManager.dataChanged();
                        }
                    } catch (IOException ioe) {
                        // 在这里进行错误处理!
                    }
                }
                mFillingGroup.check(whichFilling);
                mAddMayoCheckbox.setChecked(addMayo);
                mAddTomatoCheckbox.setChecked(addTomato);
                mFillingGroup.setOnCheckedChangeListener(
                        new RadioGroup.OnCheckedChangeListener() {
                            public void onCheckedChanged(RadioGroup group,
                                    int checkedId) {
                                Log.v(TAG, "New radio item selected: " + checkedId);
                                recordNewUIState();
                            }
                        });
                CompoundButton.OnCheckedChangeListener checkListener
                        = new CompoundButton.OnCheckedChangeListener() {
                    public void onCheckedChanged(CompoundButton buttonView,
                            boolean isChecked) {
                        Log.v(TAG, "Checkbox toggled: " + buttonView);
                        recordNewUIState();
                    }
                };
                mAddMayoCheckbox.setOnCheckedChangeListener(checkListener);
                mAddTomatoCheckbox.setOnCheckedChangeListener(checkListener);
            }
            void writeDataToFileLocked(RandomAccessFile file,
                    boolean addMayo, boolean addTomato, int whichFilling)
                throws IOException {
                    file.setLength(0L);
                    file.writeInt(whichFilling);
                    file.writeBoolean(addMayo);
                    file.writeBoolean(addTomato);
                    Log.v(TAG, "NEW STATE: mayo=" + addMayo
                            + " tomato=" + addTomato
                            + " filling=" + whichFilling);
            }
            void recordNewUIState() {
                boolean addMayo = mAddMayoCheckbox.isChecked();
                boolean addTomato = mAddTomatoCheckbox.isChecked();
                int whichFilling = mFillingGroup.getCheckedRadioButtonId();
                try {
                    synchronized (BackupManagerExample.sDataLock) {
                        RandomAccessFile file = new RandomAccessFile(mDataFile, "rw");
                        writeDataToFileLocked(file, addMayo, addTomato, whichFilling);
                    }
                } catch (IOException e) {
                    Log.e(TAG, "Unable to record new UI state");
                }
            mBackupManager.dataChanged();
     }
}

数据备份不能保证在所有Android设备上可用。但是,如果设备没有提供备份传输,应用程序并不会受到不利影响。如果你相信用户将从应用程序的数据备份中获益,就可以按照这个文档中描述的步骤实现、测试这一功能,然后发布应用程序,而不考虑设备是否实际执行备份。当应用程序在不提供备份传输的设备上运行时,它将正常运作,但是不会接受来自备份管理器的回调来备份数据。
尽管你无法知道当前传输手段是什么,但是始终可以确信,备份数据不会被设备上的其他应用程序读取。只有备份管理器和备份传输有权访问备份操作中所提供的数据。
警告: 因为云存储和传输服务在不同的设备上可能有差别,Android不能保证备份中的数据安全。在使用备份存储敏感数据(如用户名和密码)时,应该始终保持警惕。
测试你的备份代理
实现备份代理之后,可以使用bmgr命令,按照如下步骤测试备份/恢复功能:
1 . 在合适的Android系统映像上安装你的应用程序。如果使用模拟器,创建和使用带有Android 2.2(API Level 8)的AVD。如果使用真实设备,设备必须运行Android 2.2或更高版本并内建Android Market。
2 . 确保备份功能启用。如果使用的是模拟器,可以从SDK tools/路径用如下命令启用备份功能:
adb shell bmgr enable true
如果使用的是设备,打开系统设置,选择Privacy(隐私),然后启用“Back up my data” (备份我的数据)和 “Automatic restore”(自动恢复)。
3 . 打开应用程序并初始化某些数据。
如果在你的应用程序中已经正常地实现了备份功能,在每次数据改变时将要求备份。例如,每当用户修改某些数据,应用程序将会调用dataChanged(),该方法在备份服务器队列中添加一个备份请求,为了测试,你也可以用如下的bmgr命令发出一个请求:
adb shell bmgr backup your.package.name
4 . 初始化备份操作:
adb shell bmgr run
这条命令强制备份管理器执行队列中的所有备份请求。
5 . 卸载你的应用程序:
adb uninstall your.package.name
6 . 重新安装应用程序。
如果备份代理成功,第4步中初始化的所有数据将被恢复。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值