为 Android 移动应用启用脱机同步Enable offline sync for your Android mobile app

概述Overview

本教程介绍适用于 Android 的 Azure 移动应用的脱机同步功能。This tutorial covers the offline sync feature of Azure Mobile Apps for Android. 脱机同步允许最终用户与移动应用进行交互—查看、添加或修改数据—,即使在没有网络连接时也是如此。Offline sync allows end users to interact with a mobile app—viewing, adding, or modifying data—even when there is no network connection. 在本地数据库中存储更改。Changes are stored in a local database. 设备重新联机后,这些更改会与远程后端同步。Once the device is back online, these changes are synced with the remote backend.

对于首次体验 Azure 移动应用的读者,请先完成创建 Android 应用教程。If this is your first experience with Azure Mobile Apps, you should first complete the tutorial Create an Android App. 如果不使用下载的快速入门服务器项目,必须将数据访问扩展包添加到项目。If you do not use the downloaded quick start server project, you must add the data access extension packages to your project. 有关服务器扩展包的详细信息,请参阅使用适用于 Azure 移动应用的 .NET 后端服务器 SDKFor more information about server extension packages, see Work with the .NET backend server SDK for Azure Mobile Apps.

若要了解有关脱机同步功能的详细信息,请参阅 Azure 移动应用中的脱机数据同步(Azure 移动应用中的脱机数据同步)主题。To learn more about the offline sync feature, see the topic Offline Data Sync in Azure Mobile Apps.

更新应用以支持脱机同步Update the app to support offline sync

借助脱机同步,可从同步表读取和写入(使用 IMobileServiceSyncTable 接口),该表是设备上 SQLite 数据库的一部分。With offline sync, you read to and write from a sync table (using the IMobileServiceSyncTable interface), which is part of a SQLite database on your device.

若要在设备与 Azure 移动服务之间推送和拉取更改,可以使用同步上下文 (MobileServiceClient.SyncContext),该上下文借助本地存储数据时所用的本地数据库进行初始化。To push and pull changes between the device and Azure Mobile Services, you use a synchronization context (MobileServiceClient.SyncContext), which you initialize with the local database to store data locally.

  1. TodoActivity.java 中,注释掉 mToDoTable 的现有定义,并取消注释同步表版本:In TodoActivity.java, comment out the existing definition of mToDoTable and uncomment the sync table version:

    private MobileServiceSyncTable<ToDoItem> mToDoTable;
    
  2. onCreate 方法中,注释掉 mToDoTable 的现有初始化,并取消注释以下定义:In the onCreate method, comment out the existing initialization of mToDoTable and uncomment this definition:

    mToDoTable = mClient.getSyncTable("ToDoItem", ToDoItem.class);
    
  3. refreshItemsFromTable comment out the definition of results 的现有初始化,取消注释以下定义:In refreshItemsFromTable comment out the definition of results and uncomment this definition:

    // Offline Sync
    final List<ToDoItem> results = refreshItemsFromMobileServiceTableSyncTable();
    
  4. 注释掉 refreshItemsFromMobileServiceTable的定义。Comment out the definition of refreshItemsFromMobileServiceTable.

  5. 取消注释 refreshItemsFromMobileServiceTableSyncTable的定义:Uncomment the definition of refreshItemsFromMobileServiceTableSyncTable:

    private List<ToDoItem> refreshItemsFromMobileServiceTableSyncTable() throws ExecutionException, InterruptedException {
        //sync the data
        sync().get();
        Query query = QueryOperations.field("complete").
                eq(val(false));
        return mToDoTable.read(query).get();
    }
    
  6. 取消注释 sync的定义:Uncomment the definition of sync:

    private AsyncTask<Void, Void, Void> sync() {
        AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>(){
            @Override
            protected Void doInBackground(Void... params) {
                try {
                    MobileServiceSyncContext syncContext = mClient.getSyncContext();
                    syncContext.push().get();
                    mToDoTable.pull(null).get();
                } catch (final Exception e) {
                    createAndShowDialogFromTask(e, "Error");
                }
                return null;
            }
        };
        return runAsyncTask(task);
    }
    

测试应用程序Test the app

此部分在启用 WiFi 的情况下测试行为,并关闭 WiFi 以创建脱机方案。In this section, you test the behavior with WiFi on, and then turn off WiFi to create an offline scenario.

添加数据项时,它们保存在本地 SQLite 存储中,但直到按下“刷新” 按钮才同步到移动服务。When you add data items, they are held in the local SQLite store, but not synced to the mobile service until you press the Refresh button. 根据数据需要同步的时间,其他应用可能具有不同的要求,但出于演示目的,本教程让用户显式请求它。Other apps may have different requirements regarding when data needs to be synchronized, but for demo purposes this tutorial has the user explicitly request it.

按该按钮时,将启动一个新的后台任务。When you press that button, a new background task starts. 该任务先使用同步上下文推送对本地存储所做的所有更改,并将所有更改的数据从 Azure 拉取到本地表。It first pushes all changes made to the local store using synchronization context, then pulls all changed data from Azure to the local table.

脱机测试Offline testing

  1. 将设备或模拟器置于飞行模式中。Place the device or simulator in Airplane Mode. 这会创建脱机方案。This creates an offline scenario.

  2. 添加一些 ToDo 项或将一些项标记为“完成”。Add some ToDo items, or mark some items as complete. 退出设备或模拟器(或强制关闭应用),然后重新启动。Quit the device or simulator (or forcibly close the app) and restart. 验证所做更改是否保存在设备上,因为本地 SQLite 存储已保存这些更改。Verify that your changes have been persisted on the device because they are held in the local SQLite store.

  3. 使用 SQL 工具(如 SQL Server Management Studio)或 REST 客户端(如 FiddlerPostman)查看 Azure TodoItem 表的内容。View the contents of the Azure TodoItem table either with a SQL tool such as SQL Server Management Studio, or a REST client such as Fiddler or Postman. 验证新项是否 同步到服务器Verify that the new items have not been synced to the server

    + <span data-ttu-id="5005a-136">对于 Node.js 后端,请转到 [Azure 门户](https://portal.azure.cn/),在移动应用后端中单击“简易表”   > “TodoItem”  ,以查看 `TodoItem` 表的内容。</span><span class="sxs-lookup"><span data-stu-id="5005a-136">For a Node.js backend, go to the [Azure portal](https://portal.azure.cn/), and in your Mobile App backend click **Easy Tables** > **TodoItem** to view the contents of the `TodoItem` table.</span></span>
    + <span data-ttu-id="5005a-137">对于 .NET 后端,请使用 SQL 工具(如 *SQL Server Management Studio*)或 REST 客户端(如 *Fiddler* 或 *Postman*)查看表内容。</span><span class="sxs-lookup"><span data-stu-id="5005a-137">For a .NET backend, view the table contents either with a SQL tool such as *SQL Server Management Studio*, or a REST client such as *Fiddler* or *Postman*.</span></span>
    
  4. 在设备或模拟器中打开 WiFi。Turn on WiFi in the device or simulator. 接下来,按“刷新” 按钮。Next, press the Refresh button.

  5. 在 Azure 门户中再次查看 TodoItem 数据。View the TodoItem data again in the Azure portal. 新的和更改的 TodoItem 现在应会出现。The new and changed TodoItems should now appear.

其他资源Additional Resources