Introduction to the ContentProvider of "ANDROID-IPC"

Source: Internet
Author: User

1. Content Provider Introduction

Content provider is one of the ways Android provides a way to share data between different applications, and from this point of view, it is inherently suitable for IPC (inter-process Communication, interprocess communication). The bottom-level implementation of Content provider is binder, but it is much simpler than aidl, so the system has been packaged for us.

The Android system provides us with a number of content Provider, such as Address book information, calendar information, and so on, to access information about these apps, just call Contentresolver's insert, UPDATE, DELETE, Query four methods. However, we often need more than just the data for these applications, so in many cases we need to create a custom content Provider.

Content provider mainly organizes data in tabular form and can contain multiple tables. In addition to tabular forms, the Content provider also supports file formats, movies, videos, and more.

2. Content Provider Instances

In this example, we want to operate the SQLite database on the client side of the server, including queries, deletions, additions, and modifications.

2.1. Service Side

In the server, we first create a SQLite database, called Server.db, the database has a data table, called Book table, Book table has two fields: BookID represents the number of books, BookName represents the name of the book.

We create a Mydbopenhelper class that inherits from Sqliteopenhelper to initialize the information in the database, with the following code:

 PackageMy.itgungnir.server;ImportAndroid.content.Context;Importandroid.database.sqlite.SQLiteDatabase;ImportAndroid.database.sqlite.SQLiteOpenHelper;/*** Operation Database Sqliteopenhelper Tool class * Created by Itgungnir on 2017/4/6.*/ Public classMydbopenhelperextendsSqliteopenhelper {Private Static FinalString db_name = "Server.db";  Public Static FinalString table_name = "book"; Private Static Final intDb_version = 1;  PublicMydbopenhelper (Context context) {Super(Context, Db_name,NULL, db_version); } @Override Public voidonCreate (Sqlitedatabase db) {Db.execsql ("CREATE TABLE IF not EXISTS" + table_name + "(bookId INTEGER PRIMARY KEY, BookName TEXT);"); } @Override Public voidOnupgrade (Sqlitedatabase db,intOldversion,intnewversion) {    }}

With the database, we can create a content Provider that provides an interface for manipulating the database.

We create a content provider class Bookprovider that inherits from the ContentProvider class and implements OnCreate (), insert (), update (), delete (), query () and GetType () six of these methods. where the OnCreate () method is called when ContentProvider is created, you can do some initialization operations in this method; the GetType () method is used to return the MIME type of a URI request (media type, slice, video, etc.). If you do not pay attention to this option, you can directly return null or "*/*", the remaining four methods for CRUD operations, that is, to achieve the data table additions and deletions to the function. Note: These six methods are all running in the ContentProvider process, except that the OnCreate () method runs outside the main thread, and the other five methods run in the binder thread pool.

Here's the code in the Bookprovider class we created:

 PackageMy.itgungnir.server;ImportAndroid.content.ContentProvider;Importandroid.content.ContentValues;ImportAndroid.content.Context;ImportAndroid.content.UriMatcher;ImportAndroid.database.Cursor;Importandroid.database.sqlite.SQLiteDatabase;ImportAndroid.net.Uri;ImportAndroid.support.annotation.NonNull;Importandroid.support.annotation.Nullable;/*** Server ContentProvider * Created by Itgungnir on 2017/4/6.*/ Public classBookproviderextendsContentProvider {Private Static FinalString authority = "My.itgungnir.server.book_provider"; Private Static FinalUri Content_uri = Uri.parse ("content://" + Authority + "/book"); Private Static Final intUri_code = 0x001; Private Static FinalUrimatcher Uri_matcher =NewUrimatcher (Urimatcher.no_match); Static{Uri_matcher.adduri (authority,"Book", Uri_code); }    Privatecontext Context; Privatesqlitedatabase database; PrivateString gettablename (Uri uri) {if(Uri_matcher.match (URI) = =Uri_code) {            returnMydbopenhelper.table_name; }        return NULL; }    Private voidInitData () {database=Newmydbopenhelper (context). Getwritabledatabase (); Database.execsql ("DELETE from" + Mydbopenhelper.table_name + ";"); Database.execsql ("INSERT into" + Mydbopenhelper.table_name + "VALUES (1, ' Android ');"); Database.execsql ("INSERT into" + Mydbopenhelper.table_name + "VALUES (2, ' IOS ');"); Database.execsql ("INSERT into" + Mydbopenhelper.table_name + "VALUES (3, ' HTML5 ');"); } @Override Public BooleanOnCreate () {Context=GetContext ();        InitData (); return true; } @Nullable @Override PublicCursor query (@NonNull URI Uri, @Nullable string[] projection, @Nullable String selection, @Nullable string[] Selectio Nargs, @Nullable string sortOrder) {string TableName=gettablename (URI); if(TableName = =NULL) {            Throw NewIllegalArgumentException ("Unsupported URI:" +URI); }        returnDatabase.query (TableName, projection, selection, Selectionargs,NULL,NULL, SortOrder,NULL); } @Nullable @Override Publicstring getType (@NonNull uri uri) {string TableName=gettablename (URI); if(TableName = =NULL) {            Throw NewIllegalArgumentException ("Unsupported URI:" +URI); }        return NULL; } @Nullable @Override Publicuri insert (@NonNull uri uri, @Nullable contentvalues values) {String tableName=gettablename (URI); if(TableName = =NULL) {            Throw NewIllegalArgumentException ("Unsupported URI:" +URI); } database.insert (TableName,NULL, values); Context.getcontentresolver (). Notifychange (URI,NULL); returnURI; } @Override Public intDelete (@NonNull uri Uri, @Nullable string selection, @Nullable string[] selectionargs) {string TableName =gettablename (URI); if(TableName = =NULL) {            Throw NewIllegalArgumentException ("Unsupported URI:" +URI); }        intCount =Database.delete (TableName, Selection, Selectionargs); if(Count > 0) {context.getcontentresolver (). Notifychange (URI,NULL); }        returncount; } @Override Public intupdate (@NonNull uri URI, @Nullable contentvalues values, @Nullable String selection, @Nullable string[] Selectionargs ) {String TableName=gettablename (URI); if(TableName = =NULL) {            Throw NewIllegalArgumentException ("Unsupported URI:" +URI); }        intCount =database.update (TableName, values, selection, Selectionargs); if(Count > 0) {context.getcontentresolver (). Notifychange (URI,NULL); }        returncount; }}

Because content provider belongs to the four main Android components, it needs to be registered in the project's Menifest file. When registering the content provider, you need to provide a Name property and a authorities property, which is the package path of the content provider to be registered, and the authorities property is the content Unique identification of the provider. Also, if the server and client are in different processes, we also need to specify that the exported property of the content provider is true, otherwise an error will be given: Permission Denied. Below is the registration code for our Project Server Conttent provider:

< provider     Android:name =". Bookprovider "    android:authorities=" My.itgungnir.server.book_provider "     android:exported= "true"></provider>

The above is the service-side code, you can run directly.

2.2, the Client

Introduction to the ContentProvider of "ANDROID-IPC"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.