首先在需要提供内容提供者的应用中添加内容提供者的代码
package com.example.sqllite;
import com.example.sqllite.servise.DBOpenHelp;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
public class personProvider extends ContentProvider {
private DBOpenHelp dbOpenHelp;
//Uri匹配器,检验是否匹配
private static final UriMatcher MATCHER=new UriMatcher(UriMatcher.NO_MATCH);
private static final int SUCCESS=1;
static {
MATCHER.addURI("com.contentProvide.providers.personProvides", "person", SUCCESS);
}
@Override
public boolean onCreate() {
dbOpenHelp=new DBOpenHelp(this.getContext());
return true;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
// TODO Auto-generated method stub
return 0;
}
@Override
public String getType(Uri uri) {
// TODO Auto-generated method stub
return null;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
SQLiteDatabase db=dbOpenHelp.getWritableDatabase();
switch (MATCHER.match(uri)) {
case SUCCESS:
long rowID=db.insert("person", "name", values);
//Uri insertUri=Uri.parse("content://com.contentProvide.providers.personProvides/person/"+rowID);
Uri insertUri=ContentUris.withAppendedId(uri, rowID);
db.close();
return insertUri;
default:
throw new IllegalArgumentException("未知的Uir");
}
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
// TODO Auto-generated method stub
return null;
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
// TODO Auto-generated method stub
return 0;
}
}
2.在原应用中添加配置项
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sqllite"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.sqllite.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- 添加内容提供者的配置 -->
<provider android:name=".personProvider" android:authorities="com.contentProvide.providers.personProvides"/>
</application>
</manifest>
3.新应用中进行访问
Uri uri=Uri.parse("content://com.contentProvide.providers.personProvides/person");
//访问contentProvider的帮助类
ContentResolver resolver=this.getApplicationContext().getContentResolver();
ContentValues values=new ContentValues();
values.put("name", "hahha");
values.put("age", 33);
values.put("amount", "123");
resolver.insert(uri, values);