在 Android 应用程序和网络服务器之间同步数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10829371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 05:07:14  来源:igfitidea点击:

Sync data between Android App and webserver

androidandroid-syncadapterdata-sharing

提问by Omid Nazifi

I want to sync data (such as db record, media) between an Android App and a Server. If you've seen Evernoteor similar Applications, you certainly understand what I mean.

我想在 Android 应用程序和服务器之间同步数据(例如数据库记录、媒体)。如果你看过Evernote或类似的应用程序,你肯定明白我的意思。

I have some question (imagine we want to sync DB records):

我有一些问题(假设我们要同步数据库记录):

  1. Every user has a part of server space for himself (such as Evernoteor Dropbox). Maybe the user creates new records by cellphone and creates new records in server. How can I match these records together?If there are records with same ID What algorithms do you suggest me?

  2. Except JSON, Are there any way for send data between cellphone device and server?

  3. If SyncAdapterand ContentProvidercan solve my problems, please explain exactly for me. (If you could offer some samples or tutorials to me OR Any advice or keywords to help broaden/guide my search would be appreciated as well).

  1. 每个用户都有自己的一部分服务器空间(例如EvernoteDropbox)。也许用户通过手机创建新记录并在服务器中创建新记录。如何将这些记录匹配在一起?如果有相同 ID 的记录,您建议我使用什么算法?

  2. 除了JSON有没有办法在手机设备和服务器之间发送数据?

  3. 如果SyncAdapterContentProvider可以解决我的问题,请为我准确解释。(如果您可以向我提供一些示例或教程或任何有助于扩大/指导我的搜索的建议或关键字,也将不胜感激)。

回答by Grantismo

I'll try to answer all your questions by addressing the larger question: How can I sync data between a webserver and an android app?

我将尝试通过解决更大的问题来回答您的所有问题:如何在网络服务器和 android 应用程序之间同步数据?



Syncing data between your webserver and an android app requires a couple of different components on your android device.

在您的网络服务器和 android 应用程序之间同步数据需要您的 android 设备上有几个不同的组件。

Persistent Storage:

持久存储:

This is how your phone actually stores the data it receives from the webserver. One possible method for accomplishing this is writing your own custom ContentProviderbacked by a Sqlite database. A decent tutorial for a content provider can be found here: http://thinkandroid.wordpress.com/2010/01/13/writing-your-own-contentprovider/

这就是您的手机实际存储从网络服务器接收到的数据的方式。实现此目的的一种可能方法是编写您自己的由 Sqlite 数据库支持的自定义ContentProvider。内容提供者的体面教程可以在这里找到:http: //thinkandroid.wordpress.com/2010/01/13/writing-your-own-contentprovider/

A ContentProviderdefines a consistent interface to interact with your stored data. It could also allow other applications to interact with your data if you wanted. Behind your ContentProvidercould be a Sqlite database, a Cache, or any arbitrary storage mechanism.

一个ContentProvider的定义一致的接口与存储的数据进行交互。如果您愿意,它还可以允许其他应用程序与您的数据进行交互。在ContentProvider后面可以是 Sqlite 数据库、缓存或任何任意存储机制。

While I would certainly recommend using a ContentProviderwith a Sqlite database you could use any java based storage mechanism you wanted.

虽然我肯定会推荐将ContentProvider与 Sqlite 数据库一起使用,但您可以使用任何您想要的基于 Java 的存储机制。

Data Interchange Format:

数据交换格式:

This is the format you use to send the data between your webserver and your android app. The two most popular formats these days are XML and JSON. When choosing your format, you should think about what sort of serialization libraries are available. I know off-hand that there's a fantastic library for json serialization called gson: https://github.com/google/gson, although I'm sure similar libraries exist for XML.

这是您用来在您的网络服务器和您的 android 应用程序之间发送数据的格式。目前最流行的两种格式是 XML 和 JSON。在选择格式时,您应该考虑可用的序列化库类型。我立即知道有一个很棒的 json 序列化库,称为 gson:https: //github.com/google/gson,尽管我确信 XML 存在类似的库。

Synchronization Service

同步服务

You'll want some sort of asynchronous task which can get new data from your server and refresh the mobile content to reflect the content of the server. You'll also want to notify the server whenever you make local changes to content and want to reflect those changes. Android provides the SyncAdapterpattern as a way to easily solve this pattern. You'll need to register user accounts, and then Android will perform lots of magic for you, and allow you to automatically sync. Here's a good tutorial: http://www.c99.org/2010/01/23/writing-an-android-sync-provider-part-1/

您将需要某种异步任务,它可以从您的服务器获取新数据并刷新移动内容以反映服务器的内容。每当您对内容进行本地更改并希望反映这些更改时,您还需要通知服务器。Android 提供了SyncAdapter模式来轻松解决此模式。您需要注册用户帐户,然后 Android 会为您执行很多魔术,并允许您自动同步。这是一个很好的教程:http: //www.c99.org/2010/01/23/writing-an-android-sync-provider-part-1/



