监听ContentProvider中的数据的变更

监听ContentProvider中的数据的变化
当两个应用程序A,B同时放问ContentProvider时,当A应用更新了数据库中的数据时,如何让B应用也能自动的监听到ContentProvider的变化,并且获得更新的数据呢?

下面是B的应用的activity
public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Uri uri = Uri.parse("content://cn.itcast.providers.personprovider/person");
        getContentResolver().registerContentObserver(uri, true, new PersonProviderObServer(new Handler()));
    }
    
    private final class PersonProviderObServer extends ContentObserver{

		public PersonProviderObServer(Handler handler) {
			super(handler);
		}

		@Override
		public void onChange(boolean selfChange) {
			Uri uri = Uri.parse("content://cn.itcast.providers.personprovider/person");
			ContentResolver contentResolver = getContentResolver();
			// select * from person order by personid desc limit 1
			Cursor cursor = contentResolver.query(uri, null, null, null, "personid desc limit 1");
			if(cursor.moveToFirst()){
				int personid = cursor.getInt(cursor.getColumnIndex("personid"));
				String name = cursor.getString(cursor.getColumnIndex("name"));
				String phone = cursor.getString(cursor.getColumnIndex("phone"));
				int amount = cursor.getInt(cursor.getColumnIndex("amount"));
				Log.i("MainActivity", "id="+ personid+ ",name="+ name+ ",phone="+ phone+ ",amount="+ amount);
			}
		}
    }
}



注:在A应用更新完数据之后,应该主动通知B应用,使用如下代码:
getContext().getContentResolver().notifyChange(uri, null);