preface

Content providers (contentProviders) that share data across processes (AIDL is a cross-process sharing feature).

Content providers manage access to the central data store. A provider is a part of an Android application that typically provides its own UI to use data. However, content providers are primarily intended for use by other applications that use provider client objects to access them. Providers and provider clients work together to provide a consistent, standard data interface that also handles cross-process communication and safeguards data access.

Content providers manage access to structured data sets. They encapsulate data and provide a mechanism for defining data security. Content providers are standard interfaces that connect data in one process to code running in another. Data in an application can be shared externally. The data access mode is unified, and different policies are not required for different data types. Encapsulate the data, exposing only the data we want to make available to other programs. Data updates can be monitored.

If you do not plan to share data with other applications, you do not need to develop your own provider. However, you need to provide custom search suggestions in your own application through your own provider. If you want to copy and paste complex data or files from your application into other applications, you’ll also need to create your own provider. Android itself includes content providers that manage data such as audio, video, images and personal contact information. Some providers are listed in the Reference documentation of the Android. provider software package. Any Android application can access these providers, subject to certain restrictions.

Note: The provider does not need to have a primary key, nor does it need to_IDThe column name used as its primary key, if one exists. However, if you are going to bind data from the provider to the ListView, one of the column names must be_ID. The display query results section details this requirement.

First, the Content URI

Format: the content: / / authorities/path/id instance: the content: / / com. Hdib. The provider/user / 4

Content :// : Protocol name, indicating that this is a Content URI used to access the ContentProvider. Authorities: Is the authority of a provider, equivalent to a domain name, specifying a ContentProvider. Path: Indicates the path, which is usually represented by a table name. Id: A specific number (long) that specifies which row of data to access. ContentUris.withAppendedId(CONTENT_URI,4);

The following content is used inside a custom ContentProvider to configure matching information for URI identification.

UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); //URI matcher urimatcher. addURI(common. AUTHORITY, path, uriValue); Int uriValue = urimatcher.match (URI); // Get the matching value configured above according to the URI.Copy the code

Second, the permissions

If the Provider application does not specify any permissions, the visitor application does not have access to the Provider application data. However, components in a Provider application always have full read and write access regardless of whether or not you specify permissions.

<provider Android :name=".MyContentProvider" Android :authorities="${applicationId}; com.hdib" android:exported="true" android:grantUriPermissions="true" android:permission="com.hdib" Android :readPermission="com.hdib.READ" Android :writePermission="com.hdib.WRITE" /> // Permissions that are not provided by the system must be defined before being used. <permission android:name="com.hdib"/> <permission android:name="com.hdib.READ"/> <permission android:name="com.hdib.WRITE"/> <uses-permission android:name="com.hdib" /> <uses-permission android:name="com.hdib.READ" /> <uses-permission android:name="com.hdib.WRITE" />Copy the code
  • exported="true": Allows cross-process access
  • grantUriPermissions="true": Allows temporary access, which means that other applications can access the Provider when cross-process access is allowed.
  • authorities="${applicationId}; com.hdib: Indicates that two URIs can access the Provider${applicationId}orcom.hdib
  • permission="com.hdib": Specifies the access permission. To access the Provider using the URI, a visitor application must have this permission. If only this permission is configured for the Provider application, the visitor application can read and write the data of the Provider application.
  • readPermission="com.hdib.READ": If the provider is configured with this permission, its priority is higher than that of the providerpermissionThe latter configuration fails and allows the visitor application to read the provider’s data if the visitor application has this permission.
  • writePermission="com.hdib.WRITE": If the provider is configured with this permission, its priority is higher than that of the providerpermissionThe latter configuration fails and allows the visitor application to write data to the provider if the visitor application has this permission.

Third, ContentResolver CRUD

All operations depend on URIs. Common operations on URIs are as follows:

Uri baseUri = Uri.parse(content://com.hdib.provider);
Uri uri = Uri.withAppendedPath(baseUri, "user");
Uri uriNew = ContentUris.withAppendedId(uri, id);
long id = ContentUris.parseId(uri);
String table = uri.getPathSegments().get(0);
Copy the code

(C)

Add data. You can add one or more data. Note that in either case you end up inserting one by one, using the provider’s public Uri INSERT (Uri Uri, ContentValues VALUES) method.

ContentValues values = new ContentValues(); Values. The put (" name ", "big jujube"); Values. The put (" color ", "red"); Uri uri = getContentResolver().insert(uri,values); Int rows = getContentResolver().insert(uri,valuess); //BaseNameValuePair's key and value are both strings. BaseNameValuePair's key and value are both stringsCopy the code

Delete (D)

The deleted rows are those that meet the criteria, and multiple rows may be deleted. The provider’s public int DELETE (Uri Uri, String Selection, String[] selectionArgs) method is executed.

Int rows = getContentResolver().delete(uri,"name=?",new String[]{" date "});Copy the code

Change (U)

You modify the lines that meet the condition, and you may modify more than one line. The provider’s public int Update (Uri Uri, ContentValues VALUES, String Selection, String[] selectionArgs) method is executed.

ContentValues values = new ContentValues(); Values. The put (" color ", "green"); getContentResolver().update(uri,values,"name=? and color=?" ,new String[]{" red "," red "});Copy the code

Check (R)

The query is for rows that meet the criteria and typically returns more than one piece of data. Query (Uri Uri, String[] projection, String Selection, String[] selectionArgs, String sortOrder) method.

Cursor cursor = getContentResolver().query(
					uri,
					projection,
					selection,
					selectionArgs,
					sortOrder);
Copy the code

The transaction

Use transactions to process data. The provider’s public ContentProviderResult[] applyBatch(ArrayList

Operations) throws OperationApplicationException method.

ArrayList<ContentProviderOperation>ops = new ArrayList<ContentProviderOperation>(); / / add a delete User table of ops operation. The add (ContentProviderOperation. NewDelete (User. CONTENT_URI). The build ()); / / add a record to the Home table ops. The add (ContentProviderOperation. NewInsert (Home. CONTENT_URI). WithValues (values). The build ()); GetContentResolver ().applyBatch(PROVIDER.AUTHORITY,ops);Copy the code

Case of reading contact information

Runtime permissions: manifest.permission.READ_CONTACTS

Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,null,null,null); if(cursor==null){return ; } while(cursor.moveToNext()){ String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)); String number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); FastToast.show(context,name+":"+number); }Copy the code

Customizing the ContentProvider

I won’t talk about it here, but I’ll go straight to the Demo and see everything you need to know about custom ContentProviders. Including database content (add, delete, change and check, database encryption), data table management, database upgrade management, etc.

Register listener to monitor Provider data changes

getContentResolver().registerContentObserver(uri, true, New ContentObserver(new Handler()) {public void onChange(Boolean selfChange) {//TODO receives data changes and processes them accordingly. }});Copy the code

To enable listening to take effect, custom providers call the following methods to notify each successful operation: getContext().getContentresolver ().notifychange (URI, null);

Add: reference

The official documentation