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:
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.
You can execute this logic as a background process using a subclass of
Put your synchronization logic in the
startWork() method of your worker:
To create a worker that periodically performs background sync:
Create a set of constraints that specify the conditions required for your worker.
Specify how frequently your worker should execute.
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.