详解"/>
ContentProvider 详解
一、定义 ContentProvider 主要用户不同进程之间的数据共享. 二、如何构建 1、首先建立继承与ContentProvider的子类并实现他 oncreate、query、getType、insert、delete、update方法 2、在manifest中生命<provider>节点 格式如下: <provider android:name="XX" android:authorites="xxx" android:permission="xxx" android:process=":xx" /> 其中android:permission 值的是 如果要使用 必须在manifest声明这个权限 3、建立数据访问类、用于contentprovider调用 4、建立UriMather 来匹配他们的uri 示例如下: static{ uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); uriMatcher.addURI(AUTHORITY,PATH,1);uriMatcher.addURI(AUTHORITY,PATH+ "/#",2);
uriMatcher.addURI(AUTHORITY,PATH+"/#/#", 3);
}
AUTHORITY 表示访问名称和manifest中的一致、PATH表示他的子路径 具体用法见后面5、实现各个方法oncreate、query、getType、insert、delete、update 其中oncreate 在主线程中所以必须轻量级,其他在子线程中;示例如下@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
int count = 0;
int num = uriMatcher.match(uri);
if(num == 1){//对应uriMatcher.addURI(AUTHORITY,PATH,1);
count = db.update(EVENTS_TABLE, values, selection, selectionArgs);
}else if(num == 2){//对应uriMatcher.addURI(AUTHORITY,PATH+ "/#",2);
count = db.update(EVENTS_TABLE, values, ID + " = " + uri.getPathSegments().get(1) + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""), selectionArgs);
}else{
throw new IllegalArgumentException(
"Unknown URI " + uri);
}//通知他所以的监听者
getContext().getContentResolver().notifyChange(uri, null);
return count;
}三、如何使用调用conext.getContentResolver().具体方法()【如:query、insert、delete、update】并返回cursor
更多推荐
ContentProvider 详解
发布评论