一、跨进程访问共享数据
Android应用程序可以使用文件或Sqlite数据库来存储数据。Content Provider提供了一种在多个应用程序之间数据共享的方式 ,其存在目的就是为了向其他应用程序共享数据和允许其他应用程序对数据进行增删改查工作。
Android本身也提供了很多Content Provider,例如音频、视频、联系人信息等。我们可以通过这些Content Provider(内容提供者)获得相关信息的列表。这些列表数据将以Cursor对象返回。
首先需要获得Content Resolver对象。该对象需要使用Context.getContentResolver()方法获得,代码如下:
ContentResolver resolver = getContentResolver();
通过resolver对象可调用insert、delete、update、query方法进行数据操作,查询系统联系人信息数据的代码如下:
Cursor cursor = resolver.query(Contacts.CONTENT_URI, null, null, null, null);
while (cursor.moveToNext()) {
Map<String, String> contactMap = new HashMap<String,String>();
int contactId = cursor.getInt(cursor.getColumnIndex(Contacts._ID));
String contactName = cursor.getString(cursor.getColumnIndex(Contacts.DISPLAY_NAME));
Cursor phones = resolver.query(Phone.CONTENT_URI,null,
Phone.CONTACT_ID + " = "+contactId, null, null);
String phoneNum = null;
while (phones.moveToNext()) {
phoneNum = phones.getString(phones.getColumnIndex(Phone.NUMBER));
}
phones.close();
contactMap.put("contactName", contactName);
contactMap.put("phoneNum", phoneNum);
contactData.add(contactMap);
}
cursor.close();
二、在应用中创建内容提供者(Content Provider)
1、编写一个继承android.content.ContentProvider抽象类的实现类。在该类中需实现onCreate、insert、delete、update、query方法,上边ContentResolver对象调用的增删改查方法就与之对应。所以要在这些实现方法中实现对数据库中数据的操作。
2、在AndroidManifest.xml文件中配置Content Provider。代码如下:
<provider
android:name=".MyContentProvider"
android:authorities="com.sarnasea.interprocess.mycontentprovider"/>
想要保证Content Provider的唯一性,需要指定这个内容提供者的URI,以及这个Content Provider对应的类。URL的完整格式如下:
content://com.sarnasea.interprocess.mycontentprovider/words/1
其中content://为固定前缀;中间蓝色部分为Content Provider的唯一标识,使用对应内容提供者类的完整类名;绿色部分为URL的路径,是自定义的;黄色部分为需要传递的值,可省略。
3、在实现类中的增删改查方法中可以对文件数据或数据库进行增删改查操作,示例代码如下:
public class MyContentProvider extends ContentProvider{
private static UriMatcher uriMatcher;
private static final String AUTHORITY = "com.sarnasea.interprocess.mycontentprovider";
private static final int SINGLE_WORD = 1;
public static final String DATABASE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/dictionary";
public static final String DATABASE_FILENAME = "dictionary.db";
private SQLiteDatabase database;
/**
* 静态代码块中添加访问ContentProvider的Uri
*/
static{
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(AUTHORITY, "words", SINGLE_WORD);
}
@Override
public boolean onCreate(){
File dbFile = new File(DATABASE_PATH, DATABASE_FILENAME);
database = SQLiteDatabase.openOrCreateDatabase(dbFile, null);
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder){
Cursor cursor = null;
switch (uriMatcher.match(uri)) {
case SINGLE_WORD:
// 查找指定的单词
cursor = database.query("t_words", projection, selection,
selectionArgs, null, null, sortOrder);
break;
default:
throw new IllegalArgumentException("<" + uri + ">格式不正确.");
}
return cursor;
}
....
}
以上进行了查询操作,增删改与其类似。