Android IPC Mechanism (4) use ContentProvider for inter-process communication

Source: Internet
Author: User

Android IPC Mechanism (4) use ContentProvider for inter-process communication

ContentProvider provides a unified interface for data storage and retrieval. It can share data between different applications and is suitable for inter-process communication. The underlying implementation of ContentProvider is also a Binder, but it is much easier to use than AIDL. The system also made a lot of contentproviders, such as Address Book, audio and video. These operations are cross-process communication. This article mainly describes how to use ContentProvider for inter-process communication.

1. Create a database for ContentProvider

We create a database and a table named "game_provider.db", which contains two fields that respectively store the game name and Game Description. (DbOpenHelper. java)

package com.example.liuwangshu.mooncontentprovider;import android.content.Context;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper;public class DbOpenHelper extends SQLiteOpenHelper {    private static final String DB_NAME="game_provider.db";     static final String GAME_TABLE_NAME="game";    private static final int DB_VERSION=1;    private String CREATE_GAME_TABLE="create table if not exists " + GAME_TABLE_NAME +"(_id integer primary key," + "name TEXT, "+"describe TEXT)";    public DbOpenHelper(Context context) {        super(context, DB_NAME, null, DB_VERSION);    }    @Override    public void onCreate(SQLiteDatabase db) {       db.execSQL(CREATE_GAME_TABLE);    }    @Override    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {    }}

2. Use ContentProvider to operate the database
In the initProvoder method, we enable threads to operate databases, delete all table data, add data, and implement the query and insert methods. (GameProvider. java)

Package com. example. liuwangshu. mooncontentprovider; import android. content. contentProvider; import android. content. contentValues; import android. content. context; import android. content. uriMatcher; import android. database. cursor; import android. database. sqlite. SQLiteDatabase; import android.net. uri; public class GameProvider extends ContentProvider {public static final String AUTHORITY = "com. example. liuwangshu. mooncontentprovide. gameProvider "; public static final Uri GAME_CONTENT_URI = Uri. parse ("content: //" + AUTHORITY + "/game"); private static final UriMatcher mUriMatcher = new UriMatcher (UriMatcher. NO_MATCH); private SQLiteDatabase mDb; private Context mContext; private String table; static {mUriMatcher. addURI (AUTHORITY, "game", 0) ;}@ Override public boolean onCreate () {table = DbOpenHelper. GAME_TABLE_NAME; mContext = getContext (); initProvoder (); return false;} private void initProvoder () {mDb = new DbOpenHelper (mContext ). getWritableDatabase (); new Thread (new Runnable () {@ Override public void run () {mDb.exe cSQL ("delete from" + DbOpenHelper. GAME_TABLE_NAME); mDb.exe cSQL ("insert into game values (1, 'jiuyin Zhenjing ol ', 'most fun martial arts online games ');");}}). start () ;}@ Override public Cursor query (Uri uri, String [] projection, String selection, String [] selectionArgs, String sortOrder) {String table = DbOpenHelper. GAME_TABLE_NAME; Cursor mCursor = mDb. query (table, projection, selection, selectionArgs, null, sortOrder, null); return mCursor ;}@ Override public String getType (Uri uri) {return null ;} @ Override public Uri insert (Uri uri, ContentValues values) {mDb. insert (table, null, values); mContext. getContentResolver (). notifyChange (uri, null); return null ;}@ Override public int delete (Uri uri, String selection, String [] selectionArgs) {return 0 ;} @ Override public int update (Uri uri, ContentValues values, String selection, String [] selectionArgs) {return 0 ;}}

In the manifest file, we want ContentProvider to run in another process. If you do not know how to enable the process, you can view the first article in this series. Android IPC Mechanism (1) enable multi-process


  

3. Call the GameProvider method of another process in Activity
In the Activity, we insert another piece of data in the GameProvider (a piece of data was inserted before the GameProvider was initialized), and then call the GameProvider's query method to query several pieces of data in the database and print it out.

Package com. example. liuwangshu. mooncontentprovider; import android. content. contentValues; import android. database. cursor; import android.net. uri; import android. support. v7.app. appCompatActivity; import android. OS. bundle; import android. util. log; public class ContentProviderActivity extends AppCompatActivity {private final static String TAG = "ContentProviderActivity"; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_content_provider); Uri uri = Uri. parse ("content: // com. example. liuwangshu. mooncontentprovide. gameProvider "); ContentValues mContentValues = new ContentValues (); mContentValues. put ("_ id", 2); mContentValues. put ("name", "ol of the great ocean era"); mContentValues. put ("describe", "the most fun online games"); getContentResolver (). insert (uri, mContentValues); Cursor gameCursor = getContentResolver (). query (uri, new String [] {"name", "describe"}, null); while (gameCursor. moveToNext () {Game mGame = new Game (gameCursor. getString (0), gameCursor. getString (1); Log. I (TAG, mGame. gameName + "---" + mGame. gameDescribe );}}}

Bean file Game. java used in Android IPC Mechanism (3) using AIDL in Android Studio to call cross-process methods. In this article, we used it directly:

package com.example.liuwangshu.mooncontentprovider;import android.os.Parcel;import android.os.Parcelable;public class Game implements Parcelable {    public String gameName;    public String gameDescribe;    public Game(String gameName, String gameDescribe) {        this.gameName = gameName;        this.gameDescribe = gameDescribe;    }    protected Game(Parcel in) {        gameName = in.readString();        gameDescribe = in.readString();    }    public static final Creator
  
    CREATOR = new Creator
   
    () {        @Override        public Game createFromParcel(Parcel in) {            return new Game(in);        }        @Override        public Game[] newArray(int size) {            return new Game[size];        }    };    @Override    public int describeContents() {        return 0;    }    @Override    public void writeToParcel(Parcel dest, int flags) {        dest.writeString(gameName);        dest.writeString(gameDescribe);    }}
   
  

We run the program and found that GameProvider runs in another thread.

Log also prints the expected results and outputs two Game Information:

Related Article

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.