ContentProvider作用
ContentProvider中的URI
Authority:授权信息,用以区别不同的ContentProvider;
Path:表名,用以区分ContentProvider中不同的数据表;
Id:Id号,用以区别表中的不同数据;
代码示例
public class ProviderInfo {
static final String MULTI_PATH = "log";
static final String SINGLE_PATH = "log/#";
static final String AUTHORITY = "com.msy.log.provider";
public static final Uri CONTEN_URI = Uri.parse("content://" + AUTHORITY + "/" + MULTI_PATH);
}
实现ContentProvider
首先我们创建一个自己的PayLogProvider
继承ContentProvider
。默认该Provider需要实现如下六个方法,onCreate()
, query(Uri, String[], String, String[], String)
,insert(Uri, ContentValues)
, update(Uri, ContentValues, String, String[])
, delete(Uri, String, String[])
, getType(Uri)
代码示例
public class PayLogProvider extends ContentProvider {
private DBOpenHelper helper;
private static UriMatcher matcher;
private static final int MULTI_LOG = 1;
private static final int SINGLE_LOG = 2;
static {
matcher = new UriMatcher(UriMatcher.NO_MATCH);
matcher.addURI(ProviderInfo.AUTHORITY, ProviderInfo.MULTI_PATH,
MULTI_LOG);
matcher.addURI(ProviderInfo.AUTHORITY, ProviderInfo.SINGLE_PATH,
SINGLE_LOG);
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
// TODO Auto-generated method stub
String where = null;
switch (matcher.match(uri)) {
case MULTI_LOG:
where = selection;
break;
case SINGLE_LOG:
where = ProviderInfo.PayLog._ID + "=" + uri.getLastPathSegment();
if (selection != null)
where += " and (" + selection + ")";
break;
default:
throw new IllegalArgumentException("δ֪uri : " + uri);
}
SQLiteDatabase db = helper.getWritableDatabase();
int count = db.delete(DBOpenHelper.TBL_NAME, where, selectionArgs);
db.close();
return count;
}
@Override
public String getType(Uri uri) {
// TODO Auto-generated method stub
return null;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
// TODO Auto-generated method stub
if (matcher.match(uri) != MULTI_LOG) {
throw new IllegalArgumentException("δ֪uri : " + uri);
}
SQLiteDatabase db = helper.getWritableDatabase();
long rowId = db.insert(DBOpenHelper.TBL_NAME, null, values);
db.close();
if (rowId > 0)
return ContentUris.withAppendedId(uri, rowId);
return null;
}
@Override
public boolean onCreate() {
// TODO Auto-generated method stub
helper = new DBOpenHelper(getContext());
if (helper == null)
return false;
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
// TODO Auto-generated method stub
String where = null;
switch (matcher.match(uri)) {
case MULTI_LOG:
where = selection;
break;
case SINGLE_LOG:
where = ProviderInfo.PayLog._ID + "=" + uri.getPathSegments();
if (selection != null)
where += " and (" + selection + ")";
break;
default:
throw new IllegalArgumentException("δ֪uri : " + uri);
}
SQLiteDatabase db = helper.getReadableDatabase();
Cursor c = db.query(DBOpenHelper.TBL_NAME, projection, where,
selectionArgs, null, null, sortOrder);
return c;
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
// TODO Auto-generated method stub
String where = null;
switch (matcher.match(uri)) {
case MULTI_LOG:
where = selection;
break;
case SINGLE_LOG:
where = ProviderInfo.PayLog._ID + "=" + uri.getPathSegments();
if (selection != null)
where += " and (" + selection + ")";
break;
default:
throw new IllegalArgumentException("δ֪uri : " + uri);
}
SQLiteDatabase db = helper.getWritableDatabase();
int count = db.update(DBOpenHelper.TBL_NAME, values, where,
selectionArgs);
db.close();
return count;
}
}
注册ContentProvider
因为ContentProvider作为四大组件之一,所以还需要在AndroidManifest.xml中注册一下。属于静态注册,也就是说应用安装在手机上,就已经注册成功了,在其它应用当中,就可以使用该Provider了
<provider
android:name="google.mvp.contentprovider.PayLogProvider"
android:authorities="com.msy.log.provider"
android:exported="true"/> //必须加,不能其它应用不能使用
android:exported
设置此provider是否可以被其他应用使用。
android:readPermission
该provider的读权限的标识
android:writePermission
该provider的写权限标识
android:permission
provider读写权限标识
android:grantUriPermissions
临时权限标识,true时,意味着该provider下所有数据均可被临时使用;false时,则反之,但可以通过设置<grant-uri-permission>
标签来指定哪些路径可以被临时使用。举个例子,比如你开发了一个邮箱应用,其中含有附件需要第三方应用打开,但第三方应用又没有向你申请该附件的读权限,但如果你设置了此标签,则可以在start第三方应用时,传入FLAG_GRANT_READ_URI_PERMISSION
或FLAG_GRANT_WRITE_URI_PERMISSION
来让第三方应用临时具有读写该数据的权限。
数据共享(主要是其它应用中如何使用)
添加数据
String Path = "content://com.msy.log.provider/log";
Uri uri = Uri.parse(Path);
ContentResolver cr = getContentResolver();
// 插入
ContentValues values = new ContentValues();
values.put(ProviderInfo.PayLog.APP_NAME, "来自NewApi");
values.put(ProviderInfo.PayLog.TAG, "error");
values.put(ProviderInfo.PayLog.MSG, "getConfig(2d:ffmpeg.h264.decoder, ConfigCommonOutputCrop(0x700000f)) ERROR: Undefined(0x80001001)");
values.put(ProviderInfo.PayLog.DATE, System.currentTimeMillis() / 1000);
cr.insert(uri, values);
//添加多条数据
ContentValues[] arrayValues = new ContentValues[10]; //实例化每一个ContentValues...
int count = resolver.bulkInsert(uri, arrayValues );
删除数据
Uri uri = Uri.parse(Path + "/" +"2");
int result = cr.delete(uri, null, null);
// 通过selection语句删除多条数据
String selection = _ID + ">4";
int result = cr.delete(uri, selection, null);
//api提供参数
cr.delete( Uri url, String where, String[] selectionArgs)
url--->访问的地址
where--->select条件语句 || "APP_NAME=?"
selectionArgs--->条件值 || new String[]{"来自NewApi"}
更新数据
ContentValues values = new ContentValues();
values.put(ProviderInfo.PayLog.APP_NAME, "来自NewApi update");
values.put(ProviderInfo.PayLog.TAG, "error update");
Uri uri = Uri.parse(Path + "/" + "7");
int result = resolver.update(uri, values, null, null);
//api提供参数
cr.update(Uri uri, ContentValues values,String where, String[] selectionArgs)
values--->需要修改的键值对
查询数据
ContentResolver cr = context.getContentResolver();
// 查询
Cursor c = cr.query(uri, null, ProviderInfo.PayLog.APP_NAME + "=?", new String[]{app_name}, null);
if (c != null) {
List<LogMsg> logMsgs =new ArrayList<LogMsg>();
while (c.moveToNext()) {
logMsgs.add(createLogMsg(c));
}
c.close();
}
//api提供参数
cr.query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)
cr.query( Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder, CancellationSignal cancellationSignal)
projection--->查询结果需要的字段
cancellationSignal--->
监听数据
如果ContentProvider的访问者需要知道ContentProvider中的数据发生变化,可以在ContentProvider 发生数据变化时调用
getContentResolver().notifyChange(uri, null)来通知注册在此URI上的访问者
代码示例
cr.insert(uri, values);
cr.notifyChange(uri, null);
如果ContentProvider的访问者需要得到数据变化通知,必须使用ContentObserver对数据(数据采用uri描述)进行监听,当监听到数据变化通知时,
系统就会调用ContentObserver的onChange()方法:
代码示例
{
void initProvider() {
//true表示只要发出通知的Uri以方法第一个参数开头都能被监听到,否侧监听uri必须与发出通知的uri完全匹配才能被监听到
getContentResolver().registerContentObserver(Uri.parse("content://com.msy.log.provider/log"), true, new PersonObserver(new Handler()));
}
public class PersonObserver extends ContentObserver {
public PersonObserver(Handler handler) {
super(handler);
}
public void onChange(boolean selfChange) {
//此处可以进行相应的业务处理
}
}
}