How to implement read-only ContentProvider?

2019-06-20 06:56发布

问题:

I am wondering how to best implement a read-only ContentProvider. I want my data source to be modified only from within my own application through additional special methods of my ContentProvider (which of course are not accessible through a ContentResolver). In other words, other applications should only be able to use my ContentProvider's query method but not insert, delete, or update.

The obvious solution seems to be to just return null/0/0 and do nothing else in insert/delete/update. Would it be better to always throw an Exception in these methods instead so as to communicate clearly that these operations are not allowed? Or is there even a possibility of restricting the access to the ContentProvider to the query method only via permissions?

回答1:

One method to accomplish this is via security permissions which you can access at this link in the ContentProvider paragraph. Specifically, you would set a writePermission on your provider in your AndroidManifest xml file.

If you do not wish to use security permissions, however, you can use the approaches mentioned in your second paragraph. I would suggest throwing exceptions so that it is clear that those particular insert/update/delete features can't be accessed.



回答2:

Two years later, I'm asking myself the very same question. I understand that permissions are the answer.

Nevertheless, you have to write something inside the "insert/delete/update" methods (that hopefully will not be callable).

I would agree on using an exception, because, as it is not supposed to be call, you must be warned if it is.

But a line founded here : says

Although you must implement these methods, your code does not have to do anything except return the expected data type. For example, you may want to prevent other applications from inserting data into some tables. To do this, you can ignore the call to insert() and return 0.

That would say the good way to do is just to return null/0/0. I'm gonna use this way.

I'm not sure if it worth to spend time on such a minor question anyway.