ContentProvider是android中提供对应不用应用间数据共享的方式,也就是可以进行进程间通信。作为进程间通信的工具,ContentProvider的底层实现是 Binder。可见Binder在安卓中的地位。
1、用法
ContentProvider的用法很简单,只需要继承ContentProvider然后实现它的六个抽象方法就行了。六个方法包括:onCreate、query、update、delete、insert和getType。其中onCreate是指ContentProvider的创建,一般初始化的工作在这里做。getType用来返回一个Uri请求所对应的MIME类型(媒体类型),比如图片、视频。如果用不到可以返回null或者"/"。根据Binder的工作原理,我们知道这六个方法运行在ContentProvider的进程中,除了onCreate由系统调用并运行在主线程里,其他五个方法均由外界回调并运行在Binder线程池中。
2、数据存储
ContentProvider主要以表格的形式来组织数据,并且可以包含多个表。除了表格的形式,ContentProvider还支持文件数据,比如图片、视频等。文件数据和表格数据的结构不同,因此处理这类数据时可以在ContentProvider中返回文件的句柄给外界从而让文件来访问ContentProvider中的文件信息。android系统中所提供的MediaStore功能就是文件类型的ContentProvider,虽然ContentProvider的底层数据看起来很像一个SQLite数据库,但是ContentProvider对底层的数据存储方式没有任何要求,我们既可以使用SQLite数据库,也可以使用普通的文件,甚至可以采用内存中的一个对象来进行数据的存储。
3、简单的示例,演示ContentProvider的工作流程
首先创建一个BookProvider类,它继承自ContentProvider并实现了抽象方法。
package com.example.administrator.myapplication.contentprovider;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import static android.content.ContentValues.TAG;
public class BookContentProvider extends ContentProvider {
@Override
public boolean onCreate() {
Log.d(TAG, "onCreate: " + Thread.currentThread().getName());
return false;
}
@Nullable
@Override
public Cursor query(@NonNull Uri uri, @Nullable String[] strings, @Nullable String s, @Nullable String[] strings1, @Nullable String s1) {
Log.d(TAG, "query: " + Thread.currentThread().getName());
return null;
}
@Nullable
@Override
public String getType(@NonNull Uri uri) {
Log.d(TAG, "getType: ");
return null;
}
@Nullable
@Override
public Uri insert(@NonNull Uri uri, @Nullable ContentValues contentValues) {
Log.d(TAG, "insert: ");
return null;
}
@Override
public int delete(@NonNull Uri uri, @Nullable String s, @Nullable String[] strings) {
Log.d(TAG, "delete: ");
return 0;
}
@Override
public int update(@NonNull Uri uri, @Nullable ContentValues contentValues, @Nullable String s, @Nullable String[] strings) {
Log.d(TAG, "update: ");
return 0;
}
}
接下来需要在AndroidManifest注册这个BookProvider,如下
<pre><code><provider
android:authorities="com.example.administrator.myapplication.book.provider"
android:name=".contentprovider.BookContentProvider"
android:permission="com.myapplication.PROVIDER"
android:process=":provider"/></pre></code>
其中authorities是ContentProvider的唯一标识,通过这个属性外部应用就能访问要BookProvider,因此authorities必须是唯一的,建议名字加上包名前缀。这里的BookProvider运行在独立的进程中( android:process=":provider")并给它添加了权限,外界想访问BookProvider的话必须声明com.myapplication.PROVIDER权限,其中权限还分为readPermission和writePermission分别是读权限和写权限。没有声明相应的权限外界应用调用BookProvider对应方法时会异常终止。
这里BookProvider运行在独立的进程中,所有在同一应用访问BookProvider的效果和外界访问效果是一样的。注意要声明对应的权限。
package com.example.administrator.myapplication;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Uri uri = Uri.parse("content://com.example.administrator.myapplication.book.provider");
getContentResolver().query(uri, null, null ,null,null);
getContentResolver().query(uri, null, null ,null,null);
getContentResolver().query(uri, null, null ,null,null);
}
}
打印结果如下:
07-03 21:26:46.281 4970-4970/? D/ContentValues: onCreate: 4970
07-03 21:26:46.287 4970-4990/? D/ContentValues: query: 4990
07-03 21:26:46.289 4970-4991/? D/ContentValues: query: 4991
07-03 21:26:46.291 4970-4990/? D/ContentValues: query: 4990
BookProvider的query方法被调用3次分别在不同线程中,这里queryinsert、update、delete方法都运行在Binder线程中,onCreate方法运行在主线程中,所以在onCreate方法里不能做耗时操作。
下面我们建一个数据库,让BookProvider能对外提供数据
DBOpenHelper.java
package com.example.administrator.myapplication.contentprovider;
import android.content.Context;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by Administrator on 2017/7/3/003.
*/
public class DBOpenHelper extends SQLiteOpenHelper {
public static final String DB_NAME = "book_provider.db";
public static final String BOOK_TABLE_NAME ="book";
public static final String USER_TABLE_NAME = "user";
private static final int DB_VERSION = 1;
public static final String CREATE_BOOK_TABLE = "CREATE TABLE IF NOT EXISTS" + BOOK_TABLE_NAME + "(_id INTEGER PRIMAYR KEY," + "name TEXT)";
public static final String CREATE_USER_TABLE = "CREATE TABLE IF NOT EXISTS" + USER_TABLE_NAME + "(_id INTEGER PRIMAYR KEY," + "name TEXT," + "SEX INT)";
public DBOpenHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
public DBOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version, DatabaseErrorHandler errorHandler) {
super(context, name, factory, version, errorHandler);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(CREATE_BOOK_TABLE);
sqLiteDatabase.execSQL(CREATE_USER_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
}
BookContentProvider.java
package com.example.administrator.myapplication.contentprovider;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import static android.content.ContentValues.TAG;
/**
* Created by Administrator on 2017/7/3/003.
*/
public class BookContentProvider extends ContentProvider {
private static final String AUTHORITY = "com.example.administrator.myapplication.book.provider";
public static final String BOOK_CONTENT_URI = "content://" + AUTHORITY + "/book";
public static final String USER_CONTENT_URI = "content://" + AUTHORITY + "/user";
public static final int BOOK_URI_CODE = 0;
public static final int USER_URI_CODE = 1;
private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
static {
uriMatcher.addURI(AUTHORITY, "book",0);
uriMatcher.addURI(AUTHORITY, "user",1);
}
private Context context;
private SQLiteDatabase db;
@Override
public boolean onCreate() {
Log.d(TAG, "onCreate: " + Thread.currentThread().getName());
context = getContext();
//建立数据库的耗时操作最好不要放在主线程中
initProviderData();
return false;
}
private void initProviderData(){
db = new DBOpenHelper(context).getWritableDatabase();
db.execSQL("delete from " + DBOpenHelper.BOOK_TABLE_NAME);
db.execSQL("delete from " + DBOpenHelper.USER_TABLE_NAME);
db.execSQL("insert into " + DBOpenHelper.BOOK_TABLE_NAME + " values(3, 'android');");
db.execSQL("insert into " + DBOpenHelper.BOOK_TABLE_NAME + " values(4, 'ios');");
db.execSQL("insert into " + DBOpenHelper.BOOK_TABLE_NAME + " values(5, 'windows');");
db.execSQL("insert into " + DBOpenHelper.USER_TABLE_NAME + " values(1, 'laura', 0);");
db.execSQL("insert into " + DBOpenHelper.USER_TABLE_NAME + " values(2, 'map', 1);");
}
@Nullable
@Override
public Cursor query(@NonNull Uri uri, @Nullable String[] strings, @Nullable String s, @Nullable String[] strings1, @Nullable String s1) {
Log.d(TAG, "query: " + Thread.currentThread().getName());
String tableName = getTableName(uri);
if (tableName == null) {
throw new IllegalArgumentException("UnSupported URI: " + uri);
}
return db.query(tableName, strings, s, strings1,null, s1,null);
}
@Nullable
@Override
public String getType(@NonNull Uri uri) {
Log.d(TAG, "getType: ");
return null;
}
@Nullable
@Override
public Uri insert(@NonNull Uri uri, @Nullable ContentValues contentValues) {
Log.d(TAG, "insert: ");
String tableName = getTableName(uri);
if (tableName == null) {
throw new IllegalArgumentException("UnSupported URI: " + uri);
}
db.insert(tableName, null, contentValues);
context.getContentResolver().notifyChange(uri, null);
return null;
}
@Override
public int delete(@NonNull Uri uri, @Nullable String s, @Nullable String[] strings) {
Log.d(TAG, "delete: ");
String tableName = getTableName(uri);
if (tableName == null) {
throw new IllegalArgumentException("UnSupported URI: " + uri);
}
int count = db.delete(tableName, s, strings);
if (count > 0) {
context.getContentResolver().notifyChange(uri, null);
}
return count;
}
@Override
public int update(@NonNull Uri uri, @Nullable ContentValues contentValues, @Nullable String s, @Nullable String[] strings) {
Log.d(TAG, "update: ");
String tableName = getTableName(uri);
if (tableName == null) {
throw new IllegalArgumentException("UnSupported URI: " + uri);
}
int row = db.update(tableName, contentValues,s, strings);
if (row > 0) {
context.getContentResolver().notifyChange(uri, null);
}
return row;
}
private String getTableName(Uri uri){
switch (uriMatcher.match(uri)){
case BOOK_URI_CODE:
return DBOpenHelper.BOOK_TABLE_NAME;
case USER_URI_CODE:
return DBOpenHelper.USER_TABLE_NAME;
}
return null;
}
}
```
MainActivity.java
package com.example.administrator.myapplication;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Uri uri = Uri.parse("content://com.example.administrator.myapplication.book.provider/book");
// getContentResolver().query(uri, null, null ,null,null);
// getContentResolver().query(uri, null, null ,null,null);
// getContentResolver().query(uri, null, null ,null,null);
Uri bookUri = Uri.parse("content://com.example.administrator.myapplication.book.provider/book");
ContentValues values = new ContentValues();
values.put("_id", 6);
values.put("name", "android开发艺术探索");
getContentResolver().insert(bookUri, values);
Cursor bookCursor = getContentResolver().query(bookUri, new String[]{"_id", "name"}, null, null, null);
while(bookCursor.moveToNext()){
Log.d(TAG, "_id: " + bookCursor.getString(0));
Log.d(TAG, "name: " + bookCursor.getString(1));
}
bookCursor.close();
}
}
MainActivity向book表中插入一条数据,并且查寻并打印出该条数据。需要注意的是query、update、insert、delete四个方法运行在不同的线程中,可能出现多线程并发访问,所以方法内部要做好多线程同步。本例中采用了Sqlite并且只有一个SQLiteDatabase连接,所以可以正确应对多线程的情况。因为sqlite内部对数据库的操作是有做同步处理的,但是如果是多个SQLiteDatabase对象操作数据库的话就无法保证线程同步,因为SQLiteDatabase对象之间无法进行线程同步。如果ContentProvider的底层数据集是一块内存的话,比如是List,那么就要对list的操作进行线程同步了,否则可能会引起并发错误。
ContentProvider除了支持增删改查的操作外还_支持自定义调用_,需要通过ContentResolver的Call方法和ContentProvider的Call方法来完成。此处就不作演示了。
参考:android开发艺术探索