1.ContentProvider概念讲解:
2.使用系统提供的ContentProvider
其实很多时候我们用到ContentProvider并不是自己暴露自己的数据,更多的时候通过 ContentResolver来读取其他应用的信息,最常用的莫过于读取系统APP,信息,联系人, 多媒体信息等!如果你想来调用这些ContentProvider就需要自行查阅相关的API资料了! 另外,不同的版本,可能对应着不同的URL!这里给出如何获取URL与对应的数据库表的字段, 这里以最常用的联系人为例,其他自行google~
①来到系统源码文件下:all-src.rar -> TeleponeProvider -> AndroidManifest.xml查找对应API
②打开模拟器的file exploer/data/data/com.android.providers.contacts/databases/contact2.db 导出后使用SQLite图形工具查看,三个核心的表:raw_contact表,data表,mimetypes表!
下面演示一些基本的操作示例:
1)简单的读取收件箱信息:
private void getMsgs(){
Uri uri = Uri.parse("content://sms/");
ContentResolver resolver = getContentResolver();
//获取的是哪些列的信息
Cursor cursor = resolver.query(uri, new String[]{"address","date","type","body"}, null, null, null);
while(cursor.moveToNext())
{
String address = cursor.getString(0);
String date = cursor.getString(1);
String type = cursor.getString(2);
String body = cursor.getString(3);
System.out.println("地址:" + address);
System.out.println("时间:" + date);
System.out.println("类型:" + type);
System.out.println("内容:" + body);
System.out.println("======================");
}
cursor.close();
}
别忘了,往AndroidManifest.xml加入读取收件箱的权限:
2)简单的读取手机联系人
private void getContacts(){
//①查询raw_contacts表获得联系人的id
ContentResolver resolver = getContentResolver();
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
//查询联系人数据
cursor = resolver.query(uri, null, null, null, null);
while(cursor.moveToNext())
{
//获取联系人姓名,手机号码
String cName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String cNum = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
System.out.println("姓名:" + cName);
System.out.println("号码:" + cNum);
System.out.println("======================");
}
cursor.close();
}
别忘了加读联系人的权限:
自定义ContentProvider
我们很少会自己来定义ContentProvider,因为我们很多时候都不希望自己应用的数据暴露给 其他应用,虽然这样,学习如何ContentProvider还是有必要的,多一种数据传输的方式,是吧~
这是之前画的一个流程图:
接下来我们就来一步步实现:
在开始之前我们先要创建一个数据库创建类(数据库内容后面会讲~):
DBOpenHelper.java
public class DBOpenHelper extends SQLiteOpenHelper {
final String CREATE_SQL = "CREATE TABLE test(_id INTEGER PRIMARY KEY AUTOINCREMENT,name)";
public DBOpenHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_SQL);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
Step 1:自定义ContentProvider类,实现onCreate(),getType(),根据需求重写对应的增删改查方法:
NameContentProvider.java
public class NameContentProvider extends ContentProvider {
//初始化一些常量
private static UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
private DBOpenHelper dbOpenHelper;
//为了方便直接使用UriMatcher,这里addURI,下面再调用Matcher进行匹配
//addURI(String authority, String path, int code)
//Add a URI to match, and the code to return when this URI is matched.
static{
matcher.addURI("com.jay.example.providers.myprovider", "test", 1);
}
@Override
public boolean onCreate() {
dbOpenHelper = new DBOpenHelper(this.getContext(), "test.db", null, 1);
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
return null;
}
@Override
public String getType(Uri uri) {
return null;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
//int code=matcher.match(uri);
//即matcher.addURI的int code
switch(matcher.match(uri))
{
//把数据库打开放到里面是想证明uri匹配完成
case 1:
SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
long rowId = db.insert("test", null, values);
if(rowId > 0)
{
//在前面已有的Uri后面追加ID
Uri nameUri = ContentUris.withAppendedId(uri, rowId);
//通知数据已经发生改变
getContext().getContentResolver().notifyChange(nameUri, null);
return nameUri;
}
}
return null;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
return 0;
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
return 0;
}
}
- UriMatcher.addURI(String authority, String path, int code)
Add a URI to match, and the code to return when this URI is matched. - int code=matcher.match(uri);
Step 2:AndroidManifest.xml中为ContentProvider进行注册:
好的,作为ContentProvider的部分就完成了!
Step 3 : 接下来,创建一个新的项目,我们来实现ContentResolver的部分,我们直接通过按钮点击插入一条数据:
MainActivity.java
public class MainActivity extends Activity {
private Button btninsert;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btninsert = (Button) findViewById(R.id.btninsert);
//读取contentprovider 数据
final ContentResolver resolver = this.getContentResolver();
btninsert.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
ContentValues values = new ContentValues();
values.put("name", "测试");
Uri uri = Uri.parse("content://com.jay.example.providers.myprovider/test");
resolver.insert(uri, values);
Toast.makeText(getApplicationContext(), "数据插入成功", Toast.LENGTH_SHORT).show();
}
});
}
}
4.通过ContentObserver监听ContentProvider的数据变化
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//[1]注册内容观察者
Uri uri = Uri.parse("content://com.jay.example.providers.myprovider");
getContentResolver().registerContentObserver(uri, true, new MyContentObserver(new Handler()));
}
//定义一个内容观察者
private class MyContentObserver extends ContentObserver{
public MyContentObserver(Handler handler) {
super(handler);
}
//当内容发送改变的时候调用
@Override
public void onChange(boolean selfChange) {
System.out.println("哈哈哈 数据库的内容发送了改变 ");
super.onChange(selfChange);
}
}
}