If you have a Service
, then when startService()
is called this results in a call to onStartCommand()
which runs on the main (UI) Thread in the process.
In an IntentService
, when startService()
is called this results in a call to onHandleIntent()
which is called on a worker thread.
Obviously there is a potential that both of these calls will happen in parallel.
There are many ways to deal with potential parallel execution. Here are a few examples:
You can synchronize the database loading on a common object so that both threads cannot load the database at the same time. Each thread should check if the data has already been loaded before it loads to prevent duplicates.
To load your database, you can submit a job to a queue (or submit a Runnable
to a Handler
, or something similar). You then have a separate thread that dequeues entries from the queue and runs them serially (one after another). In this case, if both your services submit jobs to the queue, one will run before the other one and they will not run in parallel. Also here you should make sure that you prevent duplicates by either checking if the data has already been loaded before loading it again, or by making sure that you only run one job in the queue.
- Create a table in your database that is used as a locking mechanism and has a column that indicates whether a load is in progress (this should be a primary key column that allows no duplicates). Before you start to the load the data, insert a row into the locking table. If there is a load in progress, this should fail with "duplicate key". If it is successful, load your data. When you are done, delete the row from the locking table.