Android - sqlite content providers and multithreading

前端 未结 3 2153
花落未央
花落未央 2021-01-02 11:36

I\'m a little confused about content providers. If I have multiple activities in my application do they each get their own instance of the content provider? it\'s just essen

相关标签:
3条回答
  • 2021-01-02 12:05

    If you work directly with databases and have multiple writers from different threads you may run into concurrency issues.

    The ContentProvider can be accessed from several programs at the same time, therefore you must implement the access thread-safe. The easiest way is to use the keyword synchronized in front of all methods of the ContentProvider, so that only one thread can access these methods at the same time.

    If you do not require that Android synchronizes data access to the ContentProvider, set the android:multiprocess=true attribute in your <provider> definition in the AndroidManifest.xml file. This permits an instance of the provider to be created in each client process, eliminating the need to perform interprocess communication (IPC).

    0 讨论(0)
  • 2021-01-02 12:11

    If you are using a ContentProvider, I believe you don't care how many threads are reading/writing: the Android platform handles marshalling all your calls onto a single thread and sorting out synchronization and locking. You just open your database and read/write into it, and everyone else talks through the ContentProvider interface.

    0 讨论(0)
  • 2021-01-02 12:12

    Oops, I lost my unregistered user cookie so can't vote Femi's answer correct.

    The documentation http://developer.android.com/guide/topics/providers/content-providers.html confirms this with "When a query is initiated, the Android system identifies the content provider that's the target of the query and makes sure that it is up and running. The system instantiates all ContentProvider objects; you never need to do it on your own. In fact, you never deal directly with ContentProvider objects at all. Typically, there's just a single instance of each type of ContentProvider. But it can communicate with multiple ContentResolver objects in different applications and processes. The interaction between processes is handled by the ContentResolver and ContentProvider classes. "

    0 讨论(0)
提交回复
热议问题