假设我们的contentProvider名叫PathRecordingService, 这里在AndroidManifest.xml中可以看到
<provider
android:name="edu.njit.trackmypath.db.DataProvider"
android:authorities="edu.njit.trackmypath"
android:exported="true"/>
在DAO类,定义Uri CONTENT_URI: content://edu.njit.trackmypath/pathpoints, 这是要监听的Uri对应是table pathpoints,当然Uri和table也可以不一致。还有定义
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.njit.pathpoint";
public static final String CONTENT_ITEMTYPE = "vnd.android.cursor.item/vnd.njit.pathpoint";
在ContentProvider中,定义Uri
public static final String AUTHORITY = "edu.njit.trackmypath";
private static final int PATHPOINTS_TABLE_ID = 1;
private static final UriMatcher uriMatcher;
static {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(AUTHORITY, PathPointsTable.TABLE_NAME,
PATHPOINTS_TABLE_ID);
}
public String getType(Uri uri) {
switch (uriMatcher.match(uri))
{
case PATHPOINTS_TABLE_ID:
return PathPointsTable.CONTENT_TYPE;
default:
throw new IllegalArgumentException("Error Uri: " + uri);
}
}
这里PATHPOINTS_TABLE_ID只是一个Uri的整数代号,所以在这里CONTENT_URI就返回PathPointsTable.CONTENT_TYPE对应DAO中是vnd.android.cursor.dir。vnd.android.cursor.dir和vnd.android.cursor.item是Android中两种Uri解释方式,dir是全表变化监听,而item是监听某Row的变化。如果要监听某row,如下:
uriMatcher.addURI(AUTHORITY, “pathpoints/#”,2)
返回应选CONTENT_ITEMTYPE, #代表数字
这样就可以监听某行变化,如content://edu.njit.trackmypath/pathpoints/28
而监听变化的实现是在ContentProvider中
@Override
public Uri insert(Uri uri, ContentValues values) {
long id = db.insert(PathPointsTable.TABLE_NAME, PathPointsTable._ID, values);
if(id < 0)
throw new SQLiteException("Unable to insert " + values + " for " + uri);
Uri newUri = ContentUris.withAppendedId(uri, id);
Log.d(TAG, "new URI:"+newUri);
resolver.notifyChange(newUri, null);
return newUri;
}
newUri是content://edu.njit.trackmypath/pathpoints/28,notifyChange就会通知observer
context.getContentResolver().registerContentObserver(uri, true, observer);
Ref:
http://blog.csdn.net/luoshengyang/article/details/6950440
http://blog.csdn.net/luoshengyang/article/details/6985171
No comments:
Post a Comment