实现ContentProvider:
1.继承抽象类ContentProvider 实现 一系列对于数据的增删改查方法
2.在AndroidMainfest.xml文件中完成注册:
<provider
android:name = "com.******************"
android:authorities="com.-********************">
</provider>//authorities属性是全局唯一的
Uri 通用资源标识符
UriMatcher类 解析Uri
- UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
- matcher.addURI(“********”,“******”,*);
- mather.match(uri)
- 首先与找通过addURI()方法添加进来的Uri匹配
- 匹配成功则返回code值,否则返回-1
ContentResolver:
- 使用ContentResolver操作ContentProvider中的数据:
- 当外部应用需要对 ContentProvider中的数据进行增加、删除、修改和查询时,可用ContentResolver完成。
- 使用Activity提供的getContentResolver()方法获取ContentResolver对象
- ContentResolver类提供了与ContentProvider类相同签名的四个方法
example:-----------------------------------------------------------------------------------------------------------------
//在使用Contacts 要导入import android.provider.ContactsContract.Contacts;
//使用Phone 要导入import android.provider.ContactsContract.CommonDataKinds.Phone;
setContentView(R.layout.activity_main);
ContentResolver cr = getContentResolver();
Cursor c = cr.query(Contacts.CONTENT_URI, new String[]{Contacts._ID,Contacts.DISPLAY_NAME}, null, null, null);
if(c!=null)
{
while(c.moveToNext())
{
int id = c.getInt(c.getColumnIndex("_id"));
Log.i("info","_id:"+id);
String text = c.getString(c.getColumnIndex("display_name"));
Log.i("info","name:"+text);
Cursor c1 = cr.query(Phone.CONTENT_URI, new String[]{Phone.NUMBER,Phone.TYPE}, Phone.CONTACT_ID+"="+id, null, null);
if(c!=null)
while(c1.moveToNext())
{
int type= c1.getInt(c1.getColumnIndex(Phone.TYPE));
if(type==Phone.TYPE_HOME){
Log.i("info", c1.getString(c1.getColumnIndex(Phone.NUMBER)));
}
if(type==Phone.TYPE_MOBILE){
Log.i("info", c1.getString(c1.getColumnIndex(Phone.NUMBER)));
}
}
c1.close();
}
}
c.close();
}