一、内容提供者的创建(ContentProvider)
- URI的组成:Uri由scheme、authorities、path三部分组成。scheme是标准前缀,表明数据被ContentProvider控制,不会被修改;authorities主要用来区分不同的应用程序,为避免冲突,会采用程序包名的方式进行命名;path部分代表资源或数据,当访问者操纵不同的数据时,此部分可以动态改变。
Uri:content://cn.itcast.mycontentprovider/person
内容提供者的创建:
public class MyContentProvider extends ContentProvider{//继承ContentProvider抽象类public MyContentProvider(){}public int delete(Uri uri, String selection, String[] selectionArgs){}public String getType(Uri uri){}//用于返回指定Uri代表的数据的MIME类型,//例如Windows系统中txt文件和.jpg文件就是两种不同的MIME类型public Uri insert(Uri uri, ContentValues values){}public boolean onCreate(){//内容提供者创建时调用return false;}public Cursor query(Uri uri, String[] projection, String selection,String[] selectionArgs, String sortOrder){}public int update(Uri uri, ContentValues values, String selection,String[] selectionArgs){}}
内容提供者创建完成后自动在AndroidManifest.xml中对内容提供者进行注册。
<providerandriod:name".MyContentProvider"andriod:authorities="cn.itcast.mycontentprovider"andriod:enabled="true"andriod:exported="true"></provider>
二、内容提供者的使用(ContentResolver)
应用程序通过ContentProvider共享数据,通过ContentResolver对共享的数据进行操作。
//1.获取相应操作的UriUri uri = Uri.parse("content://cn.itcast.mycontentprovider/person");//将字符串转化为Uri对象//2.获取到ContentResolver对象ContentResolver resolver = context.getContentResolver();//3.通过ContentResolver对象查询数据Cursor cursor = resolver.query(uri,new String[] {"address", "data", "type", "body", },null, null, null );while(Cursor.moveToNext()){String address = cursor.getString(0);long date = cursor.getLong(1);int type = cursor.getInt(2);String body = cursor.getString(3);}cursor.close();//别忘关闭,否则会内存泄漏
UriMatcher的常用方法(重要)
该辅助工具类用于匹配Uripublic UriMatcher(int code);创建UriMatcher对象时调用,参数使用UriMatcher.NO_MATCH表示路径不满足条件返回-1public addURI(String authority, String path, int code);
添加一组匹配规则,authority即Uri的authorities部分,path即Uri的path部分,code即Uri匹配后返回的匹配码
public int match(Uri uri);
匹配Uri,与addURI()方法相对应,匹配成功则返回addURI()方法中传入的参数code的值
三、内容观察者的使用(ContentObserver)
通过ContentObserver实时监听ContentProvider共享的数据是否发生变化。
