//在DB應用的基礎上實現監聽內容提供者的資料變化//1 在DB應用的主介面添加一個按鈕,當點擊按鈕的時候,往內容提供者中添加一條資料 button =(Button) findViewById(R.id.button); button.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View view) {ContentResolver resolver=getContentResolver();ContentValues values=new ContentValues();values.put("name", "rew");values.put("phone", "888");values.put("amount", 5454);Uri uri=Uri.parse("content://cn.companyname.contentproviders.personcontentprovider/person");resolver.insert(uri, values); }}); //2 在內容提供者的insert()和update()和delete()方法的return語句前中都添加一條語句//getContext().getContentResolver().notifyChange(uri, null)用於向外通知數據已發生變化//如insert()方法:public Uri insert(Uri uri, ContentValues values) {SQLiteDatabase db=dbOpenHelper.getWritableDatabase();switch (URI_MATCHER.match(uri)) {case PERSONS: long rowid=db.insert("person", "name", values); getContext().getContentResolver().notifyChange(uri, null);//向外通知數據已發生變化 return ContentUris.withAppendedId(uri, rowid);default:throw new IllegalArgumentException("unknown uri"+uri.toString());}}//3 建立立一個應用ListenDB,實現監聽public class ListenDBActivity extends Activity {private final static String TAG="TTT";@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);Uri uri = Uri.parse("content://cn.companyname.contentproviders.personcontentprovider/person");this.getContentResolver().registerContentObserver(uri, true,new DBContentObserver(new Handler()));}private final class DBContentObserver extends ContentObserver {public DBContentObserver(Handler handler) {super(handler);}@Overridepublic void onChange(boolean selfChange) {//監聽內容提供者的資料變化ContentResolver resolver=getContentResolver();Uri uri=Uri.parse("content://cn.companyname.contentproviders.personcontentprovider/person");//即可擷取最新的一條資料.小技巧Cursor cursor= resolver.query(uri, null, null, null, "personid desc limit 1");while(cursor.moveToNext()){int personid=cursor.getInt(cursor.getColumnIndex("personid"));Log.i(TAG, ""+personid);}cursor.close();}}}//(1)this.getContentResolver().registerContentObserver(uri, true,new DBContentObserver(new Handler()));註冊監聽器//(2)重寫public void onChange(boolean selfChange)方法,當資料發生變化時便及時知道.