新建Aapp工程,向主页面添加一个按钮
public void insert(View v) { Uri uri = Uri .parse("content://cn.leigo.providers.personprovider/person"); ContentResolver resolver = this.getContentResolver(); ContentValues values = new ContentValues(); values.put("name", "A-App"); values.put("phone", "18800000000"); values.put("amount", 12000); resolver.insert(uri, values); }
在db工程的insert方法中,
@Override public Uri insert(Uri uri, ContentValues values) { SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); switch (MATCHER.match(uri)) { case PERSONS: long rowid = db.insert("person", "name", values); // 主键值 // content://cn.leigo.providers.personprovider/person/10 // Uri insertUri = // Uri.parse("content://cn.leigo.providers.personprovider/person/"+ // rowid); Uri insertUri = ContentUris.withAppendedId(uri, rowid); //发出数据变化通知 this.getContext().getContentResolver().notifyChange(uri, null); return insertUri; default: throw new IllegalArgumentException("this is Unknow Uri:" + uri); } }
新建Bapp工程监听Aapp向Person表中添加数据时发生的变化
package cn.leigo.bapp; import android.app.Activity; import android.database.ContentObserver; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.util.Log; public class MainActivity extends Activity { 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://cn.leigo.providers.personprovider/person"); this.getContentResolver().registerContentObserver(uri, true, new Observer(new Handler())); } private class Observer extends ContentObserver { public Observer(Handler handler) { super(handler); } @Override public void onChange(boolean selfChange) { Uri uri = Uri .parse("content://cn.leigo.providers.personprovider/person"); Cursor cursor = getApplicationContext().getContentResolver().query(uri, null, null, null, "personid desc limit 1"); if (cursor.moveToFirst()) { String name = cursor.getString(cursor.getColumnIndex("name")); Log.i(TAG, name); } } } }