赞
踩
ContentProvider做为跨进程通信的手段之一,一般用于暴露本应用数据给到外部应用,提供一套标准的数据访问模型,常常与本地数据库联合使用
<provider
android:name="包名.ProductProvider"
android:authorities="包名.ProductProvider"
android:enabled="true"
android:exported="true"
android:multiprocess="true" />
public class ProductProvider extends ContentProvider { private static final String MAUTHORITIESNAME="包名.ProductProvider"; private static UriMatcher matcher=new UriMatcher(UriMatcher.NO_MATCH); private static final int PRODUCT=1; //构建URI static { matcher.addURI(MAUTHORITIESNAME,"product",PRODUCT); } @Override public boolean onCreate() { // Log.i("testProductProvider","onCreate"); ProductDatabase.getInstance(getContext()); return true; } @Nullable @Override public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) { Log.i("testProductProvider","query"); int match=matcher.match(uri); Log.i("testProductProvider","query match:"+match); switch (match){ case PRODUCT: return ProductDatabase.getInstance(getContext()).getProductDao().getProduct(); } return null; } @Nullable @Override public String getType(@NonNull Uri uri) { int match=matcher.match(uri); switch (match){ case PRODUCT: return "vnd.android.cursor.dir/product"; } return null; } @Nullable @Override public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) { return null; } @Override public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) { return 0; } @Override public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) { return 0; } }
<queries>
<package android:name="要访问的包名"/>
</queries>
4.使用URI查询
Uri uri=Uri.parse("content://包名.类名/路径");
Cursor cursor=getContentResolver().query(uri,null,null,null,null);
//打印结果
while (cursor.moveToNext()){
Log.i("testCourse","id:"+cursor.getLong(0)
+" content:"+cursor.getString(1)
+" cover:"+cursor.getString(2)
+" type:"+cursor.getInt(3));
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。