监听ContentProvider内容改变

在开发ContentProvider的时候,不管操作增删改哪个方法,就会调用getContentResolver().notifyChange(uri,null);

在监听其数据改变,则需要ContentObserver.

public class MainActivity extends ActionBarActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		getContentResolver().registerContentObserver(Uri.parse("content://sms"),
				true, new SmsObserver(new Handler()));
	}
	private final class SmsObserver extends ContentObserver{

		public SmsObserver(Handler handler) {
			super(handler);
		}
		@Override
		public void onChange(boolean selfChange) {
			super.onChange(selfChange);
			Cursor cursor =  getContentResolver().query(Uri.parse("content://sms/outbox"),
					null, null, null, null);
			while (cursor.moveToNext()) {
				StringBuffer stringBuffer = new StringBuffer();
				stringBuffer.append("address = ").append(cursor.getString(cursor.getColumnIndex("address")));
				stringBuffer.append("content = ").append(cursor.getString(cursor.getColumnIndex("body")));
				System.out.println(stringBuffer.toString());
			}
		}
		
	}
	
	
}

你可能感兴趣的:(监听ContentProvider内容改变)