IPC—ContentProvider

2018-09-19  本文已影响0人  要学的东西太多了

1.ContentProvider的内容URI标准格式content://包名.provider/表名。

查询:Cursor cursor=getContentResolver().query(Uri 表名uri,String 指定列名,
String 约束条件,String[] 占位符值,String 排序方式); 

增加:getContentResolver().insert(Uri 表名uri,ContentValues values);

更新:getContentResolver().update(Uri 表名uri,ContentValues values,String 约束条件,
String[] 占位符值);

删除:getContentResolver().delete(Uri 表名uri,String 约束条件,String[] 占位符值);

2.ContentProvider除了onCreate方法由系统回调运行在主线程中外(onCreate方法不能做耗时操作),其他几个方法都运行在binder线程池中。

3.android:authorities是ContentProvider的唯一标识。ContentProvider的增删改查操作是存在多线程并发访问的,同一个SQLiteDataBase内部对数据库的操作是有线程同步的,多个SQLiteDataBase需要做线程同步操作。

示例:

客户端代码:

public class TestActivity extends AppCompatActivity {
    private static final String TAG = "TestActivity";
    @BindView(R.id.button)
    CircleView button;
    private Uri Uri_user = Uri.parse("content://test_privoder/table_user");
    private Uri Uri_book = Uri.parse("content://test_privoder/table_book");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_contentprovider);
        ButterKnife.bind(this);
        addUser(1, "张三", 12);
        addUser(2, "李四", 34);
        addUser(3, "麻子", 17);
        queryUser();
        deleteUser(2);
        queryUser();
        updateUser(3, "王二", 28);
        queryUser();

        addBook(1, "Android开发艺术探索");
        addBook(2, "Android群英传");
        queryBook();
        updateBook(2, "第一行代码");
        queryBook();
        deleteBook(2);
        queryBook();
    }

    private void addUser(int userId, String name, int age) {
        ContentValues values = new ContentValues();
        values.put("userId", userId);
        values.put("name", name);
        values.put("age", age);
        getContentResolver().insert(Uri_user, values);
    }

    private void queryUser() {
        Cursor cursor = getContentResolver().query(Uri_user, new String[]{"userId", "name", "age"}, null, null, null);
        while (cursor.moveToNext()) {
            System.out.println("USER: " + cursor.getInt(0) + "," + cursor.getString(1) + "," + cursor.getInt(2));
        }
        cursor.close();
    }

    private void deleteUser(int userId) {
        getContentResolver().delete(Uri_user, "userId = ?", new String[]{String.valueOf(userId)});
    }

    private void updateUser(int userId, String name, int age) {
        ContentValues values = new ContentValues();
        values.put("name", name);
        values.put("age", age);
        getContentResolver().update(Uri_user, values, "userId = ?", new String[]{String.valueOf(userId)});
    }

    private void addBook(int bookId, String name) {
        ContentValues values = new ContentValues();
        values.put("bookId", bookId);
        values.put("name", name);
        getContentResolver().insert(Uri_book, values);
    }

    private void queryBook() {
        Cursor cursor = getContentResolver().query(Uri_book, new String[]{"bookId", "name"}, null, null, null);
        while (cursor.moveToNext()) {
            System.out.println("BOOK: " + cursor.getInt(0) + "," + cursor.getString(1));
        }
        cursor.close();
    }

    private void deleteBook(int bookId) {
        getContentResolver().delete(Uri_book, "bookId = ?", new String[]{String.valueOf(bookId)});
    }

    private void updateBook(int bookId, String name) {
        ContentValues values = new ContentValues();
        values.put("name", name);
        getContentResolver().update(Uri_book, values, "bookId = ?", new String[]{String.valueOf(bookId)});
    }
}

ContentProvider代码:

public class TestProvider extends ContentProvider{
    private Context context;
    private SQLiteDatabase database;
    private static final int CODE_USER = 0;
    private static final int CODE_BOOK = 1;
    public static final String TABLE_NAME_USER="table_user";
    public static final String TABLE_NAME_BOOK="table_book";
    private UriMatcher matcher;
    public static final String AUTHORITY = "test_privoder";
    @Override
    public boolean onCreate() {
        context=getContext();
        TestSQLiteHelper testProvider=new TestSQLiteHelper(context);
        database=testProvider.getWritableDatabase();
        database.execSQL("delete from "+TABLE_NAME_USER);
        database.execSQL("delete from "+TABLE_NAME_BOOK);

        matcher=new UriMatcher(UriMatcher.NO_MATCH);
        matcher.addURI(AUTHORITY,TABLE_NAME_USER,CODE_USER);
        matcher.addURI(AUTHORITY,TABLE_NAME_BOOK,CODE_BOOK);
        return true;
    }

    @Nullable
    @Override
    public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {
        return database.query(getTableName(uri),projection,selection,selectionArgs,null,null,sortOrder,null);
    }

    @Nullable
    @Override
    public String getType(@NonNull Uri uri) {
        return null;
    }

    @Nullable
    @Override
    public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
        database.insert(getTableName(uri),null,values);
        context.getContentResolver().notifyChange(uri,null);
        return uri;
    }

    @Override
    public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
        int count = database.delete(getTableName(uri),selection,selectionArgs);
        if(count>0){
            context.getContentResolver().notifyChange(uri,null);
        }
        return count;
    }

    @Override
    public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {
        int row = database.update(getTableName(uri),values,selection,selectionArgs);
        if(row>0){
            context.getContentResolver().notifyChange(uri,null);
        }
        return row;
    }

    private String getTableName(Uri uri){
        switch (matcher.match(uri)){
            case CODE_USER:
                return TABLE_NAME_USER;
            case CODE_BOOK:
                return TABLE_NAME_BOOK;
        }
        return "";
    }
}

SQLiteOpenHelper代码:

public class TestSQLiteHelper extends SQLiteOpenHelper{
    private static final String DB_NAME="db_test";
    private static final int DB_VERSION=1;
    private String createTableUser = "create table if not exists "+TestProvider.TABLE_NAME_USER
            +"( userId INTEGER primary key , name TEXT , age INTEGER)";
    private String createTableBook = "create table if not exists "+TestProvider.TABLE_NAME_BOOK
            +"( bookId INTEGER primary key , name TEXT )";
    public TestSQLiteHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(createTableUser);
        db.execSQL(createTableBook);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}

AndroidManifest代码:

<activity android:name=".test.contentprovider.TestActivity">

        </activity>

        <provider
            android:name=".test.contentprovider.TestProvider"
            android:authorities="test_privoder"
            android:process=":privoder" />
上一篇下一篇

猜你喜欢

热点阅读