A程序中继承ContentProvider的类:需在AndroidManifest.xml中注册
<provider android:name="MyContentProvider"
android:authorities="cn.mrzhu.test24"></provider>
android:authorities="cn.mrzhu.test24"为程序B访问提供uri,只有通过此uri程序B才能访问到A程序中的数据
package cn.mrzhu.test24;
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;
public class MyContentProvider extends ContentProvider{
//Uri过滤器,通过此过滤器可以取出uri最后一个字段
UriMatcher um;
static final String AUTHORITY = "cn.mrzhu.test24";
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
return 0;
}
@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
return null;
}
@Override
public boolean onCreate() {
//初始化过滤器
um = new UriMatcher(UriMatcher.NO_MATCH);
//添加过滤内容,从其他程序传来的uri通过过滤器之后若其字段为test1,则其code为1
um.addURI(AUTHORITY, "test1", 1);
um.addURI(AUTHORITY, "test2", 2);
return false;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
SQLiteDatabase db = getContext().openOrCreateDatabase("test24.db", Context.MODE_PRIVATE, null);
Cursor cs = null;
//将uri过滤,取得返回值
int code = um.match(uri);
//根据不同的返回值执行不同的查询语句
switch(code){
case 1:
cs = db.rawQuery("select * from test1", null);
break;
case 2:
cs = db.rawQuery("select * from test2", null);
break;
}
//执行查询语句后将结果集返回
return cs;
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
// TODO Auto-generated method stub
return 0;
}
}