ContentProvider跨进程共享数据

借用ContentResolver类访问ContentProvider中共享的数据。通过getContentResolver()方法获得该类的实例。

ContentResolver中的方法:insert()、updata()、delete()、query()

ContentResolver中增删改查方法传入的是Uri(权限、路径):content://com.examlple.app.provider/table1

获得Uri字符串之后,需要将其解析成Uri对象才能作为参数传入,调用Uri.parse()解析Uri字符。

查:

1 Uri uri = Uri.parse("content://com.example.app.table1")
2 Cursor cursor = getContentResolver().query(uri,projection,selection,selectionArgs,sortOrder);
3 if(cursor != null){
4   while(cursor.moveToNext()){
5     String column1 = cursor.getString(cursor.getColumnIndex("column1"));
6     Int column2 = cursor.getInt(cursor.getColumnIndex("column2"));
7   }
8   cursor.close();
Uri uri = Uri.parse("content://com.example.app.table1")
Cursor cursor = getContentResolver().query(uri,projection,selection,selectionArgs,sortOrder);
if(cursor != null){
  while(cursor.moveToNext()){
    String column1 = cursor.getString(cursor.getColumnIndex("column1"));
    Int column2 = cursor.getInt(cursor.getColumnIndex("column2"));
  }
  cursor.close();
}

增:

ContentValues values = new ContentValues();
values.put("column1","text");
values.put("column2",1);
getContentResolver().insert(uri,values);

改;

ContentValues values = new ContentValues();
values.put("column1","");
getContentResolver().updata(uri,values,"column1=? and column2 =?",new String[]{"text","1"});

删:

getContentResolver().delete(uri,"column2=?",new String[]{"1"});

自定义ContentProvider

  重写6个抽象方法:onCreate()、query()、insert()、updata()、delete()、getType()

  匹配Uri:借助UriMatches类中addURI(权限、路径、自定义代码)传递期望匹配的URI格式,然后调用match()方法进行匹配,从而判断出调用方期望访问的是哪张表中的数据。

  getType()方法是每个ContentProvider都必须提供的一个方法,用于获取Uri对象所对应的MIME类型。

  MIME类型条件:(1)必须以vnd开头

          (2)如果是Uri路径结尾,则vnd.android.cursor.dir/vnd.com.example.app.provider.table1

          (3)如果是id结尾,则vnd.android.cursor.item/vnd.com.example.app.provider.table2

原文地址:https://www.cnblogs.com/yl-saber/p/6101777.html