红色部分较重要的
private static final int STUDENTS = 1; private static final int STUDENT = 2; private static final String TAG = "StudentProvider"; private static UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH); private DBOpenHelper dbOpenHelper; static{ matcher.addURI("com.itpc.dbtest04.providers.studentprovider", "student", STUDENTS); matcher.addURI("com.itpc.dbtest04.providers.studentprovider", "student/#", STUDENT); } @Override public boolean onCreate() { dbOpenHelper = new DBOpenHelper(getContext()); return false; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); switch (matcher.match(uri)) { case STUDENTS: Log.i(TAG, "STUDENTS"); return db.query("student", null, null, null, null, null, "id asc"); case STUDENT: Long id = ContentUris.parseId(uri); String where = "id = "+id; if(selection != null && !"".equals(selection.trim())){ where += " and " + selection; } Log.i(TAG, "STUDENT"); return db.query("student", null, where, selectionArgs, null, null, "id asc"); default: throw new IllegalArgumentException("Unknow Uri:"+uri); } }
<provider android:name=".StudentProvider" android:authorities="com.itpc.dbtest04.providers.studentprovider" />
ContentResolver resolver = getContext().getContentResolver(); Uri uri = Uri.parse("content://com.itpc.dbtest04.providers.studentprovider/student/2"); Cursor cursor = resolver.query(uri, null, null, null, null);
==========================
从C应用往A应用添加一条记录,
用B应用来获得A应用数据的变化
A应用
@Override public Uri insert(Uri uri, ContentValues values) { SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); switch (matcher.match(uri)) { case STUDENTS: db.insert("student", null, values); //监听数据变化 getContext().getContentResolver().notifyChange(uri, null); Log.i(TAG, "保存成功"); break; default: throw new IllegalArgumentException("Unknow uri:"+uri); } return null; }
(B)监听的应用
Uri uri = Uri.parse("content://com.itpc.providers.studentprovider/student"); this.getContentResolver().registerContentObserver(uri, true, new StudentContentObserver(new Handler())); public final class StudentContentObserver extends ContentObserver{ public StudentContentObserver(Handler handler) { super(handler); } @Override public void onChange(boolean selfChange) { Uri uri = Uri.parse("content://com.itpc.providers.studentprovider/student"); ContentResolver resolver = getApplicationContext().getContentResolver(); Cursor cursor = resolver.query(uri, null, null, null, "id desc limit 1"); if(cursor.moveToFirst()){ String name = cursor.getString(cursor.getColumnIndex("name")); Log.i(TAG, "其他应用:"+name); } } }
C应用代码省略