As for how you identify if the records are the same, typically you'll create items with a unique id which you store both on the android device and the server. You can use that to make sure you're referring to the same reference. Furthermore, you can store column attributes like "updated_at" to make sure that you're always getting the freshest data, or you don't accidentally write over newly written data.

至于如何识别记录是否相同,通常您将创建具有唯一 id 的项目,并将其存储在 android 设备和服务器上。您可以使用它来确保您指的是相同的参考。此外,您可以存储诸如“updated_at”之类的列属性,以确保您始终获得最新的数据,或者您不会意外地覆盖新写入的数据。

回答by Pratik Butani

If we think about today, accepted answeris too old. As we know that we have many new libraries which can help you to make this types of application.

如果我们考虑今天接受的答案太旧了。众所周知,我们有许多新的库可以帮助您制作此类应用程序。

You should learn following topics that will helps you surely:

您应该学习以下肯定会对您有所帮助的主题:

  • SyncAdapter:The sync adapter component in your app encapsulates the code for the tasks that transfer data between the device and a server. Based on the scheduling and triggers you provide in your app, the sync adapter framework runs the code in the sync adapter component.

  • Realm: Realm is a mobile database: a replacement for SQLite & Core Data.

  • RetrofitType-safe HTTP client for Android and Java by Square, Inc. Must Learn a-smart-way-to-use-retrofit

  • SyncAdapter:应用中的同步适配器组件封装了在设备和服务器之间传输数据的任务的代码。根据您在应用程序中提供的调度和触发器,同步适配器框架运行同步适配器组件中的代码。

  • Realm:Realm 是一个移动数据库:SQLite 和 Core Data 的替代品。

  • 改造用于 Android 和 Java 的类型安全 HTTP 客户端,由 Square, Inc. 提供。必须学习一种智能的使用方式改造

And your sync logic for database like: How to sync SQLite database on Android phone with MySQL database on server?

以及您的数据库同步逻辑,例如:如何将 Android 手机上的 SQLite 数据库与服务器上的 MySQL 数据库同步?

Best Luck to all new learner. :)

祝所有新学习者好运。:)

回答by openmobster

If you write this yourself these are some of the points to keep in mind

如果你自己写这些是要记住的一些要点

Proper authentication between the device and the Sync Server

设备和同步服务器之间的正确身份验证

A sync protocol between the device and the server. It will usually go in 3 phases, authentication, data exchange, status exchange (which operations worked and which failed)

设备和服务器之间的同步协议。它通常分为 3 个阶段,身份验证、数据交换、状态交换(哪些操作有效,哪些失败)

Pick your payload format. I suggest SyncML based XML mixed with JSON based format to represent the actual data. So SyncML for the protocol, and JSON for the actual data being exchanged. Using JSON Array while manipulating the data is always preferred as it is easy to access data using JSON Array.

选择您的有效负载格式。我建议将基于 SyncML 的 XML 与基于 JSON 的格式混合来表示实际数据。所以 SyncML 用于协议,JSON 用于实际交换的数据。在操作数据时使用 JSON 数组总是首选,因为使用 JSON 数组很容易访问数据。

Keeping track of data changes on both client and server. You can maintain a changelog of ids that change and pick them up during a sync session. Also, clear the changelog as the objects are successfully synchronized. You can also use a boolean variable to confirm the synchronization status, i.e. last time of sync. It will be helpful for end users to identify the time when last sync is done.

跟踪客户端和服务器上的数据更改。您可以维护在同步会话期间更改并获取它们的 id 的更改日志。此外,在对象成功同步时清除更改日志。您还可以使用布尔变量来确认同步状态,即上次同步时间。最终用户确定上次同步完成的时间将很有帮助。

Need to have a way to communicate from the server to the device to start a sync session as data changes on the server. You can use C2DM or write your own persistent tcp based communication. The tcp approach is a lot seamless

需要有一种方法可以从服务器到设备进行通信,以在服务器上的数据更改时启动同步会话。您可以使用 C2DM 或编写您自己的基于 tcp 的持久通信。tcp 方法非常无缝

A way to replicate data changes across multiple devices

一种跨多个设备复制数据更改的方法

And last but not the least, a way to detect and handle conflicts

最后但并非最不重要的是,一种检测和处理冲突的方法

Hope this helps as a good starting point.

希望这有助于作为一个好的起点。

回答by Ciro Costa

@Grantismo provides a great explanation on the overall. If you wish to know who people are actually doing this things i suggest you to take a look at how google did for the Google IO App of 2014 (it's always worth taking a deep look at the source code of these apps that they release. There's a lot to learn from there).

