Android IPC機制(四)用ContentProvider進行處理序間通訊

來源:互聯網
上載者:User

Android IPC機制(四)用ContentProvider進行處理序間通訊

ContentProvider為儲存和擷取資料提供統一的介面,它可以在不同的應用程式之間共用資料,本身就是適合處理序間通訊的。ContentProvider底層實現也是Binder,但是使用起來比AIDL要容易許多。系統也預製了很多的ContentProvider,例如通訊錄,音視頻等,這些操作本身就是跨進程進行通訊。這篇文章主要是我們來自己實現用ContentProvider來進行處理序間通訊,而非介紹ContentProvider怎麼使用。

1. 建立資料庫,方便ContentProvider使用

我們建立資料庫,並建立表”game_provider.db”,裡面有兩個欄位分別儲存遊戲的名字和遊戲的描述。(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. 使用ContentProvider對資料庫進行操作
在initProvoder方法中,我們開啟線程來對資料庫進行操作,刪除表的所有資料,再添加資料,並實現了query和insert方法。(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.execSQL("delete from " + DbOpenHelper.GAME_TABLE_NAME);                mDb.execSQL("insert into game values(1,'九陰真經ol','最好玩的武俠網遊');");            }        }).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;    }}

在manifest檔案中,我們要讓ContentProvider運行在另一個進程,如果不大瞭解如何開啟進程,可以查看本系列的第一篇文章Android IPC機制(一)開啟多進程

3. 在Activity中調用另一個進程的GameProvider的方法
在Activity中我們在GameProvider再插入一條資料(此前GameProvider初始化時已經插入了一條資料),然後調用GameProvider的query方法來查詢資料庫中有幾條資料並列印出來。

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");        mContentValues.put("describe", "最好玩的航海網遊");        getContentResolver().insert(uri, mContentValues);        Cursor gameCursor = getContentResolver().query(uri, new String[]{"name", "describe"}, null, null, null);        while (gameCursor.moveToNext()) {            Game mGame = new Game(gameCursor.getString(0), gameCursor.getString(1));            Log.i(TAG, mGame.gameName + "---" + mGame.gameDescribe);        }    }}

Bean檔案 Game.java在Android IPC機制(三)在Android Studio中使用AIDL實現跨進程方法調用這篇文章中用過,直接拿過來用:

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);    }}

我們運行程式,發現GameProvider運行在另一個線程

log中也列印出了我們想要的結果,打出了兩條遊戲資訊:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.