Docs Menu

Docs HomeDevelop ApplicationsAtlas Device SDKs

Sync a Realm in the Background - Java SDK

On this page

  • Prerequisites
  • Example
  • Synchronization Logic
  • Worker

If you need to sync data when your app isn't running, you can sync realms in a background process.

To get started with background synchronization, you need to add the following dependencies to your Android application:

Background sync requires two things:

  • synchronization logic

  • a scheduled job that periodically performs that logic.

First, write the custom logic that synchronizes your realm. Treat this logic as a standalone connection to your backend. As a result, you'll need to:

  • initialize the Realm SDK

  • authenticate a user to open the realm

You can use a user's cached credentials if the user recently used the app.

Open the realm, then use SyncSession.downloadAllServerChanges() and SyncSession.uploadAllLocalChanges() to synchronize the realm fully with the backend.

You can execute this logic as a background process using a subclass of ListenableWorker. Put your synchronization logic in the startWork() method of your worker:

To create a worker that periodically performs background sync:

  1. Create a set of constraints that specify the conditions required for your worker.

  2. Specify how frequently your worker should execute.

  3. Enqueue your worker with the Android OS. Assign it a unique identifier so that you can update the job in the future.

You can create the background sync job inside an Application subclass in your app to guarantee that the logic only executes once every time your application runs.

Since synchronizing a realm uses data, you should consider only downloading changes in the background when the device is not:

  • low on battery

  • using a metered data source

Use Constraints to describe the environment where your background sync runs.

Your repeat interval depends on how frequently data updates in the realm and how often users open your application. If the realm frequently updates throughout the day, consider setting a repeat interval of 1-3 hours. If the realm only updates a small number of times each day, it's best to set a higher repeat interval and only background sync once or twice a day.

← Check the Current Network Connection - Java SDK