@Grantismo 对整体提供了很好的解释。如果你想知道实际上是谁在做这件事,我建议你看看谷歌是如何为 2014 年的谷歌 IO 应用程序做的(深入研究他们发布的这些应用程序的源代码总是值得的。有从那里可以学到很多东西)。

Here's a blog post about it: http://android-developers.blogspot.com.br/2014/09/conference-data-sync-gcm-google-io.html

这是一篇关于它的博客文章:http: //android-developers.blogspot.com.br/2014/09/conference-data-sync-gcm-google-io.html

Essentially, on the application side: GCM for signalling, Sync Adapter for data fetching and talking properly with Content Provider that will make things persistent (yeah, it isolates the DB from direct access from other parts of the app).

本质上,在应用程序方面:用于信令的 GCM,用于数据获取和与内容提供程序正确对话的同步适配器,这将使事情持久化(是的,它将数据库与应用程序的其他部分的直接访问隔离开来)。

Also, if you wish to take a look at the 2015's code: https://github.com/google/iosched

另外,如果您想查看 2015 年的代码:https: //github.com/google/iosched

回答by Phan Van Linh

For example, you want to sync table todoTablefrom MySqlto Sqlite

例如,您希望将表todoTable从同步MySqlSqlite

First, create one column name version (type INT)in todoTablefor both Sqliteand MySqlenter image description here

首先,创建一个列名version (type INT)todoTable两个SqliteMySql在此处输入图片说明

Second, create a table name database_versionwith one column name currentVersion(INT)
enter image description here

二、创建database_version一个列名的表名currentVersion(INT)
在此处输入图片说明

In MySql, when you add a new item to todoTableor update item, you must upgrade the version of this item by +1 and alsoupgrade the currentVersionenter image description here

MySql,当你添加一个新项目todoTable或更新项目时,你必须将这个项目的版本升级+1,同时升级currentVersion在此处输入图片说明

In Android, when you want to sync (by manual press sync button or a service run with period time):

Android,当您想要同步时(通过手动按下同步按钮或​​在一段时间内运行的服务):

You will send the request with the SqlitecurrentVersion (currently it is 1) to server.
Then in server, you find what item in MySqlhave version value greater than SqlitecurrentVersion(1) then response to Android (in this example the item 3 with version 2 will response to Android)

您将使用SqlitecurrentVersion(当前为 1)向服务器发送请求。
然后在服务器中,您找到MySql版本值大于SqlitecurrentVersion(1) 的项目,然后响应 Android(在此示例中,版本 2 的项目 3 将响应 Android)

In SQLite, you will add or update new item to todoTableand upgrade the currentVersion

在 中SQLite,您将添加或更新新项目todoTable并升级当前版本

回答by Kyle

Look at parseplatform.org. it's opensource project.

看看parseplatform.org。它是开源项目。

(As well as you can go for commercial package available at back4app.com.)

(以及您可以在back4app.com 上购买商业包。)

It is a very straight forward and user friendly server side database service that gives a great android client side API

这是一个非常直接和用户友好的服务器端数据库服务,提供了一个很棒的 android 客户端 API

回答by Mayank

one way to accomplish this to have a server side application that waits for the data. The data can be sent using HttpRequestobjects in Java or you can write your own TCP/IPdata transfer utility. Data can be sent using JSONformat or any other format that you think is suitable. Also data can be encrypted before sending to server if it contains sensitive information. All Server application have to do is just wait for HttpRequeststo come in and parse the data and store it anywhere you want.

实现此目的的一种方法是让服务器端应用程序等待数据。可以使用HttpRequestJava 中的对象发送数据,也可以编写自己的TCP/IP数据传输实用程序。可以使用JSON格式或您认为合适的任何其他格式发送数据。如果数据包含敏感信息,也可以在发送到服务器之前对其进行加密。服务器应用程序所要做的就是等待HttpRequests进入并解析数据并将其存储在您想要的任何位置。

回答by Neo

I would suggest using a binary webservice protocol similar to Hessian. It works very well and they do have a android implementation. It might be a little heavy but depends on the application you are building. Hope this helps.

我建议使用类似于Hessian的二进制网络服务协议。它工作得很好,而且他们确实有一个 android 实现。它可能有点重,但取决于您正在构建的应用程序。希望这可以帮助。

回答by Sean

@Grantismo gives a great overview of Android sync components.

@Grantismo 对 Android 同步组件进行了很好的概述。

SyncManagerAndroid library provides a simple 2-way sync implementation to plug into the Android Sync framework (AbstractThreadedSyncAdapter.OnPerformSync).

SyncManagerAndroid 库提供了一个简单的 2 路同步实现来插入 Android 同步框架 (AbstractThreadedSyncAdapter.OnPerformSync)。

https://github.com/sschendel/SyncManagerAndroid

https://github.com/sschendel/SyncManagerAndroid